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: Next-gen social network built with Python. Possible? Pre-mature? Stupid? I just want to test the waters here. Do you think it would be worth it for a massive-scale social network to be built with Python? Given that Python web development is still fairly experimental at such a large scale, do you think, objectively...
Next-gen social network built with Python. Possible? Pre-mature? Stupid?
I just want to test the waters here. Do you think it would be worth it for a massive-scale social network to be built with Python? Given that Python web development is still fairly experimental at such a large scale, do you think, objectively, that its purported advantages over PHP (high-performance object-oriented exe...
[ "\nGiven that Python web development is still fairly experimental at such a large scale\n\nThis is demonstrably false. TwoThree cases in point: reddit, Disqus, YouTube.\nWhen you hit “massive scale”, you're going to have problems no matter what language/framework/tools you use (although some will certainly make tho...
[ 5 ]
[]
[]
[ "performance", "php", "python", "scalability", "social_networking" ]
stackoverflow_0005426761_performance_php_python_scalability_social_networking.txt
Q: Why is this algorithm worse? In Wikipedia this is one of the given algorithms to generate prime numbers: def eratosthenes_sieve(n): # Create a candidate list within which non-primes will be # marked as None; only candidates below sqrt(n) need be checked. candidates = [i for i in range(n + 1)] fin ...
Why is this algorithm worse?
In Wikipedia this is one of the given algorithms to generate prime numbers: def eratosthenes_sieve(n): # Create a candidate list within which non-primes will be # marked as None; only candidates below sqrt(n) need be checked. candidates = [i for i in range(n + 1)] fin = int(n ** 0.5) # Loop over t...
[ "The question is, why would it even be faster? In both examples you are filtering multiples of two, the hard way. It doesn't matter whether you hardcode candidates[4::2] = [None] * (n // 2 - 1) or that it gets executed in the first loop of for i in range(2, fin + 1):.\nIf you are interested in an optimized sieve of...
[ 2, 2, 0, 0 ]
[]
[]
[ "algorithm", "primes", "python" ]
stackoverflow_0005426237_algorithm_primes_python.txt
Q: Vertical Histogram in Python I'm trying to put text in to a vertical histogram using the length of words and the frequency of those lengths as variables. I can do it easily horizontally, but I'm totally lost when it comes to going vertical. (yes, new to Python and programming in general) I only want to use built-i...
Vertical Histogram in Python
I'm trying to put text in to a vertical histogram using the length of words and the frequency of those lengths as variables. I can do it easily horizontally, but I'm totally lost when it comes to going vertical. (yes, new to Python and programming in general) I only want to use built-in modules for Python 3 Here's what...
[ "Here you go:\n#!/usr/bin/env python\nimport fileinput\n\nfreq = {}\nmax_freq = 0\n\nfor line in fileinput.input():\n length = len(line)\n freq[length] = freq.get(length, 0) + 1\n if freq[length] > max_freq:\n max_freq = freq[length]\n\nfor i in range(max_freq, -1, -1):\n for length in sorted(fre...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005426639_python.txt
Q: Removing or disabling a resizable Tkinter window maximise button under Windows Looking for advice on how to remove or disable a resizable window's maximize button under Windows. I'm using Python 2.7 for Windows. Background: I have a resizable window with min and max sizes set via the window's minsize() and maxsize...
Removing or disabling a resizable Tkinter window maximise button under Windows
Looking for advice on how to remove or disable a resizable window's maximize button under Windows. I'm using Python 2.7 for Windows. Background: I have a resizable window with min and max sizes set via the window's minsize() and maxsize() methods. When a user clicks the maximize button, the window moves to the upper le...
[ "One possibility is to set the window as a tool window but this also comes with side effects; the window will no longer appear in the taskbar and will have a thin title bar. It will still be able to be resized at the edges.\nroot.attributes(\"-toolwindow\", 1)\n\nMore about the root attributes can be found in this ...
[ 4 ]
[]
[]
[ "events", "maximize", "python", "tkinter", "windows" ]
stackoverflow_0004333341_events_maximize_python_tkinter_windows.txt
Q: How to wrap Objective-C, to be called from Python? I have created an objective-C framework that I would like to import and access through a python script. I understand how to import this stuff in Python, but what do i need to do on the obj-c side to make that framework importable? Thanks A: You'll want to use P...
How to wrap Objective-C, to be called from Python?
I have created an objective-C framework that I would like to import and access through a python script. I understand how to import this stuff in Python, but what do i need to do on the obj-c side to make that framework importable? Thanks
[ "You'll want to use PyObjC, as Chuck said. Specifically, I'd suggest getting the source, which contains a collection of scripts, pyobjc-metadata (here's the readme), that doesn't seem to be included in the default Apple installation, for wrapping a framework, generating the metadata the Python side needs, and so fo...
[ 6, 5, 2 ]
[]
[]
[ "objective_c", "python", "scripting_bridge", "wrapper" ]
stackoverflow_0005425725_objective_c_python_scripting_bridge_wrapper.txt
Q: Moving code out of __init__.py but keeping backwards compatibility I'm working on a Python project where a previous developer placed a large portion of the code in the base __init__.py file. I would like to be able to move code out of the file to a new file in a subdirectory. spam/ __init__.py foobar/ ...
Moving code out of __init__.py but keeping backwards compatibility
I'm working on a Python project where a previous developer placed a large portion of the code in the base __init__.py file. I would like to be able to move code out of the file to a new file in a subdirectory. spam/ __init__.py foobar/ __init__.py eggs.py So importing the spam module would use ...
[ "100% compatibility is probably not possible. A few things (like pickle) really care about where something is defined.\nYou can get most of the compatibility by importing the classses/functions in the __init__.py file.\n", "Adding from foobar import * in spam/__init__.py should be sufficient to get everything in ...
[ 3, 0, 0 ]
[]
[]
[ "backwards_compatibility", "python" ]
stackoverflow_0005427204_backwards_compatibility_python.txt
Q: Get a more precise timer in python Given this example code: start = time.clock() while (abs(x**2 - userInput) > epsilon): x = 0.5 * (x + (userInput/x)) count = count+1 end = time.clock() print(end-start) And given that this operation, take very little time, how can I get a more precise timer? I have l...
Get a more precise timer in python
Given this example code: start = time.clock() while (abs(x**2 - userInput) > epsilon): x = 0.5 * (x + (userInput/x)) count = count+1 end = time.clock() print(end-start) And given that this operation, take very little time, how can I get a more precise timer? I have looked at timeit module but could not fig...
[ "Using timeit is simple. A Timer instance takes two strings, the first containing the operations to time, and the second containing setup operations that are performed once before timing begins. The following code should work, just change the variable values to whatever you want.\nimport math\nimport time\nfrom tim...
[ 2, 0 ]
[]
[]
[ "milliseconds", "precision", "python", "timer" ]
stackoverflow_0005426961_milliseconds_precision_python_timer.txt
Q: Use non-ascii characters in an app engine application How can I handle a non-ascii url in App Engine? For example http://example.org/Ñöñ-ÅŞÇİİ. application = webapp.WSGIApplication([("/Ñöñ-ÅŞÇİİ", MainPage)], debug=True) I have tried putting # -- coding: utf-8 -- but it didn't work. Edit: I get HTTP 404 Not Found...
Use non-ascii characters in an app engine application
How can I handle a non-ascii url in App Engine? For example http://example.org/Ñöñ-ÅŞÇİİ. application = webapp.WSGIApplication([("/Ñöñ-ÅŞÇİİ", MainPage)], debug=True) I have tried putting # -- coding: utf-8 -- but it didn't work. Edit: I get HTTP 404 Not Found.
[ "The rules are matched against the URLEncoded form of the string, so you need to use that instead. You can see this by looking at the logs for the dev_appserver, where you should see something like this:\nINFO 2011-03-25 00:59:56,577 dev_appserver.py:3317] \"GET /%C3%91%C3%B6%C3%B1-%C3%85%C5%9E%C3%87%C4%B0%C4%B...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005427164_google_app_engine_python.txt
Q: MySQLdb python problem refresh database I have wrote a python daemon for read a database... I do the next: db.connect('localhost', user, pass, database) while true: cursor = db.cursor() sql = "SELECT id FROM task WHERE status='pending'" r = cursor.execute(sql) if r != 0: result = cursor.fet...
MySQLdb python problem refresh database
I have wrote a python daemon for read a database... I do the next: db.connect('localhost', user, pass, database) while true: cursor = db.cursor() sql = "SELECT id FROM task WHERE status='pending'" r = cursor.execute(sql) if r != 0: result = cursor.fetchall() #..... The problem is that: ...
[ "This is just a guess since I don't have a full view of your code, but since you're connecting outside the loop any changes to database won't tell db to reconnect.\nAgain just a guess, not sure if you're threading or not threading, how the change coincides with the daemon... etc\n", "I have soluted it activating ...
[ 0, 0 ]
[]
[]
[ "mysql_python", "python" ]
stackoverflow_0005424128_mysql_python_python.txt
Q: Connecting methods Python I am currently using Oauth to allow a user to sign in through Foursquare, I then create a new session for this user. If the user is new to the system they are asked to sign in through Hunch, this can then generate a user profile based on information from both systems. I have them both sig...
Connecting methods Python
I am currently using Oauth to allow a user to sign in through Foursquare, I then create a new session for this user. If the user is new to the system they are asked to sign in through Hunch, this can then generate a user profile based on information from both systems. I have them both signing in to each application sep...
[ "You can create a parent association so that SiteUser is the parent of FoursquareAuth and HunchAuth.\nWhen the user first logs in with Foursquare you create the SiteUser model and then create the FoursquareAuth model with parent=just_created_user. Then when you send the user off to authenticate through hunch you i...
[ 0, 0 ]
[]
[]
[ "datastore", "foursquare", "google_app_engine", "oauth", "python" ]
stackoverflow_0005424339_datastore_foursquare_google_app_engine_oauth_python.txt
Q: Django: Catch/Log exceptions when using gevent-socketio and WSGIHandler I'm extending upon the ideas presented in Cody Soyland's blog post on gevent-socketio here: http://codysoyland.com/2011/feb/6/evented-django-part-one-socketio-and-gevent/ But I am having trouble finding where exceptions are being swallowed up....
Django: Catch/Log exceptions when using gevent-socketio and WSGIHandler
I'm extending upon the ideas presented in Cody Soyland's blog post on gevent-socketio here: http://codysoyland.com/2011/feb/6/evented-django-part-one-socketio-and-gevent/ But I am having trouble finding where exceptions are being swallowed up. Any errors that occur during the socketio loop seem to dissapear and executi...
[ "This fixed it\nimport sys\nimport traceback\nfrom django.core.signals import got_request_exception\n\ndef exception_printer(sender, **kwargs):\n print >> sys.stderr, ''.join(traceback.format_exception(*sys.exc_info()))\n\ngot_request_exception.connect(exception_printer)\n\n" ]
[ 5 ]
[]
[]
[ "django", "gevent", "python", "wsgi" ]
stackoverflow_0005414409_django_gevent_python_wsgi.txt
Q: Help Cleaning up a bit of Python Code Below i have a bit of code which assigns values based on the values within the tuple tup. Now this bit of code is too repetitive for my tastes and i'd like to be able to use a loop with it. Snippet: self.Levels = tup[0] self.MaxX = tup[1] self.MaxY = tup[2] ...
Help Cleaning up a bit of Python Code
Below i have a bit of code which assigns values based on the values within the tuple tup. Now this bit of code is too repetitive for my tastes and i'd like to be able to use a loop with it. Snippet: self.Levels = tup[0] self.MaxX = tup[1] self.MaxY = tup[2] self.BW = tup[3] I'd like to do some...
[ "Try this:\nself.Levels, self.MaxX, self.MaxY, self.BW = tup\n\nIt's called unpacking the tuple.\n", "Based on the revised snippet:\nattrs = ('Levels', 'MaxX', 'MaxY', 'BW')\nassert len(tup) == len(attrs)\nfor attr, val in zip(attrs, tup):\n if val is not None: # don't use !=\n setattr(self, attr, val)\...
[ 5, 2, 0 ]
[]
[]
[ "python", "tuples", "variables" ]
stackoverflow_0005427257_python_tuples_variables.txt
Q: How in Python can I call a function with a variable which is store as a string I have problem similar to describe here, but a bit more complicated. There are BeautifulSoup objects (store in list) and I want to find some other tags. The information which tags I want to find are store in strings. I.e.: a= [...] #(l...
How in Python can I call a function with a variable which is store as a string
I have problem similar to describe here, but a bit more complicated. There are BeautifulSoup objects (store in list) and I want to find some other tags. The information which tags I want to find are store in strings. I.e.: a= [...] #(list of BeautifulSoup objects) next="findNext('span')" b=[ getattr(c,next).string fo...
[ "Looks to me like what you want is:\nb = [ eval(\"c.\" + next).string for c in a ]\n\nThis will call findNext('span') for each element c of the list a and form a list of the results of each findNext call in the list b.\n", "Try\ntrees = [...] #(list of BeautifulSoup objects)\nstrings = [tree.findNext('span').stri...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0005427658_beautifulsoup_python.txt
Q: What is the URI format to create a Google Site with custom URL Using python google appengine: entry = client.create_site(orgName, description=orgDescription, source_site='https://sites.google.com/feeds/site/dpau.org/org' uri='https://sites.google.com/feeds/site/dpau.org/MyCustomURL') I get "Invalid ...
What is the URI format to create a Google Site with custom URL
Using python google appengine: entry = client.create_site(orgName, description=orgDescription, source_site='https://sites.google.com/feeds/site/dpau.org/org' uri='https://sites.google.com/feeds/site/dpau.org/MyCustomURL') I get "Invalid URI" for the uri= Am I using an invalid format for the URI? uri='MyC...
[ "You're missing a comma in your arguments list, though I don't know that this would fix the error you're seeing. Can you copy/paste the actual error?\nentry = client.create_site(orgName, description=orgDescription,\n source_site='https://sites.google.com/feeds/site/dpau.org/org', # this comma right he...
[ 0 ]
[]
[]
[ "google_app_engine", "google_sites", "python" ]
stackoverflow_0005427748_google_app_engine_google_sites_python.txt
Q: Python: How can I make my tkinter app exit properly? I need to know how to do this on a mac because whenever I try quitting it, I have to force quit it. Is there a proper way when the user clicks the exit button that Tkinter will exit normally? A: I figured out how. I just put a simple exit() command after the m...
Python: How can I make my tkinter app exit properly?
I need to know how to do this on a mac because whenever I try quitting it, I have to force quit it. Is there a proper way when the user clicks the exit button that Tkinter will exit normally?
[ "I figured out how. I just put a simple exit() command after the main loop.\n" ]
[ 2 ]
[]
[]
[ "exit", "macos", "python", "tkinter" ]
stackoverflow_0005427875_exit_macos_python_tkinter.txt
Q: python - capturing stderr of subprocesses with their shell stdout alive Here are things I'm trying to do: -python process captures stderr of multiple subprocesses to watch the subprocesses -each subprocess runs on the separate window displaying stdout. When I use Popen(command,stderr = fp4tempfile), (good) the...
python - capturing stderr of subprocesses with their shell stdout alive
Here are things I'm trying to do: -python process captures stderr of multiple subprocesses to watch the subprocesses -each subprocess runs on the separate window displaying stdout. When I use Popen(command,stderr = fp4tempfile), (good) the python process can capture stderr of the subprocesses (bad ) the subprocess ...
[ "Haven't tested this, but can you do\nimport sys\n\npp = subprocess.Popen(command, stderr = fpw, stdout = sys.stdout)\n\n", "I82Much, thank you for your answer and comment.\nYes, your comment about stderr was absolutely right. I was developing in windows7. In linux (ubuntu10), the following simply worked out:\n\n...
[ 0, 0 ]
[]
[]
[ "python", "stderr", "stdout", "subprocess" ]
stackoverflow_0005401740_python_stderr_stdout_subprocess.txt
Q: Tuple into Dictionary in Python Possible Duplicate: Transform tuple to dict How do I change a list of tuples such as: seq = [(1, 2), (3, 4), (5, 6)] into a dictionary: dicta = { 1:2, 2:4, 5:6 } A: >>> seq = [(1, 2), (3, 4), (5, 6)] >>> dict(seq) {1: 2, 3: 4, 5: 6} Isn't python nice :) As defined in the Pytho...
Tuple into Dictionary in Python
Possible Duplicate: Transform tuple to dict How do I change a list of tuples such as: seq = [(1, 2), (3, 4), (5, 6)] into a dictionary: dicta = { 1:2, 2:4, 5:6 }
[ ">>> seq = [(1, 2), (3, 4), (5, 6)]\n>>> dict(seq)\n{1: 2, 3: 4, 5: 6}\n\nIsn't python nice :)\nAs defined in the Python Docs:\nThe dict() constructor builds dictionaries directly from lists of key-value pairs stored as tuples.\n\n" ]
[ 10 ]
[]
[]
[ "dictionary", "python", "python_3.x", "tuples" ]
stackoverflow_0005428132_dictionary_python_python_3.x_tuples.txt
Q: Python options and arguments not passing correctly The following code does not have any errors when run script.py -f filename but does not function? I imagine part of it is my function/variable naming scheme which is probably causing some confusion on my part. Any ideas? #! /usr/bin/env python import boto import ...
Python options and arguments not passing correctly
The following code does not have any errors when run script.py -f filename but does not function? I imagine part of it is my function/variable naming scheme which is probably causing some confusion on my part. Any ideas? #! /usr/bin/env python import boto import os, sys, glob from optparse import OptionParser from bot...
[ "I'm not sure about the way you're accessing boto here. You're only using S3, right? The boto S3 docs use a different interface than the one you're using. Here are some excerpts from code that works under Python 2.5:\nfrom boto.s3.connection import S3Connection\nfrom boto.exception import S3ResponseError\n\nclass T...
[ 1, 1 ]
[]
[]
[ "amazon_s3", "debugging", "python", "scripting" ]
stackoverflow_0005427956_amazon_s3_debugging_python_scripting.txt
Q: How can you automate terminal commands? I'm tired of doing this. ssh me@somehost.com input my password sudo su - someuser input my password cd /some/working/directory <run some commands> Is there anyway to automate this? Do I need a special shell? or a shell emulator? can I programmatically drive the shell up to ...
How can you automate terminal commands?
I'm tired of doing this. ssh me@somehost.com input my password sudo su - someuser input my password cd /some/working/directory <run some commands> Is there anyway to automate this? Do I need a special shell? or a shell emulator? can I programmatically drive the shell up to certain point then run manual commands on it?...
[ "For the ssh/authentication piece, you can setup passwordless authentication by using keys. Then you can simply use ssh and a bash script to execute a series of commands in an automated fashion.\nYou could use Python here, but if you are executing a series of shell commands, it's probably a better idea to use a sh...
[ 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "linux", "macos", "python", "shell", "ssh" ]
stackoverflow_0005425191_linux_macos_python_shell_ssh.txt
Q: difference between django.contrib.syndication.feeds.Feed and django.contrib.syndication.views.Feed? I'm creating a new feed from django.contrib.gis.feeds.Feed which inherits django.contrib.syndication.feeds.Feed. I notice that when I try to initialize a Feed from gis, that it requires 3 arguments (self, slug, requ...
difference between django.contrib.syndication.feeds.Feed and django.contrib.syndication.views.Feed?
I'm creating a new feed from django.contrib.gis.feeds.Feed which inherits django.contrib.syndication.feeds.Feed. I notice that when I try to initialize a Feed from gis, that it requires 3 arguments (self, slug, request), but when I try to initialize a Feed from django.contrib.syndication.views.Feed, I don't need to do ...
[ "django.contrib.syndication.feeds.Feed is a deprecated class which, if I understand correctly, is now just a wrapper around the view-based API for backwards compatibility. You should use django.contrib.syndication.views.Feed so that you don't lose support in a future version. However, in terms of the gis feed, if y...
[ 1 ]
[]
[]
[ "django", "python", "rss" ]
stackoverflow_0005428242_django_python_rss.txt
Q: How do I make a new Graph class in Sage with extra methods? I am writing some code in Sage to do some calculations with Feynman graphs, which are just finite, un-oriented multigraphs with edge-labels. I need to implement methods such as edge-contraction, which are curiously missing from the class sage.graphs.grap...
How do I make a new Graph class in Sage with extra methods?
I am writing some code in Sage to do some calculations with Feynman graphs, which are just finite, un-oriented multigraphs with edge-labels. I need to implement methods such as edge-contraction, which are curiously missing from the class sage.graphs.graph.Graph. But I also want to inherit all the existing graph metho...
[ "You might simply not be inheriting things correctly. Try inserting this at the beginning of __init__():\nsuper().__init__()\n\n" ]
[ 3 ]
[]
[]
[ "class", "inheritance", "python", "sage" ]
stackoverflow_0005278911_class_inheritance_python_sage.txt
Q: Cherrypy vs. Apache/mod_wsgi What are pros/cons? -Stability -Developer friendliness -System resources -Scalability A: In my experience the best performance is by running a WSGI app with a WSGI server like FAPWS or gevent (some benchmarks here: http://nichol.as/benchmark-of-python-web-servers). Then you can conf...
Cherrypy vs. Apache/mod_wsgi
What are pros/cons? -Stability -Developer friendliness -System resources -Scalability
[ "In my experience the best performance is by running a WSGI app with a WSGI server like FAPWS or gevent (some benchmarks here: http://nichol.as/benchmark-of-python-web-servers). Then you can configure nginx with proxy_pass.\n" ]
[ 0 ]
[]
[]
[ "cherrypy", "mod_wsgi", "python" ]
stackoverflow_0005215863_cherrypy_mod_wsgi_python.txt
Q: How to pass a url as a url parameter when there is a question mark in it? I am using this line to pass the a url, main_id and user_tag_list to the handler: self.response.out.write(""" <a href="/tc?url=%s&main_id=%s&user_tag_list=%s" title="edit tag set">edit tag set</a> """ % (item.url, main_id, item.tag_list)) ...
How to pass a url as a url parameter when there is a question mark in it?
I am using this line to pass the a url, main_id and user_tag_list to the handler: self.response.out.write(""" <a href="/tc?url=%s&main_id=%s&user_tag_list=%s" title="edit tag set">edit tag set</a> """ % (item.url, main_id, item.tag_list)) this works fine except that when there is already a question mark in the passe...
[ "You just want to use urllib.quote\n>>> import urllib\n>>> urllib.quote('http://www.google.com?q=Zombie+Apocalypse')\n'http%3A//www.google.com%3Fq%3DZombie%2BApocalypse'\n\nSo:\nurllib.quote(item.url)\n\n", "urllib.quote ought to help with this.\n" ]
[ 9, 1 ]
[]
[]
[ "google_app_engine", "python", "url_parameters" ]
stackoverflow_0005428296_google_app_engine_python_url_parameters.txt
Q: Boost Threads equivalent to Python's threading.Event? Is there a Boost Threads equivalent to Python's threading.Event Less specifically, is there a synchronization primitive that allows threads to pass when an internal value is set, and blocks them when not? A: You should use Boost's condition variables. Condit...
Boost Threads equivalent to Python's threading.Event?
Is there a Boost Threads equivalent to Python's threading.Event Less specifically, is there a synchronization primitive that allows threads to pass when an internal value is set, and blocks them when not?
[ "You should use Boost's condition variables. Condition variables avoid some of the pitfalls that can happen with event objects. I find it hard to use event objects correctly in some corner cases: multiple triggers before the event is handled, some state is changed before the handler is called, etc.\nThe examples in...
[ 2 ]
[]
[]
[ "boost", "events", "multithreading", "python" ]
stackoverflow_0005428245_boost_events_multithreading_python.txt
Q: How would one go about developing a curses-based UI? I'm planning to develop a GUI application that uses curses. The idea is to provide an extra interface for a web interface, so that everything on the web site could also be done via the UI. Basically, it should be platform independent: the user would have to SSH ...
How would one go about developing a curses-based UI?
I'm planning to develop a GUI application that uses curses. The idea is to provide an extra interface for a web interface, so that everything on the web site could also be done via the UI. Basically, it should be platform independent: the user would have to SSH to the server after which the UI would automatically take ...
[ "It's certainly possible, and curses-based applications are still written regularly (e.g. PuDB is only 14 months old) although maybe not very often.\nDid you try asking questions on the Urwid mailing list and/or IRC channel?\n", "oh my, wouldn't this be a dream!\ni've seen a couple of things out there to varying ...
[ 1, 1, 1 ]
[]
[]
[ "curses", "ncurses", "python", "user_interface" ]
stackoverflow_0003601210_curses_ncurses_python_user_interface.txt
Q: Python Regexp: find all words/phrases within a querystring containing OR and AND I have a querystring like this: s = 'word1 AND word2 word3 OR "word4 word5" OR word6 AND word7 word8' I need to find all words or phrases within OR and AND, so the results will be a list like this (preferably without the spaces betwe...
Python Regexp: find all words/phrases within a querystring containing OR and AND
I have a querystring like this: s = 'word1 AND word2 word3 OR "word4 word5" OR word6 AND word7 word8' I need to find all words or phrases within OR and AND, so the results will be a list like this (preferably without the spaces between AND/OR and the word/phrase): l = ['word1', 'word2 word3', '"word4 word5"', 'word6',...
[ "If you want to use regexps, re.split should do it:\nre.split(' OR | AND ', 'word1 AND word2 word3 OR \"word4 word5\" OR word6 AND word7 word8')\n['word1', 'word2 word3', '\"word4 word5\"', 'word6', 'word7 word8']\n\nIf you need a bigger hammer, you could check out something like pyparsing:\nhttp://pyparsing.wikisp...
[ 6, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005428338_python_regex.txt
Q: python string formatting I want to execute a git command, in shell it is as below: $ git log v2.6.38..v2.6.38-rc8 --pretty=format:%s%n%n the --pretty=format:%s%n%n is to say only show the commit subject message, and every message is split by two new line. now, I want to execute in python script, and input tag nam...
python string formatting
I want to execute a git command, in shell it is as below: $ git log v2.6.38..v2.6.38-rc8 --pretty=format:%s%n%n the --pretty=format:%s%n%n is to say only show the commit subject message, and every message is split by two new line. now, I want to execute in python script, and input tag name as parameter. I want do like...
[ "Use string formatting (if you're using at least Python 2.6):\ngit_cmd = \"git log {old_tag}..{new_tag} --pretty=format:'%s%n%n'\"\ngit_cmd = git_cmd.format(old_tag='v2.6.38',new_tag='v2.6.38-rc8')\n\n", "You can escape the Python format strings by repeating the % twice.\nFor example:\ngit_cmd = \"git log %(old_t...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005428300_python.txt
Q: What is the fastest way in Python to find if a string matches any terms in a list of words, phrases, boolean ANDs? I am trying to find a fast way in Python to check if a list of terms can be matched against strings ranging in size from 50 to 50,000 characters. A term can be: A word, eg. 'apple' A phrase, eg. 'che...
What is the fastest way in Python to find if a string matches any terms in a list of words, phrases, boolean ANDs?
I am trying to find a fast way in Python to check if a list of terms can be matched against strings ranging in size from 50 to 50,000 characters. A term can be: A word, eg. 'apple' A phrase, eg. 'cherry pie' Boolean ANDing of words and phrases, eg. 'sweet pie AND savoury pie AND meringue' A match is where a word or p...
[ "I am going to give a partial answer here but why don't you split the test and matching strings on word boundaries and build a set. You can intersect sets very quickly and if the set matches then you can do the expensive regex test. \n", "The boolean AND regex with the multiple lookahead assertions can be sped up...
[ 4, 4 ]
[]
[]
[ "algorithm", "pattern_matching", "python", "regex", "string" ]
stackoverflow_0005427541_algorithm_pattern_matching_python_regex_string.txt
Q: How do I install psycopg2 in a virtualenv that seems to not have gcc access? I'm trying to install psycopg2 in a virtualenv but it seems that I don't have access to gcc. Is there a way to activate gcc from inside the virtualenv? If not, is there any other library that works with PostgreSQL that does not use gcc? M...
How do I install psycopg2 in a virtualenv that seems to not have gcc access?
I'm trying to install psycopg2 in a virtualenv but it seems that I don't have access to gcc. Is there a way to activate gcc from inside the virtualenv? If not, is there any other library that works with PostgreSQL that does not use gcc? My attempt to install psycopg2 at A2hosting.com gives me this error: running instal...
[ "You don't need PostgreSQL, you need the PostgreSQL client libraries and development files. You can try asking the host to install them, or failing that you can build it on a similar platform and copy the package manually.\n" ]
[ 0 ]
[]
[]
[ "psycopg2", "python", "virtualenv" ]
stackoverflow_0005427113_psycopg2_python_virtualenv.txt
Q: How to order xml element attributes in Python? When parsing an xml file into a Python ElementTree the attributes' order is mixed up because Python stores the attributes in a dictionary. How can I change the order of the attributes in the dictionary? A: XML attributes are by definition unordered1, compare paragra...
How to order xml element attributes in Python?
When parsing an xml file into a Python ElementTree the attributes' order is mixed up because Python stores the attributes in a dictionary. How can I change the order of the attributes in the dictionary?
[ "XML attributes are by definition unordered1, compare paragraph 3.1 of the official standard.\n1Technically, attribute lists are ordered, but the order is not significant, i.e. writers, transformers and parsers are free to switch it around as they like.\n", "Your self-answer is as you said long and cumbersome. It...
[ 6, 2, 0, 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0005381296_elementtree_python_xml.txt
Q: Entity groups, ReferenceProperty or key as a string After building a few application on the gae platform I usually use some relationship between different models in the datastore in basically every application. And often I find my self the need to see what record is of the same parent (like matching all entry with...
Entity groups, ReferenceProperty or key as a string
After building a few application on the gae platform I usually use some relationship between different models in the datastore in basically every application. And often I find my self the need to see what record is of the same parent (like matching all entry with same parent) From the beginning I used the db.ReferenceP...
[ "Tip:\nreplace...\nbar.parentFoo.key() == fooKey\n\nwith...\nBar.parentFoo.get_value_for_datastore(bar) == fooKey\n\nTo avoid the extra lookup and just fetch the key from the ReferenceProperty\nSee Property Class\n", "I think you should consider this as well. This will help you fetch all the child entities of a ...
[ 3, 2, 1, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0005425618_google_app_engine_google_cloud_datastore_python.txt
Q: How do I reveal an optional field in a Django form, when a checkbox is checked? Is this possible with Django, without using Javascript? A: It is technically possible using some CSS3 techniques, although there won't be universal browser support. Your field will have an id depending upon the form's prefix ('id' by...
How do I reveal an optional field in a Django form, when a checkbox is checked?
Is this possible with Django, without using Javascript?
[ "It is technically possible using some CSS3 techniques, although there won't be universal browser support.\nYour field will have an id depending upon the form's prefix ('id' by default, configurable when creating a form), so you can style a form element in css with the identifier #id_field_name. Then you can use so...
[ 4, 2 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0005427515_django_forms_python.txt
Q: Python init and Objects I have this issue. I wouldn't know if there is any short-cut to it but I would love a short-cut though. Say I have this class class a(object): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "<a(%s', '%s')>" % (self.x, self.y) ...
Python init and Objects
I have this issue. I wouldn't know if there is any short-cut to it but I would love a short-cut though. Say I have this class class a(object): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "<a(%s', '%s')>" % (self.x, self.y) def b(self): print('...
[ "Just set a null default value for the last parameter:\ndef __init__(self, x, y=None):\n\nYou'll need to check for y is None in a lot of your logic.\n", "You can also try this so set value of any field that you want...\n>>> class a(object):\n def __init__(self, x=None, y=None):\n self.x = x\n sel...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005424160_python.txt
Q: problems with file I/O while running python 3.2 scripts in windows cmd, but not in IDLE I am a python noob, and am having problems running programs with open() functions in cmd prompts. The code runs as expected in the python shell with IDLE, but everytime I open it by doubleclicking the icon coresponding to the...
problems with file I/O while running python 3.2 scripts in windows cmd, but not in IDLE
I am a python noob, and am having problems running programs with open() functions in cmd prompts. The code runs as expected in the python shell with IDLE, but everytime I open it by doubleclicking the icon coresponding to the script( I have .py associated with python), I get errors like what file test.txt (I entered...
[ "You're not handling end-of-line characters correctly, and IDLE gives you the end-of-line in one format, while the cmd.exe sends another.\nI suggest stripping whitespace from both ends of the input in this case.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005429094_python.txt
Q: How to replace all '0xa0' chars with a ' ' in a bunch of text files? i've been trying to mass-edit a bunch of text files to utf-8 in python and this error keeps popping out. is there a way to replace them in some python scrips or bash commands? i used the code: writer = codecs.open(os.path.join(wrd, 'dict.en'), 'w...
How to replace all '0xa0' chars with a ' ' in a bunch of text files?
i've been trying to mass-edit a bunch of text files to utf-8 in python and this error keeps popping out. is there a way to replace them in some python scrips or bash commands? i used the code: writer = codecs.open(os.path.join(wrd, 'dict.en'), 'wtr', 'utf-8') for infile in glob.glob(os.path.join(wrd,'*.txt')): ...
[ "OK, first point: your output file is set to automatically encode text written to it as utf-8, so don't include an explicit encode('utf-8') method call when passing arguments to the write() method.\nSo the first thing to try is to simply use the following in your inner loop:\nwriter.write(line)\n\nIf that doesn't w...
[ 11, 3 ]
[ "Please be serious - a simple replace() operation will do the job:\nline = line.replace(chr(0xa0), '')\n\nIn addition the codecs.open() constructors support the 'errors' parameter to handle \nconversion errors. Please read up (yourself).\n" ]
[ -3 ]
[ "bash", "python", "shell", "text", "utf_8" ]
stackoverflow_0005428844_bash_python_shell_text_utf_8.txt
Q: ConfigParser.NoSectionError: No section: 'locations' in Exe. Python I created successfully an .exe file for my python code. As a .py file, it works like a charm. But when I try to run it from the exe version, I get error as follows: Traceback (most recent call last): File "CreateAS.pyw", line 14, in <module> F...
ConfigParser.NoSectionError: No section: 'locations' in Exe. Python
I created successfully an .exe file for my python code. As a .py file, it works like a charm. But when I try to run it from the exe version, I get error as follows: Traceback (most recent call last): File "CreateAS.pyw", line 14, in <module> File "pulp\__init__.pyc", line 33, in <module> File "pulp\pulp.pyc", lin...
[ "Check if the section exists. If it does not - add it\nconfig = ConfigParser.ConfigParser()\nif not config.has_section(\"locations\"):\n config.add_section(\"locations\")\n\n", "Ok. I found the solution. There is a solvers.py in Pulp directory. Inside it, I replaced the DIRNAME to the fullpath of the Pulp dire...
[ 0, 0 ]
[]
[]
[ "executable", "python" ]
stackoverflow_0005415717_executable_python.txt
Q: Squid-style external redirector for polipo doesn't work I am trying to write a trivial squid-style redirector for polipo http proxy, as specified in the documentation. Here is the code: #!/usr/bin/python # based on # http://gofedora.com/how-to-write-custom-redirector-rewritor-plugin-squid-python/ import sys def...
Squid-style external redirector for polipo doesn't work
I am trying to write a trivial squid-style redirector for polipo http proxy, as specified in the documentation. Here is the code: #!/usr/bin/python # based on # http://gofedora.com/how-to-write-custom-redirector-rewritor-plugin-squid-python/ import sys def modify_url(line): l = line.split(" ") old_url = l[0]...
[ "That site (gofedora) mentions that you need to return either a blank line or the modified url in modify_url to make it work. Also you'll see the error if you run this manually. Your solution is to return new_url at the end of modify_url.\nPlease note that you also need to chmod +x to permit your proxy to run the s...
[ 1 ]
[]
[]
[ "http", "proxy", "python" ]
stackoverflow_0005429670_http_proxy_python.txt
Q: Is there a method for reading characters from an instance of subprocess.Popen when the process it called has not yet issued a newline? I am attempting to wrap a program that is routinely used at work. When called with an insufficient number of arguments, or with a misspelled argument, the program issues a prompt ...
Is there a method for reading characters from an instance of subprocess.Popen when the process it called has not yet issued a newline?
I am attempting to wrap a program that is routinely used at work. When called with an insufficient number of arguments, or with a misspelled argument, the program issues a prompt to the user, asking for the needed input. As a consequence, when calling the routine with subprocess.Popen, the routine never sends any inf...
[ "First thing to try: use the bufsize argument to Popen, and set it to 0:\nsubprocess.Popen(args, bufsize=0, ...)\n\nUnfortunately, whether or not this works also depends upon how the subprocess flushes its output, and I presume you don't have much control over that.\nOn some platforms, when data written to stdout i...
[ 2, 2 ]
[]
[]
[ "newline", "popen", "python", "subprocess" ]
stackoverflow_0005428505_newline_popen_python_subprocess.txt
Q: showing progress while spawning and running subprocess I need to show some progress bar or something while spawning and running subprocess. How can I do that with python? import subprocess cmd = ['python','wait.py'] p = subprocess.Popen(cmd, bufsize=1024,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subp...
showing progress while spawning and running subprocess
I need to show some progress bar or something while spawning and running subprocess. How can I do that with python? import subprocess cmd = ['python','wait.py'] p = subprocess.Popen(cmd, bufsize=1024,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.stdin.close() outputmessage = p.stdout.read()...
[ "Since the subprocess call is blocking, one way to print something out while waiting would be to use multithreading. Here's an example using threading._Timer:\nimport threading\nimport subprocess\n\nclass RepeatingTimer(threading._Timer):\n def run(self):\n while True:\n self.finished.wait(sel...
[ 6, 0 ]
[]
[]
[ "progressdialog", "python", "subprocess" ]
stackoverflow_0005429577_progressdialog_python_subprocess.txt
Q: Twitter Data Mining: Degrees of separation What ready available algorithms could I use to data mine twitter to find out the degrees of separation between 2 people on twitter. How does it change when the social graph keeps changing and updating constantly. And then, is there any dump of twitter social graph data wh...
Twitter Data Mining: Degrees of separation
What ready available algorithms could I use to data mine twitter to find out the degrees of separation between 2 people on twitter. How does it change when the social graph keeps changing and updating constantly. And then, is there any dump of twitter social graph data which I could use rather than making so many API c...
[ "From the Twitter API\nWhat's the Data Mining Feed and can I have access to it?\nThe Data Mining Feed is an expanded version of our /statuses/public_timeline REST API method. It returns 600 recent public statuses, cached for a minute at a time. You can request it up to once per minute to get a representative sample...
[ 5, 0, 0 ]
[]
[]
[ "dump", "python", "social_graph", "twitter" ]
stackoverflow_0000785327_dump_python_social_graph_twitter.txt
Q: element tree search help(python, xml) I'm trying to find all child elements whose attribute class is 'TRX' and whose attribute distName Starts with 'PLMN-PLMN/BSC-208812/BCF-1/BTS-1' Is something like this possible? root[0].findall("*[@class='TRX'][@distName='PLMN-PLMN/BSC-208812/BCF-1/BTS-1*']") I'm using cEleme...
element tree search help(python, xml)
I'm trying to find all child elements whose attribute class is 'TRX' and whose attribute distName Starts with 'PLMN-PLMN/BSC-208812/BCF-1/BTS-1' Is something like this possible? root[0].findall("*[@class='TRX'][@distName='PLMN-PLMN/BSC-208812/BCF-1/BTS-1*']") I'm using cElementTree over lxml because it is much much fa...
[ "ElementTree can in fact do this.\nYou may need to use .//* instead of *.\nPython docs ElementTree version 1.3.0 which comes with Python 2.7 has the XPath capabilities you seek.\nExample\nfrom xml.etree import ElementTree\n\net = ElementTree.fromstring(\"\"\"\n<r>\n <b>\n <a class='c' foo='e'>this is e</a...
[ 2 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0005430540_python_xml.txt
Q: What exception to throw? (Python) If I have a python function with 2 optional parameters (for search criteria) but no one is provided (I need at least one parameter) what is the right exception to throw? What if I only one of two parameters have to be passed? What exception to throw if two are provided? Or may be ...
What exception to throw? (Python)
If I have a python function with 2 optional parameters (for search criteria) but no one is provided (I need at least one parameter) what is the right exception to throw? What if I only one of two parameters have to be passed? What exception to throw if two are provided? Or may be create two distinct functions?
[ "TypeError is most appropriate - this is what you get usually.\n", "You can find a list of the built in Python exceptions here, but remember you can always create your own kind of exception if none of these match what you're after.\nI'd suggest using a TypeError (which is what you normally see in Python code bein...
[ 4, 4, 3, 3 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0005430388_exception_python.txt
Q: Importing pyFileMaker complains about EXPAT library I've just downloaded pyFileMaker. I copied the directory PyFileMaker into the dir Lib under Python31 directory, but when I simply include the module FMServer with this line: from PyFileMaker import FMServer I get this error Traceback (most recent call last): F...
Importing pyFileMaker complains about EXPAT library
I've just downloaded pyFileMaker. I copied the directory PyFileMaker into the dir Lib under Python31 directory, but when I simply include the module FMServer with this line: from PyFileMaker import FMServer I get this error Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> from PyFileMak...
[ "Well, as far as I can see the error happened not in the import, but in the print statement. (I.e. there probably was an error in import too, but it was intercepted.) The problem is that PyFileMaker is written for Python 2.x (their site says 2.4 is the minimal version), while you're using Python 3, and v3 is not co...
[ 0 ]
[]
[]
[ "expat_parser", "filemaker", "python" ]
stackoverflow_0005420592_expat_parser_filemaker_python.txt
Q: Django Eclipse Pydev environment problem Really silly one going on here... I need to use this bit of code... from sentry.client.handlers import SentryHandler if SentryHandler not in map(lambda x: x.__class__, logger.handlers): logger.addHandler(SentryHandler()) I just can't get it to import in Eclipse/Pydev. ...
Django Eclipse Pydev environment problem
Really silly one going on here... I need to use this bit of code... from sentry.client.handlers import SentryHandler if SentryHandler not in map(lambda x: x.__class__, logger.handlers): logger.addHandler(SentryHandler()) I just can't get it to import in Eclipse/Pydev. I get Unresolved import: SentryHandler Unused...
[ "I had the same problem. Here's what worked for me:\nGo back into the Pydev configuration: window > preferences > pydev > Interpreter - (Python/Jython/IronPython)\nI'm using the Python interpreter. \nAlthough my PYTHONPATH was setup properly to include dist-packages, I still needed to hit apply (or re-apply in my...
[ 1, 0 ]
[]
[]
[ "django", "eclipse", "python" ]
stackoverflow_0004349220_django_eclipse_python.txt
Q: How to print a timestamp in a human readable format in SQLite3? I need to print a date in SQLite like this "24-03-2011 10:45:00", for now I only can print the date. >>> import sqlite3 >>> database = sqlite3.connect('basedadosteste.db') >>> cursor = database.cursor() >>> cursor.execute("SELECT date('now');") <sqlit...
How to print a timestamp in a human readable format in SQLite3?
I need to print a date in SQLite like this "24-03-2011 10:45:00", for now I only can print the date. >>> import sqlite3 >>> database = sqlite3.connect('basedadosteste.db') >>> cursor = database.cursor() >>> cursor.execute("SELECT date('now');") <sqlite3.Cursor object at 0x00BC0710> >>> results = cursor.fetchall() >>> f...
[ "date only gives you the date, hence the name. If you want the date and time, you have to use datetime.\nAnd if you want to format the date, you can use strftime - either in the SQL command, or in Python. See the sqlite3 date docs.\nThis would work:\nSELECT strftime('%d-%m-%Y %H:%M:%S', 'now');\n\n" ]
[ 5 ]
[]
[]
[ "python", "sqlite", "timestamp" ]
stackoverflow_0005431398_python_sqlite_timestamp.txt
Q: pointwise operations on scipy.sparse matrices Is it possible to apply for example numpy.exp or similar pointwise operators to all elements in a scipy.sparse.lil_matrix or another sparse matrix format? import numpy from scipy.sparse import lil_matrix x = numpy.ones((10,10)) y = numpy.exp(x) x = lil_matrix(numpy.o...
pointwise operations on scipy.sparse matrices
Is it possible to apply for example numpy.exp or similar pointwise operators to all elements in a scipy.sparse.lil_matrix or another sparse matrix format? import numpy from scipy.sparse import lil_matrix x = numpy.ones((10,10)) y = numpy.exp(x) x = lil_matrix(numpy.ones((10,10))) # y = ???? numpy.exp(x) or scipy.exp...
[ "I do not know the full details, but converting to another type works, at least when using the array of non zero elements:\nxcsc = x.tocsc()\nnumpy.exp(xcsc.data) # works\n\n" ]
[ 6 ]
[]
[]
[ "python", "scipy", "sparse_matrix" ]
stackoverflow_0005431534_python_scipy_sparse_matrix.txt
Q: Cannot install psycopg2 on OSX 10.6.7 with XCode4 Trying to install psycopg2 on OSX results in the following: building 'psycopg2._psycopg' extension creating build/temp.macosx-10.6-universal-2.6 creating build/temp.macosx-10.6-universal-2.6/psycopg gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -...
Cannot install psycopg2 on OSX 10.6.7 with XCode4
Trying to install psycopg2 on OSX results in the following: building 'psycopg2._psycopg' extension creating build/temp.macosx-10.6-universal-2.6 creating build/temp.macosx-10.6-universal-2.6/psycopg gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -a...
[ "It seems that there was something wrong with the ARCHFLAGS actually sticking, so finally using:\nsudo env ARCHFLAGS=\"-arch i386 -arch x86_64\" pip install psycopg2\nactually worked.\n", "The problem is that the Python 2.6 included with OS X 10.6 was built for three supported architectures (i386, x86_64, and ppc...
[ 51, 8 ]
[]
[]
[ "installation", "pip", "psycopg2", "python", "xcode4" ]
stackoverflow_0005427157_installation_pip_psycopg2_python_xcode4.txt
Q: Is it possible to run webservice based on SOAPpy with mod_wsgi under Apache? Is it possible to run webservice based on SOAPpy with mod_wsgi under Apache? if yes can you post link to sample(example)? A: No. SOAPpy has its own HTTP server based on BaseHTTPServer which means that it is not possible to turn it into ...
Is it possible to run webservice based on SOAPpy with mod_wsgi under Apache?
Is it possible to run webservice based on SOAPpy with mod_wsgi under Apache? if yes can you post link to sample(example)?
[ "No. SOAPpy has its own HTTP server based on BaseHTTPServer which means that it is not possible to turn it into a WSGI app without a non-trivial amount of hacking.\n" ]
[ 1 ]
[]
[]
[ "apache", "mod_wsgi", "python", "soappy" ]
stackoverflow_0005431958_apache_mod_wsgi_python_soappy.txt
Q: Reset easy_install after uninstalling Python on OS X I had 64-bit Python at first, then I installed BeautifulSoup using easy_install. For some reason, I uninstalled 64-bit Python using this method. Then I reinstalled the 32-bit version from Python.org. However: Kit:~ Kit$ easy_install beautifulsoup Searching for b...
Reset easy_install after uninstalling Python on OS X
I had 64-bit Python at first, then I installed BeautifulSoup using easy_install. For some reason, I uninstalled 64-bit Python using this method. Then I reinstalled the 32-bit version from Python.org. However: Kit:~ Kit$ easy_install beautifulsoup Searching for beautifulsoup Best match: BeautifulSoup 3.2.0 Processing Be...
[ "Looks like you're running easy_install from the system Python 2.6. Apple ships easy_install with the OS. If you just installed Python 2.7 from python.org, you'll need to install distribute for that version. (Note that you'll need to do this as root so it can write to /usr/local/bin.) There are also Python vers...
[ 1 ]
[]
[]
[ "easy_install", "macos", "python", "reset" ]
stackoverflow_0005432438_easy_install_macos_python_reset.txt
Q: 2D array plotting in matplotlib I was trying to plot a 2D array vs a 1D array with pyplot. I can do that with no problems and columns in the 2D array are treated like two different sets of Y datas, which is what i want. What i don't know is how to specify a different color for every column in the 2d array. if i us...
2D array plotting in matplotlib
I was trying to plot a 2D array vs a 1D array with pyplot. I can do that with no problems and columns in the 2D array are treated like two different sets of Y datas, which is what i want. What i don't know is how to specify a different color for every column in the 2d array. if i use pyplot.plot(1darray, 2darray, "r-")...
[ "If you want to use custom colors for each column, then the best approach is to plot each column explicitly using a loop:\nfor column, colcolor in zip(2darray, colors):\n pyplot.plot(2darray, column, \"-\", color=colcolor)\n\nYou may have to use 2darray.T, I'm not sure, and I can't check right now.\n" ]
[ 1 ]
[]
[]
[ "colors", "matplotlib", "plot", "python" ]
stackoverflow_0005430076_colors_matplotlib_plot_python.txt
Q: Count number of sheets in an Excel file using win32com.client Using win32com.client, how can I count all the number of sheets in a excel file? A: Found it: excel = win32.gencache.EnsureDispatch('Excel.Application') try: wb = excel.Workbooks.Open(file) except: print "Failed to open spreadsheet " + file ...
Count number of sheets in an Excel file using win32com.client
Using win32com.client, how can I count all the number of sheets in a excel file?
[ "Found it:\nexcel = win32.gencache.EnsureDispatch('Excel.Application')\ntry:\n wb = excel.Workbooks.Open(file)\nexcept:\n print \"Failed to open spreadsheet \" + file\n sys.exit(1)\ncount = wb.Sheets.Count\n\n" ]
[ 7 ]
[]
[]
[ "excel", "python", "win32com" ]
stackoverflow_0005432497_excel_python_win32com.txt
Q: python ctypes arrays I would like to have an array of variable length arrays in ctypes. I know the size of the outer array and all of the inner arrays, too. I found an interesting thread here: How do I emulate a dynamically sized C structure in Python using ctypes But the problem with this is how to create an arra...
python ctypes arrays
I would like to have an array of variable length arrays in ctypes. I know the size of the outer array and all of the inner arrays, too. I found an interesting thread here: How do I emulate a dynamically sized C structure in Python using ctypes But the problem with this is how to create an array of Var classes (see the ...
[ "Dynamically sized data structures are handled in ctypes the same way they are in C; you use pointers to dynamic data. Unfortunately, there's no shortcut on this one. The ctypes documentation includes fairly detailed descriptions on how to handle pointers to dynamic data (such as using a pointer as an arbitrarily s...
[ 1 ]
[]
[]
[ "arrays", "ctypes", "pointers", "python" ]
stackoverflow_0005432193_arrays_ctypes_pointers_python.txt
Q: How to get volume label based on device name using Python I am making something like a list of mounted devices for Linux. On program startup I parse /etc/mtab for existing mounts. To get notified about new mounts added to the system am using DBus and in message I get there is volume.label property. Is there any w...
How to get volume label based on device name using Python
I am making something like a list of mounted devices for Linux. On program startup I parse /etc/mtab for existing mounts. To get notified about new mounts added to the system am using DBus and in message I get there is volume.label property. Is there any way to get volume label based on device name like /dev/sda1 or /...
[ "Instead of using the e2label command, you can use blkid and then parse its output:\n$ blkid -o value -s LABEL /dev/sda1\n/boot\n\n", "The e2label command will tell you the volume label when used like this:\ne2label /dev/sda1\n\nNote: this only works for ext2, ext3, or ext4 filesystems.\nFrom Python, you can invo...
[ 2, 1 ]
[]
[]
[ "label", "linux", "mount", "python", "volume" ]
stackoverflow_0004843250_label_linux_mount_python_volume.txt
Q: My python method isn't working correctly, skipping items in a list (playfair cipher) I'm trying to write a method that takes a key and an alphabet and creates a playfair cipher box. For those of you that don't know what that is, It takes the key and puts it in a 5 x 5 grid of letters, spilling onto the next line ...
My python method isn't working correctly, skipping items in a list (playfair cipher)
I'm trying to write a method that takes a key and an alphabet and creates a playfair cipher box. For those of you that don't know what that is, It takes the key and puts it in a 5 x 5 grid of letters, spilling onto the next line if neccessary, and then adds the rest of the letters of the alphabet. Each letter is only ...
[ "Your problem is in isIn:\nYour break statement only breaks out of the inner for loop. The code then continues to iterate over the second for loop. This means that only the last one is considered. You have to make sure that you exit out of both loops for this to work correctly.\nThe entire process can be made simpl...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005428069_python.txt
Q: Python PHP Integration I am facing a problem here which I could not find a good solution for it. I am developing a mobile web app using php and I need a rule based inference engine (open source) - expert system. The only one I could find was Pyke in Python. So I need to integrate Pykes' source code with my php imp...
Python PHP Integration
I am facing a problem here which I could not find a good solution for it. I am developing a mobile web app using php and I need a rule based inference engine (open source) - expert system. The only one I could find was Pyke in Python. So I need to integrate Pykes' source code with my php implementation. My service prov...
[ "I'm not familiar with Pyke; but when this type of situation arises for me, I usually end up wrapping the Python code with a web-service. I then use PHP to make SOAP or cURL calls to the webservice.\n" ]
[ 2 ]
[]
[]
[ "php", "python" ]
stackoverflow_0005431887_php_python.txt
Q: Limit Python VM memory I'm trying to find a way to limit the memory available for the Python VM, as the option "-Xmx" in the Java VM does. (The idea is to be able to play with the MemoryError exception) I'm not sure this option exist but there may be a solution using a command of the OS to "isolate" a process and ...
Limit Python VM memory
I'm trying to find a way to limit the memory available for the Python VM, as the option "-Xmx" in the Java VM does. (The idea is to be able to play with the MemoryError exception) I'm not sure this option exist but there may be a solution using a command of the OS to "isolate" a process and its memory. Thank you.
[ "On Linux I'm using the resource module:\nimport resource\nresource.setrlimit(resource.RLIMIT_AS, (megs * 1048576L, -1L))\n\n", "On *nix you can play around with the ulimit command, specifically the -m (max memory size) and -v (virtual memory).\n", "Don't waste any time on this.\nInstead, if you want to play wi...
[ 34, 12, 3 ]
[]
[]
[ "jvm", "memory", "python" ]
stackoverflow_0001760025_jvm_memory_python.txt
Q: Conceptual question on serializing data with circular references I am trying to implement a serializer in python which tries to do something like this. If there is an object Foo, having a forward reference to Bar, the serializer would dump all the data in Foo, and the reference would be converted into a data dump ...
Conceptual question on serializing data with circular references
I am trying to implement a serializer in python which tries to do something like this. If there is an object Foo, having a forward reference to Bar, the serializer would dump all the data in Foo, and the reference would be converted into a data dump of Bar. Things would be done recursively like this for any arbitrary d...
[ "Flatten out the structure beforehand with a depth-first search that records which items it has seen. Assign each object an id and replace object references with id references.\n(In essence, turn it into a graph.)\n", "Study the Python pickle module which automatically handles circular references through serializ...
[ 2, 1, 1 ]
[]
[]
[ "prototyping", "python", "serialization" ]
stackoverflow_0005424456_prototyping_python_serialization.txt
Q: Foreign keys in web2py database I use web2py framework with two tables. How can I refer one field from first table into second table? A: Here's the section on table relationships and JOINs from the web2py chapter on databases To illustrate how to implement one to many relations with the web2py DAL, define anoth...
Foreign keys in web2py database
I use web2py framework with two tables. How can I refer one field from first table into second table?
[ "Here's the section on table relationships and JOINs from the web2py chapter on databases\n\nTo illustrate how to implement one to many relations with the web2py DAL, define another table \"dog\" that refers to the table \"person\" which we redefine here:\n\n>>> db.define_table('person',\n Field(...
[ 7, 1 ]
[]
[]
[ "foreign_keys", "python", "web2py" ]
stackoverflow_0005429710_foreign_keys_python_web2py.txt
Q: Word correction program in java I need to implement a program to handle a word correction / suggestion system. - if input is given as 'freind', it should suggest 'friend'. For this I have a GUI containing a text area alone! Suggest to me a way to accomplish this. If not in Java, you can also suggest me in Python,...
Word correction program in java
I need to implement a program to handle a word correction / suggestion system. - if input is given as 'freind', it should suggest 'friend'. For this I have a GUI containing a text area alone! Suggest to me a way to accomplish this. If not in Java, you can also suggest me in Python, using javascript also because I can ...
[ "there are lots of opensource spell checker available\nhttp://spellerpages.sourceforge.net/\nhttp://jazzy.sourceforge.net/\n" ]
[ 3 ]
[]
[]
[ "java", "javascript", "python", "words" ]
stackoverflow_0005433548_java_javascript_python_words.txt
Q: Convert bmp image into DICOM I have 800 images in BMP format and I would like to convert them into DICOM. I have started like this, but it is not working for some reason. My experience with VTK is limited: file_in = 'C:/programfile/image.bmp' file_out = 'test1.dcm' vtkGDCMImageReader() A: Here it is in python: r...
Convert bmp image into DICOM
I have 800 images in BMP format and I would like to convert them into DICOM. I have started like this, but it is not working for some reason. My experience with VTK is limited: file_in = 'C:/programfile/image.bmp' file_out = 'test1.dcm' vtkGDCMImageReader()
[ "Here it is in python:\nr = vtkBMPReader()\nr.SetFileName( 'test1.bmp' )\n\nw = vtkGDCMImageWriter()\nw.SetInput( r.GetOutput() )\nw.SetFileName( 'test1.dcm' )\nw.Write()\n\nIf your input BMP uses lookup table, you can simply pass it:\nr = vtkBMPReader()\nr.SetFileName( 'test1.bmp' )\nr.Allow8BitBMPOn()\nr.Update()...
[ 1 ]
[]
[]
[ "dicom", "gdcm", "python", "vtk" ]
stackoverflow_0005035078_dicom_gdcm_python_vtk.txt
Q: How to initialize a structure variable in a C++ header file using Python ctypes? I am trying to intialize the structure ExternalInputs_add_two in .h header file using Python ctypes. The header file is: typedef struct { int32_T Input; /* '<Root>/Input' */ int32_T Input1; ...
How to initialize a structure variable in a C++ header file using Python ctypes?
I am trying to intialize the structure ExternalInputs_add_two in .h header file using Python ctypes. The header file is: typedef struct { int32_T Input; /* '<Root>/Input' */ int32_T Input1; /* '<Root>/Input1' */ } ExternalInputs_add_two; I need to initiali...
[ "It seems that you're confusing structure definitions with structure instances. As declared in the header file, ExternalInputs_add_two is a type and add_two_U is an instance. DLLs do not export types, only instances of types. Thus the following line in your Python code is nonsensical:\ncdll.add_two_win32.ExternalIn...
[ 0, 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0005421751_ctypes_python.txt
Q: Invoking different methods in python Okay so I have the following: Class OwnableObject(MobileObject): def __init__(self, name): MobileObject.__init__(self, name) self.owner = None # not owned def is_ownable(self): return True def is_owned(self): return self.owner What is the difference betwe...
Invoking different methods in python
Okay so I have the following: Class OwnableObject(MobileObject): def __init__(self, name): MobileObject.__init__(self, name) self.owner = None # not owned def is_ownable(self): return True def is_owned(self): return self.owner What is the difference between invoking the is_ownable method on Ownab...
[ "Update: Based on the code you have posted now, it's impossible to call is_ownable on a MobileObject because the MobileObject doesn't appear to have a definition for is_ownable. \nIf it does, then the difference is simply the difference between MobileObject's definition and OwnableObject's definition. I've updated ...
[ 3, 1, 1 ]
[]
[]
[ "inheritance", "python", "subclass" ]
stackoverflow_0005433760_inheritance_python_subclass.txt
Q: Get content-type from HTML page with BeautifulSoup I am trying to get the character encoding for pages that I scrape, but in some cases it is failing. Here is what I am doing: resp = urllib2.urlopen(request) self.COOKIE_JAR.extract_cookies(resp, request) content = resp.read() encodeType= resp.headers.getparam('cha...
Get content-type from HTML page with BeautifulSoup
I am trying to get the character encoding for pages that I scrape, but in some cases it is failing. Here is what I am doing: resp = urllib2.urlopen(request) self.COOKIE_JAR.extract_cookies(resp, request) content = resp.read() encodeType= resp.headers.getparam('charset') resp.close() That is my first attempt. But if ch...
[ "I decided to just go with whatever BeautifulSoup spits out. Then as I parse through each word in the document, if I can't convert it to a string, I just disregard it.\nfor word in doc.lower().split(): \n try:\n word = str(word)\n word = self.handlePunctuation(word)\n if word...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "lambda", "python" ]
stackoverflow_0005411279_beautifulsoup_lambda_python.txt
Q: Predefined Protocol for Communicating Over stdin/stdout/pipes in Python? I have a process that creates several subprocesses with which it needs to coummunicate in Python 2.5. I use the subprocess module to start the processes, setting stdin and stdout to subprocess.PIPE. So far so good. In a loop, I then, run sele...
Predefined Protocol for Communicating Over stdin/stdout/pipes in Python?
I have a process that creates several subprocesses with which it needs to coummunicate in Python 2.5. I use the subprocess module to start the processes, setting stdin and stdout to subprocess.PIPE. So far so good. In a loop, I then, run select.select() on each subproccess's stdout stream waiting for them to tell me th...
[ "You could use json or pickle to encode the data structure that contains the message, and then use the same on the other side to read the message.\n", "There are frameworks that really help you to address this kind of functionalities. If you want to send more complex messages without bother about sync issues. Som...
[ 1, 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0005434089_multiprocessing_python.txt
Q: GUI Toolkit with Good Designer for Python I am looking for a GUI toolkit which also has a good designer (like visual studio) for Python language. It should have ...Good Documentation ...Good IDE + Designer ...Cross Platform Support (if possible) A: I'd try PySide (LGPL binding for QT) with QT Designer A: I'd r...
GUI Toolkit with Good Designer for Python
I am looking for a GUI toolkit which also has a good designer (like visual studio) for Python language. It should have ...Good Documentation ...Good IDE + Designer ...Cross Platform Support (if possible)
[ "I'd try PySide (LGPL binding for QT) with QT Designer\n", "I'd recommend PyGTK for a GUI toolkit with Glade as the designer.\n", "I am not sure about dnd like Visual Studio but wxPython is very good toolkit\nEDIT: QT Designer seems good too.\n", "I've used PyQt together with Qt Designer, nice documentation a...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "toolkit", "user_interface" ]
stackoverflow_0005432871_python_toolkit_user_interface.txt
Q: polymodel.PolyModel put() overriding i need to override the put method on my model because i need to do some special stuff while storing the entity. the code looks something like this: class Asset(polymodel.PolyModel): .... def put(self, rpc=None): # do something special return self class Image(Asset): ... ...
polymodel.PolyModel put() overriding
i need to override the put method on my model because i need to do some special stuff while storing the entity. the code looks something like this: class Asset(polymodel.PolyModel): .... def put(self, rpc=None): # do something special return self class Image(Asset): ... now my problem is that if i call Asset.pu...
[ "While it is possible to monkey-patch your classes to allow you to change the behavior of put(), you might be better off writing a method -- call it save() for the sake of argument -- that wraps the put() in a more explicit and obvious fashion and frees you from having to worry about having the patched behaviors be...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005433542_google_app_engine_python.txt
Q: Load website's content through python How can i load a specific content from a website through python?For example,i want to load some posts of a blog and appear them to my own site.How can i do this? A: An answer: import urllib2 from BeautifulSoup import BeautifulSoup def fetchtags(req, name, attrs, num): ...
Load website's content through python
How can i load a specific content from a website through python?For example,i want to load some posts of a blog and appear them to my own site.How can i do this?
[ "An answer:\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\ndef fetchtags(req, name, attrs, num):\n try:\n website = urllib2.urlopen(req)\n except urllib2.HTTPError, e:\n print 'A problem occured. Please try again.'\n return\n soup = BeautifulSoup(we...
[ 4, 2 ]
[]
[]
[ "load", "python" ]
stackoverflow_0005434520_load_python.txt
Q: How to do a multidimensional array in python? I need to do a data structure in python just like this: array( 1 => array(url => "http://wwww.ff.com", msg => "msg 1..."), 2 => array(url => "http://wwww.yy.com", msg => "msg 2..."), 3 => array(url => "http://wwww.xx.com", msg => "msg 3..."), ...
How to do a multidimensional array in python?
I need to do a data structure in python just like this: array( 1 => array(url => "http://wwww.ff.com", msg => "msg 1..."), 2 => array(url => "http://wwww.yy.com", msg => "msg 2..."), 3 => array(url => "http://wwww.xx.com", msg => "msg 3..."), ); I have search the documentation, but no clue. ...
[ "Simply use a list of dictionaries:\na = [{\"url\": \"http://wwww.ff.com\", \"msg\": \"msg 1...\"},\n {\"url\": \"http://wwww.yy.com\", \"msg\": \"msg 2...\"},\n {\"url\": \"http://wwww.xx.com\", \"msg\": \"msg 3...\"}]\nprint a[0][\"url\"]\n# http://wwww.ff.com\n\nAlternatively, you could use a list of tup...
[ 8, 1, 1 ]
[]
[]
[ "multidimensional_array", "python" ]
stackoverflow_0005434562_multidimensional_array_python.txt
Q: learn python the hard way exercise 40 help hey guys i am having trouble understanding this, i dont get when themap is referenced to the cities dict really. or the last line, what is the(cities, state) part? thanks. cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} cities['NY'] = 'New York' ...
learn python the hard way exercise 40 help
hey guys i am having trouble understanding this, i dont get when themap is referenced to the cities dict really. or the last line, what is the(cities, state) part? thanks. cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} cities['NY'] = 'New York' cities['OR'] = 'Portland' def find_city(themap,...
[ "cities['_find'] is exactly find_city. So cities['_find'](cities, state) is the same as find_city(cities, state). \nThe reason for my first statement is this line: \ncities['_find'] = find_city\n\nThat doesn't call find_city, it sticks the function itself in the dictionary. Python functions are just objects like li...
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0005434740_python.txt
Q: Pylons REPL reevaluate code in running web server I'm programming in python on a pre-existing pylons project (the okfn's ckan), but I'm a lisper by trade and used to that way of doing things. Please correct me if I make false statements: In pylons it seems that I should say $ paster serve --reload to get a web se...
Pylons REPL reevaluate code in running web server
I'm programming in python on a pre-existing pylons project (the okfn's ckan), but I'm a lisper by trade and used to that way of doing things. Please correct me if I make false statements: In pylons it seems that I should say $ paster serve --reload to get a web server that will notice changes. At that point I can cha...
[ "It seems that this way of working is impossible in python for the reason given by TokenMacGuy's comment, i.e. because redefining a class doesn't change the code in an instance of that class.\nThat seems a terrible shame, since in many other respects python seems very flexible, but it does explain why there's no py...
[ 1 ]
[]
[]
[ "pylons", "python", "read_eval_print_loop" ]
stackoverflow_0005424088_pylons_python_read_eval_print_loop.txt
Q: Persistent where clause SQLAlchemy I'm trying to add a persistent SQL where clause in SQLalchimy. Basically I have a table containing a specific field, and I want all my request to add a where clause, so this field matches a clause. For instance, if my request is session.query( MyTable ).all() I'd like the genera...
Persistent where clause SQLAlchemy
I'm trying to add a persistent SQL where clause in SQLalchimy. Basically I have a table containing a specific field, and I want all my request to add a where clause, so this field matches a clause. For instance, if my request is session.query( MyTable ).all() I'd like the generated request to be as such : SELECT * FRO...
[ "If you add:\ndbengine.echo = True\nsession.query(MyTable).filter_by(specified_field = 'some_value').all()\n\nI'm not sure what you mean by: 'without adding a filter to each request.' My guess is that you don't want to filter the request client-side. The generated SQL for this should look a lot like what you're ask...
[ 1, 0 ]
[]
[]
[ "mysql", "python", "sqlalchemy" ]
stackoverflow_0005433921_mysql_python_sqlalchemy.txt
Q: How to detect Meego/Maemo platform in Python? I develop cross-platform application for Maemo/Meego/Linux platforms using python (PySide). I use a workaround to distinguish between Maemo and Linux platfroms: try: import PySide.QtMaemo5 PLATFORM = 'maemo' except ImportError: PLATFORM = 'desktop' Does a...
How to detect Meego/Maemo platform in Python?
I develop cross-platform application for Maemo/Meego/Linux platforms using python (PySide). I use a workaround to distinguish between Maemo and Linux platfroms: try: import PySide.QtMaemo5 PLATFORM = 'maemo' except ImportError: PLATFORM = 'desktop' Does anyone know how to detect Meego platform or a better...
[ "Fist way: using platform module, for Maemo:\n>>> import platform\n>>> platform.machine()\n'armv71'\n>>> platform.node() ## This is Host Name, not a safe method\n'Nokia N900'\n\nSince platform is not helpfull at least for Maemo, I recommend the second (and safer) way: using /etc/issue:\nissue = open('/etc/issue').r...
[ 4, 1 ]
[]
[]
[ "cross_platform", "maemo", "meego", "pyside", "python" ]
stackoverflow_0005231222_cross_platform_maemo_meego_pyside_python.txt
Q: Django: Django QuerySet with Date SELECT working erratically Up until a couple days ago I have been using the following query succesfully. The following query has always returned the data it was supposed to return: try: totals = MyObject.objects.get(date=report_date) except MyObject.DoesNotExist: return HttpR...
Django: Django QuerySet with Date SELECT working erratically
Up until a couple days ago I have been using the following query succesfully. The following query has always returned the data it was supposed to return: try: totals = MyObject.objects.get(date=report_date) except MyObject.DoesNotExist: return HttpResponse('Could not find totals from %s' % (report_date)) A couple...
[ "why converting to the string? you do not have a control on how date is converted, eg. locale issues.\nswitch to date objects and set in views only:\nreport_date = date.today()\n\nand get data from the form's cleaned_data dict:\nreport_date = form.cleaned_data['date']\n\n", "The fact that date-based queries work ...
[ 1, 0 ]
[]
[]
[ "date", "django", "django_queryset", "python" ]
stackoverflow_0005433897_date_django_django_queryset_python.txt
Q: Python unit-testing in multiple threads I would like to unit-test the functionality of a few classes that mainly do file in- and output. Furthermore I would like to do that on multiple cores (--jobs=4). The problem is, that the files that are created by the classes often have the same name and they get mixed up i...
Python unit-testing in multiple threads
I would like to unit-test the functionality of a few classes that mainly do file in- and output. Furthermore I would like to do that on multiple cores (--jobs=4). The problem is, that the files that are created by the classes often have the same name and they get mixed up in multiple threads. What I do currently is th...
[ "I would suggest to use the unittest module and build the classes like this:\nimport unittest\nfrom tempfile import mkdtemp\n\nclass Test(unittest.TestCase):\n\n def setUp(self):\n self.tempdir = mkdtemp()\n os.chdir(self.tempdir)\n\n def tearDown(self):\n os.rmdir(self.tempdir)\n\n de...
[ 7 ]
[]
[]
[ "multithreading", "python", "unit_testing" ]
stackoverflow_0005433839_multithreading_python_unit_testing.txt
Q: pythonic implementation of Bayesian networks for a specific application This is why I'm asking this question: Last year I made some C++ code to compute posterior probabilities for a particular type of model (described by a Bayesian network). The model worked pretty well and some other people started to use my soft...
pythonic implementation of Bayesian networks for a specific application
This is why I'm asking this question: Last year I made some C++ code to compute posterior probabilities for a particular type of model (described by a Bayesian network). The model worked pretty well and some other people started to use my software. Now I want to improve my model. Since I'm already coding slightly diffe...
[ "I've been working on this kind of thing in my spare time for quite a while. I think I'm on my third or fourth version of this same problem right now. I'm actually getting ready to release another version of Fathom (https://github.com/davidrichards/fathom/wiki) with dynamic bayesian models included and a differen...
[ 22, 3, 2, 2 ]
[]
[]
[ "bayesian", "bayesian_networks", "python" ]
stackoverflow_0003783708_bayesian_bayesian_networks_python.txt
Q: Python-Script stops working when passing through a regex I have a big text file and I am processing it line by line using the for ... in statement: f = open(sys.argv[1]) for line in f: And I pass these lines through some regexes. But my code stops when this long line is being passed through a regex: This is the l...
Python-Script stops working when passing through a regex
I have a big text file and I am processing it line by line using the for ... in statement: f = open(sys.argv[1]) for line in f: And I pass these lines through some regexes. But my code stops when this long line is being passed through a regex: This is the line: Mar 25 09:42:22 2011 amavis[30883]: (30883-10) Passed CLE...
[ "It is possible to write regular expressions that take a very, very long time to either match or fail. you've written just such a regular expression. Basically any time you see * or + nested inside another * or + be very afraid.\nI think your problem may be:\n(<\\S*>,)*\n\nOn it's own, <\\S*> will match everything ...
[ 4, 0 ]
[]
[]
[ "python", "regex", "search" ]
stackoverflow_0005434010_python_regex_search.txt
Q: Python: Writing to a csv file from a 'list' of {(tuples): value} dicts Greetings All. I have a [(tuple): value] dicts as elements in a list as follows: lst = [{('unit1', 'test1'): 11, ('unit1','test2'): 12}, {('unit2','test1'): 13, ('unit2','test2'):14 }] testnames = ['test1','test2'] unitnames = ['unit1','unit2'...
Python: Writing to a csv file from a 'list' of {(tuples): value} dicts
Greetings All. I have a [(tuple): value] dicts as elements in a list as follows: lst = [{('unit1', 'test1'): 11, ('unit1','test2'): 12}, {('unit2','test1'): 13, ('unit2','test2'):14 }] testnames = ['test1','test2'] unitnames = ['unit1','unit2'] How to write to csv file with the following output? unitnames, test1, tes...
[ "First, flatten the structure.\nunits = collections.defaultdict(lambda: collections.defaultdict(lambda: float('-inf')))\nfor (u, t), r in lst.iteritems():\n units[u][t] = r\ntable = [(u, t['test1'], t['test2']) for (u, t) in units.iteritems()]\n\nThen use csv to write out the CSV file.\n", "Following code create...
[ 4, 1, 1 ]
[]
[]
[ "csv", "dictionary", "list", "python", "tuples" ]
stackoverflow_0005432109_csv_dictionary_list_python_tuples.txt
Q: Passing Python array to c++ function with SWIG I have written a good bit of code in python and it works great. But now I'm scaling up the size of the problems that I'm analyzing and python is dreadfully slow. The slow part of the python code is for i in range(0,H,1): x1 = i - length x2 = i + len...
Passing Python array to c++ function with SWIG
I have written a good bit of code in python and it works great. But now I'm scaling up the size of the problems that I'm analyzing and python is dreadfully slow. The slow part of the python code is for i in range(0,H,1): x1 = i - length x2 = i + length for j in range(0,W,1): #print i...
[ "You can use arrays as it is described here: Doc - 5.4.5 Arrays, the carray.i or std_vector.i from the SWIG library. \nI find it easier to work with std::vector from the SWIG library std_vector.i to send a python list to a C++ SWIG extension. Though in your case where optimization matters, it may not be the optimal...
[ 11 ]
[]
[]
[ "c++", "multidimensional_array", "python", "swig" ]
stackoverflow_0005251042_c++_multidimensional_array_python_swig.txt
Q: Converting Python App into Django I've got a Python program with about a dozen classes, with several classes possessing instances of other classes, e.g. ObjectA has a list of ObjectB's, and a dictionary of (ObjectC, ObjectD) pairs. My goal is to put the program's functionality on a website. I've written and tested...
Converting Python App into Django
I've got a Python program with about a dozen classes, with several classes possessing instances of other classes, e.g. ObjectA has a list of ObjectB's, and a dictionary of (ObjectC, ObjectD) pairs. My goal is to put the program's functionality on a website. I've written and tested JSON encode and decode methods for eac...
[ "Man, what I think you can do is convert the classes you already have made into django model classes. Of course, only the ones that need to be saved to a database. The other classes, as the rest of the code, I recommend you to encapsulate them for use as helper functions. So you don't have to change too much your c...
[ 1 ]
[]
[]
[ "database_design", "django", "json", "python" ]
stackoverflow_0005435169_database_design_django_json_python.txt
Q: Could someone explain this python permutation code? I've seen some postings of code for permutations on here but I haven't really been able to find a good step-by-step walk through of what is actually going on. If someone could just explain what is actually happening in each step of this code I would really apprec...
Could someone explain this python permutation code?
I've seen some postings of code for permutations on here but I haven't really been able to find a good step-by-step walk through of what is actually going on. If someone could just explain what is actually happening in each step of this code I would really appreciate it. I can't quite seem to wrap my head around it. Th...
[ "def all_perms(str):\n # If there is only one item, there can be only one permutation\n # yield the single item\n if len(str) <=1:\n yield str\n else:\n # loop over the permutations returned by a recursive call to all_perms\n # note it is passing a subset of the list passed in.\n ...
[ 2, 1, 1 ]
[]
[]
[ "algorithm", "permutation", "python" ]
stackoverflow_0005435412_algorithm_permutation_python.txt
Q: Why is sys.maxint < (sys.maxint - 100 + 0.01) in Python? Why is sys.maxint < (sys.maxint - 100 + 0.01) in Python? A: This is probably due to loss of precision for very large floating point values. (the adding of 0.01 converts the right-hand-side to float). Edit: I have tried to come up with an exact explanation ...
Why is sys.maxint < (sys.maxint - 100 + 0.01) in Python?
Why is sys.maxint < (sys.maxint - 100 + 0.01) in Python?
[ "This is probably due to loss of precision for very large floating point values. (the adding of 0.01 converts the right-hand-side to float).\nEdit: I have tried to come up with an exact explanation of what happens here, but to no avail. So I posted a question about it.\n", "at least on my machine it is not\nIn [7...
[ 12, 3, 3 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0005429860_floating_point_python.txt
Q: Issue parsing a xhtml page using Python Hello i am trying to parse a page in xhtml with python but i receive this error: **xml.parsers.expat.ExpatError: unbound prefix: line 6, column 0** [Fri Mar 25 09:58:21 2011] [error] [client 127.0.0.1] mod_wsgi (pid=9156): Exception occurred processing WSGI script '/home/hi...
Issue parsing a xhtml page using Python
Hello i am trying to parse a page in xhtml with python but i receive this error: **xml.parsers.expat.ExpatError: unbound prefix: line 6, column 0** [Fri Mar 25 09:58:21 2011] [error] [client 127.0.0.1] mod_wsgi (pid=9156): Exception occurred processing WSGI script '/home/hidura/webapps/karinapp/Suite/Gate.py'. [Fri Ma...
[ "The problem is expat is using fb as the namespace prefix, but that tag is FB:LOGIN-BUTTON. Expat sees FB as unbound. The XHTML specification notes that all HTML elements and attributes must be lowercase since XML is case-sensitive.\nI tried your document using the lxml XML parser and it auto-converted the prefixe...
[ 2 ]
[ "I think the problem is that http://www.facebook.com/2008/fbml is a not found page\n" ]
[ -1 ]
[ "python", "python_3.x", "xhtml", "xml" ]
stackoverflow_0005434288_python_python_3.x_xhtml_xml.txt
Q: How to preserve page position in the wx.html.HtmlWindow after link clicked? I have a wx python application with wx.html.HtmlWindow window: class MyHtmlWindow(wx.html.HtmlWindow): Method SetPage is used to update html content on the window: def OpenURL(self, url, save_scroll_pos=True): def callback(src, url, s...
How to preserve page position in the wx.html.HtmlWindow after link clicked?
I have a wx python application with wx.html.HtmlWindow window: class MyHtmlWindow(wx.html.HtmlWindow): Method SetPage is used to update html content on the window: def OpenURL(self, url, save_scroll_pos=True): def callback(src, url, save_scroll_pos): pos = self.GetViewStart()[1] self.SetPage(src) ...
[ "Great Thanks to Wx Developers. They provide very usefull methods: Freeze and Thaw.\nThis is very easy solution:\ndef OpenURL(self, url, save_scroll_pos=True):\n def callback(src, url, save_scroll_pos):\n pos = self.GetViewStart()[1]\n self.Freeze()\n self.SetPage(src)\n if save_scrol...
[ 0 ]
[]
[]
[ "python", "wxhtmlwindow", "wxwidgets" ]
stackoverflow_0005405918_python_wxhtmlwindow_wxwidgets.txt
Q: How to make a Python program handle a here document? I've written a Python wrapper (pyprog) to run a program (someprogram), something like this: ...do some setup stuff in Python... print("run [y=yes]") CHOICE=input() ...do some setup stuff in Python... if CHOICE == "y": status=subprocess.call(["someprogram"]) ...
How to make a Python program handle a here document?
I've written a Python wrapper (pyprog) to run a program (someprogram), something like this: ...do some setup stuff in Python... print("run [y=yes]") CHOICE=input() ...do some setup stuff in Python... if CHOICE == "y": status=subprocess.call(["someprogram"]) sys.exit(status) A user wants to use a shell script to ru...
[ "You need to connect sys.stdin to the stdin of the call.\nstatus=subprocess.call([\"someprogram\"], stdin=sys.stdin)\n\n", "import sys\nstatus=subprocess.call([\"someprogram\"], stdin=sys.stdin)\n\n", "I've used something like this a few times before: https://gist.github.com/887225\nBasically it's a python scr...
[ 4, 1, 0 ]
[]
[]
[ "python", "shell", "subprocess" ]
stackoverflow_0005435866_python_shell_subprocess.txt
Q: Best matches for a partially specified word in Python I have a file dict.txt that has all words in the English language. The user will input their word: x = raw_input("Enter partial word: ") Example inputs would be: r-n, --n, -u-, he--o, h-llo and so on, unknown characters would be specified by a underscore prefer...
Best matches for a partially specified word in Python
I have a file dict.txt that has all words in the English language. The user will input their word: x = raw_input("Enter partial word: ") Example inputs would be: r-n, --n, -u-, he--o, h-llo and so on, unknown characters would be specified by a underscore preferably instead of (-). I want the program to come up with a l...
[ "One easy way to do this would be by using regular expressions. Since it is unclear whether this question is homework, the details are left as an exercise for the reader.\n", "Instead of using _ to denote wildcards, use \\w instead. Add \\b to the beginning and end of the pattern, then just run the dictionary thr...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005435367_python.txt
Q: Retrieve feed from a specific category with appengine python youtube api http://code.google.com/apis/youtube/articles/youtube_api_appengine.html Following this tutorial I am able to retrive the most recent video feeds for my service. feed = client.GetRecentlyFeaturedVideoFeed() with the above command, I would li...
Retrieve feed from a specific category with appengine python youtube api
http://code.google.com/apis/youtube/articles/youtube_api_appengine.html Following this tutorial I am able to retrive the most recent video feeds for my service. feed = client.GetRecentlyFeaturedVideoFeed() with the above command, I would like to retrieve videos for the four standar youtube categories news, comedy, sp...
[ "It was quite simple in a similar post\nfeed = client.GetYouTubeVideoFeed('http://gdata.youtube.com/feeds/api/videos/-/Comedy?v=2')\n\nand the relevant post: How to get the public channel URL from YouTubeVideoFeed object using the YouTube API?\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python", "youtube_api" ]
stackoverflow_0005436381_google_app_engine_python_youtube_api.txt
Q: Possible to limit filters ManyToMany/Foreign Key in Django admin for a model where the relationship is defined on the other model? So the title is a bit obtuse, I know, but I couldn't think of a more succinct way to state it. Here's the issue: I've created two proxy models for "user types", both inheriting from dj...
Possible to limit filters ManyToMany/Foreign Key in Django admin for a model where the relationship is defined on the other model?
So the title is a bit obtuse, I know, but I couldn't think of a more succinct way to state it. Here's the issue: I've created two proxy models for "user types", both inheriting from django.contrib.auth.User. Each has a custom manager limiting the queryset to items belonging to a particular Group. Specifically, there's ...
[ "So, I was able to solve my own problem. For those that might run into a similar situation, here are the steps:\nThe approach I took is to modify the change_list.html template and manually filter out the items I didn't want to be included. There's quite a number of changes to make, though.\nFirst, add a changelist_...
[ 3, 1 ]
[]
[]
[ "django", "django_admin", "django_admin_filters", "python" ]
stackoverflow_0005435175_django_django_admin_django_admin_filters_python.txt
Q: how to load Alignment format in python? Is there a way to load alignment file to python. If I have file like this: <?xml version='1.0' encoding='utf-8' standalone='no'?> <rdf:RDF xmlns='http://knowledgeweb.semanticweb.org/heterogeneity/alignment#' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:xsd='...
how to load Alignment format in python?
Is there a way to load alignment file to python. If I have file like this: <?xml version='1.0' encoding='utf-8' standalone='no'?> <rdf:RDF xmlns='http://knowledgeweb.semanticweb.org/heterogeneity/alignment#' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:xsd='http://www.w3.org/2001/XMLSchema#' xmlns:alig...
[ "Try with Redland libraries:\nhttp://librdf.org/docs/python.html\nimport RDF\nparser = RDF.Parser(name=\"rdfxml\")\nmodel = RDF.Model()\nparser.parse_into_model(model, \"file:./align.rdf\", None)\n\nAnd then query the model variable. For example, in order to retrieve all the alignments and return their measure, the...
[ 3 ]
[]
[]
[ "alignment", "python", "rdflib" ]
stackoverflow_0005436238_alignment_python_rdflib.txt
Q: Is it somehow possible to *live* modify Python code (like in Lisp or Erlang) I was wondering if it is somehow possible to modify Python code live, while keeping all state of instantiated objects and methods, like I think is possible in Lisp or Erlang (*) ? Say, I have an active Python sessions, where I instantiate...
Is it somehow possible to *live* modify Python code (like in Lisp or Erlang)
I was wondering if it is somehow possible to modify Python code live, while keeping all state of instantiated objects and methods, like I think is possible in Lisp or Erlang (*) ? Say, I have an active Python sessions, where I instantiated the foo class from a self-written module: class foo(): @classmethod def do...
[ "Yes you can, pretty simple too. You want to change only the instance f, not the class foo, right?\n>>> class foo():\n @classmethod\n def do_something(self):\n print \"this is good\"\n\n\n>>> f = foo()\n>>> f.do_something()\nthis is good\n>>> def new_ds():\n print \"this is better\"\n\n\n>>> f.do_...
[ 6, 5, 0 ]
[]
[]
[ "erlang", "lisp", "python" ]
stackoverflow_0005432964_erlang_lisp_python.txt
Q: Error when trying to assign blob object The following code for h in hits: urls.append(h['url']) result = db.Blob(urlfetch.Fetch(h['url']).content) model.image = result returns the error cannot concatenate 'str' and 'NoneType' objects. A: Use some debug printing to find out if urlfetch.Fetch(h['u...
Error when trying to assign blob object
The following code for h in hits: urls.append(h['url']) result = db.Blob(urlfetch.Fetch(h['url']).content) model.image = result returns the error cannot concatenate 'str' and 'NoneType' objects.
[ "Use some debug printing to find out if urlfetch.Fetch(h['url']).content is even returning anything. Based on the error, the result is None and db.Blob() is expecting the result to be a string.\nIf so, plan accordingly by checking the value of content before trying to apply it. And maybe a little error tracking f...
[ 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0005436122_django_google_app_engine_python.txt
Q: python: How to determine if a string contains a tuple? I need a clean way to determine if a string is actually a tuple, like so: '(123,456)' --> True 'hello world' --> False I can think of two ways to do this: a regex call eval and catch/ignore a SyntaxError I don't like the second option. I'm fine with the fir...
python: How to determine if a string contains a tuple?
I need a clean way to determine if a string is actually a tuple, like so: '(123,456)' --> True 'hello world' --> False I can think of two ways to do this: a regex call eval and catch/ignore a SyntaxError I don't like the second option. I'm fine with the first option but just wanted to know if there was a better way ...
[ "def represents_tuple(s):\n try: return type(ast.literal_eval(s)) == tuple\n except SyntaxError: return False\n except ValueError: return False\n\n", "If the tuple inside the string can only have simple numbers, then use a regex. If the tuple members can be arbitrarily complex (such as nested lists), use...
[ 7, 0 ]
[]
[]
[ "eval", "python", "string", "tuples" ]
stackoverflow_0005436420_eval_python_string_tuples.txt
Q: How do I show my argspec/docstring in bpython? I'm just starting to use bpython, mainly because I really think it will help the office nubs a lot. In bpython, it continually shows help text as you type. For example >>> zip( ┌────────────────────────────────────────────────────────────────────────┐ │ zip: (seq1 [,...
How do I show my argspec/docstring in bpython?
I'm just starting to use bpython, mainly because I really think it will help the office nubs a lot. In bpython, it continually shows help text as you type. For example >>> zip( ┌────────────────────────────────────────────────────────────────────────┐ │ zip: (seq1 [, seq2 [...]]) ...
[ "Add your documentation string as the first line of your function:\ndef funct():\n \"This function is self-documenting\"\n pass\n\nUse triple quotes if it spans multiple lines:\ndef funct():\n \"\"\"\n This function doesn't expect arguments\n and returns zero.\n \"\"\"\n return 0\n\nTo get at...
[ 3, 0 ]
[]
[]
[ "bpython", "python" ]
stackoverflow_0005436848_bpython_python.txt
Q: How to deal with configuration variables in Python? I'm new to Python and I'm doing some tests with it. What I need to know is what is the best way of dealing with configuration variables. For example, for this code: import twitter import random import sqlite3 import time import bitly_api #https://github.com/bitly...
How to deal with configuration variables in Python?
I'm new to Python and I'm doing some tests with it. What I need to know is what is the best way of dealing with configuration variables. For example, for this code: import twitter import random import sqlite3 import time import bitly_api #https://github.com/bitly/bitly-api-python class TwitterC: def logto...
[ "You could use ConfigParser out of the Python Standard Library.\n", "Or you could use argparse if you want to pass in configuration from the command line. \nThen when creating the TwitterC class, you could pass in the configuration options you want.\nclass TwitterC:\n def __init__(self, database):\n sel...
[ 2, 2, 0 ]
[]
[]
[ "configuration", "python", "variables" ]
stackoverflow_0005436444_configuration_python_variables.txt
Q: Python regular expression; why do the search & match appear to find alpha chars in a number string? I'm running search below Idle, in Python 2.7 in a Windows Bus. 64 bit environment. According to RegexBuddy, the search pattern ('patternalphaonly') should not produce a match against a string of digits. I looked at ...
Python regular expression; why do the search & match appear to find alpha chars in a number string?
I'm running search below Idle, in Python 2.7 in a Windows Bus. 64 bit environment. According to RegexBuddy, the search pattern ('patternalphaonly') should not produce a match against a string of digits. I looked at "http://docs.python.org/howto/regex.html", but did not see anything there that would explain why the sear...
[ "The star operator (*) indicates zero or more repetitions. Your string has zero repetitions of an English alphabet letter because it is entirely numbers, which is perfectly valid when using the star (repeat zero times). Instead use the + operator, which signifies one or more repetitions. Example:\n>>> n = \"3534543...
[ 7, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005436506_python_regex.txt
Q: SPI_SETSCREENSAVETIMEOUT not working on Windows 7 using Python and ctypes I'm using ctypes to call the SystemParametersInfo() API function to set the screen saver timeout value. It works fine on Windows XP but not on Windows 7. The code I'm using is the following: import ctypes user32 = ctypes.windll.LoadLibrary(...
SPI_SETSCREENSAVETIMEOUT not working on Windows 7 using Python and ctypes
I'm using ctypes to call the SystemParametersInfo() API function to set the screen saver timeout value. It works fine on Windows XP but not on Windows 7. The code I'm using is the following: import ctypes user32 = ctypes.windll.LoadLibrary("user32") user32.SystemParametersInfoA(15, 5, 0, 3) The code invokes the scree...
[ "That works absolutely fine for me. My guess is that you have no screensaver selected.\nWhen I changed my settings and selected \"(None)\" as my screensaver then the call to SystemParametersInfo had no effect.\n" ]
[ 2 ]
[]
[]
[ "ctypes", "python", "winapi" ]
stackoverflow_0005436558_ctypes_python_winapi.txt
Q: python 3 variable used in another variable's name? in python 3 (with tkinter) i have the following images: SqImg1 = PhotoImage(file='SqImg1.gif') SqImg2 = PhotoImage(file='SqImg2.gif') SqImg3 = PhotoImage(file='SqImg3.gif') SqImg4 = PhotoImage(file='SqImg4.gif') ... i also have a function that needs to return one...
python 3 variable used in another variable's name?
in python 3 (with tkinter) i have the following images: SqImg1 = PhotoImage(file='SqImg1.gif') SqImg2 = PhotoImage(file='SqImg2.gif') SqImg3 = PhotoImage(file='SqImg3.gif') SqImg4 = PhotoImage(file='SqImg4.gif') ... i also have a function that needs to return one of those images based on a variable. so if the functio...
[ "There's your mistake straight away:\nSqImg1 = PhotoImage(file='SqImg1.gif')\nSqImg2 = PhotoImage(file='SqImg2.gif')\nSqImg3 = PhotoImage(file='SqImg3.gif')\nSqImg4 = PhotoImage(file='SqImg4.gif')\n...\n\nshould be:\nSqImg = [\nPhotoImage(file='SqImg1.gif'),\nPhotoImage(file='SqImg2.gif'),\nPhotoImage(file='SqImg3....
[ 2, 0 ]
[]
[]
[ "function", "python", "python_3.x", "var", "variables" ]
stackoverflow_0005437106_function_python_python_3.x_var_variables.txt
Q: Can the switch statement have more than one variable? The question is based in all the languages that use the switch block (C++, C# PHP , Java , Python and so on). So is it possible to have something like this? switch (var1, var2) case var1 = a: something break; case var2 = b: something break; cas...
Can the switch statement have more than one variable?
The question is based in all the languages that use the switch block (C++, C# PHP , Java , Python and so on). So is it possible to have something like this? switch (var1, var2) case var1 = a: something break; case var2 = b: something break; case var1 = 0 ,var2 = 1 etc...
[ "Python does not have a switch statement. The recommended alternative is using a chained if/else chain - which is what you ought to be using in your case anyway.\nAnother common idiom is using a map. And in your case you could use a tuple of (var1,var2) to match against results.\nswitch = {\n (1,2): lambda: ..,\n...
[ 5, 4, 2, 2, 2, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "c#", "java", "php", "python", "switch_statement" ]
stackoverflow_0005436983_c#_java_php_python_switch_statement.txt
Q: Asynchronous input notification from Windows console I need to get user input from console asynchronously, i.e. without blocking. I could use the following Python code to check if there is an input available, but it gives 100% CPU load. import msvcrt while not msvcrt.kbhit(): pass Is there any other way to do...
Asynchronous input notification from Windows console
I need to get user input from console asynchronously, i.e. without blocking. I could use the following Python code to check if there is an input available, but it gives 100% CPU load. import msvcrt while not msvcrt.kbhit(): pass Is there any other way to do this? Is it possible to register a callback function for ...
[ "Using the Win32 API, you would normally call WaitForMultipleObjects along with your other events to find out which occurred first, the standard input handle itself will be considered triggered whenever any input is available.\n\nA process can specify a console input buffer handle in one of the wait functions to de...
[ 2, 0, 0 ]
[]
[]
[ "console", "python", "windows" ]
stackoverflow_0005437182_console_python_windows.txt
Q: python standard input Possible Duplicate: How do you read from stdin in python Hi All, I am a newbie in python. I was wondering how I could manage to get data from standard input, such as getline in c++ and similar, so that from terminal/console I can use a text file as an input for a python script. Thanks A: ...
python standard input
Possible Duplicate: How do you read from stdin in python Hi All, I am a newbie in python. I was wondering how I could manage to get data from standard input, such as getline in c++ and similar, so that from terminal/console I can use a text file as an input for a python script. Thanks
[ "You can use sys.stdin. It acts like a file object, so treat it as one when you use it:\n#!/usr/bin/env python\nimport sys\n\nprint sys.stdin.read()\n\nRunning this by itself hangs the interpreter, but adding a pipe operator does what it should:\n> echo \"asd\" | python test.py\n> asd\n\n" ]
[ 5 ]
[]
[]
[ "input", "python" ]
stackoverflow_0005437292_input_python.txt
Q: Why do Perl's and Python's output of print with "\n" differ? Why do I need to put "\n" twice after "Content-Type: text/html" with Perl, but only once with Python? For example, the following Python script works: #!/usr/bin/python print "Content-Type: text/html\n" print "Hello World!" But the following Perl script ...
Why do Perl's and Python's output of print with "\n" differ?
Why do I need to put "\n" twice after "Content-Type: text/html" with Perl, but only once with Python? For example, the following Python script works: #!/usr/bin/python print "Content-Type: text/html\n" print "Hello World!" But the following Perl script doesn't work (it gives a premature end of script headers error mes...
[ "Because print in Python prints with a newline and print in Perl does not.\nprint \"Hello world!\" in Python is equivalent to print \"Hello world!\\n\" in perl. Perl 6 has a say command which does the same thing as Python's print, but sadly, Perl 6 has no stable implementations. In Perl 5.10 or later, you can use ...
[ 15, 10, 1 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0005437269_perl_python.txt