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:
Are there a set of simple scripts to manipulate csv files available somewhere?
I am looking for a few scripts which would allow to manipulate generic csv files...
typically something like:
add-row FILENAME INSERT_ROW
get-row FILENAME GREP_ROW
replace-row FILENAME GREP_ROW INSERT_ROW
delete-row FILENAME GREP_... | Are there a set of simple scripts to manipulate csv files available somewhere? | I am looking for a few scripts which would allow to manipulate generic csv files...
typically something like:
add-row FILENAME INSERT_ROW
get-row FILENAME GREP_ROW
replace-row FILENAME GREP_ROW INSERT_ROW
delete-row FILENAME GREP_ROW
where
FILENAME the name of a csv file, with the first row conta... | [
"Perl has a tradition of in-place editing derived from the unix philosophy.\nWe could for example write simple add-row-by-num.pl command as follows :\n#!/usr/bin/perl -pi\nBEGIN { $ln=shift; $line=shift; }\nprint \"$line\\n\" if $ln==$.;\nclose ARGV if eof; \n\nReplace the third line by $_=\"$line\\n\" if $ln==$.; ... | [
4,
4,
0,
0
] | [] | [] | [
"csv",
"perl",
"python"
] | stackoverflow_0008365104_csv_perl_python.txt |
Q:
How do I send command with parameters to external cmd application in Python?
I need to execute and send command to external app from python:
.\Ext\PrintfPC /p “C:\Leica\DBX” /l “.\joblist.log”
It is cmd app, Is it possible to hide its console and terminate after all also using only
python?
A:
You are probably l... | How do I send command with parameters to external cmd application in Python? | I need to execute and send command to external app from python:
.\Ext\PrintfPC /p “C:\Leica\DBX” /l “.\joblist.log”
It is cmd app, Is it possible to hide its console and terminate after all also using only
python?
| [
"You are probably looking for the subprocess module. Example for executing the ls -l bash command on a unix system:\nsubprocess.call(['ls', '-l'])\n\nSo, in your case it should probably look something like:\nsubprocess.call(['.\\Ext\\PrintfPC', '/p', 'C:\\Leica\\DBX', '/l', '.\\joblist.log'])\n\nHave a look at the ... | [
1
] | [] | [] | [
"python",
"subprocess",
"windows"
] | stackoverflow_0008376819_python_subprocess_windows.txt |
Q:
Parsing an html table with BeautifulSoup
I am trying to take the data of a given day from this timetable: click here
I have been able to use Beautiful Soup to add an entire row for any given day (in this case, monday or 'Mon') to a list using this code:
from BeautifulSoup import BeautifulSoup
day ='Mon'
with ope... | Parsing an html table with BeautifulSoup | I am trying to take the data of a given day from this timetable: click here
I have been able to use Beautiful Soup to add an entire row for any given day (in this case, monday or 'Mon') to a list using this code:
from BeautifulSoup import BeautifulSoup
day ='Mon'
with open('timetable.txt', 'rt') as input_file:
html... | [
"You can find information like the course numbers using Regular Expressions, i.e., pattern matching.\nI don't know your experience with them, but Python includes a 're' module. Looking at the pattern of \"The four letters C-O-M-P followed by one or more digits.\" gives a RegEx of COMP\\d+ where \\d is one digit a... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"html_table",
"python"
] | stackoverflow_0008370389_beautifulsoup_html_parsing_html_table_python.txt |
Q:
How to CREATE a transparent gif (or png) with PIL (python-imaging)
Trying to create a transparent gif with PIL. So far I have this:
from PIL import Image
img = Image.new('RGBA', (100, 100), (255, 0, 0, 0))
img.save("test.gif", "GIF", transparency=0)
Everything I've found so far refers to manipulating... | How to CREATE a transparent gif (or png) with PIL (python-imaging) | Trying to create a transparent gif with PIL. So far I have this:
from PIL import Image
img = Image.new('RGBA', (100, 100), (255, 0, 0, 0))
img.save("test.gif", "GIF", transparency=0)
Everything I've found so far refers to manipulating an existing image to adjust it's transparency settings or overlaying a ... | [
"The following script creates a transparent GIF with a red circle drawn in the middle:\nfrom PIL import Image, ImageDraw\n\nimg = Image.new('RGBA', (100, 100), (255, 0, 0, 0))\n\ndraw = ImageDraw.Draw(img)\ndraw.ellipse((25, 25, 75, 75), fill=(255, 0, 0))\n\nimg.save('test.gif', 'GIF', transparency=0)\n\nand for PN... | [
61
] | [] | [] | [
"gif",
"imaging",
"python",
"python_imaging_library",
"transparency"
] | stackoverflow_0008376359_gif_imaging_python_python_imaging_library_transparency.txt |
Q:
Django Admin page - adding new positions to module
I'm planning to create my first project in Django - shops database, but I have some concerns, as I read some tutorials.
I like the admin page concept, but have a question:
When adding a shop I want user to be able to add some product positions related to it, like ... | Django Admin page - adding new positions to module | I'm planning to create my first project in Django - shops database, but I have some concerns, as I read some tutorials.
I like the admin page concept, but have a question:
When adding a shop I want user to be able to add some product positions related to it, like - item -> price, but their number won't be the same ever... | [
"In Django you define the database structure via your Models. So, as you say, you would have one model for Shop and another for Product, and Product would have a ForeignKey field to Shop.\nWhat you want is possible in the Django admin. Have a look at InlineModelAdmin in the docs. You would have an admin page for Sh... | [
1
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0008374866_django_django_admin_django_forms_python.txt |
Q:
mod_wsgi problem with MAMP
I make mod_wsgi is like following
$./configure
--with-python=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
--with-apxs=/usr/local/apache2/bin/apxs
checking Apache version... 2.0.63
configure: creating ./config.status
config.status: creating Makefile
$sudo make $sudo m... | mod_wsgi problem with MAMP | I make mod_wsgi is like following
$./configure
--with-python=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
--with-apxs=/usr/local/apache2/bin/apxs
checking Apache version... 2.0.63
configure: creating ./config.status
config.status: creating Makefile
$sudo make $sudo make install
and then I copy fil... | [
"Step 1: Make sure your version of MAMP is Version 2 because it includes a Universal Binary installer (32-bit & 64-bit)\nStep 2: Modify your Make file and eliminate the other compiler versions, similar to:\nCPPFLAGS = -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -DNDEBUG \nCFLAGS = -Wc,\"-a... | [
0
] | [] | [] | [
"django",
"mamp",
"mod_wsgi",
"python"
] | stackoverflow_0003257496_django_mamp_mod_wsgi_python.txt |
Q:
Submit data via web form and extract the results
My python level is Novice. I have never written a web scraper or crawler. I have written a python code to connect to an api and extract the data that I want. But for some the extracted data I want to get the gender of the author. I found this web site http://bookblo... | Submit data via web form and extract the results | My python level is Novice. I have never written a web scraper or crawler. I have written a python code to connect to an api and extract the data that I want. But for some the extracted data I want to get the gender of the author. I found this web site http://bookblog.net/gender/genie.php but downside is there isn't an ... | [
"No need to use mechanize, just send the correct form data in a POST request.\nAlso, using regular expression to parse HTML is a bad idea. You would be better off using a HTML parser like lxml.html.\nimport requests\nimport lxml.html as lh\n\n\ndef gender_genie(text, genre):\n url = 'http://bookblog.net/gender/a... | [
27,
17,
1
] | [] | [] | [
"python",
"web_crawler",
"web_scraping"
] | stackoverflow_0008377055_python_web_crawler_web_scraping.txt |
Q:
Most elegant approach for writing JSON data to a relational database using Django Models?
I have a typical Relational Database model laid out in Django where a typical model contains some ForeignKeys, some ManyToManyFields, and some fields that extend Django's DateTimeField.
I want to save data that I am receivin... | Most elegant approach for writing JSON data to a relational database using Django Models? | I have a typical Relational Database model laid out in Django where a typical model contains some ForeignKeys, some ManyToManyFields, and some fields that extend Django's DateTimeField.
I want to save data that I am receiving in JSON format (not flat) from an external api. I wan't it such that data gets saved to respe... | [
"In my opinion the cleanest place for the code you need is as a new Manager method (eg from_json_string) on a custom manager for the NinjaData model.\nI don't think you should override the standard create, get_or_create etc methods since you're doing something a bit different from what they normally do and it's goo... | [
10,
2,
1
] | [] | [] | [
"django",
"django_models",
"json",
"python",
"relational_database"
] | stackoverflow_0008367609_django_django_models_json_python_relational_database.txt |
Q:
Is it a idiomatic to implicitly make a class convertible to bool?
For some reason a lot of types are implicitly convertible to boolean values, despite Python's "be explicit" guideline. Anyway...
Is it idiomatic to make custom classes also implicitly convertible to bool, where appropriate? If yes, what function sho... | Is it a idiomatic to implicitly make a class convertible to bool? | For some reason a lot of types are implicitly convertible to boolean values, despite Python's "be explicit" guideline. Anyway...
Is it idiomatic to make custom classes also implicitly convertible to bool, where appropriate? If yes, what function should I (re)define? In my specific case, I have an Image class; I want to... | [
"This can be idiomatic; e.g., container object should test false when they are empty. You should define __nonzero__ in Python 2.x and __bool__ in Python 3 to do the conversion. When writing code targeting Python 2 and 3, define both.\nHowever, in keeping with the \"explicit is better than implicit\" guideline, you ... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0008377390_python.txt |
Q:
How to create a series of text menus in Python
I'm writing a small program that prints a menu screen with a list of options. If you choose one of the options, the screen is cleared and you're taken to the next menu.
Right now, I've made a base Menu class and given it a method draw() which draws the options. I then... | How to create a series of text menus in Python | I'm writing a small program that prints a menu screen with a list of options. If you choose one of the options, the screen is cleared and you're taken to the next menu.
Right now, I've made a base Menu class and given it a method draw() which draws the options. I then want to add a another method handle_options() which... | [
"An alternative to defining handle_options for every subclass of Menu is to define a dict that maps an option to a function call:\nclass Menu(object):\n def __init__(self):\n # Ideally, self._options would be an empty dict for the base class.\n # This is just for the sake of example.\n self._option... | [
4
] | [] | [] | [
"design_patterns",
"menu",
"python"
] | stackoverflow_0008377337_design_patterns_menu_python.txt |
Q:
Python: KeyError/IOError with urllib.urlopen
I am trying to pass some text to this readability API like so:
text = 'this reminds me of the Dutch 2001a caravan full of smoky people Auld Lang Syne'
# construct Readability Metrics API url
request_url = 'http://ipeirotis.appspot.com/readability/GetReadabilityScores?fo... | Python: KeyError/IOError with urllib.urlopen | I am trying to pass some text to this readability API like so:
text = 'this reminds me of the Dutch 2001a caravan full of smoky people Auld Lang Syne'
# construct Readability Metrics API url
request_url = 'http://ipeirotis.appspot.com/readability/GetReadabilityScores?format=json&text=%s' % text
request_url = urllib.quo... | [
"You are quoting the full url, including the http:// and what not. If you try to print the actually value of request_url, you get \n>>> print request_url\nhttp%3A%2F%2Fipeirotis.appspot.com%2Freadability%2FGetReadabilityScores%3Fformat\n%3Djson%26text%3Dthis+reminds+me+of+the+Dutch+2001a+caravan+full+of+smoky+peopl... | [
3,
1
] | [] | [] | [
"json",
"python",
"urllib",
"urlopen"
] | stackoverflow_0008377330_json_python_urllib_urlopen.txt |
Q:
GTK networking app: need design pattern
I intend to write a networking application with a GUI frontend, presumably using GTK.
I'm completely new to GTK (and GUI programming in general). My current guess would be to use two threads, one that handles networking and the other one running the GTK frontend.
Is this the... | GTK networking app: need design pattern | I intend to write a networking application with a GUI frontend, presumably using GTK.
I'm completely new to GTK (and GUI programming in general). My current guess would be to use two threads, one that handles networking and the other one running the GTK frontend.
Is this the common design pattern for this kind of probl... | [
"The normal GTK+ way of doing things is to have your GUI on the main thread, while slow operations are done on other thread(s). Note that when you want to update the GUI from another thread, you have to do it inside the GDK lock. The documentation mentions that \"with the Win32 backend, GDK calls should not be atte... | [
3,
1
] | [] | [] | [
"c",
"gtk",
"pygtk",
"python"
] | stackoverflow_0008371453_c_gtk_pygtk_python.txt |
Q:
Fastest Python equivalent to switch for array of integers
I want to find the fastest way to do the job of switch in C. I'm writing some Python code to replace C code, and it's all working fine except for a bottleneck. This code is used in a tight loop, so it really is quite crucial that I get the best performance.... | Fastest Python equivalent to switch for array of integers | I want to find the fastest way to do the job of switch in C. I'm writing some Python code to replace C code, and it's all working fine except for a bottleneck. This code is used in a tight loop, so it really is quite crucial that I get the best performance.
Optimsation Attempt 1:
First attempt, as per previous question... | [
"I think others are right to suggest numpy or pure c; but for pure python, here are some timings, for what they're worth. Based on these, I'm a bit surprised that array.array performed so much better than a dict. Are you creating these tables on the fly inside the loop? Or have I misunderstood something else about ... | [
2,
1
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0008377157_optimization_python.txt |
Q:
Parsing through a file from database and adding info to dictionary
I have text file as follows:
HEADER INFO
Last1, First1 Movie1 (1991) random stuff
Movie2 (1992) random stuff
Movie3 (1995) random stuff
Movie4 (3455) random stuff
Last2... | Parsing through a file from database and adding info to dictionary | I have text file as follows:
HEADER INFO
Last1, First1 Movie1 (1991) random stuff
Movie2 (1992) random stuff
Movie3 (1995) random stuff
Movie4 (3455) random stuff
Last2, First2 Movie1 (1998) random stuff
Movie2... | [
"Here is a solution with a for loop which is much more natural in Python. It assumes the input file is formatted with spaces, like the code posted in the question above. I have posted an alternative answer now for the case when the list is formatted with tabs instead of spaces.\nOf course you could rewrite it as a ... | [
0,
0
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0008372649_parsing_python.txt |
Q:
Python: gettext doesn't load translations on Windows
This particular piece of code works very well on Linux, but not on Windows:
locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain('exposong', LOCALE_PATH)
gettext.textdomain('exposong')
Code from here
Even if i specify the locale in locale.setlocale (I tri... | Python: gettext doesn't load translations on Windows | This particular piece of code works very well on Linux, but not on Windows:
locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain('exposong', LOCALE_PATH)
gettext.textdomain('exposong')
Code from here
Even if i specify the locale in locale.setlocale (I tried different formats) it doesn't work.
One problem might ... | [
"Standard gettext module in Python does not use startdard language settings from Windows settings, but instead relies on presence one of the environment variables: LANGUAGE, LC_MESSAGES, LC_ALL or LANG. (I'd say this is example of slack porting of Unix/Linux library to Windows.) \nThe environment variables mentione... | [
9,
6
] | [] | [] | [
"gettext",
"python",
"translation",
"windows"
] | stackoverflow_0003678174_gettext_python_translation_windows.txt |
Q:
Python: How to download a zip file
I'm attempting to download a zip file using this code:
o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
#login
p = urllib.urlencode( { usernameField: usernameVal, passField: passVal } )
f = o.open(authUrl, p )
data = f.read()
print data
f.close()
#download file
f = o.... | Python: How to download a zip file | I'm attempting to download a zip file using this code:
o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
#login
p = urllib.urlencode( { usernameField: usernameVal, passField: passVal } )
f = o.open(authUrl, p )
data = f.read()
print data
f.close()
#download file
f = o.open(remoteFileUrl)
localFile = open(loc... | [
"f.read() doesn't necessarily read the whole file, but just a packet of it (which might be the whole file if it's small, but won't be for a large file).\nYou need to loop over the packets like this:\nwhile 1:\n packet = f.read()\n if not packet:\n break\n localFile.write(packet)\nf.close()\n\nf.read() re... | [
10,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003532979_python.txt |
Q:
Putting a function to a local namespace to speeding up access taking descriptors into account
I use numpy.random.normal function in a tough loop in a class.
class MyClass(MyBaseClass):
def run(self):
while True:
...
self.L.append(numpy.random.normal(0,1))
I know that it's pr... | Putting a function to a local namespace to speeding up access taking descriptors into account | I use numpy.random.normal function in a tough loop in a class.
class MyClass(MyBaseClass):
def run(self):
while True:
...
self.L.append(numpy.random.normal(0,1))
I know that it's pretty slow in Python to use multiple lookups. In numpy.random.normal there are 3 lookups: first nump... | [
"If you must do something like this (is function lookup actually the dominant cost? Random number generation is not cheap) you should realize that one global + one attr lookup (MyClass._normal) is not that much cheaper than one global + three attr lookups (numpy.random.normal). What you really want is to get zero... | [
5,
2
] | [] | [] | [
"descriptor",
"python"
] | stackoverflow_0008377460_descriptor_python.txt |
Q:
How to download large file with binary mode in python?
I am code a download function in python. The file size >1GB. The server is linux, HTTP server is Karrigell. Client is browse, Firefox or IE. I meet a big trouble.
At first, I use sys.stdout() to send file content.
file = open(path, 'rb')
size = os.path.getsiz... | How to download large file with binary mode in python? | I am code a download function in python. The file size >1GB. The server is linux, HTTP server is Karrigell. Client is browse, Firefox or IE. I meet a big trouble.
At first, I use sys.stdout() to send file content.
file = open(path, 'rb')
size = os.path.getsize(path)
RESPONSE['Pragma'] = 'public'
RESPONSE['Expires'] =... | [
"You should try to download the file in chunks. This is an example that works for me using urllib2\nimport os\nimport urllib2\nimport math\n\ndef downloadChunks(url):\n \"\"\"Helper to download large files\n the only arg is a url\n this file will go to a temp directory\n the file will also be... | [
1
] | [] | [] | [
"download",
"python",
"sendfile"
] | stackoverflow_0005064879_download_python_sendfile.txt |
Q:
HTTP Download very Big File
I'm working at a web application in Python/Twisted.
I want the user to be able to download a very big file (> 100 Mb). I don't want to load all the file in memory (of the server), of course.
server side I have this idea:
...
request.setHeader('Content-Type', 'text/plain')
fp = open(file... | HTTP Download very Big File | I'm working at a web application in Python/Twisted.
I want the user to be able to download a very big file (> 100 Mb). I don't want to load all the file in memory (of the server), of course.
server side I have this idea:
...
request.setHeader('Content-Type', 'text/plain')
fp = open(fileName, 'rb')
try:
r = None
... | [
"Two big problems with the sample code you posted are that it is non-cooperative and it loads the entire file into memory before sending it.\nwhile r != '':\n r = fp.read(1024)\n request.write(r)\n\nRemember that Twisted uses cooperative multitasking to achieve any sort of concurrency. So the first problem w... | [
37,
3,
3,
0
] | [] | [] | [
"download",
"http",
"python",
"twisted"
] | stackoverflow_0001538617_download_http_python_twisted.txt |
Q:
I am downloading a file using Python urllib2. How do I check how large the file size is?
And if it is large...then stop the download?
I don't want to download files that are larger than 12MB.
request = urllib2.Request(ep_url)
request.add_header('User-Agent',random.choice(agents))
thefile = urllib2.urlopen(request)... | I am downloading a file using Python urllib2. How do I check how large the file size is? | And if it is large...then stop the download?
I don't want to download files that are larger than 12MB.
request = urllib2.Request(ep_url)
request.add_header('User-Agent',random.choice(agents))
thefile = urllib2.urlopen(request).read()
| [
"There's no need as bobince did and drop to httplib. You can do all that with urllib directly:\n>>> import urllib2\n>>> f = urllib2.urlopen(\"http://dalkescientific.com\")\n>>> f.headers.items()\n[('content-length', '7535'), ('accept-ranges', 'bytes'), ('server', 'Apache/2.2.14'),\n ('last-modified', 'Sun, 09 Mar 2... | [
20,
7,
1,
1
] | [] | [] | [
"download",
"file",
"python",
"urllib2"
] | stackoverflow_0001636637_download_file_python_urllib2.txt |
Q:
python - accessing superclass attributes
Hi I want to achieve the following in python, however I cant figure out what to replace the line super.a = b with:
class Super:
def __init__(self):
self.a = 1
class Sub(Super):
def method(self, b):
super.a = b
A:
An Sub is a Super, i.e. all instances of Sub c... | python - accessing superclass attributes | Hi I want to achieve the following in python, however I cant figure out what to replace the line super.a = b with:
class Super:
def __init__(self):
self.a = 1
class Sub(Super):
def method(self, b):
super.a = b
| [
"An Sub is a Super, i.e. all instances of Sub can be treated exactly like instances of Super. In your case, that means you simply set self.a = b.\n"
] | [
20
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0008377634_inheritance_python.txt |
Q:
comparing hebrew strings in python
I'm writing a small scirpt that will give me some updates from an israel cable company website written in Hebrew (html). The web page uses abbreviation which I want to change back to the full word. I have placed a line at the head of my python file
#coding=utf8
and a line in t... | comparing hebrew strings in python | I'm writing a small scirpt that will give me some updates from an israel cable company website written in Hebrew (html). The web page uses abbreviation which I want to change back to the full word. I have placed a line at the head of my python file
#coding=utf8
and a line in the code
if w = "ה.": print (w)
but ... | [
"You have to mark it as a unicode string:\nif w == u\"ה.\": print (w)\n\nThat's gonna work now.\nEDIT: Let me state the obvious: the variable w should also be a unicode string (w = u\"...\").\n",
"It helps to post a complete example illustrating the problem, along with the version of Python you are using. For ex... | [
5,
2
] | [] | [] | [
"hebrew",
"python",
"string",
"unicode"
] | stackoverflow_0008371497_hebrew_python_string_unicode.txt |
Q:
How to show and hide code in sphinx doc?
I want the same functionality mention in Sphinx, reStructuredText show/hide code snippets. But there is no code shared on that post.
A:
SQLAlchemy docs
The SQLAlchemy documentation uses a special extension (https://bitbucket.org/zzzeek/zzzeeksphinx/).
The documentation s... | How to show and hide code in sphinx doc? | I want the same functionality mention in Sphinx, reStructuredText show/hide code snippets. But there is no code shared on that post.
| [
"SQLAlchemy docs\nThe SQLAlchemy documentation uses a special extension (https://bitbucket.org/zzzeek/zzzeeksphinx/).\nThe documentation source contains markup with custom options and tokens, like in this example:\n.. sourcecode:: python+sql\n \n {sql}>>> engine.execute(\"select 1\").scalar()\n select 1\n ... | [
8
] | [] | [] | [
"python",
"python_sphinx"
] | stackoverflow_0008151729_python_python_sphinx.txt |
Q:
plotting many graphs with matplotlib
Whenever, I want to plot multiple 2d line graphs graphs with matplotlib, I define two lists :
coloTypesList=["b","g","r","c","m","y","k"];
drawTypesList=["-","--","x"];
and select a pair from these at each iteration(for each graph). This is method only helps me when I have less... | plotting many graphs with matplotlib | Whenever, I want to plot multiple 2d line graphs graphs with matplotlib, I define two lists :
coloTypesList=["b","g","r","c","m","y","k"];
drawTypesList=["-","--","x"];
and select a pair from these at each iteration(for each graph). This is method only helps me when I have less than 22 graphs to draw. Any idea about ma... | [
"From the lists you give you have 21 combinations:\n>>> from itertools import product\n>>> markers = [\"-\", \"--\", \"x\"]\n>>> colors = [\"b\", \"g\", \"r\", \"c\", \"m\", \"y\", \"k\"]\n>>> [a + b for a, b in product(colors, markers)]\n['b-', 'b--', 'bx', 'g-', 'g--', 'gx', 'r-', 'r--', 'rx', 'c-', 'c--', 'cx', ... | [
8
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0008376926_matplotlib_plot_python.txt |
Q:
Running subsequent commands within python
I would like to be able to call two (or more) commands within python but I would like to make sure that the first is finished before the second starts. Is that possible with subprocess? For example:
subprocess.call("script1 input1 > out", shell=True)
and when that command... | Running subsequent commands within python | I would like to be able to call two (or more) commands within python but I would like to make sure that the first is finished before the second starts. Is that possible with subprocess? For example:
subprocess.call("script1 input1 > out", shell=True)
and when that command finishes:
subprocess.call("script2 out>out2", ... | [
"A call to subprocess.call blocks until the command completes. From the documentation:\n\nWait for command to complete, then return the returncode attribute.\n\nA similar option that also waits for completion is subprocess.check_call. The difference between call and check_call is that the latter raises an exception... | [
6,
1,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0008377391_python_subprocess.txt |
Q:
Swapping items in a dictionary and order
I'm trying to take a dictionary of keys and values and then swap the corresponding keys and values around, from looking through previously posted questions I know you can swap keys/ values of a dictionary around using something such as:
newdict = dict((b,a) for a,b in D.ite... | Swapping items in a dictionary and order | I'm trying to take a dictionary of keys and values and then swap the corresponding keys and values around, from looking through previously posted questions I know you can swap keys/ values of a dictionary around using something such as:
newdict = dict((b,a) for a,b in D.items())
I am also aware that dictionaries are n... | [
"OrderedDict as part of the solution\nAs you mentioned, dict does not have any specific order, thus you would need to implement dict-like data structure that can be ordered.\nGood solution here is OrderedDict. You can create sorted OrderedDict like that:\n>>> D = {9: 8, 2: 1, 11: 20, 4: 3, 6: 5}\n>>> import collect... | [
3,
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"python",
"swap"
] | stackoverflow_0008377998_dictionary_python_swap.txt |
Q:
django-transmeta: How to localize sitemaps
I'm making simple webblog system translated into 2 languages. It contains 2 models Article (translated name and description here) and Category (translated name here)
How do I generate a sitemap one per category per language?
A:
Hi I am a developer of django-transmeta.
I... | django-transmeta: How to localize sitemaps | I'm making simple webblog system translated into 2 languages. It contains 2 models Article (translated name and description here) and Category (translated name here)
How do I generate a sitemap one per category per language?
| [
"Hi I am a developer of django-transmeta.\nI think that your problem is that you wat use the same template and in Django is impossible something like this:\n{{ content.title_{{ lang }} }}\n\nA solution would be have a template for each lang. But it's a ugly solution.\nOther solution, could be create a templatetag a... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005991471_django_python.txt |
Q:
How can I convert a list of strings into numeric values?
How can I convert a list of strings (each of which represents a number, i.e. [‘1’, ‘2’, ‘3’]) into numeric values.
A:
map(int, ["1", "2", "3"])
gives
[1, 2, 3]
A:
Use int() and a list comprehensions:
>>> i = ['1', '2', '3']
>>> [int(k) for k in i]
[1,... | How can I convert a list of strings into numeric values? | How can I convert a list of strings (each of which represents a number, i.e. [‘1’, ‘2’, ‘3’]) into numeric values.
| [
"\nmap(int, [\"1\", \"2\", \"3\"]) \n\ngives\n[1, 2, 3]\n\n",
"Use int() and a list comprehensions: \n>>> i = ['1', '2', '3']\n>>> [int(k) for k in i]\n[1, 2, 3]\n\n",
"As Long as the strings are of the form '1' rather than 'one' then you can use the int() function. \nSome sample code would be\nstrList = ['1',... | [
16,
10,
5,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0001345287_python.txt |
Q:
Unneeded parts when unwrapping tuple/list
Python is all about writing beautiful code. So, I was running pylint to check the "beautifulness" of my code, when I bump into something:
Unused variable 'myvar1'
From this part of my code:
for myvar1, myvar2 in mylist:
# Do stuff just using myvar2
mylist is a list ... | Unneeded parts when unwrapping tuple/list | Python is all about writing beautiful code. So, I was running pylint to check the "beautifulness" of my code, when I bump into something:
Unused variable 'myvar1'
From this part of my code:
for myvar1, myvar2 in mylist:
# Do stuff just using myvar2
mylist is a list of tuples, so I'm unwrapping the tuples into tw... | [
"In addition to @RaymondHettinger's answer: Pylint also does not complain about unused variables if their names start with a single underscore. This means that you can use:\nfor _myvar1, myvar2 in mylist:\n\ngetting the best of both worlds: \n\nno Pylint warning, \nand information about the record structure\n\nThis... | [
11,
3,
3,
2,
2
] | [
"tu = [(12,'sea'),(478,'badada'),(789,'zut')]\n\nfor x,x in tu:\n print x\n\nresult\nsea\nbadada\nzut\n\n!\n"
] | [
-1
] | [
"pylint",
"python",
"variable_assignment"
] | stackoverflow_0008361891_pylint_python_variable_assignment.txt |
Q:
Python: Unable to import mechanize module on Mac
I have mechanize module installed using easy_install but when I tried to import I get the following error:
Python 2.6.7 (r267:88850, Nov 21 2011, 14:59:21)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for mo... | Python: Unable to import mechanize module on Mac | I have mechanize module installed using easy_install but when I tried to import I get the following error:
Python 2.6.7 (r267:88850, Nov 21 2011, 14:59:21)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import mechanize
Traceback (most r... | [
"Looks like you have installed mechanize to python 2.6 provided with Os X, but you are running python interpreter installed from macports.\nYou can run easy_install for python from macports with (for python 2.7): \n/opt/local/bin/easy_install-2.7\n\n"
] | [
2
] | [] | [] | [
"easy_install",
"macports",
"mechanize",
"python"
] | stackoverflow_0008378060_easy_install_macports_mechanize_python.txt |
Q:
Parsing a single dimensional list into dict
I need to parse a the following list format into a dict.
This represents 2 people, with 3 pieces of data for each person, firstname, lastname, & email.
data = [3, 'firstname', 'lastname', 'email', 2, 'jack', 'black', 'jb@example.com', 'jane', 'green', 'jg@examlpe.com']
... | Parsing a single dimensional list into dict | I need to parse a the following list format into a dict.
This represents 2 people, with 3 pieces of data for each person, firstname, lastname, & email.
data = [3, 'firstname', 'lastname', 'email', 2, 'jack', 'black', 'jb@example.com', 'jane', 'green', 'jg@examlpe.com']
data[0] is how many people fields are being sent.... | [
"That's a good list to use iterators:\n>>> i = iter(data)\n>>> attr = [next(i) for x in range(next(i))]\n>>> [{x:next(i) for x in attr} for y in range(next(i))]\n[{'lastname': 'black', 'email': 'jb@example.com', 'firstname': 'jack'}, {'lastname': 'green', 'email': 'jg@examlpe.com', 'firstname': 'jane'}]\n\n",
"Th... | [
3,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0008378119_dictionary_list_python.txt |
Q:
python array.tostring() has NUL bytes in it
I have the following code (as an example) in a unittest TestCase
def test(self):
a = array('u','\0'*3)
a[0] = 'h'
a[1] = 'h'
a[2] = 'h'
self.assertEqual(a.tostring(), "hhh")
The assertion fails with the following error:
AssertionError: b'h\x00\x00\x... | python array.tostring() has NUL bytes in it | I have the following code (as an example) in a unittest TestCase
def test(self):
a = array('u','\0'*3)
a[0] = 'h'
a[1] = 'h'
a[2] = 'h'
self.assertEqual(a.tostring(), "hhh")
The assertion fails with the following error:
AssertionError: b'h\x00\x00\x00h\x00\x00\x00h\x00\x00\x00' != 'hhh'
Now I und... | [
"I suppose you are working with Python3, which seems to lack a 'c' option for array.\nIn this case, I would do\na = array.array(\"b\",4*(0,))\na[0] = 'h'\na[1] = 'h'\na[2] = 'h'\n\nAnother option would be\na=array.array('u', \"hhh\") # the same as yours, but shorter\na.tounicode()\n\nBut then you have a unicode str... | [
3,
1
] | [] | [] | [
"arrays",
"python",
"python_3.x",
"unicode"
] | stackoverflow_0008377165_arrays_python_python_3.x_unicode.txt |
Q:
Python: comparing items in lists with for-loop
I am trying to compare bunch of pair of lists and see if there is any same item in both lists with loops, but it looks like it's missing one item everytime I run it.
for item in alp:
for item2 in numbers:
if type((pos_ans[str(item) + str(item2)])) != int: ... | Python: comparing items in lists with for-loop | I am trying to compare bunch of pair of lists and see if there is any same item in both lists with loops, but it looks like it's missing one item everytime I run it.
for item in alp:
for item2 in numbers:
if type((pos_ans[str(item) + str(item2)])) != int:
for item3 in (pos_ans[str(item) + str(item... | [
"While it is difficult to tell exactly without more context, you might have better luck–if they really are the same object–putting the objects into sets and then calling intersect between them to see where the overlap is. \n",
"Without looking at your code, I can only assume one of your If statements is making a ... | [
1,
0
] | [] | [] | [
"comparison",
"for_loop",
"list",
"loops",
"python"
] | stackoverflow_0008378373_comparison_for_loop_list_loops_python.txt |
Q:
Retrieve and displaying BLOB images from Mysql database with Tkinter
this def should connect to a database, and if the parameters are correct should retrieve a BLOB image, however i confused on how to display that image. currently, it will display all the other information besides the BLOB image that i want to be ... | Retrieve and displaying BLOB images from Mysql database with Tkinter | this def should connect to a database, and if the parameters are correct should retrieve a BLOB image, however i confused on how to display that image. currently, it will display all the other information besides the BLOB image that i want to be displayed. i realize that setting it to a stringvar is not correct. can an... | [
"I think you'll need PIL for this (and possibly StringIO as well).\nsomething like:\nfrom PIL import Image, ImageTk\nimport cStringIO\n\n...\n\nresults = cursor.fetchone()\ndata = cStringIO.StringIO(results.tostring())\npic = ImageTk.PhotoImage(Image.open(data))\n\npatface = Tkinter.Label(func, image=pic)\npatface.... | [
0
] | [] | [] | [
"blob",
"mysql",
"python",
"tkinter"
] | stackoverflow_0008317421_blob_mysql_python_tkinter.txt |
Q:
Is there a one line way of saying this?
Pretty simple probably for someone. Is there a way to say this in one line of code?
if word.startswith('^') or word.startswith('@'):
truth = True
else:
truth = False
A:
I think this will be the shortest one:
truth = word.startswith(('^','@'))
From docs (look at t... | Is there a one line way of saying this? | Pretty simple probably for someone. Is there a way to say this in one line of code?
if word.startswith('^') or word.startswith('@'):
truth = True
else:
truth = False
| [
"I think this will be the shortest one:\ntruth = word.startswith(('^','@'))\n\nFrom docs (look at the last line):\nstartswith(...)\n S.startswith(prefix[, start[, end]]) -> bool\n\n Return True if S starts with the specified prefix, False otherwise.\n With optional start, test S beginning at that position.... | [
10,
8,
3,
1
] | [] | [] | [
"conditional",
"python"
] | stackoverflow_0008378364_conditional_python.txt |
Q:
UTF-8 minus sign rejected in python command-line arguments
I am running python 2.6 on Ubuntu Lucent and having trouble getting the minus sign in negative command-line arguments to be interpreted properly, especially when the call to the script is initiated through the OS via Rails (using backquotes). In particula... | UTF-8 minus sign rejected in python command-line arguments | I am running python 2.6 on Ubuntu Lucent and having trouble getting the minus sign in negative command-line arguments to be interpreted properly, especially when the call to the script is initiated through the OS via Rails (using backquotes). In particular, the minus sign seems to be coming in as UTF-8.
When command-l... | [
"Your input data contains a Unicode character that isn't the standard ascii hyphen.\nimport unicodedata as ud\ndata = '\\xe2\\x80\\x90122.76838'\nunicode_data = data.decode('utf8')\nprint repr(ud.name(unicode_data[0]))\nprint repr(ud.name(u'-')) # An ascii hyphen\n\nOutput:\n'HYPHEN'\n'HYPHEN-MINUS'\n\nWhile they m... | [
3,
1
] | [] | [] | [
"argparse",
"command_line",
"python",
"ruby_on_rails",
"ubuntu"
] | stackoverflow_0008378257_argparse_command_line_python_ruby_on_rails_ubuntu.txt |
Q:
Pygame Overlays
Okay, so I want to make an overlay screen.
So whenever the keypress is p then the screen pauses and a screen pops up saying
: "Press 'q' to quit or 'c' to continue,"
something like that.
Can anyone tell me how?
A:
The easiest way to do this is using a submodule, then to create a new loop for bl... | Pygame Overlays | Okay, so I want to make an overlay screen.
So whenever the keypress is p then the screen pauses and a screen pops up saying
: "Press 'q' to quit or 'c' to continue,"
something like that.
Can anyone tell me how?
| [
"The easiest way to do this is using a submodule, then to create a new loop for blit()-ing to the screen and event handling for this pause menu.\n(This is methodology only; this is how I work my projects.)\nUpdate: 13/12/11\nThe following excerpt of code is from the \"parent\" module. This is just the loop section ... | [
2
] | [] | [] | [
"overlay",
"pygame",
"python"
] | stackoverflow_0008378922_overlay_pygame_python.txt |
Q:
Self-organizing Fuzzy Neural Network (SOFNN) Implementations in Java, C, Python etc
We are looking for an implementation of a Self-organizing Fuzzy Neural Network (SOFNN) in Java or another lang such as Python or C.
Looking at Neuroph, one of the best Neural Net frameworks out there for Java there is no such net t... | Self-organizing Fuzzy Neural Network (SOFNN) Implementations in Java, C, Python etc | We are looking for an implementation of a Self-organizing Fuzzy Neural Network (SOFNN) in Java or another lang such as Python or C.
Looking at Neuroph, one of the best Neural Net frameworks out there for Java there is no such net type.
Is anyone aware of any working implementations of Fuzzy Neural Nets?
Cheers!
| [
"Check out NEFCLASS\n"
] | [
0
] | [] | [] | [
"java",
"machine_learning",
"neural_network",
"prediction",
"python"
] | stackoverflow_0007273718_java_machine_learning_neural_network_prediction_python.txt |
Q:
events happening at different speeds within a clock timer
im total rubbish at maths, and its hurting my head trying to figure this out. Im trying to have two things happen at different speeds. I want to have two speeds, doesnt particularly matter whether the scale is from 1 - 10 or 0.1 - 1. but i want to have them... | events happening at different speeds within a clock timer | im total rubbish at maths, and its hurting my head trying to figure this out. Im trying to have two things happen at different speeds. I want to have two speeds, doesnt particularly matter whether the scale is from 1 - 10 or 0.1 - 1. but i want to have them go faster the higher they are. at the moment the way i figured... | [
"At the moment, you seem to be counting up, so, consider this.\nIgnore global_speed for the minute, and just have two speeds, s1 and s2. Given you are effectively saying \"when x is a multiple of s1 or s2, output \"speed1\" or \"speed2\" respectively, a lower value will mean that x is a multiple of that value faste... | [
0,
0
] | [] | [] | [
"math",
"python",
"time"
] | stackoverflow_0008378947_math_python_time.txt |
Q:
Building a generic block-based CMS with Django
A designer recently handed me designs for a site I'm building for a client. They're great designs but I'm really scratching my head as to how I'm going to implement it on the site.
The content can very easily be broken down into blocks or chunks of data where I could ... | Building a generic block-based CMS with Django | A designer recently handed me designs for a site I'm building for a client. They're great designs but I'm really scratching my head as to how I'm going to implement it on the site.
The content can very easily be broken down into blocks or chunks of data where I could allocate a textarea for text input, a couple of char... | [
"Couldn't you implement your 'Blocks' as Django CMS Plugins? Then each page is just constructed from a number of plugins.\nEach plugin has an admin form which gets the specifics for itself, and then the page template renders the plugin as you want it.\nIf you look at the first page of the django-cms demo:\nhttps://... | [
0,
0
] | [] | [] | [
"content_management_system",
"django",
"django_orm",
"python"
] | stackoverflow_0008378877_content_management_system_django_django_orm_python.txt |
Q:
Have pointer to data. Need Numpy array in Fortran order. Want to use Cython
This is a very common use-case for me. I have a C function that returns me a pointer to doubles:
//myheader.h
double *mycfuntion(...)
I know the dimensions of the data that get returned. I also know that the data are Fortran-ordered. I ... | Have pointer to data. Need Numpy array in Fortran order. Want to use Cython | This is a very common use-case for me. I have a C function that returns me a pointer to doubles:
//myheader.h
double *mycfuntion(...)
I know the dimensions of the data that get returned. I also know that the data are Fortran-ordered. I want to write a Cython "shim" to get the data into Python as a Numpy array:
#mysh... | [
"This is a little hackish, but you can reverse the order of your dimensions then return the transpose. This should get your striding correct, but not copy the data.\ncimport numpy as cnp\ncnp.import_array()\n\ncdef double a1[10]\nfor i in range(10):\n a1[i] = i\n\n# C order\na2 = cnp.PyArray_SimpleNewFromData(2... | [
2
] | [] | [] | [
"cython",
"numpy",
"python"
] | stackoverflow_0008366095_cython_numpy_python.txt |
Q:
Filtering GMail messages in Google App Engine application
I would like to build an application in Google App Engine (Python) that would be fully connected to a single GMail account and then filter e-mails from this account (e.g. filter messages for a certain string and show it on the string). In the future I am al... | Filtering GMail messages in Google App Engine application | I would like to build an application in Google App Engine (Python) that would be fully connected to a single GMail account and then filter e-mails from this account (e.g. filter messages for a certain string and show it on the string). In the future I am also going to implement the option to send messages.
What is the ... | [
"What do you mean by \"fully connected\"?\nIt's possible to set up a GMail filter to forward emails to a different address (say, the email address of your App Engine app). And an App Engine app an send emails (say, to a GMail address). The trick is to set up the GMail filter carefully to avoid loops.\n",
"There i... | [
0,
0
] | [] | [] | [
"django",
"gmail",
"google_app_engine",
"python"
] | stackoverflow_0008367381_django_gmail_google_app_engine_python.txt |
Q:
Python have slow db-query, but Perl not
I use python (Django) for my web-shop.
When I tested high loading (db access) got interesting results:
python 10 process = 200sec / 100% CPU utilisation
perl 10 process = 65sec / 35% CPU utilisation
Centos 6, python 2.6, mysql 5.5, standard libraries, mysql-server on othe... | Python have slow db-query, but Perl not | I use python (Django) for my web-shop.
When I tested high loading (db access) got interesting results:
python 10 process = 200sec / 100% CPU utilisation
perl 10 process = 65sec / 35% CPU utilisation
Centos 6, python 2.6, mysql 5.5, standard libraries, mysql-server on other server.
Table product_cars have 70 000 000... | [
"As people have pointed out, the way you're preparing and executing statements between the two is not the same and is not the recommended practice. Both should be taking advantage of prepared statements, and both should be preparing outside the loop.\nHowever, it looks like that Python MySQL driver does not take a... | [
10,
9
] | [] | [] | [
"database",
"mysql",
"perl",
"python"
] | stackoverflow_0008377603_database_mysql_perl_python.txt |
Q:
Redirect my facebook app to the requested url after facebook authentication
I am developing an app for facebook. the problem is suppose a non authenticated user requests the following url in my domain :
http://example.com/name/3242
I redirect it to facebook's oauth page to authenticate the user and authorize the... | Redirect my facebook app to the requested url after facebook authentication | I am developing an app for facebook. the problem is suppose a non authenticated user requests the following url in my domain :
http://example.com/name/3242
I redirect it to facebook's oauth page to authenticate the user and authorize the app, after both, i want facebook to request the same above url in the canvas. An... | [
"See the Facebook docs here: http://developers.facebook.com/docs/authentication/\nYou need to spec the redirect_uri parameter when you send them to Facebook to authenticate. When they successfully authenticate, Facebook will send them back to this URL like so:\nhttp://example.com/name/3242?code=A_CODE_GENERATED_BY_... | [
1
] | [] | [] | [
"facebook",
"html",
"php",
"python"
] | stackoverflow_0008377705_facebook_html_php_python.txt |
Q:
NetworkX draw grid_2d_graph with nodelist value from file
I am trying to draw grid_2d_graph with nodelist values from file.
list1 = [(0,0),(0,1),(1,0)]
nx.draw_networkx_nodes(G, pos, nodelist=list1, node_color='b')
In the above statement, instead of manually setting the nodelist, I want to read the nodelist from... | NetworkX draw grid_2d_graph with nodelist value from file | I am trying to draw grid_2d_graph with nodelist values from file.
list1 = [(0,0),(0,1),(1,0)]
nx.draw_networkx_nodes(G, pos, nodelist=list1, node_color='b')
In the above statement, instead of manually setting the nodelist, I want to read the nodelist from a file. That file will contain the list of nodes that should b... | [
"Here is an approach for storing the node colors as node attributes and saving them in a GraphML format file. Then you can read that file and unpack the nodes and attributes into lists to pass to nx.draw() (or nx.draw_networkx_nodes())\nimport matplotlib.pyplot as plt\nimport networkx as nx\n# create graph \nG=nx.... | [
0
] | [] | [] | [
"graph",
"networkx",
"nodes",
"python"
] | stackoverflow_0008375223_graph_networkx_nodes_python.txt |
Q:
Printing a random amount of characters a random amount of times in one line
Let's assume we only have one line to work with. We have string "fo0", and we want to print each character a random amount of times, and redo that entire statement another random amount of times; Resulting in something like the following:
... | Printing a random amount of characters a random amount of times in one line | Let's assume we only have one line to work with. We have string "fo0", and we want to print each character a random amount of times, and redo that entire statement another random amount of times; Resulting in something like the following:
ffooooo000 ffffffoo00 fffo00000000
How does one go about doing this, using for l... | [
"You can use something like the following. Below, s is the input string, char_rand_max is the maximum number of times a single character is repeated in a word, and str_rand_max is the maximum number of times to produce a word. Each character appears at least once, and there is at least one word.\nimport random\n\nd... | [
4,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008379407_python.txt |
Q:
Opening Multiple Pages with Mechanize in Python
I'm trying to open multiple pages following a certain format using mechanize. I want to start with a certain page, and have mechanize follow all the links that have a certain class or piece of text in a link. For example, the root url would be something like
http://h... | Opening Multiple Pages with Mechanize in Python | I'm trying to open multiple pages following a certain format using mechanize. I want to start with a certain page, and have mechanize follow all the links that have a certain class or piece of text in a link. For example, the root url would be something like
http://hansard.millbanksystems.com/offices/prime-minister
and... | [
"That's not an error - it means that Browser.links() returns an generator object rather than a list.\nAn iterator is an object that acts \"like a list\", meaning that you can do things like\nfor link in links:\n print link\n\nand so on. But you can only access things in whatever order it defines; you can't neces... | [
2
] | [] | [] | [
"mechanize",
"python",
"web_scraping"
] | stackoverflow_0008378556_mechanize_python_web_scraping.txt |
Q:
I'm new to python, I can't tell if this will work or not
import time
varthing = 1
while varthing == 1:
time.sleep(60)
checker = time.strftime("%b, %d", time.localtime())
if checker == "Dec, 25" :
print "It's Christmas"
raw_input("Enter anything to close\n")
varthing = 0
It wor... | I'm new to python, I can't tell if this will work or not | import time
varthing = 1
while varthing == 1:
time.sleep(60)
checker = time.strftime("%b, %d", time.localtime())
if checker == "Dec, 25" :
print "It's Christmas"
raw_input("Enter anything to close\n")
varthing = 0
It works from what I can tell, but It's hard to test if this will wo... | [
"I think it'll work -- though you have the day of Christmas wrong! :) As Michael suggested, you can test by changing your clock (or using tomorrow's date and leaving it overnight).\nHere's a somewhat cleaner version:\nimport time\nwhile time.strftime('%b, %d', time.localtime()) != 'Dec, 24':\n time.sleep(60)\npr... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008379805_python.txt |
Q:
Integrate Pysmell in Kate, how hard will it be?
I want to make a plugin for kate, to support autocompletion of python using pysmell. I don't know where to start and how hard it will be.
As far as I know, kate supports scripting with javasccript, which is ok for me, but I can't find any good documentation on it and... | Integrate Pysmell in Kate, how hard will it be? | I want to make a plugin for kate, to support autocompletion of python using pysmell. I don't know where to start and how hard it will be.
As far as I know, kate supports scripting with javasccript, which is ok for me, but I can't find any good documentation on it and how far it can get, if it is possible to source pysm... | [
"I want to do this. I think that it will be implemented in January of 2012.\nI have other plugins, it's posible that it help you\nhttps://github.com/goinnn/Kate-plugins\n"
] | [
2
] | [] | [] | [
"kate",
"kde_plasma",
"plugins",
"python",
"scripting"
] | stackoverflow_0006796175_kate_kde_plasma_plugins_python_scripting.txt |
Q:
Problems with running cherrypy's hello world example
I'm trying to test cherrypy framework by using example from their site:
import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
cherrypy.quickstart(HelloWorld())
When I run it I get this response in the... | Problems with running cherrypy's hello world example | I'm trying to test cherrypy framework by using example from their site:
import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
cherrypy.quickstart(HelloWorld())
When I run it I get this response in the console:
[05/Dec/2011:00:15:11] ENGINE Listening for SIGH... | [
"By default cherrypy.quickstart is only going to bind to localhost 127.0.0.1, which can be access from the serving computer but not from computers connected to it through the network.\nIf you want to be able to access the site from another computer, you need to set the configuration, like documented in here.\nHere'... | [
13
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0008379747_cherrypy_python.txt |
Q:
Python: Import Exception
Is it possible to import everything except one module from a package?
I need a lot of modules from a particular library that I use in my class, but it looks like it used the same module name for one of the modules that I need.
I need to use set operation and intersection, but when I import... | Python: Import Exception | Is it possible to import everything except one module from a package?
I need a lot of modules from a particular library that I use in my class, but it looks like it used the same module name for one of the modules that I need.
I need to use set operation and intersection, but when I import that library from my class, i... | [
"No, there is no terminology to from ... import * except blah, bleh, bluh. You can either write your own import function to support it, or do something like:\nfrom xyz import *\ndel set\n\nwhich will stop shadowing the built-in set so you can use it again. Then if you need the xyz.set function you can do:\nfrom x... | [
7,
0,
0
] | [] | [] | [
"import",
"intersection",
"python",
"set"
] | stackoverflow_0008379740_import_intersection_python_set.txt |
Q:
What does my error mean?
I'm trying to send a localized email with a new password. It seems it crashes when I try to send the mail:
Traceback (most recent call last):
File "/base/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 174, in Handle
result = handler(self._environ, se... | What does my error mean? | I'm trying to send a localized email with a new password. It seems it crashes when I try to send the mail:
Traceback (most recent call last):
File "/base/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 174, in Handle
result = handler(self._environ, self._StartResponse)
File "/ba... | [
"It looks like your translations mechanism \"_\" is returning a proxy for the translation value. However, message.send() is checking the type and expects a string. Try this change:\nChange this:\nmessage = mail.EmailMessage(sender=senderemail,\n subject=_('Password reset successful'))\n\nto:\nmessage = mail.... | [
4
] | [] | [] | [
"debugging",
"google_app_engine",
"internationalization",
"python"
] | stackoverflow_0008380268_debugging_google_app_engine_internationalization_python.txt |
Q:
The way to make namespace packages in Python
From Namespace Packages in distribute, I know I can make use of namespace packages to separate a big Python package into several smaller ones. It is really awesome. The document also mentions:
Note, by the way, that your project’s source tree must include the
namespa... | The way to make namespace packages in Python | From Namespace Packages in distribute, I know I can make use of namespace packages to separate a big Python package into several smaller ones. It is really awesome. The document also mentions:
Note, by the way, that your project’s source tree must include the
namespace packages’ __init__.py files (and the __init__.p... | [
"A namespace package mainly has a particular effect when it comes time to import a sub-package. Basically, here's what happens, when importing foo.bar\n\nthe importer scans through sys.path looking for something that looks like foo.\nwhen it finds something, it will look inside of the discovered foo for bar.\nif b... | [
45
] | [] | [] | [
"module_packaging",
"namespace_package",
"python",
"setuptools"
] | stackoverflow_0008380381_module_packaging_namespace_package_python_setuptools.txt |
Q:
Python While Not recordset.EOF that wont .MoveNext
I don't really understand why this is happening. Maybe a fresh set of eyes could help.
in the table of an access database, say C:\dbase.mdb, I have a table called tProcedureGroups with two fields, ID and Description.
ID Description
1 DIAGNOSTIC
2 PREVENT... | Python While Not recordset.EOF that wont .MoveNext | I don't really understand why this is happening. Maybe a fresh set of eyes could help.
in the table of an access database, say C:\dbase.mdb, I have a table called tProcedureGroups with two fields, ID and Description.
ID Description
1 DIAGNOSTIC
2 PREVENTATIVE
3 RESTORATIVE
So my recordset should be a l... | [
"In Python you need to call methods explicitly with ().\nSo change: \naccess.MoveNext\n\nto \naccess.MoveNext()\n\n"
] | [
0
] | [] | [] | [
"python",
"python_2.7",
"recordset",
"while_loop",
"win32com"
] | stackoverflow_0008380376_python_python_2.7_recordset_while_loop_win32com.txt |
Q:
Default key for Python builtin max/min functions
The documentation for the built-in functions max and min in Python indicate that the key parameter should operate like it does in the sort function. In other words, I should be able to do this:
a = [1, 2, 3, 4]
max(a, key=None)
However, this raises an error:
TypeEr... | Default key for Python builtin max/min functions | The documentation for the built-in functions max and min in Python indicate that the key parameter should operate like it does in the sort function. In other words, I should be able to do this:
a = [1, 2, 3, 4]
max(a, key=None)
However, this raises an error:
TypeError: 'NoneType' object is not callable
But, if I do so... | [
"You've stumbled on to a difference in the implementation of .sort and max more than a problem with the language.\nlist.sort() takes a keyword argument \"key\" which happens to default to None. This means that the sort method can't tell the difference between you supplying a key=None argument or it just taking on t... | [
23,
8
] | [] | [] | [
"python"
] | stackoverflow_0008380179_python.txt |
Q:
Evaluating strings against boolean truth functions
I've searched and still don't have a clue here, so please bear with me.
I have strings, each corresponding to a particular feature matrix. Examples:
'a' = [-vegetable, +fruit, +apple, -orange]
'o' = [-vegetable, +fruit, -apple, +orange]
't' = [+vegetable, -fruit, ... | Evaluating strings against boolean truth functions | I've searched and still don't have a clue here, so please bear with me.
I have strings, each corresponding to a particular feature matrix. Examples:
'a' = [-vegetable, +fruit, +apple, -orange]
'o' = [-vegetable, +fruit, -apple, +orange]
't' = [+vegetable, -fruit, -apple, -orange]
Note that this is just the notation I'... | [
"You can implement the necessary logic using the set type.\nm = {\n 'a':set(['fruit', 'apple']),\n 'o':set(['fruit', 'orange']),\n 't':set(['vegetable'])\n}\n\npred = lambda f: ('fruit' in f) <= ('apple' in f)\n\n# True/False array\n[ pred(m[f]) for f in 'aoaot' ]\n\n# Number of falses\nsum( not pred(m[f])... | [
0,
0
] | [] | [] | [
"boolean",
"boolean_logic",
"logic",
"nltk",
"python"
] | stackoverflow_0008378706_boolean_boolean_logic_logic_nltk_python.txt |
Q:
Is it possible to run PowerShell and Active Directory commands from cPython?
I have 2 questions about cPython (but not IronPython):
Is it possible to run PowerShell commands from cPython?
Is it possible to run Active Directory commands from cPython?
A:
Depends what you mean by "run commands".
Active directory ... | Is it possible to run PowerShell and Active Directory commands from cPython? | I have 2 questions about cPython (but not IronPython):
Is it possible to run PowerShell commands from cPython?
Is it possible to run Active Directory commands from cPython?
| [
"Depends what you mean by \"run commands\".\nActive directory can be interfaced with via LDAP (with a package like python-ldap) or, if you must, you can always call third party \"commands\" directly using on of the many process control libs for python (like subprocess)\nIn [4]: subprocess.call('hostname')\nrafael-i... | [
0
] | [] | [] | [
"active_directory",
"cpython",
"powershell",
"powershell_2.0",
"python"
] | stackoverflow_0008376270_active_directory_cpython_powershell_powershell_2.0_python.txt |
Q:
Python - Iterating through a large list and putting in queue
I have the for loop code:
people = queue.Queue()
for person in set(list_):
first_name,last_name = re.split(',| | ',person)
people.put([first_name,last_name])
The list being iterated has 1,000,000+ items, it works, but takes a couple seconds to c... | Python - Iterating through a large list and putting in queue | I have the for loop code:
people = queue.Queue()
for person in set(list_):
first_name,last_name = re.split(',| | ',person)
people.put([first_name,last_name])
The list being iterated has 1,000,000+ items, it works, but takes a couple seconds to complete.
What changes can I make to help the processing speed?
Edi... | [
"The question is what is your queue being used for? If it isn't really necessary for threading purposes (or you can work around the threaded access) in this kind of situation, you want to switch to generators - you can think of them as the Python version of Unix shell pipes. So, your loop would look like:\ndef gene... | [
1,
1,
0,
0
] | [] | [] | [
"iteration",
"list",
"python"
] | stackoverflow_0008380699_iteration_list_python.txt |
Q:
conditionals, testing for a number within a range
I want to test a number to see if it is between one and three but I think my solution is ugly and basic.
Can someone suggest something better?
blah = ('woo','blah','foo','bah')
if int(tmpword[2]) >= 1 or int(tmpword[2]) >= len(blah):
return False, bpoints[i... | conditionals, testing for a number within a range | I want to test a number to see if it is between one and three but I think my solution is ugly and basic.
Can someone suggest something better?
blah = ('woo','blah','foo','bah')
if int(tmpword[2]) >= 1 or int(tmpword[2]) >= len(blah):
return False, bpoints[int(tmpword[2])-1]
else:
return False, word
tmp... | [
"if 1 <= int(tmpword[2]) <= len(blah):\n\netc.\nBy the way, your existing code doesn't do what you want either. You probably meant\nif int(tmpword[2]) >= 1 and int(tmpword[2]) <= len(blah):\n\netc.\n",
"def test(tmpword):\n return 1 <= int(tmpword) <= len(blah)\n\n"
] | [
3,
0
] | [] | [] | [
"conditional",
"python"
] | stackoverflow_0008380996_conditional_python.txt |
Q:
Binding the contents of list to display an image when clicked
I want to display an image when an item in a list is clicked, but when I click the item, only one image is being displaying for all the items but the specific item's image is not getting loaded.
from Tkinter import *
import os
from PIL import Image
roo... | Binding the contents of list to display an image when clicked | I want to display an image when an item in a list is clicked, but when I click the item, only one image is being displaying for all the items but the specific item's image is not getting loaded.
from Tkinter import *
import os
from PIL import Image
root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, ... | [
"You are binding your button event to the ListBox not the item in the ListBox, so when you click you get the last one binded. You need to check which item is selected in your handler and open the correct image.\nSomething like:\nfrom Tkinter import *\nimport os\nfrom PIL import Image\n\nroot = Tk()\nscrollbar = Sc... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008381059_python_tkinter.txt |
Q:
Connect to a database url in python where the url is for jdbc
I'm trying to write a Python script that will connect to a Database.
The host URL of the database was given to me in jdbc format:
URL = jdbc:mysql://www.myurl.com:3306/
I can't figure out how to translate that URL into pythonese.
Any help would be app... | Connect to a database url in python where the url is for jdbc | I'm trying to write a Python script that will connect to a Database.
The host URL of the database was given to me in jdbc format:
URL = jdbc:mysql://www.myurl.com:3306/
I can't figure out how to translate that URL into pythonese.
Any help would be appreciated. Thanks
import MySQLdb
conn = MySQLdb.connect(host="????"... | [
"You should use the urlparse.urlparse to parse the jdbc string.\nfrom urlparse import urlparse\njdbc = \"jdbc:mysql://www.myurl.com:3306\"\nresult= urlparse(jdbc)\n\n\nMySQLdb.connect(host=result.host,\n user=result.username,\n passwd=result.password,\n db=\"web3db4\")\... | [
3,
0
] | [] | [] | [
"jdbc",
"mysql",
"python"
] | stackoverflow_0008380909_jdbc_mysql_python.txt |
Q:
How to use FileUploadHandler.upload_complete(self) callback for post-upload processing?
I'm new to python and I need to get the MD5 of a file that is uploaded through the script I'm using. The original scripts were written by this guy at this blog http://www.allbuttonspressed.com/projects/django-filetransfers.
How... | How to use FileUploadHandler.upload_complete(self) callback for post-upload processing? | I'm new to python and I need to get the MD5 of a file that is uploaded through the script I'm using. The original scripts were written by this guy at this blog http://www.allbuttonspressed.com/projects/django-filetransfers.
How can I utilize the upload completed callback to get the MD5?
| [
"I guess what you need is this:\nhttps://stackoverflow.com/a/1131255/534150\njust use the MD5 algo in the uploaded file, and it should work! \n"
] | [
0
] | [] | [] | [
"callback",
"django",
"file_upload",
"python"
] | stackoverflow_0008380046_callback_django_file_upload_python.txt |
Q:
In Python, can I process two variables in one conditional?
Is it possible to simplify this? Perhaps combined the two? Teach me the ways of DRY :-\
o = old_last_result
if o == 7:
old_last_result_msg = result_7
elif o == 12:
old_last_result_msg = result_12
elif o == 23:
old_last_result_msg = result_23
el... | In Python, can I process two variables in one conditional? | Is it possible to simplify this? Perhaps combined the two? Teach me the ways of DRY :-\
o = old_last_result
if o == 7:
old_last_result_msg = result_7
elif o == 12:
old_last_result_msg = result_12
elif o == 23:
old_last_result_msg = result_23
elif o == 24:
old_last_result_msg = result_24
elif o == 103:
... | [
"result_msgs = {\n 7: result_7,\n 12: result_12,\n ...\n}\n\nold_last_result_msg = result_msgs.get(old_last_result,\n \"Error code: #%s\" % old_last_result)\nnew_last_result_msg = result_msgs.get(new_last_result,\n \"Error code: #%s\" % new_last_result)\n\n",
"You can use dictionaries:\nresults = {7: result... | [
9,
2,
1,
0,
0
] | [] | [] | [
"conditional",
"python"
] | stackoverflow_0004834284_conditional_python.txt |
Q:
How do I grab a thumbnail screenshot of many websites?
I have a list of 2500 websites and need to grab a thumbnail screenshot of them. How do I do that?
I could try to parse the sites either with Perl or Python, Mechanize would be a good thing. But I am not so experienced with Perl.
A:
Here is Perl solution:
u... | How do I grab a thumbnail screenshot of many websites? | I have a list of 2500 websites and need to grab a thumbnail screenshot of them. How do I do that?
I could try to parse the sites either with Perl or Python, Mechanize would be a good thing. But I am not so experienced with Perl.
| [
"Here is Perl solution:\n use WWW::Mechanize::Firefox;\n my $mech = WWW::Mechanize::Firefox->new();\n $mech->get('http://google.com');\n\n my $png = $mech->content_as_png();\n\nFrom the docs: \n\nReturns the given tab or the current page rendered as\n PNG image.\nAll parameters are optional. $tab defaults to t... | [
10
] | [] | [] | [
"mechanize",
"perl",
"python"
] | stackoverflow_0008381239_mechanize_perl_python.txt |
Q:
Upload file using POST in python. Where to look?
I want to upload and get the result from this website. http://cello.life.nctu.edu.tw/
I tried
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
register_openers()
params = ({"file": open("xaa", "r"),
... | Upload file using POST in python. Where to look? | I want to upload and get the result from this website. http://cello.life.nctu.edu.tw/
I tried
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
register_openers()
params = ({"file": open("xaa", "r"),
"seqtype": "prot",
"species": "eu"})
datagen, ... | [
"Error 500: Internal Server Error\n\nThis is a server error. In other words there is nothing wrong with your code - it's just this page errors out.\n"
] | [
1
] | [] | [] | [
"post",
"python",
"urllib2"
] | stackoverflow_0008381461_post_python_urllib2.txt |
Q:
how to launch gnome apps with su permissions?
I have a python app I want to distribute as an rpm. The app requires talking to usb devices. To talk to usb devices, I need sudo privileges (or some type of permission I've yet to learn about).
Unfortunately, my app fails to launch from the gnome application menu wit... | how to launch gnome apps with su permissions? | I have a python app I want to distribute as an rpm. The app requires talking to usb devices. To talk to usb devices, I need sudo privileges (or some type of permission I've yet to learn about).
Unfortunately, my app fails to launch from the gnome application menu with a .desktop file when I specify running as sudo.
w... | [
"You want gksudo, not sudo. It's that full-screen modal dialog that prompts for your password:\nEXEC=gksudo python /usr/bin/app_launcher.py %f\n\n"
] | [
2
] | [] | [] | [
"gnome",
"python",
"rpm"
] | stackoverflow_0008381543_gnome_python_rpm.txt |
Q:
How to send a mail to hundreds of thousands recipients in python fast which each of recipients is showed as receiver in mail header?
I'm looking of solutions to send huge number of mails (hundreds of thousands) in Python. I have a list of recipients (in a file), and I want to send a mail to all of them. I want eac... | How to send a mail to hundreds of thousands recipients in python fast which each of recipients is showed as receiver in mail header? | I'm looking of solutions to send huge number of mails (hundreds of thousands) in Python. I have a list of recipients (in a file), and I want to send a mail to all of them. I want each of recipients was show as receiver in mail header, not bcc or cc. Well, my solutions: send a separated mail to each of them not a mail t... | [
"Fastest would be to install a Mail Transfer Agent such as Postfix on your machine and hand all your emails to it for delivery using the /usr/sbin/sendmail mailing interface. Most reasonable mail servers can accept thousands of mail messages for delivery per second and may perform some SMTP pipelining to send a mes... | [
6,
1
] | [] | [] | [
"email",
"python",
"sendmail",
"smtplib"
] | stackoverflow_0008381210_email_python_sendmail_smtplib.txt |
Q:
How to return multiple values from *args?
I have a hello function and it takes n arguments (see below code).
def hello(*args):
# return values
I want to return multiple values from *args. How to do it? For example:
d, e, f = hello(a, b, c)
SOLUTION:
def hello(*args):
values = {} # values
rst = [] # result
... | How to return multiple values from *args? | I have a hello function and it takes n arguments (see below code).
def hello(*args):
# return values
I want to return multiple values from *args. How to do it? For example:
d, e, f = hello(a, b, c)
SOLUTION:
def hello(*args):
values = {} # values
rst = [] # result
for arg in args:
rst.append(values[arg])
... | [
"So, you want to return a new tuple with the same length as args (i.e. len(args)), and whose values are computed from args[0], args[1], etc.\nNote that you can't modify 'args' directly, e.g. you can't assign args[0] = xxx, that's illegal and will raise a TypeError: 'tuple' object does not support item assignment.\n... | [
14,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008381739_python.txt |
Q:
Seeing if values in a list are of equal value ~Python
I was wondering if their is a way to see similar values in a list. So i could say if 2 numbers of the list are of equal value print that number. Thanks for the help
EDIT:
i was wondering if this would work
a = []
v = 0
while v == 1:
n = x - (func1sub/func1... | Seeing if values in a list are of equal value ~Python | I was wondering if their is a way to see similar values in a list. So i could say if 2 numbers of the list are of equal value print that number. Thanks for the help
EDIT:
i was wondering if this would work
a = []
v = 0
while v == 1:
n = x - (func1sub/func1dsub)
a.append(n)
print (a)
d = defaultdict(int)
for v i... | [
">>> from collections import defaultdict\n>>> l = [1,2,2,3]\n>>> d = defaultdict(int)\n>>> for v in l:\n... d[v] += 1\n... \n>>> d\ndefaultdict(<type 'int'>, {1: 1, 2: 2, 3: 1})\n>>> [v for (v,c) in d.iteritems() if c > 1]\n[2]\n\nSo 2 is the only value that appears more than once.\nNote that the time complexity ... | [
2,
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008381656_list_python.txt |
Q:
Combining pygame and twisted
After yesterdays poorly chosen question I'm trying again.
I have a tic tac toe program in the works purely for the purpose of learning network play.
My understanding of twisted was that I should have a server class run the reactor and then have each player connect to it as a client (th... | Combining pygame and twisted | After yesterdays poorly chosen question I'm trying again.
I have a tic tac toe program in the works purely for the purpose of learning network play.
My understanding of twisted was that I should have a server class run the reactor and then have each player connect to it as a client (the server being a separate entity).... | [
"The difficulty of combining pygame with twisted is the issue of who controls the mainloop. This usually comes up with wanting to combine any sort of UI (GTK, Tkinter, etc) mainloop with Twisted, and PyGame is no different.\nWhat I would suggest, is that since network latency is important and since twisted has a v... | [
12
] | [] | [] | [
"pygame",
"python",
"twisted"
] | stackoverflow_0008381850_pygame_python_twisted.txt |
Q:
Update a record in a table in SQLAlchemy and Python
I have some problems when I try to update information in some tables. For example, I have this table:
class Channel(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("channels")
id = Column("id", Integer, primary_key=True)
title = Column("title", ... | Update a record in a table in SQLAlchemy and Python | I have some problems when I try to update information in some tables. For example, I have this table:
class Channel(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("channels")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
hash = Column("hash", String(50))
ru... | [
"I think your code should be either:\nfor chan in channels:\n if rChannel.id == channel.id:\n runtime = channel.runtime\n\nor\nfor chan in channels:\n if rChannel.id == channel.id:\n for item in channel.items:\n if item.id == 0:\n rChannel.items.append(item)\n\nBut not... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003681125_python_sqlalchemy.txt |
Q:
Use different view depending on object model database value in Django
I am launching a 2nd version of a project, and I want the users to be able to upgrade to the new format. It's not going to be a forced upgrade, so essentially, users will say "Make my page a V2 page". The URLs for their pages will stay the same.... | Use different view depending on object model database value in Django | I am launching a 2nd version of a project, and I want the users to be able to upgrade to the new format. It's not going to be a forced upgrade, so essentially, users will say "Make my page a V2 page". The URLs for their pages will stay the same.
I'd like to be able in the view to say:
def v1_page(request, page_id):
... | [
"Function should return result of v2_page call:\ndef v1_page(request, page_id):\n page = get_object_or_404(Page, id=page_id)\n if page.upgraded:\n return v2_page(request, page)\n else:\n # load this page \n\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008381808_django_python.txt |
Q:
Convert list of byte strings to bytearray (byte stream)
I have a list of hex strings representing bytes, of the form "FF". I want to convert the whole list to a byte stream so I can send it over a socket (Python 3). It looks like the bytearray type would work, but I can't find any way to directly convert the lis... | Convert list of byte strings to bytearray (byte stream) | I have a list of hex strings representing bytes, of the form "FF". I want to convert the whole list to a byte stream so I can send it over a socket (Python 3). It looks like the bytearray type would work, but I can't find any way to directly convert the list to a bytearray.
I can do it manually in a loop, but figure ... | [
"hexstrings = [\"DE\", \"AD\", \"BE\", \"EF\"] # big-endian 0xDEADBEEF\n\nbytes = bytearray(int(x, 16) for x in hexstrings)\nbytes = bytearray.fromhex(\"\".join(hexstrings)) # Python 2.6 may need u\"\"\n\nIf you've got a lot of 'em, it might be worthwhile to see which of those is fastest.\n",
"hexlist = [\"... | [
3,
1
] | [
"Refer to :\nchar* PyByteArray_AsString(PyObject *bytearray)\nReturn the contents of bytearray as a char array after checking for a NULL pointer\nfrom the python doc reference\n"
] | [
-1
] | [
"bytearray",
"python",
"python_3.x"
] | stackoverflow_0008382127_bytearray_python_python_3.x.txt |
Q:
access byte by byte in python ctypes class(Structure)
This is a followup question to my question , that was left unanswered
EDIT and organized
from my module:
class t_data_block(Structure):
_fields_ = [("current_readings",c_ulong * PORTS_NUM),
("power_reading",c_ulong)]
class t_sys_flags(Structure):
"... | access byte by byte in python ctypes class(Structure) | This is a followup question to my question , that was left unanswered
EDIT and organized
from my module:
class t_data_block(Structure):
_fields_ = [("current_readings",c_ulong * PORTS_NUM),
("power_reading",c_ulong)]
class t_sys_flags(Structure):
"System flags"
_fields_ = [("Alarm1",c_ulong,1),
... | [
"Check out buffer:\nfrom binascii import hexlify\nx = t_input_buff()\n\nx.header = 1\nx.sys_flags.Alarm1 = 1\nx.sys_flags.Alarm2 = 0\nx.sys_flags.reserved = 0x15555555\nx.data_block[0].current_readings[0] = 2\nx.data_block[0].current_readings[1] = 3\nx.data_block[0].power_reading = 4\nx.data_block[1].current_readin... | [
4,
0,
0
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0008374088_ctypes_python.txt |
Q:
Is there a Python library to handle OWL?
It could be something as big as Jena or something smaller. Do you know anything?
A:
What looks to be the only current and active open source package:
FuXi 1.0: A Python-based, bi-directional logical reasoning system for the semantic web
This is a Java package but it has... | Is there a Python library to handle OWL? | It could be something as big as Jena or something smaller. Do you know anything?
| [
"What looks to be the only current and active open source package:\n\nFuXi 1.0: A Python-based, bi-directional logical reasoning system for the semantic web\n\nThis is a Java package but it has a Python console (via Jython):\n\nProtégé Script Console\n\nA commercial package that has python support:\n\nPython Sesame... | [
20,
15,
10
] | [] | [] | [
"owl",
"python",
"semantic_web"
] | stackoverflow_0001719812_owl_python_semantic_web.txt |
Q:
Networkx: Regenerate the Random Geometric Graph with previously stored Node values and edges in file
I am generating Random Geometric Graph and storing node and edges
information using write_adjlist into file.
Code: python1.py
G=nx.random_geometric_graph(10,0.5)
filename = "ipRandomGrid.txt"
fh=open(filename,... | Networkx: Regenerate the Random Geometric Graph with previously stored Node values and edges in file | I am generating Random Geometric Graph and storing node and edges
information using write_adjlist into file.
Code: python1.py
G=nx.random_geometric_graph(10,0.5)
filename = "ipRandomGrid.txt"
fh=open(filename,'wb')
nx.write_adjlist(G, fh)
nx.draw(G)
plt.show()
Now from the second file I am trying to generate t... | [
"Consider the following interactive session:\n>>> import networkx as nx\n>>> G = nx.random_geometric_graph(10, 0.5)\n>>> with open(\"junk.txt\", \"wb\") as f:\n... nx.write_adjlist(G, f)\n...\n>>> G.nodes()\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> with open(\"junk.txt\", \"rb\") as f:\n... G2 = nx.read_adjlist(f)\n... | [
2
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0008382403_networkx_python.txt |
Q:
What languages other than Python have an explicit self?
It seems a bit weird that Python requires you to explicitly pass self as the first argument to all class functions. Are there other languages that require something similar?
A:
By explicit, do you mean "explicitly passed as an argument to each class functio... | What languages other than Python have an explicit self? | It seems a bit weird that Python requires you to explicitly pass self as the first argument to all class functions. Are there other languages that require something similar?
| [
"By explicit, do you mean \"explicitly passed as an argument to each class function\"?\nIf so, then Python is the only one I know off-hand. \nMost OO languages support this or self in some form, but most of them let you define class functions without always defining self as the first argument.\n",
"Depending on y... | [
5,
4,
4,
3,
2,
1,
0
] | [
"many object oriented languages if not all of them\nfor example c++ support \"this\" instead of \"self\"\nbut you dont have to pass it, it is passed passively\nhope that helps ;)\n"
] | [
-1
] | [
"programming_languages",
"python"
] | stackoverflow_0001865262_programming_languages_python.txt |
Q:
Order by related object attribute in Django/Python
I have a static Object called Module. One of the attributes for a Module object is a 'name'. I have a database table called Section that saves the Module key in a column.
I'd like to fetch the objects from that table and sort by the name of the Module they are rel... | Order by related object attribute in Django/Python | I have a static Object called Module. One of the attributes for a Module object is a 'name'. I have a database table called Section that saves the Module key in a column.
I'd like to fetch the objects from that table and sort by the name of the Module they are related with.
Most of the time, when I reference the Module... | [
"From your code I infer that MODULES is a dictionary of your Module objects, indexed by value by which they are saved in the database. These objects have a name property, so if you modify your example to fetch the object from this dictionary by saved name, you should get what you need:\nnavigation_links = sorted(na... | [
0
] | [] | [] | [
"django",
"django_queryset",
"python",
"sorting"
] | stackoverflow_0008382407_django_django_queryset_python_sorting.txt |
Q:
Convert '229, 255, 66' to (229, 255, 66) in Python
I want to do a simple conversion of u'229, 255, 66' to (229, 255, 66)
Is there a very simple way to do this? Or do I need to split, convert to int, etc...
A:
The easy way is to use the function ast.literal_eval() which has none of the security issues of using e... | Convert '229, 255, 66' to (229, 255, 66) in Python | I want to do a simple conversion of u'229, 255, 66' to (229, 255, 66)
Is there a very simple way to do this? Or do I need to split, convert to int, etc...
| [
"The easy way is to use the function ast.literal_eval() which has none of the security issues of using eval:\n>>> from ast import literal_eval\n>>> literal_eval(u'229, 255, 66')\n(229, 255, 66)\n\n",
"Builtin function eval() will return a tuple, no splitting needed (as per your question).\n\neval('299, 255, 66') ... | [
15,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008382893_python.txt |
Q:
Is there an SQLAlchemy equivalent of django-evolution?
All I want is to have a workflow somewhat similar to:
Add django_evolution to the INSTALLED_APPS for your project
Run ./manage.py syncdb
Make modifications to the model files in your project
Run ./manage.py evolve --hint --execute
Which is super simple and e... | Is there an SQLAlchemy equivalent of django-evolution? | All I want is to have a workflow somewhat similar to:
Add django_evolution to the INSTALLED_APPS for your project
Run ./manage.py syncdb
Make modifications to the model files in your project
Run ./manage.py evolve --hint --execute
Which is super simple and even though it doesn't support advanced features (like multip... | [
"The creator of SQLAlchemy recently started working on Alembic. While it's still young (version 0.1), it may suits your needs.\n",
"I think you already tried your hand on DJango :). These are the functionality right now not available with current SQLAlchemy. Suggested by @madjar you can use development version of... | [
2,
2
] | [] | [] | [
"database",
"django",
"python",
"sqlalchemy",
"sqlalchemy_migrate"
] | stackoverflow_0008382690_database_django_python_sqlalchemy_sqlalchemy_migrate.txt |
Q:
Using Mock() in Python
Can you give some clear examples of uses of the Mock() in Django unittests?
I want to understand it more clearly.
Update: I've figured out some things, so I share it below.
A:
Part 1: Basics
from mock import Mock
Mock object is an object that is a kind of a Dummy for the code that
we want... | Using Mock() in Python | Can you give some clear examples of uses of the Mock() in Django unittests?
I want to understand it more clearly.
Update: I've figured out some things, so I share it below.
| [
"Part 1: Basics\nfrom mock import Mock\n\nMock object is an object that is a kind of a Dummy for the code that\nwe want not to be executed, but for which we want to know some information (number of calls, call arguments). Also we might want to specify a return value for that code.\nLet us define simple function:\nd... | [
19,
1
] | [] | [] | [
"mocking",
"python",
"unit_testing"
] | stackoverflow_0007556161_mocking_python_unit_testing.txt |
Q:
How do I update/redraw a GTK Widget (GTKLabel) internally without a key press event using python?
I have some code below that is attempting to update a GTK Label element. I'm including two files: the ui file and the py file.
UI file:
<glade-interface>
<widget class="GtkWindow" id="ApplicationFrame">
<pro... | How do I update/redraw a GTK Widget (GTKLabel) internally without a key press event using python? | I have some code below that is attempting to update a GTK Label element. I'm including two files: the ui file and the py file.
UI file:
<glade-interface>
<widget class="GtkWindow" id="ApplicationFrame">
<property name="width_request">320</property>
<property name="height_request">240</property>
<prope... | [
"You'll want to use the Widget's queue_draw function:\n\nThe queue_draw_area() method invalidates the rectangular area of the widget (...) by calling the gtk.gdk.Window.invalidate_rect() method on the widget's window and all its child windows.\n\nBut, as you are already doing that in your set method, my guess is th... | [
10,
2
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0008381631_gtk_pygtk_python.txt |
Q:
Python Regex for hyphenated words
I'm looking for a regex to match hyphenated words in Python.
The closest I've managed to get is: '\w+-\w+[-w+]*'
text = "one-hundered-and-three- some text foo-bar some--text"
hyphenated = re.findall(r'\w+-\w+[-\w+]*',text)
which returns list ['one-hundered-and-three-', 'foo-bar']... | Python Regex for hyphenated words | I'm looking for a regex to match hyphenated words in Python.
The closest I've managed to get is: '\w+-\w+[-w+]*'
text = "one-hundered-and-three- some text foo-bar some--text"
hyphenated = re.findall(r'\w+-\w+[-\w+]*',text)
which returns list ['one-hundered-and-three-', 'foo-bar'].
This is almost perfect except for the... | [
"Try this:\nre.findall(r'\\w+(?:-\\w+)+',text)\n\nHere we consider a hyphenated word to be:\n\na number of word chars\nfollowed by any number of: \n\na single hyphen\nfollowed by word chars\n\n\n"
] | [
31
] | [] | [] | [
"hyphenation",
"python",
"regex"
] | stackoverflow_0008383213_hyphenation_python_regex.txt |
Q:
I have no idea what is wrong with this code?
Possible Duplicate:
I'm new to python, I can't tell if this will work or not
import time
from sys import stdout
varthing = 1
while varthing == 1:
time.sleep(1)
checker = time.strftime("\r%b, %d %H:%M:%S", time.localtime())
print checker,
stdout.flush()... | I have no idea what is wrong with this code? |
Possible Duplicate:
I'm new to python, I can't tell if this will work or not
import time
from sys import stdout
varthing = 1
while varthing == 1:
time.sleep(1)
checker = time.strftime("\r%b, %d %H:%M:%S", time.localtime())
print checker,
stdout.flush()
if checker == "Dec, 25 00:00:00" :
p... | [
"\nYour strftime format starts with \\r. Why? The string you are testing against in the if statement will never match because it doesn't start with \\r.\ntime.sleep(1) is not guaranteed to sleep for exactly one second. It might sleep longer and you'll miss the one-second window in which checker would match the s... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0008381192_python.txt |
Q:
Django: record creation problems when language changed
In the form I've date field in the MM/DD/YYYY format it works well when the language is set to english when another locale selected it becomes unable to create record in the database due to the incorrect date format error. The date is manually selected from th... | Django: record creation problems when language changed | In the form I've date field in the MM/DD/YYYY format it works well when the language is set to english when another locale selected it becomes unable to create record in the database due to the incorrect date format error. The date is manually selected from the user interface.
Is there any issues on this problem, may b... | [
"Before you insert your value into the database use \"strftime\".\nHow to print date in a regular format in Python?\n"
] | [
0
] | [] | [] | [
"django",
"locale",
"python"
] | stackoverflow_0008381920_django_locale_python.txt |
Q:
How to avoid resize figures with matplotlib when exporting to PDF?
I'm using Python 2.7 and Matplotlib to generate a multiple chart report.
I want produce this report to be exported as a PDF document.
I want to set the size of each page (12 inches width x 18 inches height). I'm using the code below, but what I ge... | How to avoid resize figures with matplotlib when exporting to PDF? | I'm using Python 2.7 and Matplotlib to generate a multiple chart report.
I want produce this report to be exported as a PDF document.
I want to set the size of each page (12 inches width x 18 inches height). I'm using the code below, but what I get is a document with a page size that depends on the size of my computer... | [
"Not sure whether this works for PDF export also, but you can try setting the figure resolution explicitly, e.g.\npp.savefig(dpi=100)\n\nAt least for PNG export this produces a predictable image size for a given figure size.\n"
] | [
0
] | [] | [] | [
"matplotlib",
"pdf_generation",
"python",
"python_2.7"
] | stackoverflow_0008383945_matplotlib_pdf_generation_python_python_2.7.txt |
Q:
Google App Engine error when trying to start web development in Python
I am novice with python, I have already gone through the basics with command line via using eclipse. Now want to create some web pages, I referred given link and did excatly the same, (http://www.vogella.de/articles/GoogleAppEngine/article.html... | Google App Engine error when trying to start web development in Python | I am novice with python, I have already gone through the basics with command line via using eclipse. Now want to create some web pages, I referred given link and did excatly the same, (http://www.vogella.de/articles/GoogleAppEngine/article.html#app_python) path of my app-engine is (/home/abc/google_appengine) and my wo... | [
"Do you have app.yml file with correct config in your work-directory? If you do have app.yml, you probably are providing wrong directory for dev_appserver.py.\nYou have to run it like this:\npython dev_appserver.py <directory-with-app.yml>\n\nFirst try to run it without eclipse - run it from your terminal. Then try... | [
3,
0
] | [] | [] | [
"eclipse",
"google_app_engine",
"pydev",
"python"
] | stackoverflow_0008383248_eclipse_google_app_engine_pydev_python.txt |
Q:
Searching an input string for occurences of integers and characters using a single regular expression in Python
I have an input string which is considered valid only if it contains:
At least one character in [a-z]
At least one integer in [0-9], and
At least one character in [A-Z]
There is no constraint on the or... | Searching an input string for occurences of integers and characters using a single regular expression in Python | I have an input string which is considered valid only if it contains:
At least one character in [a-z]
At least one integer in [0-9], and
At least one character in [A-Z]
There is no constraint on the order of occurrence of any of the above. How can I write a single regular expression that validates my input string ?
| [
"Try this\n^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$\n\nSee it here online on Regexr\nThe ^ and $ are anchors which bind the pattern to the start and the end of the string.\nThe (?=...) are lookahead assertions. they check if the pattern after the = is ahead but they don't match it. So to match something there needs to... | [
5,
5
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008383969_python_regex.txt |
Q:
NumPy C extension with SWIG unknown length array
I would like to wrap a C function with SWIG.
The function takes a couple arrays (of the same length) as input and returns three more arrays.
It is however not possible to predict the length of the return arrays beforehand and these are dynamically allocated in the f... | NumPy C extension with SWIG unknown length array | I would like to wrap a C function with SWIG.
The function takes a couple arrays (of the same length) as input and returns three more arrays.
It is however not possible to predict the length of the return arrays beforehand and these are dynamically allocated in the function.
Is it possible to wrap such a function with S... | [
"It seems that SWIG (or any other Python wrapper generator for that matter) cannot do this.\nI ended up writing the Python wrapper by hand, which is actually quite easy, using PyArray_SimpleNew or PyArray_SimpleNewFromData to create the output arrays.\nWith the latter one has to be extra careful so as to not genera... | [
1
] | [] | [] | [
"c",
"numpy",
"python",
"swig"
] | stackoverflow_0007929162_c_numpy_python_swig.txt |
Q:
Scrapy is redirecting direct links
I am using CrawlSpider to crawl and extract data from a webpage.
The start url has only one link (which is a direct link) and from that link data has to be scraped (data is being successfully scraped if I use BaseSpider and give the direct link). However, when I run the CrawlSpi... | Scrapy is redirecting direct links | I am using CrawlSpider to crawl and extract data from a webpage.
The start url has only one link (which is a direct link) and from that link data has to be scraped (data is being successfully scraped if I use BaseSpider and give the direct link). However, when I run the CrawlSpider, it is getting some weired 301 reque... | [
"I think you should remove everything after ? in your url so it will become: http://www.flipkart.com/office-supplies/pen/faber-castell/itmd4fpkgkd7e3fj\nUpdate:\nIn most cases attributes in query string are only used for things that do not affect content, for example: from which page you came here, which menu item ... | [
2
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0008383939_python_scrapy.txt |
Q:
URLOpen error during Web Service communication
I had to developed an application which will communicate with a Web service via python. I have to run this code on a Windows server machine for some reasons (which i am not much experianced with, notmally we use uint based systems).
My communication with the api provi... | URLOpen error during Web Service communication | I had to developed an application which will communicate with a Web service via python. I have to run this code on a Windows server machine for some reasons (which i am not much experianced with, notmally we use uint based systems).
My communication with the api provider is not directly because of some communication is... | [
"After some search based on urlopen error [Errno 10060], i decided to try proxy usage and it turns out to be the solution!\nIf WSDL url is \n\nhttp://someurl.com:1234/something/somethingmore.asmx?WSDL\n\nthen using:\nprxy = dict(http='http://someurl.com:1234/')\nClient.set_options(proxy=prxy)\n\ndefinitely solves t... | [
0
] | [] | [] | [
"python",
"suds",
"web_services"
] | stackoverflow_0008368026_python_suds_web_services.txt |
Q:
Equivalent function for xticks for an AxesSubplot object
So I am trying to use Axes objects to control my matlibplot figure. I am not using plt (aka import matlibplot.pyplot as plt) because I am embedding the figure in my tkinter GUI per this.
However, I am also using subplots in the figure, so something like:
a ... | Equivalent function for xticks for an AxesSubplot object | So I am trying to use Axes objects to control my matlibplot figure. I am not using plt (aka import matlibplot.pyplot as plt) because I am embedding the figure in my tkinter GUI per this.
However, I am also using subplots in the figure, so something like:
a = f.add_subplot(121)
a2 = f.add_subplot(122)
a.plot(fn2,mag)
a... | [
"you can use instead:\naxes.set_xticks(ticks, minor=False)\n\nand\naxes.set_xticklabels(labels, fontdict=None, minor=False)\n\n"
] | [
111
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0008384120_matplotlib_python_tkinter.txt |
Q:
I have a twisted reactor running, how do I connect to it?
I've been following the tutorials and now have a twisted reactor running. I've used telnet to test that it does stuff but I've not managed to find anything in the twisted tutorials on how to connect to the reactor.
My assumption was there would be something... | I have a twisted reactor running, how do I connect to it? | I've been following the tutorials and now have a twisted reactor running. I've used telnet to test that it does stuff but I've not managed to find anything in the twisted tutorials on how to connect to the reactor.
My assumption was there would be something within twisted to do this, should I instead use the built in s... | [
"Here's a small example of a client capable of connecting to your server above.\nfrom twisted.internet.protocol import ClientFactory\nfrom twisted.protocols.basic import LineReceiver\nfrom twisted.internet import reactor\n\nclass TTTClientProtocol(LineReceiver):\n def lineReceived(self, line):\n line = li... | [
3
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0008379110_python_twisted.txt |
Q:
Django MySQL How to stop foreign key constraint?
I have a model like this:
from django.db import models
class House(models.Model):
address = models.CharField(max_length=200)
price = models.CharField(max_length=200)
class Inhabitant(models.Model):
home = models.ForeignKey(House, blank=True, null=True,... | Django MySQL How to stop foreign key constraint? | I have a model like this:
from django.db import models
class House(models.Model):
address = models.CharField(max_length=200)
price = models.CharField(max_length=200)
class Inhabitant(models.Model):
home = models.ForeignKey(House, blank=True, null=True, on_delete=models.SET_NULL)
name = models.CharFiel... | [
"The foreign key don't means that you can not add an inhabitant without a house. \nThe constraint says: 'if Inhabitant.house contains a value then this value must appear in House model'.\nTo verify that database allow inhabitants withou house you should check that house field inhabitant table allow NULL values.\n"
... | [
2
] | [] | [] | [
"django",
"django_models",
"mysql",
"python"
] | stackoverflow_0008384407_django_django_models_mysql_python.txt |
Q:
Python: Concise / elegant way to reformat a set of text files?
I have written a python script to process a set of ASCII files within a given dir. I wonder if there is a more concise and/or "pythonesque" way to do it, without loosing readability?
Python Code
import os
import fileinput
import glob
import string
ind... | Python: Concise / elegant way to reformat a set of text files? | I have written a python script to process a set of ASCII files within a given dir. I wonder if there is a more concise and/or "pythonesque" way to do it, without loosing readability?
Python Code
import os
import fileinput
import glob
import string
indir='./'
outdir='./processed/'
for filename in glob.glob(indir+'*.as... | [
"Other than a few minor changes, due to how Python has changed through time, this looks fine.\nYou're mixing two different styles of next(); the old way was it.next() and the new is next(it). You should use the string method split() instead of going through the string module (that module is there mostly for backwar... | [
5,
1,
0,
0
] | [] | [] | [
"ascii",
"process",
"python"
] | stackoverflow_0008384384_ascii_process_python.txt |
Q:
Non-blocking Thrift Server in Python
In below code snippet, I am trying to make a non-blocking thrift server in python.
# set handler to our implementation
handler = ServiceHandler()
processor = MyService.Processor(handler)
transport = TSocket.TServerSocket(port=port)
tfactory = TTransport.TF... | Non-blocking Thrift Server in Python | In below code snippet, I am trying to make a non-blocking thrift server in python.
# set handler to our implementation
handler = ServiceHandler()
processor = MyService.Processor(handler)
transport = TSocket.TServerSocket(port=port)
tfactory = TTransport.TFramedTransport(transport)
pfactory =... | [
"I found some working Thrift code and it looks like your tfactory needs to be a TBufferedTransportFactory and not a TBufferedTransport instance. \ntfactory = TTransport.TBufferedTransportFactory()\n\n"
] | [
9
] | [] | [] | [
"nonblocking",
"python",
"thrift",
"thrift_protocol"
] | stackoverflow_0008384326_nonblocking_python_thrift_thrift_protocol.txt |
Q:
mpi4py installation in mac
I'm trying to install mpi4py on mac, but I've faced with below error:
Searching for mpi4py
Best match: mpi4py 1.2.2
Downloading http://mpi4py.googlecode.com/files/mpi4py-1.2.2.tar.gz
Processing mpi4py-1.2.2.tar.gz
Running mpi4py-1.2.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install... | mpi4py installation in mac | I'm trying to install mpi4py on mac, but I've faced with below error:
Searching for mpi4py
Best match: mpi4py 1.2.2
Downloading http://mpi4py.googlecode.com/files/mpi4py-1.2.2.tar.gz
Processing mpi4py-1.2.2.tar.gz
Running mpi4py-1.2.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-HNJHvI/mpi4py-1.2.2/egg-dist-tm... | [
"Error message is pretty clear, it looks for MacOSX10.5.sdk, you have to install it from XCode (it's in the installer options).\nTo install it try the following:\n\ndownload XCode 3.2.6\nopen the meta package (right clik-> show bundle content)\ninstall OSX-10.5.pkg\n\nEDIT before doing this painful stuff you might ... | [
0
] | [] | [] | [
"mpi",
"openmpi",
"python"
] | stackoverflow_0008385040_mpi_openmpi_python.txt |
Q:
Executing commands from Python script
I am working on automation of flashing process of a development board.
I have an command line flashing tool which allows me to execute various commands required for flashing the board.
I am trying automate the same with a Python script.
I am using subProcess.Popen to start the... | Executing commands from Python script | I am working on automation of flashing process of a development board.
I have an command line flashing tool which allows me to execute various commands required for flashing the board.
I am trying automate the same with a Python script.
I am using subProcess.Popen to start the .exe and then I need to execute other comm... | [
"You can use os.system() ( http://docs.python.org/library/os.html#os.system ) to execute another program out of python.\n",
"Guessing from your question, you are trying to execute a series commands right?\nFor example:\nfilename.exe arg1 arg2\nfile2.exe arg3 arg4\n\nThe easiest way to do that is:\nimport subproce... | [
0,
0,
0,
0
] | [] | [] | [
"build_automation",
"python"
] | stackoverflow_0008385089_build_automation_python.txt |
Q:
ValueError in Python
Traceback (most recent call last):
File "filter_import.py", line 77, in <module>
get(sys.argv[1])
File "filter_import.py", line 35, in get
timestamp, ip, hash_value = lines.split()
ValueError: need more than 2 values to unpack
I got this error message when I run my cod... | ValueError in Python | Traceback (most recent call last):
File "filter_import.py", line 77, in <module>
get(sys.argv[1])
File "filter_import.py", line 35, in get
timestamp, ip, hash_value = lines.split()
ValueError: need more than 2 values to unpack
I got this error message when I run my code filter_import, can anyon... | [
"The line in question doesn't provide two values, so the \"unpacking\" of split()'s return value into the two variables timestamp, ip and hash_value is failing.\nHere's a stand-alone reproduction of the error:\n>>> a,b,c = \"foo\".split()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0008385477_python.txt |
Q:
relativedelta in Python 2.4
How can I get the month-ago date in Python 2.4?
In Python 2.5 it's easy:
onemonthago = datetime.date.today() + relativedelta(months = -1)
A:
relativedelta is a python-dateutil function, and dateutil is python2.4 compatible, so you should be able to use the same if you have dateutil in... | relativedelta in Python 2.4 | How can I get the month-ago date in Python 2.4?
In Python 2.5 it's easy:
onemonthago = datetime.date.today() + relativedelta(months = -1)
| [
"relativedelta is a python-dateutil function, and dateutil is python2.4 compatible, so you should be able to use the same if you have dateutil installed.\n"
] | [
3
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0008385544_datetime_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.