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: SQLite Library - Python Portability I am writing some code that is intended to operate with a pre-bundled version of Python included with a program. The issue is that it doesn't as yet include the Sqlite3 library which is a requirement of my code. Currently I have a wrapped that calls a system installed version of...
SQLite Library - Python Portability
I am writing some code that is intended to operate with a pre-bundled version of Python included with a program. The issue is that it doesn't as yet include the Sqlite3 library which is a requirement of my code. Currently I have a wrapped that calls a system installed version of python2.7 to use the import. Is there an...
[ "Yes in python you have setup tools. You can use requirements.txt file and use pip install -r requirements.txt to install dependency.\npip link\n", "pysqlite is also maintained as an external project, looks like they've got downloads all the way back to Python 2.3\n" ]
[ 1, 0 ]
[]
[]
[ "portability", "python", "sqlite" ]
stackoverflow_0008385693_portability_python_sqlite.txt
Q: Is there any Python syntax highlighter for Visual Studio 2010? When I used Visual Studio 2008 I could install IronPython + IronPython Integrated IDE + Visual Studio Shell Integrated Mode and then my Visual Studio would parse .py files and highlight its syntax. I tried the same with Visual Studio 2010 beta 2 with n...
Is there any Python syntax highlighter for Visual Studio 2010?
When I used Visual Studio 2008 I could install IronPython + IronPython Integrated IDE + Visual Studio Shell Integrated Mode and then my Visual Studio would parse .py files and highlight its syntax. I tried the same with Visual Studio 2010 beta 2 with no success. Where is the catch? Should I wait a bit longer for new re...
[ "Python Tools for Visual Studio 2010\nIronPython.Net\n\nThis Extension is no longer available. See Jeff Hardy's comment below.\nTry IronPython Extensions for VisualStudio 2010:\nhttp://visualstudiogallery.msdn.microsoft.com/de-de/a0ffaffc-d1c2-4b6c-a9d1-3addc37a5673\n\n", "Here is the latest update (July 2011):\n...
[ 13, 9, 0 ]
[]
[]
[ "ironpython", "python", "syntax_highlighting", "visual_studio_2010" ]
stackoverflow_0001904681_ironpython_python_syntax_highlighting_visual_studio_2010.txt
Q: AS3 server socket, progress event, readutfbytes having a bit of an issue here. I am working on a multiplayer game with flash, and using python for the server side of things. I have the socket connection working... sorta, and quite a bit of the python work done, but I am running into a weird problem. Let's say, up...
AS3 server socket, progress event, readutfbytes
having a bit of an issue here. I am working on a multiplayer game with flash, and using python for the server side of things. I have the socket connection working... sorta, and quite a bit of the python work done, but I am running into a weird problem. Let's say, upon logging in, I send some data to the client contain...
[ "TCP connections are reliable, ordered, stream oriented transports. A stream is a sequence of bytes with no inherent message boundaries. If you want to split up your bytes into separate messages, the bytes themselves must tell you how to do this splitting (or you need some external rule that always applies, like ...
[ 2 ]
[]
[]
[ "actionscript", "python", "twisted" ]
stackoverflow_0008379764_actionscript_python_twisted.txt
Q: Ubuntu & Python: Time based scripting of multiple texts to speech Wonder if anyone can help. Here's what i'm looking to do: effectively write a "script" (as in a theatre / stage type production script), which has several voices/actors, saying different bits of text at different times. So there will be several voic...
Ubuntu & Python: Time based scripting of multiple texts to speech
Wonder if anyone can help. Here's what i'm looking to do: effectively write a "script" (as in a theatre / stage type production script), which has several voices/actors, saying different bits of text at different times. So there will be several voices all kicking off simultaneously all saying different things of differ...
[ "You probably are looking for running various threads with each one running an audio. I think is better you to read a bit of threading, or even running parallel processes with Python. For the Audio thing, there is a lot of python audio libraries that should help you. If I was looking for examples of this concept, ...
[ 0 ]
[]
[]
[ "python", "speech", "text_to_speech", "ubuntu" ]
stackoverflow_0008385863_python_speech_text_to_speech_ubuntu.txt
Q: How to enable math in sphinx? I am using sphinx with the pngmath extension to document my code that has a lot of mathematical expressions. Doing that in a *.rst file is working just fine. a \times b becomes: However, if I try the same inside a *.py file for example in a module documentation like so: """ a \times...
How to enable math in sphinx?
I am using sphinx with the pngmath extension to document my code that has a lot of mathematical expressions. Doing that in a *.rst file is working just fine. a \times b becomes: However, if I try the same inside a *.py file for example in a module documentation like so: """ a \times b """ I end up with Further...
[ "Try putting a lower case 'r' before your docstring - like this:\ndef multiply(a,b):\n r\"\"\"\n returns a \\times b\n \"\"\"\n return a*b\n\nI've never seen a raw literal string for a docstring before, but this will keep your \\t from being interpreted as a <TAB> character.\n" ]
[ 9 ]
[]
[]
[ "latex", "math", "python", "python_sphinx" ]
stackoverflow_0008385538_latex_math_python_python_sphinx.txt
Q: Script to review log files When I review logs on a server I want to have a quick overview of the type of problems that I'm facing before I got digging deeper. I usually use the below one-liner which reduces the number of log lines I need to review by making each line more generic and keeping only the ones that are...
Script to review log files
When I review logs on a server I want to have a quick overview of the type of problems that I'm facing before I got digging deeper. I usually use the below one-liner which reduces the number of log lines I need to review by making each line more generic and keeping only the ones that are unique. One-liner cat /var/l...
[ "have a look at logwatch . it does send you a daily overview of common logfiles. I have only used it for mail logs so far but afaik it can handle apache logs as well.\n" ]
[ 4 ]
[]
[]
[ "bash", "logging", "perl", "python", "shell" ]
stackoverflow_0008386341_bash_logging_perl_python_shell.txt
Q: How to get wxPython video player working in windows I'm trying to get the wxPython video player described here to work in Windows, so that I can do some minor modifications to it and get a script running that will let a user hit the spacebar while watching a video and spit out a record of the timing of each spaceb...
How to get wxPython video player working in windows
I'm trying to get the wxPython video player described here to work in Windows, so that I can do some minor modifications to it and get a script running that will let a user hit the spacebar while watching a video and spit out a record of the timing of each spacebar press. So far, though, I can't even get the videoplay...
[ "wxPython should use GStreamer on Linux, if available. See http://wxpython-users.1045709.n5.nabble.com/wxpython-gstreamer-and-overlapping-panel-staticText-td4834139.html or http://pythonide.blogspot.com/2008/03/howto-write-wxpython-video-player-with.html although I don't see why that matters when the OP was talking...
[ 1 ]
[]
[]
[ "python", "video", "wxpython" ]
stackoverflow_0008372072_python_video_wxpython.txt
Q: gae-sessions not deleting data I have added some functionality to the gae-sessions library, so that I can have flash data; That means, data that only exists between 2 requests of a certain user. Here is the code I added: def set_flashdata(key,val=None): logging.info('set flashdata '+key+'='+val ) sess = ge...
gae-sessions not deleting data
I have added some functionality to the gae-sessions library, so that I can have flash data; That means, data that only exists between 2 requests of a certain user. Here is the code I added: def set_flashdata(key,val=None): logging.info('set flashdata '+key+'='+val ) sess = get_current_session() if val: ...
[ "In the line above, you've called pop which removes the item from the dictionary.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python", "session", "session_state", "session_variables" ]
stackoverflow_0008386286_google_app_engine_python_session_session_state_session_variables.txt
Q: Python module that would create mp42 encoded ASF file I'm trying to capture a video using a webcam then encoding it as an mp42 asf file on a windows machine. I managed to encode an mpeg2 file using pymedia but pymedia doesn't seem to support mp42. I installed opencv and tried to use the python wrapper but python ...
Python module that would create mp42 encoded ASF file
I'm trying to capture a video using a webcam then encoding it as an mp42 asf file on a windows machine. I managed to encode an mpeg2 file using pymedia but pymedia doesn't seem to support mp42. I installed opencv and tried to use the python wrapper but python keeps crashing everytime I create a writer. Even with just ...
[ "According to this : http://forums.creativecow.net/readpost/291/493 mp42 is a version 2 of MP4 ISO file format. (Explained here)\nWhere as according to this wiki link, it is an old Microsoft's (proprietary) MPEG4 codec version 2. This was built-in under VFW (video for windows). I think FFMPEG allows encoding using ...
[ 0 ]
[]
[]
[ "mpeg_4", "python", "streaming" ]
stackoverflow_0008284138_mpeg_4_python_streaming.txt
Q: Web Crawler - Ignore Robots.txt file? Some servers have a robots.txt file in order to stop web crawlers from crawling through their websites. Is there a way to make a web crawler ignore the robots.txt file? I am using Mechanize for python. A: The documentation for mechanize has this sample code: br = mechanize.B...
Web Crawler - Ignore Robots.txt file?
Some servers have a robots.txt file in order to stop web crawlers from crawling through their websites. Is there a way to make a web crawler ignore the robots.txt file? I am using Mechanize for python.
[ "The documentation for mechanize has this sample code:\nbr = mechanize.Browser()\n....\n# Ignore robots.txt. Do not do this without thought and consideration.\nbr.set_handle_robots(False)\n\nThat does exactly what you want.\n", "This looks like what you need:\nfrom mechanize import Browser\nbr = Browser()\n\n# I...
[ 29, 9 ]
[]
[]
[ "mechanize", "python", "robots.txt", "web_crawler" ]
stackoverflow_0008386481_mechanize_python_robots.txt_web_crawler.txt
Q: Accuracy of stat mtime in Windows Have an example piece of (Python) code to check if a directory has changed: import os def watch(path, fdict): """Checks a directory and children for changes""" changed = [] for root, dirs, files in os.walk(path): for f in files: abspath = os.path.abs...
Accuracy of stat mtime in Windows
Have an example piece of (Python) code to check if a directory has changed: import os def watch(path, fdict): """Checks a directory and children for changes""" changed = [] for root, dirs, files in os.walk(path): for f in files: abspath = os.path.abspath(os.path.join(root, f)) ...
[ "The proper way is to watch a directory instead of polling for changes. \nCheck out FindFirstChangeNotification Function.\nWatch a Directory for Changes is a Python implementation.\nIf directory watching isn't accurate enough then probably the only alternative is to intercept file systems calls.\n", "Watchdog:\n...
[ 1, 1, 0 ]
[]
[]
[ "filemtime", "python", "windows" ]
stackoverflow_0001542711_filemtime_python_windows.txt
Q: Choose Mako preprocessor based on file extension? I would like to somehow instrument a mako.lookup.TemplateLookup such that it applies certain preprocessors only for certain file extensions. Specifically, I have a haml.preprocessor that I would like to apply to all templates whose file name ends with .haml. Thanks...
Choose Mako preprocessor based on file extension?
I would like to somehow instrument a mako.lookup.TemplateLookup such that it applies certain preprocessors only for certain file extensions. Specifically, I have a haml.preprocessor that I would like to apply to all templates whose file name ends with .haml. Thanks!
[ "You should be able to customize TemplateLookup to get the behavior you want.\ncustomlookup.py\nfrom mako.lookup import TemplateLookup\nimport haml\n\nclass Lookup(TemplateLookup):\n def get_template(self, uri):\n if uri.rsplit('.')[1] == 'haml':\n # change preprocessor used for this template\n...
[ 4 ]
[]
[]
[ "haml", "mako", "preprocessor", "python" ]
stackoverflow_0008300752_haml_mako_preprocessor_python.txt
Q: How to find more than one substring from a string in Python For example if i have a string 'ATGAGGGATAGAGGGTTGGGAGAGATGGATAGGGGATAGATTG' i have to get substring between ATG and TTG , as we can see there are two of these kinds in a string. I am not able to figure out anyway to do it , plz help me thru it! A: Usi...
How to find more than one substring from a string in Python
For example if i have a string 'ATGAGGGATAGAGGGTTGGGAGAGATGGATAGGGGATAGATTG' i have to get substring between ATG and TTG , as we can see there are two of these kinds in a string. I am not able to figure out anyway to do it , plz help me thru it!
[ "Using regular expression can easily get you there.\nFor example:\nimport re\na = 'ATGAGGGATAGAGGGTTGGGAGAGATGGATAGGGGATAGATTG'\nprint re.findall(\"ATG(.*?)TTG\", a)\n\nOutput:\n['AGGGATAGAGGG', 'GATAGGGGATAGA']\n\n" ]
[ 8 ]
[]
[]
[ "biopython", "python" ]
stackoverflow_0008386697_biopython_python.txt
Q: How to read/write file as root using Kivy for Android? I would like to write to /etc/hosts in my Kivy app, and I've surely a rooted device to test. I tried several ways but always get my app exit without any warning or error. I've tried: subprocess.Popen("su -c touch /etc/hosts", shell = True) subprocess.Popen("su...
How to read/write file as root using Kivy for Android?
I would like to write to /etc/hosts in my Kivy app, and I've surely a rooted device to test. I tried several ways but always get my app exit without any warning or error. I've tried: subprocess.Popen("su -c touch /etc/hosts", shell = True) subprocess.Popen("su -c bash -c touch /etc/hosts", shell = True) subprocess.Pope...
[ "Your error indicate that string-escape is not a known encoding. Kivy is shipping a lite version of Python with their libs, not all the encodings for example. What you can try is to:\n\nGrab python-for-android project\nGo into private/lib/encodings\nCopy the file from your computer to this directory (/usr/lib/pytho...
[ 2 ]
[]
[]
[ "android", "kivy", "python" ]
stackoverflow_0008383060_android_kivy_python.txt
Q: memcache avoid sql bursts I wan to know if there is a better way to handle "sql bursts" when using memcache. let me explain with an example object = memcache.get('some_key') if object is None: #multiple request will cause a bursts of sqls object = Object() #this trigger some sql memcache.set('some_key',oj...
memcache avoid sql bursts
I wan to know if there is a better way to handle "sql bursts" when using memcache. let me explain with an example object = memcache.get('some_key') if object is None: #multiple request will cause a bursts of sqls object = Object() #this trigger some sql memcache.set('some_key',oject,60) so a way I found to av...
[ "There's a few options mentioned on the memcache wiki.\n" ]
[ 0 ]
[]
[]
[ "memcached", "performance", "python", "race_condition", "sql" ]
stackoverflow_0008387101_memcached_performance_python_race_condition_sql.txt
Q: Why am I receiving a string from the socket until the \n newline escape sequence in python? It is supposed to receive from a tcp socket a 2 line string but in fact i am receiving only the string until the new line. socket = socket(AF_INET,SOCK_STREAM) socket.connect((ip,port)) data = socket.recv(102...
Why am I receiving a string from the socket until the \n newline escape sequence in python?
It is supposed to receive from a tcp socket a 2 line string but in fact i am receiving only the string until the new line. socket = socket(AF_INET,SOCK_STREAM) socket.connect((ip,port)) data = socket.recv(1024) print "%s" % data if a call the receive function now it will receive the second part of ...
[ "Because TCP is a streaming protocol (as indicated by the SOCK_STREAM) there are no fixed message boundaries or packets, and you can never be sure you get everything with just one call to recv. You simply have to call recv in a loop, adding to a buffer, and exit the loop when you deem that you have enough. Most tex...
[ 10 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0008386679_python_sockets.txt
Q: First steps in Python (Jython): Importing I am about to start programming python with jython on WinXP (Later Win7). After I tried out the out of the box interpreter in the comand line, I want to try out programming standalone modules. My questions are: Where do I have to put the .py files? How to run them? How to ...
First steps in Python (Jython): Importing
I am about to start programming python with jython on WinXP (Later Win7). After I tried out the out of the box interpreter in the comand line, I want to try out programming standalone modules. My questions are: Where do I have to put the .py files? How to run them? How to import scripts which are not in the same direct...
[ "the relative/absolute path should in PYTHONPATH,sample code:\nimport os,sys\n#change to your path\nsys.path.append(os.path.join(os.path.dirname(__file__),'lib'))\n\n", "you can add a pth file in lib\\site-packages containing something like (example.pth):\nc:\\myProject\n\nand then you can just import the module ...
[ 2, 0 ]
[]
[]
[ "jython", "modularity", "python" ]
stackoverflow_0008357987_jython_modularity_python.txt
Q: Create a list of tuples from list of tuples I have 4 lists l1 = [('x',20),('y',10),('z',40)] l2 = [('x',30),('r',90),('z',10),('s',20)] l3 = [('y',20),('z',40),('x',39)] l4 = [('s',10),('p',20),('z',20)] from the above lists I want to get the fifth list as l_final = [('x',39),('y',20),('z',40),('r',90),('s',20)...
Create a list of tuples from list of tuples
I have 4 lists l1 = [('x',20),('y',10),('z',40)] l2 = [('x',30),('r',90),('z',10),('s',20)] l3 = [('y',20),('z',40),('x',39)] l4 = [('s',10),('p',20),('z',20)] from the above lists I want to get the fifth list as l_final = [('x',39),('y',20),('z',40),('r',90),('s',20),('p',20)] where all the values in the tuple ar...
[ "l1 = [('x',20),('y',10),('z',40)]\nl2 = [('x',30),('r',90),('z',10),('s',20)]\nl3 = [('y',20),('z',40),('x',39)]\nl4 = [('s',10),('p',20),('z',20)]\n\nd = {}\nfor k, v in l1+l2+l3+l4:\n d.setdefault(k, []).append(v)\n\nmylist = [(k, max(v)) for k, v in d.items()]\n\nmylist is now: [('p', 20), ('s', 20), ('r', 9...
[ 5, 4, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0008386972_python_python_3.x.txt
Q: How to describe this relationship in django's model? user table: -------------------- | id | name | age | -------------------- | | | | -------------------- model: class User(models.Model): name = models.CharField(max_length=30) age = models.SmallIntegerField() pet table: ...
How to describe this relationship in django's model?
user table: -------------------- | id | name | age | -------------------- | | | | -------------------- model: class User(models.Model): name = models.CharField(max_length=30) age = models.SmallIntegerField() pet table: -------------------- | id | name | intro | -------...
[ "You use a \"through\" model. Basically, you define your own intermediary table instead of having Django do it for you automatically:\nclass User(models.Model):\n ...\n pets = models.ManyToManyField(Pet, through='UserPet')\n\nclass UserPet(models.Model):\n user = models.ForeignKey(User)\n pet = models.F...
[ 2, 0 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0008387336_database_django_python.txt
Q: What would be the easiest way to parse hg log output and present it in a different What would be the easiest way to parse some of hg log's output (with some extra options) and present it in a differently sorted way with colour on windows cmd? I know of graphlog and hgview (which I've never been able to get running...
What would be the easiest way to parse hg log output and present it in a different
What would be the easiest way to parse some of hg log's output (with some extra options) and present it in a differently sorted way with colour on windows cmd? I know of graphlog and hgview (which I've never been able to get running on windows) and alike, but they all have their little quirks and in the way, I never ge...
[ "Without any script, you can find a way to use graphlog with colors to achieve a result similar to your illustration:\nSee Short Graphlog:\n\nIt is based on an alias defined in here, however it uses special code for coloring a bash (Windows) shell. So you might need to adapt those special codes with some adapted fo...
[ 2 ]
[]
[]
[ "mercurial", "python" ]
stackoverflow_0008385629_mercurial_python.txt
Q: Calling .x file (Linux) in Python and lists I have the following code: # Initialisations filename='/home/Admin/Desktop/Ncapa/i_capa.txt' f = open(filename, 'r') ty = "r" f.readline() f.readline() f.readline() f.readline() f.readline() f.readline() f.readline() f.readline() f.readline() f.readline() f.readline()...
Calling .x file (Linux) in Python and lists
I have the following code: # Initialisations filename='/home/Admin/Desktop/Ncapa/i_capa.txt' f = open(filename, 'r') ty = "r" f.readline() f.readline() f.readline() f.readline() f.readline() f.readline() f.readline() f.readline() f.readline() f.readline() f.readline() d = float(f.readline()) D = float(f.readline())...
[ "If you know the name and line for each variable, create a dictionary:\nposition = {12: 'd',\n 13: 'D', ... }\ndata = {}\nwith open(filename, 'r') as f:\n for i, line in enumerate(f):\n if i in position:\n data[position[i]] = float(line.strip())\n\nThen use the data dictionary as if ...
[ 2, 1, 1 ]
[]
[]
[ "gnome_terminal", "linux", "python" ]
stackoverflow_0008387546_gnome_terminal_linux_python.txt
Q: Unable to dispatch com object in python I am trying to capture trading prices from a data feed provider called eSignal. Using their examples on their developer page (Link), I can easily replicate the functionality in C#. Unfortunately the provider does not support python developers and thus I am attempting to do t...
Unable to dispatch com object in python
I am trying to capture trading prices from a data feed provider called eSignal. Using their examples on their developer page (Link), I can easily replicate the functionality in C#. Unfortunately the provider does not support python developers and thus I am attempting to do this on my own, using the com object reference...
[ "Are you sure that you instantiate class (but not Interface). Googling on uid {9C7CCB46-E9E8-4DDD-9784-4458877C2F10} I've gotten ServerEsignal - and it is look like interface (IESignal) \n" ]
[ 1 ]
[]
[]
[ "com", "python" ]
stackoverflow_0008387717_com_python.txt
Q: releasing turbogears2 handle on specific DB (controlling the transaction manager) I'm building a turbogears application that works with 2 db - the second one - which I'm referring to is an mssql db - used by another application (not mine - my application is actually a hack to solve a problem - so I can't control t...
releasing turbogears2 handle on specific DB (controlling the transaction manager)
I'm building a turbogears application that works with 2 db - the second one - which I'm referring to is an mssql db - used by another application (not mine - my application is actually a hack to solve a problem - so I can't control the other application or the mssql db settings) I'm writing to a specific db table with ...
[ "DBSession.flush() executes SQL, but doesn't commit. You have to call DBSession.commit() to finish transaction (not need to explicitly call flush() in this case, commit() will do it). After commit() SQLAlchemy starts new transaction, but this shouldn't be a problem since data is usually locked only when you execute...
[ 0 ]
[]
[]
[ "python", "sql_server", "sqlalchemy", "turbogears2" ]
stackoverflow_0008369293_python_sql_server_sqlalchemy_turbogears2.txt
Q: shutil.rmtree in mixed hierarchy levels in python I'm a python newbie (so far, I'm only proficient in bash scripting) and I've got a question on recursion and shutil.rmtree. So, I have the following snippet... keepthese = ('dir1', 'dir2', '.dotfile1', '.dotfile2', 'dir3', '.dotdir1') dirpath = '/home/' + username ...
shutil.rmtree in mixed hierarchy levels in python
I'm a python newbie (so far, I'm only proficient in bash scripting) and I've got a question on recursion and shutil.rmtree. So, I have the following snippet... keepthese = ('dir1', 'dir2', '.dotfile1', '.dotfile2', 'dir3', '.dotdir1') dirpath = '/home/' + username + '/parentdir/' killthese = [os.path.join('/home', user...
[ "Assuming you want to:\n\nremove everything in a given root directory, bar a list of excepted directories\nremove everything within each excepted directory\n\nThen something like this (untested!) script should work:\nimport sys, os, shutil\n\ndef prune(dirpath, exceptions=()):\n for name in os.listdir(dirpath):\...
[ 1, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0008381402_python_recursion.txt
Q: relevent query to how to fetch public key from public key server import urllib response = urllib.urlopen('http://pool.sks-keyservers.net/') print 'RESPONSE:', response print 'URL :', response.geturl() headers = response.info() print 'DATE :', headers['date'] print 'HEADERS :' print '---------' print heade...
relevent query to how to fetch public key from public key server
import urllib response = urllib.urlopen('http://pool.sks-keyservers.net/') print 'RESPONSE:', response print 'URL :', response.geturl() headers = response.info() print 'DATE :', headers['date'] print 'HEADERS :' print '---------' print headers data = response.read() print 'LENGTH :', len(data) print 'DATA ...
[ "This spec should help you along, and stop you asking the same question repeatedly :). Basically you need to perform an HTTP GET request to the key server. Most key servers work on TCP port 11371 so you need to ensure that your firewall will let you through.\nFor example, this URL will give you God's public key:\nh...
[ 4, 1 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0001304130_python_urllib.txt
Q: SugarCRM Python API Wrapper - "NoneType" object is not subscriptable I downloaded the SugarCRM Python API wrapper from Github Trying out the basic login code, I have the following problem >>> url = 'http://<REDACTED>/service/v2/rest.php' >>> user = '<REDACTED>' >>> passwd = '<REDACTED>' >>> import sugarcrm >>...
SugarCRM Python API Wrapper - "NoneType" object is not subscriptable
I downloaded the SugarCRM Python API wrapper from Github Trying out the basic login code, I have the following problem >>> url = 'http://<REDACTED>/service/v2/rest.php' >>> user = '<REDACTED>' >>> passwd = '<REDACTED>' >>> import sugarcrm >>> session = sugarcrm.Sugarcrm(url, user, passwd) Connecting to: http://<R...
[ "There is a workaround here:\nhttps://github.com/sugarcrm/python_webservices_library/issues/3\n" ]
[ 1 ]
[]
[]
[ "python", "sugarcrm" ]
stackoverflow_0007751416_python_sugarcrm.txt
Q: Python TypeError when using Bind for a wx.Button I have a class called WxFrame which creates a wxPython frame. I added a method called createRunButton which receives self and pydepp, which is the object of a PyDEPP class import wx class WxFrame(wx.Frame): def __init__(self, parent, title): super(WxFra...
Python TypeError when using Bind for a wx.Button
I have a class called WxFrame which creates a wxPython frame. I added a method called createRunButton which receives self and pydepp, which is the object of a PyDEPP class import wx class WxFrame(wx.Frame): def __init__(self, parent, title): super(WxFrame, self).__init__(parent, title=title) self.M...
[ "The event gets passed as an argument to the callback function. This should work:\nclass PyDEPP:\n def run(self, event):\n print \"running\"\n\n", "When the event is triggered two arguments are passed to the callback function run(): the object which has triggered the event, and a wxEvent object. Since ...
[ 2, 1 ]
[]
[]
[ "argument_passing", "bind", "python", "typeerror", "wxpython" ]
stackoverflow_0008383833_argument_passing_bind_python_typeerror_wxpython.txt
Q: How do I change the data displayed, not the data itself, with QSqlTableModel? I'm using QTableView with QSqlTableModel to display data in a table. I'm displaying integer values as other unicode values- for example, displaying 0 as a checkmark. self.model = QSqlTableModel(self) index = self.model.index(0,5) qv = QV...
How do I change the data displayed, not the data itself, with QSqlTableModel?
I'm using QTableView with QSqlTableModel to display data in a table. I'm displaying integer values as other unicode values- for example, displaying 0 as a checkmark. self.model = QSqlTableModel(self) index = self.model.index(0,5) qv = QVariant(u"\u2713") self.model.setData(index, qv) This effectively changes the displ...
[ "Try setting the edit strategy so that changes are not submitted immediately:\nself.model = QSqlTableModel(self)\nself.model.setEditStrategy(QSqlTableModel.OnManualSubmit)\n\n" ]
[ 0 ]
[]
[]
[ "pyqt", "python", "sqlite" ]
stackoverflow_0008387911_pyqt_python_sqlite.txt
Q: Using setBackground correctly Hopefully an easy one for you... I've been trying to set the background color of a QtListWidgetItem, but I'm not having much luck - this is probably because I'm not using the QListWidgetItem correctly... In my test code I can set the foreground of every third item in the list, but set...
Using setBackground correctly
Hopefully an easy one for you... I've been trying to set the background color of a QtListWidgetItem, but I'm not having much luck - this is probably because I'm not using the QListWidgetItem correctly... In my test code I can set the foreground of every third item in the list, but setting the background seems to have n...
[ "You don't really need a brush. Just use a QColor:\nitem.setBackground(QtGui.QColor('red'))\n\n" ]
[ 9 ]
[]
[]
[ "pyqt", "pyside", "python" ]
stackoverflow_0008388997_pyqt_pyside_python.txt
Q: use maemo camera by python I wrote a simple program for Maemo by Python to check some pixel's color every time that my function is called. But this function runs very slowly (3-5 seconds each call). Is there any faster way to do this? import Image import os import sys # sen_pos = (pixel_x, pixel_y) def sen(sen_...
use maemo camera by python
I wrote a simple program for Maemo by Python to check some pixel's color every time that my function is called. But this function runs very slowly (3-5 seconds each call). Is there any faster way to do this? import Image import os import sys # sen_pos = (pixel_x, pixel_y) def sen(sen_pos): os.system("gst-launch ...
[ "Calling an external program via os.system is likely what's taking the time.\nTry using GStreamer Python Bindings instead and keeping the video object around between calls. The docs for Videomixer may help.\n", "As George says, you may be incurring overhead in a system call but I suspect the getpixel() call. PIL'...
[ 2, 1 ]
[]
[]
[ "camera", "gstreamer", "maemo", "python" ]
stackoverflow_0007893413_camera_gstreamer_maemo_python.txt
Q: High-precision system time in python Is there any way of obtaining high-precision system time in python? I have a little application to work with virtual COM-port. I want to measure the time interval between the sending of the message and its receiving. At the moment it works like this: I obtain the message, use ...
High-precision system time in python
Is there any way of obtaining high-precision system time in python? I have a little application to work with virtual COM-port. I want to measure the time interval between the sending of the message and its receiving. At the moment it works like this: I obtain the message, use time.time() and append its 20 digits ...
[ "Here is an excerpt from time.clock\n\nOn Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very\n definition of the meaning of “processor time”, depends on that of the\n C function of the same name, but in any case, this is the function to\n ...
[ 2 ]
[]
[]
[ "python", "serial_port" ]
stackoverflow_0008389163_python_serial_port.txt
Q: How to use urllib to download image from web I'm trying to download an image using this code: from urllib import urlretrieve urlretrieve('http://gdimitriou.eu/wp-content/uploads/2008/04/google-image-search.jpg', 'google-image-search.jpg') It worked. The image was downloaded and can be open by any im...
How to use urllib to download image from web
I'm trying to download an image using this code: from urllib import urlretrieve urlretrieve('http://gdimitriou.eu/wp-content/uploads/2008/04/google-image-search.jpg', 'google-image-search.jpg') It worked. The image was downloaded and can be open by any image viewer software. However, the code below is n...
[ "If you used the following, you can download the image:\nwget http://upload.wikimedia.org/wikipedia/en/4/44/Zindagi1976.jpg\n\nBut if you did the following:\nfrom urllib import urlretrieve\nurlretrieve('http://upload.wikimedia.org/wikipedia/en/4/44/Zindagi1976.jpg', \n 'Zindagi1976.jpg')\n\nYou may not b...
[ 12 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0008389090_python_urllib.txt
Q: How to reshuffle a shuffled list in Python I am performing shuffle operations on nested lists in Python 3. I wish to reshuffle previously shuffled lists indefinitely until the order of the nested lists meet a specific criteria. random.shuffle operates in place and calling random.shuffle() on a previously shuffled ...
How to reshuffle a shuffled list in Python
I am performing shuffle operations on nested lists in Python 3. I wish to reshuffle previously shuffled lists indefinitely until the order of the nested lists meet a specific criteria. random.shuffle operates in place and calling random.shuffle() on a previously shuffled list does not reshuffle it. What is the best way...
[ "It really seems inefficient to keep shuffling until a certain element is in the front. Why not take that element out, shuffle the remainder, then prepend that element to the front?\n", "This statement:\n\ncalling random.shuffle() on a previously shuffled list does not reshuffle it\n\nThis is incorrect. Observe:\...
[ 2, 1 ]
[]
[]
[ "python", "random", "shuffle" ]
stackoverflow_0008389501_python_random_shuffle.txt
Q: Is there a way to make == work in vim to reindent python code? Let's say I have the following Python code: if conditionOne(): if conditionTwo(): foo = bar foo += 1 bar -= 2 If I later remove conditionTwo, I would like to dedent the three lines of the block so it looks consistent with a...
Is there a way to make == work in vim to reindent python code?
Let's say I have the following Python code: if conditionOne(): if conditionTwo(): foo = bar foo += 1 bar -= 2 If I later remove conditionTwo, I would like to dedent the three lines of the block so it looks consistent with all my other code. Normally I'd just reach for =% (my primary langua...
[ "Whereas in C or C++ indenting a program does not affect its behaviour, in Python it could really, since indentation is part of the flow control.\nTherefore in Python a program with a different indentation will have a different behaviour and for an editor it is impossible to guess whether the developer wanted to in...
[ 3, 0 ]
[]
[]
[ "indentation", "python", "vim" ]
stackoverflow_0008388607_indentation_python_vim.txt
Q: Most efficient way to add a (generated) header to many files? I'm working on a script which checks / creates / updates copyright notices at the top of source files in my project. This is generally I/O bound because the header (missing or otherwise) tends to get bigger each time the script is used (e.g. adding more...
Most efficient way to add a (generated) header to many files?
I'm working on a script which checks / creates / updates copyright notices at the top of source files in my project. This is generally I/O bound because the header (missing or otherwise) tends to get bigger each time the script is used (e.g. adding more years to an existing notice), and so the rest of the file has to b...
[ "You can seek to a negative index if you pass the whence argument to file.seek, otherwise it's assumed to be absolute (so negative locations aren't allowed).\nimport os\nf = open('insert.txt', 'r+')\nf.seek(3)\nf.seek(-1, os.SEEK_CUR) # will go back one position\nf.seek(-1, os.SEEK_END) # one position before the en...
[ 4 ]
[]
[]
[ "file_io", "python", "python_2.6" ]
stackoverflow_0008389393_file_io_python_python_2.6.txt
Q: string convert with python re I get a string line: >>> line = " abc\n def\n\n ghi\n jkl" >>> print line abc def ghi jkl and I want to convert it to "abcdef\n\n ghijkl", like: >>> print " abcdef\n\n ghijkl" abcdef ghijkl I tried python re module, and write something like this: re.sub('(?P<wo...
string convert with python re
I get a string line: >>> line = " abc\n def\n\n ghi\n jkl" >>> print line abc def ghi jkl and I want to convert it to "abcdef\n\n ghijkl", like: >>> print " abcdef\n\n ghijkl" abcdef ghijkl I tried python re module, and write something like this: re.sub('(?P<word1>[^\n\s])\n\s*(?P<word2>[^\n\s])...
[ "\\s matches space, \\t, \\n (and, depending on your regex engine) a few other whitespace characters.\nSo if you only want to replace single linebreaks + spaces/tabs, you can use this:\nnewline = re.sub(r\"(?<!\\n)\\n[ \\t]*(?!\\n)\", \"\", line)\n\nExplanation:\n(?<!\\n) # Assert that the previous character isn't ...
[ 4, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008389593_python_regex.txt
Q: Check Python code for certain statements I'm working on a system that allows users to run their code on our system. While their code is sandboxed, I would still like to know if their code is using certain statements, especially imports. This is used to do a quick check for malicious code or code that is against th...
Check Python code for certain statements
I'm working on a system that allows users to run their code on our system. While their code is sandboxed, I would still like to know if their code is using certain statements, especially imports. This is used to do a quick check for malicious code or code that is against the guidelines for the platform, it will not be ...
[ "I really wouldn't bother trying to do this kind of artificial sandboxing because \n1024 ** 1024 ** 1024\n\nWill still chew up your interpreter.\nor even this\neval(\"__vzcbeg__('gvzr').nfpgvzr()\")\n\nIf you want some security look into pypy's sandbox its about the most secure way to run untrusted python code. The...
[ 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008386016_python.txt
Q: How do I know how many result pages can I get using python-twitter GetSearch() method I use twitter-python search API to retrieve search results like below import twitter api = twitter.Api() i = 1 result = api.GetSearch("Avatar", page=i) print [s.text for s in result] The code above means I want to get the result...
How do I know how many result pages can I get using python-twitter GetSearch() method
I use twitter-python search API to retrieve search results like below import twitter api = twitter.Api() i = 1 result = api.GetSearch("Avatar", page=i) print [s.text for s in result] The code above means I want to get the result on first page returned. I tried multiple assignment of i they all work. But I don't know w...
[ "The maximum value is going to depend on the query, and how many pages twitter feels like giving you.\nWhat about using try/except?\nimport twitter\napi = twitter.Api()\n\n# try a large page number:\ni = 181\n\ntry:\n result = api.GetSearch(\"Avatar\", page=i)\n print [s.text for s in result]\nexcept:\n pr...
[ 1 ]
[]
[]
[ "python", "python_twitter", "twitter" ]
stackoverflow_0008390296_python_python_twitter_twitter.txt
Q: Removing borders from frame and panels in wxPython application I'm building an app that should contain a resizable sidebar area on the left (starting at 200px width) and a main area on the right that should expand to fill the remaining area. I've gone with the SplitterWindow method as it's the only one I think off...
Removing borders from frame and panels in wxPython application
I'm building an app that should contain a resizable sidebar area on the left (starting at 200px width) and a main area on the right that should expand to fill the remaining area. I've gone with the SplitterWindow method as it's the only one I think offers manual resize on panels. I'm experiencing some black borders aro...
[ "You are drawing those lines with the call to DrawRectangle.\nIf you want to eliminate the lines and still draw the rectangle you can do:\ndc.SetPen(wx.Pen(\"WHITE\",1))\ndc.DrawRectangle(0, 0, w, h)\n\nin the two make_canvas methods. It works in windows.\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008389951_python_wxpython.txt
Q: using ngram in python i'm trying to run the following code from ngram import NGram NGram.compare('foo', 'foobar') But i'm getting the error Traceback (most recent call last): File "E:/pt/tandra", line 1, in <module> from ngram import Ngram ImportError: No module named ngram what co...
using ngram in python
i'm trying to run the following code from ngram import NGram NGram.compare('foo', 'foobar') But i'm getting the error Traceback (most recent call last): File "E:/pt/tandra", line 1, in <module> from ngram import Ngram ImportError: No module named ngram what could be the possible reason....
[ "You don't have module called ngram. You need to install it.\nJust use\neasy_install ngram\n\nor\npip install ngram\n\nin terminal (for Linux, Mac OS, Cygwin in Windows) if you have python setuptools.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008390585_python.txt
Q: what is the sole purpose of python being an interpreter? What exactly is the sole purpose of python being an interpreter. It doesn't provide executable files (how a commercial software developer use it?) If any part of the code had bugs, it doesn't show up unless python goes to that line at run it. In large proje...
what is the sole purpose of python being an interpreter?
What exactly is the sole purpose of python being an interpreter. It doesn't provide executable files (how a commercial software developer use it?) If any part of the code had bugs, it doesn't show up unless python goes to that line at run it. In large projects, all parts of code doesn't get interpreted every time, so,...
[ "First, answers to your questions. \n\nThey can use it for parts of their system for which they don't mind the source being visible (e.g. extensions) or they can Open Source their application. They can also use it to develop backend services for something which they're providing as a service (e.g. Youtube). They ca...
[ 12, 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008390626_python.txt
Q: I need assistance with splitting and making an output file in Python I need help to make a practice program for myself. It requires splitting and finding a specific string in a text file and then outputting it on another text file. I need to find every record with a date over 1979 and output all the records found...
I need assistance with splitting and making an output file in Python
I need help to make a practice program for myself. It requires splitting and finding a specific string in a text file and then outputting it on another text file. I need to find every record with a date over 1979 and output all the records found into an output file. How would I do this? This is how part of the txt fil...
[ "If you just want something that works:\nfor line in text:\n date = line.split(',')[3]\n year = int(date.split('/')[2])\n\nIf you want do be more exacting and extensible, you may want to look into the re module.\nI assume you can do the reading and writing bits.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008390772_python.txt
Q: customizing admin of django to have dependent select fields I am new in django , I am developing admin panel first for my site. I need to have dependent select fields, so that after selecting country, user will be able to select city. I want that when I select country then cities of that country options load in ci...
customizing admin of django to have dependent select fields
I am new in django , I am developing admin panel first for my site. I need to have dependent select fields, so that after selecting country, user will be able to select city. I want that when I select country then cities of that country options load in city select box but I don't know how to customize django admin. I h...
[ "You probably want to use the feature Grouped Selects in django smart selects. From the README:\nIf you have the following model:\nclass Location(models.Model)\n continent = models.ForeignKey(Continent)\n country = models.ForeignKey(Country)\n\nAnd you want that all countries are grouped by the Continent and ...
[ 15, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0008380241_django_django_admin_python.txt
Q: Randomly append items from a list to a matrix list I'm trying to create a game. I have a list. I want to take the items in this list and randomly append them to indexes in a list matrix. Think about a grid and an item moving around randomly through this grid. import random fishlist = ["salmon", "carp", "bass...
Randomly append items from a list to a matrix list
I'm trying to create a game. I have a list. I want to take the items in this list and randomly append them to indexes in a list matrix. Think about a grid and an item moving around randomly through this grid. import random fishlist = ["salmon", "carp", "bass", "catfish"] grid = [ [1,2,3], ...
[ "Try this\n>>> grid = [\n [1,2,3],\n [4,5,6],\n [7,8,9],\n ]\n>>> fishlist = [\"salmon\", \"carp\", \"bass\", \"catfish\"]\n\n>>> [r.__setitem__(i,random.choice(fishlist)) for r in grid for i in xrange(0,len(r))]\n[None, None, None, None, None, None, None, None, None]\n>>...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008390548_python.txt
Q: type conversion and string reformatting (python vs. objective-c) I am trying to do some conversion using Objective-C, I have a good experience in Python, it is very easy to convert types in python, I can change a string of numbers to integer easily, or I can even change the representation at the print statement, h...
type conversion and string reformatting (python vs. objective-c)
I am trying to do some conversion using Objective-C, I have a good experience in Python, it is very easy to convert types in python, I can change a string of numbers to integer easily, or I can even change the representation at the print statement, here are some examples: self.workingMaskInt[index] = int(self.workingMa...
[ "There is no built-in binary format specifier, a table of the supported specifiers can be found here. So for a binary format you will have to code your own.\nFor string formatting of NSStrings you can use one of several NSString methods such as:\n+ (id)stringWithFormat:(NSString *)format, ...\n- (id)initWithFormat:...
[ 0 ]
[]
[]
[ "objective_c", "python" ]
stackoverflow_0008390591_objective_c_python.txt
Q: Python Reflection and Type Conversion In Python, functions like str(), int(), float(), etc. are generally used to perform type conversions. However, these require you to know at development time what type you want to convert to. A subproblem of some Python code I'm trying to write is as follows: Given two variab...
Python Reflection and Type Conversion
In Python, functions like str(), int(), float(), etc. are generally used to perform type conversions. However, these require you to know at development time what type you want to convert to. A subproblem of some Python code I'm trying to write is as follows: Given two variables, foo and bar, find the type of foo. (I...
[ "that would be best:\ntype(foo)(bar)\n\n", "Use foo.__class__ to get the type of foo. Then call it to convert bar to the type of foo:\ndef conv(foo, bar) :\n return foo.__class__(bar)\n\nOf course, this only works if the type of foo has a constructor that knows how to convert bar.\n", "type(foo)\n\nis defini...
[ 16, 11, 0 ]
[]
[]
[ "introspection", "python", "python_datamodel", "reflection", "type_conversion" ]
stackoverflow_0000622161_introspection_python_python_datamodel_reflection_type_conversion.txt
Q: shutil.copy2 - Behaviour with different file systems and pseudo files I have written a small script to synchronize two directories. The script allows to sync certain file types and allows file comparison by checksum or date. After comparison a list of files that should be copied is given to a file copy procedure t...
shutil.copy2 - Behaviour with different file systems and pseudo files
I have written a small script to synchronize two directories. The script allows to sync certain file types and allows file comparison by checksum or date. After comparison a list of files that should be copied is given to a file copy procedure that makes use of the shutil.copy2() module. In various test runs I found a ...
[ "shutil.copy2() is simply shutil.copy() followed by shutil.copystat(). To solve your first problem, you might want to copy over the source of shutil.copy2() and enclose the copystat() part in a try-except block. You should be able to figure out which exception to catch from the error traceback.\nYou probably don't ...
[ 0 ]
[]
[]
[ "python", "shutil" ]
stackoverflow_0008391009_python_shutil.txt
Q: Python newtons method issues I have been asking the community alot for help and i appreciate it all So ive been working on a program that solves newtons method in python but for some reason its not working could someone look over it please? thanks you =) import sympy from collections import defaultdict def main(...
Python newtons method issues
I have been asking the community alot for help and i appreciate it all So ive been working on a program that solves newtons method in python but for some reason its not working could someone look over it please? thanks you =) import sympy from collections import defaultdict def main(): dir(sympy) print ("NEWTON...
[ "You're getting an infinite loop here:\nwhile 0 == 0:\n\n if abs(x1-x2) < .0001:\n print x1\n break\n\n else:\n n = x2 - (func1sub/func1dsub)\n x2 = n \n\n if abs(x - n) < .03:\n print x\n\nThe part of this loop which matters seems to be:\nn = x2 - (func1sub/func1dsub)\nx...
[ 1 ]
[]
[]
[ "equation", "loops", "newtons_method", "python" ]
stackoverflow_0008391082_equation_loops_newtons_method_python.txt
Q: IzPack, can it output a single executable jar? I found some great tutorials for IzPack and it works great at installing my program into a folder. Is it possible to have the contents of those folder wrapped into an executable jar using IzPack? My goal would be to have that executable jar call my python script which...
IzPack, can it output a single executable jar?
I found some great tutorials for IzPack and it works great at installing my program into a folder. Is it possible to have the contents of those folder wrapped into an executable jar using IzPack? My goal would be to have that executable jar call my python script which launches the application. Let me know what I can do...
[ "I don't think so. Not because IzPak did not have the capability to do that (it obviously creates the installer's jar), but because it was not designed to do so, AFAIK.\nIf you want to pack various jars in a single jar file, then you should attack this problem in the build phase of your project. If you use Netbeans...
[ 1 ]
[]
[]
[ "executable", "izpack", "jar", "java", "python" ]
stackoverflow_0008391110_executable_izpack_jar_java_python.txt
Q: Why do python scripts run through CGI/WSGI on unix-like systems fail if the file has CRLF line endings? In the past, there have been several instances where I have tried to run a Python script under CGI or WSGI, only to get the following ambiguous error in my webserver's log: [error] [client <client>] (2)No such f...
Why do python scripts run through CGI/WSGI on unix-like systems fail if the file has CRLF line endings?
In the past, there have been several instances where I have tried to run a Python script under CGI or WSGI, only to get the following ambiguous error in my webserver's log: [error] [client <client>] (2)No such file or directory: exec of '/path/to/web/root/test.py' failed This happens even with a very simple script, i....
[ "\nIn the case that the python executable cannot be found, why? Does the CRLF endings break the shebang line?\n\nYup, that's it.\n\nIs there a workaround for this other than converting the format? Is it possible to configure CGI/WSGI in such a way to handle this automatically?\n\nSomething that doesn't make you wan...
[ 1 ]
[ "Python will be able to handle the CRLF line endings, but Linux/Unix is expecting only LF as the line ending, so an incredible ugly workaround could be (having the ^M as part of the filename):\n$ sudo ln -s /usr/bin/python /usr/bin/python^M\n\nNote that you have to escape the ^M from the command line, so in bash it...
[ -2 ]
[ "cgi", "linux", "python", "webserver", "wsgi" ]
stackoverflow_0008389498_cgi_linux_python_webserver_wsgi.txt
Q: How are generators and coroutines implemented in CPython? I've read that in CPython, the interpreter stack (the list of Python functions called to reach this point) is mixed with the C stack (the list of C functions that were called in the interpreter's own code). If so, then how are generators and coroutines impl...
How are generators and coroutines implemented in CPython?
I've read that in CPython, the interpreter stack (the list of Python functions called to reach this point) is mixed with the C stack (the list of C functions that were called in the interpreter's own code). If so, then how are generators and coroutines implemented? How do they remember their execution state? Does CPyth...
[ "The notion that Python's stack and C stack in a running Python program are intermixed can be misleading.\nThe Python stack is something completely separated than the actual C stack used by the interpreter. The data structures on Python stack are actually full Python \"frame\" objects (that can even be introspected...
[ 55, 22 ]
[]
[]
[ "coroutine", "python" ]
stackoverflow_0008389812_coroutine_python.txt
Q: Python FAQ: “How fast are exceptions?” I was just looking at the Python FAQ because it was mentioned in another question. Having never really looked at it in detail before, I came across this question: “How fast are exceptions?”: A try/except block is extremely efficient. Actually catching an exception is expensi...
Python FAQ: “How fast are exceptions?”
I was just looking at the Python FAQ because it was mentioned in another question. Having never really looked at it in detail before, I came across this question: “How fast are exceptions?”: A try/except block is extremely efficient. Actually catching an exception is expensive. In versions of Python prior to 2.0 it wa...
[ "Catching exceptions is expensive, but exceptions should be exceptional (read, not happen very often). If exceptions are rare, try/catch is faster than LBYL.\nThe following example times a dictionary key lookup using exceptions and LBYL when the key exists and when it doesn't exist:\nimport timeit\n\ns = []\n\ns.a...
[ 22, 6, 0 ]
[]
[]
[ "exception", "performance", "python", "try_catch" ]
stackoverflow_0008107695_exception_performance_python_try_catch.txt
Q: Using an XML catalog with Python's lxml? Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD. A: You can add the catalog to the XML_CATALOG_FILES environment...
Using an XML catalog with Python's lxml?
Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD.
[ "You can add the catalog to the XML_CATALOG_FILES environment variable:\nos.environ['XML_CATALOG_FILES'] = 'file:///to/my/catalog.xml'\n\nSee this thread. Note that entries in XML_CATALOG_FILES are space-separated URLs. You can use Python's pathname2url and urljoin (with file:) to generate the URL from a pathname.\...
[ 8, 1, 0 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0000012591_lxml_python_xml.txt
Q: Python: Why doesn't this work? (iteration over non-sequence) I have a dictionary with each key containing a list as a value. And I'm trying to go over all the items in the lists, and let's say I'm trying to print all the items as I go through, I wrote: for item in aDict: for item2 in aDict[item]: pr...
Python: Why doesn't this work? (iteration over non-sequence)
I have a dictionary with each key containing a list as a value. And I'm trying to go over all the items in the lists, and let's say I'm trying to print all the items as I go through, I wrote: for item in aDict: for item2 in aDict[item]: print item2 This prints out the items in the list for the first val...
[ "One of your dictionary values is not a list!\n", "I'm assuming one of the items in aDict is not a sequence, string, list, tuple etc:\n>>> aDict = { 'a' : [1, 2, 3,], 'b' : [4, 5, 6,], 'c' : [7, 8, 9,] }\n>>> for item in aDict:\n... for item2 in aDict[item]:\n... print item2\n...\n1\n2\n3\n7\n8\n9\n4\...
[ 7, 5, 0, 0 ]
[]
[]
[ "dictionary", "iteration", "python", "sequence" ]
stackoverflow_0008391935_dictionary_iteration_python_sequence.txt
Q: Recursive Function to Print a Decision Tree in Python: Suppress 'None's I decision trees implemented in Python as dictionaries. Example: sampletree = {'spl':'foo', 'go_r':{'cut':150} , 'l':{'val':100}, 'r':{'val':200}} I have a recursive function prints the tree: def TREE_PRINT(tree, indent=''): #is this a ...
Recursive Function to Print a Decision Tree in Python: Suppress 'None's
I decision trees implemented in Python as dictionaries. Example: sampletree = {'spl':'foo', 'go_r':{'cut':150} , 'l':{'val':100}, 'r':{'val':200}} I have a recursive function prints the tree: def TREE_PRINT(tree, indent=''): #is this a leaf node? if 'val' in tree: print str(tree['val']) else: ...
[ "The return value of your function is None. Don't print the return value of your function - just call your function.\ndef TREE_PRINT(tree, indent=''):\n #is this a leaf node?\n if 'val' in tree:\n print str(tree['val'])\n else:\n #print the criteria\n print 'split: '+ str(tree['spl']) ...
[ 3, 1 ]
[]
[]
[ "decision_tree", "printing", "python" ]
stackoverflow_0008392104_decision_tree_printing_python.txt
Q: What is the difference between module Processing and Multiprocessing? There are two modules for Python that have an almost identical layout in terms of methods and purpose. Is one preferred over the other or do they actually perform differently? A: Multiprocessing is a standard Python library. If I had to guess,...
What is the difference between module Processing and Multiprocessing?
There are two modules for Python that have an almost identical layout in terms of methods and purpose. Is one preferred over the other or do they actually perform differently?
[ "Multiprocessing is a standard Python library.\nIf I had to guess, I'd say that Processing (which hasn't been updated since early 2008) became Multiprocessing — but don't quote me on that.\n" ]
[ 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0008392432_multiprocessing_python.txt
Q: How to swap elements in tuple? I have a very specific problem where I need to know how to swap elements in a list or tuple. I have one list that is called board state and I know the elements that need to be swapped. How do I swap them? In java with two-dimensional arrays, I could easily do the standard swap techn...
How to swap elements in tuple?
I have a very specific problem where I need to know how to swap elements in a list or tuple. I have one list that is called board state and I know the elements that need to be swapped. How do I swap them? In java with two-dimensional arrays, I could easily do the standard swap technique but here it says tuple assignme...
[ "Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple.\nLists are mutable, so convert your board_state to a list of lists:\n>>> board_state = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]\n\nAnd then use the standard Python idiom for swapping two elements in a list:\n>>> board_st...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0008392470_python.txt
Q: Count occurrences of number in two lists and return one list I am trying to count the number of occurrences a 0 occurs in two lists together and save that number using python. I am trying to put it into a third list using 'list comprehension' commands but I am not getting the output I want. My two lists are: list...
Count occurrences of number in two lists and return one list
I am trying to count the number of occurrences a 0 occurs in two lists together and save that number using python. I am trying to put it into a third list using 'list comprehension' commands but I am not getting the output I want. My two lists are: list1 = [0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1...
[ "You can use a list comprehension, like this:\nanswer = [x for x, y in zip(list1, list2) if x == y]\n\nAlternatively, you can solve it without list comprehensions by using simple list operations:\nanswer = []\nfor x, y in zip(list1, list2):\n if x == y:\n answer.append(x)\n\nIn both cases, answerwill be:\...
[ 5, 1, 0, 0, 0 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0008392496_list_list_comprehension_python.txt
Q: How to get manually assigned parent's id which is not bound yet? I have two entities child entity: class Currency(db.Model): country = db.ReferenceProperty(Country) #... parent entity: class Country(db.Model): name = db.StringProperty() #... I manually assign country to currency with appcfg...
How to get manually assigned parent's id which is not bound yet?
I have two entities child entity: class Currency(db.Model): country = db.ReferenceProperty(Country) #... parent entity: class Country(db.Model): name = db.StringProperty() #... I manually assign country to currency with appcfg.py upload_data from Currency.cvs file When I type at console, currenc...
[ "I presume by \"not bound\", you mean that the relevant record hasn't been loaded. You can get the key of a ReferenceProperty with Currency.country.get_value_for_datastore(currency_instance).\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0008388409_google_app_engine_google_cloud_datastore_python.txt
Q: How to identify stripes of different colors how can I identify the presence or absence of regular stripes of different colors, but ranging from very very very very light pink to black inside of a scanned image (bitmap 200x200dpi 24-bit). Carry a few examples. Example 1 Example 2 (the lines are in all the columns ...
How to identify stripes of different colors
how can I identify the presence or absence of regular stripes of different colors, but ranging from very very very very light pink to black inside of a scanned image (bitmap 200x200dpi 24-bit). Carry a few examples. Example 1 Example 2 (the lines are in all the columns except 7 in the second row of the last column) F...
[ "This looks to me a connected component labeling in an image to identify discrete regions of certain color range. You can have a look to cvBlobLib. Some pre-processing would be required to merge the pixels if there are holes or small variations between neighbors. \n", "Not going to happen. The human visual system...
[ 1, 1, 0 ]
[]
[]
[ "algorithm", "identification", "image_processing", "python" ]
stackoverflow_0008376124_algorithm_identification_image_processing_python.txt
Q: Gnuplot (or matplotlib): create non-bar chart with categories on x-axis I would like to create a graph like this one using gnuplot (or matplotlib, if need be), but I don't know if/how it can be done: This, of course, is just a rough sketch. What is important is that I need to plot pairs of values (in this example...
Gnuplot (or matplotlib): create non-bar chart with categories on x-axis
I would like to create a graph like this one using gnuplot (or matplotlib, if need be), but I don't know if/how it can be done: This, of course, is just a rough sketch. What is important is that I need to plot pairs of values (in this example, each pair consists of a red and a blue dot). One item from each pair is a s...
[ "In Matplotlib, you can set ticks individually. The method is explained in one of Matplotlib's examples. \nHere is a start:\n# Initializations:\nfrom matplotlib import pyplot as pp\nimport numpy as np\n\npp.ion() # \"Interactive mode on\": pyplot.* commands draw immediately\n\n# Data:\nseries_red_y = [1.3, 1.4, 2....
[ 5, 1 ]
[]
[]
[ "gnuplot", "graph", "matplotlib", "python" ]
stackoverflow_0008371993_gnuplot_graph_matplotlib_python.txt
Q: Why is a variable able to be defined after definition of function using it? I have a very simple and maybe dumb question: Why does this work? def print_list(): for student in student_list: print(student) student_list = ["Simon", "Mal", "River", "Zoe", "Jane", "Kaylee", "Hoban"] print_list() The way I...
Why is a variable able to be defined after definition of function using it?
I have a very simple and maybe dumb question: Why does this work? def print_list(): for student in student_list: print(student) student_list = ["Simon", "Mal", "River", "Zoe", "Jane", "Kaylee", "Hoban"] print_list() The way I've come to know functions and arguments, the function print_list() shouldn't rec...
[ "By the time you're calling print_list(), you have student_list defined as a global variable. \n", "The way I understand it is that your program has 3 parts\n\ndefine print_list()\ninitialise student_list (global variable)\ncall print_list()\n\nWhen you call print_list(), student_list is already there. Also, in a...
[ 6, 1, 1 ]
[]
[]
[ "arguments", "data_structures", "function", "list", "python" ]
stackoverflow_0008393122_arguments_data_structures_function_list_python.txt
Q: What is the easiest way to get an usb-drive unique id with python on linux? I want to get the unique id from an usb hard-drive with python for a project im working on. What is the easiest way of achieving this? Is there a better way to do it? Can this be done platform independent? A: Use the system call to read ...
What is the easiest way to get an usb-drive unique id with python on linux?
I want to get the unique id from an usb hard-drive with python for a project im working on. What is the easiest way of achieving this? Is there a better way to do it? Can this be done platform independent?
[ "Use the system call to read in 'lsusb', and then parse the output. \nimport os \ncmd = 'lsusb' \nos.system(cmd)\n\nOr an easier to parse solution would be the commands library. \nimport commands \noutput = commands.getstatusoutput('lsusb')\n\nAnd then you would manipulate or search output with regex for your ...
[ 2 ]
[]
[]
[ "python", "usb", "usb_drive" ]
stackoverflow_0008393202_python_usb_usb_drive.txt
Q: How can I get an specific value in a webpage? I have some <div>s and other stuff in a site and the specific line in the middle of inumerous divs <input name="extWarrantyProds" type="hidden" value="23814298 ^ true"/> How can I get the "value" part from this code, which it is in the middle of a site with other stuf...
How can I get an specific value in a webpage?
I have some <div>s and other stuff in a site and the specific line in the middle of inumerous divs <input name="extWarrantyProds" type="hidden" value="23814298 ^ true"/> How can I get the "value" part from this code, which it is in the middle of a site with other stuff ? I'm trying with urllib but I don't even know wh...
[ "import lxml.html as lh\n\nhtml = '''\n<input name=\"extWarrantyProds\" type=\"hidden\" value=\"23814298 ^ true\"/>\n'''\n\n# If you want to parse from a URL:\n# tree = lh.parse('http://example.com')\n\ntree = lh.fromstring(html)\n\nprint tree.xpath(\"//input[@name='extWarrantyProds']/@value\")\n\n", "The easiest...
[ 3, 2, 1 ]
[]
[]
[ "python", "urllib", "windows" ]
stackoverflow_0008392574_python_urllib_windows.txt
Q: Setting Python Path in Windows XAMPP using WSGI I'm setting up a development version of a live server on Webfaction, running Django apps in a virtual Apache server environment (running without any errors) on my local machine - XP, running XAMPP Lite with Python 2.6 - which I can commit changes from via Git. XAMPP ...
Setting Python Path in Windows XAMPP using WSGI
I'm setting up a development version of a live server on Webfaction, running Django apps in a virtual Apache server environment (running without any errors) on my local machine - XP, running XAMPP Lite with Python 2.6 - which I can commit changes from via Git. XAMPP is up and running OK with Python, and the server star...
[ "My PC has Python 2.6, so I'll use all the configuration under the assumption that Python 2.6 is the target version.\n\nDownload newest xampp (http://www.apachefriends.org/en/xampp-windows.html), as of Nov 29, 2010, ver 1.7.3 is the newest.\nInstall xampp for windows, I installed it c:\\xampp\nDownload and install ...
[ 9, 1 ]
[]
[]
[ "apache", "mod_wsgi", "python", "windows_xp", "xampp" ]
stackoverflow_0003891996_apache_mod_wsgi_python_windows_xp_xampp.txt
Q: Plotting graph on top of World map I'm trying to plot a graph representing a P2P network on top of a world map. I want to be able to draw vertices and edges, and it has to work with several thousands of veritces/edges on a map. Is there a python library that allows me to do so? A: The matplotlib package with the...
Plotting graph on top of World map
I'm trying to plot a graph representing a P2P network on top of a world map. I want to be able to draw vertices and edges, and it has to work with several thousands of veritces/edges on a map. Is there a python library that allows me to do so?
[ "The matplotlib package with the basemap toolkit might work for you. See here for some examples of its use.\n", "You could use the canvas object in the tkinter library for basic drawing.\nhttp://effbot.org/tkinterbook/canvas.htm\n" ]
[ 1, 0 ]
[]
[]
[ "geoip", "geolocation", "graph", "python" ]
stackoverflow_0008393460_geoip_geolocation_graph_python.txt
Q: Verifying product key Possible Duplicate: How are Software License Keys generated? How do software programs verify the product key offline? Is there already a list of possible keys in the db, or does the program decode the input key in some way? If the latter, how is the decoding done? A: Well, there are multi...
Verifying product key
Possible Duplicate: How are Software License Keys generated? How do software programs verify the product key offline? Is there already a list of possible keys in the db, or does the program decode the input key in some way? If the latter, how is the decoding done?
[ "Well, there are multitudes of algorithms that can be used to encode/decode product keys (using matricies etc.), but one of the more common methods is by use of a program called Keygen. For more information on Keygen, check out this link.\n" ]
[ 0 ]
[]
[]
[ "java", "python", "security" ]
stackoverflow_0008393555_java_python_security.txt
Q: django: handler for inline admin save When a user clicks the 'save' button on a model page of my django site, I want to do something with all the models that are to be updated, all at once. If I override save_model, it is called once per each object, but I want one function to be called with all objects to-be-upda...
django: handler for inline admin save
When a user clicks the 'save' button on a model page of my django site, I want to do something with all the models that are to be updated, all at once. If I override save_model, it is called once per each object, but I want one function to be called with all objects to-be-updated. I overrode save_formset but it didn't ...
[ "formset.save() returns a list of all objects from the formset. You can call it with commit=False and the changes are only validated, not saved in the DB.\nsave_formset() is only called by admin (you can do a grep in django's source).\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0008393107_django_django_admin_python.txt
Q: Vim python support with non system python I am trying to build vim with python support, but using a custom-built python somewhere in my $HOME directory (say $HOME/python2.6). Unfortunately, even giving --with-python-config-dir=$HOME/python2.6/lib/python2.6/config does not prevent vim configure to look into the pyt...
Vim python support with non system python
I am trying to build vim with python support, but using a custom-built python somewhere in my $HOME directory (say $HOME/python2.6). Unfortunately, even giving --with-python-config-dir=$HOME/python2.6/lib/python2.6/config does not prevent vim configure to look into the python in /usr. Is there a way around that that do...
[ "Just glancing at the configure file it looks like you can set the path to the python executable using an env var 'vi_cv_path_python'. So:\nvi_cv_path_python=~/bin/python ./configure --enable-pythoninterp\n\nReplacing ~/bin/python with the appropriate path for your install of course.\n" ]
[ 8 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0008391077_python_vim.txt
Q: specification driven packet format parsing? this could a shot in the dark: we have a wire packet format which is in design and in flux. Is there a flexible way to specify and parse the incoming stream instead of harding coding it? Preferably language agnostic ... but not necessarily so. If there is a good reason ...
specification driven packet format parsing?
this could a shot in the dark: we have a wire packet format which is in design and in flux. Is there a flexible way to specify and parse the incoming stream instead of harding coding it? Preferably language agnostic ... but not necessarily so. If there is a good reason not to do that, please enlighten me as well. Than...
[ "There is a wonderful Python library called Construct. This is by far the easiest way to get started quickly.\nIf it is more important to be language agnostic, you can limit your wire protocol to ASN.1 BER, since it's usually possible to find an encoder/decoder library for these in whatever language. For example, t...
[ 4, 1, 1 ]
[]
[]
[ "java", "networking", "python" ]
stackoverflow_0008393457_java_networking_python.txt
Q: itertools does not work in GAE? error log: 2011-12-05 14:56:01.211 <type 'exceptions.AttributeError'>: 'module' object has no attribute 'product' Traceback (most recent call last): File "/base/data/home/apps/s~ellipt-test/1.355173855249110456/helloworld.py", line 494, in <module> F16 = field_elements(2, 4) ...
itertools does not work in GAE?
error log: 2011-12-05 14:56:01.211 <type 'exceptions.AttributeError'>: 'module' object has no attribute 'product' Traceback (most recent call last): File "/base/data/home/apps/s~ellipt-test/1.355173855249110456/helloworld.py", line 494, in <module> F16 = field_elements(2, 4) File "/base/data/home/apps/s~ellipt...
[ "The app engine docs say:\n\nYour application can run in one of three runtime environments: […] a choice of Python 2.5 or the experimental Python 2.7.\n\nI'm assuming this implies the default Python is version 2.5.\nThe itertools.product() docs say:\n\nNew in version 2.6.\n\nI'm not really familiar with GAE, so not...
[ 8 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008393719_google_app_engine_python.txt
Q: Is it possible to set up ipython to tab complete function argument parameters In the ipython shell, is it possible to set it up so that I can define tab completion for function/method parameters? I have several methods that will only ever take certain arguments from a defined list of potential arguments, and it wo...
Is it possible to set up ipython to tab complete function argument parameters
In the ipython shell, is it possible to set it up so that I can define tab completion for function/method parameters? I have several methods that will only ever take certain arguments from a defined list of potential arguments, and it would be nice if I could tab complete them from inside the list. If this is possible,...
[ "Not easily, no.\nThere are ways to extend the possible tab completions, but as far as I know, no simple ways to restrict the list of possible completions.\nIf you want to try to hack something together, I think this is the place in the code to start looking: https://github.com/ipython/ipython/blob/master/IPython/c...
[ 2 ]
[]
[]
[ "ipython", "python", "tab_completion" ]
stackoverflow_0008361019_ipython_python_tab_completion.txt
Q: UnboundLocalError, local variable accessed before assignment, but not? I'm doing something pretty simple in Django and I'm getting this really weird error: UnboundLocalError at /me/profile/edit/ local variable 'form' referenced before assignment Here's my code: if request.method == "POST": form = MyForm(reque...
UnboundLocalError, local variable accessed before assignment, but not?
I'm doing something pretty simple in Django and I'm getting this really weird error: UnboundLocalError at /me/profile/edit/ local variable 'form' referenced before assignment Here's my code: if request.method == "POST": form = MyForm(request.POST) if form.is_valid(): print "Yes" else: form = MyForm...
[ "The simplest solution to this problem is to remove the else clause:\nform = MyForm(request.POST or None)\n\nif request.method == 'POST':\n if form.is_valid():\n print 'Yes'\n\nDanny Greenfeld's Advanced Django Form Usage presentation is a great example of this: http://www.slideshare.net/pydanny/advanced-...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008393812_django_python.txt
Q: python, rpy2 installation test - nosetests rpy2 results in failure I have the academic version of EPD 7.1 installed on MacOS 10.6.4. I installed Rpy2 by invoking `easy_install rpy2 Searching for rpy2 Reading http://pypi.python.org/simple/rpy2/ Reading http://rpy.sourceforge.net Best match: rpy2 2.2.4 Downloading ...
python, rpy2 installation test - nosetests rpy2 results in failure
I have the academic version of EPD 7.1 installed on MacOS 10.6.4. I installed Rpy2 by invoking `easy_install rpy2 Searching for rpy2 Reading http://pypi.python.org/simple/rpy2/ Reading http://rpy.sourceforge.net Best match: rpy2 2.2.4 Downloading http://pypi.python.org/packages/source/r/rpy2/rpy2-2.2.4.tar.gz#md5=0192...
[ "Seems like to test the installation of RPy2 you need to run:\npython -m 'rpy2.tests'\n" ]
[ 1 ]
[]
[]
[ "nosetests", "python", "rpy2" ]
stackoverflow_0008379772_nosetests_python_rpy2.txt
Q: Checking for duplicate key during signup process (Django, JS, Ajax) I have a javascript function that is called onsubmit: function formCheck(){ return usernameCheck() && passwordCheck(); } passwordCheck() works fine and returns things as it should, but for some reason usernameCheck() is having issues: functio...
Checking for duplicate key during signup process (Django, JS, Ajax)
I have a javascript function that is called onsubmit: function formCheck(){ return usernameCheck() && passwordCheck(); } passwordCheck() works fine and returns things as it should, but for some reason usernameCheck() is having issues: function usernameCheck(){ //returns true if username is free var ajaxHeaders = {...
[ "The A in Ajax stands for asynchronous. The success function you have supplied is not executed immediately, it is called after the browser gets a response from the server, which will be after you've returned from the usernameCheck() function.\nYou can't do this check with return values, you've got to use callbacks...
[ 2 ]
[]
[]
[ "ajax", "django", "javascript", "jquery", "python" ]
stackoverflow_0008394072_ajax_django_javascript_jquery_python.txt
Q: How to extract links from a webpage using lxml, XPath and Python? I've got this xpath query: /html/body//tbody/tr[*]/td[*]/a[@title]/@href It extracts all the links with the title attribute - and gives the href in FireFox's Xpath checker add-on. However, I cannot seem to use it with lxml. from lxml import etree p...
How to extract links from a webpage using lxml, XPath and Python?
I've got this xpath query: /html/body//tbody/tr[*]/td[*]/a[@title]/@href It extracts all the links with the title attribute - and gives the href in FireFox's Xpath checker add-on. However, I cannot seem to use it with lxml. from lxml import etree parsedPage = etree.HTML(page) # Create parse tree from valid page. # Xp...
[ "I was able to make it work with the following code:\nfrom lxml import html, etree\nfrom StringIO import StringIO\n\nhtml_string = '''<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html lang=\"en\">\n<head/>\n<body>\n <table border=\"1\">\n ...
[ 12, 3 ]
[]
[]
[ "extraction", "hyperlink", "lxml", "python", "screen_scraping" ]
stackoverflow_0002084670_extraction_hyperlink_lxml_python_screen_scraping.txt
Q: This is probably a trivial overlook, just starting out with python I made a short text adventure for my human phys class about the liver. link: http://pastebin.com/QYkn5VuU #SUPER LIVER ADVENTURE 12! from sys import exit from random import randint quips = ["Welcome!", "have a wonderful day", "Livers are cool...
This is probably a trivial overlook, just starting out with python
I made a short text adventure for my human phys class about the liver. link: http://pastebin.com/QYkn5VuU #SUPER LIVER ADVENTURE 12! from sys import exit from random import randint quips = ["Welcome!", "have a wonderful day", "Livers are cool!", "this text was chosen at random", "Writen in python", "woo, splas...
[ "Your elif statement on line 82 reads:\nelif idunno_something == \"sex\" or \"drugs\" or \"rock n roll\":\n\nthis should be\nelif idunno_something in (\"sex\", \"drugs\", \"rock n roll\"):\n\nThe same sort of change should help on lines 22, 38 and 77.\n", "Since you are a beginner, I will start with some suggesti...
[ 6, 2, 2 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0008393811_if_statement_python.txt
Q: Can I make a jar execute a python script? Is there some way to call a script within a jar without extracting it? A: As JAR files are zip archives, you can unzip a single file to standard output and pipe to Python. unzip -p your.jar file_in_jar.py | python A: Python will interpret a file named "__main__.py" sto...
Can I make a jar execute a python script?
Is there some way to call a script within a jar without extracting it?
[ "As JAR files are zip archives, you can unzip a single file to standard output and pipe to Python.\nunzip -p your.jar file_in_jar.py | python\n\n", "Python will interpret a file named \"__main__.py\" stored inside a zip file, if called with one as a parameter. Since jar files are zips, all you have to do is name ...
[ 3, 2, 0 ]
[]
[]
[ "executable", "jar", "java", "python" ]
stackoverflow_0008392875_executable_jar_java_python.txt
Q: How to get the region/city from a geocoding object? My problem is that eg results[0].address_components[2].short_name.toLowerCase(); in some cases returns the city and in some cases the region/state. How should I do to always get the locality (city) and which element is always the admin area (region/state)? Thanks...
How to get the region/city from a geocoding object?
My problem is that eg results[0].address_components[2].short_name.toLowerCase(); in some cases returns the city and in some cases the region/state. How should I do to always get the locality (city) and which element is always the admin area (region/state)? Thanks for any insight. The manual is here http://code.google.c...
[ "You will have to look at the types array and then extract the values accordingly. Further down the page they have an explanation of the different types \nhttp://code.google.com/apis/maps/documentation/geocoding/#Types\nEven then you might still have some problem. That is because of the address structure in differe...
[ 1 ]
[]
[]
[ "google_maps_api_3", "javascript", "python" ]
stackoverflow_0008394759_google_maps_api_3_javascript_python.txt
Q: Newbie Apache / Python error Trying to configure apache on my laptop to execute a python script for a small assignment: I've created a /scripts folder in root and granted it all permissions 777. In my virtual hosts file I have added ScriptAlias /scripts/ /scripts/ Added directory handle also in my conf file: ...
Newbie Apache / Python error
Trying to configure apache on my laptop to execute a python script for a small assignment: I've created a /scripts folder in root and granted it all permissions 777. In my virtual hosts file I have added ScriptAlias /scripts/ /scripts/ Added directory handle also in my conf file: Options +ExecCGI FollowSymLinks I...
[ "I don't have access to OSX, but I'd probably try something like this:\nScriptAlias /cgi-bin/ \"/scripts/\"\n<Directory \"/scripts\">\n Options +ExecCGI FollowSymLinks Indexes MultiViews\n AllowOverride All \n Order allow,deny\n Allow from all\n AddHandler cgi-script .py\n</Directory>\n\n" ]
[ 0 ]
[]
[]
[ "apache", "macos", "python" ]
stackoverflow_0008394680_apache_macos_python.txt
Q: How to map relation between one table and third table proxed by second table? Let's have 3 tables A, B, C and relations between them. A is many to one with B B is one to many with C How to write relation in sqlalchemy to have access to C from A, like: A.C[0].some_column A: In your example A is many to one with B...
How to map relation between one table and third table proxed by second table?
Let's have 3 tables A, B, C and relations between them. A is many to one with B B is one to many with C How to write relation in sqlalchemy to have access to C from A, like: A.C[0].some_column
[ "In your example\nA is many to one with B\nB is one to many with C\nSo finally \nA is many to many C is the last relationship if you want to access the C from A.\nYou have to create the relationship in each model to access directly. \nFor example\nA.x is relationship with B\nB.y is relationship with C\n\nthen you c...
[ 3 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0008385310_python_sqlalchemy.txt
Q: displaying within decimal range in python I am reading the wrox Beginning Python book. In chapter 2, the example states >>> print "$.03f" & 30.00123 $30.001 However this does not explain the behavior of the command. Why use .03 when .3 and .003 etc have the same behavior in the shell? Furthermore, it does not exp...
displaying within decimal range in python
I am reading the wrox Beginning Python book. In chapter 2, the example states >>> print "$.03f" & 30.00123 $30.001 However this does not explain the behavior of the command. Why use .03 when .3 and .003 etc have the same behavior in the shell? Furthermore, it does not explain what happends when I just use 3 >>> print ...
[ "The 0 in '%.03f' does nothing. This is equivalent to '%.3f'.\nAs for the second question, what does '%3f' do, it simply specifies the length for the whole number, exactly as it would in '%3s'. It becomes clear if you make it longer:\n>>> '%10f' % 2.3\n' 2.300000'\n>>> len(_)\n10\n>>>\n\n", "This is a feature kn...
[ 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008395189_python.txt
Q: trouble compiling and installing cantera python module I'm attempting to install the Cantera as a python module within Ubuntu linux. For reference I used these instructions: Installing Cantera. After running ./preconfig and make, I get the following error: fatal error: numarray/arrayobject.h: No such file or di...
trouble compiling and installing cantera python module
I'm attempting to install the Cantera as a python module within Ubuntu linux. For reference I used these instructions: Installing Cantera. After running ./preconfig and make, I get the following error: fatal error: numarray/arrayobject.h: No such file or directory According to the preconfig file, # If numpy was in...
[ "You probably have several Python distributions on your Ubuntu box. In\norder to use EPD to install Cantera you should tell it explicitly\nwhich distribution to use:\nPYTHON_CMD=${PYTHON_CMD:=\"/usr/local/EPD/bin/python\"}\n\nEvery distribution has its own site-packages directory, so by\nspecifying PYTHON_CMD you a...
[ 1, 1, 1 ]
[]
[]
[ "cantera", "failed_installation", "linux", "python", "ubuntu" ]
stackoverflow_0008175393_cantera_failed_installation_linux_python_ubuntu.txt
Q: How do I manage a Python based daemon on Linux? I have a working Python based program that I want to run as a daemon. Currently I'm doing it in a very hackish manner of starting it in with screen-d -m name session and killing it with pkill -9 -f name. Eventually I'm doing to have to move this to the better system ...
How do I manage a Python based daemon on Linux?
I have a working Python based program that I want to run as a daemon. Currently I'm doing it in a very hackish manner of starting it in with screen-d -m name session and killing it with pkill -9 -f name. Eventually I'm doing to have to move this to the better system we use here (thus I'm not willing to modify the progr...
[ "On linux there is a start-stop-daemon utility as part of the init.d tools.\nIt is very flexible and allows different ways for capturing the pid of your server.\nThere is also a file /etc/init.d/skeleton which can serve as a basis for your own init.d script.\nIf your target platform is debian based, it makes sense...
[ 6, 5, 3, 2, 1, 0 ]
[]
[]
[ "bash", "daemon", "init.d", "linux", "python" ]
stackoverflow_0002951627_bash_daemon_init.d_linux_python.txt
Q: How to reverse geocode serverside with python, json and google maps? I'm trying serverside reverse geocoding that can get me a json response and now I want to get 2 or 3 variables from the json response: I'd like to parse for instance this data and end with eg. administrative_area_level_1 = 'Stockholm' jsondata = ...
How to reverse geocode serverside with python, json and google maps?
I'm trying serverside reverse geocoding that can get me a json response and now I want to get 2 or 3 variables from the json response: I'd like to parse for instance this data and end with eg. administrative_area_level_1 = 'Stockholm' jsondata = json.load(urllib2.urlopen('http://maps.googleapis.com/maps/api/geocode/jso...
[ "Processing the response\nThere is no need to parse the JSON - it is already parsed by json.load() and returned as Python's data structure. Use it like simple dictionary with lists or different dictionaries in it.\nAccessing the needed part of the response\nTo access data you should be working with you can use the ...
[ 14 ]
[]
[]
[ "google_maps_api_3", "python", "reverse_geocoding" ]
stackoverflow_0008395252_google_maps_api_3_python_reverse_geocoding.txt
Q: how to sort alphanumerically in Unix with sort? More complex than seems I'm trying to sort a string of letters and numbers alphanumerically in an "intuitive"/natural way using the unix sort command, but cannot get it to sort properly. I have this file: $ cat ~/headers @42EBKAAXX090828:6:100:1699:328/2 @42EBKAAXX0...
how to sort alphanumerically in Unix with sort? More complex than seems
I'm trying to sort a string of letters and numbers alphanumerically in an "intuitive"/natural way using the unix sort command, but cannot get it to sort properly. I have this file: $ cat ~/headers @42EBKAAXX090828:6:100:1699:328/2 @42EBKAAXX090828:6:10:1077:1883/2 @42EBKAAXX090828:6:102:785:808/2 I'd like to sort it ...
[ "the -V option appears to do what you want - natural sorting. Intended for version numbers apparently (hence the letter chosen)\nsort -V ~/headers\n\noutputs \n@42EBKAAXX090828:6:10:1077:1883/2\n@42EBKAAXX090828:6:100:1699:328/2\n@42EBKAAXX090828:6:102:785:808/2\n\n", "It is sorting it alphabetically as it is in ...
[ 11, 4, 0 ]
[]
[]
[ "bash", "python", "shell", "sorting", "unix" ]
stackoverflow_0008395395_bash_python_shell_sorting_unix.txt
Q: Printing out strings toggling through list of tuples...help? I have a list of tuples which relate a given actor to other actors through the movies and co-stars: For a given actor E ActE: conn_list = [('m6', 'D ActD'), ('m3', 'B ActB'), ('m2', 'Kevin Bacon')] So this says that: E ActE was in a movie m6 with D ActD...
Printing out strings toggling through list of tuples...help?
I have a list of tuples which relate a given actor to other actors through the movies and co-stars: For a given actor E ActE: conn_list = [('m6', 'D ActD'), ('m3', 'B ActB'), ('m2', 'Kevin Bacon')] So this says that: E ActE was in a movie m6 with D ActD D ActE was in a movie m3 with B ActB B ActB was in a movie m3 wi...
[ "your input does not match your format string, but this is what you want to do:\nactor_name = \"ActE\"\nconn_list = [('m6', 'D ActD'), \n ('m3', 'B ActB'), \n ('m2', 'Kevin Bacon')]\n\nfor con in conn_list:\n print \"%s was in movie %s with %s\" % (actor_name, con[0], con[1])\n\nthe form...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008395713_python.txt
Q: Array element evaluation from reverse I'm still very new to python and programing and I'm trying to figure out if I'm going about this problem in the correct fashion. I tend to have a matlab approach to things but here I'm just struggling... Context: I have two numpy arrays plotted in this image on flickr since I ...
Array element evaluation from reverse
I'm still very new to python and programing and I'm trying to figure out if I'm going about this problem in the correct fashion. I tend to have a matlab approach to things but here I'm just struggling... Context: I have two numpy arrays plotted in this image on flickr since I can't post photos here :(. They are of equa...
[ "To answer you question directly, you can use n[::-1] to reverse the arrray n.\nSo the code is :\nfor j, m in enumerate(n[::-1]):\n j = len(n)-j-1\n # here is your code\n\nBut to increase calculation speed, you should avoid python loop:\nimport numpy as np\nn = np.array([1,2,3,4,2,5,7,8,3,2,3,3,0,1,1,2])\n\ni...
[ 2, 1, 0 ]
[]
[]
[ "arrays", "for_loop", "python" ]
stackoverflow_0008395348_arrays_for_loop_python.txt
Q: Understanding collisions with custom hashing I'm using the following in my application: base64.urlsafe_b64encode(str(random.getrandbits(20))).lower().replace('=', '') Minus the aesthetic changes: base64.urlsafe_b64encode(str(random.getrandbits(20)) How do I go about finding out the likelihood of collision? A: ...
Understanding collisions with custom hashing
I'm using the following in my application: base64.urlsafe_b64encode(str(random.getrandbits(20))).lower().replace('=', '') Minus the aesthetic changes: base64.urlsafe_b64encode(str(random.getrandbits(20)) How do I go about finding out the likelihood of collision?
[ "It's the same likelihood of one random.getrandbits(20) colliding with another since the outer functions are deterministic.\nIf the output of random.getrandbits are in fact, random -- the chance of one colliding with another is 1/(2^20) or ... about 1 in a million\nFor n entries, the chance that an additional entry...
[ 0, 0 ]
[]
[]
[ "collision", "python", "random" ]
stackoverflow_0008395880_collision_python_random.txt
Q: Working with WTForms FieldList I use WTForms with Flask via the Flask.WTF extension. This question isn't Flask-specific, though. WTForms includes a FieldList field for lists of fields. I'd like to use this to make a form where users can add or remove items. This will require some sort of Ajax framework to dynamica...
Working with WTForms FieldList
I use WTForms with Flask via the Flask.WTF extension. This question isn't Flask-specific, though. WTForms includes a FieldList field for lists of fields. I'd like to use this to make a form where users can add or remove items. This will require some sort of Ajax framework to dynamically add widgets, but the WTForms doc...
[ "I used something like this with my FieldList/FormField to allow adding more entries:\n$(document).ready(function () {\n $('#add_another_button').click(function () {\n clone_field_list('fieldset:last');\n });\n});\n\nfunction clone_field_list(selector) {\n var new_element = $(selector).clone(true);\...
[ 7, 1 ]
[]
[]
[ "ajax", "flask", "forms", "python", "wtforms" ]
stackoverflow_0006000595_ajax_flask_forms_python_wtforms.txt
Q: Installing dateutil I'd like to install the most recent version of dateutil, to work with Python 3.1. My systems default version of Python is 2.6.1, so I run scripts written with Python 3.x syntax by adding the following shebang to the top of each file: #!/usr/local/bin/python3.1 # -*- coding utf-8 -*- Can anyon...
Installing dateutil
I'd like to install the most recent version of dateutil, to work with Python 3.1. My systems default version of Python is 2.6.1, so I run scripts written with Python 3.x syntax by adding the following shebang to the top of each file: #!/usr/local/bin/python3.1 # -*- coding utf-8 -*- Can anyone tell me what I need to ...
[ "You probably need to invoke setup.py with the version of python you intend to use it with. Something like the following:\n$ /usr/local/bin/python3.1 setup.py build\n$ sudo /usr/local/bin/python3.1 setup.py install\n\nThere is no need to edit the first shebang line of the source files.\nSee Installing Python Module...
[ 2, 0 ]
[]
[]
[ "python", "python_dateutil" ]
stackoverflow_0006947672_python_python_dateutil.txt
Q: Compiled python code Vs py2exe I have used PyScripter to generate compiled python code file in a project. If I could generate such files using IDE's what is the need of Py2Exe? I can run my applications using compiled python code.. A: I have not used PyScripter myself but looking at their website. I can at-leas...
Compiled python code Vs py2exe
I have used PyScripter to generate compiled python code file in a project. If I could generate such files using IDE's what is the need of Py2Exe? I can run my applications using compiled python code..
[ "I have not used PyScripter myself but looking at their website. I can at-least find three reasons\n\n\"If you are using a 64bit version of Windows note that PyScripter will only work if a 32bit version of Python is installed\" as quoted here. \nCompatibility with Python 2.7\nRunning on my Linux Box. I am not a gre...
[ 0 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0008396044_py2exe_python.txt
Q: String formatting options: pros and cons These are two very popular ways of formatting a string in Python. One is using a dict: >>> 'I will be %(years)i on %(month)s %(day)i' % {'years': 21, 'month': 'January', 'day': 23} 'I will be 21 on January 23' And the other one using a simple tuple: >>> 'I will be %i on %s...
String formatting options: pros and cons
These are two very popular ways of formatting a string in Python. One is using a dict: >>> 'I will be %(years)i on %(month)s %(day)i' % {'years': 21, 'month': 'January', 'day': 23} 'I will be 21 on January 23' And the other one using a simple tuple: >>> 'I will be %i on %s %i' % (21, 'January', 23) 'I will be 21 on Ja...
[ "Why format() is more flexible than % string operations\nI think you should really stick to format() method of str, because it is the preferred way to format strings and will probably replace string formatting operation in the future.\nFurthermore, it has some really good features, that can also combine position-ba...
[ 21, 20 ]
[ "I am not answering the question but just explaining the idea I came up in my TIScript. \nI've introduced so called \"stringizer\" functions: any function with name starting from '$' is a stringizer. Compiler treats '$name(' and ')' as quotes of string literal combined with function call.\nExample, this:\n$print(I ...
[ -2 ]
[ "python", "string_formatting" ]
stackoverflow_0008395925_python_string_formatting.txt
Q: I need 'python-support' on a Mac. Where can I find it? If I am on a debian based system and using python and I want to update some modules, there is a feature of python called 'python-support'. I can install it by sudo apt-get install python-support I can't manage to find it anywhere for mac, and I have attempte...
I need 'python-support' on a Mac. Where can I find it?
If I am on a debian based system and using python and I want to update some modules, there is a feature of python called 'python-support'. I can install it by sudo apt-get install python-support I can't manage to find it anywhere for mac, and I have attempted to install it using mac ports via the ... sudo port instal...
[ "I am not a Mac user or developer, but refer to http://www.fprimex.com/coding/pymac.html, you can use easy_install or pip utility as they are on Windows or Linux.\nFor example:\nInstall a module:\npip install <module>\n\nUpgrade a module:\npip install <module> -U\n\n", "update-python-modules does not update the m...
[ 2, 2, 0 ]
[ "I believe python supports all OS like Windows, Ubuntu, Mac etc\nPlease refer http://python.org/download/\n" ]
[ -2 ]
[ "macos", "python" ]
stackoverflow_0008396049_macos_python.txt
Q: mysqldb .. 'NoneType' object is not subscriptable This code works fine when the cur.execute() and db.commit() lines are commented out; i.e. if all I do is print the query, this program runs for n number of rows. The problem seems to occur here: player_categories_statistics = cur.fetchone() player_id = player_categ...
mysqldb .. 'NoneType' object is not subscriptable
This code works fine when the cur.execute() and db.commit() lines are commented out; i.e. if all I do is print the query, this program runs for n number of rows. The problem seems to occur here: player_categories_statistics = cur.fetchone() player_id = player_categories_statistics[0] When I try to insert the result, I...
[ "The reason for your error is:\nplayer_categories_statistics = cur.fetchone()\n\nThis sets player_categories_statistics to None. None[0] raises the exception.\nThe only reason this would happen is your query returns no rows, which means your table is empty. Your table is most likely is empty because you never put...
[ 3 ]
[]
[]
[ "mysql_python", "python" ]
stackoverflow_0008393434_mysql_python_python.txt
Q: Want to extract string using regex I've string like this [[English language|English]]. I tried to extract text from string. But no luck. I just Want to ignore text [[English language|.Output should be English. Another example: [[Stack Exchange|Question]] Output should be only Question If there is no | [[Stack Exch...
Want to extract string using regex
I've string like this [[English language|English]]. I tried to extract text from string. But no luck. I just Want to ignore text [[English language|.Output should be English. Another example: [[Stack Exchange|Question]] Output should be only Question If there is no | [[Stack Exchange]] Then output should be only Stack ...
[ "This regex will do it.\n^\\[\\[(?:.*?\\|)?(.*?)?\\]\\]$\n\nRegExr.\nThe first capturing group will contain the text you want.\n", "This can be done without regex\n>>> text=\"[[English language|English]]\"\n>>> text.strip(\"[]\").split(\"|\")[-1]\n'English'\n>>> text=\"[[Stack Exchange|Question]]\"\n>>> text.stri...
[ 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008396361_python_regex.txt
Q: Cython ImportError: No module named parallel I am trying to access the new parallel features of Cython 0.15 (using Cython 0.15.1). However, if I try this minimal example (testp.py), taken from http://docs.cython.org/src/userguide/parallelism.html: from cython.parallel import prange, parallel, threadid cdef int i c...
Cython ImportError: No module named parallel
I am trying to access the new parallel features of Cython 0.15 (using Cython 0.15.1). However, if I try this minimal example (testp.py), taken from http://docs.cython.org/src/userguide/parallelism.html: from cython.parallel import prange, parallel, threadid cdef int i cdef int sum = 0 for i in prange(n, nogil=True): ...
[ "I'm using Cython 0.15+\ncython.parallel exists in Shadow.py:\nimport sys\nsys.modules['cython.parallel'] = CythonDotParallel()\n\nAnd the Shadow.py can be located in your Python's dist-packages directory like /usr/local/lib/python2.6/dist-packages/ in Linux\n", "You can check all of your python modules in python...
[ 1, 0 ]
[]
[]
[ "cython", "enthought", "parallel_processing", "python" ]
stackoverflow_0008387510_cython_enthought_parallel_processing_python.txt
Q: How to implement a if test in a customized class Is there something like _if_ or _not_ methods implemented in a customized class? So when I instantiate a new class, I can use if myobject: return True or if not myobject: return False A: If what you want is to use instances of your class as boolean value...
How to implement a if test in a customized class
Is there something like _if_ or _not_ methods implemented in a customized class? So when I instantiate a new class, I can use if myobject: return True or if not myobject: return False
[ "If what you want is to use instances of your class as boolean values, i.e., some of the instances of your class are truthy and some are falsy, then, in your class, define __nonzero__ appropriately.\nSee Section 5.1 in the docs\nBy default, saying\nif myobject:\n\nwhere myobject is an instance of some class, will e...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0008396654_python.txt
Q: obj in sequence: comparing with 'is' rather than '==' In a program I have something like this going on: class MyClass: def __init__(self, index, other_attribute) self.index = index #is of type int self.other_attribute = other_attribute # I know this is being taken out of python 3, # b...
obj in sequence: comparing with 'is' rather than '=='
In a program I have something like this going on: class MyClass: def __init__(self, index, other_attribute) self.index = index #is of type int self.other_attribute = other_attribute # I know this is being taken out of python 3, # but I haven't converted it to using __eq__ etc. def __cm...
[ "If you would like to test membership by address, you could use this any/is combo:\nif not any(b is x for x in ary):\n ary.append(b)\n\nIf you are stuck on using the in syntax, you could define your own list object and implement a __contains__ method that compares with is rather than ==.\n" ]
[ 2 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0008391301_python_python_2.7.txt
Q: How can a SQLAlchemy Class inherit properly despite having a tricky ForeignKey-relationship? I implemented joined table inheritance as described in question SQLAlchemy Inheritance. There is the following situation: I would like to have a User which has an emailaddress Alias which assigns an alias - emailaddress t...
How can a SQLAlchemy Class inherit properly despite having a tricky ForeignKey-relationship?
I implemented joined table inheritance as described in question SQLAlchemy Inheritance. There is the following situation: I would like to have a User which has an emailaddress Alias which assigns an alias - emailaddress to another email address In order to keep the emailaddress unique, the idea would be to let both c...
[ "Seems like there might be a problem be that EmailaddressAlias is inheriting from EmailAddress and not from Base.\nI'm not an expert on this, nor have I done this through the mapper_args, but I find using relationship() to set up the foreign keys works quite well. For example:\nfrom sqlalchemy.orm import relations...
[ 2 ]
[]
[]
[ "inheritance", "python", "sqlalchemy" ]
stackoverflow_0008389606_inheritance_python_sqlalchemy.txt