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:
Parse paragraphs from HTML using lxml
I am new to lxml and want to extract <p>PARAGRAPHS</p> and <li>PARAGRAPHS</li> from a given url and use them for further steps.
I followed an example from a post, and tried the following code with no luck:
html = lxml.html('http://www.google.com/intl/en/about/corporate/index.h... | Parse paragraphs from HTML using lxml | I am new to lxml and want to extract <p>PARAGRAPHS</p> and <li>PARAGRAPHS</li> from a given url and use them for further steps.
I followed an example from a post, and tried the following code with no luck:
html = lxml.html('http://www.google.com/intl/en/about/corporate/index.html')
url = 'http://www.google.com/intl/en/... | [
"import lxml.html\n\nhtmltree = lxml.html.parse('http://www.google.com/intl/en/about/corporate/index.html')\n\nprint htmltree.xpath('//p/text()')\n\n"
] | [
7
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0007785463_lxml_python.txt |
Q:
How to determine 4 nearest adjacent points in grid database around given latitude and longitude using python
I have a table named coords with the following columns |name|lat|lon|und|
import sqlite3
database = sqlite3.connect('geoida.db')
cursor = database.cursor()
cursor.execute("select lat, lon, und from coords... | How to determine 4 nearest adjacent points in grid database around given latitude and longitude using python | I have a table named coords with the following columns |name|lat|lon|und|
import sqlite3
database = sqlite3.connect('geoida.db')
cursor = database.cursor()
cursor.execute("select lat, lon, und from coords")
results = cursor.fetchall()
every line in table stores coordinates of one point of g r i d and distance from... | [
"def find_adjacent_coords(db, lat, lon, step=0.041667):\n \"\"\"Find coords that are in a +/- step range of lat, lon.\"\"\"\n #XXX disregard values near +/- 90 latitude, +/- 180 longitude\n coords_range = lat-step, lat+step, lon-step, lon+step\n return db.execute(\"\"\"select lat, lon from coords where ... | [
3
] | [] | [] | [
"coordinates",
"grid",
"python",
"sqlite"
] | stackoverflow_0007784216_coordinates_grid_python_sqlite.txt |
Q:
How to find the nearest nighboring point coordinates in 2d grid using python
I try to find the nearest point in geoida database for every point stored in second database.
Here's may approach, which is extremely slow. geoida.db stores +55000 coordinates
import sqlite3
from kdtree import KDTree
database = sqlite3.c... | How to find the nearest nighboring point coordinates in 2d grid using python | I try to find the nearest point in geoida database for every point stored in second database.
Here's may approach, which is extremely slow. geoida.db stores +55000 coordinates
import sqlite3
from kdtree import KDTree
database = sqlite3.connect('geoida.db')
cursor = database.cursor()
cursor.execute("select lat, lon fr... | [
"Why are you constructing the KDTree over and over again? It seems to me that you should construct it once and query it for every point. Constructing the tree is O(N log N) (or O(N (log N)^2) depending on the algorithm) so doing it N times makes your algorithm O(N^2 log N). Constructing the tree once and querying i... | [
3,
2
] | [] | [] | [
"coordinates",
"geospatial",
"latitude_longitude",
"python",
"sqlite"
] | stackoverflow_0007785255_coordinates_geospatial_latitude_longitude_python_sqlite.txt |
Q:
"cannot convert float infinity to integer" during drawing loglog plot from matplotlib
I need to draw some logarithmic plots from the data (values are already in logarithmic scale) however matplotlib somehow encounters infinity during preparation of loglog plot.
I believe that in is_decade function for some value w... | "cannot convert float infinity to integer" during drawing loglog plot from matplotlib | I need to draw some logarithmic plots from the data (values are already in logarithmic scale) however matplotlib somehow encounters infinity during preparation of loglog plot.
I believe that in is_decade function for some value which is close to 0, division by 0 occurs:
def is_decade(x,base=10):
lx = math.log(x)/ma... | [
"Your data is negative, for a loglog plot it has to be positive.\n"
] | [
1
] | [] | [] | [
"divide_by_zero",
"matplotlib",
"python"
] | stackoverflow_0007785720_divide_by_zero_matplotlib_python.txt |
Q:
Importing using string in Python
Short version:
Say I have a string str and a file functions.py from which I would like to import a method whose name is stored in str.
How do I go about it? I would like something like:
from functions.py import str
but have str evaluated and not to import the method 'str' (which ... | Importing using string in Python | Short version:
Say I have a string str and a file functions.py from which I would like to import a method whose name is stored in str.
How do I go about it? I would like something like:
from functions.py import str
but have str evaluated and not to import the method 'str' (which doesn't exist).
After some googling I ... | [
"Assuming your code to import the module into _tmp works then the final step is simply:\nfunc = getattr(_tmp, func_name)\n\n",
"The getattr method gives you an attribute of a given object. Since global functions are attributes of the module they are in, you can use this:\nimport functions\n\nfuncName = 'doSomethi... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007785726_python.txt |
Q:
After installing matplotlib basemap via Macports, example python code for basemap is not running
I'm using Mac OS X 10.6.8. I installed Python 2.6 using the binary installer in http://www.python.org/. I've been using it along with SciPy and Matplotlib for my scientific computing needs since March 2011 without any ... | After installing matplotlib basemap via Macports, example python code for basemap is not running | I'm using Mac OS X 10.6.8. I installed Python 2.6 using the binary installer in http://www.python.org/. I've been using it along with SciPy and Matplotlib for my scientific computing needs since March 2011 without any problems. Recently, I have the need for the matplotlib library called Basemap.
I followed this article... | [
"As you noted, MacPorts installs its own Python version (by default, at /opt/local/bin/python2.6). If you install a Python package via MacPorts, like basemap, you normally will need to run everything under the MacPorts Python. Don't try to mix and match Python instances. Packages that include C extension modules... | [
4
] | [] | [] | [
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0007783640_matplotlib_numpy_python_scipy.txt |
Q:
Is it safe to store a connection (effectively a pointer) in memcache?
I am using memcached on a web site, and I am currently needing to open connections to a database and socket each time a function is called. In the case of the db connection, I am having to decide at runtime, which database to connect to.
Because... | Is it safe to store a connection (effectively a pointer) in memcache? | I am using memcached on a web site, and I am currently needing to open connections to a database and socket each time a function is called. In the case of the db connection, I am having to decide at runtime, which database to connect to.
Because of the (default) stateless nature of web apps, I am having to tear down (i... | [
"Both languages support database connections which live beyond the lifetime of a single request. Don't use memcache for that!\n",
"\nI am wondering if it is possible to store (i.e. cache) the socket connection and the database connections in memcache \n\nNo.\n"
] | [
0,
0
] | [] | [] | [
"memcached",
"php",
"python"
] | stackoverflow_0007783860_memcached_php_python.txt |
Q:
How do I call python subclassed methods from superclass methods?
I have the following kind of superclass / subclass setup:
class SuperClass(object):
def __init__(self):
self.do_something() # requires the do_something method always be called
def do_something(self):
raise NotImplementedErro... | How do I call python subclassed methods from superclass methods? | I have the following kind of superclass / subclass setup:
class SuperClass(object):
def __init__(self):
self.do_something() # requires the do_something method always be called
def do_something(self):
raise NotImplementedError
class SubClass(SuperClass):
def __init__(self):
super(S... | [
"Your code is mostly correct, except for the use of super. You need to put the current class name in the super call, so it would be:\nsuper(SubClass, self).__init__()\n\nSince you put in the wrong class name, SuperClass.__init__ wasn't called, and as a result do_something wasn't called either.\n"
] | [
9
] | [] | [] | [
"abc",
"init",
"python",
"subclass",
"super"
] | stackoverflow_0007785894_abc_init_python_subclass_super.txt |
Q:
psycopg2: error in display many columns of data in Python connecting to PostgreSQL
I am using psycopg2 to connect to Postgres database and return query results on the screen using Python. I can only return one column of data, not many columns like PSQL does. Please see my code. Where did I do wrong?
Your kind re... | psycopg2: error in display many columns of data in Python connecting to PostgreSQL | I am using psycopg2 to connect to Postgres database and return query results on the screen using Python. I can only return one column of data, not many columns like PSQL does. Please see my code. Where did I do wrong?
Your kind response would be greatly appreciated.
#!/usr/bin/python
import psycopg2
CONNSTR = """
... | [
"I found the answer on initd.org/psycopg/docs/cursor.html. Here is the correct code. Please see the last two lines of code with the changes.\nFor clarification, the first version of code only returns one column of data. The 2nd version listed below will return, actually it will display/print, all the columns I s... | [
1,
0
] | [] | [] | [
"arrays",
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0007779659_arrays_postgresql_psycopg2_python.txt |
Q:
Determining if a query is in a string
I have a list of query terms, each with a boolean operator associated with them, like, say:
tom OR jerry OR desperate AND dan OR mickey AND mouse
Okay, now I have a string containing user-defined input, inputStr.
My question is, in Python, is there a way to determine if the s... | Determining if a query is in a string | I have a list of query terms, each with a boolean operator associated with them, like, say:
tom OR jerry OR desperate AND dan OR mickey AND mouse
Okay, now I have a string containing user-defined input, inputStr.
My question is, in Python, is there a way to determine if the string defined by the user contains the word... | [
"To check whether any of the words in a list are in the string: \nany(word in string for word in lst)\n\nExample:\n# construct list from the query by removing 'OR', 'AND'\nquery = \"tom OR jerry OR desperate AND dan OR mickey AND mouse\"\nlst = [term for term in query.split() if term not in [\"OR\", \"AND\"]]\n\nst... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007785685_python.txt |
Q:
How do I separate my executable files from my library files?
I still haven't gotten an answer that I'm happy with. Please do submit some answers if you have a nice system for your Python or PHP projects.
I'm having a management issue with my PHP and Python projects. They both have two kinds of code files: files t... | How do I separate my executable files from my library files? | I still haven't gotten an answer that I'm happy with. Please do submit some answers if you have a nice system for your Python or PHP projects.
I'm having a management issue with my PHP and Python projects. They both have two kinds of code files: files that should be run in the console or web browser, and files that sh... | [
"Separate them somehow (by name, by extension, by location).\n\nExample:\nHere's the layout of our test automation system (output is manually sorted for clarity):\n$ ls -1 automation\natf \\ two major homebrew libraries, with many submodules\natflib / \n\natfconfig configuration fil... | [
1,
0
] | [] | [] | [
"php",
"project_management",
"python"
] | stackoverflow_0007768881_php_project_management_python.txt |
Q:
Nosetests ran 0 tests
When I run
nosetests --doctest-extension=.txt
I get
Ran 0 tests in 0.002s
OK
Why does it say 0 tests when I have tests in the file README.txt?
A:
If you're using doctest you also have to specify that nose has to run with the doctest plugin enabled.
This should do the trick:
nosetests --wi... | Nosetests ran 0 tests | When I run
nosetests --doctest-extension=.txt
I get
Ran 0 tests in 0.002s
OK
Why does it say 0 tests when I have tests in the file README.txt?
| [
"If you're using doctest you also have to specify that nose has to run with the doctest plugin enabled.\nThis should do the trick:\nnosetests --with-doctest --doctest-extension=txt\n\n"
] | [
3
] | [] | [] | [
"nosetests",
"python"
] | stackoverflow_0007786195_nosetests_python.txt |
Q:
does Enthought Python distribution includes pyhdf and HDF 4
In Enthought Python Distribution, I saw it includes pyhdf and numpy. Since it includes pyhdf, does it also include HDF 4?
I am using pylab to code at this moment.
Because I want to use a module of the pyhdf package called pyhdf.SD. And it Prerequisites HD... | does Enthought Python distribution includes pyhdf and HDF 4 | In Enthought Python Distribution, I saw it includes pyhdf and numpy. Since it includes pyhdf, does it also include HDF 4?
I am using pylab to code at this moment.
Because I want to use a module of the pyhdf package called pyhdf.SD. And it Prerequisites HDF 4 library. So do I still need to install HDF 4 if I want to use... | [
"For the versions of EPD that include pyhdf, you don't need to install HDF 4 separately. However, note that pyhdf is not included in all versions of EPD---in particular, it's not included in the 64-bit Windows EPD or the 64-bit OS X EPD, though it is in the 32-bit versions.\n"
] | [
1
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0007786232_image_processing_python.txt |
Q:
Python Programming homework
First off thank you for your time and answers. My task is to have my program open a text file, read its data so every word is a different string, and creating a HTML document displaying each one of these strings into a random color. So pretty much it wants us to take every word from a t... | Python Programming homework | First off thank you for your time and answers. My task is to have my program open a text file, read its data so every word is a different string, and creating a HTML document displaying each one of these strings into a random color. So pretty much it wants us to take every word from a text file change each word into a ... | [
"Since this is homework, I'll limit my answer to a hint:\nYou're currently generating one random colour, and applying it to every word. What you should be doing is generating a new random colour for every word.\n",
"this code should be in the loop (for i in range(filelength):)\nnum = int(random.uniform(0,256))\nn... | [
9,
1,
0,
0
] | [] | [] | [
"file_io",
"html",
"python"
] | stackoverflow_0007786675_file_io_html_python.txt |
Q:
Parsing html to get a whole paragraph while avoiding interruption from other tags
I've asked a question on how to use lxml to parse a url and get <p> elements back. It is resolved. However, to fully achieve my goal, I need to consider the effect of other tags inside a <p>.
The accepted answer provided by Acorn to ... | Parsing html to get a whole paragraph while avoiding interruption from other tags | I've asked a question on how to use lxml to parse a url and get <p> elements back. It is resolved. However, to fully achieve my goal, I need to consider the effect of other tags inside a <p>.
The accepted answer provided by Acorn to parse a url and get <p> back is:
import lxml.html
htmltree = lxml.html.parse('http://w... | [
"Yes, /text() gets the immediate text element in that tag. Instead, get all p tags and use .text_content() to get all the text in them. From lxml.html doc:\n\n.text_content(): \nReturns the text content of the element, including\n the text content of its children, with no markup.\n\nSo you will have something like... | [
4,
1
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0007786443_lxml_python.txt |
Q:
string.title() thinks apostrophe is a new word start. Why?
>>> myStr="madam. i'm adam! i also tried c,o,m,m,a"
>>> myStr.title()
"Madam. I'M Adam! I Also Tried C,O,M,M,A"
This is certainly incorrect. Why would an apostrophe be considered be considered as the start of a new word. Is this a gotcha or a am I assumin... | string.title() thinks apostrophe is a new word start. Why? |
>>> myStr="madam. i'm adam! i also tried c,o,m,m,a"
>>> myStr.title()
"Madam. I'M Adam! I Also Tried C,O,M,M,A"
This is certainly incorrect. Why would an apostrophe be considered be considered as the start of a new word. Is this a gotcha or a am I assuming something wrong about the concept of title?
| [
"Because the implementation works by looking at the previous character, and if it's alphanumeric it lower cases the current character, otherwise it upper cases it. That is to say, it's relatively simple, here's what a pure-python version of it looks like:\ndef title(string):\n result = []\n prev_letter = ' '... | [
5,
3,
2,
2
] | [] | [] | [
"python",
"string",
"title"
] | stackoverflow_0007786868_python_string_title.txt |
Q:
Python Shorthand Operator?
I was researching some information on the topic of trial division, and I came across this symbol in Python:
//=
I got this from here where the code in the example says:
n //= p
I can't tell what this is supposed to mean, and my research continues to bring poor results in terms of webpa... | Python Shorthand Operator? | I was researching some information on the topic of trial division, and I came across this symbol in Python:
//=
I got this from here where the code in the example says:
n //= p
I can't tell what this is supposed to mean, and my research continues to bring poor results in terms of webpages.
| [
"// is integer division and the\nn //= p\n\nsyntax is short for \nn = n // p\n\nexcept the value n is modified directly if it supports this.\n",
"When you see an operator followed by an =, that is performing the operation and then assigning it into the variable. For example, x += 2 means x = x + 2 or add 2 to x.\... | [
10,
5,
1
] | [] | [] | [
"python",
"shorthand"
] | stackoverflow_0007786924_python_shorthand.txt |
Q:
Can I download only partial part of Internet web page using lxml?
I'm not sure if this is possible and lxml documentation is not very good to me.
Can I for example use something like:
import lxml.html as lx
x = lx.parse('http://web.info/page.html')
y = x.xpath('\\something\interesting'[2])
or similar, so that I d... | Can I download only partial part of Internet web page using lxml? | I'm not sure if this is possible and lxml documentation is not very good to me.
Can I for example use something like:
import lxml.html as lx
x = lx.parse('http://web.info/page.html')
y = x.xpath('\\something\interesting'[2])
or similar, so that I don't download whole page?
If not with lxml is there some Python module ... | [
"You could try incremental parsing:\nimport urllib2\nimport lxml.html as LH\n\n# request a partial download\nurl='http://www.python.org/'\nreq = urllib2.Request(url)\nreq.headers['Range'] = 'bytes=%s-%s' % (0, 1024)\nf = urllib2.urlopen(req)\ncontent=f.read()\n# print(content)\n\n# incremental parsing\nparser=LH.HT... | [
3,
1
] | [] | [] | [
"lxml",
"python",
"web"
] | stackoverflow_0007786979_lxml_python_web.txt |
Q:
Issues with Python Tkinter: Frames within a Canvas
I'm trying to set up a scrollable series of Frames, so I've nested them into a Canvas. Below, I've included some sample code that demonstrates the problem.
However, I have three issues:
Frame c doesn't seem to expand horizontally to fill the canvas.
If I use mul... | Issues with Python Tkinter: Frames within a Canvas | I'm trying to set up a scrollable series of Frames, so I've nested them into a Canvas. Below, I've included some sample code that demonstrates the problem.
However, I have three issues:
Frame c doesn't seem to expand horizontally to fill the canvas.
If I use multiple frames c, the canvas scrolls, but if I try to nest... | [
"It looks like you are both packing the window in a canvas and creating a window object. I honestly have never done that but I don't think the packing does any good.\nWhen you create a widget that is an object in a canvas, it will not expand to fill the canvas. What you'll need to do is create a binding to the <Con... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007787251_python_tkinter.txt |
Q:
twinx kills tick label color
I am plotting a double plot with two y-axes. The second axis ax2 is created by twinx. The problem is that the coloring of the second y-axis via yticks is not working anymore. Instead I have to set_color the labels individually. Here is the relevant code:
fig = plt.figure()
fill_between... | twinx kills tick label color | I am plotting a double plot with two y-axes. The second axis ax2 is created by twinx. The problem is that the coloring of the second y-axis via yticks is not working anymore. Instead I have to set_color the labels individually. Here is the relevant code:
fig = plt.figure()
fill_between(data[:,0], 0, (data[:,2]), color=... | [
"For whatever it's worth, you code works fine on my system even without the for loop to set the label colors. Just as a reference, here's a stand-alone example trying to follow essentially exactly what you posted:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Generate some data\nnum = 200\nx = np.linsp... | [
2
] | [] | [] | [
"colors",
"matplotlib",
"python"
] | stackoverflow_0007779164_colors_matplotlib_python.txt |
Q:
python in applescript: subprocess.call vs os.system in automator
I found a work around when calling a python script from a shell script from automator (version 2.1.1 in mac os x 10.6.8) (python 2.6.1). My issue is that os.system("mkdir foo") works in a (very specific) case where subprocess.call("mkdir foo") also ... | python in applescript: subprocess.call vs os.system in automator | I found a work around when calling a python script from a shell script from automator (version 2.1.1 in mac os x 10.6.8) (python 2.6.1). My issue is that os.system("mkdir foo") works in a (very specific) case where subprocess.call("mkdir foo") also makes the directory but then makes automator throw an error.
The purp... | [
"You could use os.mkdir(stu_dir_full)...\nBut the problem with your subprocess.call line might be that subprocess.call is expecting a list not a string. Try this:\nretcode = call([\"mkdir\",dir_full], shell=True)\n\n"
] | [
0
] | [] | [] | [
"automator",
"os.system",
"python",
"shell",
"subprocess"
] | stackoverflow_0007781000_automator_os.system_python_shell_subprocess.txt |
Q:
Parallelizing a set intersection operation?
I have a file like this:
A 1
A 1
A 2
A 3
B 2
B 3
C 2
C 3
which I converted into the following data structure:
s = [set([1, 2, 3]), set([2, 3]), set([2,3])]
To find the length of the intersection of all 2-combinations, I am using the following:
from itertools import com... | Parallelizing a set intersection operation? | I have a file like this:
A 1
A 1
A 2
A 3
B 2
B 3
C 2
C 3
which I converted into the following data structure:
s = [set([1, 2, 3]), set([2, 3]), set([2,3])]
To find the length of the intersection of all 2-combinations, I am using the following:
from itertools import combinations
for i in combinations(s, 2):
inter ... | [
"If you haven't already, check out the multiprocessing module. Also, while convenient, it isn't necessary to use itertools.combinations() to get a set of all unique 2-combinations. If you can accept the use of global variables, you could use multiprocessing.Pool.map() to farm it out to a pool of processes. For exam... | [
0
] | [] | [] | [
"mapreduce",
"parallel_processing",
"python"
] | stackoverflow_0007782419_mapreduce_parallel_processing_python.txt |
Q:
sending a period to end a mail DATA telnet session in python
im using a telnetlib in python to connect to a simple mail server and send out an email; everything works fine until the very end after i enter the DATA command, you submit the body of your message and in order to submit the email in the server's queue, ... | sending a period to end a mail DATA telnet session in python | im using a telnetlib in python to connect to a simple mail server and send out an email; everything works fine until the very end after i enter the DATA command, you submit the body of your message and in order to submit the email in the server's queue, you need to type a period "." on a new line by itself so my end tr... | [
"you need the <CR><LF> newline-squence try:\nself.tnet.write(\"\\r\\n.\\r\\n\")\n\nhope that helps\n"
] | [
1
] | [] | [] | [
"email",
"period",
"python",
"telnetlib"
] | stackoverflow_0007787978_email_period_python_telnetlib.txt |
Q:
Integrating a C applet into a Python app (GTK)
I've got a Python/GTK project I've been working on for a while, and some of the functionality I want already exists in Gnome panel applets. Based on my reading, panel applets are already in a subclass of the standard GTK Bin, so I would think there'd be a way that I ... | Integrating a C applet into a Python app (GTK) | I've got a Python/GTK project I've been working on for a while, and some of the functionality I want already exists in Gnome panel applets. Based on my reading, panel applets are already in a subclass of the standard GTK Bin, so I would think there'd be a way that I can use the C-based GTK objects in my Python-based a... | [
"The code for applets in gnome panel is quite complex. It's based on the gnome Bonobo framework (which in turn is based on CORBA). But now the whole thing is in a bit of a flux because gnome is moving away from Bonobo to a new dbus-based design. So if it's loading existing gnome panel applets you want you should ab... | [
1
] | [] | [] | [
"c",
"gtk",
"python"
] | stackoverflow_0004513937_c_gtk_python.txt |
Q:
Evaluate expression as float in Python
I want to write a function which inputs two variables a, b and which returns a/b as a float irrespective of the types of a and b. Right now I'm doing this as:
def f(a, b):
return float(a)/float(b)
Is there a better way to do this?
A:
Assuming you are using Python2, put... | Evaluate expression as float in Python | I want to write a function which inputs two variables a, b and which returns a/b as a float irrespective of the types of a and b. Right now I'm doing this as:
def f(a, b):
return float(a)/float(b)
Is there a better way to do this?
| [
"Assuming you are using Python2, put this at the top of the file\nfrom __future__ import division\n\nnow / will always give a float. Use // for the old behaviour.\nIf you are using Python3, then this is already the default behaviour of /\n",
"You could simply force the conversion of one of the operands to the flo... | [
10,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007788419_python.txt |
Q:
append word from line when reading txt file python
I am trying to create a program that will read a text file and create a list of lines of words.
However am only able to append each line and not word, any help would be appreciated with this problem.
text = open("file.txt","r")
for line in text.readlines():
s... | append word from line when reading txt file python | I am trying to create a program that will read a text file and create a list of lines of words.
However am only able to append each line and not word, any help would be appreciated with this problem.
text = open("file.txt","r")
for line in text.readlines():
sentence = line.strip()
list.append(sentence)
pr... | [
"Each line in the example is just a string, so something like,\n...\n PUNCTUATION = ',.?!\"\\''\n words = [w.strip(PUNCTUATION) for w in line.split() if w.strip(PUNCTUATION)]\n list.append(words)\n...\n\nwould probably be okay to the first approximation although may not cover every edge case in the way tha... | [
1,
1,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007788170_python.txt |
Q:
Basic Python Sound Programming
How can I make a program that plays a tone that I define while I hold down a key? I can play different notes with winsound.Beep(), but I don't think this really helps.
A:
If you just want to use the standard library and youre using, you can use msvcrt to get the current keypress an... | Basic Python Sound Programming | How can I make a program that plays a tone that I define while I hold down a key? I can play different notes with winsound.Beep(), but I don't think this really helps.
| [
"If you just want to use the standard library and youre using, you can use msvcrt to get the current keypress and map that to a frequency.\nimport msvcrt\nimport time\nimport winsound\n\nnotes = {'a': 440, 's': 935, 'd': 1039}\n\nwhile True:\n key = msvcrt.getch()\n try:\n note = notes[key]\n except... | [
1,
0
] | [] | [] | [
"audio",
"python"
] | stackoverflow_0007787825_audio_python.txt |
Q:
Way to disable "System" service or process for a short period of time? Python
I'm not sure if it is a service or process, but is there a way to disable it or stop it? A file which I'm trying to copy is being run by the system but the system does not require this .sys file.
If there is way in python I would be even... | Way to disable "System" service or process for a short period of time? Python | I'm not sure if it is a service or process, but is there a way to disable it or stop it? A file which I'm trying to copy is being run by the system but the system does not require this .sys file.
If there is way in python I would be even more ecstatic to read the response.
| [
"As a general rule, if Windows says that it needs a file, you will be very hard pressed to get it to completely relinquish control. While that process is running, it will have exclusive rights (read, write, and execute) to the file (or files) in question, so I will highly doubt that there will be an effective hack ... | [
1
] | [] | [] | [
"process",
"python",
"service",
"windows"
] | stackoverflow_0007788632_process_python_service_windows.txt |
Q:
Is auto_now_add property updated each time when put is called?
I have db model, where one property has auto_now_add=True. But looks like it doesn't work as I've expected - it is updated each time when put is called (I use my own key_name, so second/third/N call of put doesn't really create new record - just update... | Is auto_now_add property updated each time when put is called? | I have db model, where one property has auto_now_add=True. But looks like it doesn't work as I've expected - it is updated each time when put is called (I use my own key_name, so second/third/N call of put doesn't really create new record - just update it).
Here is the code:
class User(db.Model):
id = db.IntegerPro... | [
"You are recreating the entity each time, here is how the code should look like:\n#This will create the object only once\nreturn User.get_or_insert(key_name=\"id%d\" % unique_user_id, \n id=unique_user_id, \n name = current_name)\n\n#This will create the object and ... | [
4,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007783952_google_app_engine_google_cloud_datastore_python.txt |
Q:
SQLAlchemy Subquery for Suming values from another table
I am struggling to understand the proper syntax for executing a subquery in SQLAlchemy when the value needs to be returned (i.e. not used in the WHERE).
I am using the declarative approach.
There are two models being used:
class ProjectInvoices(Base):
In... | SQLAlchemy Subquery for Suming values from another table | I am struggling to understand the proper syntax for executing a subquery in SQLAlchemy when the value needs to be returned (i.e. not used in the WHERE).
I am using the declarative approach.
There are two models being used:
class ProjectInvoices(Base):
InvoiceID = Column(Integer(unsigned=True), default=0, primary_ke... | [
"Usually I would use a column_property to handle such requirement, e.g.\nclass ProjectMasters(Base):\n ...\n\n billed_total = column_property(\n select(\n [func.sum(\n func.coalesce(ProjectInvoices.ExpenseAmount, 0)\n + func.coalesce(ProjectInvoices.HoursAmount,... | [
6
] | [] | [] | [
"declarative",
"python",
"sqlalchemy",
"subquery"
] | stackoverflow_0007788288_declarative_python_sqlalchemy_subquery.txt |
Q:
app engine bulkloader post_import_function - how to call method on entity
Trying to use python GeoModel class and the bulkloader. I'm calling the following post_import_function which works fine and the entity is updated with the location field set properly.
def post_process_obj(input_dict, entity_instance, bulkl... | app engine bulkloader post_import_function - how to call method on entity | Trying to use python GeoModel class and the bulkloader. I'm calling the following post_import_function which works fine and the entity is updated with the location field set properly.
def post_process_obj(input_dict, entity_instance, bulkload_state):
entity_instance['location'] = db.GeoPt(entity_instance['latitud... | [
"You can't do this - as you observed, you're dealing with an Entity, not an instance of your model. The only option is to take the code that you want to execute it, copy-and-paste it, and modify it to work with an entity instead. \n"
] | [
1
] | [] | [] | [
"bulkloader",
"google_app_engine",
"python"
] | stackoverflow_0007769415_bulkloader_google_app_engine_python.txt |
Q:
How to send a packet via proxy?
How would I go about doing this in python? I need to establish a stronger connection than I may have to the server.
A:
Using urllib2 (which is the easiest way to fetch resources from a http server), you need to set the http_proxy environment variable.
If your proxy is unauthentic... | How to send a packet via proxy? | How would I go about doing this in python? I need to establish a stronger connection than I may have to the server.
| [
"Using urllib2 (which is the easiest way to fetch resources from a http server), you need to set the http_proxy environment variable. \nIf your proxy is unauthenticated it will be something like:\nexport http_proxy=http://proxy:port/\n\nIf your proxy is authenicating, it will be:\nexport http_proxy=http://username:... | [
1
] | [] | [] | [
"packet",
"proxy",
"python"
] | stackoverflow_0007788831_packet_proxy_python.txt |
Q:
Why is my RPC total going up?
I'm Trying to optimize my code, and I got into a problem I don't quite understand. On every page of my web app, there will be a list of notifications much like Facebook's new ticker. So, on every request, I run this code in the beggining:
notification_query = db.Query(Ticker, keys_onl... | Why is my RPC total going up? | I'm Trying to optimize my code, and I got into a problem I don't quite understand. On every page of my web app, there will be a list of notifications much like Facebook's new ticker. So, on every request, I run this code in the beggining:
notification_query = db.Query(Ticker, keys_only=True)\
.filter('friends =',sel... | [
"In addition to Peter's note, you should bear in mind that Appstats has no way to know when an asynchronous request actually completes, except when you fetch the result. As a result, even fast calls will look slow if you take a long time to request the result.\n",
"Ahhhh. It is very helpful when posting about ap... | [
3,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007759521_google_app_engine_python.txt |
Q:
working with combinations object in python
>>> import itertools
>>> n = [1,2,3,4]
>>> combObj = itertools.combinations(n,3)
>>>
>>> combObj
<itertools.combinations object at 0x00000000028C91D8>
>>>
>>> list(combObj)
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
>>>
>>> for i in list(combObj): #This prints nothing
.... | working with combinations object in python | >>> import itertools
>>> n = [1,2,3,4]
>>> combObj = itertools.combinations(n,3)
>>>
>>> combObj
<itertools.combinations object at 0x00000000028C91D8>
>>>
>>> list(combObj)
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
>>>
>>> for i in list(combObj): #This prints nothing
... print(i)
...
How can i iterate through ... | [
"Once you iterate through the itertools.combinations object once, it's been used up and you can't iterate over it a second time.\nIf you need to reuse it, the proper way is to make it a list or tuple as you did. All you need to do is give it a name (assign it to a variable) so it sticks around.\ncombList = list(com... | [
7,
0,
0
] | [] | [] | [
"combinations",
"python",
"python_3.x",
"python_itertools"
] | stackoverflow_0007788230_combinations_python_python_3.x_python_itertools.txt |
Q:
python 2.x and mysqldb 5: how to ignore all characters in a string
I am currently working on a python script that pulls data from a table on databaseA, and puts all that data into databaseB, which is not located near databaseA. when calling an insert into databaseB I get an error from the mysqldb module 1064:
You ... | python 2.x and mysqldb 5: how to ignore all characters in a string | I am currently working on a python script that pulls data from a table on databaseA, and puts all that data into databaseB, which is not located near databaseA. when calling an insert into databaseB I get an error from the mysqldb module 1064:
You have an error in your SQL syntax; check the manual that corresponds to y... | [
"Instead of (\"%s\",\"%s\", etc etc) for the insert values, just do (%s,%s, etc etc)\nYou will however need to use string formatting to get the table name in the SQL.\nHere's an example, with 2 columns instead of 40:\nsql2 = \"insert into\" + bush + \"(orders_id, customers_id) Values (%s, %s)\"\ncursor.execute(sql2... | [
1
] | [] | [] | [
"mysql_python",
"python",
"quotes"
] | stackoverflow_0007789093_mysql_python_python_quotes.txt |
Q:
Dynamic Access of Multi dimensional Python Array
I am a python newbie. I was confused on how to access array element dynamically.
I have a list b= [1,2,5,8] that I dynamically obtain so its length can vary. With help of this list I need to update multi-dimensional array as mArr[1] [2] [5] [8] . The length of the ... | Dynamic Access of Multi dimensional Python Array | I am a python newbie. I was confused on how to access array element dynamically.
I have a list b= [1,2,5,8] that I dynamically obtain so its length can vary. With help of this list I need to update multi-dimensional array as mArr[1] [2] [5] [8] . The length of the list and array dimension matches as given in the examp... | [
"if the dimensions are [1,2,5,8] you can use numbers 0, 0..1, 0..4, 0..7 for each dimension.\nNumpy lets you access positions with tuples:\nshape = [1, 2, 5, 8]\npos = [0, 1, 1, 3]\n\nmy_array = np.ones(shape)\nmy_array[tuple(pos)] # will return 1\n\n",
"You could create a function like:\ndef array_update(b, marr... | [
2,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007789143_numpy_python.txt |
Q:
What data structure/db should I use for storing the file tree structure?
I am trying to write an application(I am using python) to have a copy of a remote machines directory structure in my local machine (not the actual content of the files in the remote machine).
Once I store it in my local machine, I want to be ... | What data structure/db should I use for storing the file tree structure? | I am trying to write an application(I am using python) to have a copy of a remote machines directory structure in my local machine (not the actual content of the files in the remote machine).
Once I store it in my local machine, I want to be be able to perform the following operations on my local copy of the tree struc... | [
"I think you should declare a class which has a list of its own type. Basically a simple tree structure. \nFor ls:\nJust dispay all the child recursively.\nFor any new addition:\nAdd it to the parent directory node's child list as a child.\n"
] | [
0
] | [] | [] | [
"data_structures",
"database",
"database_design",
"python"
] | stackoverflow_0007789253_data_structures_database_database_design_python.txt |
Q:
Ipython / pylab / matplotlib plotting error
I've installed Enthought's EPD (64 bit for Windows 7).
I'm trying to plot historical stock quote data using Yahoo's API. All the code I'm trying to use is on this blog post:
http://www.traineetrader.com/importing-stock-data-from-yahoo-using-python/
The ystockquote.py fil... | Ipython / pylab / matplotlib plotting error | I've installed Enthought's EPD (64 bit for Windows 7).
I'm trying to plot historical stock quote data using Yahoo's API. All the code I'm trying to use is on this blog post:
http://www.traineetrader.com/importing-stock-data-from-yahoo-using-python/
The ystockquote.py file works fine.
But the second script to plot Googl... | [
"In addition to adding from pylab import *, you need to add show() after the last line of the script (i.e., after grid(True)) in your question to actually display the plot.\nHere is what I get after adding show():\n\n"
] | [
7
] | [] | [] | [
"ipython",
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0007789201_ipython_matplotlib_numpy_python_scipy.txt |
Q:
How do I fix the syntax in my code to make my radio buttons work with my dictionary?
I am trying to learn how to use a dictionary with a radio button. I have the code below but when ever I run it I get an error.
The error says:
Traceback (most recent call last): File "/Volumes/CHROME
USB/STORAGE/TKinker GUI/Radi... | How do I fix the syntax in my code to make my radio buttons work with my dictionary? | I am trying to learn how to use a dictionary with a radio button. I have the code below but when ever I run it I get an error.
The error says:
Traceback (most recent call last): File "/Volumes/CHROME
USB/STORAGE/TKinker GUI/Radiobutton + Dictionary.py", line 16, in
<module>
for i in sorted(choices.keys()): NameEr... | [
"You haven't provided the crucial info -- what line the error happens on.\nHowever, you appear to have an indentation error here:\nfor i in sorted(choices.keys()):\n label = \"%s - %s\" % (i, choices[i])\n rb=Radiobutton(master, text=label, variable=v, value=i)\n rb.pack(side=TOP, anchor=\"w\")\n\nThe line... | [
1
] | [] | [] | [
"dictionary",
"python",
"radio_button",
"tkinter"
] | stackoverflow_0007789090_dictionary_python_radio_button_tkinter.txt |
Q:
Share django lib
How share Django lib with multiple python (for example 2.6 and 3.1) ?
A simple way is with ln -s ... is the correct way or is there something a little more clever?
A:
You should be using virtualenv for all of your python projects anyway: just install the modules you need for whichever project yo... | Share django lib | How share Django lib with multiple python (for example 2.6 and 3.1) ?
A simple way is with ln -s ... is the correct way or is there something a little more clever?
| [
"You should be using virtualenv for all of your python projects anyway: just install the modules you need for whichever project you are working on, rather than trying to worry about 'sharing'. For modules that compile files, you are probably going to hit problems doing it that way anyway.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007784888_django_python.txt |
Q:
Creating arrays while processing big file
This is my first post even though I've been reading SO for a while.
I'm a Python beginner and I'd need your help.
I'm processing a very big file (more than 2 million of lines) but I'll show you a much smaller example (24 lines rather than 74513). So let's say I've got 24 l... | Creating arrays while processing big file | This is my first post even though I've been reading SO for a while.
I'm a Python beginner and I'd need your help.
I'm processing a very big file (more than 2 million of lines) but I'll show you a much smaller example (24 lines rather than 74513). So let's say I've got 24 lines, each one with a floating point number, af... | [
"You can use readline() to read a single line 24 times then use another readline() to skip a line and so on.\nWith your code:\nimport numpy\n\ndef mk_array(elems):\n '''Makes the nparray from an array of 24 numbers'''\n ttarray = np.array(elems) # perhaps [ float(a) for a in elems ] is needed\n ttarray.sha... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007789425_python.txt |
Q:
Whoosh Query Composition for docs containing 'most' terms
I've just started using Whoosh and noticed that queries seem to have logic applied to each term such as AND([term1, term2, ...]) or OR([term1, term2, ...]).
My problem is that I want to include documents that include most of the terms in my search string, b... | Whoosh Query Composition for docs containing 'most' terms | I've just started using Whoosh and noticed that queries seem to have logic applied to each term such as AND([term1, term2, ...]) or OR([term1, term2, ...]).
My problem is that I want to include documents that include most of the terms in my search string, but not necessarily all. The more terms a doc has, the more "rel... | [
"You can configure the Whoosh parser to default to using OR rather than AND between query terms. See http://packages.python.org/Whoosh/parsing.html#common-customizations.\nYou can then write a custom scoring class that scores items higher if they have more of the search terms. See http://packages.python.org/Whoosh/... | [
0
] | [] | [] | [
"full_text_search",
"python",
"whoosh"
] | stackoverflow_0007787893_full_text_search_python_whoosh.txt |
Q:
python How to create private class variables using setattr or exec?
I've just run into a situation where pseudo-private class member names aren't getting mangled when using setattr or exec.
In [1]: class T:
...: def __init__(self, **kwargs):
...: self.__x = 1
...: for k, v in kwargs.it... | python How to create private class variables using setattr or exec? | I've just run into a situation where pseudo-private class member names aren't getting mangled when using setattr or exec.
In [1]: class T:
...: def __init__(self, **kwargs):
...: self.__x = 1
...: for k, v in kwargs.items():
...: setattr(self, "__%s" % k, v)
...:
... | [
"I believe Python does private attribute mangling during compilation... in particular, it occurs at the stage where it has just parsed the source into an abstract syntax tree, and is rendering it to byte code. This is the only time during execution that the VM knows the name of the class within whose (lexical) sco... | [
10,
4,
2
] | [] | [] | [
"attributes",
"name_mangling",
"private_members",
"python"
] | stackoverflow_0007782233_attributes_name_mangling_private_members_python.txt |
Q:
How do I make radiobuttons assign either a 0,1,2 or 3 to my variables?
Here is a rough example of a multiple choice test that I made. It runs in terminal and I'm hoping to make a Graphical User Interface for it using Tkinter.
print "CATEGORY 1: ANXIOUS FEELINGS"
print
print "1. Anxiety, nervousness, worry or fear"... | How do I make radiobuttons assign either a 0,1,2 or 3 to my variables? | Here is a rough example of a multiple choice test that I made. It runs in terminal and I'm hoping to make a Graphical User Interface for it using Tkinter.
print "CATEGORY 1: ANXIOUS FEELINGS"
print
print "1. Anxiety, nervousness, worry or fear"
BAI_var1 = input ("Please enter 0 for not at all, 1 for somewhat, 2 for mod... | [
"change all of the places where you have v with self.v so that it becomes an attribute of the object. You'll then see that it has whatever value is selected in the group of radiobuttons.\n...\nself.v = IntVar()\n...\nRadiobutton(master, text=\"1 for somewhat\", variable=self.v, value=2)...\n...\n\nOnce you do that,... | [
2,
0
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0007788933_python_tkinter_user_interface.txt |
Q:
Python : Getting a handle to imported modules
I have written an application that gives the user an option to specify a particular network scanning tool (say nmap,xprobe,p0f) and then scans a given subnet with that tool (I do not re-implement the tool, simply call it in shell and parse its response for my app), par... | Python : Getting a handle to imported modules | I have written an application that gives the user an option to specify a particular network scanning tool (say nmap,xprobe,p0f) and then scans a given subnet with that tool (I do not re-implement the tool, simply call it in shell and parse its response for my app), parses the result and stores in a particular format in... | [
"If you only need to run on Windows, then I recommend trying py2exe.\n\npy2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.\n\nWe use it at work to speed up a very large Python program, and it copes with imported... | [
0
] | [] | [] | [
"python",
"python_2.6",
"python_module"
] | stackoverflow_0007789693_python_python_2.6_python_module.txt |
Q:
zeromq request/response example showing use of a queue in Python?
Can anyone please post a Python example that demonstrates the use of a request/response messaging model that utilizes the zeromq queue?.
I have done a lot of online searching but have not as yet been able to locate such an example. The article here ... | zeromq request/response example showing use of a queue in Python? | Can anyone please post a Python example that demonstrates the use of a request/response messaging model that utilizes the zeromq queue?.
I have done a lot of online searching but have not as yet been able to locate such an example. The article here does a great job of explaining the concept of the queue, but unfortunat... | [
"You will find several examples here http://zguide.zeromq.org/page:all#Chapter-Four-Reliable-Request-Reply\nMost of the patterns have a source code example of a client app and a server app in several languages. Even when there is a Python source code example, I find it useful to look at the C source code version to... | [
4
] | [] | [] | [
"python",
"zeromq"
] | stackoverflow_0007790063_python_zeromq.txt |
Q:
How to import all data from a sqlite db into a Django non-rel db
I have a sqlite db with some records that I want to import into my Django non-rel db models.
Is the best way just to export the sqlite as a csv and then import the csv?
Something like suggested here: how to import csv data into django models or he... | How to import all data from a sqlite db into a Django non-rel db | I have a sqlite db with some records that I want to import into my Django non-rel db models.
Is the best way just to export the sqlite as a csv and then import the csv?
Something like suggested here: how to import csv data into django models or here: http://djangosnippets.org/snippets/633/
| [
"You can create a simple (regular) django project and use inspectdb to create the initial models from your sqlite db, then use dumpdata to save it to files. You can later use loaddata in your new project to load it into your models.\nIf you need further processing, you can create a small script that copies data fr... | [
2
] | [] | [] | [
"csv",
"django_models",
"django_nonrel",
"python"
] | stackoverflow_0007760474_csv_django_models_django_nonrel_python.txt |
Q:
Django form search
I am making a search form in django, and I am struggling with processing the form in my view.
My code:
class SearchForm(forms.Form):
name = forms.CharField(label="Name", max_length=64, required=False)
...
<a few other fields>
def search(request):
if request.method == 'POST':
... | Django form search | I am making a search form in django, and I am struggling with processing the form in my view.
My code:
class SearchForm(forms.Form):
name = forms.CharField(label="Name", max_length=64, required=False)
...
<a few other fields>
def search(request):
if request.method == 'POST':
form = SearchForm... | [
"To find your error code replace this code:\nname = form.cleaned_data['name']\nqdict = { 'name': name}\nq_objs = [Q(**{qdict[k]: form.cleaned_data[k]}) for k in qdict.keys() if form.cleaned_data.get(k, None)]\nsearch_results = Group.objects.select_related().filter(*q_objs)\n\nBy this one:\nq=None\nfor k,v in form.c... | [
1,
0
] | [] | [] | [
"django",
"django_forms",
"django_views",
"forms",
"python"
] | stackoverflow_0007781204_django_django_forms_django_views_forms_python.txt |
Q:
How can I check the data transfer on a network interface in python?
There is a socket method for getting the IP of a given network interface:
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
... | How can I check the data transfer on a network interface in python? | There is a socket method for getting the IP of a given network interface:
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s',... | [
"The best way to poll ethernet interface statistics is through SNMP...\n\nIt looks like you're using linux... if so, load up your snmpd with these options... after installing snmpd, in your /etc/defaults/snmpd (make sure the line with SNMPDOPTS looks like this):\nSNMPDOPTS='-Lsd -Lf /dev/null -u snmp -I -smux,usmCo... | [
7
] | [] | [] | [
"linux",
"networking",
"pysnmp",
"python",
"snmp"
] | stackoverflow_0007731411_linux_networking_pysnmp_python_snmp.txt |
Q:
read() stops after NUL character
I'm downloading files over HTTPS, I request the files through urllib2.Request and they come back as a socket._fileobject. I'd ideally like to stream this to file to avoid loading it into memory but I'm not sure how to do this.
My problem is if I call .read() on the object it only r... | read() stops after NUL character | I'm downloading files over HTTPS, I request the files through urllib2.Request and they come back as a socket._fileobject. I'd ideally like to stream this to file to avoid loading it into memory but I'm not sure how to do this.
My problem is if I call .read() on the object it only returns all the data up to the first NU... | [
"I found out the problem was that I was running the code inside PyScripter and the in-built python interpreter terminates NUL bytes in the output. So there was no problem with my code, if I run it outside PyScripter everything works fine. Now running Wing IDE and never looking back :)\n"
] | [
1
] | [] | [] | [
"nul",
"python"
] | stackoverflow_0007581963_nul_python.txt |
Q:
Save to a parallel directory in python
My file structure looks something like this:
ROOT
├── Admin
│ └── python_script.py
└── JSON
└── target_file.out
OK, my Python file is in the admin folder. I'm trying to save a file in the JSON folder. I've done fine saving the file in the Admin folder, but now I need... | Save to a parallel directory in python | My file structure looks something like this:
ROOT
├── Admin
│ └── python_script.py
└── JSON
└── target_file.out
OK, my Python file is in the admin folder. I'm trying to save a file in the JSON folder. I've done fine saving the file in the Admin folder, but now I need it to go where it is supposed to go, the JS... | [
"If you wanna store the file via a file-object you would do something like this:\n# . = -Root----Admin\n# .. = -Root\n# ../JSON = -Root----JSON\nmy_file = open(\"../JSON/targetfile\", \"w\")\nmy_file.write(\"foo\")\nmy_file.close()\n\n",
"If you always run the code from Admin, and the JSON folder is always at th... | [
3,
1
] | [] | [] | [
"python",
"relative_path",
"save",
"working_directory"
] | stackoverflow_0007791108_python_relative_path_save_working_directory.txt |
Q:
Python is telling me an indention is expected where I put one
OK, here's a piece of the script:
def start():
print "While exploring the ruins of a recently abandoned castle you stumble apon the entrance to what appears to be a dungeon. You are carrying on you a...
I keep getting the error
user@ubuntu:~/Docu... | Python is telling me an indention is expected where I put one | OK, here's a piece of the script:
def start():
print "While exploring the ruins of a recently abandoned castle you stumble apon the entrance to what appears to be a dungeon. You are carrying on you a...
I keep getting the error
user@ubuntu:~/Documents/python$ python dungeon.py
File "dungeon.py", line 533
... | [
"\nMake sure you aren't mixing tabs and spaces for indentation\nYour string is missing a closing quote\n\nFurther, is def start() actually indented in your file? It isn't indented in this question, and that's what Python seems to be complaining about.\n",
"Check that whitespace is consistent (i.e. mixing tabs and... | [
6,
2,
2,
2,
2
] | [] | [] | [
"block",
"indentation",
"python"
] | stackoverflow_0007791217_block_indentation_python.txt |
Q:
cython multiple return
I want to wrap this simple function:
double foo(int a, int* b)
{
double div = ((double) a) / ((double) *b);
*b = a + (*b);
return div;
}
what i'm trying to do is this:
cdef pyfoo(int c, int d):
res = foo(c, &d);
re... | cython multiple return | I want to wrap this simple function:
double foo(int a, int* b)
{
double div = ((double) a) / ((double) *b);
*b = a + (*b);
return div;
}
what i'm trying to do is this:
cdef pyfoo(int c, int d):
res = foo(c, &d);
return (res, d)
I want to r... | [
"cdef functions can't be accessed by Python code. That's why they're fast: calling functions from Python is always slow.\nThe solution is using cpdef instead, so that it's both accessible from Python and fast when called from C. Or, don't call it from Python code.\n",
"The problem seems that cdef creates a functi... | [
7,
1
] | [] | [] | [
"cython",
"python"
] | stackoverflow_0007791216_cython_python.txt |
Q:
Where does the 'self' come from? Putting a member function as target for threading.Thread
in the following code
class foo:
def __init__(self,x):
self.x = x
def do(self):
print(self.x)
foo1 = foo(1)
foo2 = foo(2)
t1=threading.Thread(target=foo1.do)
t2=threading.Thread(target=foo2.do)
t1.st... | Where does the 'self' come from? Putting a member function as target for threading.Thread | in the following code
class foo:
def __init__(self,x):
self.x = x
def do(self):
print(self.x)
foo1 = foo(1)
foo2 = foo(2)
t1=threading.Thread(target=foo1.do)
t2=threading.Thread(target=foo2.do)
t1.start()
t2.start()
I am using the member function of an instantiated object as target for the th... | [
"You might want to read about Python's method objects.\nPython's self is sort of like C++'s this, except you have to put it in the method declaration.\nWhat happens that when you declare a function inside a class, it “becomes” a method. When you get a method of an object, it becomes a bound method, which has the fi... | [
4,
2,
1,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0007791035_multithreading_python.txt |
Q:
Should I use gettext for this instead?
My product must be independent of the brand/logo and it should send a localized message. I don't need more than 2 localizations now (English and Portuguese) but I might need more later so it should be easy to add a translation if my app gets used by an e.g. russian site it sh... | Should I use gettext for this instead? | My product must be independent of the brand/logo and it should send a localized message. I don't need more than 2 localizations now (English and Portuguese) but I might need more later so it should be easy to add a translation if my app gets used by an e.g. russian site it should be able to send welcome emails in russi... | [
"Surely gettext is the best solution if you want localization (just remember to use placeholders instead of concatenating strings like you did in your example).\nRegarding white-labeling, if ALL the customer-dependent content is also localizable, then gettext will do just fine - you hit two birds with one stone, pl... | [
1
] | [] | [] | [
"gettext",
"localization",
"python"
] | stackoverflow_0007786782_gettext_localization_python.txt |
Q:
How to read a file (or stdin) line by line in Python not waiting for reading entire file
We have couple of huge files (greater than size of RAM) in disk. I want to read them line by line in python and output results in terminal. I have gone through [1] and [2], but I am looking for methods which do not wait till t... | How to read a file (or stdin) line by line in Python not waiting for reading entire file | We have couple of huge files (greater than size of RAM) in disk. I want to read them line by line in python and output results in terminal. I have gone through [1] and [2], but I am looking for methods which do not wait till the entire file is read into memory.
I would be using both of these commands:
cat fileName | py... | [
"This is the standard behavior of file objects in Python:\nwith open(\"myfile.txt\", \"r\") as myfile:\n for line in myfile:\n # do something with the current line\n\nor\nfor line in sys.stdin:\n # do something with the current line\n\n",
"Just iterate over the file:\nwith open('huge.file') as hf:\n ... | [
9,
4
] | [
"if __name__ == '__main__':\n while 1:\n try:\n a=raw_input()\n except EOFError:\n break\n print a\n\nThis will read from stdin til EOF.\nTo read a file using the second method, you can use Tim's method\ni.e.\nwith open(\"myfile.txt\", \"r\") as myfile:\n for line in... | [
-1
] | [
"filter",
"python"
] | stackoverflow_0007791559_filter_python.txt |
Q:
libboost_python.so linking error (ONIPY)
I am trying to install ONIPY on ubuntu 11.10. I am using python 2.7. After modifying (I replaced python2.6 with python2.7) the makefile and installing it I can't import the wrapper library.
ERROR:
>>> import OpenNIPythonWrapper
Traceback (most recent call last):
File "<s... | libboost_python.so linking error (ONIPY) | I am trying to install ONIPY on ubuntu 11.10. I am using python 2.7. After modifying (I replaced python2.6 with python2.7) the makefile and installing it I can't import the wrapper library.
ERROR:
>>> import OpenNIPythonWrapper
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: /usr/... | [
"I fixed it after trying some modifications on the makefile. So changes are as follows...\nBEFORE :\n$(TARGET): $(OBJ)\n $(CXX) -fPIC -shared -Wl,--export-dynamic $(LIBS) -o $@ $^ \n\nAFTER:\n$(TARGET): $(OBJ)\n $(CXX) -fPIC -shared -Wl,-soname,OpenNIPythonWrapper.so -o $@ $^ $(LIBS)\n\n"
] | [
0
] | [] | [] | [
"boost",
"kinect",
"openni",
"python",
"wrapper"
] | stackoverflow_0007774914_boost_kinect_openni_python_wrapper.txt |
Q:
Eclipse/PyDev: Open Interactive console when program starts
I find myself opening the interactive shell nearly every time I launch Eclipse. To save my lazy self a few extra clicks every day, I started wonder: is there is a way to get an interactive console to open automatically on start-up of Eclipse/PyDev?
Thanks... | Eclipse/PyDev: Open Interactive console when program starts | I find myself opening the interactive shell nearly every time I launch Eclipse. To save my lazy self a few extra clicks every day, I started wonder: is there is a way to get an interactive console to open automatically on start-up of Eclipse/PyDev?
Thanks!
| [
"Currently not... please enter a feature request for that (it should be relatively straightforward adding a preference where you can choose an interpreter which would be used to open an interactive console when you open Eclipse).\n"
] | [
0
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0007773513_eclipse_pydev_python.txt |
Q:
pydev syntax highlighting python builtins
Is there any way to make Eclipse/PyDev highlight the Python built-in functions?
For example, the Python IDLE highlights int() or list() but PyDev doesn't.
I'm using Eclipse 3.7.1 and PyDev 2.2.3.
A:
Currently that's not really possible in PyDev. Please enter a feature re... | pydev syntax highlighting python builtins | Is there any way to make Eclipse/PyDev highlight the Python built-in functions?
For example, the Python IDLE highlights int() or list() but PyDev doesn't.
I'm using Eclipse 3.7.1 and PyDev 2.2.3.
| [
"Currently that's not really possible in PyDev. Please enter a feature request for that. See: http://pydev.org/about.html for details on where to report it...\n"
] | [
1
] | [] | [] | [
"pydev",
"python",
"syntax_highlighting"
] | stackoverflow_0007770760_pydev_python_syntax_highlighting.txt |
Q:
Integrating python and c#
I've decided to try and create a game before I finish studies. Searching around the net, I decided to create the basic game logic in python (for simplicity and quicker development time), and the actual I/O engine in c# (for better performance. specifically, I'm using Mono with the SFML li... | Integrating python and c# | I've decided to try and create a game before I finish studies. Searching around the net, I decided to create the basic game logic in python (for simplicity and quicker development time), and the actual I/O engine in c# (for better performance. specifically, I'm using Mono with the SFML library).
After coming to grips ... | [
"Sincerely, I would say C# is today gives you a lot of goods from Python. To quote Jon Skeet:\n\nDo you know what I really like about dynamic languages such as Python, Ruby, and \n Groovy? They suck away fluff from your code, leaving just the essence of it—the bits \n that really do something. Tedious formality g... | [
2,
2
] | [] | [] | [
"c#",
"mono",
"python"
] | stackoverflow_0007792013_c#_mono_python.txt |
Q:
Regex in Python and save in csv
Input text file view:
64120655007 6173 0578 111 8th Avenue, 7th Floor 30319.
File consist a lot of lines
I only need the numbers from the line that do not have letters attached. How do I use regex to find only the numbers without letters attached and save the results in a new CS... | Regex in Python and save in csv | Input text file view:
64120655007 6173 0578 111 8th Avenue, 7th Floor 30319.
File consist a lot of lines
I only need the numbers from the line that do not have letters attached. How do I use regex to find only the numbers without letters attached and save the results in a new CSV?
Example results:
64120655007 6173 ... | [
"with open('the_file_name') as file:\n only_numbers = [re.findall(r'\\b\\d+\\b', line) for line in file]\n\nthen save it to another file.\n",
"Did you look at the csv library?\nimport csv\n\n",
"It looks like you can use the string split method to split your line into 'words'. Then you can use the isdigit s... | [
2,
0,
0
] | [] | [] | [
"csv",
"python",
"regex"
] | stackoverflow_0007785367_csv_python_regex.txt |
Q:
Learn Python the hard way, exercise 10.4
#Combine %r with double-quote and single-quote escapes and print them out.
#Compare %r with %s. Notice how %r prints it the way you'd write it in your file,
#but %s prints it the way you'd like to see it?
This is what I wrote for the exercise:
1) mybugs1 = "Guido said: ... | Learn Python the hard way, exercise 10.4 | #Combine %r with double-quote and single-quote escapes and print them out.
#Compare %r with %s. Notice how %r prints it the way you'd write it in your file,
#but %s prints it the way you'd like to see it?
This is what I wrote for the exercise:
1) mybugs1 = "Guido said: %r and moved on." %'I \'love\' \"my\" bugs'
2... | [
"there are several ways to write string literals in python, with single or double quotes, single-line or multiline, raw or normal. None of that is preserved in the string itself, though; once the parser parses it, no information remains about how it was presented in the source; it doesn't even need to be in the s... | [
3,
2
] | [] | [] | [
"python",
"repr"
] | stackoverflow_0007791150_python_repr.txt |
Q:
Glasslab Cluster Library
I want to install a library called Glasslab-Cluster Library (Glasslab Cluster) for python. But I found that it just provided Linux and Ubuntu install commands.
Are there any ways that I can install this library on windows?
Thank you and please help.
A:
As far as I can see in the link you... | Glasslab Cluster Library | I want to install a library called Glasslab-Cluster Library (Glasslab Cluster) for python. But I found that it just provided Linux and Ubuntu install commands.
Are there any ways that I can install this library on windows?
Thank you and please help.
| [
"As far as I can see in the link you provided, there is a \"setup.py\" file in the source package.\nSo, download the sources, unzip them in a separate folder, go to that folder and type \npython setup.py install\n\nYou will probably need the MinGW GCC compiler (free) to make this run.\nHope this helps ! (I have no... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007792086_python.txt |
Q:
Saving to ManyToManyFields using ModelForm and ModelMultipleChoiceField
I've created a basic Django app that contains books/authors/publishers as per the Django Book - trying to use a ModelForm to create a means to modify existing books - the problem is that the 'authors' field is a ManyToManyField and when I choo... | Saving to ManyToManyFields using ModelForm and ModelMultipleChoiceField | I've created a basic Django app that contains books/authors/publishers as per the Django Book - trying to use a ModelForm to create a means to modify existing books - the problem is that the 'authors' field is a ManyToManyField and when I choose a choice on the ModelForm it simply wipes the existing selection and doesn... | [
"Solution was to override the save method in the ModelForm:\ndef save(self, commit=True):\n authors =[]\n for a in self.cleaned_data['authors']:\n authors.append(Author.objects.get(first_name=t.first_name))\n\n b = super(BookForm, self).save(commit=commit)\n\n for a in authors:\n b.author... | [
2,
0
] | [] | [] | [
"django",
"manytomanyfield",
"modelform",
"python"
] | stackoverflow_0007755537_django_manytomanyfield_modelform_python.txt |
Q:
Parsing non-standard XML (CDATA tag)
When I want to parsing XML document in Python using BeautifulSoup library,
I faced some problems. The XML document that I want to parse:
<item>
<title><![CDATA[Title Sample]]></title>
<link /><![CDATA[http://banhada.kr/?cateCode=09&viewCode=S0941580]]>
<time_start>2011-10-10 0... | Parsing non-standard XML (CDATA tag) | When I want to parsing XML document in Python using BeautifulSoup library,
I faced some problems. The XML document that I want to parse:
<item>
<title><![CDATA[Title Sample]]></title>
<link /><![CDATA[http://banhada.kr/?cateCode=09&viewCode=S0941580]]>
<time_start>2011-10-10 09:00:00</time_start>
<time_end>2011-10-17 ... | [
"You don't need BeautifulStoneSoup or lxml. Python's included batteries do the job just fine, and there doesn't seem to be anything non-compliant about your XML.\n>>> content='''\\\n... <item>\n... <title><![CDATA[Title Sample]]></title>\n... <link /><![CDATA[http://banhada.kr/?cateCode=09&viewCode=S0941580]]>\n...... | [
8,
7
] | [] | [] | [
"beautifulsoup",
"python",
"xml"
] | stackoverflow_0007785831_beautifulsoup_python_xml.txt |
Q:
How to convert a C++ graph structure into a Python/Numpy graph structure?
Disclaimer: The author of this post has a limited knowledge of C++ and Python, and has sufficient knowledge of Java and Ruby.
An example from the "OpenCL Programming Guide" book uses the following OpenCL-customized graph data structure for D... | How to convert a C++ graph structure into a Python/Numpy graph structure? | Disclaimer: The author of this post has a limited knowledge of C++ and Python, and has sufficient knowledge of Java and Ruby.
An example from the "OpenCL Programming Guide" book uses the following OpenCL-customized graph data structure for Dijkstra's algorithm to run on an OpenCL device:
void generateRandomGraph(GraphD... | [
"\nEverything you wanted to know about graphs and Python: http://wiki.python.org/moin/PythonGraphApi\nSeveral authors of deprecated packages of graphs recommend this package: http://networkx.lanl.gov/index.html . It can convert a graph to and from Numpy matrix, Scipy sparse matrix, etc.\n\n"
] | [
1
] | [
"No expert on the topic, but this is some kind of adjency matrix (http://en.wikipedia.org/wiki/Adjacency_matrix). Numpy core data type is the n-dimension array so this should be quite straighforward.\n"
] | [
-1
] | [
"graph",
"numpy",
"opencl",
"pyopencl",
"python"
] | stackoverflow_0007791937_graph_numpy_opencl_pyopencl_python.txt |
Q:
Error caused while using round() function of Python. What can be the issue?
While using round(2.9239,2), it produced an output 2.99999999 rather than 2.92. In stackoverflow, I had read that the best way to deal with this is use string formatting upon the output. If that's the only way, why do we even have a round ... | Error caused while using round() function of Python. What can be the issue? | While using round(2.9239,2), it produced an output 2.99999999 rather than 2.92. In stackoverflow, I had read that the best way to deal with this is use string formatting upon the output. If that's the only way, why do we even have a round function? It is not even consistent across all the numbers. As in, some numbers i... | [
"(I think you mean it should be 2.92 and the output that you get is 2.9199999999999999.)\nThis is a classic problem with floating point arithmetic - the number 2.92 is not exactly expressible as a floating pointer number - in binary it would be an infinite sequence of digits, as ⅓ is in decimal. This is nicely exp... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0007793308_python.txt |
Q:
Why is jython slow?
Jython performance is generally critized as slow --- is there a particular reason for this? Or is this just a modern myth? And most importantly, what is the future of Jython and how aggressively is it being developed? Will the ability to script in python against the JVM ever be performant eno... | Why is jython slow? | Jython performance is generally critized as slow --- is there a particular reason for this? Or is this just a modern myth? And most importantly, what is the future of Jython and how aggressively is it being developed? Will the ability to script in python against the JVM ever be performant enough for mainstream usage?... | [
"Jython 2.5.2 was released in March and featured as part of its release notes 2.5.2 Release Notes some performance gains that it 2.5.2 runs the richards benchmark 3x faster and the pystone benchmark 20% faster than 2.5.1.\nHere is a recent benchmark of jython 2.5.2 running on jvm 7 where jython is slower than Pypy ... | [
8
] | [] | [] | [
"java",
"jython",
"performance",
"python"
] | stackoverflow_0007789796_java_jython_performance_python.txt |
Q:
Monitoring a python script on Ubuntu
I have a series of Python producers that are pulling in data from various sources. At the moment, I am starting each one manually via terminal, but I need to figure a more robust system. I'd like to create a local browser based dashboard that I can use to start / stop and monit... | Monitoring a python script on Ubuntu | I have a series of Python producers that are pulling in data from various sources. At the moment, I am starting each one manually via terminal, but I need to figure a more robust system. I'd like to create a local browser based dashboard that I can use to start / stop and monitor each of the Python processes.
So, using... | [
"Looks like you want to create Daemons with Python. Please refer to the following answer to understand how to write them in Python: How do you create a daemon in Python?\nFor the \"Monitoring\" thing you can implement something that will check if the PID written in the PID File is alive, that you can do by using ps... | [
3
] | [] | [] | [
"python",
"ubuntu"
] | stackoverflow_0007793359_python_ubuntu.txt |
Q:
Best way to earmark messages in an IMAP folder?
I am working on an application that is supposed to connect to IMAP account, read through emails and pick out emails sent by lets say "Mark", then it is supposed to respond to mark
with an automatic response such as "Got it mate" and then do the same tomorrow, with th... | Best way to earmark messages in an IMAP folder? | I am working on an application that is supposed to connect to IMAP account, read through emails and pick out emails sent by lets say "Mark", then it is supposed to respond to mark
with an automatic response such as "Got it mate" and then do the same tomorrow, with the only difference that tomorrow it should not respond... | [
"The UID is guaranteed to be unique. Store each one locally.\n"
] | [
1
] | [] | [] | [
"imap",
"python"
] | stackoverflow_0007712554_imap_python.txt |
Q:
Using xmlrpclib with cookie obtained different way
How can I use xmlrpclib in Python script to connect to xmlrpc service that requires authentication, but without using xmlrpc authentication?
To be specific:
I use Drupal 7.8, there is of course service modules, I will use it's methods like node.create..
Authenti... | Using xmlrpclib with cookie obtained different way | How can I use xmlrpclib in Python script to connect to xmlrpc service that requires authentication, but without using xmlrpc authentication?
To be specific:
I use Drupal 7.8, there is of course service modules, I will use it's methods like node.create..
Authentication to any HTTP address on this server is required by... | [
"You can modify headers of a request from xmlrpclib client. Create a custom Transport class, and in its send_host method (I think?), you can modify the header to add the cookie you recieved.\nEDIT\nCheck this\n"
] | [
1
] | [] | [] | [
"python",
"xml_rpc",
"xmlrpclib"
] | stackoverflow_0007793519_python_xml_rpc_xmlrpclib.txt |
Q:
Can't generate GtkBuilder.xml in glade
I'm trying to design some window in glade, and I want it to use in my python code using GtkBuilder
I just somehow can't generate GtkBuilder xml
When I save something in Glade I get .glade file
Can you please help me how can I generate GtkBuilder xml?
$ rpm -q glade3
glade3-3.... | Can't generate GtkBuilder.xml in glade | I'm trying to design some window in glade, and I want it to use in my python code using GtkBuilder
I just somehow can't generate GtkBuilder xml
When I save something in Glade I get .glade file
Can you please help me how can I generate GtkBuilder xml?
$ rpm -q glade3
glade3-3.10.0-2.fc15.x86_64
Thank you
| [
"I have tried the following on Ubuntu 10.04 but I guess it should work on your system as well. If you are using glade-3 when you are saving the file, select Save As... option instead of Save, you will prompted to enter the file name with file browser displayed. Here in the bottom left corner you can see selection o... | [
2,
0
] | [] | [] | [
"glade",
"gtk",
"gtkbuilder",
"python"
] | stackoverflow_0007793014_glade_gtk_gtkbuilder_python.txt |
Q:
Drawing text in PythonMagick?
How can I drawing text in PythonMagick? I need add watermark to JPG files, but I can't find any example on Python.
A:
It looks like you need to use the Image.composite() method to layer the watermark image on top of the target image:
import PythonMagick
sample = PythonMagick.Image(... | Drawing text in PythonMagick? | How can I drawing text in PythonMagick? I need add watermark to JPG files, but I can't find any example on Python.
| [
"It looks like you need to use the Image.composite() method to layer the watermark image on top of the target image:\nimport PythonMagick\n\nsample = PythonMagick.Image('sample.jpg')\nwatermark = PythonMagick.Image('watermark.jpg')\n\nsample.composite(watermark, 50, 50,\n PythonMagick.CompositeOpera... | [
0
] | [] | [] | [
"python",
"watermark"
] | stackoverflow_0007793186_python_watermark.txt |
Q:
Listening to network event and keyboard input at the same time in Python
I want to write an (GUI) application that listens both to keyboard events (client side generated events) and to a network port (server side generated events). I could use some high level advice on how to do this. Some additional info:
- I am ... | Listening to network event and keyboard input at the same time in Python | I want to write an (GUI) application that listens both to keyboard events (client side generated events) and to a network port (server side generated events). I could use some high level advice on how to do this. Some additional info:
- I am using the wxPython module for the GUI
- I could set the socket in non-blocking... | [
"wxPython does have key events. Here are the wxPython docs page on the subject: http://www.wxpython.org/docs/api/wx.KeyEvent-class.html\nwxPython doesn't wrap every single thing in wxWidgets. The developers didn't think that they needed to wrap stuff that already had great support in Python itself. Thus, see Python... | [
1,
0,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0007784969_python_wxpython.txt |
Q:
pymongo no output for query
EDIT:
I have somewhat distilled the question.
mongo_documents = mongo_collection.find({"medicalObjectId": "269"})
print "\n\n"
for this_document in mongo_documents:
print this_document
print "-------------------------"
pqr = 269
mongo_documents2 = mongo_collection.find({"medicalOb... | pymongo no output for query | EDIT:
I have somewhat distilled the question.
mongo_documents = mongo_collection.find({"medicalObjectId": "269"})
print "\n\n"
for this_document in mongo_documents:
print this_document
print "-------------------------"
pqr = 269
mongo_documents2 = mongo_collection.find({"medicalObjectId": pqr})
print "\n\n"
for t... | [
"You could use the $in operator of mongodb to fetch all the rows at once and iterate through them.\nmongo_documents = mongo_collection.find({ 'medicalObjectId' : { '$in' : result_set } } );\nfor doc in mongo_documents:\n print mongo_documents\n\nI have not tested it, comment below if it doesnt work.\nEDIT\nmongo... | [
4
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0007794323_mongodb_pymongo_python.txt |
Q:
Fastest way to extract elements from a list that not matched condition in python
I'm seeking the fastest way to extract all tuple members from a list under condition(s).
Example:
From a list of tuple (e.g. [(0,0,4),(1,0,3),(1,2,1),(4,0,0)]) I need to extract all members that have more than 3 in first tuple positi... | Fastest way to extract elements from a list that not matched condition in python | I'm seeking the fastest way to extract all tuple members from a list under condition(s).
Example:
From a list of tuple (e.g. [(0,0,4),(1,0,3),(1,2,1),(4,0,0)]) I need to extract all members that have more than 3 in first tuple position, then more than 2 in second tuple position, and then more than 1 in last tuple posi... | [
">>> l = [(0,0,4), (1,0,3), (1,2,1), (4,0,0)]\n>>> output = [t for t in l if t[0]>3 or t[1]>2 or t[2]>1]\n>>> output\n[(0, 0, 4), (1, 0, 3), (4, 0, 0)]\n\nThis is fast because t[1]>2 is only evaluated if t[0]>3 is False (same for the third condition). So in your example list, only 8 comparisons are necessary.\nYou ... | [
4,
3,
2
] | [] | [] | [
"extract",
"list",
"python"
] | stackoverflow_0007794385_extract_list_python.txt |
Q:
python uni-code server error while passing non English words
I build a customized search web page using some other search engine. like.
For client side am encode the search terms and send to the my server using
http://xxx.appspot.com/search?q=encodeUIComponent(qTerms)
At server side(appengine - python) am decodin... | python uni-code server error while passing non English words | I build a customized search web page using some other search engine. like.
For client side am encode the search terms and send to the my server using
http://xxx.appspot.com/search?q=encodeUIComponent(qTerms)
At server side(appengine - python) am decoding the text using urllib
like qTerms= urllib.unquote_plus(qTerms)
a... | [
"You need to pass quote() ASCII (str) string instead of unicode string.\nYou porbbley need to call term.encode('utf8') and pass the result to quote()\n"
] | [
2
] | [] | [] | [
"encode",
"google_app_engine",
"python",
"unicode",
"urllib"
] | stackoverflow_0007794502_encode_google_app_engine_python_unicode_urllib.txt |
Q:
pythonic tree enumerator method using generator
I'm actually using Jython and am pretty new to the Python way of doing things...
When I use javax.swing.tree.DefaultMutableTreeNode I can simply go depth/breadthFirstEnumeration()...
But if I'm doing stuff with a DOM tree (e.g. from XML) there is no such equivalent... | pythonic tree enumerator method using generator | I'm actually using Jython and am pretty new to the Python way of doing things...
When I use javax.swing.tree.DefaultMutableTreeNode I can simply go depth/breadthFirstEnumeration()...
But if I'm doing stuff with a DOM tree (e.g. from XML) there is no such equivalent... but it strikes me that there must be a very elega... | [
"AFAIK, there is no built-in implementation. A very straight-forward solution would be:\nimport collections\n\ndef depth_first_search(node, get_children, depth=0):\n yield node, depth\n for child in get_children(node):\n # In the upcoming Python 3.3, the following can be written as\n # yield fr... | [
2,
0
] | [] | [] | [
"generator",
"jython",
"python",
"recursion",
"tree"
] | stackoverflow_0007786222_generator_jython_python_recursion_tree.txt |
Q:
Passive Serial Port Monitor
I'm using pyserial to open two ports, and then write to each what I read from the other. I then have a physical com port connected to one of these ports and a virtual com port connected to the other. The virtual com port is in turn connected to a second virtual com port to which my simu... | Passive Serial Port Monitor | I'm using pyserial to open two ports, and then write to each what I read from the other. I then have a physical com port connected to one of these ports and a virtual com port connected to the other. The virtual com port is in turn connected to a second virtual com port to which my simulator connects:
Hardware device <... | [
"you cannot ignore the signals, especially if you use HW based flow-control. I assume that you at least have to link the following signals between both ports besides RX(read) and TX(write)\nCTS -> RTS\nDSR -> DTR\n\nComments about your code:\n\nYou defined a timeout, this means the IO function will block (even if i... | [
2
] | [] | [] | [
"pyserial",
"python",
"serial_port"
] | stackoverflow_0007794528_pyserial_python_serial_port.txt |
Q:
Can I add a second name to a variable
I need to convince myself that this is a bad idea. I want to assign a second name to the same variable, whose contents may change.
A='Bob'
B=A #wrong function, I want to figure out something that works here.
A='Alice'
print A
print B
I want both A and B to print 'Alice' but ... | Can I add a second name to a variable | I need to convince myself that this is a bad idea. I want to assign a second name to the same variable, whose contents may change.
A='Bob'
B=A #wrong function, I want to figure out something that works here.
A='Alice'
print A
print B
I want both A and B to print 'Alice' but instead B prints 'Bob' and A prints 'Alice'... | [
"Python strings are immutable:\n\nIn Python the string object is immutable - each time a string is\n assigned to a variable a new object is created in memory to represent\n the new value.\n\nWikipedia doc on immutability and specific Python example.\nOne simple way to get the behavior you want is to wrap a string... | [
6,
3,
2,
2
] | [] | [] | [
"namespaces",
"python"
] | stackoverflow_0007795384_namespaces_python.txt |
Q:
Python design: OOP
I'm trying to do something along these lines:
class A:
def __init__( self, x=None, y=None ):
self.x = x
self.y = y
class B( A ):
def do_something_in_Bs_context( self ):
print "In B"
class C( A ):
def do_something_in_Cs_context( self ):
print "In... | Python design: OOP | I'm trying to do something along these lines:
class A:
def __init__( self, x=None, y=None ):
self.x = x
self.y = y
class B( A ):
def do_something_in_Bs_context( self ):
print "In B"
class C( A ):
def do_something_in_Cs_context( self ):
print "In C"
a = A(1,2)
b = B.d... | [
"Here's how I understand the question: B and C are collections of functions that consume data of type A. What you want to do is group the functions logically.\nI'd suggest doing one of the following:\n\nseparate the functions into classes B and C that operate on A's -- this is a HAS-A relationship. The functions... | [
6,
1
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0007795637_inheritance_oop_python.txt |
Q:
Elegant way of grouping attributes
I want to group attributes of instances of a class, so that it would be easy to iterate through all the attributes belonging to a group. The obvious answer would be to put all these into a list or dict, but then I wouldn't be able to access them as attributes of my object, and I ... | Elegant way of grouping attributes | I want to group attributes of instances of a class, so that it would be easy to iterate through all the attributes belonging to a group. The obvious answer would be to put all these into a list or dict, but then I wouldn't be able to access them as attributes of my object, and I would prefer that.
Some code should make... | [
"How about make rotatable an attribute of a Vector class:\nclass Vector(object):\n def __init__(self,v,rotatable=False):\n self.value = v\n self.rotatable = rotatable\n\nAnd then use properties to access the values easily:\nclass Vectors(object):\n def __init__(self, v1, v2, v3):\n self.v... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0007795457_python.txt |
Q:
AssertionError in nosetests
When I start tests with
nosetests --with-doctest --doctest-extension=txt
I got this error.
F
======================================================================
FAIL: Doctest: README.txt
----------------------------------------------------------------------
Traceback (most recent ca... | AssertionError in nosetests | When I start tests with
nosetests --with-doctest --doctest-extension=txt
I got this error.
F
======================================================================
FAIL: Doctest: README.txt
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python... | [
"In the README.txt file there should be more whitespace, especially after the statements that don't return a value (like import statements).\n=============\nexample\n=============\n>>> a = 3\n>>> a - 1\n2\n>>> from sqlite3 import dbapi2 as sqlite\n\nsome text\n\nImportant is the space after import statement. Withou... | [
1
] | [] | [] | [
"nosetests",
"python"
] | stackoverflow_0007793053_nosetests_python.txt |
Q:
What is the simplest way to sort a list of strings in the following way?
I have a list of strings which can represent integers as well as names.
The default string compare does the following:
sorted(['1','2','3','4','10','102','14','Alice','John','Sally'])
['1', '10', '102', '14', '2', '3', '4', 'Alice', 'John', '... | What is the simplest way to sort a list of strings in the following way? | I have a list of strings which can represent integers as well as names.
The default string compare does the following:
sorted(['1','2','3','4','10','102','14','Alice','John','Sally'])
['1', '10', '102', '14', '2', '3', '4', 'Alice', 'John', 'Sally']
I would like to sort the list as follows:
['1', '2', '3', '4', '10', ... | [
"If there are no negative numbers:\nlyst = ['1','2','3','4','10','102','14','Alice','John','Sally']\nprint sorted(lyst, key=lambda k: int(k) if k.isdigit() else k)\n\nHere's a version that doesn't rely on CPython details and works with Python 3:\nsorted(lyst, key=lambda k: (0, int(k)) if k.isdigit() else (1, k))\n\... | [
10,
5,
5,
0
] | [] | [] | [
"integer",
"list",
"python",
"sorting",
"string"
] | stackoverflow_0007795679_integer_list_python_sorting_string.txt |
Q:
logging module adds leading spaces in console output
EDIT The blank spaces were added by an obscure statement in the code, somewhere deep in a sub-function. Once this was removed, the logging output is nice... Therefore I close the subject.
The redirection of console logging to stderrpermitted to highlight this ea... | logging module adds leading spaces in console output | EDIT The blank spaces were added by an obscure statement in the code, somewhere deep in a sub-function. Once this was removed, the logging output is nice... Therefore I close the subject.
The redirection of console logging to stderrpermitted to highlight this easily, so thanks to commenters!
I'm using Python logging m... | [
"As written above, I made two mistakes in my code. Therefore, there's nothing wrong with the logging module or the configuration I made of it.\nThe blank spaces were added by an obscure statement in the code, somewhere deep in a sub-function. Once this was removed, the logging output is nice... Therefore I close th... | [
1
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0007728659_logging_python.txt |
Q:
Python access attributes of an enclosing class (not parent)
I have a simple problem, I'm developing something for which I need to have some classes accessing some common variables like that:
somevar="foo"
class A(SomeParent):
def eval_class(self):
global somevar
return somevar
def index(request,input... | Python access attributes of an enclosing class (not parent) | I have a simple problem, I'm developing something for which I need to have some classes accessing some common variables like that:
somevar="foo"
class A(SomeParent):
def eval_class(self):
global somevar
return somevar
def index(request,input_somevar):
global somevar
somevar=input_somevar
return Http... | [
"Basically you say that different threads of your Django app have an access conflict: while one of them is reading the value of somevar, another is modifying it.\nSo you seem to be solving a wrong problem. Really you need to design your application in a way that access conflicts do not happen.\nAn ideal solution wo... | [
1,
0,
0,
0
] | [] | [] | [
"class",
"django",
"python"
] | stackoverflow_0007795393_class_django_python.txt |
Q:
How to get parent element of my element?
For example:
test = label.find('image').attrib['url']
How to get parent element of image ?
A:
You can use the getparent() method:
image_parent = label.find('image').getparent()
| How to get parent element of my element? | For example:
test = label.find('image').attrib['url']
How to get parent element of image ?
| [
"You can use the getparent() method:\nimage_parent = label.find('image').getparent()\n\n"
] | [
22
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0007796248_lxml_python.txt |
Q:
ScrolledPanel inside Panel not sizing
I've been toying with this for a while and just can't seem to figure it out.
self.panel = wx.Panel(self, wx.ID_ANY)
I have a scrolledPanel inside a panel that does not scroll.
self.panel = wx.Panel(self, wx.ID_ANY)
self.stepPanel = wxscrollpanel.ScrolledPanel(self.panel, -1, s... | ScrolledPanel inside Panel not sizing | I've been toying with this for a while and just can't seem to figure it out.
self.panel = wx.Panel(self, wx.ID_ANY)
I have a scrolledPanel inside a panel that does not scroll.
self.panel = wx.Panel(self, wx.ID_ANY)
self.stepPanel = wxscrollpanel.ScrolledPanel(self.panel, -1, style=wx.EXPAND)
self.stepPanel.SetupScrolli... | [
"I think I figured it out. As usual, when adding or deleting widgets, you need to call Layout on the parent, which in this case is the scrolled panel that is getting new children. You also have to call SetupScrolling() so it can recalculate how much space there is and whether or not it needs scrollbars. Here's an e... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0007795726_python_wxpython.txt |
Q:
Difference between bson.objectid.ObjectId and bson.ObjectId?
I have generated an ObjectId through two different methods as follows:
user@ubuntu:~$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> # Method one... | Difference between bson.objectid.ObjectId and bson.ObjectId? | I have generated an ObjectId through two different methods as follows:
user@ubuntu:~$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> # Method one
>>> from bson.objectid import ObjectId
>>> idA = ObjectId()
>>> p... | [
"In [5]: bson.ObjectId\nOut[5]: bson.objectid.ObjectId\n\nThey are exactly the same thing.\n"
] | [
4
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0007795820_mongodb_pymongo_python.txt |
Q:
Is apache killing my process?
I have a strange problem regarding lucene and apache. I am using lucene for full text search and for a search I need to call:
initVM()
I found out that after this call nothing gets executed. So this all happens for a http request handled through apache.
Now when I try to do this man... | Is apache killing my process? | I have a strange problem regarding lucene and apache. I am using lucene for full text search and for a search I need to call:
initVM()
I found out that after this call nothing gets executed. So this all happens for a http request handled through apache.
Now when I try to do this manually in the interactive command pr... | [
"Lucene is really meant to be for client applications. For a webapp use, you should really use solr which is installed in a separate web container. Hope this helps. \n"
] | [
0
] | [] | [] | [
"apache",
"lucene",
"pylucene",
"python"
] | stackoverflow_0007796596_apache_lucene_pylucene_python.txt |
Q:
python regex mediawiki section parsing
I have text similar to the following:
==Mainsection1==
Some text here
===Subsection1.1===
Other text here
==Mainsection2==
Text goes here
===Subsecttion2.1===
Other text goes here.
In the above text the MainSection 1 and 2 have different names which can be ev... | python regex mediawiki section parsing | I have text similar to the following:
==Mainsection1==
Some text here
===Subsection1.1===
Other text here
==Mainsection2==
Text goes here
===Subsecttion2.1===
Other text goes here.
In the above text the MainSection 1 and 2 have different names which can be everything the user wants. Same goes for the s... | [
"The problem here is that ==(.*)== matches ==(=Subsection=)==, so the first thing to do is to make sure there is no = inside the title : ==([^=]*)==([^=]*).\nWe then need to make sure that there is no = before the beginning of the match, otherwise, the first = of the three is ignored and the subtitle is matched. Th... | [
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007795345_python_regex.txt |
Q:
Determine if a group within a regex match is a number
If I have, for example, the below regex string:
'^/abc/(?P<some_int>\d{3})/\d{0,2}/$'
Is there an easy way to determine when a group is a number/int?
I know that it is an int, but say this needed to be processed somewhere else and it needed to be deduce... | Determine if a group within a regex match is a number | If I have, for example, the below regex string:
'^/abc/(?P<some_int>\d{3})/\d{0,2}/$'
Is there an easy way to determine when a group is a number/int?
I know that it is an int, but say this needed to be processed somewhere else and it needed to be deduced from just the match object.
| [
"m.group(WHICHEVER_YOU_WANT).isdigit()\n\n",
"You are matching it with \\d{3} so it will match only if it is a number with three digits ( including leading zeroes)\n"
] | [
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007797004_python_regex.txt |
Q:
User Authentication in Pyramid
I'm building a webapp and needed to choose between Django and Pyramid. I decided to go with Pyramid.
I understand Pyramid comes with its own authentication/authorization framework which looks nice. But I haven't seen anywhere in Pyramid where users/groups/permissions are defined. ... | User Authentication in Pyramid | I'm building a webapp and needed to choose between Django and Pyramid. I decided to go with Pyramid.
I understand Pyramid comes with its own authentication/authorization framework which looks nice. But I haven't seen anywhere in Pyramid where users/groups/permissions are defined. In Django these things come for free... | [
"Pyramid has a much more flexible authentication system. And yes, if you want something simple like Django's user/group/permission concept, then flexible might be scary.\nPyramid does not have a \"User\" object, as it makes no assumptions about how you store your data or what ORM you use, therefore there isn't some... | [
66
] | [] | [] | [
"authentication",
"pyramid",
"python"
] | stackoverflow_0007792769_authentication_pyramid_python.txt |
Q:
Get local users from Mac and Linux machines
I created a python script to a while to retrieve all the local users of windows machines on my network. I used the win32net library. I now need to do this for Mac and Linux machines. I have have been search for a while now and still have nothing but a long list of Mac an... | Get local users from Mac and Linux machines | I created a python script to a while to retrieve all the local users of windows machines on my network. I used the win32net library. I now need to do this for Mac and Linux machines. I have have been search for a while now and still have nothing but a long list of Mac and Linux user groups that meet around my house. Do... | [
"I think your best bet is to use POSIX standard interface, e.g. getent via http://pypi.python.org/pypi/getent/0.1 package\ngetent.passwd() should work pretty much analogous to getpwent system call.\nEDIT: If you are doing this remotely it probably means that you can't install python packages on the hosts, so you mi... | [
5
] | [] | [] | [
"linux",
"macos",
"network_programming",
"python"
] | stackoverflow_0007797145_linux_macos_network_programming_python.txt |
Q:
Snapping to pixels in wxpython
I am creating a simple GUI to record points which are clicked on the image, using wxpython. However, i would like the click to be snapped to certain points on the image. Please suggest methods.
A:
The easiest to snap to a fixed scale grid is with something like:
snap_x = scale * r... | Snapping to pixels in wxpython | I am creating a simple GUI to record points which are clicked on the image, using wxpython. However, i would like the click to be snapped to certain points on the image. Please suggest methods.
| [
"The easiest to snap to a fixed scale grid is with something like:\nsnap_x = scale * round(x / scale)\nsnap_y = scale * round(y / scale)\n\nwhere scale is the size of your grid, eg 10 pixels.\nIf the points are nonuniformly distributed, then find the closest based on the distance (or the square of the distance for ... | [
3,
1
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0007794496_python_user_interface_wxpython.txt |
Q:
Converting f(x) into f([x]) using decorator in python
class foo(object):
def __init__(self,f):
self.f = f
def __call__(self,args_list):
def wrapped_f(args_list):
return [self.f(*args) for args in args_list]
return wrapped_f(arg... | Converting f(x) into f([x]) using decorator in python | class foo(object):
def __init__(self,f):
self.f = f
def __call__(self,args_list):
def wrapped_f(args_list):
return [self.f(*args) for args in args_list]
return wrapped_f(args_list)
if __name__=='__main__':
class abc(object... | [
"There are two transformations performed on your original function: \n\nit is converted from a function of three arguments to a function that takes a 3-tuple\nconversion from a function of a 3-tuple to a function that takes a list of 3-tuples\n\nFirst transformation\nIn Haskell, there is a function called uncurry,... | [
4,
2,
1,
0
] | [] | [] | [
"decorator",
"functional_programming",
"lifting",
"python"
] | stackoverflow_0007785098_decorator_functional_programming_lifting_python.txt |
Q:
Why does this dictionary definition raise a syntax error?
Possible Duplicate:
Is there any reason why lVals = [1, 08, 2011] throws an exception?
I am defining a dictionary to map day numbers to their respective word. For some reason the following code raises a "SyntaxError: invalid token" and highlights "08"
day... | Why does this dictionary definition raise a syntax error? |
Possible Duplicate:
Is there any reason why lVals = [1, 08, 2011] throws an exception?
I am defining a dictionary to map day numbers to their respective word. For some reason the following code raises a "SyntaxError: invalid token" and highlights "08"
days = {01:"first", 02:"second", 03:"third", 04:"fourth", 05:"fif... | [
"The number 0 is a prefix on an integer literal indicating that it is an octal number in python.\n...which as I accidentally omitted, and as @larsmans so kindly pointed out in his comment, limits the number to containing only the numerals 0 through 7, excluding 8 and 9.\nThough, also of note, this is the syntax in ... | [
9,
1,
1
] | [] | [] | [
"dictionary",
"python",
"syntax"
] | stackoverflow_0007797569_dictionary_python_syntax.txt |
Q:
How can I set up global for every imported file in Python automatically?
I have a large python code with many modules and classes. I have a special class, whose single instance is needed everywhere throughout the code (it's a threaded application, and that instance of a class also holds Thread Local Storage, locks... | How can I set up global for every imported file in Python automatically? | I have a large python code with many modules and classes. I have a special class, whose single instance is needed everywhere throughout the code (it's a threaded application, and that instance of a class also holds Thread Local Storage, locks, etc). It's a bit uncomfortable to always "populate" that instance in every i... | [
"\nCertainly it's not fun to pass that instance to the constructors of\n every classes\n\nYou don't have to do this. Set up your global class in a module like config and import it\n# /myapp/enviroment/__init__.py\n\nclass ThatSingleInstanceClass: pass\n\n# create the singleton object directly or have a function in... | [
4,
2
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0007797429_import_module_python.txt |
Q:
Python Connect Four game
I am currently working on making a Python version of the game Connect Four. It is going to be pretty basic, using Tkinter for the interface. I think I have most of the code laid out and I'm not getting any errors, but it currently isn't creating the actual game board. Right now I only have... | Python Connect Four game | I am currently working on making a Python version of the game Connect Four. It is going to be pretty basic, using Tkinter for the interface. I think I have most of the code laid out and I'm not getting any errors, but it currently isn't creating the actual game board. Right now I only have it coded to make the first ro... | [
"Don't forget to pack the buttons into the frame:\n self.b = Button(frame,image=self.Empty,command=self.makeMove)\n self.b.pack(side=LEFT)\n\n"
] | [
4
] | [] | [] | [
"connect",
"python",
"tkinter"
] | stackoverflow_0007797602_connect_python_tkinter.txt |
Q:
Resources for learning Python after having experience in C/C++
In my present job a lot of ad-hoc text processing is required. I have been coding in C for 5+ years and have some exposure to STL of C++. I decided to try out Python, and so far the combination of google and stackoverflow is working well. But it would ... | Resources for learning Python after having experience in C/C++ | In my present job a lot of ad-hoc text processing is required. I have been coding in C for 5+ years and have some exposure to STL of C++. I decided to try out Python, and so far the combination of google and stackoverflow is working well. But it would be great if I can follow some material (lecture/book) to formally le... | [
"The Google Python Class should give you a hands on guide (don't forget to check the video tutorials and the coding exercises):\nhttp://code.google.com/edu/languages/google-python-class/\nOh, and you might want to read the books the others have posted.\nFor the text processing you should check the Regular Expressio... | [
3,
1,
1
] | [
"I don't use python myself, but I have been meaning to learn and I have been repeatedly recommended Learn Python the Hard Way. It's free in HTML but there are epub and physical copies you can order as well.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0007797633_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.