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:
Using Source Command From A Python Script
I was tring to call the source command in unix from a python script. I was trying to get it done with subprocess.Popen passing the os environment to it.
Below is my function for doing the task of executing a command:
def run_command(command, tst_env):
print tst_env
... | Using Source Command From A Python Script | I was tring to call the source command in unix from a python script. I was trying to get it done with subprocess.Popen passing the os environment to it.
Below is my function for doing the task of executing a command:
def run_command(command, tst_env):
print tst_env
try:
p = subprocess.Popen(command, env=... | [
"subprocess is there for executing things. It doesn't give you a bridge between shell functions and Python. You can't \"load\" a shell file and then treat it as a Python object you can call. You can just execute the contents of the script.\n"
] | [
1
] | [] | [] | [
"python",
"subprocess",
"unix"
] | stackoverflow_0008443124_python_subprocess_unix.txt |
Q:
Installing python bindings for Selenium 2
Can someone explain (detailed directions) how I should go about installing python bindings for Selenium 2 aka Webdriver? I have read the instruction I found at:http://code.google.com/p/selenium/wiki/PythonBindings but they are a little high level. Please help! Thanks.
A:... | Installing python bindings for Selenium 2 | Can someone explain (detailed directions) how I should go about installing python bindings for Selenium 2 aka Webdriver? I have read the instruction I found at:http://code.google.com/p/selenium/wiki/PythonBindings but they are a little high level. Please help! Thanks.
| [
"try one of the following command :\n$sudo pip install selenium\n\nor\n$sudo easy_install selenium \n\ndoes it work? what's your OS ?\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0008128904_python_selenium_selenium_webdriver.txt |
Q:
python can't send attachment files through email
I have the following code which works fine, but it doesn't send the attachment files.
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders
msg=MIM... | python can't send attachment files through email | I have the following code which works fine, but it doesn't send the attachment files.
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders
msg=MIMEMultipart()
def mymail(address,body,format,mylist=No... | [
"I would recommend to use MIMEApplication instead for the attachment. You also do not need to do all the payload encoding manually since that is already done automatically. This example works for me:\nfrom email.mime.text import MIMEText\nfrom email.mime.application import MIMEApplication\nfrom email.utils import f... | [
22
] | [] | [] | [
"email",
"python"
] | stackoverflow_0008456181_email_python.txt |
Q:
python indenting failure?
i was trying to write a class for a little program i've been working on, and i ran into an odd failure of indenting. I was wondering if there's genuinely something wrong with what i wrote, or if it's the parser's fault. This fails in Fedora 15's python 3.2 package.
def __getitem__(self,... | python indenting failure? | i was trying to write a class for a little program i've been working on, and i ran into an odd failure of indenting. I was wondering if there's genuinely something wrong with what i wrote, or if it's the parser's fault. This fails in Fedora 15's python 3.2 package.
def __getitem__(self, key):
if CharacterStats.us... | [
"If I understand you correctly, you want to throw a KeyError if\nusesSubStats is True and key is not in subStats or if usesSubStats is\nFalse and key is not in stats. So I think the problem is that\nif/elif/else chaining doesn't work like you think it does.\nConsider:\ndef f(x):\n if x == 1:\n return 'fi... | [
3,
2,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008456401_python_python_3.x.txt |
Q:
app-engine: Request Data
in my webapp2.RequestHandler method:
I want to find out which uri the requester want to get.
for example, if the user wants to get "http://www.mysite.com/products/table"
I want to get into a variable the value "table" (in this case)
when I print "self.request" I see all the values of Reque... | app-engine: Request Data | in my webapp2.RequestHandler method:
I want to find out which uri the requester want to get.
for example, if the user wants to get "http://www.mysite.com/products/table"
I want to get into a variable the value "table" (in this case)
when I print "self.request" I see all the values of RequestHandler class
but I didn't m... | [
"Looked into how URLs should be handled, and wildcard URLs. Try this:\nclass ProductsHandler(webapp.RequestHandler):\n def get(self, resource):\n self.response.headers['Content-Type'] = 'text/plain'\n table = self.request.url\n self.response.out.write(table)\n self.response.out.write... | [
3
] | [] | [] | [
"google_app_engine",
"python",
"web",
"webapp2"
] | stackoverflow_0008456745_google_app_engine_python_web_webapp2.txt |
Q:
GtkSpinButton disabled by default in Glade
I added GtkSpinButton to my dialog from Glade and it is disabled by default:
What should I do to make arrows enabled?
A:
You need to configure the GtkSpinButton with the Adjustment object as follows (example values):
adj = gtk.Adjustment(1, 1, 99, 1, 1, 1)
spinBtn = se... | GtkSpinButton disabled by default in Glade | I added GtkSpinButton to my dialog from Glade and it is disabled by default:
What should I do to make arrows enabled?
| [
"You need to configure the GtkSpinButton with the Adjustment object as follows (example values):\nadj = gtk.Adjustment(1, 1, 99, 1, 1, 1)\nspinBtn = self.builder.get_object(\"spinbutton1\")\nspinBtn.configure(adj, 1, 0)\n\n"
] | [
9
] | [] | [] | [
"glade",
"pygtk",
"python"
] | stackoverflow_0008456578_glade_pygtk_python.txt |
Q:
Cannot align text with PIL textsize correctly
I use PIL to draw some text on the image.
I did as in this example Center-/middle-align text with PIL? and it worked, however, when the text phrase changes the lines are not aligned.
Font is Verdana. Where could be the problem?
This displays correctly 5 pixels from the... | Cannot align text with PIL textsize correctly | I use PIL to draw some text on the image.
I did as in this example Center-/middle-align text with PIL? and it worked, however, when the text phrase changes the lines are not aligned.
Font is Verdana. Where could be the problem?
This displays correctly 5 pixels from the right side.
colour = 'white'
text = 'Attac... | [
"When calculating the width of text, you will only get an approximation if the font is not taken into account (especially if you use a variable-width font).\nTo fix this, calculate the text width like this:\nw, h = draw.textsize(text, font)\n\nNote that you may also need to adjust the size of the right-margin to ta... | [
4
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0008454679_python_python_imaging_library.txt |
Q:
Force an indent in Python code for organizational purposes
Is there a way to force an indent in Python?
I kind of want it for the sake of making the code look organized.
As an example:
# How it looks now
class Bro:
def __init__(self):
self.head = 1
self.head.eye = 2
self.head.nose = 1
... | Force an indent in Python code for organizational purposes | Is there a way to force an indent in Python?
I kind of want it for the sake of making the code look organized.
As an example:
# How it looks now
class Bro:
def __init__(self):
self.head = 1
self.head.eye = 2
self.head.nose = 1
self.head.mouth = 1
self.neck = 1
self.to... | [
"You can not make a such indentation, because indentatin is used for parsing python code blocks, not simply just for stylish reasons...\nIf you want to group them somehow, the you can use a dict as follows:\nclass Bro:\n def __init__(self):\n self.head {\n 'head': 1,\n 'eye' : 2,\n ... | [
2,
0
] | [] | [] | [
"indentation",
"python"
] | stackoverflow_0008457561_indentation_python.txt |
Q:
Work around for selenium2 print popup
I'm currently working on a program that, with the help of the selenium's webdriver and firefox, crawls it's way through domains, scraping all visible text in the process. (program written in python)
When selenium opens pages with the javascript window.print() the crawler is cu... | Work around for selenium2 print popup | I'm currently working on a program that, with the help of the selenium's webdriver and firefox, crawls it's way through domains, scraping all visible text in the process. (program written in python)
When selenium opens pages with the javascript window.print() the crawler is currently stopping, waiting for me to manuall... | [
"I finally found a work around:\nI pasted \n \"print.always_print_silent\": \"true\",\n \"print.show_print_progress\": \"false\",\n\ninto the Firefox user profile. Selenium has it's own default user profile, which you can edit. The file containing the profile is called firefox_profile.py\nPlease note that thi... | [
5,
2
] | [] | [] | [
"firefox",
"javascript",
"python",
"selenium"
] | stackoverflow_0008318172_firefox_javascript_python_selenium.txt |
Q:
Nested loops for comparing 2 files
I am writing a program to compare two files. For each line in file 1, I want to compare it to all lines in file 2, then continue with the next line in file 1. The program is not continuing in file 1 after the first hit. Any suggestions?
Code: Select all
#! /usr/bin/env python
im... | Nested loops for comparing 2 files | I am writing a program to compare two files. For each line in file 1, I want to compare it to all lines in file 2, then continue with the next line in file 1. The program is not continuing in file 1 after the first hit. Any suggestions?
Code: Select all
#! /usr/bin/env python
import sys
import fileinput
# Open the tw... | [
"After the first line in f1 you've already read all lines from f2 file therefore for line2 in f2 has zero iteration for the second and following lines in f1 file unless f2 file grows on disk.\n#!/usr/bin/env python\nimport sys\n\ndef intersect(r1, r2):\n return r2[0] < (r1[-1]+1) and r1[0] < (r2[-1]+1)\n\nwith o... | [
3,
1,
0
] | [] | [] | [
"for_loop",
"loops",
"python"
] | stackoverflow_0007830330_for_loop_loops_python.txt |
Q:
match only exact word/string in python
How to match exact string/word while searching a list. I have tried, but its not correct. below I have given the sample list, my code and the test results
list = ['Hi, friend', 'can you help me?']
my code
dic=dict()
for item in list:
for word in item.split():
dic... | match only exact word/string in python | How to match exact string/word while searching a list. I have tried, but its not correct. below I have given the sample list, my code and the test results
list = ['Hi, friend', 'can you help me?']
my code
dic=dict()
for item in list:
for word in item.split():
dic.setdefault(word, list()).append(item)
prin... | [
"In case if you just want to see if the sentence starts with a given words you can try startswith if you don;t want the searched word to be at word boundary or split()[0] if you want it to match at word boundary. As an example\n>>> def foo(s): # @ word boundary\n return [x for x in l if x.split()[0]==s]\n\n>>> d... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008457831_python.txt |
Q:
"for line in file object" method to read files
I'm trying to find out the best way to read/process lines for super large file.
Here I just try
for line in f:
Part of my script is as below:
o=gzip.open(file2,'w')
LIST=[]
f=gzip.open(file1,'r'):
for i,line in enumerate(f):
if i%4!=3:
LIST.append(line)
... | "for line in file object" method to read files | I'm trying to find out the best way to read/process lines for super large file.
Here I just try
for line in f:
Part of my script is as below:
o=gzip.open(file2,'w')
LIST=[]
f=gzip.open(file1,'r'):
for i,line in enumerate(f):
if i%4!=3:
LIST.append(line)
else:
LIST.append(line)
b1=[ord(x) for ... | [
"The reason the memory keeps inc. even after you use enumerator is because you are using LIST.append(line). That basically accumulates all the lines of the file in a list. Obviously its all sitting in-memory. You need to find a way to not accumulate lines like this. Read, process & move on to next.\nOne more way yo... | [
4,
1,
0,
0,
0
] | [] | [] | [
"line",
"python"
] | stackoverflow_0008454413_line_python.txt |
Q:
Concurrent insertions in a Suffix Tree
Some time ago I posted a question about saving/retrieving a Suffix Tree from disk. That's finally working fine, but now the construction is extremely slow, and I don't want to mess with the Ukkonen's algorithm (linear construction) right now.
So, I wanted to make concurrent i... | Concurrent insertions in a Suffix Tree | Some time ago I posted a question about saving/retrieving a Suffix Tree from disk. That's finally working fine, but now the construction is extremely slow, and I don't want to mess with the Ukkonen's algorithm (linear construction) right now.
So, I wanted to make concurrent insertions to accelerate the process without ... | [
"Threads won't die until they exit, so you can keep them alive with a while True loop. \nThe usual pattern looks like this:\nq = Queue.Queue() # word insertion queue\nterminate = object() # sentinel value to tell a thread to terminate\n\ndef worker(q):\n while True:\n word = q.get()... | [
2
] | [] | [] | [
"concurrency",
"python",
"suffix_tree"
] | stackoverflow_0008457687_concurrency_python_suffix_tree.txt |
Q:
Write business rules in elegant way chaining possible nonexistent attributes
Take a look to this code:
>>> class c(object):
... pass
...
>>> a=c()
>>> if a.b.c:
... print 'hello'
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'c' object has no attribute 'b'
Qu... | Write business rules in elegant way chaining possible nonexistent attributes | Take a look to this code:
>>> class c(object):
... pass
...
>>> a=c()
>>> if a.b.c:
... print 'hello'
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'c' object has no attribute 'b'
Quiet! this is not the question. Please, continue reading:
When someone develops ent... | [
"To check chained attributes the following function might help:\ndef get_chainedattr(parobj, *args):\n try: \n ret = parobj\n for arg in args:\n ret = getattr(ret, arg) \n return ret\n except AttributeError:\n return None\n\nI am not sure if it is more readable ... | [
2,
1
] | [] | [] | [
"business_rules",
"python"
] | stackoverflow_0008457573_business_rules_python.txt |
Q:
More elegant way to create a 2D matrix in Python
Possible Duplicate:
How to initialize a two-dimensional array in Python?
I have always written this part of code in this way: every time I need it, I use this python code:
for x in range(8):
a.append([])
for y in range(8):
a[x].append(0... | More elegant way to create a 2D matrix in Python |
Possible Duplicate:
How to initialize a two-dimensional array in Python?
I have always written this part of code in this way: every time I need it, I use this python code:
for x in range(8):
a.append([])
for y in range(8):
a[x].append(0)
However, I'd like to know if there's a way to beau... | [
"Use nested list comprehensions:\na = [[0 for y in range(8)] for x in range(8)]\n\nwhich is eqivalent to\na = []\nfor x in range(8):\n row = []\n for y in range(8):\n row.append(0)\n a.append(row)\n\n",
"List comprehension is more concise.\na = [[0 for i in xrange(8)] for i in xrange(8)]\nprint a\... | [
20,
3,
3,
2
] | [] | [] | [
"loops",
"matrix",
"python"
] | stackoverflow_0008458315_loops_matrix_python.txt |
Q:
python threads, how to return results generated during the execution of a multithread code
I'm tring to learn how to use threads in python to save a list of object.
I'm starting from this code :
import threading
import urllib
from tempfile import NamedTemporaryFile
singlelock = threading.Lock()
class download(t... | python threads, how to return results generated during the execution of a multithread code | I'm tring to learn how to use threads in python to save a list of object.
I'm starting from this code :
import threading
import urllib
from tempfile import NamedTemporaryFile
singlelock = threading.Lock()
class download(threading.Thread):
def __init__(self, sitecode, lista):
threading.Thread.__init__(sel... | [
"First of all we should all quickly review what threads are http://en.wikipedia.org/wiki/Thread_%28computer_science%29.\nOk, so threads share memory. So this should be easy! Which is also the good and bad thing about threads, it's easy and dangerous! (also lightweight for the OS).\nNow, if using, python with cpyt... | [
3,
2
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0008457940_multithreading_python.txt |
Q:
How to build zookeeper/zkpython in 32bit mode in Mac OS X 10.7 Lion?
I ought to use 32-bit Python in 32-bit mode (due to oracle instantclient-10.2.0.4, which segfaults in 64bit in Mac OS X, but works in 32bit). Everything was fine so far, till I got zookeeper. Actually, ZooKeeper Python bindings (zkpython).
I trie... | How to build zookeeper/zkpython in 32bit mode in Mac OS X 10.7 Lion? | I ought to use 32-bit Python in 32-bit mode (due to oracle instantclient-10.2.0.4, which segfaults in 64bit in Mac OS X, but works in 32bit). Everything was fine so far, till I got zookeeper. Actually, ZooKeeper Python bindings (zkpython).
I tried to make zkpython to be 32bit, whilst keeping the client itself 64-bit as... | [
"I've fixed that myself. Here is the solution: http://blog.nolar.info/building-32-bit-zookeeper-python-bindings-in-64-bit-mac-os-x/ (in a nutshell, hack your Makefile to add \"-arch i386\" to CC definition there).\n",
"Pass CFLAGS to the configure script:\nexport CFLAGS=\"-pipe -O2 -arch i386\"\n./configure …\n\n... | [
3,
0
] | [] | [] | [
"apache_zookeeper",
"macos",
"osx_lion",
"python"
] | stackoverflow_0008389418_apache_zookeeper_macos_osx_lion_python.txt |
Q:
Syntax error when using \n
print 'For ' + str(n) ' total pieces:\n' + str(a) + ' six pieces, ' + str(b) + ' nine pieces, ' + str(c) + ' twenty pieces'
The interpreter says there is a syntax error and highlights the ' after \n
A:
There's a + missing directly after str(n). The compiler highlights the end of the ... | Syntax error when using \n | print 'For ' + str(n) ' total pieces:\n' + str(a) + ' six pieces, ' + str(b) + ' nine pieces, ' + str(c) + ' twenty pieces'
The interpreter says there is a syntax error and highlights the ' after \n
| [
"There's a + missing directly after str(n). The compiler highlights the end of the token that caused the parse error. In this case, the compiler did not expect a string literal directly after the function call str(n).\n",
"For texts such as the one in the question, it's a good idea to use formatted strings, it ... | [
4,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008458687_python.txt |
Q:
Python lxml, matching attributes
I'm having some troubles wrapping my head around lxml. I have some html I want to parse, and I managed to do it, but it doesn't feel like the best way to do it.
I want to extract the value of the value attribute, but only if the value of name is "myInput"
<input name="myInput" valu... | Python lxml, matching attributes | I'm having some troubles wrapping my head around lxml. I have some html I want to parse, and I managed to do it, but it doesn't feel like the best way to do it.
I want to extract the value of the value attribute, but only if the value of name is "myInput"
<input name="myInput" value="This is what i want"/>
I manage to... | [
"You could do it with an XPath:\nimport lxml.html as LH\n\ncontent='<input name=\"myInput\" value=\"This is what i want\"/>'\n\ndoc=LH.fromstring(content)\nfor val in doc.xpath(\"//input[@name='myInput']/@value\"):\n print(val)\n\nyields\nThis is what i want\n\nThe XPath used above has the following meaning:\n ... | [
3,
2
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0008458737_lxml_python.txt |
Q:
Python if syntax 3.2.2
This is a really basic question, but what is wrong with this code?
for row in rows:
if row["Type"] = 'DEADLINE':
print (row["Title"])
I get the error TabError: inconsistent use of tabs and spaces in indentation pointing to the colon at the end of the if.
Sorry if this is too ne... | Python if syntax 3.2.2 | This is a really basic question, but what is wrong with this code?
for row in rows:
if row["Type"] = 'DEADLINE':
print (row["Title"])
I get the error TabError: inconsistent use of tabs and spaces in indentation pointing to the colon at the end of the if.
Sorry if this is too newbie for SO, but I cant dete... | [
"You are probably mixing tabs and spaces for your indentation, just like the error message says.\nSome editors have the annoying habit of replacing 8 spaces by a tab automatically, so your code might actually look like this:\nfor row in rows:\n if row[\"Type\"] = 'DEADLINE':\n->print (row[\"Title\"])\n\nwhere ->... | [
7,
3,
2
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0008458830_python_syntax.txt |
Q:
Python, finding the max difference in an arraylist
Hi I am on this problem where you have to find the difference in an array list
I know how to do that
def diff(list):
return max(list)-min(list)
but I need to do it a for loop. Can anybody help me get started
A:
Here's a way to get the maximum of a list using ... | Python, finding the max difference in an arraylist | Hi I am on this problem where you have to find the difference in an array list
I know how to do that
def diff(list):
return max(list)-min(list)
but I need to do it a for loop. Can anybody help me get started
| [
"Here's a way to get the maximum of a list using a for loop:\nyourmax = None\nfor x in yourlist:\n if yourmax is None or x > yourmax:\n yourmax = x\n\nThis doesn't answer your entire question, but you should be able to see how to adapt this code to get the minimum value. For extra credit, see if you can g... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008458895_python.txt |
Q:
How to get red borders when a field is invalid using WTForms with GAE and Jinja2?
I've got validation practically working and part of my requirement is that when a field is not valid there should be a red border around the field that is not valid:
<tr><td valign="top">
<div class="labelform" id="lname">
{% ... | How to get red borders when a field is invalid using WTForms with GAE and Jinja2? | I've got validation practically working and part of my requirement is that when a field is not valid there should be a red border around the field that is not valid:
<tr><td valign="top">
<div class="labelform" id="lname">
{% filter capitalize %}{% trans %}name{% endtrans %}{% endfilter %}:
</div></td><td>
<di... | [
"The documentation for custom widgets in WTForms suggests implementing a custom widget that adds a class to the input element:\nclass MyTextInput(TextInput):\n def __init__(self, error_class=u'has_errors'):\n super(MyTextInput, self).__init__()\n self.error_class = error_class\n\n def __call__(s... | [
3
] | [] | [] | [
"css",
"html",
"jinja2",
"python",
"wtforms"
] | stackoverflow_0008457975_css_html_jinja2_python_wtforms.txt |
Q:
spaces in a string python
How do you detect if there are 2 consecutive spaces in a string in Python?
For example, with the input string:
Hello there
I'd like to detect the two spaces and return True.
I know you can use split and join to fill in the consecutive spaces, but how do you detect them?
A:
If you w... | spaces in a string python | How do you detect if there are 2 consecutive spaces in a string in Python?
For example, with the input string:
Hello there
I'd like to detect the two spaces and return True.
I know you can use split and join to fill in the consecutive spaces, but how do you detect them?
| [
"If you want to find two or more consecutive spaces:\nif \" \" in s:\n # s contains two or more consecutive space\n\nIf you want to find two or more spaces anywhere in the string:\nif s.count(' ') >= 2:\n # s contains two or more spaces\n\n",
"A more general solution is achieved by using regular expression... | [
7,
2
] | [] | [] | [
"python"
] | stackoverflow_0008459055_python.txt |
Q:
Bpython-like editor/IDE?
I love bpython's fast, comprehensive autocompletion and I'd really like to use it right inside my editor/IDE. Is there a way to integrate it into vim/gedit/eclipse/etc?
Thanks.
A:
I had a similar question. I wanted to have bpython in Vim as i was getting tired of switching between termin... | Bpython-like editor/IDE? | I love bpython's fast, comprehensive autocompletion and I'd really like to use it right inside my editor/IDE. Is there a way to integrate it into vim/gedit/eclipse/etc?
Thanks.
| [
"I had a similar question. I wanted to have bpython in Vim as i was getting tired of switching between terminal and Vim. Turns out there is a fantastic plugin ( as there usually are for Vim :) called conque . Docs are here \nAfter u install it at the Vim prompt do :ConqueTerm bpython and smile :) I think it works ... | [
2
] | [] | [] | [
"bpython",
"eclipse",
"python",
"vim"
] | stackoverflow_0007455743_bpython_eclipse_python_vim.txt |
Q:
How to track changes on files like dropbox does?
Anybody know how to execute methods (python) when files are modified like Dropbox and his Continuous Data Protection mechanism that can track exactly when a file is modified and sync it.
Of course it would not be of the entire hard-disk, but a track on a specified d... | How to track changes on files like dropbox does? | Anybody know how to execute methods (python) when files are modified like Dropbox and his Continuous Data Protection mechanism that can track exactly when a file is modified and sync it.
Of course it would not be of the entire hard-disk, but a track on a specified directory.
OBS: For Windows and Linux OS. Mac is a plus... | [
"On Linux, pyinotify will probably do what you want. But note the caveats mentioned in the inotify(7) manpage, in particular:\n\nNote that the event queue can overflow. In this case, events are lost. Robust applications should handle the possibility of lost events gracefully.\nIf monitoring an entire directory subt... | [
5,
4,
0
] | [] | [] | [
"dropbox",
"python"
] | stackoverflow_0008459140_dropbox_python.txt |
Q:
Find start and end positions of all occurrences within a string in Python
If you have a sequence:
example='abcdefabcdefabcdefg'
and your searching for:
searching_for='abc'
what function would give you a list with all the positions?
positions=[(0,2),(6-8),(12-14)]
i created a window list that splits 'example' by... | Find start and end positions of all occurrences within a string in Python | If you have a sequence:
example='abcdefabcdefabcdefg'
and your searching for:
searching_for='abc'
what function would give you a list with all the positions?
positions=[(0,2),(6-8),(12-14)]
i created a window list that splits 'example' by 3 so it goes from 'abc','bcd','cde'
windows=['abc', 'bcd', 'cde', 'def', 'efa'... | [
"You can use regular expressions; the match objects come with position information attached. Example using Python 2:\n>>> import re\n>>> example = 'abcdefabcdefabcdefg'\n>>> for match in re.finditer('abc', example):\n print match.start(), match.end()\n0 3\n6 9 \n12 15\n\n",
"The re module provides what you... | [
12,
3,
2
] | [] | [] | [
"position",
"python",
"range",
"string",
"window"
] | stackoverflow_0008459412_position_python_range_string_window.txt |
Q:
Python-Sorting strings to columns
Possible Duplicate:
Python- Adding a specified width to strings
Sort strings by their width, for example the instructions below, I have specific values for each column shown below, however I want to then print out the values (after being generated) into this format into a text f... | Python-Sorting strings to columns |
Possible Duplicate:
Python- Adding a specified width to strings
Sort strings by their width, for example the instructions below, I have specific values for each column shown below, however I want to then print out the values (after being generated) into this format into a text file.
Column 1-6 Record Name
Column 7-1... | [
"To sort a list of strings by their Residue Name, use something like this:\nlist_of_strings.sort(key=lambda s: s[17:20])\n\nTo learn more about sorting techniques, see Python's Sorting HOWTO Guide.\nTo learn more about string slicing see the Python Tutorial Section on Strings.\nTo build-up strings with this record ... | [
4
] | [] | [] | [
"file",
"python",
"sorting"
] | stackoverflow_0008459582_file_python_sorting.txt |
Q:
Stripping extraneous chars from gchats pulled via imap with Python
I'm working on a project that pulls down chat transcripts from gmail via imap. I have successfully logged in, and displayed the most recent gchat transcript via the following code:
import getpass, imaplib, email, re, sys
s=imaplib.IMAP4_SSL('imap.... | Stripping extraneous chars from gchats pulled via imap with Python | I'm working on a project that pulls down chat transcripts from gmail via imap. I have successfully logged in, and displayed the most recent gchat transcript via the following code:
import getpass, imaplib, email, re, sys
s=imaplib.IMAP4_SSL('imap.gmail.com', 993)
getuser = raw_input("<username>")
getpass = raw_input("... | [
"Take a look at XML parsing libraries. A fast library for python is lxml:\n\nThe lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible bu... | [
0,
0
] | [] | [] | [
"gmail",
"imap",
"python",
"regex"
] | stackoverflow_0008459726_gmail_imap_python_regex.txt |
Q:
parsing from text file to graph (python)
I'm having trouble figuring out how to parse a text file into a graph in python. The file is in the following format:
4 4
o . o . o . o
- - . -
o . o . o | o
. - . .
o | o . o . o
. - . -
o . o . o . o
The integers at the top are the dimensions (row, c... | parsing from text file to graph (python) | I'm having trouble figuring out how to parse a text file into a graph in python. The file is in the following format:
4 4
o . o . o . o
- - . -
o . o . o | o
. - . .
o | o . o . o
. - . -
o . o . o . o
The integers at the top are the dimensions (row, column). I need to take into account the space ... | [
"This function parses a grid like the one you've given into a set of nodes (stored as a pair of coordinates in the original grid), and a dict of edges (mapping each node to a list of nodes that are adjacent to it). This is a very easy-to-use representation for the graph, and you should have no trouble coding the ma... | [
2,
0,
0
] | [] | [] | [
"arrays",
"graph",
"parsing",
"python"
] | stackoverflow_0008459434_arrays_graph_parsing_python.txt |
Q:
for if comparsion
I'm new to python and I'm having a bit of trouble understanding how this is supposed to work.
Lets say i have a for loop like so :
for row in rows
if row["Title"] == List[row]
do something
gives me the error that list indicies must be integers.
if I'm cycling through every row, ... | for if comparsion | I'm new to python and I'm having a bit of trouble understanding how this is supposed to work.
Lets say i have a for loop like so :
for row in rows
if row["Title"] == List[row]
do something
gives me the error that list indicies must be integers.
if I'm cycling through every row, how can I represent the... | [
"There are some important things you should understand and you may be doing wrong based on the code sample you've provided so far.\n\nYou're trying to use an element in rows as a index. If you expected this\nto be an integer you may need to convert it (ie. if it's a string\nlike '1').\nIn addition to point 1, You'... | [
4,
3,
3,
1
] | [] | [] | [
"iteration",
"python"
] | stackoverflow_0008459824_iteration_python.txt |
Q:
PyGame in a virtualenv on OS X with brew?
Can't quite figure out how to install PyGame in a virtualenv on OSX Lion. I'd really like to keep things contained in the virtualenv, if at all possible.
I've tried downloading the source for PyGame and running the included setup.py in the virtualenv, but it seems to be... | PyGame in a virtualenv on OS X with brew? | Can't quite figure out how to install PyGame in a virtualenv on OSX Lion. I'd really like to keep things contained in the virtualenv, if at all possible.
I've tried downloading the source for PyGame and running the included setup.py in the virtualenv, but it seems to be having a bunch of issues finding the SDL requi... | [
"Yes, you can use it in 3 steps with brew:\nbrew install python\nbrew install sdl sdl_image sdl_mixer sdl_ttf smpeg portmidi \n/usr/local/share/python/pip install hg+http://bitbucket.org/pygame/pygame\n\n(this is how i did it, it's working perfectly.)\nIf you don't know brew, start here\n"
] | [
32
] | [] | [] | [
"macos",
"pygame",
"python",
"virtualenv"
] | stackoverflow_0008458911_macos_pygame_python_virtualenv.txt |
Q:
Can't get the hash() function to work in python 3.2.2
I have a problem with this code:
print('insert password below to get a hash')
pass = int(input('Input passowrd> ')
hash(pass)
input()
I just get a error when I try to run this, I tried the help(hash) in the python shell, read the docs, googled as much as poss... | Can't get the hash() function to work in python 3.2.2 | I have a problem with this code:
print('insert password below to get a hash')
pass = int(input('Input passowrd> ')
hash(pass)
input()
I just get a error when I try to run this, I tried the help(hash) in the python shell, read the docs, googled as much as possible, but I can't get it to work :-/
What is the problem?
| [
"I think you have two problems.\n\nFirstly, a pass-word is not usually an integer so your call to int will most likely raise an exception.\nYou probably want this:\npass = input('Input password> ')\n\n\nSecondly, the hash function returns a hash code for the object for fast comparison purposes. It is not a cryptogr... | [
3,
3,
2,
0
] | [] | [] | [
"hash",
"python",
"python_idle"
] | stackoverflow_0008459485_hash_python_python_idle.txt |
Q:
How to stop re.finditer at first end site
consider the code
import re
mystring = 'XYZABCDEGHIJEGIJKLMNEPABCFGDEQRST'
print re.finditer[start.start():end.start()] for start in re.finditer('(?=A)',mystring) for end in re.finditer('(?=E)',mystring) if end.start()>start.start()]
Returns output :-
A... | How to stop re.finditer at first end site | consider the code
import re
mystring = 'XYZABCDEGHIJEGIJKLMNEPABCFGDEQRST'
print re.finditer[start.start():end.start()] for start in re.finditer('(?=A)',mystring) for end in re.finditer('(?=E)',mystring) if end.start()>start.start()]
Returns output :-
ABCDE , ABCDEGHIJE , ABCDEGHIJEGIJKLMNE , ABCFGD... | [
"I think you want all shortest matches of strings starting with A and ending with E. You can use the regexp 'A.*?E' to do this: rather than being greedy like 'A.*E' would be it finds the smallest match. You can use findall rather than finditer to get the matched strings. Overall, you have code like this:\nprint re.... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008460240_python_regex.txt |
Q:
What's a good User-Agent parsing plugin for django
Is there a User-Agent-String parsing plugin or middleware that you can recommend. Right now I am using django-smartagent, but its dictionary is not complete and not updated very often.
A:
The browscap files can be read by the pythong ConfigParser library and a... | What's a good User-Agent parsing plugin for django | Is there a User-Agent-String parsing plugin or middleware that you can recommend. Right now I am using django-smartagent, but its dictionary is not complete and not updated very often.
| [
"The browscap files can be read by the pythong ConfigParser library and are updated regularly.\nhttp://browsers.garykeith.com/downloads.asp\nThis is a module that shows using ConfigParser to read, from a older djangosnippet posting (267) slightly modified version to allow for easier 'finding' of the browscap.ini fi... | [
2
] | [] | [] | [
"cross_platform",
"django",
"python",
"user_agent",
"web_applications"
] | stackoverflow_0008272523_cross_platform_django_python_user_agent_web_applications.txt |
Q:
need help for python command line argument using argparse
I need some help regarding using argparse. What I want to achieve is that I need to pass in only one argument, it could be one of the followings: --k, --r, --b, --p,(ignore the rest). If the argument count is not 1, print "usage" information and quit. Also ... | need help for python command line argument using argparse | I need some help regarding using argparse. What I want to achieve is that I need to pass in only one argument, it could be one of the followings: --k, --r, --b, --p,(ignore the rest). If the argument count is not 1, print "usage" information and quit. Also the program needs to know which flag is passed in in order to c... | [
"What you need to use to accomplish that is a mutually exclusive group:\nimport argparse\n\nparser = argparse.ArgumentParser()\ngroup = parser.add_mutually_exclusive_group()\ngroup.add_argument('-k', action='store_true')\ngroup.add_argument('-r', action='store_true')\ngroup.add_argument('-b', action='store_true')\n... | [
4,
3
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0008460587_argparse_python.txt |
Q:
Efficiently Group Overlapping Rectangles
Best way to group overlapping rectangles? I've tried using OpenCV but the grouprectangles method doesn't work as intended.
I've thought about doing something like this:
L = [every rectangle]
L_next = []
while not L.empty():
for rectangle in L:
L.remove(rectangle... | Efficiently Group Overlapping Rectangles | Best way to group overlapping rectangles? I've tried using OpenCV but the grouprectangles method doesn't work as intended.
I've thought about doing something like this:
L = [every rectangle]
L_next = []
while not L.empty():
for rectangle in L:
L.remove(rectangle)
for other_rectangle in L:
... | [
"I'd look at pygame.Rect.collide methods for a response to your problem. Since rectangle overlapping detection is so common in games, I guess their implementation is quite good in terms of computational complexity.\n"
] | [
0
] | [] | [] | [
"algorithm",
"boost",
"c++",
"computer_vision",
"python"
] | stackoverflow_0008460688_algorithm_boost_c++_computer_vision_python.txt |
Q:
Writing binary files in Python 2.6+ and 3
I am writing a program that needs to write a binary file. In contains a header of strings (key-value pairs) and numeric data (which can be little-endian or big-endian) and I am looking for a way to write a program that runs unchanged in Python 2.6+ and Python 3.2+.
Can any... | Writing binary files in Python 2.6+ and 3 | I am writing a program that needs to write a binary file. In contains a header of strings (key-value pairs) and numeric data (which can be little-endian or big-endian) and I am looking for a way to write a program that runs unchanged in Python 2.6+ and Python 3.2+.
Can anyone suggest some best practices? Additionally, ... | [
"Once you created the binary data, you just write it to a file opened in binary mode. That's all there is to it. No compatibility problems between Python 2 and 3 there at all.\nSubclassing BufferedWriter is completely unecessary.\nHow you create the data is a different question, but again there I don't see any obvi... | [
1,
0,
0
] | [] | [] | [
"binary",
"io",
"python",
"python_3.x"
] | stackoverflow_0008460135_binary_io_python_python_3.x.txt |
Q:
GtkLabel alignment and padding
I have GtkLabel in Glade with X align set to 0, X pad set to 5, Expand set to No.
Label is located under horizontal box together with spin button and another label.
The problem is that X pad is applied to both, left and right side.
I want it to be applied only to right side.
What am ... | GtkLabel alignment and padding | I have GtkLabel in Glade with X align set to 0, X pad set to 5, Expand set to No.
Label is located under horizontal box together with spin button and another label.
The problem is that X pad is applied to both, left and right side.
I want it to be applied only to right side.
What am I doing wrong?
| [
"Xpad is applied to both left and right.\nGlade 3.10\nIf you just want to have a margin on the right, then change Margin on the right available in the Common tab:\n\nGlade 3.8\nRight click on the GtkLabel widget and select Add Parent->Alignment. Click in the GtkAlignment widget and set RightPadding to the desired v... | [
5
] | [] | [] | [
"glade",
"pygtk",
"python"
] | stackoverflow_0008456556_glade_pygtk_python.txt |
Q:
Django servering static files not working with dev server
Not sure what I'm doing wrong, but I can't get this to work. I'm using Django 1.3 and Python 2.7.
My project structure looks like this:
project
static
templates
settings.py
apps
...
In my settings.py file I have
PROJECT_ROOT = os.path.r... | Django servering static files not working with dev server | Not sure what I'm doing wrong, but I can't get this to work. I'm using Django 1.3 and Python 2.7.
My project structure looks like this:
project
static
templates
settings.py
apps
...
In my settings.py file I have
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
STATIC_ROOT = os.path.realpa... | [
"You should add the complete path to the dir where you place your static files in STATICFILES_DIRS in settings.py, like this:\nSTATICFILES_DIRS = (\n '/path/to/static',\n)\n\n",
"Either add STATICFILES_DIRS as in previous answer or put the package directory that has 'static' dir in your INSTALLED_A... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008460575_django_python.txt |
Q:
Python Progressbar (PyPi) - display custom text that changes with update()
Hey I am using the progressbar package from pypi and i really like it a lot. My problem is that I haven't found a way so far to display custom text. What I mean with that is displaying text that changes when I call pbar.update()
For example... | Python Progressbar (PyPi) - display custom text that changes with update() | Hey I am using the progressbar package from pypi and i really like it a lot. My problem is that I haven't found a way so far to display custom text. What I mean with that is displaying text that changes when I call pbar.update()
For example if i scan my computer recursively for files I want the progress bar to change t... | [
"I tried to use update method in the FormatLabel widget to change the contents of the label, but it didn't work for me. However, replacing the FormatLabel with a completely new object worked for me:\nfrom progressbar import *\nimport time\n\nwidgets = [FormatLabel(''), ' ', Percentage(), ' ', Bar('/'), ' ', Rotatin... | [
10
] | [] | [] | [
"progress_bar",
"python"
] | stackoverflow_0008458655_progress_bar_python.txt |
Q:
Python XPath parsing tag with apostrophe
I'm new to XPath. I'm trying to parse a page using XPath. I need to get information from tag, but escaped apostrophe in title screws up everything.
For parsing i use Grab.
tag from source:
<img src='somelink' border='0' alt='commission:Alfred\'s misadventures' title='commi... | Python XPath parsing tag with apostrophe | I'm new to XPath. I'm trying to parse a page using XPath. I need to get information from tag, but escaped apostrophe in title screws up everything.
For parsing i use Grab.
tag from source:
<img src='somelink' border='0' alt='commission:Alfred\'s misadventures' title='commission:Alfred\'s misadventures'>
Actual XPath:... | [
"Garbage in, garbage out. Your input is not well-formed, because it improperly escapes the single quote character. Many programming languages (including Python) use the backslash character to escape quotes in string literals. XML does not. You should either 1) surround the attribute's value with double-quotes; or 2... | [
5,
2
] | [] | [] | [
"apostrophe",
"parsing",
"python",
"xpath"
] | stackoverflow_0008459637_apostrophe_parsing_python_xpath.txt |
Q:
Invalid Syntax on perfectly correct while loop?
I am writing a program for fun (hang man) and i get incorrrect syntax on this while loop
while wrong MAX_WRONG and so_far != word:
My whole program is this
import random
HANGMAN=( #this is the Hangman ascii art
"""
_________
| |
| 0
| ... | Invalid Syntax on perfectly correct while loop? | I am writing a program for fun (hang man) and i get incorrrect syntax on this while loop
while wrong MAX_WRONG and so_far != word:
My whole program is this
import random
HANGMAN=( #this is the Hangman ascii art
"""
_________
| |
| 0
|
|
|
|
_________
| |
... | [
"wrong MAX_WORD is the incorrect syntax. perhaps you want wrong <= Max_Wrong\n",
"wrong MAX_WRONG does not make sense. You'll need an operator between those two identifiers. You're probably looking for <.\n",
"while wrong < MAX_WRONG and so_far != word:\n\nIs this what you mean?(Note < comparator)\n",
"I assu... | [
4,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008460919_python.txt |
Q:
Find the position of when a particular sequence occurs in a string using a sliding window in Python 2.7
If there's a window list
text='abcdefg'
window_list=[text[i:i+3] for i in range(len(text)-3)]
print window_list
['abc', 'bcd', 'cde', 'def']
for i in window_list:
for j,k in zip(range(len(text)),i):
pri... | Find the position of when a particular sequence occurs in a string using a sliding window in Python 2.7 | If there's a window list
text='abcdefg'
window_list=[text[i:i+3] for i in range(len(text)-3)]
print window_list
['abc', 'bcd', 'cde', 'def']
for i in window_list:
for j,k in zip(range(len(text)),i):
print j,k
0 a
1 b
2 c
0 b
1 c
2 d
0 c
1 d
2 e
0 d
1 e
2 f
i'm trying to make it so when
(j==0 and k=='c') and ... | [
"Have you thought to do it in this way?\n>>> text='abcdefg'\n>>> window_list=[text[i:i+3] for i in range(len(text)-3)]\n>>> [\"-\".join([str(i),str(i+len(w))]) for i,w in enumerate(window_list) if w == 'cde'] #for single item\n['2-5']\n>>> [\"-\".join([str(i),str(i+len(w))]) for i,w in enumerate(window_list) if w i... | [
3,
2,
0
] | [] | [] | [
"find",
"position",
"python",
"string",
"window"
] | stackoverflow_0008455358_find_position_python_string_window.txt |
Q:
Searching through Dictionaries in Python
I would like to search through on one of the components in a dictionary "C".
For that component I have around 6 pairs of (x,y,z). I would like to search through until there are no more and assign the integers to a variable: x_value, then the y and then the z.
Guanine = {"C"... | Searching through Dictionaries in Python | I would like to search through on one of the components in a dictionary "C".
For that component I have around 6 pairs of (x,y,z). I would like to search through until there are no more and assign the integers to a variable: x_value, then the y and then the z.
Guanine = {"C": [(6.958, -5.037, 2.040), (7.355, -4.850, 3.5... | [
"print \"Type:\\tindex:\\tX:\\tY:\\tZ:\"\nfor atom_type, coordinates in Guanine.items():\n for i, (x,y,z) in enumerate(coordinates):\n print \"%s\\t%d\\t%5.3f\\t%5.3f\\t%5.3f\" % (atom_type, i, x, y, z)\n\nOutput:\nType: index: X: Y: Z:\nC 0 6.958 -5.037 2.040\nC 1 ... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0008460913_python.txt |
Q:
Find 4 values in window size 6 that satisfy certain criteria and extend until 4 consecutive values do not satisfy . Python
if you have a list of values:
values=['130','90','150','123','133','120','160','180','45','67','55','34','130','120']
and wanted to scan through with a window size of 6 and if 4 out of the 6 ... | Find 4 values in window size 6 that satisfy certain criteria and extend until 4 consecutive values do not satisfy . Python | if you have a list of values:
values=['130','90','150','123','133','120','160','180','45','67','55','34','130','120']
and wanted to scan through with a window size of 6 and if 4 out of the 6 were >= 100 then keep scanning until there were 4 in a row that were < 100 and then not include those in the list
so for example... | [
"You can use this code to find the index of the start of your window:\nints = map(int, values)\nfor i in range(len(ints) - 6):\n if sum(x >= 100 for x in ints[i : i + 6]) >= 4:\n return i\n\nIt can be implemented more efficiently by using a sliding window where you have a buffer of 6 elements and at each ... | [
0,
0,
0
] | [] | [] | [
"count",
"extend",
"parameters",
"python",
"window"
] | stackoverflow_0008460316_count_extend_parameters_python_window.txt |
Q:
Python log parsing for IP's
I'm new to python and have been going through some tutorials on log parsing with regular expressions. In the code below I am able to parse a log and create a file with remote IP's making a connection to the server. I'm missing the piece that will eliminate duplicate IP's in the out.txt ... | Python log parsing for IP's | I'm new to python and have been going through some tutorials on log parsing with regular expressions. In the code below I am able to parse a log and create a file with remote IP's making a connection to the server. I'm missing the piece that will eliminate duplicate IP's in the out.txt file created.
Thanks
import re
i... | [
"You can save the results seen so far in a set() and then only write-out results that have not yet been seen. This logic is easy to add to your existing code:\nimport re\nimport sys\n\nseen = set() \n\ninfile = open(\"/var/log/user.log\",\"r\")\noutfile = open(\"/var/log/intruders.txt\",\"w\")\n\npattern = r\"\\d{... | [
5
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008460945_python_regex.txt |
Q:
Regarding tracing of this program
I have the following code that outputs 6,720. However after looking at the code I have no idea how the 720 is being gotten.
def f(n):
if (n==0):
return 1
else:
v = f(n-1)
r = n * v
return r
n = 6
print(n, f(n))
A:
Your function uses a tec... | Regarding tracing of this program | I have the following code that outputs 6,720. However after looking at the code I have no idea how the 720 is being gotten.
def f(n):
if (n==0):
return 1
else:
v = f(n-1)
r = n * v
return r
n = 6
print(n, f(n))
| [
"Your function uses a technique called recursion.\n\nf(6) is 6 * f(5). Since f(5) is 120 (proof below), this gives 720.\nf(5) is 5 * f(4). Since f(4) is 24 (proof below), this gives 120.\netc...\nf(0) is 1.\n\n",
"Your f function is calculating the factorial of its argument. It is often represented with the excla... | [
3,
1,
1,
1
] | [] | [] | [
"python",
"trace"
] | stackoverflow_0008460863_python_trace.txt |
Q:
Connecting two points with a line in a plot in python
Basically what I have to do is draw a NxN grid within certain boundaries given by a boundingBox and write a function for that. My idea is that I should draw horizontal and vertical lines and calculating the width and height by dividing the range of the boundari... | Connecting two points with a line in a plot in python | Basically what I have to do is draw a NxN grid within certain boundaries given by a boundingBox and write a function for that. My idea is that I should draw horizontal and vertical lines and calculating the width and height by dividing the range of the boundaries by N. Then I want to draw the lines with pyplot using th... | [
"I don't know too much about Python or Pylab, so I'm not sure I can fully answer your question, but I might be able to give some insight. It seems like you want each iteration of the loop to draw a line. It seems then like you may need two loops, not just one.\nI would imagine your first loop may look something lik... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008220031_matplotlib_python.txt |
Q:
Use izip to read lines from two files simultaneously in python
I'm trying to use 'izip' to read lines simultaneously from two files, however got errors like below:
>>> f1=open('/home/xug/scratch/test/test_1.fastq','r')
>>> f2=open('/home/xug/scratch/test/test_2.fastq','r')
>>> from itertools import izip
>>> for i,... | Use izip to read lines from two files simultaneously in python | I'm trying to use 'izip' to read lines simultaneously from two files, however got errors like below:
>>> f1=open('/home/xug/scratch/test/test_1.fastq','r')
>>> f2=open('/home/xug/scratch/test/test_2.fastq','r')
>>> from itertools import izip
>>> for i,line1,line2 in izip(f1,f2):
... if i%4==3:
... print line... | [
"izip() simply zips the two iterables to pairs. It doesn't introduce an additional counter, as you seem to expect. Try using enumerate()\nfor i, (line1, line2) in enumerate(izip(f1, f2)):\n ...\n\nto also get that counter.\nThe error message results from the attempt to assign the first item of your iterable to... | [
7
] | [] | [] | [
"line",
"python"
] | stackoverflow_0008461154_line_python.txt |
Q:
How to control screen processes using python
I'm trying to piece together some Python code to control UNIX screen processes (/usr/bin/screen) as part of a script to ease on-server deployment. Are there any libraries or modules that could facilitate this? Is there a better way to do this than just using a standa... | How to control screen processes using python | I'm trying to piece together some Python code to control UNIX screen processes (/usr/bin/screen) as part of a script to ease on-server deployment. Are there any libraries or modules that could facilitate this? Is there a better way to do this than just using a standard Python subprocess?
| [
"Found the solution. There's a Python module called screenutils.\n",
"You could use pexpect.\nThere is also a fork: pexpect-u\nI'm not 100% certain there isn't any limitations in pexpect compared to expect, but if you find any you can always try your hand at some tcl :)\n",
"Do you need to use screen? Because ... | [
5,
3,
3
] | [] | [] | [
"gnu_screen",
"python",
"unix"
] | stackoverflow_0008315179_gnu_screen_python_unix.txt |
Q:
How do I make this only print the last value?
I have the fallowing code to encrypt a massage:
massage= raw_input("Enter message to be encrypted: ")
spec = chr(0b1010101)
key = ord(spec)
encrypt = ""
for i in range(0, len(massage)):
encrypt = encrypt + chr(ord(massage[i]) ^ key)
print encrypt
... | How do I make this only print the last value? | I have the fallowing code to encrypt a massage:
massage= raw_input("Enter message to be encrypted: ")
spec = chr(0b1010101)
key = ord(spec)
encrypt = ""
for i in range(0, len(massage)):
encrypt = encrypt + chr(ord(massage[i]) ^ key)
print encrypt
say I give "yo yo" to it
it will give me :
,
,:
,:... | [
"Put the print statement outside the loop.\nSince the print statement is inside, it is running once per iteration. If it is outside, then it will only do it one time-- once it has finished.\nfor i in range(0, len(massage)):\n encrypt = encrypt + chr(ord(massage[i]) ^ key)\n\nprint encrypt\n\n",
"unindent the c... | [
3,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003258309_python.txt |
Q:
How to determine struct used to declare the instance layout of PyObject?
I'm writing Python 3 extensions in C++ and I'm trying to find a way to check if a PyObject is related to a type (struct) defining its instance layout. I'm only interested in static-size PyObject, not PyVarObject. The instance layout is define... | How to determine struct used to declare the instance layout of PyObject? | I'm writing Python 3 extensions in C++ and I'm trying to find a way to check if a PyObject is related to a type (struct) defining its instance layout. I'm only interested in static-size PyObject, not PyVarObject. The instance layout is defined by a struct with certain well-defined layout: mandatory PyObject header and ... | [
"In Python, you can check if obj is of type Noddy or a derived type by using the test isinstance(obj, Noddy). The test in the C-API whether some PyObject *obj is of type NoddyType or a derived type is basically the same, you use PyObject_IsInstance():\nPyObject_IsInstance(obj, &NoddyType)\n\nAs for your second que... | [
5,
1
] | [] | [] | [
"api",
"pyobject",
"python",
"python_3.x"
] | stackoverflow_0008461044_api_pyobject_python_python_3.x.txt |
Q:
python pygame blit. Getting an image to display
I'm trying to get my webcam to show video through pygame. Here is the code:
# import the relevant libraries
import time
import pygame
import pygame.camera
from pygame.locals import *
# this is where one sets how long the script
# sleeps for, between frames.sleeptime_... | python pygame blit. Getting an image to display | I'm trying to get my webcam to show video through pygame. Here is the code:
# import the relevant libraries
import time
import pygame
import pygame.camera
from pygame.locals import *
# this is where one sets how long the script
# sleeps for, between frames.sleeptime__in_seconds = 0.05
# initialise the display window
py... | [
"Try creating a Camera like this. \ncam = pygame.camera.Camera(camlist[0],(640,480))\n\nThat's how it's done on this page of the pygame docs.\n\nLooking at the API page for pygame.camera, I found two things that might help. First,\n\nPygame currently supports only Linux and v4l2 cameras.\nEXPERIMENTAL!: This api ... | [
1
] | [] | [] | [
"blit",
"geometry_surface",
"pygame",
"python"
] | stackoverflow_0008461497_blit_geometry_surface_pygame_python.txt |
Q:
How can I struct.unpack many numbers at once
I want to put a bunch of packed integers into a file, e.g.:
for i in int_list:
fp.write(struct.pack('<I', i))
Now I'd like to read them out into int_list. I could do this, but it seems inefficient:
data = fp.read()
int_list = []
for i in xrange(0, len(data), 4):
... | How can I struct.unpack many numbers at once | I want to put a bunch of packed integers into a file, e.g.:
for i in int_list:
fp.write(struct.pack('<I', i))
Now I'd like to read them out into int_list. I could do this, but it seems inefficient:
data = fp.read()
int_list = []
for i in xrange(0, len(data), 4):
int_list.append(struct.unpack('<I', data[i:i+4]... | [
"You can do it more efficiently in both directions:\n>>> import struct\n\n>>> int_list = [0, 1, 258, 32768]\n>>> fmt = \"<%dI\" % len(int_list)\n>>> data = struct.pack(fmt, *int_list)\n>>> data\n'\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x02\\x01\\x00\\x00\\x00\\x80\\x00\\x00'\n\n>>> # f.write(data)\n... # data = f... | [
25,
5
] | [] | [] | [
"python",
"struct"
] | stackoverflow_0008461798_python_struct.txt |
Q:
Dynamic arrays and structures in structures in python
I am trying to implement this C structures in python using ctypes:
struct _rows {
int cols_count;
char *cols[];
}
struct _unit {
int rows_count;
struct _rows *rows;
}
int my_func(struct _unit *param);
Problem is that _rows.cols is a dynamical... | Dynamic arrays and structures in structures in python | I am trying to implement this C structures in python using ctypes:
struct _rows {
int cols_count;
char *cols[];
}
struct _unit {
int rows_count;
struct _rows *rows;
}
int my_func(struct _unit *param);
Problem is that _rows.cols is a dynamically sized array of char pointer and _unit.rows is a dynamica... | [
"I'm making some assumptions about what the OP wants, and I'd love suggestions if there is an easier way to do this, but this is what I came up with:\ndemo.py\nimport string\nfrom ctypes import Structure,c_int,c_char_p,POINTER,cast,pointer,byref,CDLL\n\nclass Row(Structure):\n _fields_ = [('cols_count', c_int), ... | [
11
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0008392203_ctypes_python.txt |
Q:
Invoke javascript methods on a page
Is there a way using either C# or a scripting language, such as Python, to load up a website in the user's default webbrowser and continue to interact it via code (e.g. invoke existing Javascript methods)? When using WinForms, you can host a Webbrowser control and invoke scripts... | Invoke javascript methods on a page | Is there a way using either C# or a scripting language, such as Python, to load up a website in the user's default webbrowser and continue to interact it via code (e.g. invoke existing Javascript methods)? When using WinForms, you can host a Webbrowser control and invoke scripts from there, but only IE is supported. Is... | [
"You might want to look into Selenium. It can automate interaction with FireFox, IE, Chrome (with chromedriver) and Opera. It may not be suitable for your purposes due to the fact that it uses a fresh, stripped down profile, rather than the user's normal browser profile.\n",
"If you look at the HTTP request heade... | [
1,
0
] | [] | [] | [
"browser",
"c#",
"javascript",
"python",
"scripting"
] | stackoverflow_0008461764_browser_c#_javascript_python_scripting.txt |
Q:
Using callLater in Twisted to keep track of auction endings
I was wondering if it would be a good idea to use callLater in Twisted to keep track of auction endings. It would be a callLater on the order of 100,000's of seconds, though does that matter? Seems like it would be very convenient. But then again it seems... | Using callLater in Twisted to keep track of auction endings | I was wondering if it would be a good idea to use callLater in Twisted to keep track of auction endings. It would be a callLater on the order of 100,000's of seconds, though does that matter? Seems like it would be very convenient. But then again it seems like a horrible idea if the server crashes.
Keeping a database o... | [
"One of the Divmod projects, Axiom, might be applicable here. Axiom is an object database. One of its unexpected, useful features is a persistent scheduling system.\nYou schedule events using APIs provided by the database. When the events come due, a callback you specified is called. The events persist across p... | [
4
] | [] | [] | [
"database",
"python",
"twisted"
] | stackoverflow_0008456126_database_python_twisted.txt |
Q:
Create and write to files based on list with like items
I have a CSV file with 237 lines of transactions, I've already figured out to group, sort, and create a new CSV file with the transactions in the correct order sorted by account number. However I'd like to go one step further and create multiple CSV files ba... | Create and write to files based on list with like items | I have a CSV file with 237 lines of transactions, I've already figured out to group, sort, and create a new CSV file with the transactions in the correct order sorted by account number. However I'd like to go one step further and create multiple CSV files based on the account number with all of that account number's t... | [
"I don't think there is such module. I would create separate lists for each account operations and put them on the dictionary where key is account number. Then after iterating whole input file you can save each list to separate .csv file.\nIf your input file is already sorted then you can simply copy line to output... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008458998_python.txt |
Q:
Always get printed value of "None"
Alright so here is my code, I get the result I want but I keep getting the "None" value under it. How do I eliminate the "None" value?
n = input("What day of the week are you leaving?")
r = input("How many days will you be resting?")
def days(n):
if n == 0:
print "S... | Always get printed value of "None" | Alright so here is my code, I get the result I want but I keep getting the "None" value under it. How do I eliminate the "None" value?
n = input("What day of the week are you leaving?")
r = input("How many days will you be resting?")
def days(n):
if n == 0:
print "Sunday"
elif n == 1:
print "M... | [
"This should do the trick:\ndays = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n \"Thursday\", \"Friday\", \"Saturday\"]\nprint days[(n+r) % 7]\n\n",
"days never returns anything, so it implicitly returns None. Change all of the print statements in days to return statements:\ndef days(n):\n if ... | [
5,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008462383_python.txt |
Q:
Are there any good online tutorials to TDD for an experienced programmer who is new to testing?
I'm working with a Python development team who is experienced with programming in Python, but is just now trying to pick up TDD. Since I have some experience working with TDD myself, I've been asked to give a presentat... | Are there any good online tutorials to TDD for an experienced programmer who is new to testing? | I'm working with a Python development team who is experienced with programming in Python, but is just now trying to pick up TDD. Since I have some experience working with TDD myself, I've been asked to give a presentation on it. Mainly, I'm just wanting to see articles on this so that I can see how other people are t... | [
"One suggestion I'd make is to start a coding Dojo group. It helps to start TDD from scratch with a group, with most of recommended best-practices and focus on TDD. \nIts basic ideas is to take a simple challenge (like a program that transforms roman algarisms strings into ints), and start to code it, starting from... | [
10,
4,
3,
1,
1,
0,
0
] | [] | [] | [
"python",
"tdd",
"testing",
"unit_testing"
] | stackoverflow_0001126173_python_tdd_testing_unit_testing.txt |
Q:
How to change ticks on a histogram? (matplotlib)
I have a histogram with only a few values. As a result, the x axis ticks are decimals:
How can I make it 1,2,3,4,5?
A:
You can use matplotlib.pyplot.xticks to set the locations of the x-axis tick marks.
Without the code used to generate the question's histogram, ... | How to change ticks on a histogram? (matplotlib) | I have a histogram with only a few values. As a result, the x axis ticks are decimals:
How can I make it 1,2,3,4,5?
| [
"You can use matplotlib.pyplot.xticks to set the locations of the x-axis tick marks.\nWithout the code used to generate the question's histogram, I resorted to creating data to produce a similar histogram. In this first example, we have a histogram with the default tick marks.\nfrom pylab import hist, show\n\nx = [... | [
9
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008462506_matplotlib_python.txt |
Q:
How to generate Excel spreadsheets with embedded graphs?
I want to create Excel spreadsheets with embedded graphs. Ideally I'd like to do with with Python on Mac. If I can't do that, I'd like to do it with some kind of Excel automation on Mac. If I can't do that I'm willing to do it on Windows by manipulating Exce... | How to generate Excel spreadsheets with embedded graphs? | I want to create Excel spreadsheets with embedded graphs. Ideally I'd like to do with with Python on Mac. If I can't do that, I'd like to do it with some kind of Excel automation on Mac. If I can't do that I'm willing to do it on Windows by manipulating Excel via COM, but I would still like to do it from Python. Does a... | [
"Here's a basic example of Python COM on Windows:\nimport win32com.client\nfrom win32com.client import constants as c\n\nxl = win32com.client.gencache.EnsureDispatch('Excel.Application')\nxl.Visible = True\nwb = xl.Workbooks.Add()\nws = xl.ActiveSheet\nws.Range('A1').FormulaR1C1 = 'X'\nws.Range('B1').FormulaR1C1 = ... | [
4,
0
] | [] | [] | [
"excel",
"graph",
"python"
] | stackoverflow_0008462025_excel_graph_python.txt |
Q:
Django - Creating & Store PDF Files using XHTML2PDF
As of now we are using XHTML2PDF to dynamically generate PDFs and outputting to browser whenever required. Now our requirements is changed to generate the PDF only once and store it in the server. The link should be displayed to user to view the PDF. Could you pl... | Django - Creating & Store PDF Files using XHTML2PDF | As of now we are using XHTML2PDF to dynamically generate PDFs and outputting to browser whenever required. Now our requirements is changed to generate the PDF only once and store it in the server. The link should be displayed to user to view the PDF. Could you please point out any resources or snippets to achieve this?... | [
"This is pretty easy to do. Observe:\nfrom django.core.files.base import ContentFile\n\n# get_pdf_contents should return the binary information for\n# a properly formed pdf doc.\npdf_contents = get_pdf_contents()\n\nfile_to_be_saved = ContentFile(pdf_contents)\n\nitem = Item.objects.get(pk=1)\n\nitem.myfilefield.sa... | [
5
] | [] | [] | [
"django",
"python",
"xhtml2pdf"
] | stackoverflow_0008462277_django_python_xhtml2pdf.txt |
Q:
Find 4 values in window size 6 that fit criteria then Add to list until 3 do not fit criteria not include last 3 -> Repeat next window . Python
if you have a list of values:
values=['130','90','150','123','133','120','160',
'45','67',
'55','34','130','120','180','130','10']
and wanted to scan thro... | Find 4 values in window size 6 that fit criteria then Add to list until 3 do not fit criteria not include last 3 -> Repeat next window . Python | if you have a list of values:
values=['130','90','150','123','133','120','160',
'45','67',
'55','34','130','120','180','130','10']
and wanted to scan through with a window size of 6 and if 4 out of the 6 were >= 100 then keep scanning until there were 3 in a row that were < 100 and then not include tho... | [
"Would you like to try with this to see if it suits your requirement?\nfor i in xrange(0,len(values)):\n results[-1].append(values[i])\n if len(filter(lambda x:int(x)<100,results[-1][-3:])) == 3:\n results.append(results[-1][-2:])\n results[-2]=results[-2][:-3]\n if len(results[-2]) == 0:... | [
1
] | [] | [] | [
"extend",
"function",
"list",
"python",
"windows"
] | stackoverflow_0008462517_extend_function_list_python_windows.txt |
Q:
How to localize my WTForms validation message?
I nearly got my validation message localized as you can see it works for English and Swedish:
English:
Swedish:
But when I switch to Portuguese I get the following error message:
Traceback (most recent call last):
File "/media/Lexar/montao/lib/webapp2/webapp2.py",... | How to localize my WTForms validation message? | I nearly got my validation message localized as you can see it works for English and Swedish:
English:
Swedish:
But when I switch to Portuguese I get the following error message:
Traceback (most recent call last):
File "/media/Lexar/montao/lib/webapp2/webapp2.py", line 545, in dispatch
return method(*args, **kw... | [
"If you want to be able to use unicode characters in your translations, you need to use the ugettext_lazy utility function and not gettext_lazy.\nThe main difference, as the function name hints, is that ugettext_lazy is unicode when gettext_lazy is not (which makes it not that useful by the way). \nWhile you're at... | [
6
] | [] | [] | [
"gettext",
"localization",
"python",
"unicode",
"wtforms"
] | stackoverflow_0008458634_gettext_localization_python_unicode_wtforms.txt |
Q:
Python module not working if called from main?
I have a project going. In the project folder, I have another folder (lib) and inside that folder I have 2 files. The contents of each is below. The problem is that req.py runs perfectly by itself, but when I run main.py, I get the following error.
Traceback (most r... | Python module not working if called from main? | I have a project going. In the project folder, I have another folder (lib) and inside that folder I have 2 files. The contents of each is below. The problem is that req.py runs perfectly by itself, but when I run main.py, I get the following error.
Traceback (most recent call last):
File "C:\Users\redacted\main.py"... | [
"\nIn the project folder, I have another folder (lib) and inside that\n folder I have 2 files.\n\nShould be 3.\n\nSetup below:\n __init__.py:import req\n\nIs this 3rd file or?\n"
] | [
0
] | [] | [] | [
"module",
"python",
"python_requests"
] | stackoverflow_0008461575_module_python_python_requests.txt |
Q:
Sphinx - generate automatic references to Trac tickets and changesets
Is Sphinx, is there way to automatically link text like #112 or r1023 to the corresponding tickets/changesets in Trac?
For eg:
#112 -> http://mytracsite/tickets/112
r1023 -> http://mytracsite/changeset/1023
See TracLinks for more examples.
A:... | Sphinx - generate automatic references to Trac tickets and changesets | Is Sphinx, is there way to automatically link text like #112 or r1023 to the corresponding tickets/changesets in Trac?
For eg:
#112 -> http://mytracsite/tickets/112
r1023 -> http://mytracsite/changeset/1023
See TracLinks for more examples.
| [
"If you put this in your config.py\n\ntrac_url = 'http://mytratsite/'\n\nfrom docutils import nodes, utils\nfrom docutils.parsers.rst import roles\nimport urllib\n\ndef trac_role(role, rawtext, text, lineno, inliner, options={}, content=[]):\n ref = trac_url + '/intertrac/' + urllib.quote(text, safe='')\n node = ... | [
9,
5
] | [] | [] | [
"python",
"python_sphinx",
"restructuredtext",
"trac"
] | stackoverflow_0002096401_python_python_sphinx_restructuredtext_trac.txt |
Q:
Python str() - specify which kind of quotes to add/use?
Is there a way to influence the kind of quotes that python uses when casting a tuple/list to string?
For some NLP software I get tuples somewhat like this:
("It", ("isn't", "true"))
I want to cast it to a string and simply remove all double quotes and comma... | Python str() - specify which kind of quotes to add/use? | Is there a way to influence the kind of quotes that python uses when casting a tuple/list to string?
For some NLP software I get tuples somewhat like this:
("It", ("isn't", "true"))
I want to cast it to a string and simply remove all double quotes and commas:
(It (Isn't true))
However, python is having its way with ... | [
"You can't rely on the exact representation that repr uses. I'd just do as you thought and write your own function -- I don't see it being more than a handful of lines of code. This should get you going.\ndef s_exp(x):\n if isinstance(x, (tuple, list)):\n return '(%s)' % (' '.join(map(s_exp, x)))\n ret... | [
5,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0008463362_python_string.txt |
Q:
Workaround read-only site-packages for cx_freeze
I'm currently trying to make cx_freeze to work on a Solaris workstation I have to work with, in order to make an executable from a Python script I have. Problem is, I'm not administrator of this machine, and installation of cx_freeze requests write to site-packages,... | Workaround read-only site-packages for cx_freeze | I'm currently trying to make cx_freeze to work on a Solaris workstation I have to work with, in order to make an executable from a Python script I have. Problem is, I'm not administrator of this machine, and installation of cx_freeze requests write to site-packages, which is read-only for me.
So, obviously, I get this ... | [
"This works like a charm for me :\n$ python setup.py install --home=$HOME\n\nRun in the source directory of cx_freeze found on the Sourceforge download page.\n"
] | [
3
] | [] | [] | [
"cx_freeze",
"python",
"solaris"
] | stackoverflow_0008077643_cx_freeze_python_solaris.txt |
Q:
Transmit JSON data to Django website
I'm transmitting a application/json in java with a HttpPost to a server which use Django.
I am performing the transmission as described here: JSON POST request parsing in PHP
How can I create a page that receive this json data ?
A:
You can receive json through request.raw_pos... | Transmit JSON data to Django website | I'm transmitting a application/json in java with a HttpPost to a server which use Django.
I am performing the transmission as described here: JSON POST request parsing in PHP
How can I create a page that receive this json data ?
| [
"You can receive json through request.raw_post_data\ndata=simplejson.loads( request.raw_post_data )\n\n",
"the request variable in your views have a property request.POST which contains post data. this is (well technically, acts like) a dictionary. you also want to have a look at the json module in python's stand... | [
7,
1
] | [] | [] | [
"django",
"json",
"python"
] | stackoverflow_0008463127_django_json_python.txt |
Q:
most performatic free database for file system tracking
I'm tracking a linux filesystem (that could be any type) with pyinotify module for python (which is actually the linux kernel behind doing the job). Many directories/folders/files (as much as the user want to) are being tracked with my application and now i w... | most performatic free database for file system tracking | I'm tracking a linux filesystem (that could be any type) with pyinotify module for python (which is actually the linux kernel behind doing the job). Many directories/folders/files (as much as the user want to) are being tracked with my application and now i would like track the md5sum of each file and store them on a d... | [
"The first database I'd attempt would be SQLite3. SQLite3 is easy to use, very well tested, provides a large array of interface libraries and pre-written tools to work with databases, and it is very easy to \"embed\" into an application. (Far easier than getting MySQL or PostgreSQL installed on a system.)\nSQLite3 ... | [
0,
0,
0
] | [] | [] | [
"database",
"database_performance",
"pyinotify",
"python"
] | stackoverflow_0008461306_database_database_performance_pyinotify_python.txt |
Q:
python-storm orm many-to-many
I'm using python-storm as orm. The many-to-many reference set is giving me headaches :(
These are the relevant objects:
class Author(object):
__storm_table__ = "author"
id = Int(primary=True)
name = Unicode()
institution_id = Int()
institution = Reference(instituti... | python-storm orm many-to-many | I'm using python-storm as orm. The many-to-many reference set is giving me headaches :(
These are the relevant objects:
class Author(object):
__storm_table__ = "author"
id = Int(primary=True)
name = Unicode()
institution_id = Int()
institution = Reference(institution_id, Institution.id)
def __i... | [
"I'm not really, familiar with storm, but looking at the documentation example, looks like is just an issue related to the order in which the arguments to ReferenceSet are passed. I tried to use this:\nAuthor.papers = ReferenceSet(Author.id, AuthorPapers.author_id, AuthorPapers.paper_id, Paper.id)\n\ninstead of thi... | [
4
] | [] | [] | [
"orm",
"python",
"storm_orm"
] | stackoverflow_0008463649_orm_python_storm_orm.txt |
Q:
What makes (open) Dylan distinct from other programming languages?
Nowadays there are so many programming languages out there: functional, object oriented, dynamically or statically typed, or mixes of these characteristics.
Recently I noticed this release: http://opendylan.org/news/2011/12/10/new_release.html
Open... | What makes (open) Dylan distinct from other programming languages? | Nowadays there are so many programming languages out there: functional, object oriented, dynamically or statically typed, or mixes of these characteristics.
Recently I noticed this release: http://opendylan.org/news/2011/12/10/new_release.html
Open Dylan.
Why would it be interesting for people to learn this programming... | [
"There are several-questions-in-one here.\nWhat is Dylan? Do read its Wikipedia page, it's a good start. The uniqueness of Dylan is that it's a Lisp, without the Lispy syntax. This was appealing to some people when Dylan was first defined. Moreover, Dylan has achieved a pretty functional macro system (which is argu... | [
8,
7,
0
] | [] | [] | [
"clojure",
"common_lisp",
"dylan",
"python",
"scala"
] | stackoverflow_0008463353_clojure_common_lisp_dylan_python_scala.txt |
Q:
Why python multiprocessing in this code is slower?
I have this sample code. I'm making some math computation (graph theory) and I want to increase the speed so I decided to go with multiprocessing but surprisingly the same code runs even slower than the single process version.
I expect that if you have a list and ... | Why python multiprocessing in this code is slower? | I have this sample code. I'm making some math computation (graph theory) and I want to increase the speed so I decided to go with multiprocessing but surprisingly the same code runs even slower than the single process version.
I expect that if you have a list and you split it in half and start two processes it should t... | [
"Instead of using multiprocessing, try cutting down on the amount of allocation you're doing. You're just filling RAM up with temporary lists (for example the halves of aList you pass the processes, and then the newList lists you create in each process). Quite possibly this is the cause of the slowness as lots of a... | [
3,
2
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0008463779_multiprocessing_python.txt |
Q:
Adding query from Twisted `enterprise.adbapi` to reactor loop created by `twistd` daemon
I am using the twisted.enterprise.adbapi inside a Twisted .tac plugin, and am finding that the deferred object returned for functions such as aConnectionPool.runQuery(sqlQuery) are not firing unless reactor.(run) is called. Ho... | Adding query from Twisted `enterprise.adbapi` to reactor loop created by `twistd` daemon | I am using the twisted.enterprise.adbapi inside a Twisted .tac plugin, and am finding that the deferred object returned for functions such as aConnectionPool.runQuery(sqlQuery) are not firing unless reactor.(run) is called. How can I add the query to the reactor loop created by twistd instead of calling reactor.run()? ... | [
"Your code makes a new ConnectionPool for every request it issues. The new ConnectionPool creates its own new thread pool to run queries in, and has to set up a new connection to the database.\nThis means you effectively have no connection pool. You just have a lot of connections that you create and use once. Al... | [
2
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0007883182_python_twisted.txt |
Q:
How to convert JavaScript `for` loop to Python?
I am new to Python and want convert this small JavaScript code to Python. How can I do that?
for (var y = 0; y < 128; y += 1024) {
for (var x = 0; x < 64; x += 1024) {
// skipped
}
}
I searched a lot in Google, but found nothing.
A:
for loops in Py... | How to convert JavaScript `for` loop to Python? | I am new to Python and want convert this small JavaScript code to Python. How can I do that?
for (var y = 0; y < 128; y += 1024) {
for (var x = 0; x < 64; x += 1024) {
// skipped
}
}
I searched a lot in Google, but found nothing.
| [
"for loops in Python\nIt can be easily converted using range() or xrange() function. The xrange() is an iterator version, which means it is more efficient (range() would first create a list you would be iterating through). Its syntax is the following: xrange([start], stop[, step]). See the following:\nfor y in xran... | [
6,
6
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0008464798_javascript_python.txt |
Q:
Trying to parse feeds for a RSS reader written in python
I am still a python beginner. As a practice project I want to code my own RSS reader.
I found a helpful tutorial here: learning python. I used the code provided in that tutorial:
#! /usr/bin/env python
import urllib2
from xml.dom import minidom, Node
""... | Trying to parse feeds for a RSS reader written in python | I am still a python beginner. As a practice project I want to code my own RSS reader.
I found a helpful tutorial here: learning python. I used the code provided in that tutorial:
#! /usr/bin/env python
import urllib2
from xml.dom import minidom, Node
""" Get the XML """
url_info = urllib2.urlopen('http://rss.slash... | [
"Well the \"terminated\" message is not an error, it's just for information that python has exited without error.\nYou're not doing anything wrong, it's just that this RSS reader is not very flexible since it only knows one variant of RSS.\nIf you compare the XML-Documents of slashdot and Spiegel Online you see dif... | [
4,
0
] | [] | [] | [
"eclipse",
"python"
] | stackoverflow_0008464714_eclipse_python.txt |
Q:
Why didn't auth.User check for required fields?
I'd like to extend django's auth.User, after reading this question,
this is my models.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.O... | Why didn't auth.User check for required fields? | I'd like to extend django's auth.User, after reading this question,
this is my models.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
age = models.SmallIntegerField... | [
"When you run user = User(), all you are doing is creating a new User instance. It will not throw an error until you try to save it with user.save().\nTo simultaneously create and save a new model instance to the DB:\nuser = User.objects.create() # should throw an IntegrityError due to required (not NULL) fields no... | [
6,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008464229_django_django_models_python.txt |
Q:
using extended Ascii codes with Python
I've created a dictionnary with Python but I've got problems with extended Ascii codes.
The loop that creats the dictionnary is : (ascii number 128 to 164 : é,à etc)
#extented ascii codes
i = 128
while i <= 165 :
dictionnary[chr(i)] = 'extended ascii'
i = i + 1
But w... | using extended Ascii codes with Python | I've created a dictionnary with Python but I've got problems with extended Ascii codes.
The loop that creats the dictionnary is : (ascii number 128 to 164 : é,à etc)
#extented ascii codes
i = 128
while i <= 165 :
dictionnary[chr(i)] = 'extended ascii'
i = i + 1
But when I try to use dictionnary :
>>> dicti... | [
"Use unichr instead of chr. The function chr produces a string containing a single byte, whereas unichr produces a string containing a single unicode character. Finally, do lookups using unicode characters too: d[u'é'] because d['é'] will look up the utf-8 encoding of é.\nYou have 3 things in your code: a latin-1 e... | [
4
] | [] | [] | [
"ascii",
"encode",
"python",
"utf_8"
] | stackoverflow_0008465226_ascii_encode_python_utf_8.txt |
Q:
simple thread management within python classes
Im trying to write a module for Python that prints out text for my program and displays a progress bar while i do something in the background. Im using the 'threading' module currently but open to suggestions if something else will make it easier.
what i want to know ... | simple thread management within python classes | Im trying to write a module for Python that prints out text for my program and displays a progress bar while i do something in the background. Im using the 'threading' module currently but open to suggestions if something else will make it easier.
what i want to know is two fold, how should i call this class elegantly ... | [
"You were very close to having working code. There just needed to be a few minor fixups:\n\nprint_text is a class. It should be instantiated with print_text()\nThe start method returns an instance of print_text, you need to save that\n in order to call stop and echo on it: t = print_text()\nThe enter method need... | [
4,
3,
0
] | [] | [] | [
"class",
"multithreading",
"python"
] | stackoverflow_0008454140_class_multithreading_python.txt |
Q:
Python recursion depth exceeded limit exceeded, and don't know how to delete recursion
Maybe the problem can be solved by deleting all those functions, can't it?
However, i really don't know what to do to get the source work.
By the way, it just simulates a horse in a chesstable, going around and around, randomly,... | Python recursion depth exceeded limit exceeded, and don't know how to delete recursion | Maybe the problem can be solved by deleting all those functions, can't it?
However, i really don't know what to do to get the source work.
By the way, it just simulates a horse in a chesstable, going around and around, randomly, trying to visit each square once; and I get a recursion depth exceeded error.
import random... | [
"This code has a lot of problems -- enough that it's worth going over in full:\nimport random\n\ndef main():\n global tries,moves\n\nThe first of many examples of over-use of global variables. When possible, pass parameters; or create a class. This is a general strategy that will help you construct more comprehe... | [
8,
3
] | [] | [] | [
"limit",
"python",
"recursion"
] | stackoverflow_0008465293_limit_python_recursion.txt |
Q:
Assignment of objects and fundamental types
There is this code:
# assignment behaviour for integer
a = b = 0
print a, b # prints 0 0
a = 4
print a, b # prints 4 0 - different!
# assignment behaviour for class object
class Klasa:
def __init__(self, num):
self.num = num
a = Klasa(2)
b = a
print a.num, ... | Assignment of objects and fundamental types | There is this code:
# assignment behaviour for integer
a = b = 0
print a, b # prints 0 0
a = 4
print a, b # prints 4 0 - different!
# assignment behaviour for class object
class Klasa:
def __init__(self, num):
self.num = num
a = Klasa(2)
b = a
print a.num, b.num # prints 2 2
a.num = 3
print a.num, b.num #... | [
"This is a stumbling block for many Python users. The object reference semantics are different from what C programmers are used to. \nLet's take the first case. When you say a = b = 0, a new int object is created with value 0 and two references to it are created (one is a and another is b). These two variables poin... | [
13,
6,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008463907_python.txt |
Q:
Django: For a fixed len. model list relation, is it OK to use a fixed number of OneToOneField's in a parent model rather than a FK in the child model?
I am designing a week-based menu application. I am wondering if I should just do this:
class MenuWeek(models.Model):
sunday = OneToOneField("MenuDay")
mond... | Django: For a fixed len. model list relation, is it OK to use a fixed number of OneToOneField's in a parent model rather than a FK in the child model? | I am designing a week-based menu application. I am wondering if I should just do this:
class MenuWeek(models.Model):
sunday = OneToOneField("MenuDay")
monday = OneToOneField("MenuDay")
#etc through Saturday
class MenuDay(models.Model):
# some stuff here, but not a foreign key to MenuWeek
instead of t... | [
"I would never use your first option. You'll end up repeating yourself all over the place to run a particular section of code for each weekday. The second option will result in much nicer code down the road.\n",
"First, the second option is much better. But you can probably even get rid of MenuWeek and just add a... | [
3,
1
] | [] | [] | [
"database_design",
"django",
"python"
] | stackoverflow_0008459353_database_design_django_python.txt |
Q:
Print true values separately
a = 'abcdef' ,'ijklmno' , 'pqrst'
b = 'ijklmno' , 'zxy'
c = b in a
print c
output :
True , False
How to print the value of true separately . i'e 'ijklmno' is true so i want to print it seperately
A:
An expression of the form x in y evaluates to True or False so that's what you'll... | Print true values separately | a = 'abcdef' ,'ijklmno' , 'pqrst'
b = 'ijklmno' , 'zxy'
c = b in a
print c
output :
True , False
How to print the value of true separately . i'e 'ijklmno' is true so i want to print it seperately
| [
"An expression of the form x in y evaluates to True or False so that's what you'll get. If you want to see the common elements, do this instead. \na = 'abcdef' ,'ijklmno' , 'pqrst'\nb = 'ijklmno' , 'zxy'\nset(a).intersection(set(b))\n\nThis will return set(['ijklmno']). \n",
"To get the desired output you can do... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0008465219_python.txt |
Q:
Modal OK/Cancel-Style Dialogs
I am part of the book
Rapid GUI Programming with Python and Qt - The Definitive Guide to PyQt Programming (2008)
I do not understand is that page 163-165
class NumberFormatDlg(QDialog):
def __init__ (self, format, parent=None):
super(NumberFormatDlg, self). __init__(parent... | Modal OK/Cancel-Style Dialogs | I am part of the book
Rapid GUI Programming with Python and Qt - The Definitive Guide to PyQt Programming (2008)
I do not understand is that page 163-165
class NumberFormatDlg(QDialog):
def __init__ (self, format, parent=None):
super(NumberFormatDlg, self). __init__(parent)
...
form = NumberFormatDlg()
Typ... | [
"When you create a instance of the class NumberFormatDlg, its __init__ method is called with the instance as first argument (self), plus any other arguments that are passed in.\nThe NumberFormatDlg.__init__ method is defined with one required argument (format) and one optional argument (parent). Optional arguments ... | [
2
] | [] | [] | [
"arguments",
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0008464159_arguments_pyqt_pyqt4_python.txt |
Q:
How to resize and draw an image using wxpython?
I want to load an image, resize it to a given size and after draw it in a specific position in a panel.
All this using wxpython.
How can I do it?
Thanks in advance!
A:
wx.Image has a Scale method that will do the resizing. The rest is normal wx coding.
Here's a co... | How to resize and draw an image using wxpython? | I want to load an image, resize it to a given size and after draw it in a specific position in a panel.
All this using wxpython.
How can I do it?
Thanks in advance!
| [
"wx.Image has a Scale method that will do the resizing. The rest is normal wx coding.\nHere's a complete example for you.\nimport wx\n\ndef scale_bitmap(bitmap, width, height):\n image = wx.ImageFromBitmap(bitmap)\n image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)\n result = wx.BitmapFromImage(im... | [
33,
1,
1
] | [] | [] | [
"draw",
"image",
"python",
"resize",
"wxpython"
] | stackoverflow_0002504143_draw_image_python_resize_wxpython.txt |
Q:
Adding a string with spaces to a stack
I'm working on developing a mini-language in Python (not really, just a few commands for a personal project).
Here's the code:
class FlashCard:
def __init__(self):
self.commands = {'addQuestion':self.addQuestion}
self.stack = []
self.questions = {}... | Adding a string with spaces to a stack | I'm working on developing a mini-language in Python (not really, just a few commands for a personal project).
Here's the code:
class FlashCard:
def __init__(self):
self.commands = {'addQuestion':self.addQuestion}
self.stack = []
self.questions = {}
def addQuestion(self):
questi... | [
"Since stack is a list, and you are calling the pop method without arguments, what you will get is the last elements in the list. You probably want to transform the list in a space-separated string, instead:\ndef addQuestion(self):\n question = ' '.join(self.stack)\n answer = input(question)\n\nObserve that t... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008466116_python.txt |
Q:
PyQt:Why a popup dialog prevents execution of other code?
I am having a little problem with a pop up dialog.I have a combobox,which when the option changes it pops up a dialog with a textedit widget,do some stuff and insert some text in the textedit widget.
This is what i use for the popup:
def function_1(self):
... | PyQt:Why a popup dialog prevents execution of other code? | I am having a little problem with a pop up dialog.I have a combobox,which when the option changes it pops up a dialog with a textedit widget,do some stuff and insert some text in the textedit widget.
This is what i use for the popup:
def function_1(self):
dialog = QDialog()
dialog.ui = Ui_Dialog_popup()
dia... | [
"That's exactly what the exec method of QDialog is designed for: modal dialogs. Read the \"Modal\" and \"Modeless dialog\" sections.\nIf you don't the dialog to block your main UI, call show() instead of exec() (and check the modal property documentation). \n",
"Elaborating on what Mat said: The show() function i... | [
5,
1,
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qdialog"
] | stackoverflow_0008463751_pyqt_pyqt4_python_qdialog.txt |
Q:
list within a list within a list in python
I wrote this but I don't understand why it is not working. By the way I am a beginner in programming.
fav_colours=[["bob"["likes:blue, hates:red"]],["john"["likes:red,hates:black"]],
["adam"["likes:purple,hates:pink"]]]
print fav_colours
I don't think there is any erro... | list within a list within a list in python | I wrote this but I don't understand why it is not working. By the way I am a beginner in programming.
fav_colours=[["bob"["likes:blue, hates:red"]],["john"["likes:red,hates:black"]],
["adam"["likes:purple,hates:pink"]]]
print fav_colours
I don't think there is any error.Thanks in advance.
| [
"You need to separate each list item via a comma, so [\"bob\"[\"likes:blue, hates:red\"] should be [\"bob\", [\"likes:blue, hates:red\"].\nAnd it looks like you might need to use a dict instead of those inner lists. {\"likes\": \"blue\"}.\n",
"In addition to Russell Dias answer:\nHaving multiple nested lists gets... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0008461358_python.txt |
Q:
How to click on a given link?
<td class="button" nowrap align="center">
<a href="#" onKeyPress="javascript:checkkey(event);" onMouseDown="javascript:funclogin();">
Login
</a>
</td>
How do i click this button using selenium in python?
A:
What about using the class of the tag ?
driver.fi... | How to click on a given link? | <td class="button" nowrap align="center">
<a href="#" onKeyPress="javascript:checkkey(event);" onMouseDown="javascript:funclogin();">
Login
</a>
</td>
How do i click this button using selenium in python?
| [
"What about using the class of the tag ?\ndriver.find_elements_by_xpath(\"//td[@class='button']/a\").click()\n\nAnyhow, you may want to add a better identifier in the code to make this more robust. \n"
] | [
0
] | [] | [] | [
"click",
"python",
"selenium"
] | stackoverflow_0008451765_click_python_selenium.txt |
Q:
BEA-error WLContext.close() in python script
I'm new to Weblogic.
Recently I've created my first script to deploy a WL application. The script is very simple. The problem is that the script throws an exception I don't know to solve.
The script looks like:
wlHost=sys.argv[1]
wlPort=sys.argv[2]
username=sys.argv[3... | BEA-error WLContext.close() in python script | I'm new to Weblogic.
Recently I've created my first script to deploy a WL application. The script is very simple. The problem is that the script throws an exception I don't know to solve.
The script looks like:
wlHost=sys.argv[1]
wlPort=sys.argv[2]
username=sys.argv[3]
password=sys.argv[4]
connect(username, password... | [
"I'm fairly sure your problem is exit() You don't run a disconnect method prior to exiting so the system is terminating all threads. Because you still have an active thread with an active connection open it's raising the exception.\n"
] | [
0
] | [] | [] | [
"python",
"weblogic",
"wlst"
] | stackoverflow_0008465332_python_weblogic_wlst.txt |
Q:
Compiling Python 2.7.2 with google-perftools
I have a debian squeeze operating system (64 bits). I want to use python with google-perftools. To perform that I compiled myself python 2.72 with the option "-lctmalloc". But I get few errors.
I installed libuwind because google-perftool asks for this package while us... | Compiling Python 2.7.2 with google-perftools | I have a debian squeeze operating system (64 bits). I want to use python with google-perftools. To perform that I compiled myself python 2.72 with the option "-lctmalloc". But I get few errors.
I installed libuwind because google-perftool asks for this package while using 64 bits
I installed all the packages needed :
... | [
"Use LDFlags\n\n-ltcmalloc \n\nand it requires posix thread support.\n\n-lpthread\n\n"
] | [
1
] | [] | [] | [
"compilation",
"google_perftools",
"python"
] | stackoverflow_0008390095_compilation_google_perftools_python.txt |
Q:
OpenCV Python and Histogram of Oriented Gradient
Is there any useful documentation for using the HOGDescriptor functionality in Python OpenCV? I have read the C++ documentation, but the Python version functions differently and I cannot figure it out just by tinkering.
Most specifically, I am seeking an OpenCV com... | OpenCV Python and Histogram of Oriented Gradient | Is there any useful documentation for using the HOGDescriptor functionality in Python OpenCV? I have read the C++ documentation, but the Python version functions differently and I cannot figure it out just by tinkering.
Most specifically, I am seeking an OpenCV command in Python that takes an image and a pixel locatio... | [
"This is a little late, but, for future reference, scikit-image has an implementation of HOG. This is a single function that could extract the Histogram of Oriented Gradients for a given image.\n",
"take a look at http://sourceforge.net/projects/hogtrainingtuto/?_test=beta for some HOG python code and a bunch of ... | [
5,
0,
0,
0
] | [] | [] | [
"gradient",
"image_processing",
"numpy",
"opencv",
"python"
] | stackoverflow_0007642259_gradient_image_processing_numpy_opencv_python.txt |
Q:
Qurl not defined in pyqt
Am learning to program python with qt using eric ide. But there seems to be one error i get.
Its says Global Qurl not defined or something. How can I define Qurl?
from PyQt4.QtGui import QMainWindow
from PyQt4.QtCore import pyqtSignature
from Ui_mainwindow import Ui_MainWindow
class Main... | Qurl not defined in pyqt | Am learning to program python with qt using eric ide. But there seems to be one error i get.
Its says Global Qurl not defined or something. How can I define Qurl?
from PyQt4.QtGui import QMainWindow
from PyQt4.QtCore import pyqtSignature
from Ui_mainwindow import Ui_MainWindow
class MainWindow(QMainWindow, Ui_MainWin... | [
"The code you posted is mostly auto-generated by the Eric4 IDE as part of the tutorial you posted a link to.\nIf you read this page of the tutorial carefully, it mentions importing QUrl in the paragraph following a code snippet for the on_btnNavigate_released method (near the bottom of the page):\n\nNotice that for... | [
3,
0
] | [] | [] | [
"import",
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0008462606_import_pyqt_pyqt4_python.txt |
Q:
python implicit casting string into datetime object
I know that there are various post similar to this.
and well aware of the strptime and strftime functions.
My question is a little different.
What is the simplest way in python to implicitly cast string into a date/dateime object.
Or explicitly, a function that w... | python implicit casting string into datetime object | I know that there are various post similar to this.
and well aware of the strptime and strftime functions.
My question is a little different.
What is the simplest way in python to implicitly cast string into a date/dateime object.
Or explicitly, a function that will accept either a string that represents a date or a da... | [
"You might want to look at the dateutil module. It has a great date time parser.\n>>> from dateutil.parser import parse\n>>> print parse(\"1:00PM\")\n2011-12-11 13:00:00\n>>> print parse(\"1/1/2008\")\n2008-01-01 00:00:00\n>>> print type(parse(\"1/1/2008\"))\n<type 'datetime.datetime'>\n\nCombine that together with... | [
4,
0
] | [] | [] | [
"casting",
"date",
"datetime",
"python",
"string"
] | stackoverflow_0008466499_casting_date_datetime_python_string.txt |
Q:
LCS implementation in python2
I implemented an n-dimensional longest common subsequence in python, but it's buggy in 3d.
# -*- coding: utf-8 -*-
from collections import defaultdict
from operator import itemgetter
def count(limits):
idcs = [0] * len(limits)
while True:
yield tuple(idcs)
for... | LCS implementation in python2 | I implemented an n-dimensional longest common subsequence in python, but it's buggy in 3d.
# -*- coding: utf-8 -*-
from collections import defaultdict
from operator import itemgetter
def count(limits):
idcs = [0] * len(limits)
while True:
yield tuple(idcs)
for n in range(len(limits)-1, -1, -1):... | [
"Found the bug. itemgetter(0) for the max function, therefore wrong backpointers.\n"
] | [
0
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0008466426_debugging_python.txt |
Q:
a Regex for extracting sentence from a paragraph in python
I'm trying to extract a sentence from a paragraph using regular expressions in python.
Usually the code that I'm testing extracts the sentence correctly, but in the following paragraph the sentence does not get extracted correctly.
The paragraph:
"But in ... | a Regex for extracting sentence from a paragraph in python | I'm trying to extract a sentence from a paragraph using regular expressions in python.
Usually the code that I'm testing extracts the sentence correctly, but in the following paragraph the sentence does not get extracted correctly.
The paragraph:
"But in the case of malaria infections and sepsis, dendritic cells throu... | [
"Riccardo Murri's answer is correct, but I thought I'd throw a bit more light on the subject.\nThere was a similar question asked with regard to PHP: php sentence boundaries detection. My answer to that question includes handling the exceptions such as \"Mr.\", \"Mrs.\" and \"Jr.\". I've adapted that regex to work ... | [
7,
2,
0
] | [] | [] | [
"python",
"regex",
"text_segmentation"
] | stackoverflow_0008465335_python_regex_text_segmentation.txt |
Q:
Dynamic Widget creation based of configparser file
I am trying a piece of python based tkinter code with following objective:
(Please go through the objective, then I will take an example to explain what exactly i require and then in the end will post the script I have written)
Reads from a config file, which is ... | Dynamic Widget creation based of configparser file | I am trying a piece of python based tkinter code with following objective:
(Please go through the objective, then I will take an example to explain what exactly i require and then in the end will post the script I have written)
Reads from a config file, which is implemented using configparser module.
Based on options ... | [
"The easiest way to do this, IMO, is to use a dict to store the references to the dynamically created variables. You could use the label as the key. For example:\nvars = {}\nfor x in config_list['entry']:\n vars[x] = StringVar()\n entry = ttk.Entry(mainframe_entry, textvariable=vars[x])\n entry.grid()\n\nB... | [
1
] | [] | [] | [
"dynamic",
"python",
"tkinter"
] | stackoverflow_0008463699_dynamic_python_tkinter.txt |
Q:
Non-django analogue to manage.py
I'm looking for some python package providing basic functionality for writing and executing project-specific commands using some common interface. There is no problem to write it myself, but I already saw a project like this somewhere, so would you help me to remember it?
A:
fab... | Non-django analogue to manage.py | I'm looking for some python package providing basic functionality for writing and executing project-specific commands using some common interface. There is no problem to write it myself, but I already saw a project like this somewhere, so would you help me to remember it?
| [
"fabric can do this but it's more geared towards deployment and other such tasks. Scons is a build tool similar to make which can have custom commands. Paver is also like make/rake for doing things like this. You can also add custom commands to the distutils setup.py script. The standard libary cmd module is a ligh... | [
0,
0,
0
] | [] | [] | [
"command",
"python"
] | stackoverflow_0008465755_command_python.txt |
Q:
submit raw body containing json to REST api
I'm writing a rest service which accepts json documents with http post.
I can submit my data using my "Chrome Rest Console" plugin by putting a JSON document into the raw body field.
I'm trying to achieve the same using urllib2.
Using urllib2 i'm not able to post data un... | submit raw body containing json to REST api | I'm writing a rest service which accepts json documents with http post.
I can submit my data using my "Chrome Rest Console" plugin by putting a JSON document into the raw body field.
I'm trying to achieve the same using urllib2.
Using urllib2 i'm not able to post data unless I urlencode one or more key/value pairs whic... | [
"I'm not flagging the question as exact duplicate as I'm not sure this is what you meant. However from this other question:\nimport json\nimport urllib2\ndata = json.dumps([1, 2, 3])\nreq = urllib2.Request(url, data, {'Content-Type': 'application/json'})\nf = urllib2.urlopen(req)\nresponse = f.read()\nf.close()\n\n... | [
3
] | [] | [] | [
"python",
"rest",
"urllib2"
] | stackoverflow_0008467438_python_rest_urllib2.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.