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:
Pyramid sending mail: pyramid_mailer or marrow.mail
I'm interested in adding outgoing email support to a Pyramid-based web-app. I'm aware of pyramid_mailer and marrow.mail (formerly known as TurboMail), with pyramid-integration example here.
There is a similar SO question, but it doesn't quite give me the experien... | Pyramid sending mail: pyramid_mailer or marrow.mail | I'm interested in adding outgoing email support to a Pyramid-based web-app. I'm aware of pyramid_mailer and marrow.mail (formerly known as TurboMail), with pyramid-integration example here.
There is a similar SO question, but it doesn't quite give me the experienced opinion I am looking for.
I have no experience with e... | [
"The experienced answer is that if you just want to send email through a SMTP server, pyramid_mailer is way easier to configure and execute. The Message class is from Lamson, which is tried and true, stable, tested and supports whatever you might want to send in an email including attachments and html. The mailer a... | [
5
] | [] | [] | [
"pyramid",
"python",
"sendmail",
"smtp"
] | stackoverflow_0006630645_pyramid_python_sendmail_smtp.txt |
Q:
appengine base64 encoded string is different from my local machine's
This is the code:
>>> import base64
>>> id = 1
>>> key = "secret key very long"
>>> enc = base64.urlsafe_b64encode(str(id)+key)
>>> enc
'MXNlY3JldCBrZXkgdmVyeSBsb25n'
>>> base64.urlsafe_b64decode(enc)
'1secret key very long'
Works as intended on... | appengine base64 encoded string is different from my local machine's | This is the code:
>>> import base64
>>> id = 1
>>> key = "secret key very long"
>>> enc = base64.urlsafe_b64encode(str(id)+key)
>>> enc
'MXNlY3JldCBrZXkgdmVyeSBsb25n'
>>> base64.urlsafe_b64decode(enc)
'1secret key very long'
Works as intended on my machine, but when I upload this code to google appengine, both encoded... | [
"I can't explain why per se, but decoding the string you got from appengine shows it prepended an '=' to your key; and appended, rather than prepended, the ID.\n>>> key='r-$b*8hglm+858&9t043hlm6-&6-3d3vfc4((7yd0dbrakhvi'\n>>> base64.urlsafe_b64decode('PXItJGIqOGhnbG0rODU4Jjl0MDQzaGxtNi0mNi0zZDN2ZmM0KCg3eWQwZGJyYWto... | [
1
] | [] | [] | [
"base64",
"decoding",
"encoding",
"google_app_engine",
"python"
] | stackoverflow_0006632197_base64_decoding_encoding_google_app_engine_python.txt |
Q:
Is fstat() a safe (sandboxed) operation?
I'm currently writing a Python sandbox using sandboxed PyPy. Basically, the sandbox works by providing a "controller" that maps system library calls to a specified function instead. After following the instructions found at codespeak (which walk through the set up process),... | Is fstat() a safe (sandboxed) operation? | I'm currently writing a Python sandbox using sandboxed PyPy. Basically, the sandbox works by providing a "controller" that maps system library calls to a specified function instead. After following the instructions found at codespeak (which walk through the set up process), I realized that the default controller does n... | [
"The fstat call can reveal certain information which you may or may not want to keep secret. Among other things:\n\nWhether two file descriptors are on the same filesystem\nThe block size of the underlying filesystem\nNumeric UID/GIDs of file owners\nModification/access times of files\n\nHowever, it will not modify... | [
4,
3
] | [] | [] | [
"pypy",
"python",
"sandbox",
"stat"
] | stackoverflow_0006576194_pypy_python_sandbox_stat.txt |
Q:
Getting the attribute holder of an attribute
Is a reference exists from an attribute to the attribute holder?
Here is an example what I mean:
class classA(object):
def __init__(self):
pass
class classB(object):
def __init__(self):
self.a=classA()
def methodB(self):
print "Clas... | Getting the attribute holder of an attribute | Is a reference exists from an attribute to the attribute holder?
Here is an example what I mean:
class classA(object):
def __init__(self):
pass
class classB(object):
def __init__(self):
self.a=classA()
def methodB(self):
print "ClassB-s methodB called"
b=classB()
a=b.a
Is it poss... | [
"No, not really.\nWhen you initialize b.a, it becomes a reference to a classA object:\n>>> b.a\n<__main__.classA object at 0x7feeb904df10>\n\nTo call the method, you could pass the parent object to classA:\n>>> class classA(object):\n... def __init__(self, parent):\n... self.parent = parent\n... \n... ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006632821_python.txt |
Q:
Mocking objects in Python
I'm new to Unit testing and mocking objects in Python. I have a function that I need to create a unit test for.
def BuildBall(self, material):
"""Create a Ball from material."""
result = {}
for b in xrange(material.ball_size()):
ball = material.ball(b)
result[ball.name()] = ... | Mocking objects in Python | I'm new to Unit testing and mocking objects in Python. I have a function that I need to create a unit test for.
def BuildBall(self, material):
"""Create a Ball from material."""
result = {}
for b in xrange(material.ball_size()):
ball = material.ball(b)
result[ball.name()] = (ball.name(), ball.description(... | [
"Take a look at the Python Mocker package: \nIt allows you to easily generate objects that mock a certain functionality for testing. You can find a simple example here.\n"
] | [
2
] | [] | [] | [
"mocking",
"mox",
"python",
"unit_testing"
] | stackoverflow_0006631974_mocking_mox_python_unit_testing.txt |
Q:
how to access SQLite with django
I'm running python 2.6 on windows and currently going over the django tutorial. In the book, it says that SQLite comes shipped with Python 2.5 and above. So if I'm running python 2.6, there's nothing additional I have to download? And how exactly do I access SQLite? Do I access... | how to access SQLite with django | I'm running python 2.6 on windows and currently going over the django tutorial. In the book, it says that SQLite comes shipped with Python 2.5 and above. So if I'm running python 2.6, there's nothing additional I have to download? And how exactly do I access SQLite? Do I access it in its own command line or gui pro... | [
"You are correct: no additional download required.\nThis is all you need (from Windows command prompt or \"cmd\"):\nC:\\> python\n>>> import sqlite3\n>>> conn = sqlite3.connect('c:/path/to/your.db')\n>>> conn.close() # optional\n\nAfter executing the above commands you will have an SQLite file at c:/path/to/ called... | [
7
] | [] | [] | [
"django",
"python",
"sql",
"sqlite"
] | stackoverflow_0006632955_django_python_sql_sqlite.txt |
Q:
try...except...else v nested try...except
Why is else clause needed for try statement in python ?
Taking it forward:
try:
f = open('foo', 'r')
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
else:
data = f.read()
f.close()
It occurs to me that the corner case solved by else clause... | try...except...else v nested try...except | Why is else clause needed for try statement in python ?
Taking it forward:
try:
f = open('foo', 'r')
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
else:
data = f.read()
f.close()
It occurs to me that the corner case solved by else clause still can be avoided by a nested try...except ... | [
"try..except..else may not be needed, but it can be nice. In this case, the try..except..else form is distinctly nicer, in my opinion.\nJust because you can do without an element of syntax, doesn't make it useless. Decorator syntax is purely syntax sugar (the most obvious example, I think), for loops are just glori... | [
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0006632954_python.txt |
Q:
Putting a text entry as a pygtk menu item
I am trying to extend a unity appindicator for project hamster. What I want to do is have a text entry directly in the indicator menu. I have seen this for example in the ubuntu memenu, but I cannot figure out how to get it to work with pygtk. I have searched for a while a... | Putting a text entry as a pygtk menu item | I am trying to extend a unity appindicator for project hamster. What I want to do is have a text entry directly in the indicator menu. I have seen this for example in the ubuntu memenu, but I cannot figure out how to get it to work with pygtk. I have searched for a while and found nothing. Does anyone know how to do th... | [
"I'm pretty sure there is no way to add that in a menu in PyGTK, but you might try a borderless window popup.\n"
] | [
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0006315007_gtk_pygtk_python.txt |
Q:
Changing Directory Names in Python
I'm trying to change how my directories and files within them are all labelled. Currently the system is "082411-SomeNameHere" (mmddyy-Title) and I'd like to change it to "110824-SomeNameHere".
I know the moving of the numbers is fairly simple, but I'm mostly unsure on how to acc... | Changing Directory Names in Python | I'm trying to change how my directories and files within them are all labelled. Currently the system is "082411-SomeNameHere" (mmddyy-Title) and I'd like to change it to "110824-SomeNameHere".
I know the moving of the numbers is fairly simple, but I'm mostly unsure on how to access the names in the directories and cha... | [
"Try this:\nimport os, re, shutil\n\nr = re.compile(r'^([0-9]{2})([0-9]{2})([0-9]{2})-(.*)$')\n\nfor root, dirs, files in os.walk('/path/to/topdir'):\n for filename in files:\n match = r.match(filename)\n if match:\n newfilename = match.group(3) + match.group(1) + match.group(2) + '-' + ... | [
1,
0
] | [] | [] | [
"date",
"directory",
"python"
] | stackoverflow_0006633049_date_directory_python.txt |
Q:
Parsing out data in an XML file using Python
I have an xml file where I need to strip out xml tags where if possible I can use a wild card because the data within the tags will be different information. See xml below:
<relationship relation="1">
<sourcedid>
<source>xxxxx</source>
<... | Parsing out data in an XML file using Python | I have an xml file where I need to strip out xml tags where if possible I can use a wild card because the data within the tags will be different information. See xml below:
<relationship relation="1">
<sourcedid>
<source>xxxxx</source>
<id>AbDT-1398</id> ***this data will be different ... | [
"If I got you right, you want to remove certain tags (and eventually their contents) from your xml file. Try using lxml for processing the lxml file. Have a look at these functions from lxml.etree.\n\nstrip_elements():\n\n\nDelete all elements with the provided\n tag names from a tree or subtree. This\n will remo... | [
2
] | [] | [] | [
"python",
"xml",
"xml_parsing"
] | stackoverflow_0006632867_python_xml_xml_parsing.txt |
Q:
Python 2.5 (PyPy) compatible web server / framework
I'm looking for a simple Python framework/library for creating a website run using PyPy.
So far, I'm using web.py, so that's the feature set (a bit a templating, sessions, input processing, that's it) I need for this project. Very minimalist, if possible.
web.py ... | Python 2.5 (PyPy) compatible web server / framework | I'm looking for a simple Python framework/library for creating a website run using PyPy.
So far, I'm using web.py, so that's the feature set (a bit a templating, sessions, input processing, that's it) I need for this project. Very minimalist, if possible.
web.py is not unfortunately not compatible with Python 2.5 (at l... | [
"I've been using flask with success on PyPy.\n",
"According to this page, Django can be run on PyPy.\n",
"Pylons is a good web python framework and compatible with Python 2.5.\nRunning Pylons on top of PyPy\n",
"I was researching this today, and the best web server I've found that runs on pypy is gunicorn. Pe... | [
7,
2,
2,
1
] | [] | [] | [
"pypy",
"python",
"python_2.5"
] | stackoverflow_0004087833_pypy_python_python_2.5.txt |
Q:
How to add django modules to pydiction dictionary?
I'm trying to use pydiction to autocomplete Python/Django statements in VIM Editor.
When I try to add django modules to complete-dic using this:
python pydiction.py /usr/lib/pymodules/python2.6/django
or:
python pydiction.py /usr/lib/pymodules/python2.6/django/__... | How to add django modules to pydiction dictionary? | I'm trying to use pydiction to autocomplete Python/Django statements in VIM Editor.
When I try to add django modules to complete-dic using this:
python pydiction.py /usr/lib/pymodules/python2.6/django
or:
python pydiction.py /usr/lib/pymodules/python2.6/django/__init__.py
I receive this error:
Couldn't import: (...).... | [
"It is quite some time since this question was raised. I faced similar problem. Following steps explain how to do it somewhat quickly.\nSince pydiction.py doesn't parse packages recursively, I had to use find and vi to build a package list for Django. Suppose you have installed django in /usr/local/lib/python2.6/di... | [
6,
1,
0
] | [] | [] | [
"django",
"python",
"vim"
] | stackoverflow_0002081345_django_python_vim.txt |
Q:
How to determine that pythons urllib2 has queried content through a given proxy?
I figured out how to use a proxy with urllib2:
encoded_params = urllib.urlencode(params)
url = "http://someurl.com"
header = {"User-Agent" : "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"}
proxy = urllib2.ProxyHan... | How to determine that pythons urllib2 has queried content through a given proxy? | I figured out how to use a proxy with urllib2:
encoded_params = urllib.urlencode(params)
url = "http://someurl.com"
header = {"User-Agent" : "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"}
proxy = urllib2.ProxyHandler({'http': '193.33.125.217:8080'})
opener = urllib2.build_opener(proxy)
urllib2.ins... | [
"You are doing everything correctly as far as I can tell. One way to test would be to run a simple web server and connect to it from your proxy. Making a simple test web server is easy:\nfrom wsgiref.simple_server import demo_app\nfrom wsgiref.simple_server import make_server\n\nhttpd = make_server('0.0.0.0', 8000,... | [
1
] | [] | [] | [
"metadata",
"proxy",
"python",
"urllib2"
] | stackoverflow_0006633506_metadata_proxy_python_urllib2.txt |
Q:
keeping the continued code that will NOT fail still in try...except?
Dive into Python -
This is a small snippet from fileinfo.py used in the book. This is opening an MP3 file and reading the last 128 bytes to fetch and later parse the metadata.
try:
fsock = open(filename, "rb", 0)... | keeping the continued code that will NOT fail still in try...except? | Dive into Python -
This is a small snippet from fileinfo.py used in the book. This is opening an MP3 file and reading the last 128 bytes to fetch and later parse the metadata.
try:
fsock = open(filename, "rb", 0)
try:
fsock.seek(-128, 2)
t... | [
"The most accepted standard is to put as little code in the try..except as possible. Reasoning is that you don't know what the other code will raise if there's a ton of code in a try.. then it becomes really messy.\nYou can see lots of good styling information in PEP 8, amongst which is:\n- Additionally, for all tr... | [
6,
6,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006633773_python.txt |
Q:
pyqt4 reference for python?
Most of the reference site i visited are for C/C++. Is there a reference site of pyqt4 for python? Like https://doc.qt.io/qt-4.8/classes.html.
A:
Absolutely! I use the classes page in their reference guide. Happy coding! :)
A:
I feel comfortable using the help() function through the... | pyqt4 reference for python? | Most of the reference site i visited are for C/C++. Is there a reference site of pyqt4 for python? Like https://doc.qt.io/qt-4.8/classes.html.
| [
"Absolutely! I use the classes page in their reference guide. Happy coding! :)\n",
"I feel comfortable using the help() function through the Python interactive interpreter.\n$python\n\n\n\nfrom PyQt4 import QtGui\nhelp(QtGui)\nhelp(QtGui.QTextEdit)\n\n\n\n"
] | [
6,
4
] | [] | [] | [
"pyqt4",
"python",
"reference"
] | stackoverflow_0006633731_pyqt4_python_reference.txt |
Q:
emacs python code completion
Possible Duplicate:
Emacs - tab-completion of local Python variables
Ok I am getting very confused about this.
What I want is code completion for:
The current file (even all open buffers)
Any module that is imported in the current file
Standard libraries
(yes I have been spoiled by... | emacs python code completion |
Possible Duplicate:
Emacs - tab-completion of local Python variables
Ok I am getting very confused about this.
What I want is code completion for:
The current file (even all open buffers)
Any module that is imported in the current file
Standard libraries
(yes I have been spoiled by intelli-sense)
What do I need to... | [
"Update: I strictly use melpa package manager now, I install auto-complete from there. It is easier. I do not use this method below anymore.\n\nI use autocomplete (docs, installation instruction)\nYou can install it via make (I used this), or by executing install.el, or manual installation (byte compiling)\nYou'll ... | [
4
] | [] | [] | [
"autocomplete",
"code_completion",
"emacs",
"python"
] | stackoverflow_0006631984_autocomplete_code_completion_emacs_python.txt |
Q:
Database Ordering in Python
I have a database which looks a bit like this:
# user1, user2, action, days since 01/03/2010, week number, age1, age2, gen1, gen2
['1181206', '3560076', '2', 0, 0, '46', '45', 'M', 'F']
['1291903', '3675534', '2', 0, 0, '32', '30', 'M', 'F']
['3723809', '3686568', '1', 7, 1, '29', '26',... | Database Ordering in Python | I have a database which looks a bit like this:
# user1, user2, action, days since 01/03/2010, week number, age1, age2, gen1, gen2
['1181206', '3560076', '2', 0, 0, '46', '45', 'M', 'F']
['1291903', '3675534', '2', 0, 0, '32', '30', 'M', 'F']
['3723809', '3686568', '1', 7, 1, '29', '26', 'M', 'F']
['3440145', '3258134',... | [
"A rather naïve approach : your 'Users\" structure could be a dictionnary ( http://docs.python.org/tutorial/datastructures.html#dictionaries ) of user activity, where the key could be a username, and the value in the dictionnary would be structure with the oldest and latest activity. \nThen, you browse the list of ... | [
1,
1
] | [] | [] | [
"database",
"python"
] | stackoverflow_0006633616_database_python.txt |
Q:
Position tkinter Window at Screenborder
I want to position a window at the right border of the screen. This is the current code, the constants should be comprehensible I think.
root = Tk()
pos_x = root.winfo_screenwidth() - WINDOW_WIDTH
geometry = '{width}x{height}+{pos_x}+{pos_y}'.format(
height=WINDOW_HEIGHT... | Position tkinter Window at Screenborder | I want to position a window at the right border of the screen. This is the current code, the constants should be comprehensible I think.
root = Tk()
pos_x = root.winfo_screenwidth() - WINDOW_WIDTH
geometry = '{width}x{height}+{pos_x}+{pos_y}'.format(
height=WINDOW_HEIGHT, width=WINDOW_WIDTH, pos_y=HEIGHT_OFFSET, po... | [
"The problem is that the window manager draws the border and does not tell you how large it is. \nYou can take full control of the window by setting the overrideredirect flag, but that would mean you do not get a border drawn by the window manager.\nBut maybe this discussion on the Tcl'ers wiki helps, as it discuss... | [
1
] | [] | [] | [
"python",
"tk_toolkit",
"tkinter"
] | stackoverflow_0006626938_python_tk_toolkit_tkinter.txt |
Q:
How can I build py2exe without errors?
I'm not a windows user typically, but I need to build exe's from my python code so I'd like to use py2exe to do this. I have an XP system where I installed python 2.6.6. I downloaded the py2exe-0.6.9 source, but when I attempted to install (via "python setup.py install"), I g... | How can I build py2exe without errors? | I'm not a windows user typically, but I need to build exe's from my python code so I'd like to use py2exe to do this. I have an XP system where I installed python 2.6.6. I downloaded the py2exe-0.6.9 source, but when I attempted to install (via "python setup.py install"), I got the error "Unable to find vcvarsall.bat".... | [
"http://bugs.python.org/issue1485576 might be a bug you may want to re-open, providing your testcase to support it.\n"
] | [
0
] | [] | [] | [
"py2exe",
"python",
"windows"
] | stackoverflow_0005989364_py2exe_python_windows.txt |
Q:
How can i enter some data after some regular interval in Django Model
I have Model
class Account:
and other model called
class Transactions:
Now i have field interest_rate in Account Model.
I want to pay the interest on 3 month basis from the opening date of account. So
i want the automatic transaction of the req... | How can i enter some data after some regular interval in Django Model | I have Model
class Account:
and other model called
class Transactions:
Now i have field interest_rate in Account Model.
I want to pay the interest on 3 month basis from the opening date of account. So
i want the automatic transaction of the required amount applied to the account after every 3 months or depending upon ... | [
"You could use cron or celery for starters.\nRun a crontab every 3 months: https://serverfault.com/questions/129633/how-to-run-cron-job-every-3-months-in-apache2\n",
"A regular job would definitely work, but I don't think doing it every three months is the right approach. Instead, do it every day and query to fin... | [
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0006629388_django_django_models_python.txt |
Q:
Terminal says "Syntax Error" when I try to open a file (Python)
As a short background, I am just starting to learn Python and am familiarizing myself with the whole environment.
Now, I have 3 things open (Windows Vista): Command Prompt, IDLE (Python GUI), and gedit.
On the IDLE, I started typing print commands lik... | Terminal says "Syntax Error" when I try to open a file (Python) | As a short background, I am just starting to learn Python and am familiarizing myself with the whole environment.
Now, I have 3 things open (Windows Vista): Command Prompt, IDLE (Python GUI), and gedit.
On the IDLE, I started typing print commands like so:
>>> print "Print this."
Print this.
>>> run thisfile.py
SyntaxE... | [
"You can't run another script like that.\nYou need to import it, and then you can call functions and use types in it, like this:\nimport thisfile\n\nThis will import the contents of thisfile into the interpreter, then you can call functions:\nthisfile.thatfunction\n\nIf you want \"thatfunction\" to be available wit... | [
2,
2,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0006634339_python_syntax.txt |
Q:
How do I find out whether a Python module is run on GAE?
I have a module that uses lxml. Since this cannot be imported on GAE, I'd like to use a suitable substitute by default. Something along the lines of:
if not ON_GAE:
import lxml
else:
import beautifulsoup
How can I determine that I'm on GAE? Is there... | How do I find out whether a Python module is run on GAE? | I have a module that uses lxml. Since this cannot be imported on GAE, I'd like to use a suitable substitute by default. Something along the lines of:
if not ON_GAE:
import lxml
else:
import beautifulsoup
How can I determine that I'm on GAE? Is there a OS variable of some sorts?
Update: There are certain module... | [
"You can use this:\non_app_engine = os.environ.get('SERVER_SOFTWARE', '').startswith('Google')\nThen something like:\nif on_app_engine:\n import lxml\nelse:\n import bla\n\n",
"You can simply try and see if an import throws an exception and use the other import only if it's necessary.\ntry:\n import lxml\nex... | [
4,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006633463_google_app_engine_python.txt |
Q:
use .pyc files via Jython
I am working on building a web interface for a Python tool. It's being designed using J2EE (Spring).
In the process, I need to make calls to Python functions and hence I am using Jython for the same.
But for some modules I don't have the Python source files, I only have the .pyc files, an... | use .pyc files via Jython | I am working on building a web interface for a Python tool. It's being designed using J2EE (Spring).
In the process, I need to make calls to Python functions and hence I am using Jython for the same.
But for some modules I don't have the Python source files, I only have the .pyc files, and a document listing the method... | [
"The 'compiled' python code '.pyc' files are implementation-specific. Even CPython (the standard Python implementation) is not able to import .pyc files generated by a different version of CPython. And is not supposed to. So, I would be surprised if Jython had an ability to run .pyc files created by any of CPython ... | [
3,
2
] | [] | [] | [
"java",
"jython",
"pyc",
"python"
] | stackoverflow_0006607858_java_jython_pyc_python.txt |
Q:
python passing parameter to a function
I am not clear about the concept of passing lists as arguments to functions in python.
I've tried researching on this myself , didn't find adequate resources.
I want to implement a helper function which returns a number of random items from a given list. (in django queryset... | python passing parameter to a function | I am not clear about the concept of passing lists as arguments to functions in python.
I've tried researching on this myself , didn't find adequate resources.
I want to implement a helper function which returns a number of random items from a given list. (in django queryset)
However, the list may contain multiple row... | [
"In Python, there are names and values. An assignment statement makes a name refer to a value. An assignment never makes a copy, and assignment never changes a value. It only changes what value a name refers to. Passing an argument to a function is like an assignment: now the local name of the argument in the ... | [
6,
3,
3,
2
] | [] | [] | [
"parameter_passing",
"python"
] | stackoverflow_0006630521_parameter_passing_python.txt |
Q:
How do i get variables/functions of another class in BaseHTTP class "WebServer"
renegade.py (main before)
import socket, re
from prerequisites import *
import datetime,random,sys,time,os,pickle,urllib
from threading import *
class Renegade():
def __init__(self, settings, main, db):
self.settings = set... | How do i get variables/functions of another class in BaseHTTP class "WebServer" | renegade.py (main before)
import socket, re
from prerequisites import *
import datetime,random,sys,time,os,pickle,urllib
from threading import *
class Renegade():
def __init__(self, settings, main, db):
self.settings = settings
self.main = main
self.fds = fds(self.settings, self.main, self)... | [
"Inside webserver.py:\nfrom main import Main\nMain.SomeFunction()\n\nYou need the import so that webserver knows about main's classes.\n\nWith regards to your latest problem, you can do either\nBaseHTTPRequestHandler.__init__(self)\n\nor else replace class WebBrowser(BaseHTTPRequestHandler): with\nclass WebBrowser(... | [
0
] | [] | [] | [
"basehttpserver",
"python"
] | stackoverflow_0006634720_basehttpserver_python.txt |
Q:
Choose Python function to call based on a regex
Is it possible to put a function in a data structure, without first giving it a name with def?
# This is the behaviour I want. Prints "hi".
def myprint(msg):
print msg
f_list = [ myprint ]
f_list[0]('hi')
# The word "myprint" is never used again. Why litter the n... | Choose Python function to call based on a regex | Is it possible to put a function in a data structure, without first giving it a name with def?
# This is the behaviour I want. Prints "hi".
def myprint(msg):
print msg
f_list = [ myprint ]
f_list[0]('hi')
# The word "myprint" is never used again. Why litter the namespace with it?
The body of a lambda function is s... | [
"This is based on Udi's nice answer.\nI think that the difficulty of creating anonymous functions is a bit of a red herring. What you really want to do is to keep related code together, and make the code neat. So I think decorators may work for you.\nimport re\n\n# List of pairs (regexp, handler)\nhandlers = []\n\n... | [
39,
16,
14,
13,
9,
6,
5,
3,
3,
3,
2,
2,
1
] | [
"If your function is complicated enough to not fit in a lambda function, then, for readability's sake, it would probably be best to define it in a normal block anyway.\n"
] | [
-1
] | [
"anonymous_function",
"lambda",
"python"
] | stackoverflow_0006629876_anonymous_function_lambda_python.txt |
Q:
Simple Python code taking strangely long to run, incorrectly reported by Hotshot
I'm trying to optimize some code using hotshot, which I expected to be great since it's the high-performance profiler and all. But for some reason, I'm getting wildly inaccurate results from it. On my most recent profiling run, hotsho... | Simple Python code taking strangely long to run, incorrectly reported by Hotshot | I'm trying to optimize some code using hotshot, which I expected to be great since it's the high-performance profiler and all. But for some reason, I'm getting wildly inaccurate results from it. On my most recent profiling run, hotshot reported the cumulative time of the top-level function I called as 7.946 seconds. Bu... | [
"If you are using Python 2.5+, try switching to cProfile. It appears that hotshot is no longer supported. \n",
"You want to find out where all the time is going, right?\nDon't think of it as measuring time.\nThink of it as finding lines of code that are on the stack a large fraction of the time, regardless of the... | [
2,
0
] | [] | [] | [
"optimization",
"profiling",
"python"
] | stackoverflow_0006630652_optimization_profiling_python.txt |
Q:
Rm duplication in list comprehension
Input is a string, the idea is to count the letters A-z only, and print them alphabetically with the count of appearances.
As usual I kept at this 'till I got a working result, but now seek to optimize it in order to better understand the Python way of doing things.
def strin... | Rm duplication in list comprehension | Input is a string, the idea is to count the letters A-z only, and print them alphabetically with the count of appearances.
As usual I kept at this 'till I got a working result, but now seek to optimize it in order to better understand the Python way of doing things.
def string_lower_as_list(string):
"""
>>>... | [
"You can compare letters directly and you actually only need to compare lower case letters\nletters = [letter for letter in string_lower_as_list(argv[1]) \n if \"a\" <= letter <= \"z\"]\n\nBut better would be to use a dictionary to count the values. letters.count has to traverse the list every time you c... | [
2,
2,
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0006634995_list_comprehension_python.txt |
Q:
Django: Caught NoReverseMatch while rendering: Reverse for '*' with arguments '()' and keyword arguments '{}' not found
Error:
Caught NoReverseMatch while rendering: Reverse for 'archive' with arguments '()' and keyword arguments '{}' not found.
Template error
In template /home/bravedick/Aptana Studio 3 Workspac... | Django: Caught NoReverseMatch while rendering: Reverse for '*' with arguments '()' and keyword arguments '{}' not found | Error:
Caught NoReverseMatch while rendering: Reverse for 'archive' with arguments '()' and keyword arguments '{}' not found.
Template error
In template /home/bravedick/Aptana Studio 3 Workspace/blog/templates/homepage/index.html, error at line 7
line 7:
6 <a href="{% url index %}">Index</a>
7 <a href="{% url ar... | [
"I can see one immediate problem with your main url configuration. You have a '$' symbol, signifying end of the url in your include statement. \nThat line should read:\n(r'^', include('blog.apps.homepage.urls')),\n\nHere's the documentation for include. \nAlso check that blog.apps.homepage.urls is a valid import pa... | [
9
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006635051_django_python.txt |
Q:
Chatbot Conversation Objects, your approach?
I'm relatively new to programming and a recent project I've started to work on is a chatbot in python for an irc channel I frequent.
One of my goals is to have the bot able to very basically keep track of conversations it is having with users.
I presently an using conve... | Chatbot Conversation Objects, your approach? | I'm relatively new to programming and a recent project I've started to work on is a chatbot in python for an irc channel I frequent.
One of my goals is to have the bot able to very basically keep track of conversations it is having with users.
I presently an using conversation objects. When a user addresses the bot, it... | [
"having clear goals is important in programming even before you set out deciding what objects and how. Unfortunately from what I've read above this isn't really clear.\nSo first forget the how of the program. forget about the objects, the code and what they do.\nNow Imagine someone else was going to write for you t... | [
1
] | [] | [] | [
"artificial_intelligence",
"chatbot",
"python"
] | stackoverflow_0006635245_artificial_intelligence_chatbot_python.txt |
Q:
Match html tags in python
I'm writing a python snippet to fix the casing of titles in HTML code. So far, I've come up with this code:
pattern = re.compile("<h1>(.*)</h1>|<h2>(.*)</h2>|<h3>(.*)</h3>|<h4>(.*)</h4>|<h5>(.*)</h5>|<h6>(.*)</h6>")
def replace(m):
contents = m.group(1)
replacement = contents[0] ... | Match html tags in python | I'm writing a python snippet to fix the casing of titles in HTML code. So far, I've come up with this code:
pattern = re.compile("<h1>(.*)</h1>|<h2>(.*)</h2>|<h3>(.*)</h3>|<h4>(.*)</h4>|<h5>(.*)</h5>|<h6>(.*)</h6>")
def replace(m):
contents = m.group(1)
replacement = contents[0] + contents[1:].lower()
retu... | [
"From what I understand you just want to capitalize all of the headings. You can use lxml which would make this fairly painless:\nimport lxml.html\n\ndoc = lxml.html.parse(your_html)\nfor i in range(1,7):\n for h in doc.xpath('//h%d' % i):\n h.text = h.text.capitalize()\n\nprint lxml.html.tostring(doc)\n\... | [
5,
1,
1,
0
] | [] | [] | [
"python",
"regex",
"xml",
"xpath"
] | stackoverflow_0006633491_python_regex_xml_xpath.txt |
Q:
python threading and tkinter.tix.NoteBook tabs not accessible beyond first open tab
In the following example I'm unable to write to the other tabs aside from the open-by-default Log tab:
#!/usr/bin/python
import os, sys
import threading
import time
from itertools import count
import tkinter
from tkinter import *
... | python threading and tkinter.tix.NoteBook tabs not accessible beyond first open tab | In the following example I'm unable to write to the other tabs aside from the open-by-default Log tab:
#!/usr/bin/python
import os, sys
import threading
import time
from itertools import count
import tkinter
from tkinter import *
from tkinter import tix
import tkinter.tix
from tkinter.constants import *
import traceba... | [
"For one, Tkinter is not thread safe. You can't access the tk widgets from more than one thread. Doing so yields unpredictable behavior (though one can usually predict that it will cause crashes). \nAs for the other question -- how to declare gui.SettingsFrame in advance -- I'm not sure how to answer it without sta... | [
0
] | [] | [] | [
"multithreading",
"python",
"python_multithreading",
"tix",
"tkinter"
] | stackoverflow_0006635251_multithreading_python_python_multithreading_tix_tkinter.txt |
Q:
Python Curses: Returning to the Previous Menu
I have a menu system in ncurses.
Choosing one of the options takes you to another menu. But how do I get back?
import curses
def Main():
x = 0
while x!= ord('2'):
x = screen.getch()
screen.clear();screen.border();
screen.addstr(1,1, "Please... | Python Curses: Returning to the Previous Menu | I have a menu system in ncurses.
Choosing one of the options takes you to another menu. But how do I get back?
import curses
def Main():
x = 0
while x!= ord('2'):
x = screen.getch()
screen.clear();screen.border();
screen.addstr(1,1, "Please choose:")
screen.addstr(3,1, "1 - Another M... | [
"Add x = 0 after the second while loop ends.\n(You need to reset x every time around the loop, not just the first. Otherwise exiting from the first menu will x set to \"exit\", so will also exit the second menu.)\n"
] | [
1
] | [] | [] | [
"curses",
"menu",
"python"
] | stackoverflow_0006635633_curses_menu_python.txt |
Q:
ImportError: No module named NetCDF
I am trying to sort the following error but not getting the correct answer till now. Actually I am using Ubuntu 10.04 and I have installed netcdf-3.6.2 but even then i found this error, although I added the header like
import Scientific.IO.NetCDF
from Numeric import *
from Net... | ImportError: No module named NetCDF | I am trying to sort the following error but not getting the correct answer till now. Actually I am using Ubuntu 10.04 and I have installed netcdf-3.6.2 but even then i found this error, although I added the header like
import Scientific.IO.NetCDF
from Numeric import *
from NetCDF import *
But it does not make any im... | [
"If the module is Scientific.IO.NetCDF, then you need to do from Scientific.IO.NetCDF import * (and you don't need to do import Scientific.IO.NetCDF first). Also, importing everything is often a bad style, and should be avoided.\n"
] | [
0
] | [] | [] | [
"c++",
"netcdf",
"python"
] | stackoverflow_0006634770_c++_netcdf_python.txt |
Q:
Common neighbors and preferential attachment score matrixes using igraph for python
Is there an efficient way to calculate the matrix score for common neighbors(CC) and preferential attachment(PA) in python? I'm using igraph to calculate score matrixes for other methods such as jaccard's coefficient (Graph.similar... | Common neighbors and preferential attachment score matrixes using igraph for python | Is there an efficient way to calculate the matrix score for common neighbors(CC) and preferential attachment(PA) in python? I'm using igraph to calculate score matrixes for other methods such as jaccard's coefficient (Graph.similarity_jaccard()), dice (Graph.similarity_dice) and adamic/adar (Graph.similarity_inverse_lo... | [
"There is no direct function for this in igraph. However, note that len(g.neighbors(i)) is simply the degree of vertex i, so you can call g.degree(), treat it as a 1D matrix using NumPy, then multiply it with its own transpose s.t. a column vector is multiplied by a row vector from the right. This gives you the pre... | [
2
] | [] | [] | [
"igraph",
"python",
"social_networking"
] | stackoverflow_0006632445_igraph_python_social_networking.txt |
Q:
How do I change position elements in a queryset?
I got:
model_list = Models.objects.filter(date_of_addition__gte=today).order_by('name')
How do I change position elements in view, for example put 5th (model_list.id=5) element to the top of the list?
template:
{% for m in model_list %}
<li>{{m.name}}</li>
{% endfo... | How do I change position elements in a queryset? | I got:
model_list = Models.objects.filter(date_of_addition__gte=today).order_by('name')
How do I change position elements in view, for example put 5th (model_list.id=5) element to the top of the list?
template:
{% for m in model_list %}
<li>{{m.name}}</li>
{% endfor %}
And get:
Toyota
Audi
BWM
Chevrolet
Honda
VW
ins... | [
"For your example:\nfor m in [model_list[4]] + model_list[0:4] + model_list[5:]\n\n",
"Use del to remove an item. Use insert to place an item wherever you wish:\n>>> lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g']\n>>> item5 = lst[5]\n>>> del(lst[5])\n>>> lst\n['a', 'b', 'c', 'd', 'e', 'g']\n>>> lst.insert(0, item5)\n>... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006635515_django_python.txt |
Q:
Problem when using python xoltar toolkit, error raised when employ closure
Recently I've been reading some materials about functional programming in Python, one of them is here: http://www.ibm.com/developerworks/linux/library/l-prog2/index.html
I type the code:
from functional import *
taxdue = lambda: (in... | Problem when using python xoltar toolkit, error raised when employ closure | Recently I've been reading some materials about functional programming in Python, one of them is here: http://www.ibm.com/developerworks/linux/library/l-prog2/index.html
I type the code:
from functional import *
taxdue = lambda: (income-deduct)*rate
incomeClosure = lambda income,taxdue: closure(taxdue)
deductCl... | [
"The problem is that the variables income, deduct and rate aren't defined anywhere when you do lambda: (income-deduct)*rate.\nMaybe you intended to make them parameters to the lambda?\n"
] | [
0
] | [] | [] | [
"closures",
"functional_programming",
"python"
] | stackoverflow_0006635081_closures_functional_programming_python.txt |
Q:
Python / TG2 - Sprox
I am looking into using sprox but I can't seem to find any information about styling the generated form. I am sure its got to be something obvious but i didn't see it in the docs or find anything using a google/google groups search.
Ideally i would use sprox to generate the form but be able t... | Python / TG2 - Sprox | I am looking into using sprox but I can't seem to find any information about styling the generated form. I am sure its got to be something obvious but i didn't see it in the docs or find anything using a google/google groups search.
Ideally i would use sprox to generate the form but be able to pass in some css for lay... | [
"You should be able to pass the form to the template, render it there while adding any custom css rule inside the template itself. For example using <style> tag inside the template head.\nIf you really want to add a custom CSS on python side you can try to add CSSLink/CSSSource to css key inside form __base_widget_... | [
0
] | [] | [] | [
"python",
"sprox",
"web_applications"
] | stackoverflow_0006006773_python_sprox_web_applications.txt |
Q:
Can I have scripts outside my python exe?
I'm new to Python and starting to learn it. However I have one query, which I'd like to know for the future.
Once I've made a python program and produced an exe via py2exe, is it then possible to execute python scripts outside of the exe or do I have to look at plugins?
... | Can I have scripts outside my python exe? | I'm new to Python and starting to learn it. However I have one query, which I'd like to know for the future.
Once I've made a python program and produced an exe via py2exe, is it then possible to execute python scripts outside of the exe or do I have to look at plugins?
| [
"Yes, it is entirely possible. It's a standard Python interpreter. You'll need to put the directory in sys.path so that the filesystem importer will pick it up. And then for runtime imports generally using the __import__ function will be the easiest way.\nA Google search for \"py2exe runtime import\" provides early... | [
1
] | [] | [] | [
"py2exe",
"pygtk",
"python"
] | stackoverflow_0006636110_py2exe_pygtk_python.txt |
Q:
How to let Python code continue after telnet (telnetlib) timeout
I am using Python for Automated telnet program using telnetlib. The problem is: when the device that I am trying to telnet to doesn't responsd, means timeout; the program gives me timeout message and doesn't continue to next commands.
My Code:
import... | How to let Python code continue after telnet (telnetlib) timeout | I am using Python for Automated telnet program using telnetlib. The problem is: when the device that I am trying to telnet to doesn't responsd, means timeout; the program gives me timeout message and doesn't continue to next commands.
My Code:
import telnetlib
HOST = ("x.x.x.x")
USER = ("xxxxx")
PWD = ("yyyyy") ... | [
"Wrap the operations in a try block, and handle the exception in a catch block.\n",
"Python terminates your program whenever as exception arrives. For handling exception you need to wrap it in try, catch statements.\nPut your telnet statement in try statement and catch exception using except as shown below:\nimpo... | [
3,
3,
3
] | [] | [] | [
"python",
"telnetlib",
"timeout"
] | stackoverflow_0005364730_python_telnetlib_timeout.txt |
Q:
Turbogears change user via function calls
In TG1, you could change the logged in user by doing something like:
identity.set_current_identity(identity)
Is it possible to do something similar in TG2? It seems like repoze.who should provide something similar, but I can't seem to find the magic words.
Alternatively, ... | Turbogears change user via function calls | In TG1, you could change the logged in user by doing something like:
identity.set_current_identity(identity)
Is it possible to do something similar in TG2? It seems like repoze.who should provide something similar, but I can't seem to find the magic words.
Alternatively, is their any documentation on how to use repoze... | [
"You can use the identifier to remember a new user. By default in TurboGears2 users are identified by their username, so you can switch them using the username.\ndef force_user(user_name):\n request = tg.request\n response = tg.response\n\n request.cookies.clear()\n authentication_plugins = request.envi... | [
3
] | [] | [] | [
"authentication",
"python",
"repoze.who",
"turbogears2"
] | stackoverflow_0004576486_authentication_python_repoze.who_turbogears2.txt |
Q:
Recent-ish changes to the Python execution model?
I just re-read the section on execution models in the 3rd edition of Learning Python (late 2007), and it felt fairly tentative. So, I looked at the same section in the 4th edition (late 2009) and was pretty disappointed that it was completely unchanged.
What is the... | Recent-ish changes to the Python execution model? | I just re-read the section on execution models in the 3rd edition of Learning Python (late 2007), and it felt fairly tentative. So, I looked at the same section in the 4th edition (late 2009) and was pretty disappointed that it was completely unchanged.
What is the status for executing Python beyond CPython? It feels l... | [
"The developer of Psyco, Armin Rigo, now works on PyPy along with a lot of other brilliant developers. PyPy is very actively developed and a lot of exciting stuff is planned for it in the future. PyPy compiled with JIT is almost always faster than CPython, frequently by a large margin. They have a collection of ben... | [
22
] | [] | [] | [
"execution",
"psyco",
"pypy",
"python"
] | stackoverflow_0006636127_execution_psyco_pypy_python.txt |
Q:
Parsing text file and store these values in python dictionary
I have text file as follows
ID Value 1 Value 2
1 0.8 0.08
2 0.10 0.11
3 11 12
Now the issue is i have to store these values in python dictionary and write to a file..
Can anybody help me how to do this using pytho... | Parsing text file and store these values in python dictionary | I have text file as follows
ID Value 1 Value 2
1 0.8 0.08
2 0.10 0.11
3 11 12
Now the issue is i have to store these values in python dictionary and write to a file..
Can anybody help me how to do this using python
Thanks
N
| [
"Reading the file into a dict is fairly easy:\n# use with statement to open the file\nwith open(file_name) as f:\n # skip first two lines (containing header) and split on whitespace\n # this creates a nested list like: [[val1, i1, i2], [val2, i1, i2]]\n lines = [x.split() for x in f.readlines()[2:]\n # ... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0006636453_python.txt |
Q:
Get entity's property value in different format (GAE-Python)
In google app engine
When i try to get propery value by ReferenceProperty element
It return referenced entity value in different format Like:
real stored value "Name" : "demoname"
when i get and print/write: u'demoname
is there any function or way to ge... | Get entity's property value in different format (GAE-Python) | In google app engine
When i try to get propery value by ReferenceProperty element
It return referenced entity value in different format Like:
real stored value "Name" : "demoname"
when i get and print/write: u'demoname
is there any function or way to get value in proper string format.
code:
person model has name prope... | [
"If modelobject.ref.name is a StringProperty, then it is \"returned by the datastore as a unicode value.\"\nThe u' looks like the repr() of a unicode object:\n>>> s = u\"Unicode String.\"\n>>> print s\nUnicode String.\n>>> print repr(s)\nu'Unicode String.'\n\nPerhaps sro.write() calls repr() or you're storing the r... | [
1
] | [] | [] | [
"google_app_engine",
"python",
"referenceproperty"
] | stackoverflow_0006635275_google_app_engine_python_referenceproperty.txt |
Q:
Javascript or Python? beginner getting up to speed
Which language will allow a beginner to get up to speed quicker?
Basically which language of the two is easier to learn
A:
Depends what you want to do. If you're just interested in learning a programming language, I would recommend Python because:
The interact... | Javascript or Python? beginner getting up to speed | Which language will allow a beginner to get up to speed quicker?
Basically which language of the two is easier to learn
| [
"Depends what you want to do. If you're just interested in learning a programming language, I would recommend Python because:\n\nThe interactive prompt is great for learning a language\nIt's simple and well-designed, whereas JavaScript has a number of design flaws that can be confusing to newbies\nThere is a partic... | [
10,
10,
4,
2,
1,
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0002838856_javascript_python.txt |
Q:
Problem with iFrames in Selenium
I'm trying to scrape a webpage using Selenium (in Python) that is almost entirely Javascript.
For instance, this is the body of the page:
<body class="bodyLoading">
<!-- this is required for GWT history support -->
<iframe id="__gwt_historyFrame" role="presentation" width="0" heigh... | Problem with iFrames in Selenium | I'm trying to scrape a webpage using Selenium (in Python) that is almost entirely Javascript.
For instance, this is the body of the page:
<body class="bodyLoading">
<!-- this is required for GWT history support -->
<iframe id="__gwt_historyFrame" role="presentation" width="0" height="0" tabindex="-1" title="empty" styl... | [
"The iframes are separate documents, so you won't get their contents included in the HTML code for the main page; you have to read them separately.\nYou can do this using Selenium's select_frame function.\nYou can access a frame via its name, CSS selector, xpath reference, etc, as with other elements.\nWhen you sel... | [
5
] | [] | [] | [
"iframe",
"python",
"selenium"
] | stackoverflow_0006363966_iframe_python_selenium.txt |
Q:
How do I convert a string with a different time zone to a datetime object?
I understand how to convert a string to a datetime object, but what about a string that has a different time zone? for example "10/07/2011 04:22 CEST"
A:
EST can mean two different timezones: European Summer Time, or Eastern Standard Time... | How do I convert a string with a different time zone to a datetime object? | I understand how to convert a string to a datetime object, but what about a string that has a different time zone? for example "10/07/2011 04:22 CEST"
| [
"EST can mean two different timezones: European Summer Time, or Eastern Standard Time. So datetime strings such as 08/07/2011 04:22 EST are ambiguous -- there's no sure-fire way to correctly convert such strings to a timezone-aware datetime.\nIf you are willing to just make a stab at a possibly correct answer, then... | [
4,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0006637106_datetime_python.txt |
Q:
Django: Avoiding Server-Side and Client-Side Validation Code Duplication
How do you avoid duplicating validation code on the server-side and on the client-side with Django?
Given that Django follows a Don't Repeat Yourself principle, it seems logical that there would be a way to do this, but I have no idea how.
A... | Django: Avoiding Server-Side and Client-Side Validation Code Duplication | How do you avoid duplicating validation code on the server-side and on the client-side with Django?
Given that Django follows a Don't Repeat Yourself principle, it seems logical that there would be a way to do this, but I have no idea how.
| [
"Here's an uncompleted (\"alpha grade\") project that addresses your problem: http://eikke.com/django-validation-an-introduction/ :\n\nSo I’ve been thinking since some time\n to create a Django templatetag which\n allows one to generate client-side\n Javascript form validation code\n without writing any code hi... | [
3
] | [] | [] | [
"client_side_validation",
"code_duplication",
"django",
"python",
"server_side_validation"
] | stackoverflow_0006636587_client_side_validation_code_duplication_django_python_server_side_validation.txt |
Q:
How Can i integrate c++ and Python with SWIG
Possible Duplicate:
Integrate Python And C++
I am the python GUY and do web stuff in django. I want to know that how easy or hard it is to integrate python and C++ using SWIG.
Is it efficient/easy to do or should leave C++ and code the things in python.
There are som... | How Can i integrate c++ and Python with SWIG |
Possible Duplicate:
Integrate Python And C++
I am the python GUY and do web stuff in django. I want to know that how easy or hard it is to integrate python and C++ using SWIG.
Is it efficient/easy to do or should leave C++ and code the things in python.
There are some things C++ files which have been coded already ... | [
"Using swig is easy. Usually easier than people think.\nSee http://www.swig.org/tutorial.html. \nBasically you just a have to write an interface file *.i that just includes the headers you need.\nexample.i :\n %module example\n %{\n /* Includes the header in the wrapper code */\n #include \"header.h\"\n %}\n\n... | [
6,
4,
3
] | [] | [] | [
"c++",
"django",
"linux",
"python"
] | stackoverflow_0006637012_c++_django_linux_python.txt |
Q:
Compiling numpy with external libraries for super computer
I am compiling numpy and get an error so I think I need to include external libraries. The atlas installation is in /usr/lib64/atlas. Since I don't have access to root I have everything installed in my home directory including python 2.6.7.
I am assuming I... | Compiling numpy with external libraries for super computer | I am compiling numpy and get an error so I think I need to include external libraries. The atlas installation is in /usr/lib64/atlas. Since I don't have access to root I have everything installed in my home directory including python 2.6.7.
I am assuming I change the site.cfg file but do I only need to add the /usr/lib... | [
"You can probably get this to work by setting CFLAGS and LDFLAGS before you run pip install numpy so that it uses your own personal library directory.\nCFLAGS='-l/home/me/include'\nLDFLAGS='-L/home/me/lib'\n\nIf that doesn't work, find a machine (or a VM) where you can build tools and access /usr/lib, then follow t... | [
2
] | [] | [] | [
"atlas",
"numpy",
"python"
] | stackoverflow_0006610090_atlas_numpy_python.txt |
Q:
DLL not loaded from documented search path
I have a process which is loading a DLL from a place not listed in the documented search order (docs linked below). I want to know why.
Here's the description of my setup:
I have a folder 'c:\foo' containing a.dll and b.dll.
I have a python script also stored in c:\foo.
... | DLL not loaded from documented search path | I have a process which is loading a DLL from a place not listed in the documented search order (docs linked below). I want to know why.
Here's the description of my setup:
I have a folder 'c:\foo' containing a.dll and b.dll.
I have a python script also stored in c:\foo.
The python script does a LoadLibrary('c:/foo/a.d... | [
"a.dll is probably using runtime dynamic linking as a last resort\nhttp://msdn.microsoft.com/en-us/library/ms686944%28VS.85%29.aspx\n"
] | [
0
] | [] | [] | [
"dll",
"matlab",
"process_monitor",
"python"
] | stackoverflow_0006546744_dll_matlab_process_monitor_python.txt |
Q:
How to create a save option ? to save change that is made in .txt file from python
this is my assignment:
Description: We are interested to develop a Costumer Management System for a company, which stores customers and orders information and helps system user to search, edit, and enter data. Each customer has a Cu... | How to create a save option ? to save change that is made in .txt file from python | this is my assignment:
Description: We are interested to develop a Costumer Management System for a company, which stores customers and orders information and helps system user to search, edit, and enter data. Each customer has a CustomerNumber (ID), Name, Address, and Phone which can be stored in a list such as [1, “A... | [
"Go read the Python tutorial on file I/O, it's really good. Good luck solving that assignment of yours.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006637544_python.txt |
Q:
Bit-operations on large number of bytes
Doing some exercises with simple file encryption/decryption and am currently just reading in a bunch of bytes and performing the appropriate bit-operations on each byte one at a time, then writing them to the output file.
This method seems pretty slow. For example, if I want... | Bit-operations on large number of bytes | Doing some exercises with simple file encryption/decryption and am currently just reading in a bunch of bytes and performing the appropriate bit-operations on each byte one at a time, then writing them to the output file.
This method seems pretty slow. For example, if I want to XOR every byte by 0xFF, I would loop over... | [
"Using the bitwise array operations from numpy may be what you're looking for.\n",
"No matter what, it appears that each byte would have to be \n\nread from memory,\nmodified in some fashion, and \nwritten back to memory.\n\nYou can save a bit (no pun intended) of time by operating on multiple bytes at a time, fo... | [
7,
3
] | [] | [] | [
"bitwise_operators",
"encryption",
"python"
] | stackoverflow_0006637581_bitwise_operators_encryption_python.txt |
Q:
Python: What's wrong with my xpath expression?
I have this:
<div class="down_butt_pad1" style="" id="downloadlink"><a href="http://www.link.com" class="down_butt1" onclick="javascript:window.open('http://s.spam.com','popunder','width=800,height=800,scrollbars=yes,status=no,resizable=yes, toolbar=no'); window.focus... | Python: What's wrong with my xpath expression? | I have this:
<div class="down_butt_pad1" style="" id="downloadlink"><a href="http://www.link.com" class="down_butt1" onclick="javascript:window.open('http://s.spam.com','popunder','width=800,height=800,scrollbars=yes,status=no,resizable=yes, toolbar=no'); window.focus();"></a></div>
I'm trying to do a xpath("//div[@id... | [
"You have to use a single = in XPath. What you're looking for is\n\"//div[@id='downloadlink']\"\n\nHowever, there is nothing interesting about the div. Why stop there? Perhaps you want to extract the URL:\n\"//div[@id='downloadlink']/a/@href\"\n\nI recommend using a deep dive to extract exactly what you want, rathe... | [
4,
1
] | [] | [] | [
"python",
"xpath"
] | stackoverflow_0006637782_python_xpath.txt |
Q:
Wrapping a template function with boost.python
I'm trying to expose the following c++ function to python using boost.python:
template <typename genType>
genType refract(
genType const & I,
genType const & N,
typename genType::value_type const & eta);
and what I got is this:
template... | Wrapping a template function with boost.python | I'm trying to expose the following c++ function to python using boost.python:
template <typename genType>
genType refract(
genType const & I,
genType const & N,
typename genType::value_type const & eta);
and what I got is this:
template<typename N>
N reflect(N const & i, N const & n,... | [
"This is not the perfect answer since it requires abusing the type system and writing plenty of additional glue code.\nYou could try defining a wrapper template to decorate your target type such that it would have the necessary typedefs to satisfy the calling function (reflect).\nThis example demonstrates the faili... | [
3
] | [] | [] | [
"boost",
"c++",
"python",
"templates",
"word_wrap"
] | stackoverflow_0006537553_boost_c++_python_templates_word_wrap.txt |
Q:
How to add a list into a file .txt
hi i was suppose to add a customer name to a customer.txt file
[1, “Amin Milani Fard”, “Columbia College”, 778]
[2, “Ali”, “Douiglas College”, 77238]
def addingcustomer(file_name,new_name):
f=open(file_name,'w')
for line in f:
if new_name==line:
retur... | How to add a list into a file .txt | hi i was suppose to add a customer name to a customer.txt file
[1, “Amin Milani Fard”, “Columbia College”, 778]
[2, “Ali”, “Douiglas College”, 77238]
def addingcustomer(file_name,new_name):
f=open(file_name,'w')
for line in f:
if new_name==line:
return ("already existed")
elif new_n... | [
"You probably want to close the file too, after you are done.\nf.close()\n\n",
"You are opening the file with w, meaning you ask for write only permissions. Then you try to loop through all lines in the file, which is clearly a read operation. IIRC you should open the file with r+, w+ or a+, depending on what beh... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006638229_python.txt |
Q:
Python Profile Pitfalls
I am a beginner just starting to profile my code and was confused why the elapsed time given by cProfile was so off from the time given by using time.time().
# Python 2.7.2
import cProfile
def f(n):
G = (i for i in xrange(n))
sum = 0
for i in G:
sum += i
num = 10**6
... | Python Profile Pitfalls | I am a beginner just starting to profile my code and was confused why the elapsed time given by cProfile was so off from the time given by using time.time().
# Python 2.7.2
import cProfile
def f(n):
G = (i for i in xrange(n))
sum = 0
for i in G:
sum += i
num = 10**6
cProfile.run('f(num)')
This ... | [
"The point of profiling is to find out what parts of your program are taking the most time, and thus need the most attention. If 90% of the time is being used by one function, you should be looking there to see how you can make that function more efficient. It doesn't matter whether the entire run takes 10 second... | [
3,
1
] | [] | [] | [
"benchmarking",
"profile",
"python"
] | stackoverflow_0006638313_benchmarking_profile_python.txt |
Q:
Having difficulty installing Google Python API into newer Python
I'm trying to set up the Python Google API on my system; I have both Python 2.6 and 2.7 installed; 2.7 is the version I use. Howver, the installer installs itself into my old Python (2.6) and I get library not found errors when I try to use it on 2.7... | Having difficulty installing Google Python API into newer Python | I'm trying to set up the Python Google API on my system; I have both Python 2.6 and 2.7 installed; 2.7 is the version I use. Howver, the installer installs itself into my old Python (2.6) and I get library not found errors when I try to use it on 2.7.
Has anybody had any success installing the Google API into a specif... | [
"Generally to install a package you either download it and run python setup.py install or use easy_install/pip. You can use which python to verify you are running the installer with the proper version of Python. There is a good chance you are simply installing it with 2.6, thus it never gets installed for 2.7. If y... | [
1
] | [] | [] | [
"api",
"python"
] | stackoverflow_0006638283_api_python.txt |
Q:
Using rpmbuild in Python
I'm a newbie and I'm trying to write a python script to build rpm packages as part of an automated build system (Hudson).
I'm looking at the rpm-python API but I can't seem to see anything that relates to rpmbuild.
Am I missing something or is there no way to build an rpm package through ... | Using rpmbuild in Python | I'm a newbie and I'm trying to write a python script to build rpm packages as part of an automated build system (Hudson).
I'm looking at the rpm-python API but I can't seem to see anything that relates to rpmbuild.
Am I missing something or is there no way to build an rpm package through the rpm api's? I was hoping I ... | [
"Debian includes python bindings for rpm allowing you to use rpm from python scripts\nhttp://packages.debian.org/stable/python/python-rpm\nAlso checkout : \nAPI Documentation\nRPM Python bindings - presentation and tutorial\n",
"If your project uses distutils, it is as simple as ./setup.py bdist_rpm More info on ... | [
0,
0
] | [] | [] | [
"python",
"rpmbuild"
] | stackoverflow_0003597801_python_rpmbuild.txt |
Q:
How do i make a while loop so it reads through every single line in .txt file before it decide what to?
Im creating a function called addingcustomer(n):
so i need it to read through every single line in the .txt to make sure there is no repeated customer name only add the new customer name:
my customer.txt:
[1. "Y... | How do i make a while loop so it reads through every single line in .txt file before it decide what to? | Im creating a function called addingcustomer(n):
so i need it to read through every single line in the .txt to make sure there is no repeated customer name only add the new customer name:
my customer.txt:
[1. "Yuvin Ng”, “Columbia College”, 778]
[2, “Ali”, “Douiglas College”, 77238]
my current function:
def addingcust... | [
"First of all, you don't need the two while statements. Also, you need to close the file before you return. Something like this:\ndef addingcustomer(file_name,new_name):\n f=open(file_name,\"r+\")\n for line in f:\n if new_name in line:\n f.close()\n return (\"The Customer exist... | [
2
] | [] | [] | [
"python",
"variable_assignment"
] | stackoverflow_0006638595_python_variable_assignment.txt |
Q:
Download html of URL with Python - but with javascript enabled
I am trying to download this page so that I can scrape the search results. However, when I download the page and try to process it with BeautifulSoup, I find that parts of the page (for example, the search results) aren't included as the site has detec... | Download html of URL with Python - but with javascript enabled | I am trying to download this page so that I can scrape the search results. However, when I download the page and try to process it with BeautifulSoup, I find that parts of the page (for example, the search results) aren't included as the site has detected that javascript is not enabled.
Is there a way to download the H... | [
"@kstruct: My preferred way, instead of writing a full browser with QtWebKit and PyQt4, is to use one already written. There's the PhantomJS (C++) project, or PyPhantomJS (Python). Basically the Python one is QtWebKit and Python.\nThey're both headless browsers which you can control directly from JavaScript. The Py... | [
3,
2,
0,
0
] | [] | [] | [
"python",
"screen_scraping"
] | stackoverflow_0006630214_python_screen_scraping.txt |
Q:
Python: Adding a word from a stringlist to another stringlist
I'm trying to add whole words from one string to another if they contain a certain character:
mylist = ["hahah", "hen","cool", "breaker", "when"]
newlist = []
for word in mylist:
store = word #stores current string
if 'h' in word: ... | Python: Adding a word from a stringlist to another stringlist | I'm trying to add whole words from one string to another if they contain a certain character:
mylist = ["hahah", "hen","cool", "breaker", "when"]
newlist = []
for word in mylist:
store = word #stores current string
if 'h' in word: #splits string into characters and searches for 'h'
newlis... | [
"Use append [docs]:\nnewlist.append(store)\n\nOr shorter (using list comprehension [docs]):\nnewlist = [word for word in mylist if 'h' in word]\n\n\nWhy does newlist += store not work?\nThis is the same as newlist = newlist + store and is extending the existing list (on left side) by all the items in the sequence [... | [
7,
1,
0,
0
] | [] | [] | [
"add",
"python",
"string"
] | stackoverflow_0006637860_add_python_string.txt |
Q:
Class Name and File Name
I am from Java background. I am going through the official Python tutorials but can't seem to find the information in relation to Python source file names and classes.
In Java, file name is the same as main class name plus the .java extension. In Python what's the case? In the examples of ... | Class Name and File Name | I am from Java background. I am going through the official Python tutorials but can't seem to find the information in relation to Python source file names and classes.
In Java, file name is the same as main class name plus the .java extension. In Python what's the case? In the examples of official tutorials, they are w... | [
"There's a file. Period. Whatever is contained in it is of no interest for imports, and the file name or location doesn't have any effect on the contained code (generally - it is accessible during execution, so some metaprogramming makes use of it but should be agnostic w.r.t. the actual value).\nThe contents of a ... | [
16,
11,
7
] | [] | [] | [
"class",
"filenames",
"python"
] | stackoverflow_0006637811_class_filenames_python.txt |
Q:
Dynamically create new kind with all the same properties of existing model class
I'm trying to create a universal way of versioning data for my models. I'd like to dynamically create a new backup for class SomeModel(db.Model) with new kind BackupSomeModel.
Do you have any tips on how to do this in python? Or maybe... | Dynamically create new kind with all the same properties of existing model class | I'm trying to create a universal way of versioning data for my models. I'd like to dynamically create a new backup for class SomeModel(db.Model) with new kind BackupSomeModel.
Do you have any tips on how to do this in python? Or maybe you have a general idea on how to version data in GAE?
PS: I'm trying to move away fr... | [
"The easiest way to do it is like this:\nclass BackupSomeModel(SomeModel): pass\n\nIf you're keeping an audit log, though, storing serialized protocol buffers in a separate kind is probably a better approach. I would suggest having an 'AuditLog' kind, entities of which are child entities of the record they audit, c... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006597583_google_app_engine_python.txt |
Q:
Python: raising exception in try/except/else block, processing order problem
I am a novice to Python and have started to write my first module which will perform a backup to external storage (typically one or more USB disks).
The desired behaviour is:
check if destination (backup disk) is mounted already. destin... | Python: raising exception in try/except/else block, processing order problem | I am a novice to Python and have started to write my first module which will perform a backup to external storage (typically one or more USB disks).
The desired behaviour is:
check if destination (backup disk) is mounted already. destination_was_mounted becomes True or False
If destination_was_mounted = False then mo... | [
"You have the unmounting code in the try block. In finally, you're just logging.\n"
] | [
0
] | [] | [] | [
"exception_handling",
"loops",
"python"
] | stackoverflow_0006638562_exception_handling_loops_python.txt |
Q:
How do I execute two programs from python at the same time?
This post explains how to launch a single external program from Python
How shall I launch multipal programs(or threads) at the same time ?
My intended application is a video slide show. I want to launch a image sequence player and a music player at the sa... | How do I execute two programs from python at the same time? | This post explains how to launch a single external program from Python
How shall I launch multipal programs(or threads) at the same time ?
My intended application is a video slide show. I want to launch a image sequence player and a music player at the same time
Thanks in advance
| [
"subprocess.Popen doesn't block unless you explicitly ask it to by calling communicate on the returned object, so you can call it more than once to start more than one process.\nIf you do need to communicate with both sub-processes simultaneously (read their STDOUT, for instance), then invoke subprocess.Popen in se... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0006639032_python.txt |
Q:
Scrape gmail for the last time external pop accounts were checked and check them if longer than X time since the last check
Goal:
To develop an script that will check the last time my external pop accounts were checked by google -- while not being logged in. If the time exceeds some amount, then check the pop acc... | Scrape gmail for the last time external pop accounts were checked and check them if longer than X time since the last check | Goal:
To develop an script that will check the last time my external pop accounts were checked by google -- while not being logged in. If the time exceeds some amount, then check the pop account.
My Reason:
I use an offline client. I don't want to be logged into gmail and I want all my external emails to flow thru g... | [
"Probably http://www.phantomjs.org/ is going to be the best tool for this job. They have lots of examples in their github repository for how to do this type of thing. People have had good success with complex scraping tasks.\n"
] | [
1
] | [] | [] | [
"javascript",
"python",
"screen_scraping",
"web_scraping"
] | stackoverflow_0006639125_javascript_python_screen_scraping_web_scraping.txt |
Q:
Delete a matching line from a .txt file using python
I'm creating a delete function.
my customerlist.txt
[1. 'Yuvin Ng', 'Columbia College', 778]
[2, 'Ali', 'Douiglas College', 77238]
[3, 'Nancy', 'Douglas College', 7783390222]
If I want to delete Yuvin Ng and its whole line, how can I do it?
My plan was to creat... | Delete a matching line from a .txt file using python | I'm creating a delete function.
my customerlist.txt
[1. 'Yuvin Ng', 'Columbia College', 778]
[2, 'Ali', 'Douiglas College', 77238]
[3, 'Nancy', 'Douglas College', 7783390222]
If I want to delete Yuvin Ng and its whole line, how can I do it?
My plan was to create an empty list which will return the whole thing as "" an... | [
"If I understand correctly, you want to return content of the file minus the deleted line\nret = []\nfor line in f:\n if name != line[1]:\n ret.append(line);\nreturn ret\n\n",
"new_file = open(nf,'w')\nwith open(fn) as f:\n for l in f:\n if not 'Yuvin Ng' in l:\n new_file.write(l)\n... | [
1,
1
] | [] | [] | [
"file",
"python",
"text_files"
] | stackoverflow_0006639289_file_python_text_files.txt |
Q:
How do you create an indexable empty list in python?
Is there a way to neatly create large (i.e. indexable) empty lists in python?
This is what I am doing at the moment:
firstgen=G.neighbors(node1)
secgen=[]
thirdgen=[[],[],[],[],[],[],[],[],[],[],[]] #11 brackets because len(secgen)=11
for i in firstgen:
s... | How do you create an indexable empty list in python? | Is there a way to neatly create large (i.e. indexable) empty lists in python?
This is what I am doing at the moment:
firstgen=G.neighbors(node1)
secgen=[]
thirdgen=[[],[],[],[],[],[],[],[],[],[],[]] #11 brackets because len(secgen)=11
for i in firstgen:
secgen.append(G.neighbors(i))
for i in range(len(secgen... | [
"You don't need to create the empty lists. You can use list comprehensions to build your nested lists:\nfirstgen = G.neighbors(node1)\nsecndgen = [G.neighbors(node) for node in firstgen]\nthirdgen = [[G.neighbors(node) for node in group] for group in secndgen]\n\n\nfirstgen: [node, ...]\nsecndgen: [[node, ...], ...... | [
3,
2,
2,
0
] | [] | [] | [
"arrays",
"list",
"python"
] | stackoverflow_0006638339_arrays_list_python.txt |
Q:
Generate html from plain text with formatting markers in Python 3
I have written a set of Python 3 scripts to take a formatted text file and move the data into a SQLite database. The data in the database is then used as a part of a PHP application. The data in my text file has formatting markers for bold and ita... | Generate html from plain text with formatting markers in Python 3 | I have written a set of Python 3 scripts to take a formatted text file and move the data into a SQLite database. The data in the database is then used as a part of a PHP application. The data in my text file has formatting markers for bold and italics, but not in anything intelligible to a browser. The formatting sc... | [
"To format the bracketed sections, you could do something like this:\nwhile text.find(\":{\") > -1:\n index = text.find(\":{\")\n if text[index-2:index]==\"fb\":\n text = text[:index-2] + \"<b>\" + text[index+2:] #insert <b>\n text = text.replace(\"}\",\"</b>\",1) # replace one.\n # else if f... | [
1
] | [] | [] | [
"html",
"python",
"python_3.x",
"text_parsing"
] | stackoverflow_0006639375_html_python_python_3.x_text_parsing.txt |
Q:
re.sub(...) replacing leftmost occurrences?
$ pydoc re.sub :
sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl.
>>> re.sub('ROAD', 'RD.', 'BRRROADBBRROAD ROAD ROAD MY ROAD')
'BR... | re.sub(...) replacing leftmost occurrences? | $ pydoc re.sub :
sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl.
>>> re.sub('ROAD', 'RD.', 'BRRROADBBRROAD ROAD ROAD MY ROAD')
'BRRRD.BBRRD. RD. RD. MY RD.'
I don't quite underst... | [
"Note the 's' ending leftmost non-overlapping occurrences. \nre.sub replaces all occurrences. You can use the optional count argument to limit the amount of replacements it does.\n\"Leftmost non-overlapping\" means that if several occurrences are overlapping and can be potentially replaced, only the leftmost will:\... | [
11,
5
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006639522_python_regex.txt |
Q:
Returning an object based on __class__.__name__ in Python
So I have a Superclass (which for simplicity I'll call), Mammal, from which classes Dog, Monkey, and Bear inherit methods. Some of the inherited methods return an object that needs to be of the same class it is called from. For example, Dog.find(...) shou... | Returning an object based on __class__.__name__ in Python | So I have a Superclass (which for simplicity I'll call), Mammal, from which classes Dog, Monkey, and Bear inherit methods. Some of the inherited methods return an object that needs to be of the same class it is called from. For example, Dog.find(...) should return Dog objects. But because the find() method is inherit... | [
"Just try return self.__class__()\n",
"Use a classmethod to make a factory:\nclass Mammal(object):\n\n @classmethod\n def new(cls, *args, **kwds):\n return cls(*args, **kwds)\n\nclass Dog(Mammal):\n\n def find(self):\n return self.new()\n\n>>> d = Dog()\n>>> d2 = d.find()\n>>> type(d2)\n<cl... | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0006639536_python.txt |
Q:
python script call on user modification or adding of files to linux directory
I have a directory of files on my Ubuntu machine. I run python 2.6. All of these files are represented in a database for purposes of sorting, searching, locating, etc. I'd like to trigger a python script every time a file is added or mod... | python script call on user modification or adding of files to linux directory | I have a directory of files on my Ubuntu machine. I run python 2.6. All of these files are represented in a database for purposes of sorting, searching, locating, etc. I'd like to trigger a python script every time a file is added or modified to update said database.
basically, upon adding, moving, deleting, or renami... | [
"Use incron to run a script that gets passed the new filenames.\n"
] | [
2
] | [] | [] | [
"directory",
"filesystems",
"linux",
"python"
] | stackoverflow_0006639611_directory_filesystems_linux_python.txt |
Q:
difference b/w [ab] and (a|b) in regex match?
I knew that [] denotes a set of allowable characters -
>>> p = r'^[ab]$'
>>>
>>> re.search(p, '')
>>> re.search(p, 'a')
<_sre.SRE_Match object at 0x1004823d8>
>>> re.search(p, 'b')
<_sre.SRE_Match object at 0x100482370>
>>> re.search(p, 'ab')
>>> re.search(p, 'ba')
... | difference b/w [ab] and (a|b) in regex match? | I knew that [] denotes a set of allowable characters -
>>> p = r'^[ab]$'
>>>
>>> re.search(p, '')
>>> re.search(p, 'a')
<_sre.SRE_Match object at 0x1004823d8>
>>> re.search(p, 'b')
<_sre.SRE_Match object at 0x100482370>
>>> re.search(p, 'ab')
>>> re.search(p, 'ba')
But ... today I came across an expression with vert... | [
"In this case it is the same.\nHowever, the alternation is not just limited to a single character. For instance,\n^(hello|world)$\n\nwill match \"hello\" or \"world\" (and only these two inputs) while\n^[helloworld]$\n\nwould just match a single character (\"h\" or \"w\" or \"d\" or whatnot).\nHappy coding.\n",
"... | [
39,
17,
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006639820_python_regex.txt |
Q:
Live countdown clock with django and sql?
If I make a live countdown clock like ebay, how do I do this with django and sql? I'm assuming running a function in django or in sql over and over every second to check the time would be horribly inefficient.
Is this even a plausible strategy?
Or is this the way they d... | Live countdown clock with django and sql? | If I make a live countdown clock like ebay, how do I do this with django and sql? I'm assuming running a function in django or in sql over and over every second to check the time would be horribly inefficient.
Is this even a plausible strategy?
Or is this the way they do it:
When a page loads, it takes the end datet... | [
"I don't think this question has anything to do with SQL, really--except that you might retrieve an expiration time from SQL. What you really care about is just how to display the timeout real-time in the browser, right?\nObviously the easiest way is just to send a \"seconds remaining\" counter to the page, either... | [
2,
0
] | [] | [] | [
"countdown",
"django",
"javascript",
"python",
"time"
] | stackoverflow_0006639247_countdown_django_javascript_python_time.txt |
Q:
How match a regex if it does not contain a particular word?
I want to write a regex in Python or JavaScript to match if the given string does not JUST contain the given word (e.g "any").
For example :
any : does not match
AnY : does not match
anyday : match
any day : match
blabla : match
A:
If you also... | How match a regex if it does not contain a particular word? | I want to write a regex in Python or JavaScript to match if the given string does not JUST contain the given word (e.g "any").
For example :
any : does not match
AnY : does not match
anyday : match
any day : match
blabla : match
| [
"If you also need words other that starting with \"any\" you can use a negative lookahead\n^(?!any$).*$\n\nThis will match anything besides \"any\".\n",
"It is probably more efficient to not use a regex, this works as well:\ndef noAny(i):\n i = i.lower().replace('any', '')\n return len(i) > 0\n\n",
"Somet... | [
5,
2,
1,
1,
1
] | [] | [] | [
"javascript",
"python",
"regex"
] | stackoverflow_0006640019_javascript_python_regex.txt |
Q:
Django 1.0, using default password reset
I'm trying to use the password reset setup that comes with Django, but the documentation is not very good for it. I'm using Django 1.0 and I keep getting this error:
Caught an exception while rendering: Reverse for 'mysite.django.contrib.auth.views.password_reset_confirm' ... | Django 1.0, using default password reset | I'm trying to use the password reset setup that comes with Django, but the documentation is not very good for it. I'm using Django 1.0 and I keep getting this error:
Caught an exception while rendering: Reverse for 'mysite.django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments ...
... | [
"Edit: I used your example, and had to change to not use keyword parameters.\n{% url django.contrib.auth.views.password_reset_confirm uid, token %}\n\nNamed parameters do work, as long as both uid and token are defined. If either are not defined or blank I get the same error you do:\n{% url django.contrib.auth.vie... | [
3,
2,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000942148_django_python.txt |
Q:
Avoiding 503 errors with urllib2
I'm new to web scraping with python, so I don't know if I'm doing this right.
I'm using a script that calls BeautifulSoup to parse the URLs from the first 10 pages of a google search. Tested with stackoverflow.com, worked just fine out-of-the-box. I tested with another site a few t... | Avoiding 503 errors with urllib2 | I'm new to web scraping with python, so I don't know if I'm doing this right.
I'm using a script that calls BeautifulSoup to parse the URLs from the first 10 pages of a google search. Tested with stackoverflow.com, worked just fine out-of-the-box. I tested with another site a few times, trying to see if the script was ... | [
"Automated querying is not permitted by Google Terms of Service.\nSee this article for information:\nUnusual traffic from your computer\nand also Google Terms of service\n",
"As Ettore said, scraping the search results is against our ToS. However check out the WebSearch api, specifically the bottom section of the... | [
5,
0
] | [] | [] | [
"beautifulsoup",
"extract",
"python",
"screen_scraping"
] | stackoverflow_0006635128_beautifulsoup_extract_python_screen_scraping.txt |
Q:
Python's asyncore to periodically send data using a variable timeout. Is there a better way?
I wanted to write a server that a client could connect to and receive periodic updates without having to poll. The problem I have experienced with asyncore is that if you do not return true when dispatcher.writable() is c... | Python's asyncore to periodically send data using a variable timeout. Is there a better way? | I wanted to write a server that a client could connect to and receive periodic updates without having to poll. The problem I have experienced with asyncore is that if you do not return true when dispatcher.writable() is called, you have to wait until after the asyncore.loop has timed out (default is 30s).
The two ways... | [
"The \"select law\" doesn't apply to your case, as you have not only client-triggered (pure server) activities, but also time-triggered activities - this is precisely what the select timeout is for. What the law should really say is \"if you specify a timeout, make sure you actually have to do something useful when... | [
4,
4,
2,
1,
0
] | [] | [] | [
"asynchronous",
"python",
"sockets"
] | stackoverflow_0001036646_asynchronous_python_sockets.txt |
Q:
python continuous integration
I am looking to set up a continuous integration server for a python project. Normally this would build the project however as python is not built as such, what should be done instead? Just unit tests? Or are there additional steps that anyone can recommend?
A:
There are a couple of ... | python continuous integration | I am looking to set up a continuous integration server for a python project. Normally this would build the project however as python is not built as such, what should be done instead? Just unit tests? Or are there additional steps that anyone can recommend?
| [
"There are a couple of excellent recourses on how to use Jenkins together with Python:\n\nTalk from PyCon\nA blog post.\nAnother blog post.\n\nThe standard option would be to run the unittests, record the test coverage and run pylint or some other style checker.\n",
"Using Jenkins/Hudson for continuous integratio... | [
12,
0
] | [] | [] | [
"continuous_integration",
"python"
] | stackoverflow_0006640385_continuous_integration_python.txt |
Q:
SocketServer continue execution after serve_forever
I'm using the SocketServer module in python to implement a simple embedded web server in my application. At the moment I'm calling the serve_forver method within a dedicated thread in order to continue the execution of my application.
I was wondering if there is ... | SocketServer continue execution after serve_forever | I'm using the SocketServer module in python to implement a simple embedded web server in my application. At the moment I'm calling the serve_forver method within a dedicated thread in order to continue the execution of my application.
I was wondering if there is there a more pythonic way to start my SocketServer and re... | [
"That is a very pythonic way:\nthreading.Thread(target=myServer.serve_forever).start()\n\nI don't see how that could be unclear or overly verbose. If you want the program to exit once your main thread finishes, add daemon=True to the Thread call.\nAn alternative is calling handle_request in a loop yourself, but tha... | [
15
] | [] | [] | [
"python"
] | stackoverflow_0006640458_python.txt |
Q:
Is there a better way to determine something is a module in python
I have the name of an 'thing' in python. I want to check if this 'thing' is a module or not. I can do it with the below code:
mod = eval(module_name)
print inspect.ismodule(mod)
I don't like the idea of calling eval. Is there a better way to get f... | Is there a better way to determine something is a module in python | I have the name of an 'thing' in python. I want to check if this 'thing' is a module or not. I can do it with the below code:
mod = eval(module_name)
print inspect.ismodule(mod)
I don't like the idea of calling eval. Is there a better way to get from the module_name, which is a string, to the actual module object?
| [
"Better yet, forget about __import__'ing it, and just see if it exists. :)\nNow, I don't know if this is actually much faster, however it's what I would do. __import__ at the core uses imp.find_module() anyways.\nimport imp\ntry:\n imp.find_module('module')\nexcept ImportError:\n import sys\n sys.exit('No ... | [
3,
2,
0
] | [
"Use dir() on the 'thing':\ndir(something)\n\n"
] | [
-1
] | [
"introspection",
"python"
] | stackoverflow_0006640378_introspection_python.txt |
Q:
How to populate shelf with existing dictionary
Lets say I have a large, 100s of megabytes, dictionary that I want to make into an on disk shelve. I'm using pypar to utilize MPI to generate cleaned bits of a master list. What's the best way to achieve this? Example:
# much earlier
masterDict = shelve.open( 'aShel... | How to populate shelf with existing dictionary | Lets say I have a large, 100s of megabytes, dictionary that I want to make into an on disk shelve. I'm using pypar to utilize MPI to generate cleaned bits of a master list. What's the best way to achieve this? Example:
# much earlier
masterDict = shelve.open( 'aShelveFile' )
# .. . . . .
# then we work out which par... | [
"Here you shelve a simple dictionary and make it accessibly via key myDict:\nimport shelve\nmyDict = {\"a\" : 1, \"b\" : 2}\nmyShelvedDict = shelve.open(\"my_shelved_dictionary.db\")\nmyShelvedDict[\"myDict\"] = myDict\n\nNote that the contents of the dictionary must be pickleable, as for anything that is to be she... | [
7
] | [] | [] | [
"mpi",
"python",
"shelve"
] | stackoverflow_0006640212_mpi_python_shelve.txt |
Q:
Python ctypes: get variable type and value problem
I want to use a C library in some Python code by using ctypes.
My problem is that I don't know C. I've been trying to read the code and about C structure for some days now, but I am stuck at one problem. I'm also fairly new to Python, since I'm currently making th... | Python ctypes: get variable type and value problem | I want to use a C library in some Python code by using ctypes.
My problem is that I don't know C. I've been trying to read the code and about C structure for some days now, but I am stuck at one problem. I'm also fairly new to Python, since I'm currently making the switch from Matlab, and my Python is thus limited to s... | [
"One issue is enums are not structures. Also make sure the fields in your structure are in the same order as the C header ('type' comes first). Try this:\nimport ctypes\n\nVAR_TYPE = ctypes.c_int\nTT_EMPTY = 0\nTT_ERROR = 1\nTT_LONG = 2\nTT_DOUBLE = 3\nTT_STRING = 4\n\nVRESULT = ctypes.c_int\nVR_OK =... | [
2,
1
] | [] | [] | [
"ctypes",
"python",
"struct",
"union"
] | stackoverflow_0005990674_ctypes_python_struct_union.txt |
Q:
Is there an automated way to install python modules (à la rubygems)?
I'm new to python. Are there alternatives to downloading a tarball for a python module & installing it via python setup install ? Anything like rubygems?
UPDATE I'm surprised that there are so many solutions for this one problem.
A:
setuptools ... | Is there an automated way to install python modules (à la rubygems)? | I'm new to python. Are there alternatives to downloading a tarball for a python module & installing it via python setup install ? Anything like rubygems?
UPDATE I'm surprised that there are so many solutions for this one problem.
| [
"setuptools is one option. Install that and then you can install many Python modules using the easy_install command-line tool.\n",
"There are many options - you can stick with your system's default packaging system (if it has one) or you can pick one (or more) of existing Python tools like easy_install, zc.buildo... | [
4,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004426897_python.txt |
Q:
Detecting if a file is an image in Python
Is there any general way to detect if a file is a image (jpg, bmp, png, etc...)
Or is making a list of the file extensions and doing a one-by-one comparison the only way?
A:
Assuming:
>>> files = {"a_movie.mkv", "an_image.png", "a_movie_without_extension", "an_image_with... | Detecting if a file is an image in Python | Is there any general way to detect if a file is a image (jpg, bmp, png, etc...)
Or is making a list of the file extensions and doing a one-by-one comparison the only way?
| [
"Assuming:\n>>> files = {\"a_movie.mkv\", \"an_image.png\", \"a_movie_without_extension\", \"an_image_without_extension\"}\n\nAnd they are proper movie and image files in script folder.\nYou can use builtin mimetypes module, but it won't work without extensions.\n>>> import mimetypes\n>>> {file: mimetypes.guess_typ... | [
28,
2
] | [] | [] | [
"image",
"python"
] | stackoverflow_0006640605_image_python.txt |
Q:
How can I integrate Java classes with Python?
I am building website with Python and django. There are ome data mining classes already programmed in java. Can i use those function in djnago via anything like
A:
Try running Django on Jython. I believe it should be possible to integrate Java classes in such way.
| How can I integrate Java classes with Python? | I am building website with Python and django. There are ome data mining classes already programmed in java. Can i use those function in djnago via anything like
| [
"Try running Django on Jython. I believe it should be possible to integrate Java classes in such way.\n"
] | [
1
] | [] | [] | [
"django",
"java",
"python"
] | stackoverflow_0006641120_django_java_python.txt |
Q:
Calling a class functions using map
Sorry if this has been asked but I couldn't find anything online to indicate if this was possible. The easiest way I can explain this is just with a code segment, with this just being representative of my problem:
class A:
def a(self,):
print "Hello"
B = [A for i in ... | Calling a class functions using map | Sorry if this has been asked but I couldn't find anything online to indicate if this was possible. The easiest way I can explain this is just with a code segment, with this just being representative of my problem:
class A:
def a(self,):
print "Hello"
B = [A for i in xrange(10)]
map(self.a,B)
Basically I wa... | [
"Is this what you want?\n>>> class A:\n... def a(self):\n... print \"Hello\"\n... \n>>> B = [A() for i in xrange(10)]\n>>> map(lambda a: a.a(), B)\nHello\nHello\nHello\nHello\nHello\nHello\nHello\nHello\nHello\nHello\n[None, None, None, None, None, None, None, None, None, None]\n\n",
"You almost never want to ... | [
4,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006631807_python.txt |
Q:
Variables Access, get and post
how to get to these variables.
This is probably quite easy, but I do not think today.
class Contact(webapp.RequestHandler):
def get(self):
self.a = random.randint(1,4)
self.b = random.randint(0,4)
template_values = {
'a': self.a,
... | Variables Access, get and post | how to get to these variables.
This is probably quite easy, but I do not think today.
class Contact(webapp.RequestHandler):
def get(self):
self.a = random.randint(1,4)
self.b = random.randint(0,4)
template_values = {
'a': self.a,
'b': self.b
}
path ... | [
"Each request creates a new handler instance. For example, you can add this constructor to your handler:\nclass AppHandler(webapp.RequestHandler):\n def __init__(self, *args, **kwargs):\n logging.debug('handler \"%s\" created' % self)\n super(AppHandler, self).__init__(*args, **kwargs)\n <...>\n... | [
4
] | [] | [] | [
"google_app_engine",
"python",
"variables"
] | stackoverflow_0006640468_google_app_engine_python_variables.txt |
Q:
Algorithm for drawing a graph structure?
I have a digraph graph G=(V,E) that I would like to redraw because it is currently very messy. This is a flow chart that is being visualized and since |V|>1000 and each v in V has more than 1 outgoing edge, it is very hard to trace by eye. For instance; a node on the lower ... | Algorithm for drawing a graph structure? | I have a digraph graph G=(V,E) that I would like to redraw because it is currently very messy. This is a flow chart that is being visualized and since |V|>1000 and each v in V has more than 1 outgoing edge, it is very hard to trace by eye. For instance; a node on the lower left corner is connected by an edge to a node ... | [
"You want to look at graphviz.org; this is a difficult problem on which there has been a lot of research, reimplementing the wheel is not the right way to go.\nProbably you'll have to get the java to write out a datafile which a tool like 'dot' can read and use for the graph layout.\n",
"That messy one seems to b... | [
4,
0
] | [] | [] | [
"algorithm",
"graph",
"java",
"optimization",
"python"
] | stackoverflow_0006641568_algorithm_graph_java_optimization_python.txt |
Q:
Remove axes from a figure
Is it possible to remove the axes from a pyplot.figure()?
Using the pyplot.imsave() to create an image without axes works OK
plt.imsave(file, zi)
but it's limited because it only works with grid data.
When I use pyplot.figure() and save it using pyplot.savefig() as follows
...
# create f... | Remove axes from a figure | Is it possible to remove the axes from a pyplot.figure()?
Using the pyplot.imsave() to create an image without axes works OK
plt.imsave(file, zi)
but it's limited because it only works with grid data.
When I use pyplot.figure() and save it using pyplot.savefig() as follows
...
# create figure
fig = plt.figure(figsize... | [
"I was able to remove the axis display and any spacing that was allocated to the axis with the following code:\nfig = plt.figure(figsize=(1.0,1.0))\nax = fig.add_axes([0.0, -0.2, 1.2, 1.2])\nplt.contour(zi,15,linewidths=0.1,colors='k')\nplt.contourf(zi,15,cmap=plt.cm.jet)\nax.set_ylim(ax.get_ylim()[::-1])\nax.set_a... | [
6
] | [] | [] | [
"axes",
"figure",
"matplotlib",
"python"
] | stackoverflow_0006586337_axes_figure_matplotlib_python.txt |
Q:
Trouble running example django code
Im trying to learn Django by looking at examples, but Im having a bit of a problem running the examples I find.
I downloaded 'cheeserator' from https://github.com/jacobian/cheeserater
and I tried running it with python manage.py runserver
but I get the following error -
Error: ... | Trouble running example django code | Im trying to learn Django by looking at examples, but Im having a bit of a problem running the examples I find.
I downloaded 'cheeserator' from https://github.com/jacobian/cheeserater
and I tried running it with python manage.py runserver
but I get the following error -
Error: Can't find the file
'settings.py' in th... | [
"You need to have a settings.py file. \nAs per the instructions in the link provided:\nThen you'll want to create a settings.py file in this directory containing::\nfrom settings_template import *\n\n# Override any settings you like here.\n\nOr if you don't want to override anything rename settings_template.py to ... | [
3
] | [] | [] | [
"cheeseshop",
"django",
"model_view_controller",
"python"
] | stackoverflow_0006641719_cheeseshop_django_model_view_controller_python.txt |
Q:
Processing error while connect to rabbitmq via STOMP
I tried to connect to RabbitMQ(v2.5.1) via STOMP protocol using telnet and got following error:
#telnet localhost 61613
Trying ::1...
Connected to localhost.localdomain.
Escape character is '^]'.
CONNECT
login:guest
passcode:guest
^@
ERROR... | Processing error while connect to rabbitmq via STOMP | I tried to connect to RabbitMQ(v2.5.1) via STOMP protocol using telnet and got following error:
#telnet localhost 61613
Trying ::1...
Connected to localhost.localdomain.
Escape character is '^]'.
CONNECT
login:guest
passcode:guest
^@
ERROR
message:Processing error
content-type:text/plain
ve... | [
"You're using version 2.3.1 of the Erlang Client and version 2.5.1 of the STOMP plugin. You need to run the same version of both. You can download 2.5.1 of the Erlang Client here.\n"
] | [
0
] | [] | [] | [
"php",
"python",
"rabbitmq",
"stomp"
] | stackoverflow_0006606041_php_python_rabbitmq_stomp.txt |
Q:
Filling the action area of a gtk.Dialog window with its buttons - instead of having them aligned to the right
Using PyGTK, I create a bunch of buttons in the action area of a gtk.Dialog using the add_button() method, as below:
self.replace_all_button = self.add_button(_("Replace All"),
gtk.RESPONSE_AC... | Filling the action area of a gtk.Dialog window with its buttons - instead of having them aligned to the right | Using PyGTK, I create a bunch of buttons in the action area of a gtk.Dialog using the add_button() method, as below:
self.replace_all_button = self.add_button(_("Replace All"),
gtk.RESPONSE_ACCEPT)
The resulting dialog has all the buttons aligned to the right, as seen in the following image:
However, I w... | [
"Maybe you could replace the hbuttonbox in the dialog with a normal hbox and then more easily control the packing.\n",
"My problem was \"solved\" when I discovered I was looking for a nonexistent problem.\nI am trying to copying the look-and-feel fo the Gedit search and replace window. Then I started Gedit using ... | [
1,
0
] | [] | [] | [
"dialog",
"gtk",
"pygtk",
"python"
] | stackoverflow_0006627910_dialog_gtk_pygtk_python.txt |
Q:
Python - HardDrive access when opening files
If you open a file for reading, read from it, close it, and then repeat the process (in a loop) does python continually access the hard-drive? Because it doesn't seem to from my experimentation, and I'd like to understand why.
An (extremely) simple example:
while True:
... | Python - HardDrive access when opening files | If you open a file for reading, read from it, close it, and then repeat the process (in a loop) does python continually access the hard-drive? Because it doesn't seem to from my experimentation, and I'd like to understand why.
An (extremely) simple example:
while True:
file = open('/var/log/messages', 'r')
stuf... | [
"Likely your operating system or file-system is smart enough to serve the file from the OS cache if the file has not changed in between.\n",
"The answer depends on your operating system and the type of hard drive you have. Most of the time, when you access something off the drive, the information is cached in ma... | [
3,
3,
2
] | [] | [] | [
"hard_drive",
"python"
] | stackoverflow_0006642384_hard_drive_python.txt |
Q:
how to put gap between y axis and first bar in vertical barchart matplotlib
I have a barchart code snippet as below..When you run this,you get 4 bars ,the first of which lies against the y axis.Is it possible to put some gap between y axis and the first bar?
def plot_graph1():
xvals = range(4)
xnames=["one... | how to put gap between y axis and first bar in vertical barchart matplotlib | I have a barchart code snippet as below..When you run this,you get 4 bars ,the first of which lies against the y axis.Is it possible to put some gap between y axis and the first bar?
def plot_graph1():
xvals = range(4)
xnames=["one","two","three","four"]
yvals = [10,30,40,20]
width = 0.25
yinterval ... | [
"In your specific case, it's easiest to use plt.margins and plt.ylim(ymin=0). margins will act like axis('tight'), but leave the specified percentage of \"padding\", instead of scaling to the exact limits of the data.\nAlso, plt.bar has an align=\"center\" option that simplifies your example somewhat.\nHere's a sl... | [
16
] | [] | [] | [
"bar_chart",
"matplotlib",
"python"
] | stackoverflow_0006642482_bar_chart_matplotlib_python.txt |
Q:
psycopg2 binary package for windows and postgres 8?
Where is the psycopg2 binary package for windows and postgres 8?
I can only find a release for postgres 9 on http://www.stickpeople.com/projects/python/win-psycopg/
There is a link for older versions at the bottom of the page but it does not realy help.
EDIT: I c... | psycopg2 binary package for windows and postgres 8? | Where is the psycopg2 binary package for windows and postgres 8?
I can only find a release for postgres 9 on http://www.stickpeople.com/projects/python/win-psycopg/
There is a link for older versions at the bottom of the page but it does not realy help.
EDIT: I could find them, see my answer below
| [
"I just found the binary packages for postgres 8 start at http://www.stickpeople.com/projects/python/win-psycopg/index.2.2.1.html\nThe html pages are chained, so I simply had to repeat the scroll down and click the \"old versions\" links on the page several times.\n"
] | [
2
] | [] | [] | [
"binary",
"postgresql",
"psycopg2",
"python",
"windows"
] | stackoverflow_0006642848_binary_postgresql_psycopg2_python_windows.txt |
Q:
How to implement a simple Google Checkout callback function with Django?
I have a simple 'Buy Now' Google Checkout button on my Django site (very simple; no basket or anything more fancy). What I want is for Google to send a notification to a URL on my server once a new order has been processed. The notification s... | How to implement a simple Google Checkout callback function with Django? | I have a simple 'Buy Now' Google Checkout button on my Django site (very simple; no basket or anything more fancy). What I want is for Google to send a notification to a URL on my server once a new order has been processed. The notification should tell me the customer's email address and name (preferably as simple POST... | [
"Take a look at how Satchmo handles notifications in: payment.modules.google\n"
] | [
1
] | [] | [] | [
"django",
"google_checkout",
"python"
] | stackoverflow_0006635982_django_google_checkout_python.txt |
Q:
python gtk.window.resize not working when trying to make bigger/smaller window
I have a window that I start in a certain size and want to make smaller or bigger when user does an interaction.. I have made it into a top dock so nothing can maximize over it.
I cannot resize it to a smaller or bigger size, nothing ha... | python gtk.window.resize not working when trying to make bigger/smaller window | I have a window that I start in a certain size and want to make smaller or bigger when user does an interaction.. I have made it into a top dock so nothing can maximize over it.
I cannot resize it to a smaller or bigger size, nothing happens.
Here is the code for me creating the window:
window = gtk.Window(gtk.WINDOW_T... | [
"Your code would work, just need to change this line:\nwindow.resize(gtk.gdk.screen_width(),100) # Instead of gtk.gdk.screen.width()\n\nand It would be better to use below line of code i.e.\nwindow.window.property_change(\"_NET_WM_STRUT\", \"CARDINAL\", 32,\n gtk.gdk.PROP_MODE_REPLACE, [0, 0, 100, 0])\n\nafter t... | [
2
] | [] | [] | [
"gtk",
"linux",
"python",
"resize"
] | stackoverflow_0006642239_gtk_linux_python_resize.txt |
Q:
Dividing a string in python
How do I tell a program to read /123/456/789/ as three separate strings to be handled individually?
A:
If all your strings have this exact same format:
>>> "/123/456/789/".split("/")[1:-1]
['123', '456', '789']
You get your 3 strings from the list.
A:
an other solution if your stri... | Dividing a string in python | How do I tell a program to read /123/456/789/ as three separate strings to be handled individually?
| [
"If all your strings have this exact same format:\n>>> \"/123/456/789/\".split(\"/\")[1:-1]\n['123', '456', '789']\n\nYou get your 3 strings from the list.\n",
"an other solution if your string do not necessarry starts, or ends with '/', could be:\n'/123/456/789/'.strip('/').split('/')\n> ['123', '456', '789']\n\... | [
10,
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006643005_python_string.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.