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:
Catching a value of None with "or" in an expression
I came across this in a code review:
def some_method(self, path):
path = os.path.abspath(os.path.expanduser(path or ""))
My first reaction was "ahhhh bad!" but on second thought... is it?
A:
This is a common pattern for implementing some kind of a default v... | Catching a value of None with "or" in an expression | I came across this in a code review:
def some_method(self, path):
path = os.path.abspath(os.path.expanduser(path or ""))
My first reaction was "ahhhh bad!" but on second thought... is it?
| [
"This is a common pattern for implementing some kind of a default value or fallback value if the first part of the expression evaluates to False. Consider it as best-practice - like it or not. It can also be used to turning None into an empty string.\n",
"It's a bit pointless in this example though, because calli... | [
2,
1
] | [] | [] | [
"boolean",
"python",
"short_circuiting"
] | stackoverflow_0005818670_boolean_python_short_circuiting.txt |
Q:
Displaying images in a py2exe'd PyGTK program
I have written a GUI app in Python using PyGTK and want to distribute it as an executable, for which I'm using py2exe. When I run my program, I get the following warning
GdkPixbuf-WARNING **: Cannot open pixbuf loader module file 'gtk-2.0\gdk-pixbuf.loaders': No such ... | Displaying images in a py2exe'd PyGTK program | I have written a GUI app in Python using PyGTK and want to distribute it as an executable, for which I'm using py2exe. When I run my program, I get the following warning
GdkPixbuf-WARNING **: Cannot open pixbuf loader module file 'gtk-2.0\gdk-pixbuf.loaders': No such file or directory
and my images do not display, ev... | [
"If you are using py2exe, you must pack gtk+ (etc, shared, lib) inside your project at the same level of your exe:\nSample directory structure:\nPROGRAM.exe\nLOT_OF_PYD_AND_LIB_FILES...\netc\netc\\fonts\netc\\gtk-2.0\netc\\pango\nlib\nlib\\gtk-2.0\nshare\nshare\\aclocal\nshare\\glib-2.0\nshare\\locale\nshare\\theme... | [
0,
0
] | [] | [] | [
"gtk",
"pixbuf",
"py2exe",
"pygtk",
"python"
] | stackoverflow_0004413456_gtk_pixbuf_py2exe_pygtk_python.txt |
Q:
I defined a search path, but files in otrher folders are being searched
Can someone PLEASE tell me why the below code is searching for sub folders in the specified path. I only want all .txt and .log files in c:\Python27 to be searched. But the search is showing results for .txt and .log file in c:\Python27\Doc ..... | I defined a search path, but files in otrher folders are being searched | Can someone PLEASE tell me why the below code is searching for sub folders in the specified path. I only want all .txt and .log files in c:\Python27 to be searched. But the search is showing results for .txt and .log file in c:\Python27\Doc ... so on and so forth as well. Thanks.
elif searchType =='3':
print ... | [
"os.walk is recursive directory walking - its documentation says:\n\nGenerate the file names in a directory\n tree by walking the tree either\n top-down or bottom-up.\n\nSo you get what you ask for ;-) \nIf you don't need recursion, just use os.listdir instead. Since os.walk by default walks top-down you could al... | [
5
] | [] | [] | [
"path",
"python",
"regex"
] | stackoverflow_0005819313_path_python_regex.txt |
Q:
Getting field names reflectively with Python
Is it possible to get the name of a field reflectively in Python (3.2)?
See the following example:
class Something:
def __init__(self):
self.x = 1
def validate():
return validator.max(self.x, 10)
validator.max(self.x, 10) should produce an erro... | Getting field names reflectively with Python | Is it possible to get the name of a field reflectively in Python (3.2)?
See the following example:
class Something:
def __init__(self):
self.x = 1
def validate():
return validator.max(self.x, 10)
validator.max(self.x, 10) should produce an error message containing the name of the field x as st... | [
"You would have to pass the attribute name as a string\ndef validate():\n return validator.max(self, \"x\", 10)\n\nthen validator.max might look like this\ndef max(ob, attr, max_value):\n val = getattr(ob, attr) # val would be self.x now\n ...\n\n",
"Unlikely. Things might not even have names - what i... | [
5,
2,
2
] | [] | [] | [
"python",
"reflection"
] | stackoverflow_0005818192_python_reflection.txt |
Q:
how do I write a custom encoding in python to clean up my data?
I know I've done this before at another job, but I can't remember what I did.
I have a database that is full of varchar and memo fields that were cut and pasted from Office, webpages, and who knows where else. This is starting to cause encoding error... | how do I write a custom encoding in python to clean up my data? | I know I've done this before at another job, but I can't remember what I did.
I have a database that is full of varchar and memo fields that were cut and pasted from Office, webpages, and who knows where else. This is starting to cause encoding errors for me. Since Python has a very nice "decode" function to take a b... | [
"I've expanded this with a bit more detail.\nIf you are reasonably sure of the encoding of the text in the database, you can do text.decode('cp1252') to get a Unicode string. If the guess is wrong this will likely blow up with an exception, or the decoder will 'disappear' some characters. \nCreating a decoder alo... | [
3
] | [] | [] | [
"encoding",
"python"
] | stackoverflow_0005819586_encoding_python.txt |
Q:
Completing object with its relations and avoiding unnecessary queries in sqlalchemy
I have some database structure; as most of it is irrelevant for us, i'll describe just some relevant pieces. Let's lake Item object as example:
items_table = Table("invtypes", gdata_meta,
Column("typeID", Intege... | Completing object with its relations and avoiding unnecessary queries in sqlalchemy | I have some database structure; as most of it is irrelevant for us, i'll describe just some relevant pieces. Let's lake Item object as example:
items_table = Table("invtypes", gdata_meta,
Column("typeID", Integer, primary_key = True),
Column("typeName", String, index=True),
... | [
"To force loading lazy attributes just access them. This the simplest way and it works fine for relations, but is not as efficient for Columns (you will get separate SQL query for each column in the same table). You can get a list of all unloaded properties (both relations and columns) from sqlalchemy.orm.attribute... | [
7,
4
] | [] | [] | [
"eager_loading",
"python",
"sqlalchemy"
] | stackoverflow_0005795492_eager_loading_python_sqlalchemy.txt |
Q:
django date_based object_detail issue
I'm very new to django, trying to create a basic blog as a working learning experience. I'm following a tutorial from WebMonkey but my view does not return any result when I enter a date based url.
Going to /blog/, I get the list of all my blog entries.
Going to /blog/2011/04... | django date_based object_detail issue | I'm very new to django, trying to create a basic blog as a working learning experience. I'm following a tutorial from WebMonkey but my view does not return any result when I enter a date based url.
Going to /blog/, I get the list of all my blog entries.
Going to /blog/2011/04/24/, the template spits out the static htm... | [
"Your date-based URL refers to the object_detail view rather than archive_index.\n"
] | [
0
] | [] | [] | [
"django_models",
"python"
] | stackoverflow_0005819898_django_models_python.txt |
Q:
Slicing in python similar to MATLAB
In Matlab, slice can be a vector:
a = {'a','b','c','d','e','f','g'}; % cell array
b = a([1:3,5,7]);
How can I do the same thing in python?
a = ['a','b','c','d','e','f','g']
b = [a[i] for i in [0,1,2,4,6]]
but when 1:3 becomes 1:100, this will not work. Using range(2),4,6 retur... | Slicing in python similar to MATLAB | In Matlab, slice can be a vector:
a = {'a','b','c','d','e','f','g'}; % cell array
b = a([1:3,5,7]);
How can I do the same thing in python?
a = ['a','b','c','d','e','f','g']
b = [a[i] for i in [0,1,2,4,6]]
but when 1:3 becomes 1:100, this will not work. Using range(2),4,6 returns ([0,1,2],4,6), not (0,1,2,4,6). Is the... | [
"If you want to do things that are similar to Matlab in Python, NumPy should always be your first guess. In this case, you need numpy.r_:\nfrom numpy import array, r_\na = array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])\nprint a[r_[1:3, 5, 7]]\n\n['b' 'c' 'f' 'h']\n\n",
"One way is using itertools.chain:\n>>> b ... | [
13,
5,
3
] | [] | [] | [
"list",
"matlab",
"python",
"slice"
] | stackoverflow_0005819118_list_matlab_python_slice.txt |
Q:
Multithreaded thumbnail generation in Python
I'd like to recurse a directory of images and generate thumbnails for each image. I have 12 usable cores on my machine. What's a good way to utilize them? I don't have much experience writing multithreaded applications so any simple sample code is appreciated. Than... | Multithreaded thumbnail generation in Python | I'd like to recurse a directory of images and generate thumbnails for each image. I have 12 usable cores on my machine. What's a good way to utilize them? I don't have much experience writing multithreaded applications so any simple sample code is appreciated. Thanks in advance.
| [
"Abstract\nUse processes, not threads, because Python is inefficient with CPU-intensive threads due to the GIL.\nTwo possible solutions for multiprocessing are:\nThe multiprocessing module\nThis is preferred if you're using an internal thumbnail maker (e.g., PIL). Simply write a thumbnail maker function, and launch... | [
8,
3,
1
] | [] | [] | [
"image_processing",
"multithreading",
"python"
] | stackoverflow_0005818732_image_processing_multithreading_python.txt |
Q:
Help me setup a cron job on Ubuntu
Hi :) I wanted to have a every-20 mins-notifier kind of app and decided to develop one by myself using Tomboy notes. I read up about crontab and set a job through the sudo crontab -e command.
*/20 * * * * python /home/phantom/Desktop/alarm.py 2>/home/phantom/Desktop/whatswrong.lo... | Help me setup a cron job on Ubuntu | Hi :) I wanted to have a every-20 mins-notifier kind of app and decided to develop one by myself using Tomboy notes. I read up about crontab and set a job through the sudo crontab -e command.
*/20 * * * * python /home/phantom/Desktop/alarm.py 2>/home/phantom/Desktop/whatswrong.log
And my python code would go like:
#!/u... | [
"The fundamental issue is that an running X session is required in your case, and when CRON script runs, it runs without such a session (it actually runs detached from any terminal). Dbus executable needs to be able to initialize X session (it doesn't actually need a running X).\nThere are a couple of solutions:\n\... | [
2,
0
] | [] | [] | [
"cron",
"dbus",
"python",
"ubuntu_10.10"
] | stackoverflow_0005819667_cron_dbus_python_ubuntu_10.10.txt |
Q:
Use Python Popen to benchmark a script?
I have a script (it's a hadoop pig script to b precice) from which I want to measure the execution time. I might planned to run the tests several times and take the average / median time as the execution time.
As starting the script several times by hand might get quite cumb... | Use Python Popen to benchmark a script? | I have a script (it's a hadoop pig script to b precice) from which I want to measure the execution time. I might planned to run the tests several times and take the average / median time as the execution time.
As starting the script several times by hand might get quite cumbersome, I wanted to write a script for runnin... | [
"I'd also just use the time utility:\ntime python foo.py\n\nYou can then make a bash script to run this multiple times, recording the time taken for each run. Then, just average them with a shell utility or a Python script.\n"
] | [
2
] | [] | [] | [
"benchmarking",
"popen",
"process",
"python"
] | stackoverflow_0005820141_benchmarking_popen_process_python.txt |
Q:
More elegant way for updating a slice of a list
Given a list, I would like to apply some set of operations to a subset(slice) of the list, and store the result of each transformation in the original list.
My background is in Ada, which led me to make the following mistake:
Number_List = [0,1,2,3,4,5,6,7,8,9]
for... | More elegant way for updating a slice of a list | Given a list, I would like to apply some set of operations to a subset(slice) of the list, and store the result of each transformation in the original list.
My background is in Ada, which led me to make the following mistake:
Number_List = [0,1,2,3,4,5,6,7,8,9]
for Index, Number in enumerate(Number_List[1:]):
Numbe... | [
"enumerate takes a start parameter:\nNumber_List = [0,1,2,3,4,5,6,7,8,9]\nfor Index, Number in enumerate(Number_List[1:], start=1):\n Number_List[Index] = Number + 1\n\nYou can also write\nNumber_List[1:] = [x+1 for x in Number_List[1:]]\n\n",
"from itertools import islice\nnumber_list[start:stop] = (x + 1 for x... | [
8,
1,
1
] | [] | [] | [
"iteration",
"list",
"python"
] | stackoverflow_0005820392_iteration_list_python.txt |
Q:
Python / IDLE CPU usage for no reason
Here is a strange problem I have with IDLE (version 2.6.5 with the same Python version) on windows.
I try to run the following three commands:
fid= open('file.txt', 'r')
lines=fid.readlines()
print lines
When the print lines command is executed, the pythonw.exe process is goi... | Python / IDLE CPU usage for no reason | Here is a strange problem I have with IDLE (version 2.6.5 with the same Python version) on windows.
I try to run the following three commands:
fid= open('file.txt', 'r')
lines=fid.readlines()
print lines
When the print lines command is executed, the pythonw.exe process is going CPU crazy, consuming 100% of CPU and the... | [
"Try reading it line by line:\nfid = open('file.txt', 'r')\n\nfor line in fid:\n print line\n\nFrom the documentation on Input Output, there seem to be two ways to read files:\nprint f.read() # This reads the *whole* file. Might be bad to do this for large files.\n\nfor l in f: # This reads it line by line\n p... | [
2
] | [] | [] | [
"cpu_usage",
"python",
"python_idle"
] | stackoverflow_0005820622_cpu_usage_python_python_idle.txt |
Q:
Reading images and approximating and recreating each pixel with closest colours?
http://pastebin.com/v0B3Vje2
I'm looking for a way to get pixels from an image, then find the closest color to that in another program(I can compile it into the source of the "Another program"; perfect if compatible without source inj... | Reading images and approximating and recreating each pixel with closest colours? | http://pastebin.com/v0B3Vje2
I'm looking for a way to get pixels from an image, then find the closest color to that in another program(I can compile it into the source of the "Another program"; perfect if compatible without source injection) and then use that color and put it to a correct pixel. Basically, Script/Code/... | [
"You can use the Python Imaging Library to load an image and extract the pixel color values:\nimport Image\n\nimg = Image.open('random.png')\nwidth, height = img.size\npixels = img.getdata()\nprint 'pixels:'\nfor i, px in enumerate(img.getdata()):\n\n # decide whether to replace this pixel\n\n # call out to e... | [
1,
1
] | [] | [] | [
"approximation",
"c++",
"cgi",
"pixels",
"python"
] | stackoverflow_0005819087_approximation_c++_cgi_pixels_python.txt |
Q:
In Python, what's the best way to avoid using the same name for a __init__ argument and an instance variable?
Whats the best way to initialize instance variables in an init function. Is it poor style to use the same name twice?
class Complex:
def __init__(self, real, imag):
self.real = real
... | In Python, what's the best way to avoid using the same name for a __init__ argument and an instance variable? | Whats the best way to initialize instance variables in an init function. Is it poor style to use the same name twice?
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
It looks sloppy to me to come up with arbitrary alternative names like this:
class Complex:
... | [
"It is perhaps subjective, but I wouldn't consider it poor style to use the same name twice. Since self is not implicit in Python, self.real and real are totally distinct and there is no danger of name hiding etc. as you'd experience in other languages (i.e. C++/Java, where naming parameters like members is somewha... | [
13,
4
] | [] | [] | [
"coding_style",
"naming_conventions",
"python"
] | stackoverflow_0005821387_coding_style_naming_conventions_python.txt |
Q:
How to view crawled unicoded arabic string?
I have crawled some webpages using Python. I ripped off the html tags and only stored some content of those pages as repr(s). Most of those pages are not in English. Now how can I view the crawled content in its original language?
For example, the crawler wrote only one ... | How to view crawled unicoded arabic string? | I have crawled some webpages using Python. I ripped off the html tags and only stored some content of those pages as repr(s). Most of those pages are not in English. Now how can I view the crawled content in its original language?
For example, the crawler wrote only one line of some Arabic text to a txt file:
u'\u0639\... | [
">>> x= u'\\u0639\\u0644\\u0649'\n>>> open('x.html','w').write(x.encode('ascii','xmlcharrefreplace'))\n\nOpen x.html in a browser and it should display properly. Actual content:\nعلى\n\n",
"You don't get human-readable code because you've used repr(s) to write the string to file - and that's wh... | [
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"unicode",
"web_crawler"
] | stackoverflow_0005814324_python_unicode_web_crawler.txt |
Q:
setup.py imports not working correctly
I'm trying to install a simple python library I created and think I may be missing a step. The setup goes fine (or runs at least) but when I import it doesn't work as I expect.
The directory structure looks like
Foo/
setup.py
README.txt
LICENSE.txt
foo/
__ini... | setup.py imports not working correctly | I'm trying to install a simple python library I created and think I may be missing a step. The setup goes fine (or runs at least) but when I import it doesn't work as I expect.
The directory structure looks like
Foo/
setup.py
README.txt
LICENSE.txt
foo/
__init__.py
bar.py
I can do
>>> import fo... | [
"Your foo is a package, and packages don't automatically import modules. You have to do explicitly. That's just how Python works. You can also do import foo.bar and reference foo.bar then.\n",
"Your setup.py appears fine. How are you installing your package? For example:\n% cd Foo\n% python setup.py install --r... | [
1,
1,
1
] | [] | [] | [
"import",
"python",
"setup.py"
] | stackoverflow_0005821662_import_python_setup.py.txt |
Q:
Finding a substring inside of a string and its slice?
I've been trying to help my friend with his assignment and I can't even figure out where to start. I can get it to identify the substring inside of the string but giving where it starts is troubling me. I've been at it for hours. Any help is welcome. Here is ... | Finding a substring inside of a string and its slice? | I've been trying to help my friend with his assignment and I can't even figure out where to start. I can get it to identify the substring inside of the string but giving where it starts is troubling me. I've been at it for hours. Any help is welcome. Here is everything I have about the assignment below.
PS. his enti... | [
"stringA = \"the car is in that carport\"\nstringB = \"the\"\n\nexact = []\nreverse = []\nalmost = []\n\nlenA = len(stringA)\nlenB = len(stringB)\nlimit = lenA - lenB\nreversedB = stringB[::-1]\n\npos = stringA.find(stringB)\nwhile pos >= 0:\n exact.append(pos)\n pos = stringA.find(stringB, pos + 1)\n\npos = ... | [
1,
0,
0
] | [] | [] | [
"indexing",
"python",
"string",
"substring"
] | stackoverflow_0005813260_indexing_python_string_substring.txt |
Q:
object inheritance and nested cmd
This is probably a basic OO question:
I'm trying to do a nested console menu with cmd which has gone well.
I also want all my sub-consoles to have access to the same objects. This has not gone well.
My simple Example:
import cmd
class MainConsole(cmd.Cmd):
def __init__(self,ob... | object inheritance and nested cmd | This is probably a basic OO question:
I'm trying to do a nested console menu with cmd which has gone well.
I also want all my sub-consoles to have access to the same objects. This has not gone well.
My simple Example:
import cmd
class MainConsole(cmd.Cmd):
def __init__(self,obj1,obj2):
cmd.Cmd.__init__(self... | [
"EDIT Okay, I misunderstood what you're doing.\nYou are right, SubConsole1 and 2 do not need to inherit from MainConsole. But they should have a reference to the main console.\nSomething like:\nclass MainConsole(cmd.Cmd):\n def __init__(self):\n cmd.Cmd.__init__(self, obj1, obj2)\n self.obj1 = obj2\n... | [
5,
2,
2
] | [] | [] | [
"cmd",
"inheritance",
"oop",
"python"
] | stackoverflow_0005822164_cmd_inheritance_oop_python.txt |
Q:
Matplotlib histogram, frequency as thousands
I have a histogram I'm drawing in matplotlib with some 260,000 values or so.
The problem is that the frequency axis (y axis) on the histogram reaches high numbers such as 100,000... What I'd really like is to have the y labels as thousands, so instead of, for instance:
... | Matplotlib histogram, frequency as thousands | I have a histogram I'm drawing in matplotlib with some 260,000 values or so.
The problem is that the frequency axis (y axis) on the histogram reaches high numbers such as 100,000... What I'd really like is to have the y labels as thousands, so instead of, for instance:
100000
75000
50000
25000
0
To have this:
100
75... | [
"Use matplotlib.ticker.FuncFormatter:\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport numpy as np\n\nmu, sigma = 100, 15\nx = mu + sigma * np.random.randn(1000000)\n\nfig, ax = plt.subplots()\nn, bins, patches = ax.hist(x, 50, facecolor='green', alpha=0.75)\n\nax.yaxis.set_major_formatt... | [
15,
0
] | [] | [] | [
"graph",
"histogram",
"matplotlib",
"python"
] | stackoverflow_0005821895_graph_histogram_matplotlib_python.txt |
Q:
The right way to do a Python IRC bot?
So I'm starting to write a simple procedural Python IRC bot from scratch (i.e. raw sockets) and I'm trying to work out the best way of designing it.
Usually I have a big ol' while() loop that'll sit there and push data received from the socket into a buffer and I'll use a mass... | The right way to do a Python IRC bot? | So I'm starting to write a simple procedural Python IRC bot from scratch (i.e. raw sockets) and I'm trying to work out the best way of designing it.
Usually I have a big ol' while() loop that'll sit there and push data received from the socket into a buffer and I'll use a massive if/else statement to scan through the s... | [
"def incoming_ping():\n pass\n\nregexes = {\"^PING: (.+)\": incoming_ping,\n \"more regex\": \"more meanings\"}\n\nInstead of strings, use references to functions.\nps. If you're \"serious\" about the IRC bot thing, you might want to have a look at Twisted.\n",
"Write a generic IRC protocol parser, w... | [
2,
2
] | [] | [] | [
"irc",
"parsing",
"python",
"regex",
"sockets"
] | stackoverflow_0005822447_irc_parsing_python_regex_sockets.txt |
Q:
Passing parameters to a CGI program using the URL (python)
As the title suggests, I'm trying to pass parameters into my cgi script so that when you type in (for example): www.helloworld.com/cgi-bin/world.py?post=101, the script will display that post
I've tried the following:
link = '<a href="world.py?post=%s">tes... | Passing parameters to a CGI program using the URL (python) | As the title suggests, I'm trying to pass parameters into my cgi script so that when you type in (for example): www.helloworld.com/cgi-bin/world.py?post=101, the script will display that post
I've tried the following:
link = '<a href="world.py?post=%s">test</a>' % postNumber
link = cgi.FieldStorage()
id = link.getvalu... | [
"How about:\nid = link[\"post\"].value\nprint id\n\n"
] | [
6
] | [] | [] | [
"cgi",
"html",
"python"
] | stackoverflow_0005822280_cgi_html_python.txt |
Q:
selenium test not selecting inner frame
I have a selenium test that I am trying to get up and running but one problem is that it has to select a frame and is failing at it.
the html looks like this
<iframe src="#" name="mainframe" id="mainframe" />
and the python test uses the command
sel.select_frame("mainframe"... | selenium test not selecting inner frame | I have a selenium test that I am trying to get up and running but one problem is that it has to select a frame and is failing at it.
the html looks like this
<iframe src="#" name="mainframe" id="mainframe" />
and the python test uses the command
sel.select_frame("mainframe")
and when I run the test I get an output li... | [
"Try using the CSS identifier of the iframe...\nsel.select_frame(\"css=iframe[id=mainframe]\")\n\n",
"Thanks for the input I did not verify that the above solution works but the problem was related to the script executing a function before it had logged into the application\n"
] | [
2,
0
] | [] | [] | [
"iframe",
"python",
"selenium",
"selenium_rc"
] | stackoverflow_0005809290_iframe_python_selenium_selenium_rc.txt |
Q:
Python regular expression to get filename in a long path
I need to analysis some log file and it look like below, I would like to retrieve 3 parts of data,
Time
part of directory, in this case, it would be ABC and DEF in input file.
file name in input file, i.e. 2C.013000000B.dat, 20100722B.TXT, 20100722D1-XYZ.T... | Python regular expression to get filename in a long path | I need to analysis some log file and it look like below, I would like to retrieve 3 parts of data,
Time
part of directory, in this case, it would be ABC and DEF in input file.
file name in input file, i.e. 2C.013000000B.dat, 20100722B.TXT, 20100722D1-XYZ.TXT and 2C.250B in this case.
I use this regular expression, b... | [
"Regular expressions are very good at solving problems like this one - i.e. parsing log file records. MarcoS's answer solves your immediate problem nicely. However, another approach is to write a (reusable) generalized function which decomposes a log file record into its various components and returns a match objec... | [
3,
2,
1,
1,
1,
0
] | [] | [] | [
"file",
"python",
"regex"
] | stackoverflow_0005820779_file_python_regex.txt |
Q:
How can I convert an ndarray to a matrix in scipy?
How can I convert an ndarray to a matrix in numpy? I'm trying to import data from a csv and turn it into a matrix.
from numpy import array, matrix, recfromcsv
my_vars = ['docid','coderid','answer1','answer2']
toy_data = matrix( array( recfromcsv('toy_data.csv', n... | How can I convert an ndarray to a matrix in scipy? | How can I convert an ndarray to a matrix in numpy? I'm trying to import data from a csv and turn it into a matrix.
from numpy import array, matrix, recfromcsv
my_vars = ['docid','coderid','answer1','answer2']
toy_data = matrix( array( recfromcsv('toy_data.csv', names=True)[my_vars] ) )
print toy_data
print toy_data.sh... | [
"If the ultimate goal is to make a matrix, there's no need to create a recarray with named columns. You could use np.loadtxt to load the csv into an ndarray, then use np.asmatrix to convert it to a matrix:\nimport numpy as np\ntoy_data = np.asmatrix(np.loadtxt('toy_data.csv',delimiter=','skiprows=1))\nprint toy_dat... | [
5,
0
] | [] | [] | [
"arrays",
"matrix",
"numpy",
"python"
] | stackoverflow_0005822452_arrays_matrix_numpy_python.txt |
Q:
grouping list of objects according to a certain characteristic
I have a list of objects (strings in this example) which I want to categorize according to a certain characteristic returned by a function.
For example, consider the following list:
['sky', 'ocean', 'grass', 'tomato', 'leaf']
and a function color(item... | grouping list of objects according to a certain characteristic | I have a list of objects (strings in this example) which I want to categorize according to a certain characteristic returned by a function.
For example, consider the following list:
['sky', 'ocean', 'grass', 'tomato', 'leaf']
and a function color(item) which returns the color of the string passed to it, e.g. color('sk... | [
"I think I'd go about this question this way:\nfrom collections import defaultdict\n\nD = defaultdict(list)\n\na = ['sky', 'ocean', 'grass', 'tomato', 'leaf']\n\nfor item in a:\n D[color(item)].append(item)\n\nThat gives you a dictionary of lists, keyed by colors, that contains items for that category.\n",
"a = ... | [
5,
0,
0
] | [] | [] | [
"dictionary",
"list",
"list_comprehension",
"python"
] | stackoverflow_0005821714_dictionary_list_list_comprehension_python.txt |
Q:
Browsers cookie problem
Well,
Opera and Chrome add 2 hours to expiration where i only want 15 minutes to be added. Actually they are both successful at that 15 minutes part but because of some reasons i didn't understand yet, they also add another 2 hours to date.
Here is response header:
Content-Type:text/html
D... | Browsers cookie problem | Well,
Opera and Chrome add 2 hours to expiration where i only want 15 minutes to be added. Actually they are both successful at that 15 minutes part but because of some reasons i didn't understand yet, they also add another 2 hours to date.
Here is response header:
Content-Type:text/html
Date:Thu, 28 Apr 2011 15:59:27... | [
"As you are not posting the related code to your question it is impossible to say what is causing the issue.\nBut my nose tells me you are probably mixing timezones in your time delta code.\nHere is some info when dealing with timezone aware time and datetime objects in Python:\nhttp://blog.mfabrik.com/2008/06/30/r... | [
0
] | [] | [] | [
"browser",
"cookies",
"python"
] | stackoverflow_0005819957_browser_cookies_python.txt |
Q:
How to specify a maximum image size with get_serving_url
Some pictures, not all, exceed the maximum width and height that I want.
Is there a way to specify the max image size with get_serving_url()?
A:
Yes, size is an optional 2nd argument on get_serving_url. You can specify an integer between 0 and 1600; if eit... | How to specify a maximum image size with get_serving_url | Some pictures, not all, exceed the maximum width and height that I want.
Is there a way to specify the max image size with get_serving_url()?
| [
"Yes, size is an optional 2nd argument on get_serving_url. You can specify an integer between 0 and 1600; if either the height or width exceed this, the image is resized down to fit.\nhttp://code.google.com/appengine/docs/python/images/functions.html\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005822043_google_app_engine_python.txt |
Q:
TypeError: 'int' object is not iterable. Why am i getting this error? please help
def get_top_k(frequency, k):
temp = frequency
key = ""
tvalues = []
values = []
kk = int(k)
i = 0
for i in temp.keys():
key = i
num = [int(frequency[key])]
tvalues += num
tvalue... | TypeError: 'int' object is not iterable. Why am i getting this error? please help | def get_top_k(frequency, k):
temp = frequency
key = ""
tvalues = []
values = []
kk = int(k)
i = 0
for i in temp.keys():
key = i
num = [int(frequency[key])]
tvalues += num
tvalues = bubble_sort(tvalues)
i = 0
for i in kk:
num = [int(tvalues[i])]
... | [
"Perhaps you meant \nfor i in range(kk):\n\n",
"a bit off topic, but:\nfor i in temp.keys():\n key = i\n num = [int(frequency[key])]\n tvalues += num\n\nshould just be:\n\ntvalues = temp.values()\n\nexample:\n>>> D = {'a':1, 'b':2, 'c':3, 'd':4}\n>>> D.keys()\n['a', 'c', 'b', 'd']\n>>> D.values()\n[1, 3,... | [
6,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005822904_python.txt |
Q:
App Engine - Difficulty Accessing Twitter Data - Flask
I'm having problems getting data from the Twitter search API with Google App Engine. Working in the personal development environment I have no problems. I'm able to get the JSON I want. However, once the code gets deployed to App Engine, I encounter a HTTP 500... | App Engine - Difficulty Accessing Twitter Data - Flask | I'm having problems getting data from the Twitter search API with Google App Engine. Working in the personal development environment I have no problems. I'm able to get the JSON I want. However, once the code gets deployed to App Engine, I encounter a HTTP 500 Error Code.
The only ideas I have for whats going on is th... | [
"As Calvin indicated, all App Engine apps source outbound HTTP requests from the same pool of IPs, so the issue is almost certainly rate limiting:\nFrom http://dev.twitter.com/pages/rate-limiting:\n\nHowever,\n all requests coming from an IP address\n are applied to a Search Rate Limit.\n The Search Rate Limit i... | [
1
] | [] | [] | [
"flask",
"google_app_engine",
"python",
"twitter"
] | stackoverflow_0005819265_flask_google_app_engine_python_twitter.txt |
Q:
Python ssh client over socks (proxy)
So, I need to connect to SSH server through proxy socks.
I read paramiko and twisted.conch docs, but didn`t found proxy socks support there.
A:
This socket-wrapper allows you to use static ssh-tunnels. I found a common solution for my problem:
Use paramiko SSHClient class
Ex... | Python ssh client over socks (proxy) | So, I need to connect to SSH server through proxy socks.
I read paramiko and twisted.conch docs, but didn`t found proxy socks support there.
| [
"This socket-wrapper allows you to use static ssh-tunnels. I found a common solution for my problem:\n\nUse paramiko SSHClient class\nExtend SSHClient with your own class\nRe-implement the connect() method: \nInstead of using a standard socket object we pass to it a fixed proxied socket from the python package sock... | [
4,
2
] | [] | [] | [
"paramiko",
"python",
"socks",
"ssh",
"twisted"
] | stackoverflow_0005816070_paramiko_python_socks_ssh_twisted.txt |
Q:
Python: Does key exist in dictionary (Python 3.1)
arguments=dict()
if (arg.find("--help") == 0):
arguments["help"] = 1
if help in arguments:
#this doesnt work
print(arguments["help"]) # This will print 1
Cannot find out if a certain key has been defined. .has_key has been deprecated in 2.7 and I haven't find... | Python: Does key exist in dictionary (Python 3.1) | arguments=dict()
if (arg.find("--help") == 0):
arguments["help"] = 1
if help in arguments:
#this doesnt work
print(arguments["help"]) # This will print 1
Cannot find out if a certain key has been defined. .has_key has been deprecated in 2.7 and I haven't find other solution than this. What am I doing wrong?
| [
"Just do \"help\" in arguments.\n>>> arguments = dict()\n>>> arguments[\"help\"]=1\n>>> \"help\" in arguments\nTrue\n\nIn your example you have written help in arguments without quotes around the string. Hence it assumes to ask whether the built-in function help is a key in your dictionary.\nAlso notice that you ca... | [
8,
3
] | [] | [] | [
"dictionary",
"key_value",
"python"
] | stackoverflow_0005823396_dictionary_key_value_python.txt |
Q:
How to display line count where regex match was found
I've seen several examples of how to display a line count, and have tried to implement those into my code, but was unsuccessful. I am a Python newbie, so I guess I have more to learn. Can someone show me how I would display the line count of the match found in ... | How to display line count where regex match was found | I've seen several examples of how to display a line count, and have tried to implement those into my code, but was unsuccessful. I am a Python newbie, so I guess I have more to learn. Can someone show me how I would display the line count of the match found in a file, thanks?
elif searchType =='3':
print "Directo... | [
"Well, I'm assuming you want to output the line number as well. For that, you'd do:\n regex = re.compile(r'(?:3\\d){6}')\n for root,dirname, files in os.walk(directory):\n for file in files:\n if file.endswith(\".log\") or file.endswith(\".txt\"):\n f=open(os.path.join(root,file))\n fo... | [
4,
2
] | [] | [] | [
"count",
"python",
"regex"
] | stackoverflow_0005823392_count_python_regex.txt |
Q:
Creating a GUI for Python scripts
I use a python script record.py to record certain events.
The command work in this way:
python record.py <scriptname>
It stores the the script in local disk. Later you can replay the recorded script by simply saying:
python scriptname.py
All these actions (described above wor... | Creating a GUI for Python scripts | I use a python script record.py to record certain events.
The command work in this way:
python record.py <scriptname>
It stores the the script in local disk. Later you can replay the recorded script by simply saying:
python scriptname.py
All these actions (described above work correctly) but are done through comma... | [
"Daniel,\nI suggest wxPython as well. \nIf you decide to go with wxPython, here is a broad outline of how you would make the tabs work. It requires you to fill in some blanks, but once you grasp the basics of wxPython, this will show you how to build a \"Notebook\" with tabs.\nWhat you would basically do would be t... | [
4,
3
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0005823021_python_user_interface.txt |
Q:
Python function slows down with presence of large list
I was testing the speeds of a few different ways to do complex iterations over some of my data, and I found something weird. It seems that having a large list local to some function slows down that function considerably, even if it is not touching that list. F... | Python function slows down with presence of large list | I was testing the speeds of a few different ways to do complex iterations over some of my data, and I found something weird. It seems that having a large list local to some function slows down that function considerably, even if it is not touching that list. For example, creating 2 independent lists via 2 instances of ... | [
"When you create that many new objects (3 million tuples), the garbage collector gets bogged down. If you turn off garbage collection with gc.disable(), the issue goes away (and the program runs 4x faster to boot).\n",
"It's impossible to say without more detailed instrumentation.\nAs a very, very preliminary ste... | [
12,
2,
2,
0
] | [] | [] | [
"allocation",
"memory",
"performance",
"python"
] | stackoverflow_0005823465_allocation_memory_performance_python.txt |
Q:
Foreign language Chatterbot web app
My goal is to write some sort of chatterbot that speaks in spanish. I've seen examples for simple python chatterbots, but their answers are mostly just random. I want the bot to partially understand the question and formulate a response to it, like http://cleverbot.com does. I'm... | Foreign language Chatterbot web app | My goal is to write some sort of chatterbot that speaks in spanish. I've seen examples for simple python chatterbots, but their answers are mostly just random. I want the bot to partially understand the question and formulate a response to it, like http://cleverbot.com does. I'm guessing I would want to use python for ... | [
"For a starting place, I'd take a look at the Natural Language Toolkit: http://www.nltk.org/.\n",
"Spanish chatterbots are listed on:\nhttp://www.chatbots.org/language/spanish/\nThere is a forum for beginners 'New to chatbot programming'\nhttp://www.chatbots.org/ai_zone/viewforum/35/\nAnd a document with the very... | [
1,
0
] | [] | [] | [
"artificial_intelligence",
"chatbot",
"python",
"web_applications"
] | stackoverflow_0005811925_artificial_intelligence_chatbot_python_web_applications.txt |
Q:
Differing decryption output for same keys in python RSA
I'm working on writing a little implementation of RSA to help me study for a class at college and I've come across a bug that I can't fix.
Here's the code I have so far:
import numpy
def primesfrom2to(n):
""" Input n>=6, Returns a array of primes, 2 <= p... | Differing decryption output for same keys in python RSA | I'm working on writing a little implementation of RSA to help me study for a class at college and I've come across a bug that I can't fix.
Here's the code I have so far:
import numpy
def primesfrom2to(n):
""" Input n>=6, Returns a array of primes, 2 <= p < n
Taken from: http://stackoverflow.com/questions/... | [
"Your pick_e function is apparently returning a numpy.int64 instead of an int; if you replace the return statement with\nreturn int(e)\n\nyour code works as expected (at least for me :-) )\n"
] | [
1
] | [] | [] | [
"python",
"rsa"
] | stackoverflow_0005823677_python_rsa.txt |
Q:
Matching nonempty lines with pyparsing
I am trying to make a small application which uses pyparsing to extract data from files produced by another program.
These files have following format.
SOME_KEYWORD:
line 1
line 2
line 3
line 4
ANOTHER_KEYWORD:
line a
line b
line c
How can i construct grammar which will hel... | Matching nonempty lines with pyparsing | I am trying to make a small application which uses pyparsing to extract data from files produced by another program.
These files have following format.
SOME_KEYWORD:
line 1
line 2
line 3
line 4
ANOTHER_KEYWORD:
line a
line b
line c
How can i construct grammar which will help to extract line 1, line 2 ... line 4 and l... | [
"My take on it:\n from pyparsing import *\n\n # matches and removes end of line\n EOL = LineEnd().suppress()\n\n # line starts, anything follows until EOL, fails on blank lines,\n line = LineStart() + SkipTo(LineEnd(), failOn=LineStart()+LineEnd()) + EOL\n\n lines = OneOrMore(line)\n\n # Group ... | [
7,
3
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0005822709_pyparsing_python.txt |
Q:
What is the best way to do text formatting to a document in Python
I'm trying to format a semi-elaborate, logical, and very readable text document. I'm using the cmd module to parse text (search and match) in a file. The cmd module makes use of different functions (all that have the structure: def do_name(self, li... | What is the best way to do text formatting to a document in Python | I'm trying to format a semi-elaborate, logical, and very readable text document. I'm using the cmd module to parse text (search and match) in a file. The cmd module makes use of different functions (all that have the structure: def do_name(self, line):). I'm trying to understand how I can A) print a title and columns t... | [
"Would formatting with Restructured Text and printing via rst2pdf help?\n",
"Reading the files\npyparsing is a useful parsing library for structured text in python, I have successfully used it a great deal in the past.\ninteresting but maybe not 100% applicable is\nHachoir is an interesting file parsing library, ... | [
2,
2
] | [] | [] | [
"document",
"python"
] | stackoverflow_0005824187_document_python.txt |
Q:
Python sum trouble
I have next problem:
x=[['1', '7', 'U1'], ['1.5', '8', 'U1']]
y=sum(sum(float(el) for el in els[:-1]) for els in x)
print(x)
print(y)
In this code sum, sum all numbers, but I want to sum from first ['1', '7', 'U1'], first number, and from second ['1.5', '8', 'U1'] first number, and same for ... | Python sum trouble | I have next problem:
x=[['1', '7', 'U1'], ['1.5', '8', 'U1']]
y=sum(sum(float(el) for el in els[:-1]) for els in x)
print(x)
print(y)
In this code sum, sum all numbers, but I want to sum from first ['1', '7', 'U1'], first number, and from second ['1.5', '8', 'U1'] first number, and same for second...
so final resu... | [
">>> x=[['1', '7', 'U1'], ['1.5', '8', 'U1']]\n>>> zip(*x)\n[('1', '1.5'), ('7', '8'), ('U1', 'U1')]\n>>> [[sum(float(n) for n in nums)] for nums in zip(*x)[:-1]]\n[[2.5], [15.0]]\n\nzip(*x) is a simple way to transpose the matrix (switch rows <--> columns), and this allows you to easily sum each row.\n"
] | [
8
] | [] | [] | [
"matrix",
"python"
] | stackoverflow_0005824692_matrix_python.txt |
Q:
How can I search within a document for a keyword and then subsequent key words within a set number of lines of the original keyword in Python?
I want to search for a key word in a document and then check to see whether that keyword is within 5 lines of another key word. If it is, I want to print the line and the ... | How can I search within a document for a keyword and then subsequent key words within a set number of lines of the original keyword in Python? | I want to search for a key word in a document and then check to see whether that keyword is within 5 lines of another key word. If it is, I want to print the line and the following 50 lines.
In this example, I am searching a document for the word "carrying" and I want to make sure that the word "carrying" is within 5 ... | [
"Instead of\n\"Financial Assets:\" in searchlines[m-5:m+5]\n\nYou need to have:\nany(\"Financial Assets:\" in line2 for line2 in searchlines[m-5:m+5])\n\nYour original code looks for a line which contains exactly the content \"Financial Assets:\", instead of looking for it as a substring in each line.\n",
"The ex... | [
2,
0
] | [] | [] | [
"python",
"search"
] | stackoverflow_0005825055_python_search.txt |
Q:
How can a flex mxml file being run on server as swf/html file be made non cachable?
I have a application developed in flex deployed on server. In the application data is filled by user and saved in cookies so as to be available even when the user closes the application. However if new version of application is rel... | How can a flex mxml file being run on server as swf/html file be made non cachable? | I have a application developed in flex deployed on server. In the application data is filled by user and saved in cookies so as to be available even when the user closes the application. However if new version of application is released the user can still access the older version saved in the cahe. How can it be assure... | [
"Easy enough, you just need a unique query string at the end of the swf file:\n<object width=\"550\" height=\"400\">\n<param name=\"movie\" value=\"somefilename.swf?key=<ADD RANDOM NUMBER HERE>\">\n<embed src=\"somefilename.swf?key=<ADD RANDOM NUMBER HERE>\" width=\"550\" height=\"400\">\n</embed>\n</object>\n\nHow... | [
1,
0
] | [] | [] | [
"apache_flex",
"html",
"python"
] | stackoverflow_0005820970_apache_flex_html_python.txt |
Q:
Python array multiply
hh=[[82.5], [168.5]]
N=1./5
ll=N*hh
What I'm doing wrong? I received error :
"can't multiply sequence by non-int of
type 'float'"
I try to add float(), but this is not solve my problem;
I need to multiply each element in array...
thanks to all
**Ok thanks for idea for number * array, bu... | Python array multiply | hh=[[82.5], [168.5]]
N=1./5
ll=N*hh
What I'm doing wrong? I received error :
"can't multiply sequence by non-int of
type 'float'"
I try to add float(), but this is not solve my problem;
I need to multiply each element in array...
thanks to all
**Ok thanks for idea for number * array, but how to multiply array*arr... | [
"When you multiply a sequence by X in Python, it doesn't multiply each member of the sequence - what it does is to repeat the sequence X times. That's why X has to be an integer (it can't be a float).\nWhat you want to do is to use a list comprehension:\nhh = [[82.5], [168.5]]\nN = 1.0 / 5\nll = [[x*N for x in y] ... | [
21,
8,
6
] | [] | [] | [
"floating_point",
"multiplication",
"python"
] | stackoverflow_0005825208_floating_point_multiplication_python.txt |
Q:
Why does adding my Sql UPDATE break my loop?
I have the following code which, without the escaped SQL statement, is working fine - it iterates over the full set of returns from a previous SELECT query printing the ID, detected language (from bingtranslate) and text.
for row in c:
lang=bingtranslate(row[0])
... | Why does adding my Sql UPDATE break my loop? | I have the following code which, without the escaped SQL statement, is working fine - it iterates over the full set of returns from a previous SELECT query printing the ID, detected language (from bingtranslate) and text.
for row in c:
lang=bingtranslate(row[0])
tweetid = row[1]
print tweetid, lang, row[0]
#... | [
"I think the call to execute alters the state of c, so that on the next iteration the loop ends.\n",
"I don't know Python, so I try to explain what I do in C#.\nYou're executing a Command using same object of a DataReader (c in python), so you have a reset and so the strange behaviour.\nIn my opinion you don't ne... | [
4,
1
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0005825180_python_sql_sqlite.txt |
Q:
Are urllib2 and httplib thread safe?
I'm looking for information on thread safety of urllib2 and httplib.
The official documentation (http://docs.python.org/library/urllib2.html and http://docs.python.org/library/httplib.html) lacks any information on this subject; the word thread is not even mentioned there...
UP... | Are urllib2 and httplib thread safe? | I'm looking for information on thread safety of urllib2 and httplib.
The official documentation (http://docs.python.org/library/urllib2.html and http://docs.python.org/library/httplib.html) lacks any information on this subject; the word thread is not even mentioned there...
UPDATE
Ok, they are not thread-safe out of t... | [
"httplib and urllib2 are not thread-safe.\nurllib2 does not provide serialized access to a global (shared)\nOpenerDirector object, which is used by urllib2.urlopen().\nSimilarly, httplib does not provide serialized access to HTTPConnection objects (i.e. by using a thread-safe connection pool), so sharing HTTPConnec... | [
42
] | [] | [] | [
"httplib",
"python",
"thread_safety",
"urllib2"
] | stackoverflow_0005825151_httplib_python_thread_safety_urllib2.txt |
Q:
Question about starting SSH tunnel using Python
I have ran into trouble while starting SSH tunnel from HTTP RPC server written in Python.
There is a simple HTTP RPC server written in Python based on Python's BaseHTTPServer.
As a part of one of the services I would like to start a SSH tunnel from the RPC server to... | Question about starting SSH tunnel using Python | I have ran into trouble while starting SSH tunnel from HTTP RPC server written in Python.
There is a simple HTTP RPC server written in Python based on Python's BaseHTTPServer.
As a part of one of the services I would like to start a SSH tunnel from the RPC server to a remote machine. I used os.system to start the SSH ... | [
"Instead of os.system(), try using subprocess.Popen() and set close_fds=True (available in Python 2.4 and higher).\nimport subprocess \nsubprocess.Popen(\"ssh -f -n -N -L 127.0.0.1:%d:localhost:%d user@%s\" % (6800, 9000, \"remote.machine\"), shell=True, close_fds=True)\n\nIn theory, I believe you should also be... | [
2,
0,
0
] | [] | [] | [
"python",
"ssh"
] | stackoverflow_0003574965_python_ssh.txt |
Q:
How do I handle Python unicode strings with null-bytes the 'right' way?
Question
It seems that PyWin32 is comfortable with giving null-terminated unicode strings as return values. I would like to deal with these strings the 'right' way.
Let's say I'm getting a string like: u'C:\\Users\\Guest\\MyFile.asy\x00\x00sy'... | How do I handle Python unicode strings with null-bytes the 'right' way? | Question
It seems that PyWin32 is comfortable with giving null-terminated unicode strings as return values. I would like to deal with these strings the 'right' way.
Let's say I'm getting a string like: u'C:\\Users\\Guest\\MyFile.asy\x00\x00sy'. This appears to be a C-style null-terminated string hanging out in a Python... | [
"I'd say it's a bug. The right way to deal with it would probably be fixing pywin32, but in case you aren't feeling adventurous enough, just trim it.\nYou can get everything before the first '\\x00' with filename.split('\\x00', 1)[0].\n",
"This doesn't happen on the version of PyWin32/Windows/Python I tested; I d... | [
6,
2,
0
] | [] | [] | [
"python",
"pywin32",
"unicode",
"winapi"
] | stackoverflow_0005559810_python_pywin32_unicode_winapi.txt |
Q:
Python multiply 2 arrays
This is continued from thread:
Python array multiply
I need to multiply array vs array. I don't want to use "numpy". From previous thread, I learned how to multiply
number*array:
hh=[[82.5], [168.5]]
N=1./5
ll = [[x*N for x in y] for y in hh]
But how can I multiply array*array: ->matrix... | Python multiply 2 arrays | This is continued from thread:
Python array multiply
I need to multiply array vs array. I don't want to use "numpy". From previous thread, I learned how to multiply
number*array:
hh=[[82.5], [168.5]]
N=1./5
ll = [[x*N for x in y] for y in hh]
But how can I multiply array*array: ->matrix multiplication.
hh=[[82.5], [... | [
"Your idea is right, but you can write it down a bit simpler:\nlist_a = [1,2,3,4,5] # or hh[0]\nlist_b = [6,7,8,9,0] # or hh[1]\nmultiplied = [a * b for a, b in zip(list_a, list_b)]\n\nAlso, if you want / operator to return float, add from __future__ import division at the top of your source.\n",
"You can use lis... | [
3,
3,
2,
1
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0005825653_arrays_python.txt |
Q:
"Enabling" comparison for classes
I would like some help on my CSC HW. It is on classes/objects, and it's a simple class on defining a circle, with the name class Circle(object).
The exact text of the HW (I completed the first two parts of this hw and thus this 3rd part is an expansion on the initial problem):
"""... | "Enabling" comparison for classes | I would like some help on my CSC HW. It is on classes/objects, and it's a simple class on defining a circle, with the name class Circle(object).
The exact text of the HW (I completed the first two parts of this hw and thus this 3rd part is an expansion on the initial problem):
"""Expand on your Circle class by enabling... | [
"You can use the total_ordering decorator from functools, which generates all the missing compare methods if you supply __eq__() and one other.\n\nGiven a class defining one or more\n rich comparison ordering methods, this\n class decorator supplies the rest.\n This simplifies the effort involved in\n specifyin... | [
41,
25,
0,
0
] | [] | [] | [
"class",
"object",
"python"
] | stackoverflow_0005824382_class_object_python.txt |
Q:
How to store cookie jar to be used between functions inside class?
I'd like to hear your suggestions on how to effectively store cookies, that are to be used inside a class by other functions. My current code looks like this:
class SomeClass:
def __init__(self, username, password):
self.logged_in ... | How to store cookie jar to be used between functions inside class? | I'd like to hear your suggestions on how to effectively store cookies, that are to be used inside a class by other functions. My current code looks like this:
class SomeClass:
def __init__(self, username, password):
self.logged_in = False
self.username = username
self.password ... | [
"First, as jathanism noticed, you are not actually installing the cookie jar. \nimport cookielib\n...\n\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) \n\nThen, urllib2.install_opener(opener) will install the opener globally(!), which you do not need to do. Remove urllib2.install... | [
3,
1
] | [] | [] | [
"cookiestore",
"python"
] | stackoverflow_0005825957_cookiestore_python.txt |
Q:
Store an empty list in a dynamic property in Python for GAE?
Cannot store empty list to dynamic property
class Mo(db.Expando)
pass
def newFunction
mo = Mo(key_name='1')
mo.list_of_stuff = [] # <--Error
After executing the last statement, I get the error:
Cannot store empty list to dynamic property... | Store an empty list in a dynamic property in Python for GAE? | Cannot store empty list to dynamic property
class Mo(db.Expando)
pass
def newFunction
mo = Mo(key_name='1')
mo.list_of_stuff = [] # <--Error
After executing the last statement, I get the error:
Cannot store empty list to dynamic property list_of_stuff
How do I store an empty list to a dynamic property ... | [
"You can't, because it's an invalid concept. Datastore entities are stored as a set of key/value pairs. When you store a list of any kind, it's internally represented as multiple pairs with the same key and different values, rather than one key with a list of values.\nStoring an empty list is thus equivalent to not... | [
4,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005824239_google_app_engine_python.txt |
Q:
Python, numpy, matrix
A=[['2' '7' 'fas']
['4' '8' 'sda']
['1' '5' 'daf']
['2' '24' 'gag']]
How can I get just matrix A, instead last "atribute" in each row:
A=[['2' '7']
['4' '8']
['1' '5' ]
['2' '24']]
I know that last element in row is [:-1]
I tried with numpy:
A[:, ?? ]
Matrix A is random elements, so... | Python, numpy, matrix | A=[['2' '7' 'fas']
['4' '8' 'sda']
['1' '5' 'daf']
['2' '24' 'gag']]
How can I get just matrix A, instead last "atribute" in each row:
A=[['2' '7']
['4' '8']
['1' '5' ]
['2' '24']]
I know that last element in row is [:-1]
I tried with numpy:
A[:, ?? ]
Matrix A is random elements, so I was thinking somethin in... | [
">>> arr=np.array([[1,2,3],[4,5,6],[7,8,9]])\n>>> arr[:,:-1]\narray([[1, 2],\n [4, 5],\n [7, 8]])\n\n",
">>> A = [ ['2', '7', 'fas']\n , ['4', '8', 'sda']\n , ['1', '5', 'daf']\n , ['2', '24', 'gag']\n ]\n\n>>> [ x[:-1] for x in A ]\n[['2', '7'], ['4', '8'], ['1', '5'], ['2... | [
6,
1
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0005826276_matrix_numpy_python.txt |
Q:
geodjango + PostGIS = GPL?
I always get confused with licenses, I'm reading up again, but I'm sure someone out there already understands this and may be able to explain it more clearly.
I'm trying to get my company to use geodjango, and being a typical large enterprise company they don't want to open-source the re... | geodjango + PostGIS = GPL? | I always get confused with licenses, I'm reading up again, but I'm sure someone out there already understands this and may be able to explain it more clearly.
I'm trying to get my company to use geodjango, and being a typical large enterprise company they don't want to open-source the resulting project. And therefore ... | [
"Disclaimer: the following is my opinion and not intended to be legal advice -- consult a licensed attorney for that.\nIn general, using psycopg2/PostGIS with your GeoDjango project does not make it subject to the GPLv2. I'll speak about PostGIS since others have already addressed the question as it relates to psy... | [
8,
3,
2,
1,
1
] | [] | [] | [
"django",
"licensing",
"python"
] | stackoverflow_0001117764_django_licensing_python.txt |
Q:
Sound shortened in PyGame
I'm using Ubuntu 10.4 and learning PyGame following the tutorial 'Pummel the chimp and win $$$'.
I made two '.wav' files, but when i try to play them, i get a strange noise just like a thud, very short.
I don't get any error message. Why doesn't this work as expected?
>>> import pygame
>>... | Sound shortened in PyGame | I'm using Ubuntu 10.4 and learning PyGame following the tutorial 'Pummel the chimp and win $$$'.
I made two '.wav' files, but when i try to play them, i get a strange noise just like a thud, very short.
I don't get any error message. Why doesn't this work as expected?
>>> import pygame
>>> pygame.init()
(6, 0)
>>> def ... | [
"My first thought was that this sounds like a problem with sampling frequency. Whenever the mixer is initiated its default values are:\n\npygame.mixer.init(frequency=22050,\n size=-16, channels=2, buffer=4096):\n return None\n\nIf frequency=22050, being the sampling frequency, is different from the sampling frequ... | [
3,
2,
2
] | [] | [] | [
"audio",
"pygame",
"python"
] | stackoverflow_0004329773_audio_pygame_python.txt |
Q:
Creating a regular expression that will search for strings converted to 12 digit hex values
I'm trying to create a regexp that will search for all 12 digit hex values in a file. For example: string 448699 => hex 343438363939. The regexp that I have now is:
(r'3[0-9]\d{10}')
it matches the first character to 3 the... | Creating a regular expression that will search for strings converted to 12 digit hex values | I'm trying to create a regexp that will search for all 12 digit hex values in a file. For example: string 448699 => hex 343438363939. The regexp that I have now is:
(r'3[0-9]\d{10}')
it matches the first character to 3 the second 0-9 and the next 10 are any random digits. The hex above is 12 digits and starting with t... | [
"You're really close. The pattern you want is:\n(r'(?:3\\d){6}')\n\nEdit - As Mike Pennington pointed out, hex numbers can include letters A-F. I wasn't actually sure of the purpose of the \"every other digit is 3\" rule, so I left the rules as you described them.\n",
"Confusion reigns supreme ...\nIf you want to... | [
3,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005821697_python_regex.txt |
Q:
How can I iterate through tags using Python?
I would like to iterate through some html and store data into a dictionary. Each iteration starts with:
<h1 class="docDisplay" id="docTitle">
I have the following code:
html = '<html><body><h1 class="docDisplay" id="docTitle">Data1</h1><p>other data<\p><h1 class="docD... | How can I iterate through tags using Python? | I would like to iterate through some html and store data into a dictionary. Each iteration starts with:
<h1 class="docDisplay" id="docTitle">
I have the following code:
html = '<html><body><h1 class="docDisplay" id="docTitle">Data1</h1><p>other data<\p><h1 class="docDisplay" id="docTitle">Data2</h1><p>other data2<\p>... | [
"To match the text of the paragraphs under each header, I would try something like this (you may have to modify this depending on the exact output format that you want):\n from BeautifulSoup import BeautifulSoup\n\n html = \"\"\" \n <html>\n <head>\n </head>\n\n <body>\n <h1 class=\"docDispla... | [
2
] | [
"@samplebias: @Lynch is right. If the OP doesn't close his/her tags properly, they simply cannot expect for the parser to be able to read their mind.\nTry fixing your HTML, it will probably work then. =)\n"
] | [
-1
] | [
"beautifulsoup",
"loops",
"python",
"tags"
] | stackoverflow_0005811022_beautifulsoup_loops_python_tags.txt |
Q:
Directory Stats in Python
How does one get statistics for a directory (not a file) in python?
For instance, I need to know when a directory was created. Seems that os.stat should be the solution, but os.stat does not work for directories. It only works on files, as far as I can tell.
Thanks!
A:
it works on d... | Directory Stats in Python | How does one get statistics for a directory (not a file) in python?
For instance, I need to know when a directory was created. Seems that os.stat should be the solution, but os.stat does not work for directories. It only works on files, as far as I can tell.
Thanks!
| [
"it works on directories\n>>> import os\n>>> os.stat(\"/\")\n(16877, 2L, 2049L, 25, 0, 0, 4096L, 1302891913, 1302891902, 1302891902)\n\n",
"Seems to work well for me:\n>>> import os\n>>> os.stat(\"/etc/\")\nposix.stat_result(st_mode=16877, st_ino=204001, st_dev=2051L, st_nlink=170, st_uid=0, st_gid=0, st_size=122... | [
6,
4
] | [] | [] | [
"directory",
"operating_system",
"python",
"statistics"
] | stackoverflow_0005826638_directory_operating_system_python_statistics.txt |
Q:
Custom default file storage in Django
I'm trying to use a custom file storage (https://bitbucket.org/david/django-storages/wiki/S3Storage). I followed the directions and put this in my settings.py
DEFAULT_FILE_STORAGE='storages.backends.s3boto.S3BotoStorage'
When I go to import default_storage, it's not of the t... | Custom default file storage in Django | I'm trying to use a custom file storage (https://bitbucket.org/david/django-storages/wiki/S3Storage). I followed the directions and put this in my settings.py
DEFAULT_FILE_STORAGE='storages.backends.s3boto.S3BotoStorage'
When I go to import default_storage, it's not of the type S3BotoStorage. I have to make the call ... | [
"From what I understand of django storages, the storage class will always be DefaultStorage (unless you set it explicitly in the model). It's at the _wrapped class that should look.\nDid you try to print \"p.original.storage._wrapped\" ?\nFrom my side, I get the same results as you, but if I print p.original.storag... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005108186_django_python.txt |
Q:
Python/Matplotlib - Colorbar Range and Display Values
When using matplotlib with a contour plot, I'm having trouble getting the colorbar to display as I want. I've read through numerous similar examples, but have still not been able to get what I want.
In the image below, I want two things changed. I want the m... | Python/Matplotlib - Colorbar Range and Display Values | When using matplotlib with a contour plot, I'm having trouble getting the colorbar to display as I want. I've read through numerous similar examples, but have still not been able to get what I want.
In the image below, I want two things changed. I want the minimum value and maximum values to be display on the color ... | [
"If I understand correctly what you want, I think this should do it:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nxi = np.array([0., 0.5, 1.0])\nyi = np.array([0., 0.5, 1.0])\nzi = np.array([[0., 1.0, 2.0],\n [0., 1.0, 2.0],\n [-0.1, 1.0, 2.0]])\n\nv = np.linspace(-.1, 2.0, 15... | [
45
] | [] | [] | [
"colorbar",
"contour",
"matplotlib",
"python"
] | stackoverflow_0005826592_colorbar_contour_matplotlib_python.txt |
Q:
Facebook Graph API: 400 Bad Request when getting user data
I'm making a page that displays details of an event, and details of any user that has registered an interest in coming to that event. I am using Facebook's Python-SDK (https://github.com/facebook/python-sdk) and I have had no problem getting the access tok... | Facebook Graph API: 400 Bad Request when getting user data | I'm making a page that displays details of an event, and details of any user that has registered an interest in coming to that event. I am using Facebook's Python-SDK (https://github.com/facebook/python-sdk) and I have had no problem getting the access token of the currently logged-in user. However, when the user visit... | [
"http://code.google.com/p/googleappengine/issues/detail?id=4824\n"
] | [
1
] | [] | [] | [
"facebook_graph_api",
"python"
] | stackoverflow_0005808389_facebook_graph_api_python.txt |
Q:
How to use argparse to collect arguments for a separate command line without --?
I'm writing Python programs that run other programs, like:
my-wrapper-program --foo --bar git commit --all
Here, foo and bar are arguments to my-wrapper-program, and git commit --all is the sub-command I'm interested in running. How... | How to use argparse to collect arguments for a separate command line without --? | I'm writing Python programs that run other programs, like:
my-wrapper-program --foo --bar git commit --all
Here, foo and bar are arguments to my-wrapper-program, and git commit --all is the sub-command I'm interested in running. How do I do this in argparse, without having to always specify the -- special argument? ... | [
"This page has some suggestions.\n"
] | [
4
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0005826881_argparse_python.txt |
Q:
Advice on python program
So i had to write a program that asks for a user input (which should be a 3 letter string) and it outputs the six permutations of the variations of the placements of the letters inside the string. However, my professor wants the output to be surrounded by curly brackets whereas mine is a l... | Advice on python program | So i had to write a program that asks for a user input (which should be a 3 letter string) and it outputs the six permutations of the variations of the placements of the letters inside the string. However, my professor wants the output to be surrounded by curly brackets whereas mine is a list (so it is square brackets)... | [
"The only datatype im aware of that 'natively' outputs with { } is a dictionary, which doesnt seem to apply here. I would just write a small function to output your lists in the desired fashion\n>>> def curlyBracketOutput(l):\n x = ''\n for i in l: x += i\n return '{' + x + '}'\n\n>>> curlyBra... | [
2,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005826697_python.txt |
Q:
print that only prints one line
How would you make print only print one line each time like
for i in range(1,100)
print i
but then i would want it to print one line each time so it would be: 1 and then 1 would be erased then it would print 2 and so on.
A:
A trailing comma suppresses the newline, a carriage ... | print that only prints one line | How would you make print only print one line each time like
for i in range(1,100)
print i
but then i would want it to print one line each time so it would be: 1 and then 1 would be erased then it would print 2 and so on.
| [
"A trailing comma suppresses the newline, a carriage return moves to the beginning of the line.\nfor i in range(1,100):\n print \"\\r\",i,\n\nThis works on Linux.\n",
"like this?\nimport sys\nimport time\n>>> for i in range(1, 100):\n... sys.stdout.write(str(i))\n... sys.stdout.flush()\n... time.sl... | [
3,
3,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005827000_python.txt |
Q:
Installing signal handler with Python
(there is a follow up to this question here)
I am working on trying to write a Python based Init system for Linux but I'm having an issue getting signals to my Python init script. From the 'man 2 kill' page:
The only signals that can be sent to process ID 1, the init process, ... | Installing signal handler with Python | (there is a follow up to this question here)
I am working on trying to write a Python based Init system for Linux but I'm having an issue getting signals to my Python init script. From the 'man 2 kill' page:
The only signals that can be sent to process ID 1, the init process, are those for which init has explicitly i... | [
"Signal handlers mostly work in Python. But there are some problems. One is that your handler won't run until the interpreter re-enters it's bytecode interpreter. if your program is blocked in a C function the signal handler is not called until it returns. You don't show the code where you are waiting. Are you usin... | [
1
] | [] | [] | [
"c",
"init",
"linux",
"python",
"signal_handling"
] | stackoverflow_0005826824_c_init_linux_python_signal_handling.txt |
Q:
How do I count the number of identical characters in a string by position using python?
For example:
String 1: AGGCCT
|| | |
String 2: AGCCAT
These two strings are identical at 4 positions, so the function I want would return 4.
Is there a clever (i.e., fast) method for doing this, other than the obviou... | How do I count the number of identical characters in a string by position using python? | For example:
String 1: AGGCCT
|| | |
String 2: AGCCAT
These two strings are identical at 4 positions, so the function I want would return 4.
Is there a clever (i.e., fast) method for doing this, other than the obvious method of iterating through both strings at the same time?
Thanks!
Uri
| [
"I don't think any \"clever\" trick beats the obvious approach, if it's well executed:\nsum(c1 == c2 for c1, c2 in itertools.izip(s1, s2))\n\nOr, if the use of booleans for arithmetic irks you, \nsum(1 for c1, c2 in itertools.izip(s1, s2) if c1 == c2)\n\n",
"Though I prefer delnan's generator expression, this wor... | [
7,
1,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0005825921_python_string.txt |
Q:
Django syncdb error
I have django.contrib.auth in my installed apps and everything was was working about 10 minutes ago. I deleted the existed database because I had problems with south migrations. When I try to rebuild it I get an error.
Error: django.db.utils.DatabaseError: no such table: auth_user
Traceback... | Django syncdb error | I have django.contrib.auth in my installed apps and everything was was working about 10 minutes ago. I deleted the existed database because I had problems with south migrations. When I try to rebuild it I get an error.
Error: django.db.utils.DatabaseError: no such table: auth_user
Traceback (most recent call last):... | [
"The problem is that you are running a query against the User model\n File \"/home/bruk/workspace/hungryDroid/src/hungryDroid/Ingredient/models.py\", line 26, in Ingredient\nFKowner = models.ForeignKey(User, default=User.objects.get(pk=1).id)\n\nIn the syncdb process (during field declaration actually, so any time... | [
8
] | [] | [] | [
"django",
"python",
"syncdb"
] | stackoverflow_0005827148_django_python_syncdb.txt |
Q:
How to "hide" superclass methods in a subclass
I basically want to create a subclass that "hides" methods on the superclass so that they don't show up in a dir() or hasattr() call and the users can't call them (at least not through any of the normal channels). I would also like to do this with the least amount of... | How to "hide" superclass methods in a subclass | I basically want to create a subclass that "hides" methods on the superclass so that they don't show up in a dir() or hasattr() call and the users can't call them (at least not through any of the normal channels). I would also like to do this with the least amount of "magic" possible. Thanks.
| [
"Overriding the __dir__ and __getattribute__ method respectively should do the trick. This is the pretty much the canonical way to do this kind of stuff in Python. Although whether you should be actually doing this is entirely a different matter.\nSee Python docs on Customizing Attribute Access\nUse __dir__ to list... | [
7,
6
] | [] | [] | [
"attributes",
"properties",
"python",
"subclass"
] | stackoverflow_0005827277_attributes_properties_python_subclass.txt |
Q:
Printing lines in python
How can i print lines in python like this
print " text here
text here
text here
line here"
I am trying cgi, so i dont have to use print to each line i have to print
thanks
A:
use triple quoted strings
print( """
Something
You
can
print
multi-line
""")
| Printing lines in python | How can i print lines in python like this
print " text here
text here
text here
line here"
I am trying cgi, so i dont have to use print to each line i have to print
thanks
| [
"use triple quoted strings \nprint( \"\"\"\nSomething \nYou \ncan\nprint\nmulti-line\n\"\"\")\n\n"
] | [
2
] | [] | [] | [
"cgi",
"printing",
"python"
] | stackoverflow_0005827399_cgi_printing_python.txt |
Q:
help with logging into a asp page using urllib
I'm trying to login to a aspx page. this is what i have so far:
o = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(o)
page = 'http://page/LoginForm.aspx'
raw_params = {'ctl00$ContentPlaceHolder1$usertext':'username','ctl00$ContentPlaceHolde... | help with logging into a asp page using urllib | I'm trying to login to a aspx page. this is what i have so far:
o = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(o)
page = 'http://page/LoginForm.aspx'
raw_params = {'ctl00$ContentPlaceHolder1$usertext':'username','ctl00$ContentPlaceHolder1$passtext':'password', 'ctl00$ContentPlaceHolder1$... | [
"Well asp.net is problematic by itself in many ways. I can only imagine how the page is coded, but mostly asp.net submits are done in a very painful way through _doPostback where it sets additional hidden fields. You might want to try reading this http://www.xefteri.com/articles/show.cfm?id=18 and reviewing the gen... | [
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0005741521_python_urllib2.txt |
Q:
Why can I manually build a Python MSI installer, but my Bamboo remote agent service fails to?
Background
My Bamboo server is running on Linux. I use Bamboo to build executable installers and source distributions for a Python app.
I can't build MSI installers for my Python package from Linux, so I am running a Bamb... | Why can I manually build a Python MSI installer, but my Bamboo remote agent service fails to? | Background
My Bamboo server is running on Linux. I use Bamboo to build executable installers and source distributions for a Python app.
I can't build MSI installers for my Python package from Linux, so I am running a Bamboo Remote Agent as a service on Windows 7 64-bit on another machine. This remote agent is configure... | [
"If the Bamboo agent is a Windows service, you might need to run it with elevated privileges. There are weird rules about how service accounts can access the MSI service. (I never narrowed down the exact permissions that are required.)\n"
] | [
3
] | [] | [] | [
"bamboo",
"python",
"windows",
"windows_installer",
"windows_services"
] | stackoverflow_0005825407_bamboo_python_windows_windows_installer_windows_services.txt |
Q:
*python code* problem/s with .txt file and tuples + dictionaries
I am writing this game, and having trouble coding my high scores list.
The high score table consists of a .txt file where the Name, Score is listed in that order, each on a new line right now for testing it has.
Matthew, 13
Luke, 6
John, 3
my code t... | *python code* problem/s with .txt file and tuples + dictionaries | I am writing this game, and having trouble coding my high scores list.
The high score table consists of a .txt file where the Name, Score is listed in that order, each on a new line right now for testing it has.
Matthew, 13
Luke, 6
John, 3
my code to record the score is:
print "You got it!\nWell done", NAME,",You gue... | [
"To sort by score rather than by name, use the key keyword argument. \nplayers.sort(key=lambda x: int(scorelist[x]))\n\nTo answer your second question (I think?), you are using a dictionary to save the scores. So any given name can only store one score at a time. \nparts = [p.strip() for p in line.split(\",\")]\nsc... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0005827411_python.txt |
Q:
How can I sort a portion of a list in place?
Possible Duplicate:
Python: sort a part of a list, in place
I want to implement a decision tree algorithm, and my implementation calls for sorting the table in order attribute by attribute, in place.
Here is the gist of it: choose an attribute, sort over it. All entr... | How can I sort a portion of a list in place? |
Possible Duplicate:
Python: sort a part of a list, in place
I want to implement a decision tree algorithm, and my implementation calls for sorting the table in order attribute by attribute, in place.
Here is the gist of it: choose an attribute, sort over it. All entries in the table that share that attribute can no... | [
"This is sort-of inplace. It does require temporary storage for the sorted part\n>>> a=range(20,0,-1)\n>>> a\n[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n>>> a[10:15]=sorted(a[10:15])\n>>> a\n[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 6, 7, 8, 9, 10, 5, 4, 3, 2, 1]\n>>> \n\n"
] | [
9
] | [] | [] | [
"python"
] | stackoverflow_0005827592_python.txt |
Q:
Ruby's watchr equivalent in Python?
I like the concept of watchr: it monitor the file system and run a callback when something changes. Is there a pure Python equivalent? Preferably pip installable.
A:
You should probably look at watchdog:
http://packages.python.org/watchdog/
A:
For Windows, there's watcher, t... | Ruby's watchr equivalent in Python? | I like the concept of watchr: it monitor the file system and run a callback when something changes. Is there a pure Python equivalent? Preferably pip installable.
| [
"You should probably look at watchdog:\nhttp://packages.python.org/watchdog/\n",
"For Windows, there's watcher, that is probably close to what you need although I'm not sure it provides 100% equivalent information.\n"
] | [
5,
0
] | [] | [] | [
"python",
"watchr"
] | stackoverflow_0005816346_python_watchr.txt |
Q:
Convert a JSON string to a Java/Python (Jython) object?
So I understand that you can convert JSON strings to strings and handle JSON objects in general through the org.json bundle in Android, but here's my current situation:
I need to take a JSON string from a certain URL (I'm already able to successfully do this)... | Convert a JSON string to a Java/Python (Jython) object? | So I understand that you can convert JSON strings to strings and handle JSON objects in general through the org.json bundle in Android, but here's my current situation:
I need to take a JSON string from a certain URL (I'm already able to successfully do this) and make it into an array. Well actually two arrays. The fra... | [
"Mapping a python dict to a json array is ... more work than you'd expect. It'd be better to make it into either a json object or start with a list, which can be mapped straight to a json array. Info on serializing between python and java. \nHere's a code example where I create a list structure in Python, and then ... | [
3
] | [] | [] | [
"android",
"arrays",
"java",
"json",
"python"
] | stackoverflow_0005827615_android_arrays_java_json_python.txt |
Q:
multiple d-bus session bus objects in python
I've written a script that connects to d-bus session bus on a remote computer like so:
os.environ["DBUS_SESSION_BUS_ADDRESS"] = "tcp:host=192.168.0.1,port=1234"
bus = dbus.SessionBus()
That works fine except now I need to be able to connect to multiple session buses on... | multiple d-bus session bus objects in python | I've written a script that connects to d-bus session bus on a remote computer like so:
os.environ["DBUS_SESSION_BUS_ADDRESS"] = "tcp:host=192.168.0.1,port=1234"
bus = dbus.SessionBus()
That works fine except now I need to be able to connect to multiple session buses on different computers. I've tried the following:
os... | [
"Its a confused question in retrospect.\nThere's no fundamental difference between a session bus or a system bus or any other d-bus. If you want to connect to a bus at a particular address just use dbus.bus.BusConnection:\nbus1 = dbus.bus.BusConnection(\"tcp:host=192.168.0.1,port=1234\")\nbus2 = dbus.bus.BusConnect... | [
3,
1
] | [] | [] | [
"dbus",
"python"
] | stackoverflow_0003776791_dbus_python.txt |
Q:
Beautiful Soup And While Statement
I'm trying to find the first 30 TED Videos (Name of Video and URL) using the following BeautifulSoup script:
import urllib2
from BeautifulSoup import BeautifulSoup
total_pages = 3
page_count = 1
count = 1
url = 'http://www.ted.com/talks?page='
while page_count < total_pages:
... | Beautiful Soup And While Statement | I'm trying to find the first 30 TED Videos (Name of Video and URL) using the following BeautifulSoup script:
import urllib2
from BeautifulSoup import BeautifulSoup
total_pages = 3
page_count = 1
count = 1
url = 'http://www.ted.com/talks?page='
while page_count < total_pages:
page = urllib2.urlopen("%s%d") %(url... | [
"First, simplify the loop and eliminate a few variables, which amount to boilerplate cruft in this case:\nfor pagenum in xrange(1, 4): # The 4 is annoying, write it as 3+1 if you like.\n url = \"http://www.ted.com/talks?page=%d\" % pagenum\n # do stuff with url\n\nBut let's open the file outside of the loop, ins... | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0005828290_beautifulsoup_python.txt |
Q:
python re.search (regex) to search words who have pattern like {{world}} only
I have on HTML file in which I have inserted the custom tags like {{name}}, {{surname}}. Now I want to search the tags who exactly match the pattern like {{world}} only not even {world}}, {{world}, {world}, { word }, {{ world }}, etc.
... | python re.search (regex) to search words who have pattern like {{world}} only | I have on HTML file in which I have inserted the custom tags like {{name}}, {{surname}}. Now I want to search the tags who exactly match the pattern like {{world}} only not even {world}}, {{world}, {world}, { word }, {{ world }}, etc.
I wrote the small code for the
re.findall(r'\{(\w.+?)\}', html_string)
... | [
"Um, shouldn't the regex be:\n'\\{\\{(\\w.+?)\\}\\}'\n\nOk, after the comments, I understand your requirements more:\n'\\{\\{\\w+?\\}\\}'\n\nshould work for you.\nBasically, you want {{any nnumber of word characters including underscore}}. You don't even need the lazy match in this case actually so you may remove t... | [
5,
2,
2,
2,
2
] | [] | [] | [
"matching",
"python",
"regex"
] | stackoverflow_0005828560_matching_python_regex.txt |
Q:
Pythonic way to merge two List of tuples into single list of dict
Hi I'm pretty new to Python, so I'm not really aware of all the little tricks and shortcuts yet. I have two multi-dimensional arrays:
>>> colorStrings
[('0', '2371_9890_020'), ('1', '2371_9031_100'), ('2', '2371_9890_464')]
and
>>> skus
[('0', '00... | Pythonic way to merge two List of tuples into single list of dict | Hi I'm pretty new to Python, so I'm not really aware of all the little tricks and shortcuts yet. I have two multi-dimensional arrays:
>>> colorStrings
[('0', '2371_9890_020'), ('1', '2371_9031_100'), ('2', '2371_9890_464')]
and
>>> skus
[('0', '0017651670'), ('0', '0017651688'), ('0', '0017651696'), ('0', '0017651704... | [
"try this :\n result = [\n {\n 'colorString' : color, \n 'skus' : [value for key, value in skus if key is colorkey]\n } for colorkey, color in colorStrings \n ]\n\n",
"Use defaultdict to group the skus by sku_id first, then use a list comprehension to generate the combined dataset\nfrom co... | [
10,
9
] | [] | [] | [
"dictionary",
"list",
"merge",
"python"
] | stackoverflow_0005828809_dictionary_list_merge_python.txt |
Q:
Slug field error in django
I am trying to integrate the following Blog app to my site,I get the following error for the slug field ,how to resolve this issue
TypeError at /login/
__init__() got an unexpected keyword argument 'prepopulate_from'
Request Method: GET
Request URL: http://192.1... | Slug field error in django | I am trying to integrate the following Blog app to my site,I get the following error for the slug field ,how to resolve this issue
TypeError at /login/
__init__() got an unexpected keyword argument 'prepopulate_from'
Request Method: GET
Request URL: http://192.168.254.35/accounts/login/new_win... | [
"The error says it all: a SlugField does not take the keyword argument prepopulate_from. The docs back this up - it only takes the argument max_length in addition to the standard argument. This should be done in the admin class instead.\nEdit: So your model file would be:\nfrom django.db import models\nfrom datetim... | [
4,
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0005828980_django_django_models_django_templates_django_views_python.txt |
Q:
Python: parsing help needed!
I am trying to retrieve certain fields within a .lua file. Initially I thought I could just split on commas but the second set of curly brackets ruins that. An example:
return {
{ 6163, 0, "tv", false, {1302}, "ESPN Deportes", "ESPN Deportes es el", nil,"tv","936",nil,"4x3", media... | Python: parsing help needed! | I am trying to retrieve certain fields within a .lua file. Initially I thought I could just split on commas but the second set of curly brackets ruins that. An example:
return {
{ 6163, 0, "tv", false, {1302}, "ESPN Deportes", "ESPN Deportes es el", nil,"tv","936",nil,"4x3", mediaRestrictions={"m2g" } },
{ 570... | [
"Probably convert to json.\nimport json\n\ntext = r\"\"\"return { \n{ 6163, 0, \"tv\", false, {1302}, \"ESPN Deportes\", \"ESPN Deportes es el\", nil,\"tv\",\"936\",nil,\"4x3\", mediaRestrictions={\"m2g\" } },\n{ 57075, 0, \"tv\", false, {1302}, \"Video Rola\", \"Video \\\"Música Para Tus Ojos\\\", uedes ver.\", ni... | [
3,
1,
1
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0005829050_parsing_python_regex.txt |
Q:
message reassembly / socket communication
I have a socket which receives information in packets of 1024 characters or less. In those packets I some messages or parts thereof. Each message is ended with 2 characters.
The problem appears when there is fragmentation of messages across two packages. What algorithm do ... | message reassembly / socket communication | I have a socket which receives information in packets of 1024 characters or less. In those packets I some messages or parts thereof. Each message is ended with 2 characters.
The problem appears when there is fragmentation of messages across two packages. What algorithm do you recommend to handle this fragmentation? (I'... | [
"buffer = ''\n\n# reading loop\nwhile True:\n\n data = socket.recv(1024)\n if not data:\n break\n\n # add the current data read by the socket to a temporary buffer\n buffer += data\n\n # search complete messages\n messages = buffer.split('\\r\\r')\n\n # we need at least 2 messages to continue\n if len(me... | [
4
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0005829148_python_sockets.txt |
Q:
Script languages: Max. Line Length
I have written a script which stores digital signatures in binaries and script files. This question is only regarding scripts: Currently, all these signatures get stored in one single line (a comment) such as:
#!/usr/bin/perl
print "Hello"
print " World\n"
#Signature:ASDASG13412s... | Script languages: Max. Line Length | I have written a script which stores digital signatures in binaries and script files. This question is only regarding scripts: Currently, all these signatures get stored in one single line (a comment) such as:
#!/usr/bin/perl
print "Hello"
print " World\n"
#Signature:ASDASG13412sdflsal4sf etc........
The example is Pe... | [
"Most scripting languages will have long enough limits, if indeed they have a formal limit on the length of lines. POSIX recommends 2048 minimum.\nHow long are your signatures? Most likely, not more than 1024...in which case, I really wouldn't worry. If it doesn't work for some language, you should report the bu... | [
3,
3,
2
] | [] | [] | [
"bash",
"interpreter",
"line",
"perl",
"python"
] | stackoverflow_0005829059_bash_interpreter_line_perl_python.txt |
Q:
Which python gui library to use to create dock application?
I would like to make a docking application using Python to run on Linux, but i have not enough insights / experience to chose the right GUI library. The requirements are:
The dock should be borderless.
The background should be transparent and / or custom... | Which python gui library to use to create dock application? | I would like to make a docking application using Python to run on Linux, but i have not enough insights / experience to chose the right GUI library. The requirements are:
The dock should be borderless.
The background should be transparent and / or customisable with SVG themes.
It should import icons in SVG format.
It ... | [
"Well i found out that Qt (using PyQt4) should be able to do this. It has a special library to handle SVG images and it seems to be possible to theme the entire GUI without using another library. See PyQt4 documentation over here.\n"
] | [
1
] | [] | [] | [
"dock",
"linux",
"python",
"svg",
"user_interface"
] | stackoverflow_0005791551_dock_linux_python_svg_user_interface.txt |
Q:
Why can't my post-receive hook run a virtualenv source command?
I have a post-receive hook that is running as user 'git'. I have a virtualenv /python/ve//bin/activate that is readable by git. Running:
source /python/ve/<name>/bin/activate
works fine for a user in the git group.
When it runs as a post-receive hook... | Why can't my post-receive hook run a virtualenv source command? | I have a post-receive hook that is running as user 'git'. I have a virtualenv /python/ve//bin/activate that is readable by git. Running:
source /python/ve/<name>/bin/activate
works fine for a user in the git group.
When it runs as a post-receive hook after a push, I get the error "source: not found".
I'm not sure wher... | [
"This is something of a guess, since you haven't quoted your complete post-receive hook, but I suspect that you don't have a shebang line pointing to /bin/bash at the top. Your post-receive hook should begin:\n#!/bin/bash\n\nI suspect this because if I run a strict Bourne shell, like dash, I get the same error whe... | [
14
] | [] | [] | [
"git",
"git_post_receive",
"linux",
"python",
"virtualenv"
] | stackoverflow_0005829784_git_git_post_receive_linux_python_virtualenv.txt |
Q:
Debug Pylons application through Eclipse
I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?
A:
Create a new launch configuration (Py... | Debug Pylons application through Eclipse | I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?
| [
"Create a new launch configuration (Python Run)\nMain tab\nUse paster-script.py as main module (you can find it in the Scripts sub-directory in your python installation directory)\nDon't forget to add the root folder of your application in the PYTHONPATH zone\nArguments\nSet the base directory to the root folder al... | [
10,
6,
2,
2,
1,
1,
0
] | [] | [] | [
"eclipse",
"pydev",
"pylons",
"pyramid",
"python"
] | stackoverflow_0000147650_eclipse_pydev_pylons_pyramid_python.txt |
Q:
How do I define a unique property for a Model in Google App Engine?
I need some properties to be unique. How can I achieve this?
Is there something like unique=True?
I'm using Google App Engine for Python.
A:
Google has provided function to do that:
http://code.google.com/appengine/docs/python/datastore/modelcla... | How do I define a unique property for a Model in Google App Engine? | I need some properties to be unique. How can I achieve this?
Is there something like unique=True?
I'm using Google App Engine for Python.
| [
"Google has provided function to do that:\nhttp://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_or_insert\nModel.get_or_insert(key_name, **kwds)\n\nAttempts to get the entity of the model's kind with the given key name. If it exists, get_or_insert() simply returns it. If it doesn't exist... | [
25,
21
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0001185628_google_app_engine_google_cloud_datastore_python.txt |
Q:
How to assign a memory address to a variable in Python?
here's the scenario:
I foolishly forget to assign the returned object to a variable:
>>> open("random_file.txt")
<open file 'random_file.txt', mode 'r' at 0x158f780>
Is there a way to directly assign the memory address to a variable? Something roughly equiva... | How to assign a memory address to a variable in Python? | here's the scenario:
I foolishly forget to assign the returned object to a variable:
>>> open("random_file.txt")
<open file 'random_file.txt', mode 'r' at 0x158f780>
Is there a way to directly assign the memory address to a variable? Something roughly equivalent to
int *ptr;
*ptr = 0x158f780;
Counter-points:
In this... | [
"Python is a high level language. You can't (not directly anyway) mess with memory addresses so the answer is no. \nThe REPL however does conveniently store the result of the last expression in a magic variable _. You can fetch it from there. To quote your example. \n>>> open(\"/etc/passwd\",\"r\") #Oops I forgot t... | [
17,
3
] | [] | [] | [
"pointers",
"python",
"variables"
] | stackoverflow_0005830179_pointers_python_variables.txt |
Q:
XML Cross Reference
I have an XML file that contains an ID and another XML file that contains the same ID.
I would like to cross reference these files and extract information from the second file.
The first file contains only those ID's that I need.
For example the first file contains the ID's 345, 350, 353, 356
... | XML Cross Reference | I have an XML file that contains an ID and another XML file that contains the same ID.
I would like to cross reference these files and extract information from the second file.
The first file contains only those ID's that I need.
For example the first file contains the ID's 345, 350, 353, 356
and the second file conta... | [
"To extract all id values from the first xml string:\nfrom lxml import etree\n\ne1 = etree.fromstring(xml1)\nids = e1.xpath('//id/text()')\n\nTo extract all <node> elements from the second xml string that are parents to id elements with known id values from the first one:\nimport re\n\ne2 = etree.fromstring(xml2)\n... | [
1
] | [] | [] | [
"perl",
"python",
"ruby",
"scripting",
"xml"
] | stackoverflow_0005827564_perl_python_ruby_scripting_xml.txt |
Q:
Python - Import file into NamedTuple
Recently I had a question regarding data types.
Since then, I've been trying to use NamedTuples (with more or less success).
My problem currently:
- How to import the lines from a file to new tuples,
- How to import the values separated with space/tab(/whatever) into a given ... | Python - Import file into NamedTuple | Recently I had a question regarding data types.
Since then, I've been trying to use NamedTuples (with more or less success).
My problem currently:
- How to import the lines from a file to new tuples,
- How to import the values separated with space/tab(/whatever) into a given part of the tuple?
Like:
Monday 8:00 ... | [
"Such database files are called comma separated values even though they are not really separated by commas. Python has a handy library called csv that lets you easily read such files\nHere is a slightly modified example from the docs\ncsv.register_dialect('mycsv', delimiter='\\t', quoting=csv.QUOTE_NONE)\nwith open... | [
12,
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0005830197_python.txt |
Q:
Is there any wysiwyg app which I can use to make the frontend pages of a sinmple django webapp?
I've never done any web development before. I'm using django because I'm OK at python. I just want to make a small webapp which does a small task fast...
A:
I found all wysiwyg editors I've used are much more confusin... | Is there any wysiwyg app which I can use to make the frontend pages of a sinmple django webapp? | I've never done any web development before. I'm using django because I'm OK at python. I just want to make a small webapp which does a small task fast...
| [
"I found all wysiwyg editors I've used are much more confusing to use than just some plain old html. It is super easy to get started. Do it in plain html.\n",
"http://code.google.com/p/django-tinymce/ for example. It is pretty simple.\n",
"Perhaps this http://developers.whatwg.org/introduction.html#introduction... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005830767_django_python.txt |
Q:
python 2.6.6 "phantom" whitespaces
Basically, I'm opening some files and removing all whitespaces from every line in that file.
code snippet:
for filepath in filelist:
if filepath.endswith(".shader"):
shaderfile = open(filepath,"r").readlines()
for line in shaderfile:
... | python 2.6.6 "phantom" whitespaces | Basically, I'm opening some files and removing all whitespaces from every line in that file.
code snippet:
for filepath in filelist:
if filepath.endswith(".shader"):
shaderfile = open(filepath,"r").readlines()
for line in shaderfile:
line = Left(line, line.find("\n"))+"\n... | [
"from StringIO import StringIO\n\na = StringIO(\"\"\"textures/common/lightgrid\ntextures/common/mirror1\n\ntextures/common/mirror2\n\nmaptextures/common/invisible.tga\n\ntextures/common/watercaulk\n\ntextures/common/clipnokick\n\ntextures/common/invisible\"\"\")\n\n\ndef clean_lines(fileobj):\n for line in fileo... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005830958_python.txt |
Q:
how to run and check run in python
I am completely new in Python.I need to write a python script which parse the request url of apache and find some data out of it.
Script is :
#!/usr/bin/python
import sys
import re
for line in sys.stdin:
ipAddress = re.search('ipAddress=([^&]*)', line)
key = re.sear... | how to run and check run in python | I am completely new in Python.I need to write a python script which parse the request url of apache and find some data out of it.
Script is :
#!/usr/bin/python
import sys
import re
for line in sys.stdin:
ipAddress = re.search('ipAddress=([^&]*)', line)
key = re.search('key=([^&]*)', line)
if len(ipAdd... | [
"You haven't specified what error you're getting, and your code doesn't generate any error for me, but I can see a few things that could go bad with your code.\nFirst, you just want the URL, not the method and HTTP version (which could cause some problems if ipAddress or key were the last fields), so you should spl... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005831333_python_regex.txt |
Q:
python mmap.error: Too many open files. What's wrong?
I'm reading a bunch of netcdf files using the pupynere interface (linux). The following code results in an mmap error:
import numpy as np
import os, glob
from pupynere import NetCDFFile as nc
alts = []
vals = []
path='coll_mip'
filter='*.nc'
for infile in glob.... | python mmap.error: Too many open files. What's wrong? | I'm reading a bunch of netcdf files using the pupynere interface (linux). The following code results in an mmap error:
import numpy as np
import os, glob
from pupynere import NetCDFFile as nc
alts = []
vals = []
path='coll_mip'
filter='*.nc'
for infile in glob.glob(os.path.join(path, filter)):
curData = nc(infi... | [
"My guess is that the mmap.mmap call in pupynere is holding the file descriptor open (or creating a new one). What if you do this:\nvals.append(curData.variables['O3.MIXING.RATIO'][:].copy())\nalts.append(curData.variables['ALTITUDE'][:].copy())\n\n",
"@corlettk: yeah since it is linux, do strace -e trace=file w... | [
6,
3,
2,
1
] | [] | [] | [
"linux",
"mmap",
"netcdf",
"numpy",
"python"
] | stackoverflow_0005830397_linux_mmap_netcdf_numpy_python.txt |
Q:
unit testing Python objects with pytest
I've a method that returns a list of objects that meet certain criteria
result = find_objects(some_criteria)
print("%r" % result)
>> [<my_object.my_object object at 0x85abbcc>]
I would like to write a pytest to verify the operation of find_objects()
def test_finder(testbed... | unit testing Python objects with pytest | I've a method that returns a list of objects that meet certain criteria
result = find_objects(some_criteria)
print("%r" % result)
>> [<my_object.my_object object at 0x85abbcc>]
I would like to write a pytest to verify the operation of find_objects()
def test_finder(testbed):
result = testbed.find_objects(some_cri... | [
"As you guessed, the problem is trying to do an 'is' comparison. 'is' means 'is the exact same object', and even two objects that appear identical can fail this test.\nHere are some things you might want to test\n\nNo exception was raised\nThe object returned was the right type\nassert isinstance(object, ResultClas... | [
4,
2,
2
] | [] | [] | [
"comparison",
"object",
"pytest",
"python",
"testing"
] | stackoverflow_0005825236_comparison_object_pytest_python_testing.txt |
Q:
regex to extract part of filename
I want to extract part of a filename that is contained in a xml string
Sample
<assets>
<media width="100%" height="100%" img="/assets/560PEgnR/kVvNKfOX7w9tf7.JPG" valign="top"/>
<media width="100%" height="100%" img="/assets/560PEgnR/kVvNKfOX7w9tf5.JPG" valign="top"/>
<media wid... | regex to extract part of filename | I want to extract part of a filename that is contained in a xml string
Sample
<assets>
<media width="100%" height="100%" img="/assets/560PEgnR/kVvNKfOX7w9tf7.JPG" valign="top"/>
<media width="100%" height="100%" img="/assets/560PEgnR/kVvNKfOX7w9tf5.JPG" valign="top"/>
<media width="100%" height="100%" img="/assets/56... | [
"Alternatively...\n/assets/([^/])+/\n\n",
"You should try with:\n/assets/(.*?)/.*\n\n.* is gready, but using ? it stops on the first /. \n",
"There are several alternatives. Your mistake is that your .* part also includes the '/', so either you make it less greedy (as hsz proposed above) or you exclude a '/' fr... | [
4,
3,
2,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005831301_python_regex.txt |
Q:
Reading gzip file that is currently being written to
My program does a lot of file processing, and as the files are large I prefer to write them as GZIP. One challenge is that I often need to read files as they are being written. This is not a problem without GZIP compression, but when compression is on, the rea... | Reading gzip file that is currently being written to | My program does a lot of file processing, and as the files are large I prefer to write them as GZIP. One challenge is that I often need to read files as they are being written. This is not a problem without GZIP compression, but when compression is on, the reading complains about failed CRC, which I presume might hav... | [
"I think flushing data to file (compressed) just writes the data into file, but headers are written only on close(), so you need to close the file first, and only after you can open it and read all data you need. If you need to write large data ammounts, you can try to use database, like PostgreSQL or MySQL where y... | [
0
] | [] | [] | [
"file",
"gzip",
"io",
"python"
] | stackoverflow_0005829964_file_gzip_io_python.txt |
Q:
Python: Setting conditions within if-elif-else block
I have the following code snippet:
for row in lst:
if 'Type' in row[0]:
for col in range(len(row)):
#do something
elif (not 'Type' or '') in row[0]:
for col in range(len(row)):
#do something
row_count +=1
For the ... | Python: Setting conditions within if-elif-else block | I have the following code snippet:
for row in lst:
if 'Type' in row[0]:
for col in range(len(row)):
#do something
elif (not 'Type' or '') in row[0]:
for col in range(len(row)):
#do something
row_count +=1
For the second part of elif (not 'Type' or '') how do I NOT increa... | [
"How about this:\nfor row in spamReader:\n if row[0] == '':\n continue\n\n if 'Type' in row[0]:\n row_count = 0\n ... start new worksheet ...\n\n for col in range(len(row)):\n ws.write(row_count,col,convert(row[col]),style) \n\n"
] | [
0
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0005831631_if_statement_python.txt |
Q:
Help with Complicated SQL Alchemy Join
First, the database overview:
competitors - people who compete
competitions - things that people compete at
competition_registrations - Competitors registered for a particular competition
event - An "event" at a competition.
events_couples - A couple (2 competitors) competin... | Help with Complicated SQL Alchemy Join | First, the database overview:
competitors - people who compete
competitions - things that people compete at
competition_registrations - Competitors registered for a particular competition
event - An "event" at a competition.
events_couples - A couple (2 competitors) competing in an event.
First, EventCouple, a Python... | [
"Your leading's condition mixes expression and string to be eval()ed. And following's condition mixes Python and SQL operators: and in Python is not what you expected here. Below are corrected examples using both variants:\nleading = relationship('EventCouple', primaryjoin=(\n (competition_id==EventCouple.compet... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0005822608_python_sqlalchemy.txt |
Q:
how do i import and use WordNet 3.0 in python?
I have downloaded the latest version of WordNet 3.0. I am not able to find a proper documentation of how to use it in python.
Does NLTK have wordnet 3.0 ?
I have already used an older version of wordnet in nltk.
Please help me.
A:
No, it seems that NLTK only suppor... | how do i import and use WordNet 3.0 in python? | I have downloaded the latest version of WordNet 3.0. I am not able to find a proper documentation of how to use it in python.
Does NLTK have wordnet 3.0 ?
I have already used an older version of wordnet in nltk.
Please help me.
| [
"No, it seems that NLTK only supports 3.0.\nIf I were doing this, I'd choose between using the 3.0 Java API through Jython or spawn the wn executable using the subprocess module.\nI'd lean towards the latter method in case I needed to integrate with an extensive existing codebase. Unfortunately this means doing wor... | [
3
] | [] | [] | [
"python",
"wordnet"
] | stackoverflow_0005830617_python_wordnet.txt |
Q:
Python data passing
I need exchange data between python daemon (cluster nods send data to this daemon) and php script (apache) which, is accessed by webbrowsers. What do you recommend as technology which could establish some connection between them. Both, python daemon and apache/php is on the same machine.
Thank... | Python data passing | I need exchange data between python daemon (cluster nods send data to this daemon) and php script (apache) which, is accessed by webbrowsers. What do you recommend as technology which could establish some connection between them. Both, python daemon and apache/php is on the same machine.
Thank you.
| [
"What you are wanting to do is called IPC (inter process communication). Since these are common Linux applications I am going to refer you to this SO question which recommends Unix Domain Sockets.\nFor PHP look here and for Python look here.\n",
"If you want things to be synchronous use a named socket(Amazing fea... | [
0,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0005832346_php_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.