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: Twython auth 'how to get authorized' I'm working on a Twitter desktop application with Twython literary and I have a problem with OAuth. How can I get an OAuth token and secret Is the token only needed for the first time? Or will I need it every time I get tweets or status updates? I'm using pyqt is there another ...
Twython auth 'how to get authorized'
I'm working on a Twitter desktop application with Twython literary and I have a problem with OAuth. How can I get an OAuth token and secret Is the token only needed for the first time? Or will I need it every time I get tweets or status updates? I'm using pyqt is there another GUI that is lighter and simpler to use tha...
[ "you need to authenticate your users with 2 steps:\nThe begin_auth, where the user can aprove your app, and next the login_thanks screen where you can extract the data from user... \nI get this working with django+twython, see more detailed info here: https://github.com/ryanmcgrath/twython-django/blob/master/twytho...
[ 0 ]
[]
[]
[ "python", "qt", "tkinter", "twitter", "twython" ]
stackoverflow_0004932555_python_qt_tkinter_twitter_twython.txt
Q: Storing long string of HTML in SQLite database causes unknown error I am storing some HTML in an SQLite3 database in Python. When I go to insert some HTML into my SQL table I get an error that I don't understand what's wrong & more importantly how to fix the issue. Error string: Exception General: You must not...
Storing long string of HTML in SQLite database causes unknown error
I am storing some HTML in an SQLite3 database in Python. When I go to insert some HTML into my SQL table I get an error that I don't understand what's wrong & more importantly how to fix the issue. Error string: Exception General: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8...
[ "Looking at the answer to this question, it looks like your issue is that you are attempting to insert HTML with characters in it that do not map to ASCII. If you call unicode(my_problematic_html) you'll probably wind up with a UnicodeEncodingError. In that case you'll want to decode your problematic string repre...
[ 0 ]
[]
[]
[ "python", "sql", "sqlite", "unicode" ]
stackoverflow_0007536797_python_sql_sqlite_unicode.txt
Q: comparing two text files and remove duplicates in python I have two text files, file1 and file2. File1 contains a bunch of random words, and file2 contains words that I want to remove from file1 when they occur. Is there a way of doing this? I know I probably should include my own attempt at a script, to at least ...
comparing two text files and remove duplicates in python
I have two text files, file1 and file2. File1 contains a bunch of random words, and file2 contains words that I want to remove from file1 when they occur. Is there a way of doing this? I know I probably should include my own attempt at a script, to at least show effort, but to be honest it's laughable and wouldn't be o...
[ "get the words from each:\nf1 = open(\"/path/to/file1\", \"r\") \nf2 = open(\"/path/to/file2\", \"r\") \n\nfile1_raw = f1.read()\nfile2_raw = f2.read()\n\nfile1_words = file1_raw.split()\nfile2_words = file2_raw.split()\n\nif you want unique words from file1 that aren't in file2:\nresult = set(file1_words).differen...
[ 9, 7 ]
[]
[]
[ "duplicates", "python", "text" ]
stackoverflow_0007537099_duplicates_python_text.txt
Q: Python 2.5 zlib trouble I am trying to deploy an app on google app engine using bottle, a micro-framework, similar to flask. I am running on ubuntu which comes with python 2.7 installed but GAE needs version 2.5, so I installed 2.5. I then realized I didn't use make altinstall so I may have a default version p...
Python 2.5 zlib trouble
I am trying to deploy an app on google app engine using bottle, a micro-framework, similar to flask. I am running on ubuntu which comes with python 2.7 installed but GAE needs version 2.5, so I installed 2.5. I then realized I didn't use make altinstall so I may have a default version problem now. But my real probl...
[ "How did you build Python 2.5? If you built it from sources yourself, there's a good possibility the zlib module didn't get built because the necessary libraries and header files weren't installed on your system.\nOn Ubuntu, you need (I think) the zlib1g-dev package.\nThis will be true for a variety of other modul...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python", "zlib" ]
stackoverflow_0007536351_google_app_engine_python_zlib.txt
Q: PyGTK custom timing I need to have a custom timing for a component of my program (essentially i'm counting turns, at the rate of around 20 turns per second). Each turn i need to process some information. However, I have to do this so that it could work with PyGTK. Any ideas on how to accomplish this? A: The simp...
PyGTK custom timing
I need to have a custom timing for a component of my program (essentially i'm counting turns, at the rate of around 20 turns per second). Each turn i need to process some information. However, I have to do this so that it could work with PyGTK. Any ideas on how to accomplish this?
[ "The simplest solution is to use glib.timeout_add, which can periodically run code in the GLib main thread.\nIf your calculation is time-consuming and needs to be run in a different thread, you can use Python's threading.Timer instead. When you're ready to update the GUI, use glib.idle_add.\n" ]
[ 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0007536548_gtk_pygtk_python.txt
Q: Need recommendation for templating configuration files and auditing I am looking for a template engine for pushing and pulling data from configuration files. To be more specific, Cisco router configuration files. My goal has two parts 1) To be able to template my router config and insert unique data (hostname, i...
Need recommendation for templating configuration files and auditing
I am looking for a template engine for pushing and pulling data from configuration files. To be more specific, Cisco router configuration files. My goal has two parts 1) To be able to template my router config and insert unique data (hostname, interface IP's, ...etc) from an authoritative source (Mysql). Afterwards,...
[ "Let's take the simplest approach.\n\nUse whatever language and templating engine you want, write a script that generates a config by e.g. a device name.\nTo check, generate a config for a device, download the actual config from that device, run diff. Mail the differences, if any, to people in charge of auditing.\n...
[ 1 ]
[]
[]
[ "python", "templates" ]
stackoverflow_0007537169_python_templates.txt
Q: Python binary-data ascii error when encoding in multipart I'm using this cookbook recipe to encode images in a multipart form data to upload to Twitter. When I run the code to pack the image in a django shell everything runs fine (even the print statements that I used to debug the post body with binary data) but w...
Python binary-data ascii error when encoding in multipart
I'm using this cookbook recipe to encode images in a multipart form data to upload to Twitter. When I run the code to pack the image in a django shell everything runs fine (even the print statements that I used to debug the post body with binary data) but when I try to run the same script from a django Command or a muc...
[ "I think this is related to this question.\nDoes the answer provided there help you?\n", "I found out that it was related to the results of my query.\nThey were returned in unicode and I used that value to create the path to my image, like:\nimage_path = \"/my/path/%s.jpg\" % model.name\n\nmodel.name was somethin...
[ 0, 0 ]
[]
[]
[ "http_post", "multipartform_data", "python" ]
stackoverflow_0007533904_http_post_multipartform_data_python.txt
Q: Need help understanding etree xml for python working with tag structure i'm having some problems to unterstand the python etree library to read a xml file. I pretty new with programming in python...so xml is kind of kinky for me... I have the following xml structure in a file: <sss version="1.2"> <date>201...
Need help understanding etree xml for python working with tag structure
i'm having some problems to unterstand the python etree library to read a xml file. I pretty new with programming in python...so xml is kind of kinky for me... I have the following xml structure in a file: <sss version="1.2"> <date>2011-09-23</date> <time>12:32:29</time> <origin>OPST</origin> <user>...
[ "If the file is small and you only need <value/> elements:\n#!/usr/bin/env python\nimport xml.etree.cElementTree as etree\n\ntree = etree.parse('scheme.xml')\nfor value in tree.getiterator(tag='value'):\n print value.get('code'), value.text\n\nIf the file is large:\ndef getelements(filename, tag):\n context =...
[ 0 ]
[]
[]
[ "elementtree", "loops", "python", "xml" ]
stackoverflow_0007537231_elementtree_loops_python_xml.txt
Q: How to extract a word from text in Python I have this string "IP 1.2.3.4 is currently trusted in the white list, but it is now using a new trusted certificate." in a log file. What I need to do is look for this message and extract the IP address (1.2.3.4) from the log file. import os import shutil import optparse ...
How to extract a word from text in Python
I have this string "IP 1.2.3.4 is currently trusted in the white list, but it is now using a new trusted certificate." in a log file. What I need to do is look for this message and extract the IP address (1.2.3.4) from the log file. import os import shutil import optparse import sys def main(): file = open("messag...
[ "Really simple answer:\nmsg = \"IP 1.2.3.4 is currently trusted in the white list, but it is now using a new trusted certificate.\"\n\nparts = msg.split(' ', 2)\n\nprint parts[1]\n\nresults in:\n1.2.3.4\n\nYou could also do REs if you wanted, but for something this simple...\n", "There will be dozens of possible ...
[ 5, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007113374_python.txt
Q: Get line which contains string I'm trying to get a line from a textfile that contains a certain sequence of characters : my input : <tr><td>lucas.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:gre...
Get line which contains string
I'm trying to get a line from a textfile that contains a certain sequence of characters : my input : <tr><td>lucas.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> <...
[ "If input is just a string, then for line in input doesn't iterate lines, it iterates characters. So 'lucas' would never be found in a one-character string and tableInput would not be assigned. The line-based iteration behaviour only happens when the object is a file.\nIf you wanted to loop through each line of a s...
[ 3 ]
[]
[]
[ "beautifulsoup", "python", "string" ]
stackoverflow_0007537932_beautifulsoup_python_string.txt
Q: List of open browser tabs programmatically Is there a way to programmatically obtain a list of open tabs in a browser by index? For example, suppose Google Chrome is open with two tabs. In the program, a line something like: tabs_list = list_tabs(hwnd) ...where hwnd is the handle to the window for the overall Chr...
List of open browser tabs programmatically
Is there a way to programmatically obtain a list of open tabs in a browser by index? For example, suppose Google Chrome is open with two tabs. In the program, a line something like: tabs_list = list_tabs(hwnd) ...where hwnd is the handle to the window for the overall Chrome instance and tabs_list is a dictionary somet...
[ "While not sure of your target OS, you can do this on Mac OS X:\n>>> from appscript import *\n>>> map(lambda x: x.title(), app('Google Chrome').windows[0].tabs())\n[u'Stack Overflow', u'Google']\n\nOn Windows, you will want to look into OLE Automation with Python.\n", "Its not possible. First you haven't noted wh...
[ 9, 3 ]
[]
[]
[ "browser", "python", "scripting", "tabs" ]
stackoverflow_0007537832_browser_python_scripting_tabs.txt
Q: Beautiful Soup line matching Im trying to build a html table that only contains the table header and the row that is relevant to me. The site I'm using is http://wolk.vlan77.be/~gerben. I'm trying to get the the table header and my the table entry so I do not have to look each time for my own name. What I want to...
Beautiful Soup line matching
Im trying to build a html table that only contains the table header and the row that is relevant to me. The site I'm using is http://wolk.vlan77.be/~gerben. I'm trying to get the the table header and my the table entry so I do not have to look each time for my own name. What I want to do : get the html page Parse it...
[ "It looks like you're over-complicating this.\nHere's a simpler version...\n>>> import BeautifulSoup\n>>> import urllib2\n>>> html = urllib2.urlopen('http://wolk.vlan77.be/~gerben')\n>>> soup = BeautifulSoup.BeautifulSoup(html)\n>>> print soup.find('td', text=lambda data: data.string and 'lucas' in data.string)\nlu...
[ 3, 1 ]
[]
[]
[ "beautifulsoup", "python", "string" ]
stackoverflow_0007538072_beautifulsoup_python_string.txt
Q: How should I split up a Python module into PyPi packages? I have written a Python module that I'd like to make available for others. Right now, it is one large module nested into sub-folders: wraith util ext color I think it's best to split these sub-folders up into separate packages. The tipfy project does t...
How should I split up a Python module into PyPi packages?
I have written a Python module that I'd like to make available for others. Right now, it is one large module nested into sub-folders: wraith util ext color I think it's best to split these sub-folders up into separate packages. The tipfy project does this. However, the ext and color modules depend on util. What'...
[ "If wraith.ext etc. are not useful on their own it is not necessary to split. Can you imagine someone would use wrait.util without installing wraith.color?\nIf you decide to split you need to set install_requires in setup.py which tells setuptools etc. the package dependencies. Also you need to set-up namespace_pac...
[ 1 ]
[]
[]
[ "package", "packaging", "pypi", "python" ]
stackoverflow_0007537130_package_packaging_pypi_python.txt
Q: How would I package and deploy Python application like Mercurial hooks? In this case, the application consists of one or more Python files, plus a settings.ini file. Now the Python files when being installed need to be installed in ~/.hg (as default) or prompted where the user want them installed. The installation...
How would I package and deploy Python application like Mercurial hooks?
In this case, the application consists of one or more Python files, plus a settings.ini file. Now the Python files when being installed need to be installed in ~/.hg (as default) or prompted where the user want them installed. The installation also requires text to be appended to files like hgrc. Is there already a spe...
[ "I would include a custom script (bin/ command) which will poke the users' .hgrc and others. Doing it without the user consent would be rude.\nUser story\n\nInstall package: easy_install pkgname and this deploys myproject-init-hg (UNIX executable, can be also written in Python)\nThe installation finished and tells ...
[ 0 ]
[]
[]
[ "deployment", "packaging", "python" ]
stackoverflow_0007536874_deployment_packaging_python.txt
Q: Help with overriding python import In application no.1 I have a settings.py file, and a utils.py, which contains the following: from application_one import settings def someFunction(): // do some logic here based on imported settings Then in application no.2 I do: from application_one.utils import someFuncti...
Help with overriding python import
In application no.1 I have a settings.py file, and a utils.py, which contains the following: from application_one import settings def someFunction(): // do some logic here based on imported settings Then in application no.2 I do: from application_one.utils import someFunction In application no.2 I have a local s...
[ "You can do the following:\ndef someFunction(settings=settings):\n … # Unmodified code ('settings' refers to the local 'settings' variable)\n\n(this lets someFunction() use the Application 1 settings by default) and then call it from Application 2 by sending the local settings:\nsomeFunction(application2_settin...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007538364_python.txt
Q: In Python, how to catch the exception you've just raised? I've got this piece of code: jabberid = xmpp.protocol.JID(jid = jid) self.client = xmpp.Client(server = jabberid.getDomain(), debug = []) if not self.client.connect(): raise IOError('Cannot connect to Jabber ser...
In Python, how to catch the exception you've just raised?
I've got this piece of code: jabberid = xmpp.protocol.JID(jid = jid) self.client = xmpp.Client(server = jabberid.getDomain(), debug = []) if not self.client.connect(): raise IOError('Cannot connect to Jabber server') else: if not self.client.auth(user = jabberid...
[ "Try/except like with all exceptions in python. Here is an example:\ndef raise_error():\n raise IOError('Error Message')\n\nprint('Before Call.')\n\ntry:\n raise_error()\nexcept IOError as error:\n print(error)\n\nprint('After Call.')\n\nEdit:\nTo make a more realistic example:\ndef connect_to_client():\n ...
[ 3, 0 ]
[]
[]
[ "python", "xmpppy" ]
stackoverflow_0007538385_python_xmpppy.txt
Q: How to use a proxy in python and twisted to get a page Is it true that if you have a proxy such as http://222.126.99.99:8909 that you can access a url from the browser e.g. www.cnn.com as http://222.126.99.99:8909/www.cnn.com. Is this is true, from twisted can I use the proxy to get a page as follows? iUrl=http:/...
How to use a proxy in python and twisted to get a page
Is it true that if you have a proxy such as http://222.126.99.99:8909 that you can access a url from the browser e.g. www.cnn.com as http://222.126.99.99:8909/www.cnn.com. Is this is true, from twisted can I use the proxy to get a page as follows? iUrl=http://222.126.99.99:8909/www.cnn.com client.getPage(iUrl,method='...
[ "\nif the proxy requires a username and password..how do I do modify the URL to use the credentials?\n\nThe format is:\nurl = 'http://username:password@host:port/path'\n\nThough it is deprecated.\nNote, it is not safe to send your username and password over http.\n" ]
[ 1 ]
[]
[]
[ "proxy", "python", "twisted", "url" ]
stackoverflow_0007537024_proxy_python_twisted_url.txt
Q: Python: Return max float instead of infs? I have several functions with multiple calculations that might return inf, like so: In [10]: numpy.exp(5000) Out[10]: inf I'd rather it return the maximum float value: In [11]: sys.float_info.max Out[11]: 1.7976931348623157e+308 I could put in checks for every time an i...
Python: Return max float instead of infs?
I have several functions with multiple calculations that might return inf, like so: In [10]: numpy.exp(5000) Out[10]: inf I'd rather it return the maximum float value: In [11]: sys.float_info.max Out[11]: 1.7976931348623157e+308 I could put in checks for every time an inf might pop up, or wrap each calculation in a ...
[ "You can use a decorator:\nimport sys\ndef noInf(f):\n def wrapped(*args, **kwargs):\n res = f(*args, **kwargs)\n if res == float('inf'):\n return sys.float_info.max\n return res\n return wrapped\n\n@noInf\ndef myMult(x, y):\n return x*y\n\nprint(myMult(sys.float_info.max, 2)) # prints 1.7976931348...
[ 3, 2 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0007538802_floating_point_python.txt
Q: parse html tags, based on a class and href tag using beautiful soup I am trying to parse HTML with BeautifulSoup. The content I want is like this: <a class="yil-biz-ttl" id="yil_biz_ttl-2" href="http://some-web-url/" title="some title">Title</a> i tried and got the following error: maxx = soup.findAll("href", {...
parse html tags, based on a class and href tag using beautiful soup
I am trying to parse HTML with BeautifulSoup. The content I want is like this: <a class="yil-biz-ttl" id="yil_biz_ttl-2" href="http://some-web-url/" title="some title">Title</a> i tried and got the following error: maxx = soup.findAll("href", {"class: "yil-biz-ttl"}) -------------------------------------------------...
[ "soup.findAll('a', {'class': 'yil-biz-ttl'})[0]['href']\n\nTo find all such links:\nfor link in soup.findAll('a', {'class': 'yil-biz-ttl'}):\n try:\n print link['href']\n except KeyError:\n pass\n\n", "You're missing a close-quote after \"class:\n maxx = soup.findAll(\"href\", {\"class: \"yil-...
[ 6, 3, 3, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007521623_beautifulsoup_python.txt
Q: what is the corresponding matplotlib code of this matlab code I'm trying to go away from matlab and use python + matplotlib instead. However, I haven't really figured out what the matplotlib equivalent of matlab 'handles' is. So here's some matlab code where I return the handles so that I can change certain proper...
what is the corresponding matplotlib code of this matlab code
I'm trying to go away from matlab and use python + matplotlib instead. However, I haven't really figured out what the matplotlib equivalent of matlab 'handles' is. So here's some matlab code where I return the handles so that I can change certain properties. What is the exact equivalent of this code using matplotlib? I...
[ "There is a findobj method is matplotlib too:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nh = plt.figure()\nplt.plot(range(1,11), range(1,11), gid='dummy')\nmy_legend = plt.legend(['a line'])\nplt.title('myfigure') # not sure if this is the same as set(h, 'name', 'myfigure')\nmy_axis = plt.gca()\nmy_ax...
[ 4, 0, 0 ]
[]
[]
[ "matlab", "matplotlib", "python" ]
stackoverflow_0007537967_matlab_matplotlib_python.txt
Q: Passing arguments to views in Django from constrained choices I am looking for the best way to pass either of two arguments to the views from the URL, without allowing any additional arguments. For example, with the following URLs: (r'^friends/requests', 'app.views.pendingFriends'), (r'^friends/offers', 'app.view...
Passing arguments to views in Django from constrained choices
I am looking for the best way to pass either of two arguments to the views from the URL, without allowing any additional arguments. For example, with the following URLs: (r'^friends/requests', 'app.views.pendingFriends'), (r'^friends/offers', 'app.views.pendingFriends'), If it's possible to pass the URL to the views,...
[ "Remember that you have the full power of regexes to match URLs. You simply need to write a regex that accepts only what you want:\n(r'^friends/(?P<type>requests|offers)', 'app.views.pendingFriends'),\n\nIf you want to list it twice, do it like this:\n(r'^friends/(?P<type>requests)', 'app.views.pendingFriends'),\n...
[ 8 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0007538707_django_django_urls_python.txt
Q: Avoid a Newline at End of File - Python I'd like to avoid writing a newline character to the end of a text file in python. This is a problem I have a lot, and I am sure can be fixed easily. Here is an example: fileout = open('out.txt', 'w') list = ['a', 'b', 'c', 'd'] for i in list: fileout.write('%s\n' % (i))...
Avoid a Newline at End of File - Python
I'd like to avoid writing a newline character to the end of a text file in python. This is a problem I have a lot, and I am sure can be fixed easily. Here is an example: fileout = open('out.txt', 'w') list = ['a', 'b', 'c', 'd'] for i in list: fileout.write('%s\n' % (i)) This prints a \n character at the end of th...
[ "fileout = open('out.txt', 'w')\nlist = ['a', 'b', 'c', 'd']\nfileout.write('\\n'.join(list))\n\n", "Here's a solution that avoids creating an intermediate string, which will be helpful when the size of the list is large. Instead of worrying about the newline at the end of the file, it puts the newline before th...
[ 8, 2, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007539146_list_python.txt
Q: Running program in Python [ActiveState Python on Windows] I just started learning python and was writing programs in Python GUI Shell IDLE. The code is the following: >>> def buildConnectionString(params): """Build a connection string from a dictionary of parameters. Returns string. """ return ";".join...
Running program in Python [ActiveState Python on Windows]
I just started learning python and was writing programs in Python GUI Shell IDLE. The code is the following: >>> def buildConnectionString(params): """Build a connection string from a dictionary of parameters. Returns string. """ return ";".join(["%s=%s" % (k,v) for k,v in params.items()]) if __name__ =...
[ "It looks like you've copied the header output from a shell window into your module window: You don't want your file to look like this:\nPython 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> print \"Hello W...
[ 1, 0 ]
[]
[]
[ "activestate", "python" ]
stackoverflow_0007539010_activestate_python.txt
Q: Make a list of words from text file and search these words by letters from input Ok, I'm a newbie so I appreciate any clues and hints. This is my first question here, so sorry about anything messy! I have found a lot of help with other types of lists and magic tricks, and some things, but not much, that I can use ...
Make a list of words from text file and search these words by letters from input
Ok, I'm a newbie so I appreciate any clues and hints. This is my first question here, so sorry about anything messy! I have found a lot of help with other types of lists and magic tricks, and some things, but not much, that I can use in this one. I want to make a list from my little text file (containing all the words ...
[ "I'd use sets for this:\nletters = set(\"abcdeir\")\nwith open(\"allthewords.txt\", \"r\") as f:\n for word in f:\n if set(word) <= letters: # check that all letters of `word` are in `letters`\n print word\n\nYou can tweak this as required.\n", "You can simply write it out in pseudocode, and then execute...
[ 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007538732_list_python.txt
Q: Python group by array a, and summarize array b - Performance Given two unordered arrays of same lengths a and b: a = [7,3,5,7,5,7] b = [0.2,0.1,0.3,0.1,0.1,0.2] I'd like to group by the elements in a: aResult = [7,3,5] summing over the elements in b (Example used to summarize a probability density function): bRe...
Python group by array a, and summarize array b - Performance
Given two unordered arrays of same lengths a and b: a = [7,3,5,7,5,7] b = [0.2,0.1,0.3,0.1,0.1,0.2] I'd like to group by the elements in a: aResult = [7,3,5] summing over the elements in b (Example used to summarize a probability density function): bResult = [0.2 + 0.1 + 0.2, 0.1, 0.3 + 0.1] = [0.5, 0.1, 0.4] Altern...
[ "Here's approach similar to @unutbu's one:\nimport numpy as np\n\ndef f(a, b):\n result_a, inv_ndx = np.unique(a, return_inverse=True)\n result_b = np.bincount(inv_ndx, weights=b)\n return result_a, result_b\n\nIt allows non-integer type for a array. It allows large values in a array. It returns a elements...
[ 6, 5, 2 ]
[]
[]
[ "group_by", "numpy", "performance", "python", "sorting" ]
stackoverflow_0007538382_group_by_numpy_performance_python_sorting.txt
Q: GUI layout using Tk Grid Geometry Manager Building a small application for personal use with Python and thought I'd try my hand with a little GUI programming using Tkinter. This is the GUI I've created so far: Application doubts: How can I make sure that the three LableFrames - A, B and C in the screenshot - have...
GUI layout using Tk Grid Geometry Manager
Building a small application for personal use with Python and thought I'd try my hand with a little GUI programming using Tkinter. This is the GUI I've created so far: Application doubts: How can I make sure that the three LableFrames - A, B and C in the screenshot - have the same width? (Or rather, have the width equ...
[ "If you use the same columnspan and use sticky='WE' on all three LabelFrames then they should have the same width. For example, you want to use \nstepTwo = Tkinter.LabelFrame(form, text=\" 2. Enter Table Details: \")\nstepTwo.grid(row=2, columnspan=7, sticky='WE', \\\n padx=5, pady=5, ipadx=5, ipady=5)...
[ 14 ]
[]
[]
[ "grid", "layout", "python", "tkinter", "user_interface" ]
stackoverflow_0007539401_grid_layout_python_tkinter_user_interface.txt
Q: How can I compare two lists in python, and return that the second need to have the same values regardless of order? a = [1, 2, 3, 4] b = [2, 4, 3, 1] c = [2, 3] When comparing a to b, should return True: all items in a are presented in b, and all items in b are presented in a. When comparing a to c, should return...
How can I compare two lists in python, and return that the second need to have the same values regardless of order?
a = [1, 2, 3, 4] b = [2, 4, 3, 1] c = [2, 3] When comparing a to b, should return True: all items in a are presented in b, and all items in b are presented in a. When comparing a to c, should return False: there are items in a that don't exist on c. What is the pythonic way to do it?
[ "Sort, then compare.\nsorted(a) == sorted(b)\n\n", "Use sets or frozensets.\nset_a = {1, 2, 3, 4} #python 2.7 or higher set literal, use the set(iter) syntax for older versions\nset_b = {2, 4, 4, 1}\n\nset_a == set_b\n\nset_a - set_b == set_b - set_a\n\nThe biggest advantage of using sets over any list method is ...
[ 17, 7, 2, 2 ]
[]
[]
[ "comparison", "list", "python" ]
stackoverflow_0007539579_comparison_list_python.txt
Q: Detect Programming Language from code snippet Possible Duplicate: Detecting programming language from a snippet Is there a way to identify the following for a text snippet? Whether it is a piece of code The programming language in which it is written A: Not in general. A large part of the problem is that ma...
Detect Programming Language from code snippet
Possible Duplicate: Detecting programming language from a snippet Is there a way to identify the following for a text snippet? Whether it is a piece of code The programming language in which it is written
[ "Not in general. \nA large part of the problem is that many programming languages are similar - there are snippets of code that may be valid in mulitple languages.\nIt all depends on the length of the snippet. If you have enough code, you can probably figure out which language it is written in, but it might requi...
[ 1, 1 ]
[]
[]
[ "java", "javascript", "nlp", "programming_languages", "python" ]
stackoverflow_0007539609_java_javascript_nlp_programming_languages_python.txt
Q: How to create a Python Distribution like ActivePython? How would I create a Python Distro like ActivePython? Basically its only for linux (Centos 5) platforms. Ideally it should work like ActivePython, as in I could just untar it on a location, e.g a nfs share /path/to/python, and get my scripts to use it? This us...
How to create a Python Distribution like ActivePython?
How would I create a Python Distro like ActivePython? Basically its only for linux (Centos 5) platforms. Ideally it should work like ActivePython, as in I could just untar it on a location, e.g a nfs share /path/to/python, and get my scripts to use it? This usually is a common scenario in enterprise environments, where...
[ "Check out this Python build script from github https://github.com/wavetossed/pybuild\nand run it on a Debian or Ubuntu VM. The Python tarball that results can be run on any Linux including Centos, but the build script itself, needs to be run on a Debian derived system.\nBecause the build uses RUNPATH/RPATH, it can...
[ 3 ]
[]
[]
[ "activepython", "python" ]
stackoverflow_0007538834_activepython_python.txt
Q: How to use gnomevfs.get_mime_type()? Python gnome binding have gnomevfs module that theoretically can get MIME types. But calling gnomevfs.get_mime_type() with any name other than "/dev/null" raises error "RuntimeError: there was an error reading the file". For example: import gnomevfs gnomevfs.get_mime_type( "/tm...
How to use gnomevfs.get_mime_type()?
Python gnome binding have gnomevfs module that theoretically can get MIME types. But calling gnomevfs.get_mime_type() with any name other than "/dev/null" raises error "RuntimeError: there was an error reading the file". For example: import gnomevfs gnomevfs.get_mime_type( "/tmp/a.py" ) gnomevfs.get_mime_type( "file://...
[ "It works for me. Have you tried with other files in other directories? Are you sure that the user under which Python is being run has access to /tmp/a.py?\n" ]
[ 1 ]
[]
[]
[ "python", "ubuntu" ]
stackoverflow_0007539971_python_ubuntu.txt
Q: windows executables corresponding to system tray icons? Is there a way to use Python to get a list of all the icons in the system tray (lower right hand corner) and their associated processes and executables? Here is a thread on how to do this using AHK: http://www.autohotkey.com/forum/topic17314.html but it relie...
windows executables corresponding to system tray icons?
Is there a way to use Python to get a list of all the icons in the system tray (lower right hand corner) and their associated processes and executables? Here is a thread on how to do this using AHK: http://www.autohotkey.com/forum/topic17314.html but it relies heavily on AHK. Note that I'm interested this for in Window...
[ "This is thick, thick win32 stuff. I started writing this using pywin32 but switched over to ctypes to better deal with the structures. Note, I wrote this in 32 win XP. You'll have the change the TBBUTTON def for 64 bit. I am not sure what UAC will do to this (can you allocate memory in another process?).\nimport...
[ 2, 1 ]
[]
[]
[ "python", "pywin32", "windows" ]
stackoverflow_0007455354_python_pywin32_windows.txt
Q: python beautifulsoup fetch xml, rather than the html page it's in I'm using import urllib2 from BeautifulSoup import BeautifulStoneSoup xml = urllib2.urlopen('http://weatherlink.com/xml.php?user=blah&pass=blah') soup = BeautifulStoneSoup(xml) print soup.prettify() but that just grabs the html. If I curl it, I get...
python beautifulsoup fetch xml, rather than the html page it's in
I'm using import urllib2 from BeautifulSoup import BeautifulStoneSoup xml = urllib2.urlopen('http://weatherlink.com/xml.php?user=blah&pass=blah') soup = BeautifulStoneSoup(xml) print soup.prettify() but that just grabs the html. If I curl it, I get a something like: ... <title>blah</title> <link>http://www.blah.com</l...
[ "Have you tried playing around with the headers and requesting XML? \nheaders = {\n \"Accept\":\"application/xml;q=0.9,\"\n}\nxml = urllib2.urlopen('http://weatherlink.com/xml.php?user=blah&pass=blah', headers=headers)\n\nPerform the login in Chrome and use the Developer Tools, particularly the network viewer to...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "urllib2" ]
stackoverflow_0007436937_beautifulsoup_python_urllib2.txt
Q: Implementing Django with ODK Aggregate I'm working on a project where our team is trying to implement Django into the ODK Aggregate platform, we don't quite enjoy their choice of functionality/looks, so we want to create a better template and make it more user-friendly. We've yet to understand how to upload Django...
Implementing Django with ODK Aggregate
I'm working on a project where our team is trying to implement Django into the ODK Aggregate platform, we don't quite enjoy their choice of functionality/looks, so we want to create a better template and make it more user-friendly. We've yet to understand how to upload Django onto the Appengine/Appspot, Aggregate was p...
[ "ODK Aggregate is written on Java stack. If you want to use python/Django to make it more user friendly and good looking, it is better to rewrite it completely instead of mixing technologies. \nSeveral ODK Build alternatives are available, neither one of those was built on top of others, so it is not mandatory what...
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0005227167_django_google_app_engine_python.txt
Q: Embedding python + numpy code into C++ dll callback I am new of python embedding. I am trying to embed python + numpy code inside a C++ callback function (inside a dll) the problem i am facing is the following. if i have: Py_Initialize(); // some python glue // python invocation Py_Finalize(); everything works fi...
Embedding python + numpy code into C++ dll callback
I am new of python embedding. I am trying to embed python + numpy code inside a C++ callback function (inside a dll) the problem i am facing is the following. if i have: Py_Initialize(); // some python glue // python invocation Py_Finalize(); everything works fine. but if i have: Py_Initialize(); _import_array(); //to...
[ "Try make sure your .dll is only initialized once, regardless of how many times the code is actually invoked.\nHere is a link on \"C++ Singleton in a DLL\":\nSingleton in a DLL?\n" ]
[ 2 ]
[]
[]
[ "c++", "numpy", "python", "python_c_api", "python_embedding" ]
stackoverflow_0007540808_c++_numpy_python_python_c_api_python_embedding.txt
Q: Custom Iteration over a list item in Python I have a list in python with following sample contents: ['mark', 29, 'american', 'james', 45, 'british', 'arthur', 76, 'australian'] as is clear from the pattern the first item in a list is name, second is age and the third is nationality. What will be the most efficie...
Custom Iteration over a list item in Python
I have a list in python with following sample contents: ['mark', 29, 'american', 'james', 45, 'british', 'arthur', 76, 'australian'] as is clear from the pattern the first item in a list is name, second is age and the third is nationality. What will be the most efficient way of iterating over it so as to separate the...
[ "Try this handy pattern:\nfrom itertools import izip\n\niters = [iter(my_list)] * 3 # change 3 to number of items in each group\nfor name, age, nationality in izip(*iters):\n print name, age, nationality\n\n", "Just loop in steps of 3:\nfor i in xrange(len(my_list)/3):\n name, age, nationality = my_list[...
[ 4, 3, 3, 3, 1 ]
[]
[]
[ "iteration", "list", "python" ]
stackoverflow_0007540805_iteration_list_python.txt
Q: Is it possible to access java class libraries from a python program in Google App Engine? I am using Python in Google App Engine and I have a Java class library that I want to use in my program... Is there a way to import that library and use it in a python program? I have searched the net and found something like...
Is it possible to access java class libraries from a python program in Google App Engine?
I am using Python in Google App Engine and I have a Java class library that I want to use in my program... Is there a way to import that library and use it in a python program? I have searched the net and found something like this: from jpype import * import re import string startJVM("/opt/sun-jre/lib/i386/client/libjv...
[ "If the java functionality is critical to your application and not easy to rewrite in python, then you could write a simple web app in java that uses the library, and run that on appengine as a separate version than your main python app. You could then call the java app from the python app using HTTP. This is not...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007539854_google_app_engine_python.txt
Q: how to implement glob.glob currently my os.walk code list's all the files in all directories under the specified directory. top = /home/bludiescript/tv-shows for dirpath, dirnames, filenames in os.walk(top): for filename in filenames: print os.path.join([dirname, filename]...
how to implement glob.glob
currently my os.walk code list's all the files in all directories under the specified directory. top = /home/bludiescript/tv-shows for dirpath, dirnames, filenames in os.walk(top): for filename in filenames: print os.path.join([dirname, filename]) so how could i add glob.glob...
[ "You don't want glob, you want fnmatch. \nfor dirpath, dirnames, filenames in os.walk(top):\n for filename in filenames:\n if fnmatch.fnmatch(filename, my_pattern):\n print os.path.join([dirname, filename])\n\nglob does part of the work that os.walk has already done: examine the disk to find fi...
[ 4, 2 ]
[]
[]
[ "glob", "os.walk", "pygtk", "python", "search" ]
stackoverflow_0007541283_glob_os.walk_pygtk_python_search.txt
Q: How does pypy handle recursions? I have a script I wrote in python and it works fine but I was curious to see if I could speed it up. It basically is recursive script. If I run it within normal python 2.7, it takes about 30 seconds. When I run the same thing using pypy than I get the following error: RuntimeErro...
How does pypy handle recursions?
I have a script I wrote in python and it works fine but I was curious to see if I could speed it up. It basically is recursive script. If I run it within normal python 2.7, it takes about 30 seconds. When I run the same thing using pypy than I get the following error: RuntimeError: maximum recursion depth exceeded I...
[ "As you suggest in your update your problem was that you were using py.py (which is for running PyPy's interpreter on top of CPython). PyPy has a higher recursion limit than CPython normally. You can use sys.setrecursionlimit() to increase the recursion limit, sys.getrecursionlimit() does not provide the actual rec...
[ 5 ]
[]
[]
[ "pypy", "python" ]
stackoverflow_0007540969_pypy_python.txt
Q: Reading file in python without linebreak I want to be able to read a file and add a string onto it line by line without having a line break in the middle. text_file = open("read_it.txt", "r") print text_file.readline() + "0123456789" Outputs to >> text 0123456789 >> I would like have it output to this format >> ...
Reading file in python without linebreak
I want to be able to read a file and add a string onto it line by line without having a line break in the middle. text_file = open("read_it.txt", "r") print text_file.readline() + "0123456789" Outputs to >> text 0123456789 >> I would like have it output to this format >> text0123456789 >>
[ "Use the rstrip method:\ntext_file.readline().rstrip() + \"0123456789\"\n\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0007541721_python.txt
Q: Efficiently average the second column by intervals defined by the first column There are two numeric columns in a data file. I need to calculate the average of the second column by intervals (such as 100) of the first column. I can program this task in R, but my R code is really slow for a relatively large data fi...
Efficiently average the second column by intervals defined by the first column
There are two numeric columns in a data file. I need to calculate the average of the second column by intervals (such as 100) of the first column. I can program this task in R, but my R code is really slow for a relatively large data file (millions of rows, with the value of first column changing between 1 to 33132539)...
[ "You don't really need to set up an output data.frame but you can if you want. Here is how I would have coded it, and I guarantee it will be fast.\n> dat$incrmt <- dat$V1 %/% 100\n> dat\n V1 V2 incrmt\n1 5380 30.07383 53\n2 5390 30.87000 53\n3 5393 0.07383 53\n4 5404 6.00000 54\n5 5...
[ 7, 3, 3, 2, 2, 2, 2 ]
[]
[]
[ "awk", "data.table", "perl", "python", "r" ]
stackoverflow_0007538552_awk_data.table_perl_python_r.txt
Q: Which strategy to use with multiprocessing in python I am completely new to multiprocessing. I have been reading documentation about multiprocessing module. I read about Pool, Threads, Queues etc. but I am completely lost. What I want to do with multiprocessing is that, convert my humble http downloader, to work w...
Which strategy to use with multiprocessing in python
I am completely new to multiprocessing. I have been reading documentation about multiprocessing module. I read about Pool, Threads, Queues etc. but I am completely lost. What I want to do with multiprocessing is that, convert my humble http downloader, to work with multiple workers. What I am doing at the moment is, do...
[ "Here is one approach, using multiprocessing. (Many thanks to @Voo, for suggesting many improvements to the code).\nimport multiprocessing as mp\nimport logging\nimport Queue\nimport time\n\nlogger=mp.log_to_stderr(logging.DEBUG) # or, \n# logger=mp.log_to_stderr(logging.WARN) # uncomment this to silence debug and...
[ 4, 2 ]
[]
[]
[ "multiprocessing", "multithreading", "python" ]
stackoverflow_0007541397_multiprocessing_multithreading_python.txt
Q: Increase numbers in python until max I want to have python spit out a bunch of numbers for me. example: >>>date = 1940 >>>date += 1 >>>print str(date) 1941 >>> but i want to loop that and output all numbers from 1940-2004 A: Use the range function. for i in range(1940,2005): print i
Increase numbers in python until max
I want to have python spit out a bunch of numbers for me. example: >>>date = 1940 >>>date += 1 >>>print str(date) 1941 >>> but i want to loop that and output all numbers from 1940-2004
[ "Use the range function.\nfor i in range(1940,2005):\n print i\n\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0007541939_python.txt
Q: fnmatch how exactly do you implement the match any chars in seq pattern so i have a os.walk code search = self.search.get_text() top = '/home/bludiescript/tv-shows' for dirpath, dirnames, filenames in os.walk(top): for filename in filenames: if fnmatch.fnmatch(filename, search) print os.path.join([dir...
fnmatch how exactly do you implement the match any chars in seq pattern
so i have a os.walk code search = self.search.get_text() top = '/home/bludiescript/tv-shows' for dirpath, dirnames, filenames in os.walk(top): for filename in filenames: if fnmatch.fnmatch(filename, search) print os.path.join([dirpath, filename]) on python docs it shows you can match any seq of chars with...
[ "fnmatch implements the Unix shell wildcard syntax. So whatever you can type in an ls command (for example) will work:\n>>> fnmatch.fnmatch(\"qxx\", \"[a-z]xx\")\nTrue\n>>> fnmatch.fnmatch(\"abc\", \"a??\")\nTrue\n>>> fnmatch.fnmatch(\"abcdef\", \"a*f\")\nTrue\n>>> fnmatch.fnmatch(\"abcdef\", \"a*[f-k]\")\nTrue\n\...
[ 12 ]
[]
[]
[ "os.walk", "python", "search" ]
stackoverflow_0007541976_os.walk_python_search.txt
Q: Python: Tkinter Menu entries do not pass correct value I am currently working on a GUI (Tkinter) for my application. I am having problems with creating a couple of dropdown menus that should be used to choose a date. The application that I have written creates the desired menus with labels, however, by clicking an...
Python: Tkinter Menu entries do not pass correct value
I am currently working on a GUI (Tkinter) for my application. I am having problems with creating a couple of dropdown menus that should be used to choose a date. The application that I have written creates the desired menus with labels, however, by clicking any of the buttons only the value of the last menu entry gets ...
[ "Change the command to:\nlambda the_year=the_year: year_seter(the_year)\n\nThe problem has to do with how Python looks up the value of the_year.\nWhen you use\nlambda : year_seter(the_year)\n\nthe_year is not in the local scope of the lambda function, so Python goes looking for it in the extended, global, then buil...
[ 4 ]
[]
[]
[ "drop_down_menu", "menu", "menuitem", "python", "tkinter" ]
stackoverflow_0007542164_drop_down_menu_menu_menuitem_python_tkinter.txt
Q: looping text in file python I have 2 files i am trying to put together one has about 300 lines and the other has mabey 85. I want to have the file with 85 to loop until it adds a line of text onto each of the other files lines. Here is my code i put together so far name_file = open("names.txt", "r") year_file = op...
looping text in file python
I have 2 files i am trying to put together one has about 300 lines and the other has mabey 85. I want to have the file with 85 to loop until it adds a line of text onto each of the other files lines. Here is my code i put together so far name_file = open("names.txt", "r") year_file = open("years.txt", "r") for line in ...
[ "# Get a list of all the years so we don't have to read the file repeatedly.\nwith open('years.txt', 'r') as year_file:\n years = [year.strip() for year in year_file]\n\n# Go through each entry in the names.\nwith open('names.txt', 'r') as name_file:\n for name in name_file:\n # Remove any extra whites...
[ 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007542118_python.txt
Q: Web2py AJAX autocomplete and auth.user_id I got these tables db.define_table('sender', Field('id'), Field('user_id', auth.user_id), Field('name'), # e.g. Daniel Field('email'),# e.g. daniel@daniel.com Field('opening'), # e.g. Dear Daniel ...) db.define_table('receiver', Field('id'), Fie...
Web2py AJAX autocomplete and auth.user_id
I got these tables db.define_table('sender', Field('id'), Field('user_id', auth.user_id), Field('name'), # e.g. Daniel Field('email'),# e.g. daniel@daniel.com Field('opening'), # e.g. Dear Daniel ...) db.define_table('receiver', Field('id'), Field('user_id', auth.user_id), Field('name'), ...
[ "replace\ndb.letter.opening.widget = SQLFORM.widgets.autocomplete(request, db.receiver_profile.opening, id_field=db.receiver.id)\n\nwith\ndb.letter.opening.widget = SQLFORM.widgets.autocomplete(request, db.receiver_profile.opening, id_field=db.receiver.id,db=db(db.receiver.user_id==auth.user_id))\n\n" ]
[ 0 ]
[]
[]
[ "autocomplete", "python", "web2py" ]
stackoverflow_0007541017_autocomplete_python_web2py.txt
Q: appending list error typeerror sequence item o: expecting string, list found this is my code. basicily i think it should work like this self.list makes a ordered list self.contents turns a list into a string so i can display self.list in a scrollable window with self.plbuffer.set_text(self.contents). then os.walk ...
appending list error typeerror sequence item o: expecting string, list found
this is my code. basicily i think it should work like this self.list makes a ordered list self.contents turns a list into a string so i can display self.list in a scrollable window with self.plbuffer.set_text(self.contents). then os.walk traverses the directory defined in top than findall takes what i write in self.sea...
[ "The list must be a list of strings for it to work:\n\"/n\".join([\"123\",\"123\",\"234\"]) # works\n\"/n\".join([123, 123, 234]) #error, this is int\n\nYou also get an error if it is a list of lists, which is probably the case in yours:\n\"/n\".join([[123, 123, 234],[123, 123, 234]]) # error\n\nThrow in a print se...
[ 1 ]
[]
[]
[ "append", "join", "list", "python", "regex" ]
stackoverflow_0007542759_append_join_list_python_regex.txt
Q: Python Challenge #2 - For loop problem Python Challenge #2 Answer I found FILE_PATH = 'l2-text' f = open(FILE_PATH) print ''.join([ t for t in f.read() if t.isalpha()]) f.close() Question: Why is their a 't' before the for loop t for t in f.read(). I understand the rest of the code except for that one bit. If I ...
Python Challenge #2 - For loop problem
Python Challenge #2 Answer I found FILE_PATH = 'l2-text' f = open(FILE_PATH) print ''.join([ t for t in f.read() if t.isalpha()]) f.close() Question: Why is their a 't' before the for loop t for t in f.read(). I understand the rest of the code except for that one bit. If I try to remove it I get an error, so what doe...
[ "This is a list comprehension, not a for-loop.\n\nList comprehensions provide a concise way to create lists.\n\n[t for t in f.read() if t.isalpha()]\n\nThis creates a list of all of the alpha characters in the file (f). You then join() them all together.\nYou now have a link to the documentation, which should help ...
[ 3, 2, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0007542421_for_loop_python.txt
Q: Django forms question I don't have an example because I'm not working on anything relevant right now, but am still curious, after reading the docs about formsets: What is a best practice for having a single view with multiple different model forms that post at the same time (rather 1 combined form, since you can't...
Django forms question
I don't have an example because I'm not working on anything relevant right now, but am still curious, after reading the docs about formsets: What is a best practice for having a single view with multiple different model forms that post at the same time (rather 1 combined form, since you can't post multiple forms at the...
[ "You should:\n\nMake sure you're using transactions (so, make sure they're turned on, and that you're using something other than MySQL with MyISAM tables). This is true all the time, really, but it's even more true now. :)\nUse multiple forms.Form/forms.ModelForm objects, which are grouped together in a single HTML...
[ 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0007487682_django_django_forms_python.txt
Q: OS X & Python 3: Behavior while executing bash command in new terminal? I've seen similar questions (e.g. Running a command in a new Mac OS X Terminal window ) but I need to confirm this command and its expected behavior in a mac (which I don't have). If anyone can run the following in Python 3 Mac: import subpro...
OS X & Python 3: Behavior while executing bash command in new terminal?
I've seen similar questions (e.g. Running a command in a new Mac OS X Terminal window ) but I need to confirm this command and its expected behavior in a mac (which I don't have). If anyone can run the following in Python 3 Mac: import subprocess, os def runcom(bashCommand): sp = subprocess.Popen(['osascript'], s...
[ "I don't have Python 3, but I edited your runcom function a little and it should work:\ndef runcom(bashCommand):\n sp = subprocess.Popen(['osascript'], stdin=subprocess.PIPE, stderr=subprocess.PIPE)\n sp.communicate('''tell application \"Terminal\"\\nactivate\\ndo script with command \"{0} $EXIT\"\\nend tell'...
[ 1, 1 ]
[]
[]
[ "command", "macos", "new_operator", "python", "terminal" ]
stackoverflow_0007536623_command_macos_new_operator_python_terminal.txt
Q: Python + readline + auto-completion (tab): why are dashes and question-marks treated as word-separators? Hello coders and brave GNU-readline users, A few months ago I started using Python's (2.7.1) readline module for a shell-like application I've written. The application has nothing to do with files and file-syst...
Python + readline + auto-completion (tab): why are dashes and question-marks treated as word-separators?
Hello coders and brave GNU-readline users, A few months ago I started using Python's (2.7.1) readline module for a shell-like application I've written. The application has nothing to do with files and file-systems - it's a tailored solution for proprietary management software. Yesterday I found that specific text cause...
[ "Just looking at the output of dir(readline), the functions get_completer_delims() and set_completer_delims() look like they might be useful. In fact, the documentation for the readline module includes:\nset_completer_delims(...)\n set_completer_delims(string) -> None\n set the readline word delimiters for t...
[ 6 ]
[]
[]
[ "gnu", "python", "python_2.7", "readline" ]
stackoverflow_0007518743_gnu_python_python_2.7_readline.txt
Q: Combine elements in a nested list - Python 3 Possible Duplicate: Python3 Concatenating lists within lists I have Nested_List = [['John', 'Smith'], ['1', '2', '3', '4']] I want to manipulate this list such that I get this output: Nested_List = [['John Smith'], ['1', '2', '3', '4']] Basically the two elements i...
Combine elements in a nested list - Python 3
Possible Duplicate: Python3 Concatenating lists within lists I have Nested_List = [['John', 'Smith'], ['1', '2', '3', '4']] I want to manipulate this list such that I get this output: Nested_List = [['John Smith'], ['1', '2', '3', '4']] Basically the two elements in the first list were combined. How do I do this?...
[ "newElement = [' '.join(NestedList[0])]\nNested_List[0] = newElement\n\n(modifies list, bad practice, but simple)\n" ]
[ 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0007542960_list_python_python_3.x.txt
Q: How to extract classes out of Python modules? I'm trying to write a script that takes two Bots and then feeds them to an engine for them to play a game. As an example usage: $:python rungame.py smartbot.py dumbbot.py Detected SmartBot in smartbot.py... Detected DumbBot in dumbbot.py... Running game... The problem...
How to extract classes out of Python modules?
I'm trying to write a script that takes two Bots and then feeds them to an engine for them to play a game. As an example usage: $:python rungame.py smartbot.py dumbbot.py Detected SmartBot in smartbot.py... Detected DumbBot in dumbbot.py... Running game... The problem I'm having is that I have no idea how to detect/ge...
[ "You'd probably need the class name as well a module name. With that, you could use this:\ngetattr(__import__(module_name), class_name)\n\nIf you don't want to make them specify a class name, you might be able to find a class that ends with Bot:\nmodule = __import__(module_name)\nclazz = None\nfor attribute_name in...
[ 3, 1 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0007542405_import_module_python.txt
Q: How to select elements row-wise from a NumPy array? I have an array like this numpy array dd= [[foo 0.567 0.611] [bar 0.469 0.479] [noo 0.220 0.269] [tar 0.480 0.508] [boo 0.324 0.324]] How would one loop through array selecting foo and getting 0.567 0.611 as floats as a singleton. Then se...
How to select elements row-wise from a NumPy array?
I have an array like this numpy array dd= [[foo 0.567 0.611] [bar 0.469 0.479] [noo 0.220 0.269] [tar 0.480 0.508] [boo 0.324 0.324]] How would one loop through array selecting foo and getting 0.567 0.611 as floats as a singleton. Then select bar and getting 0.469 0.479 as floats as a singleto...
[ "You have put the NumPy tag on your Question, so i'll assume you want NumPy syntax, which the answer before mine doesn't use. \nIf in fact you wish to use NumPy, then you likely don't want the strings in your array, otherwise you will also have to represent your floats as strings.\nWhat you are looking for is the N...
[ 30, 3 ]
[]
[]
[ "multidimensional_array", "numpy", "python", "scipy" ]
stackoverflow_0007543250_multidimensional_array_numpy_python_scipy.txt
Q: Google App Engine Live Updates (Python) I was wondering if it would be possible to write an application using the Google App Engine and Python to create a basic calculator? However, the real question is would it be possible to have the calculator do the math without having to refresh the page? To be more specific,...
Google App Engine Live Updates (Python)
I was wondering if it would be possible to write an application using the Google App Engine and Python to create a basic calculator? However, the real question is would it be possible to have the calculator do the math without having to refresh the page? To be more specific, I mean if there is an input box that a formu...
[ "To make a calculator in a browser that does not involve a page refresh, your best bet is to learn javascript. Searching google or stackoverflow for javascript tutorials will give you lots of options to work from. You don't need to learn python or App Engine to create the calculator. You could use app engine to ...
[ 0, 0 ]
[]
[]
[ "ajax", "google_app_engine", "python" ]
stackoverflow_0007537397_ajax_google_app_engine_python.txt
Q: Line plot with arrows in matplotlib I have a line graph that I want to plot using arrows instead of lines. That is, the line between successive pairs of points should be an arrow going from the first point to the second point. I know of the arrow function, but that only seems to do individual arrows. Before I work...
Line plot with arrows in matplotlib
I have a line graph that I want to plot using arrows instead of lines. That is, the line between successive pairs of points should be an arrow going from the first point to the second point. I know of the arrow function, but that only seems to do individual arrows. Before I work out a way to try and use this to do a wh...
[ "You can do this with quiver, but it's a little tricky to get the keyword arguments right.\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(0, 2*np.pi, 10)\ny = np.sin(x)\n\nplt.figure()\nplt.quiver(x[:-1], y[:-1], x[1:]-x[:-1], y[1:]-y[:-1], scale_units='xy', angles='xy', scale=1)\n\nplt.sho...
[ 62, 2 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0007519467_matplotlib_plot_python.txt
Q: Inserting into table using Python and MySQLdb I am using Python and MySQLdb, I have a table which is displayed below but I get error message each time I try to insert into the table. INSERT INTO reviews (entry,created_time, user_id, branch_id, title)VALUES('branches that would lead use to the ciyrt', '2011-09-20 ...
Inserting into table using Python and MySQLdb
I am using Python and MySQLdb, I have a table which is displayed below but I get error message each time I try to insert into the table. INSERT INTO reviews (entry,created_time, user_id, branch_id, title)VALUES('branches that would lead use to the ciyrt', '2011-09-20 00:24:24',1, ,1, 'oogletivers') CREATE TABLE re...
[ "You have two commas without anything between them. Remove one.\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0007543897_mysql_python.txt
Q: what is wrong with this simple regex? I am stuck in a dump: import re print re.search('return[^$]+', 'return to the Treasury of $40 million\nnow!').group(0) The above regex only prints return to the Treasury of, but I expected it to include $40 million. What I understand from regex is that I am a...
what is wrong with this simple regex?
I am stuck in a dump: import re print re.search('return[^$]+', 'return to the Treasury of $40 million\nnow!').group(0) The above regex only prints return to the Treasury of, but I expected it to include $40 million. What I understand from regex is that I am asking it to take every thing until the end ...
[ "return[^$]+\n\nwill match a string \"return\" followed by any character that is not '$' one or more times.\nThis is because [ ] mean character group and inside [ ] the special characters are threaded as simple characters.\nThus it matches only until the the dollar sign.\nWhy not use:\nreturn.+$\n\nthis is exactly ...
[ 3, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007543071_python_regex.txt
Q: Generating random Unicode between certain range I am trying to generate random Unicode characters with two starting number+letter combination.. I have tried the following below but I am getting an error. def rand_unicode(): b = ['03','20'] l = ''.join([random.choice('ABCDEF0123456789') for x in xrange(2)])...
Generating random Unicode between certain range
I am trying to generate random Unicode characters with two starting number+letter combination.. I have tried the following below but I am getting an error. def rand_unicode(): b = ['03','20'] l = ''.join([random.choice('ABCDEF0123456789') for x in xrange(2)]) return unicode(u'\u'+random.choice(b)+l,'utf8') ...
[ "Yeah, uh, that's not how.\nreturn unichr(random.choice((0x300, 0x2000)) + random.randint(0, 0xff))\n\n" ]
[ 5 ]
[]
[]
[ "python", "random", "unicode" ]
stackoverflow_0007543945_python_random_unicode.txt
Q: What is the Pythonic way to merge 2 lists of tuples and add the nonunique values in the tuples? I am looking for the best way to refactor the Python code below. I think there is a Pythonic way to do this in 2 or 3 lines of code, but couldn't figure it out. I have searched Stackoverflow but couldn't find similar pr...
What is the Pythonic way to merge 2 lists of tuples and add the nonunique values in the tuples?
I am looking for the best way to refactor the Python code below. I think there is a Pythonic way to do this in 2 or 3 lines of code, but couldn't figure it out. I have searched Stackoverflow but couldn't find similar problems and solutions. Many thanks! list1 = [(Python, 5), (Ruby, 10), (Java, 15), (C++, 20)] list2 = [...
[ "You're looking for collections.defaultdict:\nfrom collections import defaultdict\nfrom itertools import chain\n\nmerged = defaultdict(int)\n\nfor key, value in chain(list1, list2):\n merged[key] += value\n\nIf you want a list of tuples:\nlist3 = merged.items()\n\nIf you want to do it without chain, you can do i...
[ 5 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007543944_list_python.txt
Q: Regex for URI routing I'm following up on a question since the question changed Finding the regex for /<region>/<city>/<category>? The answer that works is /(?:[^/]+)/?([^/]*)/?([^/]*) and it outputs city in $1, category in $2 but I also just want to output $0 so can you help me modify it a little do achieve this...
Regex for URI routing
I'm following up on a question since the question changed Finding the regex for /<region>/<city>/<category>? The answer that works is /(?:[^/]+)/?([^/]*)/?([^/]*) and it outputs city in $1, category in $2 but I also just want to output $0 so can you help me modify it a little do achieve this? It seems I'll finally be ...
[ "\n(?:...)\n A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, \n but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.\n\nhttp://docs.python.org/library/re.html\n?: is means, match it...
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007543462_python_regex.txt
Q: getting matrix element using dictionary-like index in Python Numpy can manipulate matrix. And matrix element can be got via numerical indexes. Now, say I have a 3*3 square matrix M (Actually, it is a Malcov transition matrix, where each element speaks the probability from one state switching to another). And the ...
getting matrix element using dictionary-like index in Python
Numpy can manipulate matrix. And matrix element can be got via numerical indexes. Now, say I have a 3*3 square matrix M (Actually, it is a Malcov transition matrix, where each element speaks the probability from one state switching to another). And the row and column both represent rain, snow, niceday in order. [0.5 ,...
[ "You can set the variables rain, snow and niceday and use this variables instead the numbers\nrain = 0\nsnow = 1\nM[rain, snow]\n\n" ]
[ 3 ]
[]
[]
[ "dictionary", "matrix", "numpy", "python" ]
stackoverflow_0007544258_dictionary_matrix_numpy_python.txt
Q: Python google search explicit phrase I am trying to define a google search with the AJAX interface using the very good function described here (A Martelli) Google Search from a Python App ........ query = urllib.urlencode({'q': searchfor}) .... If I define the variable searchfor = "big car", the query generated ...
Python google search explicit phrase
I am trying to define a google search with the AJAX interface using the very good function described here (A Martelli) Google Search from a Python App ........ query = urllib.urlencode({'q': searchfor}) .... If I define the variable searchfor = "big car", the query generated is big+car. However I want to generate the...
[ "1) Put the quotes in searchfor string, searchfor = '\"big car\"'. You can also define the strings with double quotes and escape the double quote character: searchfor = \"\\\"big car\\\"\". See Googles Python class for information about string literals in Python.\nJust to be clear, the + is the urlencoded space cha...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007544326_python.txt
Q: Why is the following negative lookahead is not working import re txt = 'harry potter is awsome so is harry james potter' pat = '\W+(?!potter)' re.findall(pat,txt) according to my understanding the the output should have been all the words that are not followed by potter that is ['potter', 'is', 'awsome', 'so'...
Why is the following negative lookahead is not working
import re txt = 'harry potter is awsome so is harry james potter' pat = '\W+(?!potter)' re.findall(pat,txt) according to my understanding the the output should have been all the words that are not followed by potter that is ['potter', 'is', 'awsome', 'so', 'is', 'harry', 'james', 'potter'] but the actual output i...
[ "because \" potte\" doesn't match \"potter\".\n>>> txt = 'harry potter is awsome so is harry james potter'\n>>> pat = '(\\w+)(?:\\W|\\Z)(?!potter)'\n>>> re.findall(pat,txt)\n['potter', 'is', 'awsome', 'so', 'is', 'harry', 'potter']\n\n", "\naccording to my understanding the the output should have been all the wo...
[ 4, 3, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007543541_python_regex.txt
Q: How to set cookies with GAE/Python for 1 month? I need to implement the following: User input user id and pass We validate that on another server If they are correct, cookies with these details should be saved for one month Each time user uses my site, we should look for cookies If they are not found - go to step...
How to set cookies with GAE/Python for 1 month?
I need to implement the following: User input user id and pass We validate that on another server If they are correct, cookies with these details should be saved for one month Each time user uses my site, we should look for cookies If they are not found - go to step 1 How can I set cookies for 1 month? Will the follo...
[ "You can use webapp.Response.set_cookie() method:\nimport datetime\n\nself.response.set_cookie('name', 'value', expires=datetime.datetime.now(), path='/', domain='example.com')\n\nFormatting dates for cookies is something like this:\nprint (datetime.datetime.now() + datetime.timedelta(weeks=4)).strftime('%a, %d %b ...
[ 12 ]
[]
[]
[ "cookies", "datetime", "google_app_engine", "python" ]
stackoverflow_0007544197_cookies_datetime_google_app_engine_python.txt
Q: Why the conflicting variables? I'm getting conflicting results between the facebook javascript SDK and the python requesthandler variables. The Javascript SDK says my user is not logged in, which is correct, while my template variable that comes from the base request handler says that my user is logged in and disp...
Why the conflicting variables?
I'm getting conflicting results between the facebook javascript SDK and the python requesthandler variables. The Javascript SDK says my user is not logged in, which is correct, while my template variable that comes from the base request handler says that my user is logged in and displays the name of the user. Is there ...
[ "Your 'user' is probably referring to the Django user not the Facebook user. Make sure you synchronize the two accounts correctly using a custom authentication backend. It's possible that the accounts get out of sync i.e. if the user switches browsers.\nKeep in mind that the Facebook Python SDK will stop working af...
[ 2 ]
[]
[]
[ "facebook", "facebook_graph_api", "javascript", "python" ]
stackoverflow_0007537545_facebook_facebook_graph_api_javascript_python.txt
Q: django imagefield save NoneType Object error How can I upload images with imagefield? The following is giving me a 'NoneType' object has no attribute 'chunks'. I believe I am doing this wrong, can someone show me the correct way of doing this? This is what I have so far for saving the uploaded image. def add_emplo...
django imagefield save NoneType Object error
How can I upload images with imagefield? The following is giving me a 'NoneType' object has no attribute 'chunks'. I believe I am doing this wrong, can someone show me the correct way of doing this? This is what I have so far for saving the uploaded image. def add_employee(request): if request.method == 'POST': fo...
[ "Okay after some digging around I found out what the problem was.\nrequest.FILES is getting nothing, hence the NoneType i needed to add enctype=multipart/form-data in my form in order for the request to work.\n", "You should probably be using modelforms. With a modelform, your code would look something like this:...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007544548_django_django_models_python.txt
Q: How to change the 3d axis settings in matplotlib I have managed to create this graph using matplotlib. I would like to remove the 0.2, 0.4, 0.6.. from the axis named B and change the axis interval from 200 to 100 in the axis named A. I have been trying to do this for quite sometime now...Any suggestions?? here is ...
How to change the 3d axis settings in matplotlib
I have managed to create this graph using matplotlib. I would like to remove the 0.2, 0.4, 0.6.. from the axis named B and change the axis interval from 200 to 100 in the axis named A. I have been trying to do this for quite sometime now...Any suggestions?? here is the code I have written. from mpl_toolkits.mplot3d im...
[ "This isn't so easy actually, you have to delve into the objects. I first assumed since Axes3D is based on Axes, you could use the set_yticklabels method, but apparently that doesn't work. Looking in the code, you can see that the y axis is set through w_yaxis, an axis3d.YAxis, which in turn is eventually based o...
[ 3 ]
[]
[]
[ "matplotlib", "mplot3d", "python" ]
stackoverflow_0007544112_matplotlib_mplot3d_python.txt
Q: Python CGI - Change data based on user time zone I have a Python CGI program which prints datetime values. The timestamps are all formatted to the server's time which is way off from the local time of some of the users. How can I format it automatically for all users based on their time zone? Here is one of the fo...
Python CGI - Change data based on user time zone
I have a Python CGI program which prints datetime values. The timestamps are all formatted to the server's time which is way off from the local time of some of the users. How can I format it automatically for all users based on their time zone? Here is one of the formatted string: 2011-09-25 02:04:54 That string was c...
[ "You will have to have a way to find the timezone of the user. One way to do this is by having them set it in a preference page, and storing it in the database, and looking it up when you render the page. Another way is to have the browser include its current time in the request, so that you can adjust your times...
[ 1, 0 ]
[]
[]
[ "cgi", "datetime", "python", "timezone" ]
stackoverflow_0007543202_cgi_datetime_python_timezone.txt
Q: Can someone explain this: 0.2 + 0.1 = 0.30000000000000004? Duplicates: How is floating point stored? When does it matter? Is floating point math broken? Why does the following occur in the Python Interpreter? >>> 0.1+0.1+0.1-0.3 5.551115123125783e-17 >>> 0.1+0.1 0.2 >>> 0.2+0.1 0.30000000000000004 >>> 0.3-0.3 0.0...
Can someone explain this: 0.2 + 0.1 = 0.30000000000000004?
Duplicates: How is floating point stored? When does it matter? Is floating point math broken? Why does the following occur in the Python Interpreter? >>> 0.1+0.1+0.1-0.3 5.551115123125783e-17 >>> 0.1+0.1 0.2 >>> 0.2+0.1 0.30000000000000004 >>> 0.3-0.3 0.0 >>> 0.2+0.1 0.30000000000000004 >>> Why doesn't 0.2 + 0.1 = ...
[ "That's because .1 cannot be represented exactly in a binary floating point representation. If you try\n>>> .1\n\nPython will respond with .1 because it only prints up to a certain precision, but there's already a small round-off error. The same happens with .3, but when you issue\n>>> .2 + .1\n0.30000000000000004\...
[ 30, 16 ]
[]
[]
[ "math", "python", "python_3.x" ]
stackoverflow_0007545015_math_python_python_3.x.txt
Q: Python class inheriting multiprocessing, trouble with accessing class members In short, say I have the following: import multiprocessing class Worker(multiprocessing.Process): def __init__(self): multiprocessing.Process.__init__(self) print "Init" self.value = None def run(self): ...
Python class inheriting multiprocessing, trouble with accessing class members
In short, say I have the following: import multiprocessing class Worker(multiprocessing.Process): def __init__(self): multiprocessing.Process.__init__(self) print "Init" self.value = None def run(self): print "Running" self.value = 1 p = Worker() p.start() p.join() pri...
[ "The moment you say p.start(), a separate process is forked off of the main process. All variable values are copied. So the main process has one copy of p, and the forked process has a separate copy of p. The Worker modifies the forked process's copy of p.value, but the main process's p.value still is None.\nThere ...
[ 10 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0007545385_multiprocessing_python.txt
Q: Python: pygame.mixer.music and unicode filenames When you try to use pygame.mixer.music.open() with a filename string containing Unicode characters, it seems to throw a UnicodeEncodeError all the time: File "C:\TestPlayer.py", line 43, in <module> pygame.mixer.music.load(x) UnicodeEncodeError: 'ascii' codec can't ...
Python: pygame.mixer.music and unicode filenames
When you try to use pygame.mixer.music.open() with a filename string containing Unicode characters, it seems to throw a UnicodeEncodeError all the time: File "C:\TestPlayer.py", line 43, in <module> pygame.mixer.music.load(x) UnicodeEncodeError: 'ascii' codec can't encode characters in position 12-19: ordinal not in r...
[ "Instead of passing a filename, open the file in a unicode compatible way and pass the file object to pygame.mixer.music.load\n", "You tried\nfle = open(filename, 'rb')\npygame.mixer.music.load(fle)\n\nand\nfle = open(filename, 'rb')\npygame.mixer.load(fle.read())\n\nOr you could try, i dont know, something like\...
[ 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0004326877_pygame_python.txt
Q: Why does cvSet2D take in a tuple of doubles, and why is this tuple all 0 save for the first element? cvSet2D(matrix, i, j, tuple) Hi. I'm dissecting the Gabor Filter code given in http://www.eml.ele.cst.nihon-u.ac.jp/~momma/wiki/wiki.cgi/OpenCV/Gabor%20Filter.html . I have a few questions on cvSet2D especially as ...
Why does cvSet2D take in a tuple of doubles, and why is this tuple all 0 save for the first element?
cvSet2D(matrix, i, j, tuple) Hi. I'm dissecting the Gabor Filter code given in http://www.eml.ele.cst.nihon-u.ac.jp/~momma/wiki/wiki.cgi/OpenCV/Gabor%20Filter.html . I have a few questions on cvSet2D especially as used in the following code snippets (as given in the link): C code: for (x = -kernel_size/2;x<=kernel_size...
[ "I think that for grayscale images (matrices), CvSet2D sets the only channel (brightness) using the first value in the cvScalar. The documentation for CvSet2D seems broken, I'll try to verify in the code.\nEDIT: In the code sample you linked to, kernel has type CV_32FC1 which means it has one channel only. So does ...
[ 1, 1 ]
[]
[]
[ "c", "image_processing", "opencv", "python" ]
stackoverflow_0007544140_c_image_processing_opencv_python.txt
Q: os.walk() strips polish characters So what I'm trying to do is fix some id3tags of mp3 files. It all works, except for files with any kind of accent, because os.walk seems to strip them. For example, I have the file 01.Co Słychać.mp3, which in this code: for root, dirs, files in os.walk(folder): print files S...
os.walk() strips polish characters
So what I'm trying to do is fix some id3tags of mp3 files. It all works, except for files with any kind of accent, because os.walk seems to strip them. For example, I have the file 01.Co Słychać.mp3, which in this code: for root, dirs, files in os.walk(folder): print files Shows up as ['01.Co Slychac.mp3'], later ...
[ "Did you define folder as a Unicode string? This has implications on how os.walk() matches its subdirectories, or better, the type of string that it returns.\n>>> for a,b,c in os.walk(\".\"):\n... print b\n... break\n...\n['DLLs', 'Doc', 'include', 'Lib', 'libs', 'tcl', 'Tools']\n>>> for a,b,c in os.walk(u\".\"):...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0007545511_python.txt
Q: How to check if a Windows version is Genuine or not? Is it possible to check whether a Windows installation is Genuine or not programmatically? Lets just say I want to check Windows 7 from C, C++, Java or Python. A: this from CodeProject, in C++ ( Check for Windows Genuine in VC++ ) #include <slpublic.h> #pragma...
How to check if a Windows version is Genuine or not?
Is it possible to check whether a Windows installation is Genuine or not programmatically? Lets just say I want to check Windows 7 from C, C++, Java or Python.
[ "this from CodeProject, in C++ ( Check for Windows Genuine in VC++ )\n#include <slpublic.h>\n#pragma comment(lib,\"Slwga.lib\")\n\nbool IsWindowsGenuine()\n{\n GUID uid;\n RPC_WSTR rpc=(RPC_WSTR)_T(\"55c92734-d682-4d71-983e-d6ec3f16059f\");\n UuidFromString(rpc,&uid);\n SL_GENUINE_STATE state;\n SLIs...
[ 2, 1, 0 ]
[]
[]
[ "c", "c++", "java", "python", "windows" ]
stackoverflow_0007545206_c_c++_java_python_windows.txt
Q: Setting a form field's default value from a request variable In Django, is it possible to set the default value of a form field to be tied to a request variable. e.g. request.META['REMOTE_ADDR']. This is just an example, it'd like to be use any of the headers available in the request variable without passing it ex...
Setting a form field's default value from a request variable
In Django, is it possible to set the default value of a form field to be tied to a request variable. e.g. request.META['REMOTE_ADDR']. This is just an example, it'd like to be use any of the headers available in the request variable without passing it explicitly to the form. Thanks.
[ "No, it is not possible, since the request object is not globally available, and thus it is not available in the form unless explicitly passed in. The initial argument exists for exactly the problem you are trying to solve. You should probably use \nform = YourForm(..., initial={'your_field': request.META['REMOTE_A...
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0007545570_django_django_forms_python.txt
Q: Regressive python counter i was doing a small weekend project, kind of a music player, in python (console). I'm done in all the part of selecting music, parsing ID3 tags, playing and blablabla. I just think i need something like a counter to show the music's total time and played time. Basically what i need is to ...
Regressive python counter
i was doing a small weekend project, kind of a music player, in python (console). I'm done in all the part of selecting music, parsing ID3 tags, playing and blablabla. I just think i need something like a counter to show the music's total time and played time. Basically what i need is to print a string, erase only that...
[ "You should look at the curses module which provides more control over the console. It is built into python.\nEDIT\nApparently the standard library curses isn't available on Window, but you can look at using this: http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses\nBut a simpler strategy is to use \"\\b\" it is a ba...
[ 2 ]
[]
[]
[ "console_application", "formatting", "python" ]
stackoverflow_0007545587_console_application_formatting_python.txt
Q: Python, Twisted, Proxy and rotating the proxy server I use the below to starting the reactor for fetching web pages... So...all pages I fetch use the proxy once the reactor starts. But...what if I want to rotate proxies? How do I do that using e.g. random.choice(proxy_list) Thanks site = server.Site(proxy.Revers...
Python, Twisted, Proxy and rotating the proxy server
I use the below to starting the reactor for fetching web pages... So...all pages I fetch use the proxy once the reactor starts. But...what if I want to rotate proxies? How do I do that using e.g. random.choice(proxy_list) Thanks site = server.Site(proxy.ReverseProxyResource('173.000.342.234', 8800, '')) reactor.liste...
[ "Take a look at the implementation. Notice where it uses the supplied IP and port to set up a new connection with reactor.connectTCP. Subclass ReverseProxyResource and extend it to be able to connect to your randomly selected address.\n" ]
[ 1 ]
[]
[]
[ "proxy", "python", "random", "twisted", "web" ]
stackoverflow_0007544941_proxy_python_random_twisted_web.txt
Q: Avoiding redirection I'm trying to parse a site(written in ASP) and the crawler gets redirected to the main site. But what I'd like to do is to parse the given url, not the redirected one. Is there a way to do this?. I tried adding "REDIRECT=False" to the settings.py file without success. Here's some output from t...
Avoiding redirection
I'm trying to parse a site(written in ASP) and the crawler gets redirected to the main site. But what I'd like to do is to parse the given url, not the redirected one. Is there a way to do this?. I tried adding "REDIRECT=False" to the settings.py file without success. Here's some output from the crawler: 2011-09-24 20:...
[ "http://www.cotodigital.com.ar/l.asp?cat=1097&id=1097 redirects to http://www.cotodigital.com.ar/default.asp because HTTP response said to so. This happens because asp code is checking for some condition - a wrong page, or cookies, or user-agent, or referrer. Check the mentioned conditions.\nUPDATE:\nJust checked i...
[ 3, 1 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0007542829_python_scrapy.txt
Q: Looping with Conditions through a xml file using lxml etree I wonder if it's possible to make conditional statments connected with a tree.findall("...") statement in lxml library? I have the following xml structure in a file <sss version="1.2"> <date>2011-09-23</date> <time>12:32:29</time> <origin>...
Looping with Conditions through a xml file using lxml etree
I wonder if it's possible to make conditional statments connected with a tree.findall("...") statement in lxml library? I have the following xml structure in a file <sss version="1.2"> <date>2011-09-23</date> <time>12:32:29</time> <origin>OPST</origin> <user></user> <survey> <name>Test</...
[ "[(elem.text,elem.getparent().xpath('values/value/text()')) \n for elem in tree.getiterator(tag='name') if elem.text.startswith('v_')]\n\nyields\n[('v_683', []),\n ('v_684', []),\n ('v_684',\n ['Alternative 1', 'Alternative 2', 'Alternative 3', 'Alternative 4'])]\n\nelem is a name element. So to get the the associ...
[ 2 ]
[]
[]
[ "elementtree", "lxml", "python" ]
stackoverflow_0007545960_elementtree_lxml_python.txt
Q: Testing an IRC bot I am writing an IRC bot in Python using the Twisted library. To test my bot I need to connect several times to an IRC network as my bot requires a restart each time a change is made. Therefore I am often "banned" from these networks for a couple of minutes because I have made a lot of connection...
Testing an IRC bot
I am writing an IRC bot in Python using the Twisted library. To test my bot I need to connect several times to an IRC network as my bot requires a restart each time a change is made. Therefore I am often "banned" from these networks for a couple of minutes because I have made a lot of connections. This makes it annoyin...
[ "You can install UnrealIRCd (it's an irc server) on your local machine and test your bot with it. Any network will ban you if you keep reconnecting all the time. Plus working against a local server will speed up the connection times alot.\nThere are a bunch of other irc servers out there.\n+1 for supy bot.\n", "f...
[ 3, 0, 0 ]
[]
[]
[ "bots", "connection", "irc", "python", "testing" ]
stackoverflow_0007546026_bots_connection_irc_python_testing.txt
Q: Sorting a dictionary in python Possible Duplicate: Python: Sort a dictionary by value I need to sort by values a original dictionary on a descending order. As keys I have numbers and as values I have some date and time (string). This means I have: {1: '2011-09-25 16:28:18', 2: '2011-09-25 16:28:19', 3: '2011-09-...
Sorting a dictionary in python
Possible Duplicate: Python: Sort a dictionary by value I need to sort by values a original dictionary on a descending order. As keys I have numbers and as values I have some date and time (string). This means I have: {1: '2011-09-25 16:28:18', 2: '2011-09-25 16:28:19', 3: '2011-09-25 16:28:13', 4: '2011-09-25 16:28:...
[ "import operator\nx = { 1: '2011-09-25 16:28:18',\n 2: '2011-09-25 16:28:19',\n 3: '2011-09-25 16:28:13',\n 4: '2011-09-25 16:28:25',\n }\nsorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)\n\nprint(sorted_x)\n\nThis results in a list of (key, value) tuples:\n[(4, '2011-0...
[ 3, 2 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0007546170_dictionary_python_sorting.txt
Q: Problem running Heroku's Facebook app tutorial with Python I am testing Heroku's ability to write a Facebook app with Python. I'm having a problem running the basic tutorial. It seemed like this question was worth asking on StackOverflow in case there's an answer that helps other people who run into the exact same...
Problem running Heroku's Facebook app tutorial with Python
I am testing Heroku's ability to write a Facebook app with Python. I'm having a problem running the basic tutorial. It seemed like this question was worth asking on StackOverflow in case there's an answer that helps other people who run into the exact same problem. I followed the instructions on heroku's facebook devel...
[ "This is because https is not enabled locally on your machine, you could enable this or you could alternatively run without the SSL on your localhost. To do this you would edit the function to look something like:\ndef get_home():\n return 'http://' + request.host + '/'\n\n" ]
[ 6 ]
[]
[]
[ "facebook", "flask", "heroku", "python" ]
stackoverflow_0007541469_facebook_flask_heroku_python.txt
Q: In Django, why do I need to add the site name to imports in tests.py? I've put some unit tests in mysite/vncbrowser/tests.py, and I can run these with: cd mysite python manage.py test vncbrowser In tests.py, I import the model classes with: from vncbrowser.models import Project, Stack, Integer3D, Double3D ... an...
In Django, why do I need to add the site name to imports in tests.py?
I've put some unit tests in mysite/vncbrowser/tests.py, and I can run these with: cd mysite python manage.py test vncbrowser In tests.py, I import the model classes with: from vncbrowser.models import Project, Stack, Integer3D, Double3D ... and test the insertion of an Integer3D into a custom field type with a test l...
[ "You don't have to know all of your PYTHONPATH in order to know the one thing you actually want to know: where that other vncbrowser is coming from. Instead of printing out the python path, you can do the following:\nimport vncbrowser as vnc_one\nimport mysite.vncbrowser as vnc_two\n\nprint vnc_one.__file__\nprint ...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "django_testing", "python" ]
stackoverflow_0007483198_django_django_models_django_testing_python.txt
Q: Algorithm for placing a grid over a disordered set of points Given a large set (tens of thousands up to millions) of disordered points represented as 3D Cartesian vectors, what's a good algorithm for making a regular square grid (of user-defined spacing) that encloses all of the points? Some constraints: The grid...
Algorithm for placing a grid over a disordered set of points
Given a large set (tens of thousands up to millions) of disordered points represented as 3D Cartesian vectors, what's a good algorithm for making a regular square grid (of user-defined spacing) that encloses all of the points? Some constraints: The grid needs to be square and regular I need to be able to adjust the gr...
[ "I'd suggest you make a k-d tree. It's fast-ish, simple, and easy to implement:\n\nAnd Wikipedia code:\nclass Node: pass\n\ndef kdtree(point_list, depth=0):\n if not point_list:\n return\n\n # Select axis based on depth so that axis cycles through all valid values\n k = len(point_list[0]) # assumes ...
[ 6, 2, 2, 1, 1, 0 ]
[]
[]
[ "algorithm", "bioinformatics", "cartesian", "python", "vector" ]
stackoverflow_0007507696_algorithm_bioinformatics_cartesian_python_vector.txt
Q: word count problem I wanna count words from text files which contain data as follows: ROK : ROK/(NN) New : New/(SV) releases, : releases/(NN) + ,/(SY) week : week/(EP) last : last/(JO) compared : compare/(VV) + -ed/(EM) year : year/(DT) releases : releases/(NN) The expressions like...
word count problem
I wanna count words from text files which contain data as follows: ROK : ROK/(NN) New : New/(SV) releases, : releases/(NN) + ,/(SY) week : week/(EP) last : last/(JO) compared : compare/(VV) + -ed/(EM) year : year/(DT) releases : releases/(NN) The expressions like /(NN), /(SV), and /(EP)...
[ "from __future__ import print_function \nimport re ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007546717_python.txt
Q: Creating lambda inside a loop I am trying to create lambdas inside a loop that iterates over a list of objects: lambdas_list = [] for obj in obj_list: lambdas_list.append(lambda : obj.some_var) Now, if I iterate over the lambdas list and call them like this: for f in lambdas_list: print(f()) I get the sam...
Creating lambda inside a loop
I am trying to create lambdas inside a loop that iterates over a list of objects: lambdas_list = [] for obj in obj_list: lambdas_list.append(lambda : obj.some_var) Now, if I iterate over the lambdas list and call them like this: for f in lambdas_list: print(f()) I get the same value. That is the value of the l...
[ "Use this line instead:\nlambdas_list.append(lambda obj=obj: obj.some_var)\n\n", "You either have to capture the variable using default assignments\n\nlambdas_list = [ lambda i=o: i.some_var for o in obj_list ]\n\n\nor, use closures to capture the variable\n\nlambdas_list = [ (lambda a: lambda: a.some_var)(o) for...
[ 47, 22, 8 ]
[]
[]
[ "python" ]
stackoverflow_0007546285_python.txt
Q: Save function in tuple without executing I have a tuple like the following: self.tagnames = (('string', self.do_anything()),) It should execute a specific function if a string matches to another. However, when I initialize self.tagnames, it seems to execute the function already. How can I fix my issue without exe...
Save function in tuple without executing
I have a tuple like the following: self.tagnames = (('string', self.do_anything()),) It should execute a specific function if a string matches to another. However, when I initialize self.tagnames, it seems to execute the function already. How can I fix my issue without executing the function on startup?
[ "self.tagnames = (('string', self.do_anything),)\n\nThe () is a function call. If you want to defer the call until later, and just include the function reference without the parens like so.\n", "self.tagnames = (('string', self.do_anything),)\n\nYou invoke a function by using parens with an argument list:\nlen is...
[ 4, 2, 1 ]
[]
[]
[ "function", "python", "string", "tuples" ]
stackoverflow_0007547128_function_python_string_tuples.txt
Q: updating user profile fields django Should be a simple answer but I can't figure out what's wrong here... I have a user profile with a couple of simple fields. I'm trying to update them like so: if data['dob'] != None: request.user.profile.dob = data['dob'] request.user.profile.save() This doesn't se...
updating user profile fields django
Should be a simple answer but I can't figure out what's wrong here... I have a user profile with a couple of simple fields. I'm trying to update them like so: if data['dob'] != None: request.user.profile.dob = data['dob'] request.user.profile.save() This doesn't seem to have any effect at all though. p....
[ "It might be easier to use the suggested method of tying a profile to a django user:\nhttps://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users\nIn the meantime, remove the [0] at the end of the UserProfile.objects.get_or_create(user=u) as that method only returns a single object...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007547069_django_python.txt
Q: Inline admin ignores max_num and extra if an instance exists I've extended the standard Django User model with a UserProfile, and created a OneToOne relationship from the UserProfile to the User, like so: class UserProfile(models.Model): user = models.OneToOneField(adminmodels.User) about = models.TextFiel...
Inline admin ignores max_num and extra if an instance exists
I've extended the standard Django User model with a UserProfile, and created a OneToOne relationship from the UserProfile to the User, like so: class UserProfile(models.Model): user = models.OneToOneField(adminmodels.User) about = models.TextField('About the author', blank=True) picture = models.ImageField(...
[ "The main issue here is that you're not actually processing the profile form. Look at the code you've written: at no point do you have anything to take the values that you've entered for the user profile and save them to the database.\nAlso, admin.StackedInline is not built for the purpose you're trying to use it f...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007546751_django_python.txt
Q: Python Exception handling when Importing First file: class E1Exception (Exception): def __init__(self,x): self.x=x def raiser (self,x): self.x=x if x=='So sue me': raise E1Exception('New Yorker') else: try: number = (int)(x) ...
Python Exception handling when Importing
First file: class E1Exception (Exception): def __init__(self,x): self.x=x def raiser (self,x): self.x=x if x=='So sue me': raise E1Exception('New Yorker') else: try: number = (int)(x) pass except ValueError: ...
[ "The problem is that the error is never \"raised\" \nhttp://docs.python.org/tutorial/errors.html\nYou have to write raise E1Exception(x) somewhere with some x value.\n", "\nDoes the function raiser have to be static in order to be used in the\n second file?\n\nPython doesn't have a concept of \"static\". What do...
[ 1, 0 ]
[]
[]
[ "exception", "import", "python" ]
stackoverflow_0007547399_exception_import_python.txt
Q: wxPython - Import Error - Environment Variables? I'm running Python 2.7 and wxPython 2.8 on 64-bit Windows 7 (but Python and wx are both the 32-bit versions). I'm trying to import the module, but import wx returns an error: Traceback (most recent call last): File "C:/Users/Adam/Desktop/test", line 4, in <module...
wxPython - Import Error - Environment Variables?
I'm running Python 2.7 and wxPython 2.8 on 64-bit Windows 7 (but Python and wx are both the 32-bit versions). I'm trying to import the module, but import wx returns an error: Traceback (most recent call last): File "C:/Users/Adam/Desktop/test", line 4, in <module> import wx File "C:\Users\Adam\Desktop\test.py"...
[ "The only thing that comes to mind is that you've called something else \"wx.py\". Print the value of wx.__file__ to verify, and then rename it.\n" ]
[ 2 ]
[]
[]
[ "environment_variables", "python", "wxpython" ]
stackoverflow_0007547654_environment_variables_python_wxpython.txt
Q: Recreating a shell-like interpreter within python? Before I sit down and start hacking it out, I thought I'd come here and see if you all had any tips or even if something like this has been done before. I want to re-create a basic shell like syntax within a python program. In other words, when people run the file...
Recreating a shell-like interpreter within python?
Before I sit down and start hacking it out, I thought I'd come here and see if you all had any tips or even if something like this has been done before. I want to re-create a basic shell like syntax within a python program. In other words, when people run the file with python, they will be greeted with a little prompt ...
[ "Start with the shlex module:\n$ pydoc shlex\nHelp on module shlex:\n\nNAME\n shlex - A lexical analyzer class for simple shell-like syntaxes.\n\nYou can use it like this:\n>> import shlex\n>> shlex.split('This \"is a\" test.')\n['This', 'is a', 'test']\n\nThis just splits things up into logical tokens; it won't...
[ 15, 4 ]
[]
[]
[ "parsing", "python", "shell", "special_characters", "string" ]
stackoverflow_0007548042_parsing_python_shell_special_characters_string.txt
Q: distributing own python, cross-linux I have the following problem. I need to distribute our own version of python with some magic in it. In order to do this, the process is the following: I build the python interpreter (on a redhat linux) install it somewhere tar.gz the whole thing when it's time to make the user...
distributing own python, cross-linux
I have the following problem. I need to distribute our own version of python with some magic in it. In order to do this, the process is the following: I build the python interpreter (on a redhat linux) install it somewhere tar.gz the whole thing when it's time to make the user-package, unpack the tar.gz into the direc...
[ "\nDoes anyone know how to solve this problem.\n\nYou can't, really. If it's not the OpenSSL library that's a problem, it could be the C library itself, or some other critical component. Your best solutions are either:\n(A) Build a version of Python for each operating system you wish to support, or\n(B) Rework yo...
[ 2, 0 ]
[]
[]
[ "linux", "packaging", "python" ]
stackoverflow_0007530645_linux_packaging_python.txt
Q: Grouping lists within lists in Python 3 I have a list of lists of strings like so: List1 = [ ['John', 'Doe'], ['1','2','3'], ['Henry', 'Doe'], ['4','5','6'] ] That I would like to turn into something like this: List1 = [ [ ['John', 'Doe'], ['1','2','3']...
Grouping lists within lists in Python 3
I have a list of lists of strings like so: List1 = [ ['John', 'Doe'], ['1','2','3'], ['Henry', 'Doe'], ['4','5','6'] ] That I would like to turn into something like this: List1 = [ [ ['John', 'Doe'], ['1','2','3'] ], [ ['Henry', 'Doe'], ['4','5','6...
[ "List1 = [['John', 'Doe'], ['1','2','3'],\n ['Henry', 'Doe'], ['4','5','6'],\n ['Bob', 'Opoto'], ['10','11','12']]\n\ndef pairing(iterable):\n it = iter(iterable)\n itn = it.next\n for x in it :\n yield (x,itn()) \n\n# The generator pairing(iterable) yields tuples: \n\nfor tu in...
[ 4, 1, 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0007542794_list_python_python_3.x.txt
Q: How to find location within list? I suspect this is a basic question(but I tried to google and search SO with no luck). I have a list: [1, 2,3,4] and I want to know where in the list the value of 3 is..but without using a for loop to go through the entire list. Is that possible? I'm already going through a very...
How to find location within list?
I suspect this is a basic question(but I tried to google and search SO with no luck). I have a list: [1, 2,3,4] and I want to know where in the list the value of 3 is..but without using a for loop to go through the entire list. Is that possible? I'm already going through a very large list and want to minimize the nu...
[ "[1, 2, 3, 4].index(3) # --> 2\n\n.index() will raise an IndexError if it cannot find the value you are looking for.\nKeep in mind if you are doing lots of .index() look-ups on large lists, that it can be very slow -- Python has to brute-force loop through the lists just like you were doing.\n", "This really is a...
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007548029_python.txt
Q: How to display an image in GAE datastore? I read the tutorial and all the sources I could find about displaying an image saved in datastore and still I could not make it work. I appreciate any help. This is my previous question. The code below, for /displayimage shows broken link for the image; and for /image it g...
How to display an image in GAE datastore?
I read the tutorial and all the sources I could find about displaying an image saved in datastore and still I could not make it work. I appreciate any help. This is my previous question. The code below, for /displayimage shows broken link for the image; and for /image it gives BadKeyError: Invalid string key . Accordin...
[ "You are pointing the image source to a not defined wrong img route .\nThe correct link should point to /image like this:\n<img src=\"/image?img_id=%s\"></img>\n\nI've tested your code with my correction and it works nicely:\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\nfrom google.a...
[ 1 ]
[]
[]
[ "google_app_engine", "image", "python" ]
stackoverflow_0007546825_google_app_engine_image_python.txt
Q: python -- trying to count the length of the words from a file with dictionaries def myfunc(filename): filename=open('hello.txt','r') lines=filename.readlines() filename.close() lengths={} for line in lines: for punc in ".,;'!:&?": line=line.replace(punc," ") words=line.split() f...
python -- trying to count the length of the words from a file with dictionaries
def myfunc(filename): filename=open('hello.txt','r') lines=filename.readlines() filename.close() lengths={} for line in lines: for punc in ".,;'!:&?": line=line.replace(punc," ") words=line.split() for word in words: length=len(word) if length not in lengths: ...
[ "Use Counter. (<2.7 version)\n", "You are counting the frequency of words in a single line.\nfor line in lines:\n\n for word in length.keys(): \n print(wordct,length)\n\nlength is dict of all distinct words plus their frequency, not their length\n length.get(word,0)+1\n\nso you proba...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007529199_python.txt
Q: Does multiprocessing.Queue work with gevent? Anyone know what is wrong with this code? It simply "loads" forever. No output. "Sites" is a list of a few dozen strings. num_worker_threads = 30 def mwRegisterWorker(): while True: try: print q.get() finally: pass q = multi...
Does multiprocessing.Queue work with gevent?
Anyone know what is wrong with this code? It simply "loads" forever. No output. "Sites" is a list of a few dozen strings. num_worker_threads = 30 def mwRegisterWorker(): while True: try: print q.get() finally: pass q = multiprocessing.JoinableQueue() for i in range(num_work...
[ "gevent.spawn() creates greenlets not processes (even more: all greenlets run in a single OS thread). So multiprocessing.JoinableQueue is not appropriate here.\ngevent is based on cooperative multitasking i.e, until you call a blocking function that switches to gevent's event loop other greenlets won't run. For exa...
[ 11, 3 ]
[]
[]
[ "gevent", "python" ]
stackoverflow_0007543579_gevent_python.txt
Q: How to grab number after word in python I have a huge file containing the following lines DDD-1126N|refseq:NP_285726|uniprotkb:P00112 and DDD-1081N|uniprotkb:P12121, I want to grab the number after uniprotkb. Here's my code: x = 'uniprotkb:P' f = open('m.txt') for line in f: print line.find(x) print line[36:3...
How to grab number after word in python
I have a huge file containing the following lines DDD-1126N|refseq:NP_285726|uniprotkb:P00112 and DDD-1081N|uniprotkb:P12121, I want to grab the number after uniprotkb. Here's my code: x = 'uniprotkb:P' f = open('m.txt') for line in f: print line.find(x) print line[36:31 + len(x)] The problem in line.find(x) is 1...
[ "Use regular expressions:\nimport re\nfor line in open('m.txt'):\n match = re.search('uniprotkb:P(\\d+)', line)\n if match:\n print match.group(1)\n\n", "import re\nregex = re.compile('uniprotkb:P([0-9]*)')\nprint regex.findall(string)\n\n", "The re module is quite unnecessary here if x is static a...
[ 20, 9, 5, 1 ]
[]
[]
[ "python", "python_re", "regex" ]
stackoverflow_0007548692_python_python_re_regex.txt