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:
I can't figure out this error using time() in python
Here is my code:
# Given an Unix timestamp in milliseconds (ts), return a human-readable date and time (hrdt)
def parseTS(ts):
hrdt = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.time(int(ts)/1000))
return str(hrdt)
I am getting this error:
TypeError: ... | I can't figure out this error using time() in python | Here is my code:
# Given an Unix timestamp in milliseconds (ts), return a human-readable date and time (hrdt)
def parseTS(ts):
hrdt = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.time(int(ts)/1000))
return str(hrdt)
I am getting this error:
TypeError: time() takes no arguments (1 given)
UPDATE:
This worked:
... | [
"The time.time(int(ts)/1000) function is wrong.\nTry one of time.ctime, time.gtime() or time.localtime() functions to achieve what you want.\nPython Docs (Time)\n",
"As the error says, time.time() doesn't take any arguments, it just returns current time as floating point. Maybe you are thinking of time.ctime()?\... | [
4,
0,
0
] | [] | [] | [
"python",
"time"
] | stackoverflow_0007655531_python_time.txt |
Q:
How to deal with long lines of code and commands in Python
I've tried searching, but I couldn't find any situations similar to mine. I am writing a program and so far I've stuck to the no more than 79 characters in a line rule. However I'm not sure where to break lines in a few situations.
Here are the problem are... | How to deal with long lines of code and commands in Python | I've tried searching, but I couldn't find any situations similar to mine. I am writing a program and so far I've stuck to the no more than 79 characters in a line rule. However I'm not sure where to break lines in a few situations.
Here are the problem areas:
self.proc.stdin.write('(SayText "%s")\n' % text.repl... | [
"In my opinion, one of the reasons to prefer shorter lines is that it makes the programmer more likely to break up code into individual shorter lines which are easier to understand and to spot errors or better ways to do things in.\nfrom __future__ import print_function \n\nFMT_SAY_TEXT = '(SayText \"%s\")'\n\n\... | [
4,
3,
3,
3,
2,
1,
1
] | [] | [] | [
"line_breaks",
"pep8",
"python"
] | stackoverflow_0007655422_line_breaks_pep8_python.txt |
Q:
Python: add column to CSV file based on existing column
I already have written what I need for identifying and parsing the value I am seeking, I need help writing a column to the csv file (or a new csv file) with the parsed value. Here's some pseudocode / somewhat realistic Python code for what I am trying to do:
... | Python: add column to CSV file based on existing column | I already have written what I need for identifying and parsing the value I am seeking, I need help writing a column to the csv file (or a new csv file) with the parsed value. Here's some pseudocode / somewhat realistic Python code for what I am trying to do:
# Given a CSV file, this function creates a new CSV file with... | [
"I'd do it like this. I'm guessing that isWhatIWant() is something that is supposed to replace a field in-place.\nimport csv\n\ndef handleCSVfile(infilename, outfilename):\n with open(infilename, 'rb') as infile:\n with open(outfilename, 'wb') as outfile:\n reader = csv.reader(infile, linetermi... | [
3
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0007655581_csv_python.txt |
Q:
What is the Pythonic way to use private variables?
I recently posted a question on stackoverflow and I got a resolution.
Some one suggested to me about the coding style and I haven't received further input. I have the following question with reference to the prior query.
How can we declare private variables insi... | What is the Pythonic way to use private variables? | I recently posted a question on stackoverflow and I got a resolution.
Some one suggested to me about the coding style and I haven't received further input. I have the following question with reference to the prior query.
How can we declare private variables inside a class in python? I thought that by using a double u... | [
"Everything is public in Python, the __ is a suggestion by convention that you shouldn't use that function as it is an implementation detail. \nThis is not enforced by the language or runtime in any way, these names are decorated in a semi-obfuscated way, but they are still public and still visible to all code that... | [
9,
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007655895_python.txt |
Q:
Python parser to extract keyvalue pair from a output
I have just started with python and am posed with extracting data from a text output. The text output is in forms of a text blocks and has key value pairs
status active
name server01
read:bytes 4096
user abcd-12345-def
drive hgbcv-76s7e-hwte7ehxd-22byt82h
write... | Python parser to extract keyvalue pair from a output | I have just started with python and am posed with extracting data from a text output. The text output is in forms of a text blocks and has key value pairs
status active
name server01
read:bytes 4096
user abcd-12345-def
drive hgbcv-76s7e-hwte7ehxd-22byt82h
write:bytes 4096
read:requests 1
type disk
write:requests 1
siz... | [
"This is approximately what you want:\ndef create_dict(lines):\n return dict(line.split(\" \") for line in lines)\n\nlines1 = [\n \"status active\",\n \"name server01\",\n \"read:bytes 4096\",\n \"user abcd-12345-def\",\n \"drive hgbcv-76s7e-hwte7ehxd-22byt82h\",\n \"write:bytes 4096\",\n \"... | [
0
] | [] | [] | [
"parsing",
"python",
"text"
] | stackoverflow_0007655837_parsing_python_text.txt |
Q:
Arbitrary Amount of Tuple Unpacking With Common Date
Input
datas2 = [[("01/01/2011", 1), ("02/02/2011", "No"), ("03/03/2011", 11)],
[("01/01/2011", 2), ("03/03/2011", 22), ("22/22/2222", "no")],
[("01/01/2011", 3), ("03/03/2011", 33), ("22/22/2222", "333")]]
Intended Output
[("01/01/2011", 1, 2, 3), ("03/03/2011"... | Arbitrary Amount of Tuple Unpacking With Common Date | Input
datas2 = [[("01/01/2011", 1), ("02/02/2011", "No"), ("03/03/2011", 11)],
[("01/01/2011", 2), ("03/03/2011", 22), ("22/22/2222", "no")],
[("01/01/2011", 3), ("03/03/2011", 33), ("22/22/2222", "333")]]
Intended Output
[("01/01/2011", 1, 2, 3), ("03/03/2011", 11, 22, 33)]
[Update]
I was asked about real data and m... | [
"from collections import defaultdict\nimport itertools\n\nd = defaultdict(list)\nfor i,j in itertools.chain.from_iterable(datas2):\n if not isinstance(j, str):\n d[i].append(j)\n\nand d will be a dict like:\n{'01/01/2011': [1, 2, 3], '03/03/2011': [11, 22, 33]}\n\nSo you can format it later as tuples with... | [
3,
2
] | [] | [] | [
"iterable_unpacking",
"list_comprehension",
"python",
"tuples"
] | stackoverflow_0007656049_iterable_unpacking_list_comprehension_python_tuples.txt |
Q:
How should one manage hook specific files in the '.hg/' state directory?
I'm writing a series of changegroup and commit hooks using the native Python implementation of the Mercurial API. Part of this requires me to save certain bits of information that are specific to my hooks, such as the last revision ID that my... | How should one manage hook specific files in the '.hg/' state directory? | I'm writing a series of changegroup and commit hooks using the native Python implementation of the Mercurial API. Part of this requires me to save certain bits of information that are specific to my hooks, such as the last revision ID that my hooks actually saw.
I want to do this in a way where all external meta data i... | [
"The hgrc config files are intentional read-only and there's no internal API to write to these files. The only exception to this rule is that clone creates a default .hg/hgrc containing the clone source URL. So, no, don't try to use that.\nThe usual way to do this sort of thing is to just read and write your own pr... | [
5
] | [] | [] | [
"mercurial",
"mercurial_api",
"mercurial_hook",
"python"
] | stackoverflow_0007650781_mercurial_mercurial_api_mercurial_hook_python.txt |
Q:
matrix list comprehension mean
This is an offshoot of a previous question which started to snowball. If I have a matrix A and I want to use the mean/average of each row [1:] values to create another matrix B, but keep the row headings intact, how would I do this? I've included matrix A, my attempt at cobbling to... | matrix list comprehension mean | This is an offshoot of a previous question which started to snowball. If I have a matrix A and I want to use the mean/average of each row [1:] values to create another matrix B, but keep the row headings intact, how would I do this? I've included matrix A, my attempt at cobbling together a list comprehension, and the... | [
"Your list comprehension looks a little weird. You are using the same variable for the iterable and the item. \nThis approach seems to work:\ndef average(lst):\n return sum(lst) / len(lst)\n\nB = [(a[0], average(a[1:])) for a in A]\n\nI've created a function average for readability. It matches your expected v... | [
5,
1
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0007654247_list_list_comprehension_python.txt |
Q:
Django make query about .save()
DB TABLE (null is ok)
select * from TESTDB;
id | AAA | BBB | CCC |
======================
Django code
new_dataset = TESTDB(BBB = 222)
new_dataset.save()
I want to change code like this...
target_field = 'BBB'
new_dataset = TESTDB( target_field = 222 )
new_dataset.save()
How can I... | Django make query about .save() | DB TABLE (null is ok)
select * from TESTDB;
id | AAA | BBB | CCC |
======================
Django code
new_dataset = TESTDB(BBB = 222)
new_dataset.save()
I want to change code like this...
target_field = 'BBB'
new_dataset = TESTDB( target_field = 222 )
new_dataset.save()
How can I complete this code?
| [
"You can use dict as keyword arguments feature of Python:\ntarget_field = 'BBB'\nnew_dataset = TESTDB(**{target_field: 222})\nnew_dataset.save()\n\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007656175_django_python.txt |
Q:
Getting "IOError: [Errno 2] No such file or directory: 'myoutfile.csv' " error in Python
I am using this line to create a new file (the file does not exist):
with open(outfilename, 'rwb') as outfile:
And it gets this error:
IOError: [Errno 2] No such file or directory: 'myoutfile.csv'
I am trying to create this ... | Getting "IOError: [Errno 2] No such file or directory: 'myoutfile.csv' " error in Python | I am using this line to create a new file (the file does not exist):
with open(outfilename, 'rwb') as outfile:
And it gets this error:
IOError: [Errno 2] No such file or directory: 'myoutfile.csv'
I am trying to create this file, and I thought if I used 'w' that would create it if it doesn't exist. If it is permissio... | [
"The open mode passed to the open() function accepts only a specific few combinations of letters. In your case, 'rwb' is not one of those combinations, and Python is perhaps assuming that you meant 'rb'. Try:\nwith open(outfilename, 'wb') as outfile:\n\nThis opens the file for writing. If you need to both write to ... | [
4,
1
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0007656217_file_io_python.txt |
Q:
Clearing a cookie when using Twisted and Python
I am using twisted to fetch a page. For every callback to get a page....is the cookie reset? If not, how do I reset a cookie for every callback? Below is an example...I need a separate cookie for each reqest.
client.getPage(iUrl,headers,method='GET',cookies= {}).... | Clearing a cookie when using Twisted and Python | I am using twisted to fetch a page. For every callback to get a page....is the cookie reset? If not, how do I reset a cookie for every callback? Below is an example...I need a separate cookie for each reqest.
client.getPage(iUrl,headers,method='GET',cookies= {}).addCallback(self.processPage,iUrl).addErrback(self.pr... | [
"Yes. {} creates a new dictionary each time it is evaluated. Each of the 4 calls in your example uses a separate cookies dictionary. No cookies are shared between the requests.\n"
] | [
0
] | [] | [] | [
"cookies",
"python",
"twisted"
] | stackoverflow_0007656051_cookies_python_twisted.txt |
Q:
Python: How to sort a list of objects using attrgetter with case insensitivity
self.data = sorted(self.data, key=attrgetter('word'))
self.data is a list of Word objects. Word objects have 'word', 'definition', 'example' and 'difficulty' attributes. I want to sort by the 'word' strings of each Word object, and the... | Python: How to sort a list of objects using attrgetter with case insensitivity | self.data = sorted(self.data, key=attrgetter('word'))
self.data is a list of Word objects. Word objects have 'word', 'definition', 'example' and 'difficulty' attributes. I want to sort by the 'word' strings of each Word object, and the code above does that except it's not case insensitive. How would I go about making ... | [
"You can write your own key function:\nself.data = sorted(self.data, key = lambda w: w.word.lower())\n\n",
"Try something like:\nself.data = sorted(self.data, key=lambda w: attrgetter('word')(w).lower())\n\nThough, with that you would probably be much better off simply using:\nself.data = sorted(self.data, key=la... | [
2,
1
] | [] | [] | [
"attr",
"case_insensitive",
"key",
"python",
"sorting"
] | stackoverflow_0007656339_attr_case_insensitive_key_python_sorting.txt |
Q:
Regarding simple python date calc
I am trying to find out when someone will turn 1 billion seconds old. the user inputs when they were born. These values are then converted to seconds and then I add 1 billion seconds and convert back into a date. However, when I enter certain dates, python seems to mess up. Such a... | Regarding simple python date calc | I am trying to find out when someone will turn 1 billion seconds old. the user inputs when they were born. These values are then converted to seconds and then I add 1 billion seconds and convert back into a date. However, when I enter certain dates, python seems to mess up. Such an example is 1993/11/05 00:00:00 where ... | [
"Time calculations are tricky. Months don't all have 30 days, for example. Hours, minutes, and seconds are numbered starting from 0, but days and months are numbered starting from 1, creating off-by-one bugs in your calculations (hint, ask for month, then subtract one, do all the calculations, then add one when d... | [
1,
1
] | [] | [] | [
"date_arithmetic",
"python"
] | stackoverflow_0007656366_date_arithmetic_python.txt |
Q:
Using the emacs bindings in pycharm in OS X Lion
I am trying to use the emacs keybindings in Pycharm 1.5 in OS X 10.7. They all work except that ALT+B inserts a beta symbol rather than moving back a word. It's puzzling since ALT+F does correctly move forward a word.
Also, I was wondering if Pycharm has support fo... | Using the emacs bindings in pycharm in OS X Lion | I am trying to use the emacs keybindings in Pycharm 1.5 in OS X 10.7. They all work except that ALT+B inserts a beta symbol rather than moving back a word. It's puzzling since ALT+F does correctly move forward a word.
Also, I was wondering if Pycharm has support for moving between matching parentheses or brackets, lik... | [
"I found a solution on the JetBrains forum. The forum post includes a keymap as an attachment that globally disables the alt keys from generating symbols.\nQuoting the forum, \n\"So, after some digging around, I figured that this option key maps to these relatively unused symbols that are take precedence in the ope... | [
5,
2
] | [] | [] | [
"osx_lion",
"pycharm",
"python"
] | stackoverflow_0007637671_osx_lion_pycharm_python.txt |
Q:
numpy: syntax/idiom to cast (n,) array to a (n, 1) array?
I'd like to cast a numpy ndarray object of shape (n,) into one having shape (n, 1). The best I've come up with is to roll my own _to_col function:
def _to_col(a):
return a.reshape((a.size, 1))
But it is hard for me to believe that such a ubiquitous op... | numpy: syntax/idiom to cast (n,) array to a (n, 1) array? | I'd like to cast a numpy ndarray object of shape (n,) into one having shape (n, 1). The best I've come up with is to roll my own _to_col function:
def _to_col(a):
return a.reshape((a.size, 1))
But it is hard for me to believe that such a ubiquitous operation is not already built into numpy's syntax. I figure tha... | [
"I'd use the following:\na[:,np.newaxis]\n\nAn alternative (but perhaps slightly less clear) way to write the same thing is:\na[:,None]\n\nAll of the above (including your version) are constant-time operations.\n",
"np.expand_dims is my favorite when I want to add arbitrary axis.\nNone or np.newaxis is good for c... | [
10,
2
] | [] | [] | [
"arrays",
"casting",
"numpy",
"python",
"vector"
] | stackoverflow_0007635237_arrays_casting_numpy_python_vector.txt |
Q:
place a 0 in front of numbers in a list if they are less than ten (in python)
Write a Python program that will ask the user to enter a string of lower-case characters and then print its corresponding two-digit code. For example, if the input is "home", the output should be "08151305".
Currently I have my code wor... | place a 0 in front of numbers in a list if they are less than ten (in python) |
Write a Python program that will ask the user to enter a string of lower-case characters and then print its corresponding two-digit code. For example, if the input is "home", the output should be "08151305".
Currently I have my code working to make a list of all the number, but I cannot
get it to add a 0 in front of ... | [
"output.append(\"%02d\" % number) should do it. This uses Python string formatting operations to do left zero padding.\n",
"Or, use the built in function designed to do this - zfill():\ndef word ():\n # could just use a str, no need for a list:\n output = \"\"\n input = raw_input(\"please enter a string ... | [
12,
11,
5,
4
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007656754_list_python.txt |
Q:
How can I use Django to store a table of data into MySQL?
I am parsing a HTML file to pull down attributes for a list of cell phones. What is the best way to store this data in Python/Django so I can save each cell phone as a record in MySQL?
In other words, if I have data that looks like this:
NAME ATTRIBUTE-A A... | How can I use Django to store a table of data into MySQL? | I am parsing a HTML file to pull down attributes for a list of cell phones. What is the best way to store this data in Python/Django so I can save each cell phone as a record in MySQL?
In other words, if I have data that looks like this:
NAME ATTRIBUTE-A ATTRIBUTE-B ATTRIBUTE-C
iPhone 3 Hours 4 Hours 5 Hours
evo 4G 2 ... | [
"Create a model that matches your data. Parse your data (method will vary by if your data is json, xml, csv, xls, etc, etc). Set model fields to your data values and save.\nYou should read up on models (Django Models) for more information on how a django project interacts with databases\n"
] | [
5
] | [] | [] | [
"django",
"mysql",
"parsing",
"python"
] | stackoverflow_0007656939_django_mysql_parsing_python.txt |
Q:
Column_match([[1],[1,1]]) <--- how to make dimensions match with NA values?
Any flag for this? Please, see the intended.
>>> numpy.column_stack([[1], [1,2]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/pymodules/python2.7/numpy/lib/shape_base.py", line 296, in column_s... | Column_match([[1],[1,1]]) <--- how to make dimensions match with NA values? | Any flag for this? Please, see the intended.
>>> numpy.column_stack([[1], [1,2]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/pymodules/python2.7/numpy/lib/shape_base.py", line 296, in column_stack
return _nx.concatenate(arrays,1)
ValueError: array dimensions must agree... | [
"a pure numpy solution:\n>>> lili = [[1],[2,2],[3,3,3],[4,4,4,4]]\n>>> y = np.nan*np.ones((4,4))\n>>> y[np.tril_indices(4)] = np.concatenate(lili)\n>>> y\narray([[ 1., nan, nan, nan],\n [ 2., 2., nan, nan],\n [ 3., 3., 3., nan],\n [ 4., 4., 4., 4.]])\n\n>>> y[:,::-1]\narray([... | [
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007612767_numpy_python.txt |
Q:
Match "without this"
I need to remove all <p></p> that are only <p>'s in <td>.
But how it can be done?
import re
text = """
<td><p>111</p></td>
<td><p>111</p><p>222</p></td>
"""
text = re.sub(r'<td><p>(??no</p>inside??)</p></td>', r'<td>\1</td>', text)
How can I match without</p>inside?
A:
I would ... | Match "without this" | I need to remove all <p></p> that are only <p>'s in <td>.
But how it can be done?
import re
text = """
<td><p>111</p></td>
<td><p>111</p><p>222</p></td>
"""
text = re.sub(r'<td><p>(??no</p>inside??)</p></td>', r'<td>\1</td>', text)
How can I match without</p>inside?
| [
"I would use minidom. I stole the following snippet from here which you should be able to modify and work for you:\nfrom xml.dom import minidom\n\ndoc = minidom.parse(myXmlFile)\nfor element in doc.getElementsByTagName('MyElementName'):\n if element.getAttribute('name') in ['AttrName1', 'AttrName2']:\n pa... | [
1,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007652266_python_regex.txt |
Q:
better way to communicate between python script and android application
In my android project I am reading a xml file which are continuously updated by one python script. and for update data I am continuosly reading the xml file and whenever the data is updated in xml file by python script I used that in my app.
B... | better way to communicate between python script and android application | In my android project I am reading a xml file which are continuously updated by one python script. and for update data I am continuosly reading the xml file and whenever the data is updated in xml file by python script I used that in my app.
But now problem is, because of python script and my android project continuosl... | [
"You could try using Sockets to communicate. http://download.oracle.com/javase/tutorial/networking/sockets/clientServer.html\n"
] | [
1
] | [] | [] | [
"android",
"communication",
"python"
] | stackoverflow_0007657296_android_communication_python.txt |
Q:
How to remove extra space for the 'print' command in python?
I'm new to python, I'm using v2.7
#Filename:ReverseNumber.py
data=int(raw_input("Enter any number: "))
print "Reverse of the number: ",
while data!=0:
a=data%10
print a,
data=data/10
So the output should come like :
Enter any number: 123
Rev... | How to remove extra space for the 'print' command in python? | I'm new to python, I'm using v2.7
#Filename:ReverseNumber.py
data=int(raw_input("Enter any number: "))
print "Reverse of the number: ",
while data!=0:
a=data%10
print a,
data=data/10
So the output should come like :
Enter any number: 123
Reverse of the number: 321
but instead of this in the second line it... | [
"You could modify your approach in a number of ways:\nCreate a list of your values, then join them with a blank string for printing:\nout = []\nwhile data != 0:\n out.append(data % 10)\n data /= 10\nprint ''.join(map(str, out))\n\nYou could skip the whole integer conversion step and just reverse the incoming stri... | [
4,
2,
0
] | [
"Make a empty variable for purpose of storing reversed number, append every digit to it in a loop and then do the printing.\na = ''\nwhile data!=0:\n a += data%10\n data=data/10\nprint a\n\n"
] | [
-2
] | [
"python"
] | stackoverflow_0007657396_python.txt |
Q:
Python Shell Wrapper
I'm trying to write a simple Python version of the time command line program, except that instead of displaying the real/usr/sys times to the shell, it'll record it to a database.
What I currently have is:
wrapper.py
#!/usr/bin/python
import sys
from subprocess import Popen, PIPE
cmd = 'time '... | Python Shell Wrapper | I'm trying to write a simple Python version of the time command line program, except that instead of displaying the real/usr/sys times to the shell, it'll record it to a database.
What I currently have is:
wrapper.py
#!/usr/bin/python
import sys
from subprocess import Popen, PIPE
cmd = 'time ' + (' '.join(['"%s"' % v i... | [
"First, why are you handling the I/O with python at all? Just let the sub process's stdout and stderr go to the same place as python's. Second, instead of actually using the time command, you can retrieve the resources directly from python. Try something like this:\n#! /usr/bin/python\n\nimport os\nimport resour... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007652161_python.txt |
Q:
Creating "Typed" Lists in Python 2.5
I'm familiar with the C# syntax to, for example, create a list of strings by List<string> MyList.
Is there a similar syntax in python that will cause it to fail if I attempt to add a type that is not in the collection type?
A:
No. You will need to create a custom class that ... | Creating "Typed" Lists in Python 2.5 | I'm familiar with the C# syntax to, for example, create a list of strings by List<string> MyList.
Is there a similar syntax in python that will cause it to fail if I attempt to add a type that is not in the collection type?
| [
"No. You will need to create a custom class that implements the __*item__() methods appropriately.\n",
"As others have said, Python doesn't have anything like that built in.\nIf you wanted to make something like that, you would subclass the built-in list() class, and make all the methods that allow inserting or a... | [
1,
1
] | [] | [] | [
"c#",
"list",
"python"
] | stackoverflow_0007655847_c#_list_python.txt |
Q:
Python MySQL installing wrongly on Mac OS X 10.6 i386
When trying to install MySQL's python bindings, MySQLdb, I followed the instructions to build and install on my MacBook running Mac OS X 10.6 i386, and after entering the following line into the terminal:
user-152-3-158-79:MySQL-python-1.2.3c1 jianweigan$ sudo ... | Python MySQL installing wrongly on Mac OS X 10.6 i386 | When trying to install MySQL's python bindings, MySQLdb, I followed the instructions to build and install on my MacBook running Mac OS X 10.6 i386, and after entering the following line into the terminal:
user-152-3-158-79:MySQL-python-1.2.3c1 jianweigan$ sudo python setup.py build
I get the following errors:
running ... | [
"It appears you have installed and are using a python.org python2.6. Because that installer is designed to work for a range of systems, to build extensions with that python on 10.6, you need to install the optional 10.4 SDK which is part of the Xcode package on the Snow Leopard installation DVD or machine restore ... | [
9,
1
] | [
"Well the error is pretty clear, do you have xcode installed? http://developer.apple.com/tools/Xcode/\nYou can look at a more detailed solution to this in http://blog.some-abstract-type.com/2009/09/mysql-python-and-mac-os-x-106-snow.html which includes downloading the latest xcode. Hope it helps.\n"
] | [
-1
] | [
"macos",
"mysql",
"python"
] | stackoverflow_0001562314_macos_mysql_python.txt |
Q:
ValueError when I'm trying to implement lost password
I was playing around with Python, I'm new in Python Language so I'm trying to reset a lost password but I come across ValueError Exception here's my code:
models.py:
def forgot(request):
if request.method == 'POST':
try:
user = User.obje... | ValueError when I'm trying to implement lost password | I was playing around with Python, I'm new in Python Language so I'm trying to reset a lost password but I come across ValueError Exception here's my code:
models.py:
def forgot(request):
if request.method == 'POST':
try:
user = User.objects.get(username=request.POST['username'])
lost... | [
"The third parameter to the url function is supposed to be a dictionary consisting of extra arguments to pass to the view function. For some reason, you've got 'blog.apps.homepage.views.forgot' there instead - but you've already set the view function, forgot.\nBy the way, note that Django already includes a \"reset... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007658395_django_python.txt |
Q:
Can someone explain this odd Python/Django import behaviour?
I have a project where the directory structure looks like:
mywebsite/
manage.py
__init__.py
myapp/
models/
__init__.py
base.py
myapp/models/base.py contains:
class X(object):
pass
myapp/models/__init__.py... | Can someone explain this odd Python/Django import behaviour? | I have a project where the directory structure looks like:
mywebsite/
manage.py
__init__.py
myapp/
models/
__init__.py
base.py
myapp/models/base.py contains:
class X(object):
pass
myapp/models/__init__.py contains:
from base import X
Now, if I do manage.py shell I can ... | [
"When you open a Django shell, it adds the path to your project to sys.path. You can see this by running import sys; print sys.path on a Django shell and on a normal python shell and comparing the output. You will note that the output from the Django shell includes the path to the mywebsite directory as the first i... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007658438_django_python.txt |
Q:
Python logging in Django
I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.
I have the root logger ... | Python logging in Django | I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.
I have the root logger going to sys.stderr, and I hav... | [
"Allow me to answer my own question. The underlying problem here is that settings.py gets imported twice, or maybe even more (See here). (I still don't understand why this is. Maybe some Django expert could explain that to me.) This seems to be true of some other modules as well. At this point I don't think it... | [
30,
24,
14,
11,
6,
3,
3,
3,
1,
0,
0
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0000342434_django_logging_python.txt |
Q:
Diamond python with exactly 19 lines
Possible Duplicate:
ASCII Python Art # 2
i = 10
while i>0:
print i*'*' + 2*(10-i)*' ' + i*'*'
i -=1
for x in range(1,11):
print x* '*' + 2*(10-x)*' '+ x*'*'
x +=1
I am trying to make a asterisk diamond with 19 lines.
I get 20 instead.
This is what I want:
**... | Diamond python with exactly 19 lines |
Possible Duplicate:
ASCII Python Art # 2
i = 10
while i>0:
print i*'*' + 2*(10-i)*' ' + i*'*'
i -=1
for x in range(1,11):
print x* '*' + 2*(10-x)*' '+ x*'*'
x +=1
I am trying to make a asterisk diamond with 19 lines.
I get 20 instead.
This is what I want:
********************
********* *********
*... | [
"The basic idea is to decide which loop should print the line with just a single start on each side. Then modify the other loop not to print that line (i.e. end or start with the 2-star line).\nChange \nfor x in range(1,11):\n\nto\nfor x in range(2,11):\n\nAlso, you can get rid of the very last line, as the second ... | [
2,
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007657860_python.txt |
Q:
Finding index of the same elements in a list
Suppose I have to find each index of letter 'e' in the word "internet":
letter = 'e'
word = 'internet'
idx = word.index(letter)
But this code gives only the first index. How can I find the rest of them?
A:
Try using enumerate in a list comprehension:
[index for (inde... | Finding index of the same elements in a list | Suppose I have to find each index of letter 'e' in the word "internet":
letter = 'e'
word = 'internet'
idx = word.index(letter)
But this code gives only the first index. How can I find the rest of them?
| [
"Try using enumerate in a list comprehension:\n[index for (index, letter) in enumerate(word) if letter == 'e']\n\n",
"Mark's answer is better for a single letter. I'm adding this in case your real substring is longer than a single character.\nIf you want to use str.index(), it can take an optional start position ... | [
13,
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0007658932_python.txt |
Q:
Display label on each marker point in 2D plot
I'm using Matplotlib to create a projection of the ensemble onto PC1 and PC2:
plt.figure(figsize=(5,4))
showProjection(ensemble, pca[:2])
plt.show ()
Can anyone suggest me on how to label each marker point. Each point represent solved X-ray structure of proteins. I wa... | Display label on each marker point in 2D plot | I'm using Matplotlib to create a projection of the ensemble onto PC1 and PC2:
plt.figure(figsize=(5,4))
showProjection(ensemble, pca[:2])
plt.show ()
Can anyone suggest me on how to label each marker point. Each point represent solved X-ray structure of proteins. I want to check which point represent each protein. Is ... | [
"You can annotate a specific point in the image using plt.text(x,y,str). However, it looks like that will belong inside the showProjection function. Is that something you wrote yourself, or imported from some package?\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007657336_matplotlib_python.txt |
Q:
How can I use a mix of Appengine's OpenID and facebook OAuth for authentication on AppEngine?
Appengine supports federated login in which arbitrary OpenID providers can be added to the list of parties who can authenticate a user. However, some organizations - notably facebook - don't support OpenID. How is it poss... | How can I use a mix of Appengine's OpenID and facebook OAuth for authentication on AppEngine? | Appengine supports federated login in which arbitrary OpenID providers can be added to the list of parties who can authenticate a user. However, some organizations - notably facebook - don't support OpenID. How is it possible to combine the OpenID support provided with GAE with mechanisms that can support OAuth or othe... | [
"I've done a little bit of digging on this and my conclusion is that it is not possible to integrate the standard Appengine authentication mechanisms (ie those provided 'for free' with Appengine) with facebook's OAuth. More specifically, the app.yaml login controls can only relate to Google's standard mechanisms an... | [
4,
2
] | [] | [] | [
"facebook",
"google_app_engine",
"openid",
"python"
] | stackoverflow_0007648264_facebook_google_app_engine_openid_python.txt |
Q:
selecting unicode characters from text file or webpage
I am able to syllabalise the devnagari words as shown on the following page.
https://gist.github.com/950405
But what I want to do is to find the words those start with "ह" from the following webpage.
http://www.sacred-texts.com/hin/mbs/mbs12030.htm
How it can ... | selecting unicode characters from text file or webpage | I am able to syllabalise the devnagari words as shown on the following page.
https://gist.github.com/950405
But what I want to do is to find the words those start with "ह" from the following webpage.
http://www.sacred-texts.com/hin/mbs/mbs12030.htm
How it can done using python?
| [
"If your words are unicode strings, collected in a list words, then the following snippet shows you all words beginning with \"x\"\nfor word in words:\n if word.startswith(u\"x\"):\n print word\n\nOr if you want to get a list of all words starting with u\"x\", you can use list comprehension:\nselected_wo... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007659244_python.txt |
Q:
show fields containing html tag in django templates like ordinary html tag
I have a model named news,news have a field named description,I use a RichTextArea to get the value of description from user,so user can enter html tags into this field,now I show the value of description in my template like this:
<div>
<h... | show fields containing html tag in django templates like ordinary html tag | I have a model named news,news have a field named description,I use a RichTextArea to get the value of description from user,so user can enter html tags into this field,now I show the value of description in my template like this:
<div>
<h1>{{news.Title}}</h1>
{{news.Description}}
</div>
imagine that description fiel... | [
"You need the safe filter:\n{{news.Description|safe}}\n\n"
] | [
13
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007659769_django_python.txt |
Q:
getting rid of characters in an output in python
If someone writes 'james', I want my program to style their name as j*a*m*e*s
I thought it would be simple:
for letter in name:
print letter+' *',
but I don't know how to get rid of the last asterix at the end.
I had a friend show me in C though...so I understand ... | getting rid of characters in an output in python | If someone writes 'james', I want my program to style their name as j*a*m*e*s
I thought it would be simple:
for letter in name:
print letter+' *',
but I don't know how to get rid of the last asterix at the end.
I had a friend show me in C though...so I understand the underlying concept, just not how to achieve it.
C ... | [
"There is an easier way in Python:\n>>> '*'.join('james')\n'j*a*m*e*s'\n\nThis makes use of the fact that in Python, strings are iterable.\n",
"It's easy:\nname = 'james'\nprint '*'.join(name)\n\nEdit:\nTo understand how its done here is a more verbose code that explains the concept.\nname = 'james'\n\ndecorated_... | [
8,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007659986_python.txt |
Q:
How to tie radiobutton selections with array data
I'm attempting to write a GUI searchable bacteria database with the database array embedded in the code using tkinter python 2.7. Choosing certain criteria via radiobuttons selectively searches the array, then hitting the 'Identify' button should print out the id ... | How to tie radiobutton selections with array data | I'm attempting to write a GUI searchable bacteria database with the database array embedded in the code using tkinter python 2.7. Choosing certain criteria via radiobuttons selectively searches the array, then hitting the 'Identify' button should print out the id of all bacteria which match those selections as a label... | [
"This solution uses a probability comparison instead of + and - (i.e., each bacteria has X probability of getting a + score and 1-X probability of getting a - score.) But this code will tie in the radiobuttons to the data matrix and then rank the top ten scoring bacteria accordingly. All the pieces are cooperatin... | [
0
] | [] | [] | [
"arrays",
"python",
"radio_button",
"tkinter"
] | stackoverflow_0007410037_arrays_python_radio_button_tkinter.txt |
Q:
Xcode Target Phase Python Script
I am trying to add a Python script to into my project to obtain the build and marketing numbers directly from Git.
I have created a new target phase and that runs a script as explained in:
http://yeahrightkeller.com/2008/10/19/xcode-run-script-build-phase-tip/
And I have written a ... | Xcode Target Phase Python Script | I am trying to add a Python script to into my project to obtain the build and marketing numbers directly from Git.
I have created a new target phase and that runs a script as explained in:
http://yeahrightkeller.com/2008/10/19/xcode-run-script-build-phase-tip/
And I have written a Python script that parses the program ... | [
"I have the same problem, and I wanted to keep the python version because handling the plist via NSMutableDictionary is much nicer than using regex on Info.plist.\nBuilding on Maxence's answer, the solution was to strip the python code out of the Run Script build phase into a gitversion.py file:\n#!/usr/bin/env pyt... | [
2,
1,
1,
0
] | [] | [] | [
"iphone",
"python",
"xcode"
] | stackoverflow_0001698494_iphone_python_xcode.txt |
Q:
Adding multiple images to one canvas in Python
I want to load a number of images from harddrive and place them on a larger white background. And I want to do it in Python. I am wondering what is the best way of doing that. I am using a windows machine and I can use any library I want. Any pointer to a webpage or a... | Adding multiple images to one canvas in Python | I want to load a number of images from harddrive and place them on a larger white background. And I want to do it in Python. I am wondering what is the best way of doing that. I am using a windows machine and I can use any library I want. Any pointer to a webpage or a sample code that can point me to a good direction w... | [
"A very popular image processing library for Python is PIL. The official PIL tutorial might be useful, especially the section about \"Cutting, Pasting and Merging Images\".\n",
"PIL isn't enough. Try also with PIL the aggdraw library.\nBut aggdraw also isn't enough. It works poorly with transparency. I mean 0.5-1... | [
1,
0
] | [] | [] | [
"image",
"python"
] | stackoverflow_0004777243_image_python.txt |
Q:
How does one programmatically determine if "write" system call is atomic on a particular file?
In some cases the coder cannot rely on system calls being atomic, e.g. if the file is on a NFS filesystem. (c.f. NFS Overview, FAQ and HOWTO Documents). But atomic system calls are ultimately required for most database... | How does one programmatically determine if "write" system call is atomic on a particular file? | In some cases the coder cannot rely on system calls being atomic, e.g. if the file is on a NFS filesystem. (c.f. NFS Overview, FAQ and HOWTO Documents). But atomic system calls are ultimately required for most database work. (c.f. Atomicity of database systems).
Is there a standard (and OS independent) way of confirm... | [
"The write call as defined in POSIX has no atomicity guarantee at all. So you don't need to confirm anything, it's not atomic.\nIt doesn't even guarantee that the data will have reached the hard drive (if there is a drive at all) if it completes successfully. Successfully reading back the data doesn't give you any ... | [
4
] | [] | [] | [
"atomic",
"c",
"portability",
"python",
"system_calls"
] | stackoverflow_0007660293_atomic_c_portability_python_system_calls.txt |
Q:
Setting name of variable in a class with a function?
I have a class and I want to do something like the following:
class my_class:
def my_func(self, var_name):
self.var_name = 5
a = my_class()
a.my_func('yes')
print(a.yes)
I am not sure how to set the class variable name using the function however ... | Setting name of variable in a class with a function? | I have a class and I want to do something like the following:
class my_class:
def my_func(self, var_name):
self.var_name = 5
a = my_class()
a.my_func('yes')
print(a.yes)
I am not sure how to set the class variable name using the function however
| [
">>> class my_class(object):\n... def my_func(self,var_name):\n... setattr(self,var_name,5)\n...\n>>> a = my_class()\n>>> a.my_func('yes')\n>>> a.yes\n5\n\n"
] | [
5
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0007660427_oop_python.txt |
Q:
Why a function is executed two times?
I import a function from a package:
from read_video import getData
I wrote this function. It has the following structure:
def getData()
print 'start'
...
print 'end'
Then I call this function:
video_data = getData()
On the screen I see;
start
end
start
end
I thoug... | Why a function is executed two times? | I import a function from a package:
from read_video import getData
I wrote this function. It has the following structure:
def getData()
print 'start'
...
print 'end'
Then I call this function:
video_data = getData()
On the screen I see;
start
end
start
end
I thought that may be my function calls itself. Bu... | [
"Modify the code to this:\nimport pdb\n\ndef getData():\n print 'start'\n pdb.set_trace()\n ...\n\nAnd once you've dropped in an interpreter prompt, press w to see a call trace. This should help you figure things out.\n",
"I got the answer for my own question. My code was saved in the dimension.py file. So, I ... | [
1,
0
] | [] | [] | [
"call",
"execution",
"python",
"return"
] | stackoverflow_0007659567_call_execution_python_return.txt |
Q:
Installing a package in Python virtualenv still causes it to be installed globally
I installed virtualenv and created a virtual environment called ENV1.
Then I activated the environment by running 'source bin/activate'. I am sure the virtual environment is activated because the command prompt has changed, reflecti... | Installing a package in Python virtualenv still causes it to be installed globally | I installed virtualenv and created a virtual environment called ENV1.
Then I activated the environment by running 'source bin/activate'. I am sure the virtual environment is activated because the command prompt has changed, reflecting the new environment.
Then from that command prompt, I ran 'pip install lpthw.web'. I ... | [
"Check which pip you are actually running (which pip), also try running pip -E path-to-your-env install ....\n"
] | [
3
] | [] | [] | [
"pip",
"python",
"virtualenv"
] | stackoverflow_0007657937_pip_python_virtualenv.txt |
Q:
Python pause thread execution
Is there a way to "pause" the main python thread of an application perminantly?
I have some code that fires off two threads
class start():
def __init__(self):
Thread1= functions.threads.Thread1()
Thread1.setDaemon(True)
Thread1.start()
Thread2= func... | Python pause thread execution | Is there a way to "pause" the main python thread of an application perminantly?
I have some code that fires off two threads
class start():
def __init__(self):
Thread1= functions.threads.Thread1()
Thread1.setDaemon(True)
Thread1.start()
Thread2= functions.threads.Thread2()
Thr... | [
"Use join:\nThread1.join()\nThread2.join()\n\n\nAlso note that setDaemon is the old API. \nThread1.daemon = True\n\nis the preferred way now.\n",
"The whole point of daemon threads is to not prevent the application from being terminated if any of them is still running. You obviously want your threads to keep the ... | [
4,
4,
4
] | [] | [] | [
"python",
"python_multithreading"
] | stackoverflow_0007661053_python_python_multithreading.txt |
Q:
psycopg2 + pgbouncer. Async mode with gevent error
I've got an application psycopg2 + pgbouncer + gevent. Asynchronous application, ie one process serves multiple requests. Asynchronous access to database appeared in the latest version of psycopg2, if rather then 2.2. But just in this release introduces bug for wh... | psycopg2 + pgbouncer. Async mode with gevent error | I've got an application psycopg2 + pgbouncer + gevent. Asynchronous application, ie one process serves multiple requests. Asynchronous access to database appeared in the latest version of psycopg2, if rather then 2.2. But just in this release introduces bug for which there is a lot of disconnections from pgbouncer.
In... | [
"You are probably not calling connection.close(). Before Psycopg 2.2 an implicit ROLLBACK was issued on connection delete, but this condition couldn't be guaranteed anymore (and even before it was considered not safe).\nSee http://initd.org/psycopg/docs/connection.html#connection.close\n"
] | [
4
] | [] | [] | [
"gevent",
"pgbouncer",
"postgresql",
"psycopg",
"python"
] | stackoverflow_0007658714_gevent_pgbouncer_postgresql_psycopg_python.txt |
Q:
python: split string after a character
I have a string with two "-"
467.2-123-hdxdlfow
I want to remove everything after the second "-" so that I get "467.2-123". What is the best way to do this?
A:
before, sep, after = theString.rpartition("-")
This splits the str about the last occurrence of "-" and your ans... | python: split string after a character | I have a string with two "-"
467.2-123-hdxdlfow
I want to remove everything after the second "-" so that I get "467.2-123". What is the best way to do this?
| [
"before, sep, after = theString.rpartition(\"-\")\n\nThis splits the str about the last occurrence of \"-\" and your answer would be the variable before.\n",
"In [6]: \"-\".join('467.2-123-hdxdlfow'.split('-')[0:2])\nOut[6]: '467.2-123'\n\n",
" >>> s = '467.2-123-hdxdlfow'\n >>> s[:s.rfind('-')]\n '467.2-123'\n... | [
13,
10,
2,
2,
1,
0,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0007660847_python_regex_string.txt |
Q:
python error get object value
I'm a bit new in programming with python, but I have do this code:
dimValue = 0
........
elif event[0] == "control" and body["location"] == location and body["action"] == "on":
auxValue = int(body["dim"])
print("AuxValue = " + str(auxValue))
if auxValue > dimValue:
... | python error get object value | I'm a bit new in programming with python, but I have do this code:
dimValue = 0
........
elif event[0] == "control" and body["location"] == location and body["action"] == "on":
auxValue = int(body["dim"])
print("AuxValue = " + str(auxValue))
if auxValue > dimValue:
print("entrou")
dimContro... | [
"It sounds like neither the if block nor the elif block are being entered. This probably occurs when auxValue equals dimValue; then neither of the criteria evaluate to true. You could change > to >= or change < to <=, depending on which block you want to run when they are equal.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007661279_python.txt |
Q:
Set a list name in a class, using a function
I have a class to import data from a CSV file, and a function that takes the filename and a name for the output list. I want to set the name of the self.data_name to be self.info using the setattr() function. How can I do this?
import csv
class import_data:
def im... | Set a list name in a class, using a function | I have a class to import data from a CSV file, and a function that takes the filename and a name for the output list. I want to set the name of the self.data_name to be self.info using the setattr() function. How can I do this?
import csv
class import_data:
def import_csv(self, filename_csv, data_name):
... | [
"Try this:\nclass import_data:\n def import_csv(self, filename_csv, data_name):\n with open(filename_csv, 'r') as f:\n setattr(self, data_name, list(csv.reader(f)))\n print(\"finished importing data\")\n\n",
"You're going to have to replace all usages of self.data_name in the import_c... | [
2,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0007661383_oop_python.txt |
Q:
New to OpenGL and deprecation
I've begun playing around with OpenGL in Python using PyOpenGL 3.0.1b.
I looked at some sample code and started running it and modifying it etc. All was well until I became a little less ignorant.
On http://pyopengl.sourceforge.net/documentation/manual-3.0/index.xhtml the OpenGL func... | New to OpenGL and deprecation | I've begun playing around with OpenGL in Python using PyOpenGL 3.0.1b.
I looked at some sample code and started running it and modifying it etc. All was well until I became a little less ignorant.
On http://pyopengl.sourceforge.net/documentation/manual-3.0/index.xhtml the OpenGL functions are listed as well as whether... | [
"Thanks to Jason L. McKesson\nNo deprecated code fantastic examples and tutorials here (in OpenGL 3.3)\nhttp://www.arcsynthesis.org/gltut/index.html\nAnd another one without too much explanation here (in OpenGL 4.x and 3.3)\nhttp://openglbook.com/the-book/\n",
"OpenGL ES 2.0 is in fact very similar to OpenGL 3, w... | [
3,
2,
2
] | [] | [] | [
"deprecated",
"opengl",
"opengl_3",
"pyopengl",
"python"
] | stackoverflow_0002079038_deprecated_opengl_opengl_3_pyopengl_python.txt |
Q:
Django DynamicSites database error
I'm trying to get the Django DynamicSites (multi-site) application (see https://bitbucket.org/uysrc/django-dynamicsites/src and http://blog.uysrc.com/2011/03/23/serving-multiple-sites-with-django/) up and running on Django 1.3.1, but I keep getting "Database Error: No such column... | Django DynamicSites database error | I'm trying to get the Django DynamicSites (multi-site) application (see https://bitbucket.org/uysrc/django-dynamicsites/src and http://blog.uysrc.com/2011/03/23/serving-multiple-sites-with-django/) up and running on Django 1.3.1, but I keep getting "Database Error: No such column django_site.folder_name."
I've set up a... | [
"Apparently, there is a bug in the package that doesn't add the folder_name and subdomains columns to the Sites table in the Django database. Using a database browser, I've added them manually (using the ALTER TABLE command) and DynamicSites appears to work now. \n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007652149_django_python.txt |
Q:
How can I fix Vim's line breaking behavior for long lines in Python?
So here's my problems. Let's say I have a Python file and I'm typing a really long line, like the last one here:
class SomeClass(object):
def some_method(self):
some_variable = SomeOtherClass.some_other_method(some_parameter=some_value)
Wh... | How can I fix Vim's line breaking behavior for long lines in Python? | So here's my problems. Let's say I have a Python file and I'm typing a really long line, like the last one here:
class SomeClass(object):
def some_method(self):
some_variable = SomeOtherClass.some_other_method(some_parameter=some_value)
When I type this in Vim, this happens:
class SomeClass(object):
def some_m... | [
"You aren't setting linebreak. Without it, vim ignores the breakat variable. See here for details, and lots of vim goodness. Also note that you need to set nolist as it breaks linebreak.\nAnother blog post dealing with word wrapping here. This one notes that some filetypes do not auto include the format options \"t... | [
3
] | [] | [] | [
"pep8",
"python",
"vim"
] | stackoverflow_0007662000_pep8_python_vim.txt |
Q:
What are the different options for social authentication on Appengine - how do they compare?
[This question is intended as a means to both capture my findings and sanity check them - I'll put up my answer toute suite and see what other answers and comments appear.]
I spent a little time trying to get my head aroun... | What are the different options for social authentication on Appengine - how do they compare? | [This question is intended as a means to both capture my findings and sanity check them - I'll put up my answer toute suite and see what other answers and comments appear.]
I spent a little time trying to get my head around the different social authentication options for (python) Appengine. I was particularly confused ... | [
"In my research on this question I found that there are essentially three options:\n\nUse Google's authentication mechanisms (including their federated login via OpenID)\n\nPros:\n\nYou can easily check who is logged in via the Users service provided with Appengine\nGoogle handles the security so you can be quite s... | [
11
] | [] | [] | [
"facebook_authentication",
"google_app_engine",
"oauth",
"openid",
"python"
] | stackoverflow_0007660059_facebook_authentication_google_app_engine_oauth_openid_python.txt |
Q:
What is the best way to configure a django project
I am about to set up a project, and am wondering what the best way to do it is.
I notice some open source files have an "apps" directory, which stores all third-party apps, etc.
I was looking at the following two projects
https://github.com/josephmisiti/NewsBlur
h... | What is the best way to configure a django project | I am about to set up a project, and am wondering what the best way to do it is.
I notice some open source files have an "apps" directory, which stores all third-party apps, etc.
I was looking at the following two projects
https://github.com/josephmisiti/NewsBlur
https://github.com/dkukral/everyblock
My project will con... | [
"This question has been covered several times. See:\n\nDjango tips: laying out an application\nWeb Application (Django) typical project folder structure\nBest practice folder hierarchy of a Django Web App\n\n",
"I don't think there is an exact 'best way' which is suitable for every project. But there are some gen... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007654952_django_python.txt |
Q:
Generate CSS background colour from a primary key that is drastically different from the next primary key
In Python I'm generating a 6 digit hex from the primary key of a model (in Django) that I can use as the CSS background colour for a div on a page.
If I have two primary keys which are close together how can ... | Generate CSS background colour from a primary key that is drastically different from the next primary key | In Python I'm generating a 6 digit hex from the primary key of a model (in Django) that I can use as the CSS background colour for a div on a page.
If I have two primary keys which are close together how can I generate noticeably different colours. For example using the primary keys 24 and 25 give almost the same colo... | [
"It would be best not to generate colors from keys at all.\nBut if you want to/need to, you can outline the number to 24 bits. Then reverse the number. The lowest bits now become the highest. \nThis way, increment of 1 is always noticable, although numbers that are a bit further apart may still be very much the sam... | [
0,
0
] | [] | [] | [
"css",
"python"
] | stackoverflow_0007659582_css_python.txt |
Q:
Dynamic library problems with Python and libstdc++
Executive summary: a Python module is linked against a different version of libstdc++.dylib than the Python executable. The result is that calls to iostream from the module crash.
Backstory
I'm creating a Python module using SWIG on an older computer (running 10.5... | Dynamic library problems with Python and libstdc++ | Executive summary: a Python module is linked against a different version of libstdc++.dylib than the Python executable. The result is that calls to iostream from the module crash.
Backstory
I'm creating a Python module using SWIG on an older computer (running 10.5.8). For various reasons, I am using GCC 4.5 (installed ... | [
"Solved it. I discovered that this problem is not too uncommon when mixing GCC versions on the mac. After reading this solution for mpich and checking the mpich source code, I found that the solution is to add the following flag to gcc on mac systems:\n-flat_namespace\n\nI am so happy. I wish this hadn't taken me a... | [
2
] | [
"Run Python in GDB, set a breakpoint on malloc_error_break. That will show you what's being freed that's not allocated. I doubt that this is an error between ABIs between the versions of libstdc++.\n"
] | [
-3
] | [
"dll",
"gcc",
"macos",
"macports",
"python"
] | stackoverflow_0007561640_dll_gcc_macos_macports_python.txt |
Q:
How do I save values to an anonymous cookie based session in Pyramid using Beaker
I have a Pyramid application using Beaker Encrypted cookie sessions. I can log a user in using a RequestWithUserAttribute, pyramid.security.authenticated_userid(), remember() and forget() just fine.
However, the majority of users wi... | How do I save values to an anonymous cookie based session in Pyramid using Beaker | I have a Pyramid application using Beaker Encrypted cookie sessions. I can log a user in using a RequestWithUserAttribute, pyramid.security.authenticated_userid(), remember() and forget() just fine.
However, the majority of users will never log in, and there is a specific value I'd like to save in a cookie (encrypted ... | [
"Sessions and Authentication in Pyramid (and in general) are disjoint concepts. There are a lot of people who learn the way to store the authenticated user \"is in a session\", but in no way is this a requirement. The point of a session is to store arbitrary data for a visitor to your site across requests. That cou... | [
3
] | [] | [] | [
"beaker",
"pylons",
"pyramid",
"python",
"session"
] | stackoverflow_0007655784_beaker_pylons_pyramid_python_session.txt |
Q:
Sorting a txt file with Python
I need some help printing out a sorted txt logfile.
there is no problem with the printing except that I dont want to print out the same IP number more than once.
This is my code.
text_file = open("access_log.txt")
entire_file = text_file.readlines()
text_file.close()
for line i... | Sorting a txt file with Python | I need some help printing out a sorted txt logfile.
there is no problem with the printing except that I dont want to print out the same IP number more than once.
This is my code.
text_file = open("access_log.txt")
entire_file = text_file.readlines()
text_file.close()
for line in reversed(entire_file):
try:
... | [
"# empty set of already seen ips:\nseen_ips = set()\n\nwith open(\"access_log.txt\") as f:\n for line in lines:\n arr = line.split(' ')\n date = arr[3] \n\n # if the ip still not seen, then print and add it to the seen_ips set:\n if arr[0] not in seen_ips:\n print arr[0], \... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0007660363_python.txt |
Q:
What are prevalent techniques for enabling user code extensions in Python?
I'm looking for techniques that allow users to override modules in an application or extend an application with new modules.
Imagine an application called pydraw. It currently provides a Circle class, which inherits Shape. The package tree ... | What are prevalent techniques for enabling user code extensions in Python? | I'm looking for techniques that allow users to override modules in an application or extend an application with new modules.
Imagine an application called pydraw. It currently provides a Circle class, which inherits Shape. The package tree might look like:
/usr/lib/python/
└── pydraw
├── __init__.py
├── shape.p... | [
"Discovery of extensions can be a bit brittle and complex, and also requires you to look through all of PYTHONPATH which can be very big.\nInstead, have a configuration file that lists the plugins that should be loaded. This can be done by listing them as module names, and also requiring that they are located on th... | [
3,
1,
1,
0
] | [] | [] | [
"oop",
"python",
"python_3.x"
] | stackoverflow_0007201397_oop_python_python_3.x.txt |
Q:
How to highlight more than two characters per line in difflibs html output
I am using difflib.HtmlDiff to compare two files. I want the differences to be highlighted in the outputted html.
This already works when there are a maximum of two different chars in one line:
a = "2.000"
b = "2.120"
But when there are mo... | How to highlight more than two characters per line in difflibs html output | I am using difflib.HtmlDiff to compare two files. I want the differences to be highlighted in the outputted html.
This already works when there are a maximum of two different chars in one line:
a = "2.000"
b = "2.120"
But when there are more different characters on one line then in the output the whole line is marked ... | [
"difflib's algorithm does not claim to yield minimal edit sequences.\nAlthough that statement comes from the docs for SequenceMatcher, I suspect it applies to difflib in general, and HTMLDiff in particular.\nWhile googling around for \"python alternative difflib minimal edit\"\nI found google-diff-match-patch. If y... | [
3
] | [] | [] | [
"difflib",
"html",
"python"
] | stackoverflow_0007661045_difflib_html_python.txt |
Q:
Multiple Python Processes slow
I have a python script which goes off and makes a number of HTTP and urllib requests to various domains.
We have a huge amount of domains to processes and need to do this as quickly as possible.
As HTTP requests are slow (i.e. they could time out of there is no website on the domain... | Multiple Python Processes slow | I have a python script which goes off and makes a number of HTTP and urllib requests to various domains.
We have a huge amount of domains to processes and need to do this as quickly as possible.
As HTTP requests are slow (i.e. they could time out of there is no website on the domain) I run a number of the scripts at a... | [
"Check the ulimit and quota for the box and the user running the scripts. /etc/security/limits.conf may also contain resource restrictions that you might want to modify. \nulimit -n will show the max number of open file descriptors allowed.\n\nMight this have been exceeded with all of the open sockets?\nIs the sc... | [
7,
2,
1,
1
] | [] | [] | [
"http",
"performance",
"python",
"task",
"unix"
] | stackoverflow_0007619259_http_performance_python_task_unix.txt |
Q:
How to use index as a key in Python?
I have a list: v = [1,2,2,3]. I would like to use this list as a key. I can do it "manually":
x = {}
x[1,2,2,3] = 7
But
x[v] = 7
does not work. What is the easiest way to do what I need to do?
ADDED
I imagine the solution as something like that:
x[open(v)] = 7
A:
The problem... | How to use index as a key in Python? | I have a list: v = [1,2,2,3]. I would like to use this list as a key. I can do it "manually":
x = {}
x[1,2,2,3] = 7
But
x[v] = 7
does not work. What is the easiest way to do what I need to do?
ADDED
I imagine the solution as something like that:
x[open(v)] = 7
| [
"The problem is that keys must be immutable, which lists are not. Tuples, however, are.\nSimply convert v to a tuple:\nx[tuple(v)] = 7\n\nTo elaborate, the above is the same as writing\nx[1,2,2,3] = 7\n\nand the latter is a syntactic variation of\nx[(1,2,2,3)] = 7\n\n",
"Dict keys must be hashable. Lists are not ... | [
7,
2,
2
] | [] | [] | [
"assign",
"dictionary",
"key",
"list",
"python"
] | stackoverflow_0007664168_assign_dictionary_key_list_python.txt |
Q:
error: command 'gcc' failed with exit status 1
The error I am getting is " error: command 'gcc' failed with exit status 1 "
The command I'm using is: python setup.py build --compiler=mingw32
I'm on Windows XP and I installed minGW. I am trying to use kinterbasdb for python.
A:
That means it did not use mingw32 ... | error: command 'gcc' failed with exit status 1 | The error I am getting is " error: command 'gcc' failed with exit status 1 "
The command I'm using is: python setup.py build --compiler=mingw32
I'm on Windows XP and I installed minGW. I am trying to use kinterbasdb for python.
| [
"That means it did not use mingw32 as a compiler. In the terminal type\nwhich mingw32\n\nIf that does not return anything the system does not know that this compiler is installed. That could be the problem. Then you'd have to add the compiler to the path variable and try again.\n"
] | [
0
] | [] | [] | [
"mingw",
"python"
] | stackoverflow_0007664091_mingw_python.txt |
Q:
Strip Trademark Symbol from string Python
I'm trying to prep some data for a designer. I'm pulling data out of SQL Server with python on a Windows machine (not sure if OS is important). How would I make the string 'Official Trademark™' = 'Official Trademark'? Also, any further information/reading on unicode or th... | Strip Trademark Symbol from string Python | I'm trying to prep some data for a designer. I'm pulling data out of SQL Server with python on a Windows machine (not sure if OS is important). How would I make the string 'Official Trademark™' = 'Official Trademark'? Also, any further information/reading on unicode or the pertinent subject matter would help me become... | [
"The trademark symbol is Unicode character U+2122, or in Python notation u\"\\u2122\".\nJust do a search and replace:\n'string'.replace(u\"\\u2122\", '')\n\n",
">>> 'Official Trademark™'.strip('™')\n'Official Trademark'\n>>> \n\n"
] | [
8,
3
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0007664483_python_regex_string.txt |
Q:
How to Read-in Binary of a File in Python
In Python, when I try to read in an executable file with 'rb', instead of getting the binary values I expected (0010001 etc.), I'm getting a series of letters and symbols that I do not know what to do with.
Ex: ???}????l?S??????V?d?\?hG???8?O=(A).e??????B??$????????: ??... | How to Read-in Binary of a File in Python | In Python, when I try to read in an executable file with 'rb', instead of getting the binary values I expected (0010001 etc.), I'm getting a series of letters and symbols that I do not know what to do with.
Ex: ???}????l?S??????V?d?\?hG???8?O=(A).e??????B??$????????: ???Z?C'???|lP@.\P?!??9KRI??{F?AB???5!qtWI??8???!ᢉ... | [
"That is the binary. They are stored as bytes, and when you print them, they are interpreted as ASCII characters.\nYou can use the bin() function and the ord() function to see the actual binary codes.\nfor value in enumerate(data):\n print bin(ord(value))\n\n",
"Byte sequences in Python are represented using st... | [
6,
4,
3,
0
] | [
"If you realy want to convert the binaray bytes to a stream of bits, you have to remove the first two chars ('0b') from the output of bin() and reverse the result:\nwith open(\"settings.dat\", \"rb\") as fp:\n print \"\".join( (bin(ord(c))[2:][::-1]).ljust(8,\"0\") for c in fp.read() )\n\nIf you use Python prior... | [
-2
] | [
"binary",
"python"
] | stackoverflow_0007663193_binary_python.txt |
Q:
Is there a better way to read an element from a file in Python?
I have written a crude Python program to pull phrases from an index in a CSV file and write these rows to another file.
import csv
total = 0
ifile = open('data.csv', "rb")
reader = csv.reader(ifile)
ofile = open('newdata_write.csv', "wb")
writer = ... | Is there a better way to read an element from a file in Python? | I have written a crude Python program to pull phrases from an index in a CSV file and write these rows to another file.
import csv
total = 0
ifile = open('data.csv', "rb")
reader = csv.reader(ifile)
ofile = open('newdata_write.csv', "wb")
writer = csv.writer(ofile, delimiter='\t', quotechar='"', quoting=csv.QUOTE_AL... | [
"You're looking for any with a generator expression:\nmatches = \"some text\", \"some more text\", \"even more text I'm looking for\"\nfor row in reader:\n if any(match in row for match in matches): \n total += 1 \n writer.writerow(row)\n\nAlternatively, you could just write all the rows at once... | [
6,
1,
0,
0,
0
] | [] | [] | [
"csv",
"list",
"python"
] | stackoverflow_0007664271_csv_list_python.txt |
Q:
How do I display most recent week items by default with WeekArchiveView?
I'm astonished by how little documentation on class-based generic views there is.
Anything slightly more complex than a trivial sample has to get done through guesswork, trial and error.
I want to use WeekArchiveView to display a week's item ... | How do I display most recent week items by default with WeekArchiveView? | I'm astonished by how little documentation on class-based generic views there is.
Anything slightly more complex than a trivial sample has to get done through guesswork, trial and error.
I want to use WeekArchiveView to display a week's item list.
There's my urls.py entry:
url(r'^items/(?P<year>\d{4})/week/(?P<week>\... | [
"Urls like /items/ or /items/2011/ wouldn't match your regexp because \\d{4} means exactly 4 digits. \nYou probably should specify two another url entries for both cases:\nurl(r'^items/$', AchievementListView.as_view(\n year=str(date.today().year), week=str(date.today().isocalendar()[1])\n )),\nurl(r'^items/(... | [
3
] | [] | [] | [
"django",
"django_1.3",
"django_class_based_views",
"python"
] | stackoverflow_0007664590_django_django_1.3_django_class_based_views_python.txt |
Q:
Setup OpenCV 2.3 w/ python bindings in ubuntu
How to install OpenCV (exactly 2.3.*, not 2.1.*) with python bindings in Ubuntu (or generally, in Linux)? I've seen few manuals on Windows installations, but none for Linux.
I've read and used instructions from willow garage site:
wget downloads.sourceforge.net/project... | Setup OpenCV 2.3 w/ python bindings in ubuntu | How to install OpenCV (exactly 2.3.*, not 2.1.*) with python bindings in Ubuntu (or generally, in Linux)? I've seen few manuals on Windows installations, but none for Linux.
I've read and used instructions from willow garage site:
wget downloads.sourceforge.net/project/opencvlibrary/opencv-unix/2.3.1/OpenCV-2.3.1a.tar.... | [
"Have you installed the Python development headers?\nsudo apt-get install python-dev\n\nRecompile it with those installed.\n"
] | [
12
] | [] | [] | [
"linux",
"opencv",
"python"
] | stackoverflow_0007664803_linux_opencv_python.txt |
Q:
Using python robotparser
I am not understandong how to use the parse function in robotparser module . Here is what I tried :
In [28]: rp.set_url("http://anilattech.wordpress.com/robots.txt")
In [29]: rp.parse("""# If you are regularly crawling WordPress.com sites please use our firehose to receive real-time push... | Using python robotparser | I am not understandong how to use the parse function in robotparser module . Here is what I tried :
In [28]: rp.set_url("http://anilattech.wordpress.com/robots.txt")
In [29]: rp.parse("""# If you are regularly crawling WordPress.com sites please use our firehose to receive real-time push updates instead.
# Please see... | [
"There are two issues here. Firstly the rp.parse method takes a list of strings, so you should add .split(\"\\n\") to that line.\nThe second issue is that rules for the * user agent are stored in rp.default_entry rather than rp.entries. If you check that you'll see it contains an Entry object.\nI'm not sure who is ... | [
1,
0
] | [] | [] | [
"python",
"screen_scraping",
"web"
] | stackoverflow_0007658468_python_screen_scraping_web.txt |
Q:
Running non-system Python with virtualenv in 32bit mode on OS X
Short Question
Using virtualenv / virtualenvwrapper is it possible to add a prefix to the python call that linked to a specific virtual environment?
Background
I would like to have multiple virtual environment using a brew installed Python 2.7, but ... | Running non-system Python with virtualenv in 32bit mode on OS X | Short Question
Using virtualenv / virtualenvwrapper is it possible to add a prefix to the python call that linked to a specific virtual environment?
Background
I would like to have multiple virtual environment using a brew installed Python 2.7, but some running in 64 bit mode and the others 32bit mode.
Below I have t... | [
"Adding an alias to your activate script, and activating your virtualenv each type you want to use it.\n$ cd env32\n$ echo \"alias python='arch -i386 python'\" >> bin/activate\n$ source bin/activate\n$ python myscript.py\n\n"
] | [
6
] | [] | [] | [
"macos",
"python",
"virtualenv",
"virtualenvwrapper"
] | stackoverflow_0007663852_macos_python_virtualenv_virtualenvwrapper.txt |
Q:
Project euler in python (#53)
So I'm learning python so I'm going through some project euler problems. And I'm not sure if this is a python problem I'm having, or just me being retarded, but I seem to be getting the wrong answer for problem 53. Here's a link to the problem http://projecteuler.net/index.php?section... | Project euler in python (#53) | So I'm learning python so I'm going through some project euler problems. And I'm not sure if this is a python problem I'm having, or just me being retarded, but I seem to be getting the wrong answer for problem 53. Here's a link to the problem http://projecteuler.net/index.php?section=problems&id=53
and this is my code... | [
"range( a, b) does not include b.\n",
"I think your code is correct, however, you should iterate x to 100 inclusive, so you should use\nfor x in range(1,101):\n\nHope that helps. Euler rocks!\n",
"Note that n is greater than or equal to 1 AND smaller than or equal to 100. Currently your n goes from 1 to 99. You... | [
10,
4,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003360842_python.txt |
Q:
Using Split arguments in other functions
The code is suppose to take a string of multiple arguments and split them with the "Split()". It does do that, but it only passes the first argument to the "CheckList()". So if I type " 1 2 4" it will only pass "1" to CheckList. Everything else works as it should.
import r... | Using Split arguments in other functions | The code is suppose to take a string of multiple arguments and split them with the "Split()". It does do that, but it only passes the first argument to the "CheckList()". So if I type " 1 2 4" it will only pass "1" to CheckList. Everything else works as it should.
import re
def CheckList(Start):
DoIt ... | [
"Your problem is right here:\nfor PodCheck in F.readlines():\n\nThe first call to CheckList uses up all the data in F. Subsequent calls to Checklist skip the for loop because there is nothing left to read.\nSo after opening F your should read all of it's data. Without changing too much of your code I would add th... | [
5
] | [] | [] | [
"for_loop",
"python",
"split"
] | stackoverflow_0007665124_for_loop_python_split.txt |
Q:
How to use "import oauth2" in Google App Engine?
I want to use Tumblr's API v2, which includes OAuth. so I need to find a OAuth module.
I am supposed to use it like this:
import oauth2 as oauth
I have found the oauth2 source code here: https://github.com/simplegeo/python-oauth2
If I want to use it in my Linux Ub... | How to use "import oauth2" in Google App Engine? | I want to use Tumblr's API v2, which includes OAuth. so I need to find a OAuth module.
I am supposed to use it like this:
import oauth2 as oauth
I have found the oauth2 source code here: https://github.com/simplegeo/python-oauth2
If I want to use it in my Linux Ubuntu 10.08, whats the process? I have installed git. I... | [
"On Ubuntu, simply sudo apt-get install python-oauth2 and the package will be installed for you automatically.\nFor AppEngine, you might take a look at the Google API Python Client's appengine examples. They have an OAuth2 client specifically designed to work with AppEngine.\n"
] | [
2
] | [] | [] | [
"api",
"google_app_engine",
"oauth",
"python",
"tumblr"
] | stackoverflow_0007665200_api_google_app_engine_oauth_python_tumblr.txt |
Q:
Monday as first day of week for WeekArchiveView
How do I convince WeekArchiveView that Monday is the first day of week?
A:
Juding by this diff, it is achieved by adding week_format parameter to urls.py:
url(r'^items/(?P<year>\d{4})/week/(?P<week>\d{1,2})/$', ItemArchiveView.as_view(
week_format='%W'
)),
| Monday as first day of week for WeekArchiveView | How do I convince WeekArchiveView that Monday is the first day of week?
| [
"Juding by this diff, it is achieved by adding week_format parameter to urls.py:\nurl(r'^items/(?P<year>\\d{4})/week/(?P<week>\\d{1,2})/$', ItemArchiveView.as_view(\n week_format='%W'\n)),\n\n"
] | [
4
] | [] | [] | [
"django",
"django_1.3",
"django_class_based_views",
"python",
"weekday"
] | stackoverflow_0007665280_django_django_1.3_django_class_based_views_python_weekday.txt |
Q:
Why use is_safe?
I'm reading Django documentation on custom filter.
and.. I don't see the reason of the existence of is_safe.
https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#filters-and-auto-escaping
when I coded some examples and then tried them, the result were always same whether is_safe is Tr... | Why use is_safe? | I'm reading Django documentation on custom filter.
and.. I don't see the reason of the existence of is_safe.
https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#filters-and-auto-escaping
when I coded some examples and then tried them, the result were always same whether is_safe is True or False.
Why do yo... | [
"Using is_safe together with mark_safe() is redundant, which is probably why you don't see any differences.\nAs noted in the section you linked to, down where it talks about mark_safe():\n\nThere's no need to worry about the is_safe attribute in this case (although including it wouldn't hurt anything). Whenever you... | [
11
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007665512_django_python.txt |
Q:
Exporting to Excel .xlsx from a Python Pyramid project
I know about the XLWT library, which I've used before on a Django project. XLWT is very neat but as far as I know, it doesn't support .xlsx which is the biggest obstacle in my case. I'm probably going to be dealing with more than 2**16 rows of information. Is ... | Exporting to Excel .xlsx from a Python Pyramid project | I know about the XLWT library, which I've used before on a Django project. XLWT is very neat but as far as I know, it doesn't support .xlsx which is the biggest obstacle in my case. I'm probably going to be dealing with more than 2**16 rows of information. Is there any other mature similar library? Or even better, is t... | [
"This is pretty good. I used it for a couple of small things: \nhttp://packages.python.org/openpyxl/\n",
"Another really good alternative, actually what I switched to from Openpyxl is TabLib.\nhttp://tablib.org\n",
"Export a CSV don't use .xlsx..\n"
] | [
4,
2,
0
] | [] | [] | [
"openpyxl",
"python",
"xls",
"xlsx",
"xlwt"
] | stackoverflow_0007576309_openpyxl_python_xls_xlsx_xlwt.txt |
Q:
Python how to get the domain of a cookie
I want to get the domain of the cookie from the HTTP response. Code is:
cookie = Cookie.SimpleCookie()
cookie.load(cookie_string)
print 'cookie = ', cookie
this shows the cookie as
cookie= Set-Cookie: Cycle=MA==|MA==|MA==; Domain=.abc.xyz.net; expires=Tue, 05-Oct-2021 0... | Python how to get the domain of a cookie | I want to get the domain of the cookie from the HTTP response. Code is:
cookie = Cookie.SimpleCookie()
cookie.load(cookie_string)
print 'cookie = ', cookie
this shows the cookie as
cookie= Set-Cookie: Cycle=MA==|MA==|MA==; Domain=.abc.xyz.net; expires=Tue, 05-Oct-2021 04:15:18 GMT; Path=/
I want to extract the doma... | [
"try:\ncookie['Cycle']['domain'] # lowercase domain !\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0007665888_python.txt |
Q:
Matplotlib: Label points on mouseover
I have a scatter plot with several thousand points. This post tells me how to label them:
Matplotlib: How to put individual tags for a scatter plot
But that will look like a disaster with so many points. What I would like instead is to have a "tool tip" type label that pops ... | Matplotlib: Label points on mouseover | I have a scatter plot with several thousand points. This post tells me how to label them:
Matplotlib: How to put individual tags for a scatter plot
But that will look like a disaster with so many points. What I would like instead is to have a "tool tip" type label that pops up when you mouseover a point. Is that pos... | [
"Once you get the coords of the point you can show them or any object-linked info in a textctrl in the toolbar. For this you have to instantiate a toolbar (NavigationToolbar2Wx()) in your canvas and add the textcontrol there. This is not as nice as a popup but it does the job. \nHere you have an example of customi... | [
6
] | [] | [] | [
"label",
"matplotlib",
"python"
] | stackoverflow_0007665892_label_matplotlib_python.txt |
Q:
Using a Python logger SocketHandler to log directly into carbon (graphite)?
I did my best to log metrics directly into carbon through SocketHandler with no luck:
logger.conf:
[loggers]
keys=root,carbon
[handlers]
keys=carbonHandler
[formatters]
keys=carbonFormatter
[logger_carbon]
level=DEBUG
handlers=carbonHan... | Using a Python logger SocketHandler to log directly into carbon (graphite)? | I did my best to log metrics directly into carbon through SocketHandler with no luck:
logger.conf:
[loggers]
keys=root,carbon
[handlers]
keys=carbonHandler
[formatters]
keys=carbonFormatter
[logger_carbon]
level=DEBUG
handlers=carbonHandler
qualname=carbon
propagate=0
[logger_root]
level=DEBUG
handlers=carbonHandle... | [
"Assuming your config file is exactly as is - replace \"$HOST\" in your config file with the actual name of the host. What happens then? If that works and you need the name to be environment-dependent, try using\nargs=(os.environ['HOST'], 2003) \n\nin the config file.\n"
] | [
0
] | [] | [] | [
"graphite",
"python"
] | stackoverflow_0007664397_graphite_python.txt |
Q:
Writing regular expression to skip a line if specific set of characters are present?
I am trying to write a regex in python to parse a file having contents like this :-
static const PropertyID PROPERTY_X = 10225;
//static const PropertyID PROPERTY_Y = 10226;
//static const PropertyID PROPERTY_Z = 10227;
I want... | Writing regular expression to skip a line if specific set of characters are present? | I am trying to write a regex in python to parse a file having contents like this :-
static const PropertyID PROPERTY_X = 10225;
//static const PropertyID PROPERTY_Y = 10226;
//static const PropertyID PROPERTY_Z = 10227;
I want to extract the property name and number for only non commented properties.
This is the ... | [
"Try:\nr\"(?m)^(?!//)static\\s+const\\s+PropertyID\\s+(\\S+)\\s+=\\s+(\\d+);\"\n\nA couple notes.\n^ matches beginning of line\n(?!//) is a negative lookahead, asserting that it is NOT followed by //\n\\s is any space character\n\\S is any non-space character\n",
"You could specify that, after the start of the li... | [
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007666369_python_regex.txt |
Q:
Floating point representation error in Python
Possible Duplicate:
How is floating point stored? When does it matter?
Python rounding error with float numbers
I am trying to understand why we get floating point representation error in python. I know this is not new question here but honestly I am finding hard tim... | Floating point representation error in Python |
Possible Duplicate:
How is floating point stored? When does it matter?
Python rounding error with float numbers
I am trying to understand why we get floating point representation error in python. I know this is not new question here but honestly I am finding hard time to understand it. I am going through the officia... | [
"You can think of 0.1 being a rational number for a computer - a rational number whose decimal expansion is not finite.\nTake 1/3 for instance. For us humans, we know that it means \"one third\" (no more, no less). But if we were to write it down without fractions, we would have to write 0.3333... and so on. In fac... | [
1
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0007666331_floating_point_python.txt |
Q:
modify program of generation for saving words in list and choosing them with random.choice()
How to modify program of generation for saving words in list and choosing them with random.choice() previously do import random?
where is mistake? its not working correct
def generate_model(cfdist,word,num=15):
for i ... | modify program of generation for saving words in list and choosing them with random.choice() | How to modify program of generation for saving words in list and choosing them with random.choice() previously do import random?
where is mistake? its not working correct
def generate_model(cfdist,word,num=15):
for i in range(num):
word=random.choice.im_class(cfdist
[word].keys())
... | [
"There is all kinds of weird stuff going on with that code:\ndef generate_model(cfdist,word,num=15):\n\nYou use word as the key to look up in the dictionary.\n word=\n\nThen you change it? Are you intentionally chaining the result of one random lookup as the key for the next lookup?\nrandom.choice\n\nIf you're i... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007666357_python.txt |
Q:
How would I go about expanding my PHP code library with Python code?
I have a rather large API written in PHP that I've worked on for years. Some of the functionality needs to be upgraded to the extent where I should really just rewrite the classes. Since I need to scrap the old code anyway, I was thinking perhaps... | How would I go about expanding my PHP code library with Python code? | I have a rather large API written in PHP that I've worked on for years. Some of the functionality needs to be upgraded to the extent where I should really just rewrite the classes. Since I need to scrap the old code anyway, I was thinking perhaps I could replace the old functionality with Python code.
I came across PiP... | [
"I can think of two options, which should also make the overall solution somewhat more flexible:\n\nWrite it as a web service: Write the python parts as a RESTful web service. Should be relatively straightforward to do.\nUse something like ZeroMQ to create a message queue: There are zmq libraries for both PHP and P... | [
2,
1
] | [] | [] | [
"php",
"python"
] | stackoverflow_0007544498_php_python.txt |
Q:
Sorting a dict in Python
I want to sort the dict in python. As I am new I don't know where I am going wrong. The below code does sort but the first two entries only.
Pls advice
scorecard ={}
result_f = open("results.txt")
for line in result_f:
(name,score) =line.split()
scorecard[score]=name
for each_sc... | Sorting a dict in Python | I want to sort the dict in python. As I am new I don't know where I am going wrong. The below code does sort but the first two entries only.
Pls advice
scorecard ={}
result_f = open("results.txt")
for line in result_f:
(name,score) =line.split()
scorecard[score]=name
for each_score in sorted(scorecard.keys()... | [
"My guess is you are keeping the scores as strings rather than integers. Strings do not sort the same way as integers. Consider:\n>>> sorted(['2','10','15'])\n['10', '15', '2']\n>>> sorted([2, 10, 15])\n[2, 10, 15]\n\nAn aside: You map from score to surfer -- the mapping should be reverse of that. Otherwise you w... | [
3,
2,
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0007666406_python_sorting.txt |
Q:
How to use static/helper method in a class?
I'm writting a Fraction class and I am trying to use gcd(a,b) in the initialization of a Fraction object. However, when I was trying to do this it would not work WITHOUT the Fraction part of Fraction.gcd(a,b). I used @staticmethod here, but it does absolutely nothing, i.... | How to use static/helper method in a class? | I'm writting a Fraction class and I am trying to use gcd(a,b) in the initialization of a Fraction object. However, when I was trying to do this it would not work WITHOUT the Fraction part of Fraction.gcd(a,b). I used @staticmethod here, but it does absolutely nothing, i.e. my code works the same without it.
Is there a... | [
"Don't forget, in Python not everything needs to be in a class. There's nothing about gcd that makes it better-suited to being a class method than a standalone function: so take it out of the class. Now you can just call gcd(a, b).\n",
"Think of methods in a class just like any other class attribute -- reference ... | [
11,
8,
5,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007667667_python.txt |
Q:
Sum of Fibonacci numbers
I found this task here.
Given the ith (1<=i<=35) Fibonacci
number F(i) calculate the sum of the
ith till i+9th number
F(i)+F(i+1)+...+F(i+9) and the last
digit of the i+246th one F(i+246)
I have been trying to solve this using python and some tricks(Binnet's formula and a tricky ... | Sum of Fibonacci numbers | I found this task here.
Given the ith (1<=i<=35) Fibonacci
number F(i) calculate the sum of the
ith till i+9th number
F(i)+F(i+1)+...+F(i+9) and the last
digit of the i+246th one F(i+246)
I have been trying to solve this using python and some tricks(Binnet's formula and a tricky recurrence):
f=lambda n:((1+5... | [
"Did you try to use this sum formula? \nhttp://en.wikipedia.org/wiki/Fibonacci_number#Second_identity (\"Second Identity\")?\n",
"f = lambda n,t=5**.5:((1+t)**n-(1-t)**n)/(2**n*t) etc. spends 8 characters ,t=5**.5 to gain 12: three lots of 5**.5 -> t. That's a saving of 4 characters, which seems to be what you re... | [
5,
2,
1,
0,
0
] | [
"This one prints the Fibonacci series up to n.\ndef fib(n): \n a, b = 0, 1\n while a < n:\n print(a, end=' ')\n a, b = b, a+b\n print()\n\n"
] | [
-1
] | [
"algorithm",
"fibonacci",
"math",
"python"
] | stackoverflow_0005565845_algorithm_fibonacci_math_python.txt |
Q:
How do I paginate WeekArchiveView?
In continuation of my struggle with WeekArchiveView, how do I paginate it by week?
All I want is:
to know if there is next / previous week available;
in case there is, provide a link in the template.
I'd like it to also skip empty weeks.
The source shows get_next_day / get_pr... | How do I paginate WeekArchiveView? | In continuation of my struggle with WeekArchiveView, how do I paginate it by week?
All I want is:
to know if there is next / previous week available;
in case there is, provide a link in the template.
I'd like it to also skip empty weeks.
The source shows get_next_day / get_prev_day and get_next_month / get_prev_mon... | [
"That is definitely interesting. Sure enough MonthMixin includes get_next_month/get_prev_month methods, and DayMixin includes get_next_day/get_prev_day methods. However, both YearMixin and WeekMixin have no functional equivalent in their definitions. Seems like a bit of an oversight on the Django team's part.\nI th... | [
3,
2
] | [] | [] | [
"django",
"django_1.3",
"django_class_based_views",
"django_pagination",
"python"
] | stackoverflow_0007665013_django_django_1.3_django_class_based_views_django_pagination_python.txt |
Q:
Numpy object arrays
I've recently run into issues when creating Numpy object arrays using e.g.
a = np.array([c], dtype=np.object)
where c is an instance of some complicated class, and in some cases Numpy tries to access some methods of that class. However, doing:
a = np.empty((1,), dtype=np.object)
a[0] = c
solv... | Numpy object arrays | I've recently run into issues when creating Numpy object arrays using e.g.
a = np.array([c], dtype=np.object)
where c is an instance of some complicated class, and in some cases Numpy tries to access some methods of that class. However, doing:
a = np.empty((1,), dtype=np.object)
a[0] = c
solves the issue. I'm curious... | [
"In the first case a = np.array([c], dtype=np.object), numpy knows nothing about the shape of the intended array.\nFor example, when you define\nd = range(10)\na = np.array([d])\n\nThen you expect numpy to determine the shape based on the length of d.\nSo similarly in your case, numpy will attempt to see if len(c) ... | [
11
] | [] | [] | [
"arrays",
"class",
"numpy",
"python"
] | stackoverflow_0007667799_arrays_class_numpy_python.txt |
Q:
Python indentation issues using panic CODA
Any one else getting lots of indentation syntax errors when writing python in panics coda IDE? Ive been getting a lot of these, and just shuffling my code around seems gets rid of the error. Bug?
A:
This is usually due to shifting between tabs and spaces as tabs. I've s... | Python indentation issues using panic CODA | Any one else getting lots of indentation syntax errors when writing python in panics coda IDE? Ive been getting a lot of these, and just shuffling my code around seems gets rid of the error. Bug?
| [
"This is usually due to shifting between tabs and spaces as tabs. I've set my invisible character color (Preferences -> Colors) to be visible on the page so that I can see if I'm using tabs or spaces. The Python standard is to use 4 spaces for a tab. I've set this as the default as well (Preferences -> Editor then ... | [
5
] | [] | [] | [
"coda",
"panic",
"python"
] | stackoverflow_0007510184_coda_panic_python.txt |
Q:
Access to the cookies of the default browser
I want to write a program that opens the browser and open a url with a given cookie. I dont know how to do this. Maybe I could modify the cookies in the default place.
A:
In python, you can emulate a browser with the mechanize library. Also, there is good documentatio... | Access to the cookies of the default browser | I want to write a program that opens the browser and open a url with a given cookie. I dont know how to do this. Maybe I could modify the cookies in the default place.
| [
"In python, you can emulate a browser with the mechanize library. Also, there is good documentation about mechanize and cookies. \n",
"import urllib2\nopener = urllib2.build_opener()\nopener.addheaders.append(('Cookie', 'cookiename=cookievalue'))\nf = opener.open(\"http://example.com/\")\n\nModules to look into:\... | [
2,
2
] | [] | [] | [
"browser",
"cookies",
"python"
] | stackoverflow_0007668177_browser_cookies_python.txt |
Q:
How do I make relative importing work in Python using Eclipse with PyDev?
So I am working on a Python project that was here before me in an SVN repo. When I first pulled it, the structure was a bit odd due to the fact that it was similar to:
Proj\
src\
tags\
trunk\
And then everything is inside src\ a... | How do I make relative importing work in Python using Eclipse with PyDev? | So I am working on a Python project that was here before me in an SVN repo. When I first pulled it, the structure was a bit odd due to the fact that it was similar to:
Proj\
src\
tags\
trunk\
And then everything is inside src\ are the python module files except src\ turns out to just be a logical folder wi... | [
"Have you added the root folder to your system path?\nimport sys\nsys.path.append(<place the Proj dir here>)\n\nthen you could import as follows:\nfrom src.model.somefile import Something\n\nIf you don't know the absolute path for Proj, you can always use combinations such as\nos.path.dirname(os.getcwd())\n\n"
] | [
3
] | [] | [] | [
"eclipse",
"pydev",
"python",
"svn"
] | stackoverflow_0007667871_eclipse_pydev_python_svn.txt |
Q:
Login to site programatically using python
I am wondering on how to log in to specific site, however no luck so far.
The way it happens on browser is that you click on button, it triggers jQuery AJAX request to /ajax/authorize_ajax.html with post variables login and pass. When it returns result = true it reloads d... | Login to site programatically using python | I am wondering on how to log in to specific site, however no luck so far.
The way it happens on browser is that you click on button, it triggers jQuery AJAX request to /ajax/authorize_ajax.html with post variables login and pass. When it returns result = true it reloads document and you are logged in.
When I go to /aja... | [
"Here's a blog post I did a while ago about using an HttpWebRequest to post to a site when cookies are involved:\nhttp://crazorsharp.blogspot.com/2009/06/c-html-screen-scraping-part-2.html\nThe idea is, when you get a Response using the HttpWebRequest, you can get access to the Cookies that are sent down. For every... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007667841_python.txt |
Q:
In Python - Parsing a response xml and finding a specific text vaule
I'm new to python and I'm having a particularly difficult time working with xml and python. The situation I have is this, I'm trying to count the number of times a word appears in an xml document. Simple enough, but the xml document is a response... | In Python - Parsing a response xml and finding a specific text vaule | I'm new to python and I'm having a particularly difficult time working with xml and python. The situation I have is this, I'm trying to count the number of times a word appears in an xml document. Simple enough, but the xml document is a response from a server. Is it possible to do this without writing to a file? It wo... | [
"If you are just trying to count the number of times a word appears in an XML document, just read the document as a string and do a count:\nimport urllib2\ndata = urllib2.urlopen('http://www.example.com/file.xml').read()\nprint data.count('foobar')\n\nOtherwise, you can just iterate through the tags you are looking... | [
5,
5,
2,
0
] | [] | [] | [
"memory",
"parsing",
"python",
"xml"
] | stackoverflow_0007668204_memory_parsing_python_xml.txt |
Q:
python httplib Name or service not known
I'm trying to use httplib to send credit card information to authorize.net. When i try to post the request, I get the following traceback:
File "./lib/cgi_app.py", line 139, in run res = method()
File "/var/www/html/index.py", line 113, in ProcessRegistration conn.request(... | python httplib Name or service not known | I'm trying to use httplib to send credit card information to authorize.net. When i try to post the request, I get the following traceback:
File "./lib/cgi_app.py", line 139, in run res = method()
File "/var/www/html/index.py", line 113, in ProcessRegistration conn.request("POST", "/gateway/transact.dll", mystring, hea... | [
"As an (obvious) heads up, this same error can also be triggered by including the protocol in the host parameter. For example this code:\nconn = httplib.HTTPConnection(\"http://secure.authorize.net\", 80, ....) \n\nwill also cause the \"gaierror: [Errno -2] Name or service not known\" error, even if all your netwo... | [
19,
8,
1,
0
] | [] | [] | [
"httplib",
"python",
"ssl"
] | stackoverflow_0004673166_httplib_python_ssl.txt |
Q:
Match elements from one list to another, skip already-matched elements, Python
The solution to this is likely obvious to many of you, but I'm stuck so I thought I'd ask.
I have two lists in the following format:
target_list =['apples 1', 'oranges 1', 'bananas 2', 'apples 3', 'oranges 2','mango 3', 'apples 2']
sour... | Match elements from one list to another, skip already-matched elements, Python | The solution to this is likely obvious to many of you, but I'm stuck so I thought I'd ask.
I have two lists in the following format:
target_list =['apples 1', 'oranges 1', 'bananas 2', 'apples 3', 'oranges 2','mango 3', 'apples 2']
source_list = ['A apples', 'B mango', 'C apples', 'D bananas', 'E oranges','F apples', ... | [
"target_list =['apples 1', 'oranges 1', 'bananas 2', 'apples 3', 'oranges 2','mango 3', 'apples 2']\nsource_list = ['A apples', 'B mango', 'C apples', 'D bananas', 'E oranges','F apples', 'G oranges']\n\nfrom collections import defaultdict\n\n# you want each target fruit to be a group, so use them as keys in a dic... | [
2
] | [] | [] | [
"list",
"python",
"text_processing"
] | stackoverflow_0007668534_list_python_text_processing.txt |
Q:
Extract/scrape specific data from JSON file
This been bugging me for quite a few hours. I've been searching a lot and I have found a lot of information. The problem is, I'm not that good, I'm actually a beginner to the max. I'd like to achieve this with Python (if it's possible!). Maybe with JavaScript and PHP als... | Extract/scrape specific data from JSON file | This been bugging me for quite a few hours. I've been searching a lot and I have found a lot of information. The problem is, I'm not that good, I'm actually a beginner to the max. I'd like to achieve this with Python (if it's possible!). Maybe with JavaScript and PHP also? Let me explain.
I just found this website http... | [
"Python (after you loaded the json)\nfor elem in data:\n print('{artist}\\n{title}\\n{album}\\n'.format(**elem['metadata']))\n\nTo save in a file:\nwith open('the_file_name.txt','w') as f:\n for elem in data:\n f.write('{artist}\\n{title}\\n{album}\\n\\n'.format(**elem['metadata']))\n\n",
"Okay this ... | [
3,
2,
2,
1
] | [] | [] | [
"javascript",
"jquery",
"php",
"python"
] | stackoverflow_0007667787_javascript_jquery_php_python.txt |
Q:
Errors occur about dictionary function in Python
Part of my python script:
(I first made the dictionary "h")
def histogram(L):
d= {}
for x in L:
if x in d:
d[x] +=1
else:
d[x] =1
return d
h=histogram(LIST)
for vhfile in vhfiles:
linelist=commands.getoutput('cat ' ... | Errors occur about dictionary function in Python | Part of my python script:
(I first made the dictionary "h")
def histogram(L):
d= {}
for x in L:
if x in d:
d[x] +=1
else:
d[x] =1
return d
h=histogram(LIST)
for vhfile in vhfiles:
linelist=commands.getoutput('cat ' + vhfile).splitlines(True)
list1=[]
for line i... | [
"You get a KeyError when you try to look something up in the dict, and the dict doesn't contain that key.\nIn this case, it appears that the key '080821_HWI-EAS301_0002_30ALBAAXX:1:46:1643:1310' does not occur in h.\n",
"A key error means that you've referenced a key in your dict that doesn't exist. There was an ... | [
3,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007668551_dictionary_python.txt |
Q:
psycopg2: interval type for storing weeks
I'm using postgresql and python and I need to store data group by week of the year. So, there's plenty alternatives:
week and year in two separated fields
a date pointing to the start of the week (or a random day of the week)
And, the one I like: an interval type.
I neve... | psycopg2: interval type for storing weeks | I'm using postgresql and python and I need to store data group by week of the year. So, there's plenty alternatives:
week and year in two separated fields
a date pointing to the start of the week (or a random day of the week)
And, the one I like: an interval type.
I never use it, but reading the docs, seems to fit. B... | [
"The PostgreSQL interval type isn't really what you're looking for -- it's specifically intended for storing an arbitrary length of time, ranging anywhere from a microsecond to a few million years. An interval has no starting or ending point; it's just a measure of \"how long\".\nIf you're specifically after storin... | [
4
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0007668822_postgresql_psycopg2_python.txt |
Q:
Sending hex packets in python
How would I send hex data in a packet? I'm trying to copy a packet exactly by using the hex instead of ASCII. All I'm looking for is what the sendto argument would be if, say, the hex I needed to send was 00AD12.
A:
Use struct to convert between bytes (typically expressed in hexadec... | Sending hex packets in python | How would I send hex data in a packet? I'm trying to copy a packet exactly by using the hex instead of ASCII. All I'm looking for is what the sendto argument would be if, say, the hex I needed to send was 00AD12.
| [
"Use struct to convert between bytes (typically expressed in hexadecimal fashion) and numbers:\n>>> import struct\n>>> struct.pack('!I', 0xAD12)\nb'\\x00\\x00\\xad\\x12'\n\nIf you have a hex string and want to convert it to bytes, use binascii.unhexlify:\n>>> import binascii\n>>> binascii.unhexlify('ad12')\nb'\\xad... | [
12
] | [] | [] | [
"hex",
"packet",
"python"
] | stackoverflow_0007668919_hex_packet_python.txt |
Q:
Multiple Domains for one Django App, with and without SSL
I want to point multiple Domains (each with and whitout ssl) to a single Django App, using mod_wsgi with Apache 2.
I already know how to set up Django to support multiple Domains, but I do not know how to set up Apache properly. If the sites didn't have to ... | Multiple Domains for one Django App, with and without SSL | I want to point multiple Domains (each with and whitout ssl) to a single Django App, using mod_wsgi with Apache 2.
I already know how to set up Django to support multiple Domains, but I do not know how to set up Apache properly. If the sites didn't have to use SSL, I would use "ServerAlias"-directives for all relevant ... | [
"If they are using exact same code base, and same Django settings module etc, then set them up as if they are different applications, but at global scope in Apache configuration add:\nWSGIDaemonProcess all-django-sites\n\nand then in each VirtualHost add:\nWSGIProcessGroup all-django-sites\nWSGIApplicationGroup %{G... | [
0
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0007668397_apache_django_mod_wsgi_python.txt |
Q:
Using pycurl to login and retrieve cookie
I found something similar to something I want to do using urllib2 here: How to use Python to login to a webpage and retrieve cookies for later usage?
Their solution was :
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.Cookie... | Using pycurl to login and retrieve cookie | I found something similar to something I want to do using urllib2 here: How to use Python to login to a webpage and retrieve cookies for later usage?
Their solution was :
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTT... | [
"This looks a lot like a dupe of Logging in and using cookies in pycurl. You give pycurl a path to a file to write cookies to with \nc.setopt(pycurl.COOKIEJAR, 'cookie.txt')\n\nand a path to read them from (probably the same) with\nc.setopt(pycurl.COOKIEFILE, 'cookie.txt')\n\n"
] | [
1
] | [] | [] | [
"pycurl",
"python"
] | stackoverflow_0007668878_pycurl_python.txt |
Q:
python: calling java program
I have a tag cloud generator that I would like to call from my python program. How can I do it?
I run it in a batch file
java -jar ibm-word-cloud.jar -C configure.txt input.txt output.png
thanks for your help.
A:
The subprocess module is now preferred over os.system(). A simple ex... | python: calling java program | I have a tag cloud generator that I would like to call from my python program. How can I do it?
I run it in a batch file
java -jar ibm-word-cloud.jar -C configure.txt input.txt output.png
thanks for your help.
| [
"The subprocess module is now preferred over os.system(). A simple example, assuming run_prog.bat contains the command you need:\nimport subprocess\ncmd = \"run_prog.bat\"\nproc = subprocess.Popen(cmd)\n\n",
"You can use the os module:\nimport os\nos.system('mybatchfile.bat')\n\nor use the subprocess module\n"
] | [
3,
2
] | [] | [] | [
"jar",
"java",
"python"
] | stackoverflow_0007629023_jar_java_python.txt |
Q:
Debugging a segmentation fault in C++ code called from Python
I have a test that runs a python script, which calls into C++ code, where it segfaults and dumps core. I've tried to load the core file in GDB using /usr/bin/python2.6, but this just gives me ?? for all the items in the stack trace. How do I debug thi... | Debugging a segmentation fault in C++ code called from Python | I have a test that runs a python script, which calls into C++ code, where it segfaults and dumps core. I've tried to load the core file in GDB using /usr/bin/python2.6, but this just gives me ?? for all the items in the stack trace. How do I debug this core file?
| [
"You need to compile a version of Python with debugging symbols. You can do this by building Python with ./configure --with-pydebug. Hopefully you will be able to find the error that way.\nThat will change the behavior of Python internally in some ways. If you don't still get the segfault that way, you might try ru... | [
1
] | [] | [] | [
"c++",
"core_file",
"gdb",
"python"
] | stackoverflow_0007668850_c++_core_file_gdb_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.