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:
python version for maya and other 3d apps
I have a couple small projects that I want to use to learn python. What version should I be using if I want to move to scripting for Maya, Blender, etc later? Also, what resources are there for scripting for those programs?
A:
If you are using Maya 2011 it comes bundled ... | python version for maya and other 3d apps | I have a couple small projects that I want to use to learn python. What version should I be using if I want to move to scripting for Maya, Blender, etc later? Also, what resources are there for scripting for those programs?
| [
"If you are using Maya 2011 it comes bundled with and bound to py 2.6.4 already. You don't need a separate install, not even for pyMEL anymore.\nIf you want to learn Python on its own before applying the knowledge to a 3D app, then pretty much any 2.x Python will do really, the version specific features only come i... | [
5,
2,
2
] | [] | [] | [
"3d",
"maya",
"python"
] | stackoverflow_0003860386_3d_maya_python.txt |
Q:
How to insert item into c_char_p array
I want to pass an array of char pointer to a C function.
I refer to http://docs.python.org/library/ctypes.html#arrays
I write the following code.
from ctypes import *
names = c_char_p * 4
# A 3 times for loop will be written here.
# The last array will assign to a null point... | How to insert item into c_char_p array | I want to pass an array of char pointer to a C function.
I refer to http://docs.python.org/library/ctypes.html#arrays
I write the following code.
from ctypes import *
names = c_char_p * 4
# A 3 times for loop will be written here.
# The last array will assign to a null pointer.
# So that C function knows where is the ... | [
"What you did was to create an array type, not an actual array, so basically:\nimport ctypes\narray_type = ctypes.c_char_p * 4\nnames = array_type()\n\nYou can then do something along the lines of:\nnames[0] = \"foo\"\nnames[1] = \"bar\"\n\n...and proceed to call your C function with the names array as parameter.\n... | [
17
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0004687170_ctypes_python.txt |
Q:
Retrieve wall-time in Python using the standard library?
How can I retrieve wall-time in Python using the standard library?
This question, and this question would suggest that something like clock_gettime(CLOCK_MONOTONIC_RAW) or /proc/uptime are most appropriate on Linux. On Windows, time.clock() has the desired e... | Retrieve wall-time in Python using the standard library? | How can I retrieve wall-time in Python using the standard library?
This question, and this question would suggest that something like clock_gettime(CLOCK_MONOTONIC_RAW) or /proc/uptime are most appropriate on Linux. On Windows, time.clock() has the desired effect.
I would use time.time(), but the function is not guaran... | [
"Victor Stinner wrote a Python implementation of a monotonic timer. See http://bugs.python.org/issue10278 for the discussion and the docs for the upcoming 3.3 release referencing the new feature (coded in C).\nThere is also Monoclock:\n\nMonoclock is a Python module that\n provides access to the monotonic clock\n ... | [
6
] | [] | [] | [
"clock",
"python",
"standard_library",
"time",
"wall_time"
] | stackoverflow_0004687408_clock_python_standard_library_time_wall_time.txt |
Q:
Problem in printing array of char pointer passing from Python
My following C code works quite well, till my Python code trying to pass an array of char pointer to it.
The output I obtain is
The file_name is python-file
Another 3 string is not being printed out. Anything I had missed out?
C Code
#include <iostre... | Problem in printing array of char pointer passing from Python | My following C code works quite well, till my Python code trying to pass an array of char pointer to it.
The output I obtain is
The file_name is python-file
Another 3 string is not being printed out. Anything I had missed out?
C Code
#include <iostream>
#include "c_interface.h"
int foo(const char* file_name, const ... | [
"Using and compiling your C++ code, I can only repeat the code I already stated in my last answer:\nIn [1]: import ctypes\n\nIn [2]: lib = ctypes.CDLL(\"libfoo.so.1.0\")\n\nIn [3]: names = (ctypes.c_char_p*4)()\n\nIn [4]: names[0] = \"NAME0\"\n\nIn [5]: names[1] = \"NAME1\"\n\nIn [6]: names[2] = \"NAME2\"\n\nIn [7]... | [
1
] | [] | [] | [
"c",
"c++",
"ctypes",
"python"
] | stackoverflow_0004687520_c_c++_ctypes_python.txt |
Q:
Using an iterator to print integers
What I want to do is print the integers 0 through 5 in the code below but all I get is an address of the iterator?
def main():
l = []
for i in range(0,5):
l.append(i)
it = iter(l)
for i in range(0,5):
print it
it.next()
if __name__ == ... | Using an iterator to print integers | What I want to do is print the integers 0 through 5 in the code below but all I get is an address of the iterator?
def main():
l = []
for i in range(0,5):
l.append(i)
it = iter(l)
for i in range(0,5):
print it
it.next()
if __name__ == '__main__':
main()
| [
"To access the values returned by an iterator, you use the next() method of the iterator like so:\ntry:\n while True:\n val = it.next()\n print(val)\nexcept StopIteration:\n print(\"Iteration done.\")\n\nnext() has both the purpose of advancing the iterator and returning the next element. StopIt... | [
9,
3,
3
] | [] | [] | [
"iterator",
"list",
"printing",
"python"
] | stackoverflow_0004687657_iterator_list_printing_python.txt |
Q:
Compacting a Python Application into a Single Source File
I have a strange situation where I need to upload a Python source file to a testing server for evaluation, but I want to keep my application organized into multiple files/modules/packages. Unfortunately, the testing server is out of my control, so I can't m... | Compacting a Python Application into a Single Source File | I have a strange situation where I need to upload a Python source file to a testing server for evaluation, but I want to keep my application organized into multiple files/modules/packages. Unfortunately, the testing server is out of my control, so I can't modify it to allow me to upload a ZIP file containing my code.
I... | [
"If you can't upload a zip file, perhaps you can follow some of the suggestions contained here. The idea is to create and upload a script file which contains a Python shebang line (ignored by the interpreter) prepended to a zip file archive. You can then either let the Python interpreter read the zip file directl... | [
4
] | [] | [] | [
"python",
"scripting"
] | stackoverflow_0004687167_python_scripting.txt |
Q:
Connecting to Google app email servers in Python to send from an alias
I'm looking to send many emails via Python and would like to connect to Google's email servers to send it from my company email address (it's for work). I've got working code for sending the email through the old company email (user@work.com) w... | Connecting to Google app email servers in Python to send from an alias | I'm looking to send many emails via Python and would like to connect to Google's email servers to send it from my company email address (it's for work). I've got working code for sending the email through the old company email (user@work.com) which is our login, but can't figure out how to send it through the alias (us... | [
"If I understand properly, what you are trying to do is get the Google App Engine send an email on behalf of logged in user, who is using his Google Apps Account name to login. Is it right?\nIn that case, the mail API for App Engine informs about the mail.send_mail() wherein From: address can be the current user ... | [
1
] | [] | [] | [
"email",
"google_apps",
"python"
] | stackoverflow_0004688019_email_google_apps_python.txt |
Q:
Filtering Data in a Text File with Python
I'm new to Python (like Zygote new), and it's just to supplement another program but what I need is I have a text file that's a group of items for a game and it is formatted so:
[1]
Name=Blah
Faction=Blahdiddly
Cost=1000
[2]
Name=Meh
Faction=MehMeh
Cost=2000
[3]
Name=Lol... | Filtering Data in a Text File with Python | I'm new to Python (like Zygote new), and it's just to supplement another program but what I need is I have a text file that's a group of items for a game and it is formatted so:
[1]
Name=Blah
Faction=Blahdiddly
Cost=1000
[2]
Name=Meh
Faction=MehMeh
Cost=2000
[3]
Name=Lollypop
Faction=Blahdiddly
Cost=100
And I need t... | [
"As Senthil indicates, ConfigParser is what you really want to read such a file. However, it doesn't provide an easy way to filter things the way you want. You can do it (get a list of the sections, see if the key is in each section, and if so, whether it has the desired value, and if so, record the section), but s... | [
4,
1
] | [] | [] | [
"file",
"filter",
"python",
"text"
] | stackoverflow_0004688167_file_filter_python_text.txt |
Q:
Does Django have a plugin/app that handles "levels" for users? And certain permissions/rankings for each?
I want to promote users to moderators, admins, etc.
What about scoring and game mechanics? What app takes care of that?
What about moderation? When someone changes a title of a post, it needs 3 more moderator... | Does Django have a plugin/app that handles "levels" for users? And certain permissions/rankings for each? | I want to promote users to moderators, admins, etc.
What about scoring and game mechanics? What app takes care of that?
What about moderation? When someone changes a title of a post, it needs 3 more moderators to approve it before it takes affect.
| [
"Using django's built in authentication module, you could create specific \"Groups\" to assign permissions to, and then promote users by re-assigning the groups they belong to.\nhttp://docs.djangoproject.com/en/dev/topics/auth/\nFor specific approvals and use cases you will probably need to write your own handling.... | [
1
] | [] | [] | [
"django",
"plugins",
"python"
] | stackoverflow_0004688165_django_plugins_python.txt |
Q:
connect website to paypal
Is there a possibility of connecting paypal account to website? Such as facebook connect? I want to make a verification tool which:
1. takes me to paypal website
2. wants me to log in
3. redirects me back to my website and sends some authorization data.
Is it possible to do it?
A:
Paypa... | connect website to paypal | Is there a possibility of connecting paypal account to website? Such as facebook connect? I want to make a verification tool which:
1. takes me to paypal website
2. wants me to log in
3. redirects me back to my website and sends some authorization data.
Is it possible to do it?
| [
"Paypal has great documentation on how to connect to it, including some SDK's and sample code (I don't see anything in Python, though). See https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_documentation\nIf you follow dcrodjer's link, you'll eventually find a link to a project cal... | [
3,
0
] | [] | [] | [
"django",
"paypal",
"python"
] | stackoverflow_0004668259_django_paypal_python.txt |
Q:
Getting shell output with Python?
I have a shell script that gets whois info for domains, and outputs taken or available to the shell depending on the domain.
I'd like to execute the script, and be able to read this value inside my Python script.
I've been playing around with subprocess.call but can't figure out h... | Getting shell output with Python? | I have a shell script that gets whois info for domains, and outputs taken or available to the shell depending on the domain.
I'd like to execute the script, and be able to read this value inside my Python script.
I've been playing around with subprocess.call but can't figure out how to get the output.
e.g.,
subprocess... | [
"subprocess.call() does not give you the output, only the return code. For the output you should use subprocess.check_output() instead. These are friendly wrappers around the popen family of functions, which you could also use directly.\nFor more details, see: http://docs.python.org/library/subprocess.html\n",
"M... | [
8,
6,
5,
1
] | [] | [] | [
"linux",
"python",
"shell"
] | stackoverflow_0004676749_linux_python_shell.txt |
Q:
What to reference in the shebang python26 or python2.6
For a Python script I need a specific Python version. Now my installation of Python 2.6 contains both python26 and python2.6
Which one should I put in the shebang?
Option 1:
#!/usr/bin/env python2.6
Option 2:
#!/usr/bin/env python26
EDIT: Yes, there is a rea... | What to reference in the shebang python26 or python2.6 | For a Python script I need a specific Python version. Now my installation of Python 2.6 contains both python26 and python2.6
Which one should I put in the shebang?
Option 1:
#!/usr/bin/env python2.6
Option 2:
#!/usr/bin/env python26
EDIT: Yes, there is a reason not to use plain python. In some of our environments in ... | [
"You can't always guarantee that the shebang will be used (or even that the user will have that version).\nYou shouldn't really limit to a specific version exactly. It's best to require at least a given version (if your code works on Python 2.6, why wouldn't it work on Python 2.7? I might not have Python 2.6 instal... | [
8,
3
] | [
"Why don't you just use /usr/bin/python instead? Is there any reason for not doing that?\nIf you don't have it already, you can create a link to it using this command:\nln -s /usr/bin/python26 /usr/bin/python\nThis ensures compatibility if you ever upgrade your python in the future.\n"
] | [
-1
] | [
"python",
"shebang"
] | stackoverflow_0004689233_python_shebang.txt |
Q:
android.bluetooth.BluetoothSocket cannot connect
I've tried all the suggestions in other comments without avail and I hope someone can help me. I've been struggling with this problem for three days now. I'm quite sure my UUIDs are correct and I know that the bluetooth access is enabled in the manifest.
I'm trying ... | android.bluetooth.BluetoothSocket cannot connect | I've tried all the suggestions in other comments without avail and I hope someone can help me. I've been struggling with this problem for three days now. I'm quite sure my UUIDs are correct and I know that the bluetooth access is enabled in the manifest.
I'm trying to connect my android application to a python server r... | [
"Your code looks generally good, I assume you just copy and paste it from some examples. \nThere is a bug in some Android phones such as HTC desire, which cause method device.createRfcommSocketToServiceRecord to fail. I would suggest following approach:\n1) Trying to chat between two linux computer using pythong sc... | [
3
] | [] | [] | [
"android",
"bluetooth",
"python",
"sockets"
] | stackoverflow_0004395386_android_bluetooth_python_sockets.txt |
Q:
Separate first, middle and last names (Python)
I have a list of several hundred members that I want to separate by First Name, Middle Name and Last name, but some of the members have prefixes (denoted by 'P'). All possible combinations:
First Middle Last
P First Middle Last
First P Middle Last
P First p Middle Las... | Separate first, middle and last names (Python) | I have a list of several hundred members that I want to separate by First Name, Middle Name and Last name, but some of the members have prefixes (denoted by 'P'). All possible combinations:
First Middle Last
P First Middle Last
First P Middle Last
P First p Middle Last
How do I separate First (with P, if available), M... | [
"How about this complete test script:\nimport sys\n\ndef process(file):\n for line in file:\n arr = line.split()\n if not arr:\n continue\n last = arr.pop()\n n = len(arr)\n if n == 4:\n first, middle = ' '.join(arr[:2]), ' '.join(arr[2:])\n elif n ... | [
2,
2,
1,
1,
0,
0
] | [
"Here's another solution (obtained by making changes to source code given in question) :\nimport csv\ninPath = \"input.txt\"\noutPath = \"output.txt\"\n\nnewlist = []\n\nfile = open(inPath, 'rU')\nif file:\n for line in file:\n member = line.split()\n newlist.append(member)\n file.close()\nelse:... | [
-1,
-2
] | [
"python"
] | stackoverflow_0004678132_python.txt |
Q:
Python asyncore & dbus
Is it possible to integrate asyncore with dbus through the same main loop?
Usually, DBus integration is done through glib main loop: is it possible to have either asyncore integrate this main loop or have dbus use asyncore's ?
A:
asyncore sucks. glib already provides async stuff, so just ... | Python asyncore & dbus | Is it possible to integrate asyncore with dbus through the same main loop?
Usually, DBus integration is done through glib main loop: is it possible to have either asyncore integrate this main loop or have dbus use asyncore's ?
| [
"asyncore sucks. glib already provides async stuff, so just use glib's mainloop to do everything.\n",
"I wrote a trivial GSource wrapper for one of my own projects called AsyncoreGSource\nJust attach it to an appropriate MainContext:\nsource = AsyncoreGSource([socket_map])\nsource.attach([main_context])\n\nNatura... | [
7,
1,
0
] | [] | [] | [
"asyncore",
"dbus",
"python"
] | stackoverflow_0002149358_asyncore_dbus_python.txt |
Q:
Python collections of non-base type?
I'm learning python, and I'm a bit confused about which the purpose of the different data structures like list, tuples, dictionaries, sets.
For example, let's say cars are defined by Brand,Model,Horsepower
I wish to have a collection of cars on which I could
sort by Horsepower... | Python collections of non-base type? | I'm learning python, and I'm a bit confused about which the purpose of the different data structures like list, tuples, dictionaries, sets.
For example, let's say cars are defined by Brand,Model,Horsepower
I wish to have a collection of cars on which I could
sort by Horsepower, or brand
compare by model (to erase dupl... | [
"Like most things, there's more than one possible approach.\nUsing a class\nThe neatest would probably be to make a Car class. You don't need to redefine operators - just have some properties and a constructor.\nclass Car:\n def __init__(self, brand, model, hp):\n self.brand = brand\n self.model = ... | [
2,
0
] | [] | [] | [
"collections",
"python"
] | stackoverflow_0004689837_collections_python.txt |
Q:
Network programming issue
I have written a client server program in which the server sends a program to the client, and the client executes the received program. In this case it is a line drawing program in OpenGL. The problem is that on running the server and client the whole program i.e. sending of the program t... | Network programming issue | I have written a client server program in which the server sends a program to the client, and the client executes the received program. In this case it is a line drawing program in OpenGL. The problem is that on running the server and client the whole program i.e. sending of the program to server and client execution t... | [
"1. a TCP socket is a stream (packets are an implementation detail)\nthe network stack is optimized in order to limit the number of packets sent. thus, when you call send() multiple times on a socket, the network stack is free to split (or not split) the data between multiple packets. \non a computer running on a r... | [
4
] | [] | [] | [
"networking",
"python"
] | stackoverflow_0004690155_networking_python.txt |
Q:
Windows 7 default programs and Python
I'm making photo viewing application for Windows 7 using Python 2.6. I'd like to make it so that my program automatically becomes the default photo-viewer on Windows, how would I go about this?
A:
Maybe this can help: Add your program to "Default Programs" in Windows 7
| Windows 7 default programs and Python | I'm making photo viewing application for Windows 7 using Python 2.6. I'd like to make it so that my program automatically becomes the default photo-viewer on Windows, how would I go about this?
| [
"Maybe this can help: Add your program to \"Default Programs\" in Windows 7\n"
] | [
1
] | [] | [] | [
"default",
"python",
"tkinter",
"windows_7"
] | stackoverflow_0004690304_default_python_tkinter_windows_7.txt |
Q:
Sorting dictionary keys based on their values
I have a python dictionary setup like so
mydict = { 'a1': ['g',6],
'a2': ['e',2],
'a3': ['h',3],
'a4': ['s',2],
'a5': ['j',9],
'a6': ['y',7] }
I need to write a function which returns the ordered keys in a list, d... | Sorting dictionary keys based on their values | I have a python dictionary setup like so
mydict = { 'a1': ['g',6],
'a2': ['e',2],
'a3': ['h',3],
'a4': ['s',2],
'a5': ['j',9],
'a6': ['y',7] }
I need to write a function which returns the ordered keys in a list, depending on which column your sorting on so for exa... | [
"Wouldn't it be much easier to use\nsorted(d, key=lambda k: d[k][1])\n\n(with d being the dictionary)?\n",
">>> L = sorted(d.items(), key=lambda (k, v): v[1])\n>>> L\n[('a2', ['e', 2]), ('a4', ['s', 2]), ('a3', ['h', 3]), ('a1', ['g', 6]), ('a6', ['y', 7]), ('a5', ['j', 9])]\n\n>>> map(lambda (k,v): k, L)\n['a2',... | [
55,
10,
3,
2,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0004690094_python_sorting.txt |
Q:
Python error, " 'module' object has no attribute 'lstrip' "
Python documentation from http://docs.python.org/library/string.html :
string.lstrip(s[, chars])
Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars mus... | Python error, " 'module' object has no attribute 'lstrip' " | Python documentation from http://docs.python.org/library/string.html :
string.lstrip(s[, chars])
Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from... | [
"Documentation for py3k version is located here: http://docs.python.org/py3k/index.html\nstring functions were removed in py3k and you have to use now str methods:\n>>> x = 'Hi'\n>>> x.lstrip('H')\n'i'\n\nNote, that as documentation says, chars must be a string. Not an integer.\n",
"For Python 2.6 the following w... | [
9,
4,
1,
1,
1
] | [] | [] | [
"python",
"python_3.x",
"string"
] | stackoverflow_0004690378_python_python_3.x_string.txt |
Q:
How do you move a user to a different OU using Python
I've been having a play with the fantastic active_directory module from Tim Golden and the extensive python-ldap module and while I see a great slew of articles on how to query, modify, create and delete entries within Active Directory from python I can't for t... | How do you move a user to a different OU using Python | I've been having a play with the fantastic active_directory module from Tim Golden and the extensive python-ldap module and while I see a great slew of articles on how to query, modify, create and delete entries within Active Directory from python I can't for the life of me find any advise on moving a user to a differe... | [
"Ok I've solved it, and its rather nice too.\nThis is a windows only solution I'm afraid as this uses the pywin32 module (though under python-ldap you have modrdn so you can solve it there too)\nOk Here is how to move user \"jimboface\" to OU \"happyland\"\nimport active_directory\n\nuser = active_directory.find_us... | [
4
] | [] | [] | [
"active_directory",
"ldap",
"python",
"pywin32"
] | stackoverflow_0004678748_active_directory_ldap_python_pywin32.txt |
Q:
Plotting system of (implicit) equations in matplotlib
First off, I'm new to python and matplotlib. I need to plot several systems of implicit equations in one figure.
The equations are in form of:
3x+2y=1
Is there an easy way to plot these, other than first making the equations explicit (i.e. y=...)?
A:
import ... | Plotting system of (implicit) equations in matplotlib | First off, I'm new to python and matplotlib. I need to plot several systems of implicit equations in one figure.
The equations are in form of:
3x+2y=1
Is there an easy way to plot these, other than first making the equations explicit (i.e. y=...)?
| [
"import numpy as np\nimport matplotlib.pyplot as plt\n# Note the order of y,x.\ny,x=np.ogrid[-5:5:100j,-5:5:100j]\nplt.contour(x.ravel(),y.ravel(),3*x+2*y,[1])\nplt.show()\n\n\n",
"You can use contour() to do implicit plots in two space dimensions:\nx = numpy.linspace(-2., 2.)\ny = numpy.linspace(-2., 2.)[:, None... | [
7,
4
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0004690471_matplotlib_plot_python.txt |
Q:
Redirect python interactive help()
I'm working on a interactive python shell for an application using Qt. However I can't seem to get the interactive help to redirect. I have this in my python code:
class OutputCatcher:
def __init__(self):
self.data = ''
def write(self, stuff):
self.data ... | Redirect python interactive help() | I'm working on a interactive python shell for an application using Qt. However I can't seem to get the interactive help to redirect. I have this in my python code:
class OutputCatcher:
def __init__(self):
self.data = ''
def write(self, stuff):
self.data += stuff
sys.stdout = OutputCatcher()
... | [
"Help doesn't just dump to stdout, but interacts with the terminal. It also is never meant to be used outside of the shell, so it wouldn't be written to guarantee such things work.\nWhat you are trying to do is implement a terminal and that is a non-trivial task, but there are probably existing terminal emulation l... | [
2,
2
] | [] | [] | [
"pyqt4",
"python",
"qt"
] | stackoverflow_0004690768_pyqt4_python_qt.txt |
Q:
My python program always brings down my internet connection after several hours running, how do I debug and fix this problem?
I'm writing a python script checking/monitoring several server/websites status(response time and similar stuff), it's a GUI program and I use separate thread to check different server/websi... | My python program always brings down my internet connection after several hours running, how do I debug and fix this problem? | I'm writing a python script checking/monitoring several server/websites status(response time and similar stuff), it's a GUI program and I use separate thread to check different server/website, and the basic structure of each thread is using an infinite while loop to request that site every random time period(15 to 30 s... | [
"This may or may not be the problem but it's a good idea to always use context managers when dealing with things that opens resources, like files or urls.\nSince Python 2.5 you can do this with files:\nwith open('/tmp/filename', 'rt') as infile:\n data = infile.read()\n whatever(data)\n\nAnd the file will be ... | [
3,
0
] | [] | [] | [
"mechanize",
"multithreading",
"network_programming",
"python",
"urllib2"
] | stackoverflow_0004690890_mechanize_multithreading_network_programming_python_urllib2.txt |
Q:
Is it possible to include OpenOffice Writer or MS Word data in a ReportLab generated PDF?
The desire is to have the user provide information in an OpenOffice Writer or MS Word file that is inserted into part of a ReportLab generated PDF. I am comfortable with ReportLab; but, I don't have any experience with using ... | Is it possible to include OpenOffice Writer or MS Word data in a ReportLab generated PDF? | The desire is to have the user provide information in an OpenOffice Writer or MS Word file that is inserted into part of a ReportLab generated PDF. I am comfortable with ReportLab; but, I don't have any experience with using Writer or Word data in this way. How would you automate the process of pulling in the Writer/Wo... | [
"You can not embed such objects as is within a PDF, adobe specification does not support that. However you could always parse the data from the Office document and reproduce it as a table/graph/etc using reportlab in the output PDF. If you don't care about the data being an actual text you could always save it in t... | [
0
] | [] | [] | [
"ms_word",
"openoffice_writer",
"python",
"reportlab"
] | stackoverflow_0004478478_ms_word_openoffice_writer_python_reportlab.txt |
Q:
In python how to get name of a class inside its static method
how to get name of a class inside static method, i have inheritance
and want name of derived class
IN following example what shall be there in place of XXX in method my_name()
class snake()
@staticmethod
def my_name():
print XXX.__name___... | In python how to get name of a class inside its static method | how to get name of a class inside static method, i have inheritance
and want name of derived class
IN following example what shall be there in place of XXX in method my_name()
class snake()
@staticmethod
def my_name():
print XXX.__name___
class python (snake)
pass
class cobra (snake)
pass
python.... | [
"I'm pretty sure that this is impossible for a static method. Use a class method instead:\nclass Snake(object):\n @classmethod\n def my_name(cls): \n print cls.__name__\n\n",
"A static method in Python is for all intents and purposes just a function. It knows nothing about the class, so you should ... | [
58,
12
] | [] | [] | [
"python"
] | stackoverflow_0004691925_python.txt |
Q:
Django: How to manipulate a Model object before adding it to DB?
In Python-Django, I've got a Model with a FileField member in it. This member stores video files.
I'd like to "interfere" with the standard "add model row/object/instance" proecdure of Django, and manipulate each video I'm adding, before actually com... | Django: How to manipulate a Model object before adding it to DB? | In Python-Django, I've got a Model with a FileField member in it. This member stores video files.
I'd like to "interfere" with the standard "add model row/object/instance" proecdure of Django, and manipulate each video I'm adding, before actually committing or adding it to database.
The manipulation is to convert the v... | [
"You can either override save() or use signals.\nHowever, converting the video will take a lot of time. It is probably not a good idea to do that synchronously in your web request. A common approach is to offload the work to a task queue. Have a look at Celery for that.\n",
"Or you can use django signals to trigg... | [
5,
3,
3,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004691729_django_python.txt |
Q:
How to print source code lines in python logger
Is there some relatively simple way to programmatically include source code lines to python logger report. For example...
import logging
def main():
something_is_not_right = True
logging.basicConfig(level=logging.DEBUG,
format=('%(fil... | How to print source code lines in python logger | Is there some relatively simple way to programmatically include source code lines to python logger report. For example...
import logging
def main():
something_is_not_right = True
logging.basicConfig(level=logging.DEBUG,
format=('%(filename)s: '
'%(lev... | [
"import inspect\nimport logging\nimport linecache\n\ndef main():\n something_is_not_right = True\n logging.basicConfig(level=logging.DEBUG,\n format=('%(filename)s: ' \n '%(levelname)s: '\n '%(funcName)s(): '\n ... | [
21,
5
] | [] | [] | [
"debugging",
"logging",
"python"
] | stackoverflow_0004691575_debugging_logging_python.txt |
Q:
How to improve the look and feel of PyGTK GUI?
Can we somehow customize how PyGtk GUI windows look, by for example - changing the color of the title bar, the grey color of the windows, for a rich feel on the lines of Adobe Flex UI?
A:
GTK's way seems to be that the look is a user choice, not a developer choice.
... | How to improve the look and feel of PyGTK GUI? | Can we somehow customize how PyGtk GUI windows look, by for example - changing the color of the title bar, the grey color of the windows, for a rich feel on the lines of Adobe Flex UI?
| [
"GTK's way seems to be that the look is a user choice, not a developer choice.\nSo, the user can change the GTK Theme, and that will affect all gtk apps, including yours.\nTake a look at some themes here.\n"
] | [
2
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0004687755_pygtk_python.txt |
Q:
Is there a usecase for nested classes?
I've recently seen several people doing things like this here on Stackoverflow:
class A:
foo = 1
class B:
def blah(self):
pass
In other words, they have nested classes. This works (although people new to Python seem to run into problems because i... | Is there a usecase for nested classes? | I've recently seen several people doing things like this here on Stackoverflow:
class A:
foo = 1
class B:
def blah(self):
pass
In other words, they have nested classes. This works (although people new to Python seem to run into problems because it doesn't behave like they thought it would)... | [
"The main reason for putting one class in another is to avoid polluting the global namespace with things that are used only inside one class and therefore doesn't belong in the global namespace. This is applicable even to Python, with the global namespace being a namespace of a particular module. For example if you... | [
6,
4,
3,
2,
2,
1,
1,
1
] | [] | [] | [
"c++",
"oop",
"python",
"ruby"
] | stackoverflow_0004482901_c++_oop_python_ruby.txt |
Q:
Choosing a data structure in VB.NET and performing comparison
I'm a Python programmer and VB.NET newbie converting an application from Python to VB.NET (3.5).
In Python, I have a function which returns a list of tuples which I run on two datasets with results like this:
data1 = [(1,"a",2),(5,"c",7)...]
data2 = [(1... | Choosing a data structure in VB.NET and performing comparison | I'm a Python programmer and VB.NET newbie converting an application from Python to VB.NET (3.5).
In Python, I have a function which returns a list of tuples which I run on two datasets with results like this:
data1 = [(1,"a",2),(5,"c",7)...]
data2 = [(1,"a",2),(5,"x",7)...]
Then I want to check if the two data sets ar... | [
"You can use the Tuple(Of T1, T2, T3) generic type, or make your own class.\nEither way, you'll need to create an IEqualityComparer(Of T) for the class; you can then check whether set1.SequenceEqual(set2, New MyComparer()).\nIf you create your own class, you can override Equals() and GetHashCode() instead of creati... | [
1,
1
] | [] | [] | [
"python",
"vb.net"
] | stackoverflow_0004692660_python_vb.net.txt |
Q:
Python argparse mutual exclusive args
How can I make argparse do something like:
[ 'all' | [ pos1 [ pos2 [ pos3 ...]]]] --some --other --flags
where all is a reserved word (making it a flag would not be ok if it doesn't need a - prefix)
Second:
is it possible to have some aliases for named parameters like -h and ... | Python argparse mutual exclusive args | How can I make argparse do something like:
[ 'all' | [ pos1 [ pos2 [ pos3 ...]]]] --some --other --flags
where all is a reserved word (making it a flag would not be ok if it doesn't need a - prefix)
Second:
is it possible to have some aliases for named parameters like -h and --help meaning the same option? Maybe I sho... | [
"add_mutually_exclusive_group() is designed for exactly this - you are trying to add a mutually exclusive group.\nIn regards to the second part of your question, this should do what you want:\nparser.add_argument('-f', '--foobar')\n\n(Note: your question is a bit confusing - there are two questions there and the se... | [
4
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0004692556_argparse_python.txt |
Q:
Creating a list from a Scipy matrix
This is my first post and I'm still a Python and Scipy newcomer, so go easy on me! I'm trying to convert an Nx1 matrix into a python list. Say I have some 3x1 matrix
x = scipy.matrix([1,2,3]).transpose()
My aim is to create a list, y, from x so that
y = [1, 2, 3]
I've tried usi... | Creating a list from a Scipy matrix | This is my first post and I'm still a Python and Scipy newcomer, so go easy on me! I'm trying to convert an Nx1 matrix into a python list. Say I have some 3x1 matrix
x = scipy.matrix([1,2,3]).transpose()
My aim is to create a list, y, from x so that
y = [1, 2, 3]
I've tried using the tolist() method, but it returns [[... | [
"A question for your question\nWhile Sven and Navi have answered your question on how to convert \nx = scipy.matrix([1,2,3]).transpose()\n\ninto a list, I'll ask a question before answering:\n\nWhy are you using an Nx1 matrix instead of an array?\n\nUsing array instead of matrix\nIf you look at the Numpy for Matlab... | [
4,
0,
0
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0004690366_numpy_python_scipy.txt |
Q:
installed new version of python, but django still uses system default
On Dreamhost, I did the following
installed Python 2.7.1 in my ~/opt directory,
added export PATH=$HOME/opt/bin/:$PATH in my .bash_profile
verified with python --version that 2.7.1 was default
installed setuptools 0.6c11-py2.7
installed Django ... | installed new version of python, but django still uses system default | On Dreamhost, I did the following
installed Python 2.7.1 in my ~/opt directory,
added export PATH=$HOME/opt/bin/:$PATH in my .bash_profile
verified with python --version that 2.7.1 was default
installed setuptools 0.6c11-py2.7
installed Django 1.2.4 with /path/to/python2.7 setup.py install
verified version 1.2.4 with ... | [
"Maybe you can change the WSGIPythonExecutable directive in your mod_wsgi configuration?\nTo configure Passenger's Python interpretter, you can follow these steps.\n"
] | [
1
] | [] | [] | [
"django",
"dreamhost",
"python"
] | stackoverflow_0004692816_django_dreamhost_python.txt |
Q:
Testing email sending? - Python/Django
I have a live site, but would like to run a periodic task that would periodically check if various pages and email sending work.
e.g. register page, forgot password page, etc...
I'm having quite a problem figuring out how to do this...
Any ideas? :)
A:
At my workplace we u... | Testing email sending? - Python/Django | I have a live site, but would like to run a periodic task that would periodically check if various pages and email sending work.
e.g. register page, forgot password page, etc...
I'm having quite a problem figuring out how to do this...
Any ideas? :)
| [
"At my workplace we use nagios to monitor, among many things, that the smtp service and web apps are running as it should. For crucial pages, we use the check_http nagios plugin to ensure that the pages are accessible and contain specific keywords.\nYou can set each check to run as frequently as you like, and have ... | [
3
] | [] | [] | [
"django",
"email",
"hmail_server",
"python"
] | stackoverflow_0004692767_django_email_hmail_server_python.txt |
Q:
Autodoc params?
I'm newbie using sphinx. It looks pretty good.
I have almost documented all my project using autodoc, but I want to change one behavior. Reading the documentation, I've seen this: autodoc_member_order, and want to change to 'bysource' value, the point is, where am I supposed to put this value?
Tha... | Autodoc params? | I'm newbie using sphinx. It looks pretty good.
I have almost documented all my project using autodoc, but I want to change one behavior. Reading the documentation, I've seen this: autodoc_member_order, and want to change to 'bysource' value, the point is, where am I supposed to put this value?
Thanks, and I apologize ... | [
"put\nautodoc_member_order = 'bysource'\n\nat the bottom of the config file. \nOf course you need version 1.0, as the docs you linked in the question mention:\n\nChanged in version 1.0: Support for 'bysource'.\n\n"
] | [
13
] | [] | [] | [
"autodoc",
"python",
"python_sphinx"
] | stackoverflow_0004692865_autodoc_python_python_sphinx.txt |
Q:
Pyqt - get CSV from model
I have treeview based on proxymodel based on model.
So I get a table, that can be filtered and sortered.
I just want to export current view of this table to CSV file.
Just what I see, export to a file or print.
I suppose I have to use proxymodel for that, right?
I cant find a method row o... | Pyqt - get CSV from model | I have treeview based on proxymodel based on model.
So I get a table, that can be filtered and sortered.
I just want to export current view of this table to CSV file.
Just what I see, export to a file or print.
I suppose I have to use proxymodel for that, right?
I cant find a method row or something like that.
Really I... | [
"There is a CSV reader/writer for python, which you can use in Frank Osterfeld's solution.\nSee http://docs.python.org/library/csv.html#examples for more examples!\nimport csv\nwriter = csv.writer(open(\"some.csv\", \"wb\"))\nwriter.writerows(someiterable)\n\n",
"I'm not aware of any CSV parser or exporter for QA... | [
3,
2
] | [] | [] | [
"model",
"pyqt",
"python",
"qt"
] | stackoverflow_0004669711_model_pyqt_python_qt.txt |
Q:
geodjango using mysql
I have been working on an application using django and mysql, am trying now to work on the tutorial from this here
http://docs.djangoproject.com/en/1.2/ref/contrib/gis/tutorial/
but it failed the moment I ran syncdb with the following error
AttributeError: 'DatabaseOperations' object has no ... | geodjango using mysql | I have been working on an application using django and mysql, am trying now to work on the tutorial from this here
http://docs.djangoproject.com/en/1.2/ref/contrib/gis/tutorial/
but it failed the moment I ran syncdb with the following error
AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'
Wh... | [
"set django.contrib.gis.db.backends.mysql in your settings.DATABASE engine db config.\n",
"Does your MySQL have spatial data types installed? What do you get if you do:\nCREATE TABLE geom (g GEOMETRY);\n\nIf that doesn't recognise the GEOMETRY type, then you need to upgrade/recompile/reconfigure your MySQL.\n"
] | [
36,
5
] | [] | [] | [
"django",
"geodjango",
"python"
] | stackoverflow_0004578352_django_geodjango_python.txt |
Q:
Anybody know a valid mechanism to detect the degree of similarity between a string and its hashcode?
Suppose I hashed a password and obtained a hashcode for it. I need to find the degree of similarity between the password and its hashcode. Please suggest me some different mechanism for this
A:
This is impossible... | Anybody know a valid mechanism to detect the degree of similarity between a string and its hashcode? | Suppose I hashed a password and obtained a hashcode for it. I need to find the degree of similarity between the password and its hashcode. Please suggest me some different mechanism for this
| [
"This is impossible. That's the entire point of secure hash algorithms that are used, among other things, to hash passwords.\n",
"If you mean the md5 hash of the password, what is known is if you give same string and calculate the md5 hash it, they will produce the same results. There are also cases when two dif... | [
7,
1,
0,
0
] | [] | [] | [
"cryptography",
"python"
] | stackoverflow_0004689456_cryptography_python.txt |
Q:
What tools can I use to view diff of two sections of the same file?
I'm trying to refactor a python module in which the main problem is duplicate code.
Is there any tool that I can use to view diff of two selected sections, so that I can see the difference between those almost-the-same codes?
A:
While I don't th... | What tools can I use to view diff of two sections of the same file? | I'm trying to refactor a python module in which the main problem is duplicate code.
Is there any tool that I can use to view diff of two selected sections, so that I can see the difference between those almost-the-same codes?
| [
"While I don't think the interface is great, check Clone Digger. See the example.\nThe Thinking Craftsman's Tool Kit (TC Toolkit) might make it easier to find the duplicated code, but doesn't seem to offer good visualization.\nEdit: If you're on Willing to pay, Atomiq looks interesting.\nFor good visualization, I h... | [
3,
3,
1,
0
] | [
"Beyond Compare's text compare has an \"Open Clipboard\" command that will put whatever is on the clipboard on one side of the comparison. If you then copy the second function and use the command again it will line them up with differences highlighted.\n"
] | [
-1
] | [
"diff",
"python",
"refactoring"
] | stackoverflow_0004687678_diff_python_refactoring.txt |
Q:
Make python display help screen if no action is given
Let's say a user runs the script w/o giving any paramters. How can I make it so that it defaults to ./myscript.py -h so that it shows them the help info?
parser = optparse.OptionParser()
parser.add_option("-d", "--directory", metavar="DIR",
... | Make python display help screen if no action is given | Let's say a user runs the script w/o giving any paramters. How can I make it so that it defaults to ./myscript.py -h so that it shows them the help info?
parser = optparse.OptionParser()
parser.add_option("-d", "--directory", metavar="DIR",
help="Directory to scan for big files")
parser.add_option(... | [
"if len(sys.argv) == 1:\n parser.print_help()\n\n",
" if len(argv) == 0:\n parser.print_help()\n\n"
] | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004693576_python.txt |
Q:
How to open a directory/folder on a machine on LAN using python?
I am designing a website for a local server on our lan, so that anyone who tires to access that IP from a browser sees a web page and when he clicks on some link on that web page then a directory or some folder from that server should open.
I am usin... | How to open a directory/folder on a machine on LAN using python? | I am designing a website for a local server on our lan, so that anyone who tires to access that IP from a browser sees a web page and when he clicks on some link on that web page then a directory or some folder from that server should open.
I am using python for this purpose and the server is just like another PC with ... | [
"If you just want to redirect the user to your file server, then it sort of depends on what operating system they're using. If everybody's going to be on Windows, then you should be able to include a link to \"//Your-Fileserver-Name/Path1/Path2\". Obviously you have to share the appropriate files on your server u... | [
1
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0004693740_python_sockets.txt |
Q:
Threads, wxpython and statusbar
I'm doing a program in which I'm using a wxStatusBar, when a download starts I start a child thread like this:
def OnDownload(self, event):
child = threading.Thread(target=self.Download)
child.setDaemon(True)
child.start()
Download is another function without parameters... | Threads, wxpython and statusbar | I'm doing a program in which I'm using a wxStatusBar, when a download starts I start a child thread like this:
def OnDownload(self, event):
child = threading.Thread(target=self.Download)
child.setDaemon(True)
child.start()
Download is another function without parameters (except self). I would like to updat... | [
"Most people get directed to the wxPython wiki:\nhttp://wiki.wxpython.org/LongRunningTasks\nI also wrote up a little piece on the subject here:\nhttp://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/\nI don't think I've ever seen your solution before though.\n",
"How are you updating the status bar?\n... | [
1,
0
] | [] | [] | [
"multithreading",
"python",
"statusbar",
"wxpython"
] | stackoverflow_0004692726_multithreading_python_statusbar_wxpython.txt |
Q:
make a tree based on the key of each element in list
>>> s
[{'000000': [['apple', 'pear']]}, {'100000': ['good', 'bad']}, {'200000': ['yeah', 'ogg']}, {'300000': [['foo', 'foo']]}, {'310000': [['#'], ['#']]}, {'320000': ['$', ['1']]}, {'321000': [['abc', 'abc']]}, {'322000': [['#'], ['#']]}, {'400000': [['yeah', '... | make a tree based on the key of each element in list | >>> s
[{'000000': [['apple', 'pear']]}, {'100000': ['good', 'bad']}, {'200000': ['yeah', 'ogg']}, {'300000': [['foo', 'foo']]}, {'310000': [['#'], ['#']]}, {'320000': ['$', ['1']]}, {'321000': [['abc', 'abc']]}, {'322000': [['#'], ['#']]}, {'400000': [['yeah', 'baby']]}]
>>> for i in s:
... print i
...
{'000000': ... | [
"Here's one approach. I'm making the assumption that you can rely on your keys to represent the tree structure properly (no '310000' without '300000' -- that would cause problems, unless you handle missing nodes when you add them to your TreeCtrl.)\nI would start by reorganizing the data, so you can retrieve the a... | [
2,
0
] | [] | [] | [
"list",
"nested",
"python",
"tree",
"wxpython"
] | stackoverflow_0004687739_list_nested_python_tree_wxpython.txt |
Q:
Workflow using virtualenv and pip
I have python2.6 and django1.2.3 already installed on my system (Ubuntu 10.x).
This is the setup i use for most of my projects. But for some projects I need sandboxed environments, different django version, some extra python modules and sometimes even different python version.
So,... | Workflow using virtualenv and pip | I have python2.6 and django1.2.3 already installed on my system (Ubuntu 10.x).
This is the setup i use for most of my projects. But for some projects I need sandboxed environments, different django version, some extra python modules and sometimes even different python version.
So, I am trying to use pip and virtualenv ... | [
"You want to do:\nvirtualenv --python=/path/to/python/version --no-site-packages ENV_NAME\n\nFor example:\nvirtualenv --python=/usr/bin/python2.6 --no-site-packages my_project_env\n\nIf you follow this for your projects you should be able to have a separate configuration for each one.\n",
"I have installed every ... | [
9,
5,
1
] | [] | [] | [
"django",
"python",
"virtualenv"
] | stackoverflow_0004693814_django_python_virtualenv.txt |
Q:
How to query a couchdb view using a composite key?
I have a couchdb view "record_by_date_product" with the following definition:
function(doc) {
emit([doc.logtime, doc.product_id], doc);
}
I am trying to run a query which is something like:
(logtime > fromdate & logtime < todate) & product_id in (1,2,6)
Is th... | How to query a couchdb view using a composite key? | I have a couchdb view "record_by_date_product" with the following definition:
function(doc) {
emit([doc.logtime, doc.product_id], doc);
}
I am trying to run a query which is something like:
(logtime > fromdate & logtime < todate) & product_id in (1,2,6)
Is this possible with this view?
I am also using couchdb pyth... | [
"I think I just found the exact answer:\nDesign a view 'sampleview' which is like:\n{\n \"records_by_date_product\": {\n \"map\": \"function(doc) {\\n emit([doc.prod_id, doc.logtime], doc);\\n}\"\n }\n}\n\nLet us say that the query parameters are:\nprod_id in [1,3]\nfrom_date = '2010-01-01 00:00:00'\nto_... | [
5,
3
] | [
"How about this solution:\n\nI create a view for each product with logtime as the index.\nAccess each view if required and filter theresults using the range - [fromdate todate] \nDo 3 for each product in the input parameters and collate the results\n\nThis has a drawback that for every product we will have to creat... | [
-1
] | [
"composite_key",
"couchdb",
"python"
] | stackoverflow_0004680713_composite_key_couchdb_python.txt |
Q:
Actual SQL statement after bind variables specified
I am trying to log every SQL statement executed from my scripts. However I contemplate one problem I can not overcome.
Is there a way to compute actual SQL statement after bind variables were specified. In SQLite I had to compute the statement to be executed man... | Actual SQL statement after bind variables specified | I am trying to log every SQL statement executed from my scripts. However I contemplate one problem I can not overcome.
Is there a way to compute actual SQL statement after bind variables were specified. In SQLite I had to compute the statement to be executed manually, using code below:
def __sql_to_str__(self, value,a... | [
"The query is never computed as a single string. The actual text of the query and the params are never interpolated and don't produce a real full string with both.\nThat's the whole point of using parameterized queries - you separate the query from the data - preventing sql injections and limitations all in one go,... | [
7,
1,
0
] | [] | [] | [
"cx_oracle",
"oracle",
"python",
"sql"
] | stackoverflow_0004693926_cx_oracle_oracle_python_sql.txt |
Q:
Python Twisted - Prospective Broker and Server-Side Deffereds
Background:
I have a gtk client that uses twisted and perspective broker to perform remote object execution and server/client communication. This works great for me and was a breeze to start working with.
I have amqp (Message Queue/MQ) services that I ... | Python Twisted - Prospective Broker and Server-Side Deffereds | Background:
I have a gtk client that uses twisted and perspective broker to perform remote object execution and server/client communication. This works great for me and was a breeze to start working with.
I have amqp (Message Queue/MQ) services that I also need to communicate from the client.
I have a security model i... | [
"\nOn the server side, how do I defer the response inside one of the servers pb methods?\n\nEasy. Return the Deferred from the remote_ method. Done.\n"
] | [
3
] | [] | [] | [
"amqp",
"deferred",
"pygtk",
"python",
"twisted"
] | stackoverflow_0004694706_amqp_deferred_pygtk_python_twisted.txt |
Q:
Launching python within python and timezone issue
I had to make a launcher script for my django app, and it seems it somehow switches the timezone to GMT (default being +2), and every datetime is two hours behind when using the script. What could be causing that?
Here is the launcher script that I use:
#!/usr/bin/... | Launching python within python and timezone issue | I had to make a launcher script for my django app, and it seems it somehow switches the timezone to GMT (default being +2), and every datetime is two hours behind when using the script. What could be causing that?
Here is the launcher script that I use:
#!/usr/bin/env python
import os
import subprocess
import shlex
im... | [
"Following up on Robert's idea, you might try adding the env parameter to the Popen call. For example:\nimport subprocess\np = subprocess.Popen([\"date\"], env={'TZ':'America/New_York'})\np.wait()\n# Fri Jan 14 14:45:44 EST 2011\n\np = subprocess.Popen([\"date\"], env={'TZ':'Asia/Taipei'})\np.wait()\n# Sat Jan 15 0... | [
3,
1
] | [] | [] | [
"datetime",
"django",
"python",
"timezone"
] | stackoverflow_0004694988_datetime_django_python_timezone.txt |
Q:
How can I block on readline() in python so I don't have to poll?
Possible Duplicate:
tail -f in python with no time.sleep
I am trying to monitor a log file that is being written to (like tail -f), and I can't figure out how to make readline() block once it reaches eof. All of my googling has only turned up solu... | How can I block on readline() in python so I don't have to poll? |
Possible Duplicate:
tail -f in python with no time.sleep
I am trying to monitor a log file that is being written to (like tail -f), and I can't figure out how to make readline() block once it reaches eof. All of my googling has only turned up solutions to make things NON-blocking. Does anyone know a way to make a ... | [
"You can't really 'block without polling'. You have to check if the file has new data for you at some point. When you write constantly updating processes, you have to poll eventually, unless you're writing ISRs (interrupt service routines) in assembly. Even then, the CPU is constantly polling for any pending interr... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004694812_python.txt |
Q:
Regex. Match words that contain special characters or 'http://'
I want to match words that contain special characters or that begin with 'http://'
So this sentence
%he#llo, my website is: http://www.url.com/abcdef123
should turn into this
my website
So far, i have this
re.sub(r"^[^\w]", " ", "%he#llo, my websi... | Regex. Match words that contain special characters or 'http://' | I want to match words that contain special characters or that begin with 'http://'
So this sentence
%he#llo, my website is: http://www.url.com/abcdef123
should turn into this
my website
So far, i have this
re.sub(r"^[^\w]", " ", "%he#llo, my website is: http://www.url.com/abcdef123")
This just removes the symbols,... | [
"For the example string you give, the following regular expression works OK:\n>>> a = '%he#llo, my website is: http://www.url.com/abcdef123'\n>>> re.findall('(http://\\S+|\\S*[^\\w\\s]\\S*)',a)\n['%he#llo,', 'is:', 'http://www.url.com/abcdef123']\n\n... or you can remove those words with re.sub\n>>> re.sub('(http:/... | [
6,
4,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004695143_python_regex.txt |
Q:
Extract all URLS from a page matching a particular pattern in BeautifulSoup
I'm using BeautifulSoup to parse a HTML page. I need to extract all URLs and sentences from a page that match a particular regex pattern. E.g.
http.*?example\.php
How can i do this?
A:
Since you don't care where the URLs are, in tags or... | Extract all URLS from a page matching a particular pattern in BeautifulSoup | I'm using BeautifulSoup to parse a HTML page. I need to extract all URLs and sentences from a page that match a particular regex pattern. E.g.
http.*?example\.php
How can i do this?
| [
"Since you don't care where the URLs are, in tags or in sentences, you could simply run a re.findall() on the raw html you have. Of course, you're gonna have to do better than that piddly little regex. Behold:\n(http|https|ftp)\\://([a-zA-Z0-9\\.\\-]+(\\:[a-zA-Z0-9\\.&%\\$\\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1... | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004694693_beautifulsoup_python.txt |
Q:
Django pdf question with pisa
I want to generate a html template to a pdf file using pisa. I believe I have all the packages I need but I seem to be having problems doing so. Here is my view below so
far what I have done.
EDIT: Here is my latest url, views & template.
url.py
(r'^index/render_pdf/(?P<id>\d+)/$'... | Django pdf question with pisa | I want to generate a html template to a pdf file using pisa. I believe I have all the packages I need but I seem to be having problems doing so. Here is my view below so
far what I have done.
EDIT: Here is my latest url, views & template.
url.py
(r'^index/render_pdf/(?P<id>\d+)/$', render_pdf),
views.py
def fetch_... | [
"I dont know how much this will help, but this is the function i use to render the pdf:\ndef fetch_resources(uri, rel):\n \"\"\"\n Callback to allow pisa/reportlab to retrieve Images,Stylesheets, etc.\n `uri` is the href attribute from the html link element.\n `rel` gives a relative path, but it's not used here.\n\... | [
1,
0
] | [] | [] | [
"django",
"export",
"pdf",
"python",
"views"
] | stackoverflow_0004678723_django_export_pdf_python_views.txt |
Q:
Is there some lispy language that seamlessly integrates with Python?
Is there a language based on S-expressions with powerful macros that allows as seamless integration with Python as Clojure with JVM?
I want to try using such syntax and features while having access to all usual python libraries (including PyQt).
... | Is there some lispy language that seamlessly integrates with Python? | Is there a language based on S-expressions with powerful macros that allows as seamless integration with Python as Clojure with JVM?
I want to try using such syntax and features while having access to all usual python libraries (including PyQt).
| [
"I've been working a project to do this: psil. I have a series of blog posts talking about what I've done. Here's the short manifesto:\n\nPsil is a new general-purpose programming language in the Lisp family of languages. Psil is implemented on top of Python, allowing easy access to existing Python libraries.\n\nBe... | [
8,
2,
0
] | [] | [] | [
"clojure",
"lisp",
"python",
"scheme"
] | stackoverflow_0004632030_clojure_lisp_python_scheme.txt |
Q:
How to pass all Visual Studio 2008 "Macros" to Python script?
[NOTE: This questions is similar to but not the same as this one.]
Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress.... | How to pass all Visual Studio 2008 "Macros" to Python script? | [NOTE: This questions is similar to but not the same as this one.]
Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress. Examples:
ConfigurationName Release
TargetPath ... | [
"You might want to look into PropertySheets. These are files containing Visual C++ settings, including user macros. The sheets can inherit from other sheets and are attached to VC++ projects using the PropertyManager View in Visual Studio. When you create one of these sheets, there is an interface for creating user... | [
2,
0,
0
] | [] | [] | [
"python",
"visual_c++",
"visual_studio",
"visual_studio_2005",
"visual_studio_2008"
] | stackoverflow_0000130587_python_visual_c++_visual_studio_visual_studio_2005_visual_studio_2008.txt |
Q:
Need guidance with logic programming in Python
I have been struggling to create 2 very small logic applications in Python. I am very new to programming and could definitely use some of your guidance, as this would possibly be very easy to someone with experience.
The first is a small program which is to calculate ... | Need guidance with logic programming in Python | I have been struggling to create 2 very small logic applications in Python. I am very new to programming and could definitely use some of your guidance, as this would possibly be very easy to someone with experience.
The first is a small program which is to calculate statistical equations based on numbers input into th... | [
"How about this?\nn = int(raw_input(\"How many numbers?\"))\nnums = []\nfor i in range(n):\n nums[i] = float(raw_input(\"Enter %i th numnber >\" %i))\ns = sum(nums)\ns2 = sum(map(lambda x:x*x,nums))\nmu = s/n\nmu2 = s2/n\nsigma = (mu2-mu)**(0.5)\nerror_in_mean = sigma/(n)**(0.5)\n\nprint \"x_i\\tx_i-mu\\t(x_i-mu... | [
1,
1
] | [] | [] | [
"deviation",
"logic",
"python",
"statistics"
] | stackoverflow_0004695403_deviation_logic_python_statistics.txt |
Q:
Operation not permitted
I want to run some command in python script
import fcntl
KDSETLED = 0x4B32
SCR_LED = 0x01
console_fd = os.open('/dev/console', os.O_NOCTTY)
fcntl.ioctl(console_fd, KDSETLED, SCR_LED)
I've set a+rw for /dev/console but when I run script from regular user:
fcntl.ioctl(console_fd, KDSETLE... | Operation not permitted | I want to run some command in python script
import fcntl
KDSETLED = 0x4B32
SCR_LED = 0x01
console_fd = os.open('/dev/console', os.O_NOCTTY)
fcntl.ioctl(console_fd, KDSETLED, SCR_LED)
I've set a+rw for /dev/console but when I run script from regular user:
fcntl.ioctl(console_fd, KDSETLED,
SCR_LED) IOError: [Errno... | [
"I believe you need to get your script executed with CAP_SYS_TTY_CONFIG. Either that, or (if you're running on the console), using your controlling tty (e.g., /dev/tty1) instead of /dev/console might work.\nThe kernel code that enforces this appears to be drivers/tty/vt/vt_ioctl.c:\n/*\n * To have permissions to do... | [
4
] | [] | [] | [
"ioctl",
"linux",
"python"
] | stackoverflow_0004695599_ioctl_linux_python.txt |
Q:
Regex to extract all URLs from a page
This question has been asked a few times on SO but I couldn't get any of the answers to work correctly. I need to extract all the URLs in page both in href links and the plain text. I don't need to individual groups of the regex. I need a list of strings i.e. URLs in the page.... | Regex to extract all URLs from a page | This question has been asked a few times on SO but I couldn't get any of the answers to work correctly. I need to extract all the URLs in page both in href links and the plain text. I don't need to individual groups of the regex. I need a list of strings i.e. URLs in the page. Could someone point me to a good working e... | [
"HTML is not a regular language, and thus cannot be parsed by regular expressions.\nIt's possible to make reasonable guesses using regular expressions, and/or to recognize a restricted subset of URIs, but that way lies madness (lengthy debugging processes, inaccurate results).\nThat said, if you're willing to go th... | [
3,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004696418_python_regex.txt |
Q:
ftp.retrbinary() help python
I have created a python script to connect to a remserver.
datfile = []
for dk in range(len(files)):
dfnt=files[dk]
dpst=dfnt.find('.dat')
if dpst == 15:
dlist = dfnt[:]
datfile.append(dlist)
assert datfile == ['a.dat','b.dat']
# True
Which as you can see creates... | ftp.retrbinary() help python | I have created a python script to connect to a remserver.
datfile = []
for dk in range(len(files)):
dfnt=files[dk]
dpst=dfnt.find('.dat')
if dpst == 15:
dlist = dfnt[:]
datfile.append(dlist)
assert datfile == ['a.dat','b.dat']
# True
Which as you can see creates a list. Now I am passing this lis... | [
"It's telling you that you aren't supplying enough arguments to the retrbinary method.\nThe documentation specifies that you must also supply a 'callback' function that gets called for every block of data received. You'll want to write a callback function and do something with the data it gives you (e.g. write it ... | [
31
] | [] | [] | [
"ascii",
"binary",
"ftp",
"python"
] | stackoverflow_0004696413_ascii_binary_ftp_python.txt |
Q:
How would I make this query in Django?
class Content(models.Model):
author = models.ForeignKey('auth.User')
stamp = models.CharField(max_length=50)
class Comments(models.Model):
content = models.ForeignKey(Content)
message = models.TextField()
I want to get all the comments for content that the c... | How would I make this query in Django? | class Content(models.Model):
author = models.ForeignKey('auth.User')
stamp = models.CharField(max_length=50)
class Comments(models.Model):
content = models.ForeignKey(Content)
message = models.TextField()
I want to get all the comments for content that the current logged in user created.
But this doe... | [
"Use field lookups:\nComments.objects.filter(content__author=request.user)\n\n\nDjango offers a powerful and intuitive way to \"follow\" relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across models, s... | [
6
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0004696619_database_django_mysql_python.txt |
Q:
Sorting bytes in words, tuples in python
I looked around and I can't seem to find the proper way of sorting a 32 entry tuple by inverting every odd and even entry.
ex:
1 0 3 2 5 4 7 6 9 8
to
0 1 2 3 4 5 6 7 8 9
My current code looks like this
i=0
nd = []
while i < len(self.r.ipDeviceName):
print(i)
if i%2... | Sorting bytes in words, tuples in python | I looked around and I can't seem to find the proper way of sorting a 32 entry tuple by inverting every odd and even entry.
ex:
1 0 3 2 5 4 7 6 9 8
to
0 1 2 3 4 5 6 7 8 9
My current code looks like this
i=0
nd = []
while i < len(self.r.ipDeviceName):
print(i)
if i%2:
nd[i]=self.r.ipDeviceName[i-1]
els... | [
"Tuples are immutable - you can't modify them once they are created. To modify individual elements you want to store the data in a mutable collection such as a list instead. You can use the built-in functions list and tuple to convert from tuple to list or vice versa.\nAlternatively you could use zip and a function... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004695988_python.txt |
Q:
Using regex to find data in Python
I am new to python, and developing in general. Let me give an example what I am trying to do.
I want to find the text name="username" type="hidden" value="blah" and I only want to pull the "blah"
How would I begin to go about that?
A:
You can use regex groups to pick out rele... | Using regex to find data in Python | I am new to python, and developing in general. Let me give an example what I am trying to do.
I want to find the text name="username" type="hidden" value="blah" and I only want to pull the "blah"
How would I begin to go about that?
| [
"You can use regex groups to pick out relevant parts of a match.\n#!/usr/bin/env python\n\ns = \"\"\" Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do\neiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim\nveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex e... | [
3,
2,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004696640_python_regex.txt |
Q:
How do I use the max function in Python?
num = request.GET.get("num",20)
By default, the num is 20. But, if the user passes in 100, how can I set num to 50? (the max that I allow?)
A:
Just add one more line:
num = int(request.GET.get("num", 20))
if num > 50:
num = 50
Or, if you want to use min you could wr... | How do I use the max function in Python? | num = request.GET.get("num",20)
By default, the num is 20. But, if the user passes in 100, how can I set num to 50? (the max that I allow?)
| [
"Just add one more line:\nnum = int(request.GET.get(\"num\", 20))\nif num > 50:\n num = 50\n\nOr, if you want to use min you could write:\n# \"num\" parameter assumed to be convertable to an `int`\nnum = min(int(request.GET.get(\"num\", 20)), 50)\n\n",
"Actually, you should use min rather than max:\nnum = int(... | [
7,
6
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004697009_django_python.txt |
Q:
Python: Split string by list of separators
In Python, I'd like to split a string using a list of separators. The separators could be either commas or semicolons. Whitespace should be removed unless it is in the middle of non-whitespace, non-separator characters, in which case it should be preserved.
Test case 1: A... | Python: Split string by list of separators | In Python, I'd like to split a string using a list of separators. The separators could be either commas or semicolons. Whitespace should be removed unless it is in the middle of non-whitespace, non-separator characters, in which case it should be preserved.
Test case 1: ABC,DEF123,GHI_JKL,MN OP
Test case 2: ABC;DEF123;... | [
"This should be much faster than regex and you can pass a list of separators as you wanted:\ndef split(txt, seps):\n default_sep = seps[0]\n\n # we skip seps[0] because that's the default separator\n for sep in seps[1:]:\n txt = txt.replace(sep, default_sep)\n return [i.strip() for i in txt.split... | [
28,
6,
2,
1
] | [] | [] | [
"python",
"regex",
"separator",
"split"
] | stackoverflow_0004697006_python_regex_separator_split.txt |
Q:
Using gae-sessions between domains
I'm using gae-sessions library for session management in my GAE app. I want to this app to be a registration and login center for several other GAE apps. I mean when user enters one of the others app (let's say "client app" - this app also is using gae-sessions), and want to log ... | Using gae-sessions between domains | I'm using gae-sessions library for session management in my GAE app. I want to this app to be a registration and login center for several other GAE apps. I mean when user enters one of the others app (let's say "client app" - this app also is using gae-sessions), and want to log in, its credentials are submitted to the... | [
"You could do this if your apps are subdomains of a particular domain:\n\nAdd the Domain key to COOKIE_FMT (in gae-sessions source file) to indicate that the cookie from the \"central app\" should be sent to all subdomains (if your domain was xyz.com then you would want the cookie's domain value to be set to .xyz.c... | [
1
] | [] | [] | [
"google_app_engine",
"python",
"session"
] | stackoverflow_0004689965_google_app_engine_python_session.txt |
Q:
Is there an alternative to gobject.timeout_add() in Python?
I'm using gobject.timeout_add() to display a timer in my project (dojotools).
I was wondering if there is any other way to achieve the same results, but without the gobject dependency.
The requirement is just calling a method repeatedly, in a certain time... | Is there an alternative to gobject.timeout_add() in Python? | I'm using gobject.timeout_add() to display a timer in my project (dojotools).
I was wondering if there is any other way to achieve the same results, but without the gobject dependency.
The requirement is just calling a method repeatedly, in a certain time interval.
| [
"You can use a thread with time.sleep(interval) to achieve the same effect.\nimport thread, time\n\ndef timer():\n while True:\n time.sleep(1)\n # do something here\n\nthread.start_new_thread(timer, ())\n\n",
"If you are OK with using TkInter, which should be available on all Pythons (except cell... | [
2,
1
] | [] | [] | [
"gobject",
"python"
] | stackoverflow_0002444665_gobject_python.txt |
Q:
Are query fetch() and iteration effectively the same in App Engine?
With App Engine Version 1.3.6, released Aug-17-2010, the 1000-item fetch() limit was removed.
Does that mean that ModelClass.all().fetch(limit=99999999999) and [e for e in ModelClass.all()] are equivalent?
If they differ, they may differ in subtle... | Are query fetch() and iteration effectively the same in App Engine? | With App Engine Version 1.3.6, released Aug-17-2010, the 1000-item fetch() limit was removed.
Does that mean that ModelClass.all().fetch(limit=99999999999) and [e for e in ModelClass.all()] are equivalent?
If they differ, they may differ in subtle ways. For example, is the number of RPC calls equivalent?
| [
"Though the 1000 entity limit was removed from fetch, you still need to provide an explicit upper bound of your own. Of course, if you make this sufficiently large then you'll retrieve all of your entities.\nThe iterator approach you proposed above is functionally equivalent (if the limit passed to fetch is big en... | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004697542_google_app_engine_python.txt |
Q:
Get the value of specific JSON element in Python
I'm new to Python and JSON, so I'm sorry if I sound clueless. I'm getting the following result from the Google Translate API and want to parse out the value of "translatedText":
{
"data": {
"translations": [
{
"translatedText": "Toute votre base sont appar... | Get the value of specific JSON element in Python | I'm new to Python and JSON, so I'm sorry if I sound clueless. I'm getting the following result from the Google Translate API and want to parse out the value of "translatedText":
{
"data": {
"translations": [
{
"translatedText": "Toute votre base sont appartiennent à nous"
}
]
}
}
This response is simpl... | [
"You can parse the text into an object using the json module in Python >= 2.6:\n>>> import json\n>>> translation = json.loads(\"\"\"{\n... \"data\": {\n... \"translations\": [\n... {\n... \"translatedText\": \"Toute votre base sont appartiennent nous\"\n... },\n... {\n... \"translate\": \"¡Qué ... | [
13
] | [] | [] | [
"json",
"python"
] | stackoverflow_0004697626_json_python.txt |
Q:
Able to ping but cannot browse after several hours running of my python program
It's a GUI program I wrote in python checking website/server status running on my XP SP3, multi threads are used to check different site/server. After several hours running, the program starts to get urlopen error timed out all the tim... | Able to ping but cannot browse after several hours running of my python program | It's a GUI program I wrote in python checking website/server status running on my XP SP3, multi threads are used to check different site/server. After several hours running, the program starts to get urlopen error timed out all the time, and this always happens right after a POST request from a server(not a certain one... | [
"Are you sure you are closing TCP sessions after each request? Try to check netstat information from time to time and if you'll see that the number of active/established sessions is rising it means that you have some problems in your script.\nYes, usually you can ping even if you are out of free TCP sockets.\n"
] | [
3
] | [] | [] | [
"multithreading",
"network_programming",
"python",
"python_multithreading",
"urllib2"
] | stackoverflow_0004697623_multithreading_network_programming_python_python_multithreading_urllib2.txt |
Q:
Set serial port pin high using python
Is it possible to set one pin of the serial port continuously high using python (or C)?
If yes, how?
A:
Using the pyserial methods setRTS(level=True) and setDTR(level=True) you can control the RTS and DTR lines at will. For instance, the following code will toggle the RTS pi... | Set serial port pin high using python | Is it possible to set one pin of the serial port continuously high using python (or C)?
If yes, how?
| [
"Using the pyserial methods setRTS(level=True) and setDTR(level=True) you can control the RTS and DTR lines at will. For instance, the following code will toggle the RTS pin of the first serial port. (See the pyserial documentation for the details).\nimport time\nimport serial\n\nser = serial.Serial(0)\nser.setRTS(... | [
17,
3,
1
] | [] | [] | [
"python",
"serial_port"
] | stackoverflow_0002438848_python_serial_port.txt |
Q:
How does this If conditional work in Python?
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
self... | How does this If conditional work in Python? | from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
self.response.headers['Content-Type'] = 'text/plain'
... | [
"It'll basically check if user is an actual object or None. If it's None, the code will go into the else block and redirect to a \"create login\" page.\n",
"I suspect that users.get_current_user() returns an object, or None if there is no current user. Python interprets None as False in a conditional statement.\... | [
8,
3,
2,
1
] | [] | [] | [
"conditional",
"python"
] | stackoverflow_0004697840_conditional_python.txt |
Q:
How can I find all matches to a regular expression in Python?
In a program I'm writing I have Python use the re.search() function to find matches in a block of text and print the results. However, the program exits once it finds the first match in the block of text.
How do I do this repeatedly where the program do... | How can I find all matches to a regular expression in Python? | In a program I'm writing I have Python use the re.search() function to find matches in a block of text and print the results. However, the program exits once it finds the first match in the block of text.
How do I do this repeatedly where the program doesn't stop until ALL matches have been found? Is there a separate f... | [
"Use re.findall or re.finditer instead.\nre.findall(pattern, string) returns a list of matching strings.\nre.finditer(pattern, string) returns an iterator over MatchObject objects.\nExample:\nre.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')\n# Output: ['cats', 'dogs']\n... | [
786
] | [] | [] | [
"python",
"regex",
"search"
] | stackoverflow_0004697882_python_regex_search.txt |
Q:
python 3.1 - Creating normal distribution
I have scipy and numpy, Python v3.1
I need to create a 1D array of length 3million, using random numbers between (and including) 100-60,000. It has to fit a normal distribution.
Using 'a = numpy.random.standard_normal(3000000)', I get a normal distribution for that requi... | python 3.1 - Creating normal distribution | I have scipy and numpy, Python v3.1
I need to create a 1D array of length 3million, using random numbers between (and including) 100-60,000. It has to fit a normal distribution.
Using 'a = numpy.random.standard_normal(3000000)', I get a normal distribution for that required length; not sure how to achieve the require... | [
"A standard normal distribution has mean 0 and standard deviation 1. What I understand from your requirements is that you need a ((60000-100)/2, (60000-100)/2) one. Take each value from standard_normal() result, multiply it by the new variance, and add the new mean.\nI haven't used NumPy, but a quick search of the ... | [
10,
6
] | [
"try this nice little method:\nYou'll want a method that just makes one random number. \nimport random\nlist = [random.randint(min,max) for i in range(numitems)]\n\nThis will give you a list with numitems random numbers between min and max.\nOf course, 3000000 is a lot of items to have in memory. Consider making th... | [
-4
] | [
"python"
] | stackoverflow_0004697836_python.txt |
Q:
Python Combining strings into the shortest possible string?
If I have a list of strings, I would like to combine them into one string with overlapping characters. If there is no overlapping strings left just add it to the end. Here is an overly simplified version.
input = ['one', 'two']
output = 'twone'
What i'm ... | Python Combining strings into the shortest possible string? | If I have a list of strings, I would like to combine them into one string with overlapping characters. If there is no overlapping strings left just add it to the end. Here is an overly simplified version.
input = ['one', 'two']
output = 'twone'
What i'm looking for as some way to do that with any number of strings in ... | [
"It isn't really good enough to give one trivial example. This is just about the most underspecified question of the (lunar) year. However assuming that overlap can occur only the ends, and each word is tested only twice (against each end of the current output), and you want the maximum overlap, this would do the j... | [
5,
2
] | [] | [] | [
"algorithm",
"python",
"string"
] | stackoverflow_0004697508_algorithm_python_string.txt |
Q:
python - remove string from words in an array
#!/usr/bin/python
#this looks for words in dictionary that begin with 'in' and the suffix is a real word
wordlist = [line.strip() for line in open('/usr/share/dict/words')]
newlist = []
for word in wordlist:
if word.startswith("in"):
newlist.append(word)
fo... | python - remove string from words in an array |
#!/usr/bin/python
#this looks for words in dictionary that begin with 'in' and the suffix is a real word
wordlist = [line.strip() for line in open('/usr/share/dict/words')]
newlist = []
for word in wordlist:
if word.startswith("in"):
newlist.append(word)
for word in newlist:
word = word.split('in')
pri... | [
"#!/usr/bin/env python\n\n# Look for all words beginning with 'in'\n# such that the rest of the word is also\n# a valid word.\n\n# load the dictionary:\nwith open('/usr/share/dict/word') as inf:\n allWords = set(word.strip() for word in inf) # one word per line\n\n\nusing 'with' ensures the file is always prope... | [
2,
1,
1,
0
] | [] | [] | [
"arrays",
"list",
"python",
"string"
] | stackoverflow_0004697779_arrays_list_python_string.txt |
Q:
Can I write a function that detect if it is called from 'with'-statement or not?
More specifically, can I detect if a function is called as EXPR in with EXPR: BLOCK statement?
I am trying to make myself familiar with the usage of with-statement in python. As a first step, I re-implemented an example, which genera... | Can I write a function that detect if it is called from 'with'-statement or not? | More specifically, can I detect if a function is called as EXPR in with EXPR: BLOCK statement?
I am trying to make myself familiar with the usage of with-statement in python. As a first step, I re-implemented an example, which generate marked up text, appeared in the reference of contextlib.contextmanager (ignoring ex... | [
"You're not actually calling tag() \"from\" the with statement. You're calling tag(), then passing the return value from tag() to the with statement, which then calls __enter__ on that passed-in value, then runs the body, then calls __exit__.\nSo no, you can't detect the with statement before it's actually invoked ... | [
5
] | [] | [] | [
"python",
"with_statement"
] | stackoverflow_0004698064_python_with_statement.txt |
Q:
Is there a way to keep lines from being skipped when using csv.dictWriter.writerow(somerow)
I am processing some files and want to create a log of what I am processing. I created the log by using a dictionary to hold the keys and values for each observation and then I am appending the dictionary to a list (a list... | Is there a way to keep lines from being skipped when using csv.dictWriter.writerow(somerow) | I am processing some files and want to create a log of what I am processing. I created the log by using a dictionary to hold the keys and values for each observation and then I am appending the dictionary to a list (a list of dictionaries).
To save the log I am using Python's csv module to write out the list of dictio... | [
"See the documentation at http://docs.python.org/library/csv.html#csv-examples\nThey give a UnicodeWriter class as follows:\nclass UnicodeWriter:\n \"\"\"\n A CSV writer which will write rows to CSV file \"f\",\n which is encoded in the given encoding.\n \"\"\"\n\n def __init__(self, f, dialect=csv.e... | [
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0004697890_csv_python.txt |
Q:
Get the uri of the page in Google App Engine / Django?
I'm using Google App Engine with the standard Django templates found in Webapp.
I wanted to display the permalink to the page the user is on. How do I get the uri?
A:
Should be in self.request.url in your RequestHandler-based class.
| Get the uri of the page in Google App Engine / Django? | I'm using Google App Engine with the standard Django templates found in Webapp.
I wanted to display the permalink to the page the user is on. How do I get the uri?
| [
"Should be in self.request.url in your RequestHandler-based class.\n"
] | [
0
] | [] | [] | [
"django",
"google_app_engine",
"httpwebrequest",
"python"
] | stackoverflow_0004698265_django_google_app_engine_httpwebrequest_python.txt |
Q:
Dictionaries with more than one key per value in Python
I am attempting to create a nice interface to access a data set where each value has several possible keys. For example, suppose that I have both a number and a name for each value in the data set. I want to be able to access each value using either the numbe... | Dictionaries with more than one key per value in Python | I am attempting to create a nice interface to access a data set where each value has several possible keys. For example, suppose that I have both a number and a name for each value in the data set. I want to be able to access each value using either the number OR the name.
I have considered several possible implementat... | [
"In C/C++, I believe that I would use pointers to reference the same piece of \ndata from different keys.\n\nThis would correspond with option number 2. In Python, dictionaries really store pointers to objects. That means that having two keys point to the same object will not create the object twice.\n",
"Are bot... | [
5,
1,
1,
1
] | [] | [] | [
"data_structures",
"map",
"python"
] | stackoverflow_0004698103_data_structures_map_python.txt |
Q:
may be python error!
Hi
I'm not familiar with python, I just want to check something so I tried to run a .py code in linux so I wrote :
./waf wifi-olsr-flowmon --plot
which is a .py program after that whatever I want to run just see these error:
/home/bahar/Desktop/ns/ns-allinone-3.9/ns-allinone-3.9/ns-3.9/wscri... | may be python error! | Hi
I'm not familiar with python, I just want to check something so I tried to run a .py code in linux so I wrote :
./waf wifi-olsr-flowmon --plot
which is a .py program after that whatever I want to run just see these error:
/home/bahar/Desktop/ns/ns-allinone-3.9/ns-allinone-3.9/ns-3.9/wscript: error: Traceback (most... | [
"It means that Python was unable to locate a module named cflags, but the code you're running tries to import it. Perhaps you need to set PYTHONPATH, or install the cflags module.\n(Also, paragraphs are your friend.)\n"
] | [
1
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0004698376_linux_python.txt |
Q:
Printing Graphics in Python
I need to print "Wheel Tags" from python. Wheel tags will have images, lines, and text.
The Python tutorial has two paragraphs about creating postscript files with the image lib. After reading it I still do not know how to lay out the data. I was hoping some one might have samples of h... | Printing Graphics in Python | I need to print "Wheel Tags" from python. Wheel tags will have images, lines, and text.
The Python tutorial has two paragraphs about creating postscript files with the image lib. After reading it I still do not know how to lay out the data. I was hoping some one might have samples of how to layout the images, text and... | [
"See http://effbot.org/imagingbook/psdraw.htm\nNote that:\n\nthe PSDraw module does not appear to have been actively maintained since 2005; I would guess that most of the effort has been redirected into supporting the PDF format instead. You might be happier using pypdf instead;\nit has comments like '# FIXME: inco... | [
3,
1
] | [] | [] | [
"postscript",
"printing",
"python"
] | stackoverflow_0004692375_postscript_printing_python.txt |
Q:
Converting from samplerate/cutoff frequency to pi-radians/sample in a discrete time sampled IIR filter system
I am working on doing some digital filter work using Python and Numpy/Scipy.
I'm using scipy.signal.iirdesign to generate my filter coefficents, but it requires the filter passband coefficents in a format ... | Converting from samplerate/cutoff frequency to pi-radians/sample in a discrete time sampled IIR filter system | I am working on doing some digital filter work using Python and Numpy/Scipy.
I'm using scipy.signal.iirdesign to generate my filter coefficents, but it requires the filter passband coefficents in a format I am not familiar with
wp, ws : float
Passband and stopband edge frequencies, normalized from 0 to 1 (1 correspo... | [
"If your sampling rate is fs, the Nyquist rate is fs/2. This represents the highest representable frequency you can have without aliasing. It is also equivalent to the normalized value of 1 referred to by the documentation. Therefore, if you are designing a low pass filter with a corner frequency of fc, you'd enter... | [
6,
2
] | [] | [] | [
"digital_filter",
"python",
"scipy",
"signal_processing"
] | stackoverflow_0004697235_digital_filter_python_scipy_signal_processing.txt |
Q:
GoogleAppEngine data store isn't returning any records
I'm learning how to use the GoogleAppEngine with Python as the language of choice.
Here's my code:
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.... | GoogleAppEngine data store isn't returning any records | I'm learning how to use the GoogleAppEngine with Python as the language of choice.
Here's my code:
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Greeting(db.Model):
autho... | [
"Well, first of all I'm getting error the following log error (it maybe is just for me):\ndev_appserver_main.py:466] <class 'google.appengine.api.datastore_errors.InternalError'>\nAre you using FloatProperty and/or GeoPtProperty? Unfortunately loading float values from the datastore file does not work with Python 2... | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004697973_google_app_engine_google_cloud_datastore_python.txt |
Q:
How do i tell from a list of methods, which ones have been defined in that class and those that have been inherited?
How do i tell from a list of methods, which ones have been defined in that class and those that have been inherited? Eg. i have a bank module that has two classes, BankAccount and Transactions. Tran... | How do i tell from a list of methods, which ones have been defined in that class and those that have been inherited? | How do i tell from a list of methods, which ones have been defined in that class and those that have been inherited? Eg. i have a bank module that has two classes, BankAccount and Transactions. Transcations inherits from BankAccount
>>> dir(bank.BankAccount)
[ 'chk', 'interest']
>>> dir(bank.Transcations)
[ 'chk', 'd... | [
">>> class BankAccount(object):\n... def deposit(self):\n... pass\n... def account_no(self):\n... pass\n... \n>>> class Transaction(BankAccount):\n... def withdrawal(self):\n... pass\n... \n>>> Transaction.__dict__.keys()\n['__module__', '__doc__', 'withdrawal']\n>>> ... | [
3,
1
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0004698631_inheritance_python.txt |
Q:
Python 3, urllib ... Reset Connection Possible?
In the larger scale of my program the goal of the below code is to filter out all dynamic html in a web-page source code
code snippet:
try:
deepreq3 = urllib.request.Request(deepurl3)
deepreq3.add_header("User-Agent","etc......")
deepdata3 = urllib.reques... | Python 3, urllib ... Reset Connection Possible? | In the larger scale of my program the goal of the below code is to filter out all dynamic html in a web-page source code
code snippet:
try:
deepreq3 = urllib.request.Request(deepurl3)
deepreq3.add_header("User-Agent","etc......")
deepdata3 = urllib.request.urlopen(deepurl3).read().decode("utf8", 'ignore')
... | [
"Try closing the connection after reading the data:\ntry:\n deepreq3 = urllib.request.Request(deepurl3)\n deepreq3.add_header(\"User-Agent\",\"etc......\")\n connection = urllib.request.urlopen(deepurl3)\n deepdata3 = connection.read().decode(\"utf8\", \"ignore\")\n connection.close()\n\n",
"I've m... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"urllib"
] | stackoverflow_0004638698_python_python_3.x_urllib.txt |
Q:
Is it possible to create a Python list and fake populating it?
I am working with Neo4j graph database, and would like to adapt one of the current REST libraries. Imagine a case with a database with 20 nodes.
>>> db = Database("http://localhost:7474")
I would like the API to be as simple as possible, so that it wo... | Is it possible to create a Python list and fake populating it? | I am working with Neo4j graph database, and would like to adapt one of the current REST libraries. Imagine a case with a database with 20 nodes.
>>> db = Database("http://localhost:7474")
I would like the API to be as simple as possible, so that it would be possible to get the 14th node with something similar to this:... | [
"Yes, you can write a custom class that implements __getitem__ and generates a result dynamically.\n>>> class MyDatabase(object):\n... def __getitem__(self, x):\n... if 10 <= x <= 15:\n... return \"foo\"\n... else:\n... raise IndexError('key not in database')\n...\n>>> db... | [
10
] | [] | [] | [
"neo4j",
"python"
] | stackoverflow_0004698755_neo4j_python.txt |
Q:
How to open a large number of file with for loop?
I have tab-delimited file like this
tag1 DATA
tag20 DATA
tag4 DATA
tag3 DATA
tag10 DATA
This data has around 250000 lines. I want to sort these line into file by tag. Line begin with tag1 go into tag1.txt. Line begin with tag2 goto tag2.txt... | How to open a large number of file with for loop? | I have tab-delimited file like this
tag1 DATA
tag20 DATA
tag4 DATA
tag3 DATA
tag10 DATA
This data has around 250000 lines. I want to sort these line into file by tag. Line begin with tag1 go into tag1.txt. Line begin with tag2 goto tag2.txt ... etc.
Is there any clever way to do this with loop ... | [
"import collections\n\nfile_data = collections.defaultdict(list)\n\nwith open(\"you_file\") as f\n for line in file:\n tag, data = line.split('\\t', 1)\n file_data[tag].append(data) \n\nfor file_name, data in file_data.items():\n with open(file_name, 'w') as f:\n f.write(\"\\n\".join(da... | [
2,
1
] | [] | [] | [
"file",
"python"
] | stackoverflow_0004698842_file_python.txt |
Q:
python delayed execution of print command?
In some part of my python program , I need to do this -
print a message on the terminal (using the print command)
make some directories (using os.mkdirs)
copy a file (using shutil.copy2)
Again display a message on terminal (using the print command)
(All this is in a loo... | python delayed execution of print command? | In some part of my python program , I need to do this -
print a message on the terminal (using the print command)
make some directories (using os.mkdirs)
copy a file (using shutil.copy2)
Again display a message on terminal (using the print command)
(All this is in a loop)
Now the problem is, although command '1.' is ... | [
"This might be what you are looking for How to flush output of Python print?\n"
] | [
11
] | [] | [] | [
"printing",
"python"
] | stackoverflow_0004699186_printing_python.txt |
Q:
One-line expression to map dictionary to another
I have dictionary like
d = {'user_id':1, 'user':'user1', 'group_id':3, 'group_name':'ordinary users'}
and "mapping" dictionary like:
m = {'user_id':'uid', 'group_id':'gid', 'group_name':'group'}
All i want to do is "replace" keys in first dictionary with values fr... | One-line expression to map dictionary to another | I have dictionary like
d = {'user_id':1, 'user':'user1', 'group_id':3, 'group_name':'ordinary users'}
and "mapping" dictionary like:
m = {'user_id':'uid', 'group_id':'gid', 'group_name':'group'}
All i want to do is "replace" keys in first dictionary with values from the second one. The expected output is:
d = {'uid':... | [
"Sure:\nd = dict((m.get(k, k), v) for (k, v) in d.items())\n\n",
"Let's take the excellent code from @karlknechtel and see what it does:\n>>> d = dict((m.get(k, k), v) for (k, v) in d.items())\n{'gid': 3, 'group': 'ordinary users', 'uid': 1, 'user': 'user1'}\n\nBut how does it work?\nTo build a dictionary, you ca... | [
25,
24,
9,
2
] | [] | [] | [
"python"
] | stackoverflow_0004698932_python.txt |
Q:
Add custom method to string object
Possible Duplicate:
Can I add custom methods/attributes to built-in Python types?
In Ruby you can override any built-in object class with custom method, like this:
class String
def sayHello
return self+" is saying hello!"
end
end
puts 'JOH... | Add custom method to string object |
Possible Duplicate:
Can I add custom methods/attributes to built-in Python types?
In Ruby you can override any built-in object class with custom method, like this:
class String
def sayHello
return self+" is saying hello!"
end
end
puts 'JOHN'.downcase.sayHello # >>> 'john is s... | [
"You can't because the builtin-types are coded in C. What you can do is subclass the type:\nclass string(str):\n def sayHello(self):\n print(self, \"is saying 'hello'\")\n\nTest:\n>>> x = string(\"test\")\n>>> x\n'test'\n>>> x.sayHello()\ntest is saying 'hello'\n\nYou could also overwrite the str-type wit... | [
27,
3
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0004699179_python_ruby.txt |
Q:
Learning Python - Permutation Error
I'm teaching myself Python. I saw a java permutation generator from a string, and I figured I use the java version and write the Python version myself.
Here is what I wrote in Python:
a = "abc"
a = list(a)
def swap(i,j):
c = a[i]
a[i] = a[j]
a[j] = c
def perm2(n):... | Learning Python - Permutation Error | I'm teaching myself Python. I saw a java permutation generator from a string, and I figured I use the java version and write the Python version myself.
Here is what I wrote in Python:
a = "abc"
a = list(a)
def swap(i,j):
c = a[i]
a[i] = a[j]
a[j] = c
def perm2(n):
if n == 1:
print a
else... | [
"Change len(a) with n :\ndef perm2(n):\n if n == 1:\n print a\n else:\n for i in range(n): # << here\n swap(i, n-1) \n perm2(n-1)\n swap(i, n-1)\n\nResult :\n['b', 'c', 'a']\n['c', 'b', 'a']\n['c', 'a', 'b']\n['a', 'c', 'b']\n['b', 'a', 'c']\n['a', 'b', 'c']\n\n... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0004699423_python.txt |
Q:
Why can't I call del [:] on a dict?
What's going on here?
>>> a = {1: "a", 2: "b"}
>>> del a[1]
>>> a
{2: 'b'}
>>> a = {1: "a", 2: "b"}
>>> del a[:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type
>>> a.clear()
>>> a
{}
Why must I call dict.clear?
A:
a[:] is a... | Why can't I call del [:] on a dict? | What's going on here?
>>> a = {1: "a", 2: "b"}
>>> del a[1]
>>> a
{2: 'b'}
>>> a = {1: "a", 2: "b"}
>>> del a[:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type
>>> a.clear()
>>> a
{}
Why must I call dict.clear?
| [
"a[:] is a quick way to make a shallow copy of a list (and tuple). See towards the bottom of the docs for clarification on different types of copying.\nThus, it would reason to say that del a[:] on a dictionary doesn't really make much sense.\nIf you want to delete the entire dictionary, you can simply do del a\n>>... | [
3,
3,
3,
1,
0
] | [] | [] | [
"datamodel",
"dictionary",
"python"
] | stackoverflow_0004697690_datamodel_dictionary_python.txt |
Q:
What command to use to introspect instances in scala REPL?
In python:
>>> s = "abc"
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', ...
Is there an equivalent way - i.e. dir() function - to do this with instances in the scala REPL ?
A:
When you press the tabulator-key the REPL shows you the m... | What command to use to introspect instances in scala REPL? | In python:
>>> s = "abc"
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', ...
Is there an equivalent way - i.e. dir() function - to do this with instances in the scala REPL ?
| [
"When you press the tabulator-key the REPL shows you the methods which you can call on an object:\nscala> val s = \"abc\"\ns: java.lang.String = abc\n\nscala> s.<tab>\n\n+ asInstanceOf charAt\ncodePointAt codePointBefore codePointCount\ncompareTo compareToIgn... | [
8,
7
] | [] | [] | [
"python",
"scala"
] | stackoverflow_0004698831_python_scala.txt |
Q:
Currently, in Django-notification, everytime I send a notification, it sends the email in plain text
Is there a way to customize the HTML and send a notification email in html?
A:
Just adjust your template, e.g.
https://github.com/pinax/django-notification/blob/master/notification/templates/notification/email_... | Currently, in Django-notification, everytime I send a notification, it sends the email in plain text | Is there a way to customize the HTML and send a notification email in html?
| [
"Just adjust your template, e.g. \n\nhttps://github.com/pinax/django-notification/blob/master/notification/templates/notification/email_body.txt\n\nor add an extra template, e.g. email_body.html. For that you'll have to adjust models.py starting, e.g. here:\n\nhttps://github.com/pinax/django-notification/blob/maste... | [
0
] | [] | [] | [
"css",
"django",
"html",
"notifications",
"python"
] | stackoverflow_0004699047_css_django_html_notifications_python.txt |
Q:
Searching a list of tuples in python
I'm having a database (sqlite) of members of an organisation (less then 200 people). Now I'm trying to write an wx app that will search the database and return some contact information in a wx.grid. The app will have 2 TextCtrls, one for the first name and one for the last name... | Searching a list of tuples in python | I'm having a database (sqlite) of members of an organisation (less then 200 people). Now I'm trying to write an wx app that will search the database and return some contact information in a wx.grid. The app will have 2 TextCtrls, one for the first name and one for the last name. What I want to do here is make it possi... | [
"selected = [t for t in all_data if t[1].startswith('Jo')]\n\nbut, measure, don't guess. I think that in some cases, the query would be faster - specially if you have too many records. Maybe you should use a query on the first char, and then start using python-side filter, since you already have the results.\n",
... | [
2,
2,
0
] | [] | [] | [
"python",
"sqlite",
"tuples"
] | stackoverflow_0004698933_python_sqlite_tuples.txt |
Q:
What is the fastest iteration over a large network instance of DiGraph networkx?
I'm writing a class which inherits from DiGraph.py from the open source networkx package in python.
In some method in my class, I need to search for nodes with certain degrees (outdegrees or indegrees for directed graph) and return th... | What is the fastest iteration over a large network instance of DiGraph networkx? | I'm writing a class which inherits from DiGraph.py from the open source networkx package in python.
In some method in my class, I need to search for nodes with certain degrees (outdegrees or indegrees for directed graph) and return them.
This class is to be used with a data mining project\natural language processing , ... | [
"Iterators are better for large graphs because you don't construct a copy of the dictionary. How about something like this:\nlist_of_2 = []\nfor g in G.out_degree_iter():\n if g[1]==2:\n list_of_2.append(g[0])\n\nOr,\nlist_of_2 = map(lambda x:x[0],filter(lambda x:(x[1]==2),G.out_degree_iter()))\n\n",
"T... | [
2,
2
] | [] | [] | [
"algorithm",
"iteration",
"networkx",
"python"
] | stackoverflow_0004694316_algorithm_iteration_networkx_python.txt |
Q:
python program that plays flash games for me
Yes, that's what I need to achieve, don't ask why:)
So, since this is mainly OS dependent stuff I will be using Windows or Linux (whatever is simpler)
Every second my program will:
1. do a screenshot, analyze the board and other stuff (this I can do)
2. then move the m... | python program that plays flash games for me | Yes, that's what I need to achieve, don't ask why:)
So, since this is mainly OS dependent stuff I will be using Windows or Linux (whatever is simpler)
Every second my program will:
1. do a screenshot, analyze the board and other stuff (this I can do)
2. then move the mouse to some XY and do a left-click
that's all
My ... | [
"I've done this very thing before - use PIL to get the screenshots, and pywinauto to generate the mouse clicks.\n",
"Use ctypes and user32 calls. This is for the second part:\nfrom ctypes import *\nwindll.user32.SetCursorPos(x, y)\n\nSendInput is the thing that you're looking for to simulate mouse clicks, here's ... | [
3,
2,
1
] | [] | [] | [
"click",
"python",
"screenshot"
] | stackoverflow_0004007847_click_python_screenshot.txt |
Q:
Invalid syntax in this simple Python application
Getting an invalid syntax when creating the template_value variable:
class MainPage(webapp.RequestHandler):
def get(self):
blogPosts_query = BlogPost.all().order('-postDate')
blogPosts = blogPosts_query.fetch(10)
if users.get_current_us... | Invalid syntax in this simple Python application | Getting an invalid syntax when creating the template_value variable:
class MainPage(webapp.RequestHandler):
def get(self):
blogPosts_query = BlogPost.all().order('-postDate')
blogPosts = blogPosts_query.fetch(10)
if users.get_current_user():
url = users.create_logout_url(self.r... | [
"You're trying to create a dictionary with round brackets rather than curly ones - change it to:\n template_value = {\n 'blogPosts': blogPosts,\n 'url': url,\n 'url_linktext': url_linktext,\n }\n\n... and the syntax is valid again.\n",
"Did you mean to use () for template value? Diction... | [
5,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0004700460_python_syntax.txt |
Q:
python getelementbyid from string
I have the following program, that is trying to upload a file (or files) to an image upload site, however I am struggling to find out how to parse the returned HTML to grab the direct link (contained in a <dd class="download"><input type="text" value="{hereisthelink}"></dd> ).
I h... | python getelementbyid from string | I have the following program, that is trying to upload a file (or files) to an image upload site, however I am struggling to find out how to parse the returned HTML to grab the direct link (contained in a <dd class="download"><input type="text" value="{hereisthelink}"></dd> ).
I have the code below:
#!/usr/bin/python
#... | [
"The urlparse module has nothing to do with parsing HTML. All it does is break a URL up into bits: protocol, network address, path, etc. For example:\n\n>>> urlparse.urlparse(\"http://www.stackoverflow.com/questions/4699888\")\nParseResult(scheme='http', netloc='www.stackoverflow.com', path='/questions/4699888', ... | [
1
] | [] | [] | [
"file_upload",
"html_parsing",
"python"
] | stackoverflow_0004699888_file_upload_html_parsing_python.txt |
Q:
Python regex not working
I am using the following code:
downloadlink = re.findall("http://uploadir.com/u/(.*)\b", str(downloadhtml))
However, when I pass it the following string:
<input type="text" value="http://uploadir.com/u/bb41c5b3" />
It finds nothing, when I'm expecting it to find: http://uploadir.com/u/bb... | Python regex not working | I am using the following code:
downloadlink = re.findall("http://uploadir.com/u/(.*)\b", str(downloadhtml))
However, when I pass it the following string:
<input type="text" value="http://uploadir.com/u/bb41c5b3" />
It finds nothing, when I'm expecting it to find: http://uploadir.com/u/bb41c5b3. What am I doing wrong?... | [
"Get in the habit of making all regex patterns with raw strings:\nIn [16]: re.findall(\"http://uploadir.com/u/(.*)\\b\", '<input type=\"text\" value=\"http://uploadir.com/u/bb41c5b3\" />')\nOut[16]: []\n\nIn [17]: re.findall(r\"http://uploadir.com/u/(.*)\\b\", '<input type=\"text\" value=\"http://uploadir.com/u/bb4... | [
12,
8
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004700912_python_regex.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.