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: Extract feeds from web page I'm looking for a code snippet (language is not important here) that will extract all feeds (RSS, atom etc.) that is associated with this page. So input is URL and output list of channels. Important is completeness, it means if the page has associated some information channel it should ...
Extract feeds from web page
I'm looking for a code snippet (language is not important here) that will extract all feeds (RSS, atom etc.) that is associated with this page. So input is URL and output list of channels. Important is completeness, it means if the page has associated some information channel it should be found. I'm asking preferably f...
[ "You find feeds in the head tag in html files. There they should be specified as link tags with an associated content type and a href attribute specifying it's location.\nTo extract all feed urls from a page using python you could use something like this:\nimport urllib\nfrom HTMLParser import HTMLParser\n\nclass F...
[ 4 ]
[]
[]
[ "feed", "javascript", "python", "rss", "text_extraction" ]
stackoverflow_0007607066_feed_javascript_python_rss_text_extraction.txt
Q: pyramid_handlers not working I'm currently moving a project from Pylons 1.0 to Pyramid. My problem so far is how to use restful routes in Pyramid. I'm currently using pyramid_handlers since it seemed like a good start. I'm using Akhet. So here is the two important lines in my route: config.add_handler("new_acco...
pyramid_handlers not working
I'm currently moving a project from Pylons 1.0 to Pyramid. My problem so far is how to use restful routes in Pyramid. I'm currently using pyramid_handlers since it seemed like a good start. I'm using Akhet. So here is the two important lines in my route: config.add_handler("new_account", "/accounts/new", "sproci2.ha...
[ "Well a call to add_handler needs an action pattern. So that's either adding {action} to the url pattern, or setting action= as an argument. Those actions must match the names defined in @action decorators. In your example, you named the action new_account, yet you called add_handler with an action of new. Thus the...
[ 0 ]
[]
[]
[ "akhet", "pyramid", "python", "restful_architecture" ]
stackoverflow_0007588190_akhet_pyramid_python_restful_architecture.txt
Q: Python unintuitive member variable behaviour This script: class testa(): a = [] class testb(): def __init__(self): self.a = [] ta1 = testa(); ta1.a.append(1); ta2 = testa(); ta2.a.append(2) tb1 = testb(); tb1.a.append(1); tb2 = testb(); tb2.a.append(2) print ta1.a, ta2.a, tb1.a, tb2.a produces ...
Python unintuitive member variable behaviour
This script: class testa(): a = [] class testb(): def __init__(self): self.a = [] ta1 = testa(); ta1.a.append(1); ta2 = testa(); ta2.a.append(2) tb1 = testb(); tb1.a.append(1); tb2 = testb(); tb2.a.append(2) print ta1.a, ta2.a, tb1.a, tb2.a produces this output: [1, 2] [1, 2] [1] [2] but I expected...
[ "In testa the variable a is a class variable and is shared between all instances. ta1.a and ta2.a refer to the same list.\nIn testb the variable a is an object variable. Each instance has its own value.\nSee Class and Object Variables for more details.\n", "One is a class variable, the other is an instance variab...
[ 7, 4, 3, 0 ]
[]
[]
[ "class", "python", "variables" ]
stackoverflow_0007606582_class_python_variables.txt
Q: sql nested select parsing Situation: I have several SSRS reports of which I need the sql-code to be documented. For this I need the code to be formatted in exactly the same way time and time again. Problem: In some of my reports I have structures like select outer from ( select outin from ( select inner from ( sel...
sql nested select parsing
Situation: I have several SSRS reports of which I need the sql-code to be documented. For this I need the code to be formatted in exactly the same way time and time again. Problem: In some of my reports I have structures like select outer from ( select outin from ( select inner from ( select innerMax from )z where )x w...
[ "This is trickier than you might think: split, substring and regex will not be enough to reliably tackle this problem. Consider comments, or string literals inside your SQL code that might contain text that looks like SQL or contains parenthesis which will mess up your indentation levels.\nA better way is to use an...
[ 1 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0007607848_parsing_python.txt
Q: Make pyplot faster than gnuplot I recently decided to give matplotlib.pyplot a try, while having used gnuplot for scientific data plotting for years. I started out with simply reading a data file and plot two columns, like gnuplot would do with plot 'datafile' u 1:2. The requirements for my comfort are: Skip lin...
Make pyplot faster than gnuplot
I recently decided to give matplotlib.pyplot a try, while having used gnuplot for scientific data plotting for years. I started out with simply reading a data file and plot two columns, like gnuplot would do with plot 'datafile' u 1:2. The requirements for my comfort are: Skip lines beginning with a # and skip empty ...
[ "Since you have matplotlib installed, you must also have numpy installed. numpy.genfromtxt meets all your requirements and should be much faster than parsing the file yourself in a Python loop:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport textwrap\nfname='/tmp/tmp.dat'\nwith open(fname,'w') as f:\...
[ 6, 2 ]
[]
[]
[ "gnuplot", "matplotlib", "python" ]
stackoverflow_0007608099_gnuplot_matplotlib_python.txt
Q: NLP algorithm to 'fill out' search terms I'm trying to write an algorithm (which I'm assuming will rely on natural language processing techniques) to 'fill out' a list of search terms. There is probably a name for this kind of thing which I'm unaware of. What is this kind of problem called, and what kind of algori...
NLP algorithm to 'fill out' search terms
I'm trying to write an algorithm (which I'm assuming will rely on natural language processing techniques) to 'fill out' a list of search terms. There is probably a name for this kind of thing which I'm unaware of. What is this kind of problem called, and what kind of algorithm will give me the following behavior? Input...
[ "\nIt should basically figure out that if \"Dolphin\" appears at all, it's virtually always either in the bigrams \"Dolphin Watching\" or \"Miami Dolphins\".\n\nSounds like you want to determine the collocations that Dolphin occurs in. There are various methods for collocation finding, the most popular being to com...
[ 7, 0 ]
[]
[]
[ "n_gram", "nlp", "python" ]
stackoverflow_0007604492_n_gram_nlp_python.txt
Q: In Matplotlib, is there a way to know the list of available output format According to Matplotlib documentation, matplotlib.figure.save_figtakes an optional argument format (see matplotlib.figure documentation). This parameters takes 'one of the file extensions supported by the active backend' (as said by the offi...
In Matplotlib, is there a way to know the list of available output format
According to Matplotlib documentation, matplotlib.figure.save_figtakes an optional argument format (see matplotlib.figure documentation). This parameters takes 'one of the file extensions supported by the active backend' (as said by the official documentation). My point is: how to know, for a specific backend, the list...
[ "If you create a figure, you can get the available supported file format with the canvas object : \nimport matplotlib.pyplot as plt\nfig = plt.figure()\n\nprint fig.canvas.get_supported_filetypes()\n\n>>> {\n 'svgz': 'Scalable Vector Graphics', \n 'ps': 'Postscript', \n 'emf': 'Enhanced Metafile', \n 'rgba'...
[ 42, 4, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007608066_matplotlib_python.txt
Q: Not able to overwrite kml file I generate KML files on-the-fly.After generating, I call Google maps like this : http://maps.google.com/maps?q=http://<my ip>:8081/<location>/<name>.kml . The name of the file I use is based on the lat/long of the starting location entered by the user. Obviously, when the locat...
Not able to overwrite kml file
I generate KML files on-the-fly.After generating, I call Google maps like this : http://maps.google.com/maps?q=http://<my ip>:8081/<location>/<name>.kml . The name of the file I use is based on the lat/long of the starting location entered by the user. Obviously, when the location is same, a new kml file is gene...
[ "A google query on Google Maps Caching KML seems to indicate that Google are caching KML files for about 5 minutes.\nA simple solution is to add a random query to your URL, so instead of linking to http://maps.google.com/maps?q=http://<my ip>:8081/<location>/<name>.kml, you would link to http://maps.google.com/maps...
[ 3 ]
[]
[]
[ "kml", "python", "simplekml" ]
stackoverflow_0007608246_kml_python_simplekml.txt
Q: Django url pattern with or without as path to view? I'm new to Django and been reading the http://djangobook.com and finds that the following two patterns work the same way with no hiccups for project named mysite and views.py on the project root with a function named hello. (r'^hello/$', 'mysite.views.hello') (r...
Django url pattern with or without as path to view?
I'm new to Django and been reading the http://djangobook.com and finds that the following two patterns work the same way with no hiccups for project named mysite and views.py on the project root with a function named hello. (r'^hello/$', 'mysite.views.hello') (r'^hello/$', 'views.hello) May I know what's the practice ...
[ "the fisrt one is because the mysite dir is in your python path;\nthe second one is because when your run the project, the current path will add to python path.\n" ]
[ 1 ]
[]
[]
[ "django", "python", "urlconf" ]
stackoverflow_0007608576_django_python_urlconf.txt
Q: Python: How to read all text file contents in multiple folders and save them into one excel file I am currently working on this task and got stuck. Please give me your advices. The code I am writing below, it returns only the .txt file name from multiple folders, while I would like to print out the content of each...
Python: How to read all text file contents in multiple folders and save them into one excel file
I am currently working on this task and got stuck. Please give me your advices. The code I am writing below, it returns only the .txt file name from multiple folders, while I would like to print out the content of each .txt file and save in different rows in excel. The contents of each .txt file are numbers. import os,...
[ "Well, you see the file names because you write them. L contains the file name. (And the L = file.strip() seems unnecessary to me.)\nIf you want to write the file contents, you should do instead L = open(os.path.join(dir, file), \"r\").read().\n", "If you want to write the file contents, you should do instead \nw...
[ 2, 2 ]
[]
[]
[ "excel", "python", "text", "xlwt" ]
stackoverflow_0007606827_excel_python_text_xlwt.txt
Q: How much input validation should I be doing on my python functions/methods? I'm interested in how much up front validation people do in the Python they write. Here are a few examples of simple functions: def factorial(num): """Computes the factorial of num.""" def isPalindrome(inputStr): """Tests to see i...
How much input validation should I be doing on my python functions/methods?
I'm interested in how much up front validation people do in the Python they write. Here are a few examples of simple functions: def factorial(num): """Computes the factorial of num.""" def isPalindrome(inputStr): """Tests to see if inputStr is the same backwards and forwards.""" def sum(nums): """Same as ...
[ "I assert what's absolutely essential.\nImportant: What's absolutely essential. Some people over-test things.\ndef factorial(num):\n assert int(num)\n assert num > 0\n\nIsn't completely correct. long is also a legal possibility.\ndef factorial(num):\n assert type(num) in ( int, long )\n assert num > 0...
[ 9, 7, 5, 4, 2, 1, 0, 0 ]
[]
[]
[ "python", "validation" ]
stackoverflow_0000367560_python_validation.txt
Q: Replacing particular elements in a list Code: >>> mylist = ['abc','def','ghi'] >>> mylist ['abc', 'def', 'ghi'] >>> for i,v in enumerate(mylist): ... if v=='abc': ... mylist[i] = 'XXX' ... >>> mylist ['XXX', 'def', 'ghi'] >>> Here, I try to replace all the occurrences of 'abc' with 'XXX'. Is the...
Replacing particular elements in a list
Code: >>> mylist = ['abc','def','ghi'] >>> mylist ['abc', 'def', 'ghi'] >>> for i,v in enumerate(mylist): ... if v=='abc': ... mylist[i] = 'XXX' ... >>> mylist ['XXX', 'def', 'ghi'] >>> Here, I try to replace all the occurrences of 'abc' with 'XXX'. Is there a shorter way to do this?
[ "Instead of using an explicit for loop, you can use a list comprehension. This allows you to iterate over all the elements in the list and filter them or map them to a new value.\nIn this case you can use a conditional expression. It is similar to (v == 'abc') ? 'XXX' : v in other languages.\nPutting it together, ...
[ 14, 11 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007609335_list_python.txt
Q: Is it a convention to prefix private classes with underscores? I have seen code in which functions/constants are prefixed with underscores. My understanding is that this indicates that they are not to be used directly. Can I do this with classes ? class _Foo(object): pass class __Bar(object): pass A: Be...
Is it a convention to prefix private classes with underscores?
I have seen code in which functions/constants are prefixed with underscores. My understanding is that this indicates that they are not to be used directly. Can I do this with classes ? class _Foo(object): pass class __Bar(object): pass
[ "Better only use one _. This indicates that a name is private within a module.\nIt is not imported with the catch-all from <module> import *, and it has some other features such as \"preferred destruction\".\nFrom here:\n\nIf __all__ is not defined, the set of public names includes all names\n found in the module’...
[ 10, 6, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007609508_python.txt
Q: For what reason do we have the lower_case_with_underscores naming convention? Depending on your interpretation this may or may not be a rhetorical question, but it really baffles me. What sense does this convention make? I understand naming conventions don't necessarily have to have a rhyme or reason behind them, ...
For what reason do we have the lower_case_with_underscores naming convention?
Depending on your interpretation this may or may not be a rhetorical question, but it really baffles me. What sense does this convention make? I understand naming conventions don't necessarily have to have a rhyme or reason behind them, but why deviate from the already popular camelCase? Is there a rhyme and reason beh...
[ "camelCase and/or CamelCase (and that's a debate in its own right;-) may be overwhelmingly most popular for the kind of environments you are most familiar with, but that hardly makes them universal -- or have you never heard of the obscure language called C++, with its std::find_first_of and std::replace_copy_if al...
[ 53, 20, 16, 7, 5, 3, 2, 2, 1, 0 ]
[]
[]
[ "camelcasing", "naming_conventions", "pep8", "python" ]
stackoverflow_0001740116_camelcasing_naming_conventions_pep8_python.txt
Q: Automate firefox with python? Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions? A: You could try selenium. A: The PyXPCOM extension is one possibility. But looking at what firewatir provides, I have to 2nd the suggestion for twill. I...
Automate firefox with python?
Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?
[ "You could try selenium.\n", "The PyXPCOM extension is one possibility.\nBut looking at what firewatir provides, I have to 2nd the suggestion for twill. It's based on mechanize, which might also be useful in this context.\n", "I use Selenium RC. All my tests are written in Python and are run with test suite.\nO...
[ 5, 4, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "automation", "firefox", "linux", "python", "ubuntu" ]
stackoverflow_0000060152_automation_firefox_linux_python_ubuntu.txt
Q: python/pygame, pass input from a class to another class there is a way to pass a value or a variable from a class to another class without having to pass through the main function I'm using python A: well, of course you can access other objects attributes in methods of a specific object. e.g: class A(object): ...
python/pygame, pass input from a class to another class
there is a way to pass a value or a variable from a class to another class without having to pass through the main function I'm using python
[ "well, of course you can access other objects attributes in methods of a specific object. e.g:\nclass A(object):\n def method(self, other):\n other.somevar = 5\n\nclass B(object):\n pass\n\ndef main():\n a = A()\n b = B()\n\n b.somevar = \"Hello World\"\n a.method(b)\n print(b.somevar) ...
[ 1 ]
[]
[]
[ "class", "oop", "pygame", "python" ]
stackoverflow_0007610531_class_oop_pygame_python.txt
Q: Storing data in memcache to be accessed by different languages I am working on a system that has components written in the following languages: C C++ C# PHP Python These components all use (infrequently changing) data that comes from the same source and can be cached and accesed from memcache for performance rea...
Storing data in memcache to be accessed by different languages
I am working on a system that has components written in the following languages: C C++ C# PHP Python These components all use (infrequently changing) data that comes from the same source and can be cached and accesed from memcache for performance reasons. Because different data types may be stored differently by diff...
[ "memcached I think primarily only understands byte[] and representation of byte is same in all languages. You can serialize your objects using protocol buffers or a similar library and consume it in any other language. I've done this in my projects.\n", "Regardless of the back-end chosen, (memcached, mongodb, red...
[ 3, 1, 0 ]
[]
[]
[ "c#", "c++", "memcached", "php", "python" ]
stackoverflow_0007609940_c#_c++_memcached_php_python.txt
Q: Python: how to keep only first 50 char of a string I have a string which x = "very_long_string_more_than_50_char_long" I want to keep only first 50 char and delete the rest. how would i do that? thanks A: x = x[:50] For details on slices like this, refer to the documentation. A: use the powerful slicing mec...
Python: how to keep only first 50 char of a string
I have a string which x = "very_long_string_more_than_50_char_long" I want to keep only first 50 char and delete the rest. how would i do that? thanks
[ "x = x[:50]\n\nFor details on slices like this, refer to the documentation.\n", "use the powerful slicing mechanism:\nx = x[:50]\n\n", "You could use slicing\nx = \"very_long_string_more_than_50_char_long\"\nprint x[0:50]\n\n", ">>> x = \"fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\...
[ 16, 5, 3, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007610694_python_string.txt
Q: Unable to iterate over ManyToMany - how do I calculate the sum? My models look like this: class Article(models.Model): name = models.CharField(max_length=50) description = models.TextField() price = models.FloatField() def __unicode__(self): return "%s - %s" % (self.name, self.price) class Order(models.Model...
Unable to iterate over ManyToMany - how do I calculate the sum?
My models look like this: class Article(models.Model): name = models.CharField(max_length=50) description = models.TextField() price = models.FloatField() def __unicode__(self): return "%s - %s" % (self.name, self.price) class Order(models.Model): client = models.ForeignKey(User) articles = models.ManyToManyField...
[ "I'd replace your total field with a property:\nclass Order():\n ....\n @property\n def total(self):\n return self.articles.aggregate(Sum('price'))['price__sum']\n\nthe reason is: when you add items to collection your object is not saved again, so it wouldn't update your counter. With this property ...
[ 4, 1, 0 ]
[]
[]
[ "django", "django_models", "many_to_many", "python" ]
stackoverflow_0007610457_django_django_models_many_to_many_python.txt
Q: get windows service used memory using wmi I'm trying to retrieve the amount of memory used by a windows service, for example, IIS. I'm using python and windows wmi extensions. I didn't find any method on WIN32_Service class that would give me the information I need. What's the best approach to get this information...
get windows service used memory using wmi
I'm trying to retrieve the amount of memory used by a windows service, for example, IIS. I'm using python and windows wmi extensions. I didn't find any method on WIN32_Service class that would give me the information I need. What's the best approach to get this information?
[ "Information concerning process memory is exposed through WMI using the Win32_Process class. In particular, you'd probably be interested in the WorkingSetSize and VirtualSize properties. Since you are starting from a service, you will want to obtain the ProcessId property from your service in order to select the ap...
[ 1 ]
[]
[]
[ "python", "wmi" ]
stackoverflow_0007609476_python_wmi.txt
Q: How to improve my performance in filling gaps in time series and data lists with Python I'm having a time series data sets comprising of 10 Hz data over several years. For one year my data has around 3.1*10^8 rows of data (each row has a time stamp and 8 float values). My data has gaps which I need to identify and...
How to improve my performance in filling gaps in time series and data lists with Python
I'm having a time series data sets comprising of 10 Hz data over several years. For one year my data has around 3.1*10^8 rows of data (each row has a time stamp and 8 float values). My data has gaps which I need to identify and fill with 'NaN'. My python code below is capable of doing so but the performance is by far t...
[ "First, realize that your innermost loop is not necessary:\nfor it in range(num_fills):\n data_a.insert(i+1+it+shift, float(nan))\n\nis the same as\ndata_a[i+1+shift:i+1+shift] = [float(nan)] * int(num_fills)\n\nThat might make it slightly faster because there's less allocation and less moving items going on.\nT...
[ 4, 1 ]
[]
[]
[ "math", "numeric", "optimization", "performance", "python" ]
stackoverflow_0007610576_math_numeric_optimization_performance_python.txt
Q: Open Source Scripting Languages that work well with Microsoft SQL Server I have been using PHP for a number of years now and have found it to be (relatively) well documented, easy to work with, to setup and to use. One of its main advantages is its capablility of working, without many modifications, similarly on a...
Open Source Scripting Languages that work well with Microsoft SQL Server
I have been using PHP for a number of years now and have found it to be (relatively) well documented, easy to work with, to setup and to use. One of its main advantages is its capablility of working, without many modifications, similarly on a Windows or *nix platforms. It also has good support for connecting to Microso...
[ "Both Ruby and Python should be able to connect to MS SQL databases.\nPython libraries:\n\nPyTDS\npymssql\n\nRuby libraries:\n\nTinyTDS - doesn't seem to be DBI compliant, but there is an ActiveRecord adapter.\n\n", "Ruby on Rails / ActiveRecord has support for mssql, using the activerecord-sqlserver-adapter gem....
[ 1, 0 ]
[]
[]
[ "node.js", "php", "python", "ruby", "sql_server" ]
stackoverflow_0007610815_node.js_php_python_ruby_sql_server.txt
Q: Python Convert Unicode-Hex utf-8 strings to Unicode strings Have s = u'Gaga\xe2\x80\x99s' but need to convert to t = u'Gaga\u2019s' How can this be best achieved? A: s = u'Gaga\xe2\x80\x99s' t = u'Gaga\u2019s' x = s.encode('raw-unicode-escape').decode('utf-8') assert x==t print(x) yields Gaga’s A: Where ever...
Python Convert Unicode-Hex utf-8 strings to Unicode strings
Have s = u'Gaga\xe2\x80\x99s' but need to convert to t = u'Gaga\u2019s' How can this be best achieved?
[ "s = u'Gaga\\xe2\\x80\\x99s'\nt = u'Gaga\\u2019s'\nx = s.encode('raw-unicode-escape').decode('utf-8')\nassert x==t\n\nprint(x)\n\nyields\nGaga’s\n\n", "Where ever you decoded the original string, it was likely decoded with latin-1 or a close relative. Since latin-1 is the first 256 codepoints of Unicode, this wo...
[ 8, 7, 2 ]
[]
[]
[ "python", "unicode", "utf_8" ]
stackoverflow_0007609776_python_unicode_utf_8.txt
Q: Logging problems when using modules individually I'm making extensive use of the logging module in all my own modules. This works fine when I create a configuration for the logging module in my main routine. But when I want to test one of my modules individually in an interactive shell and logging.getLogger("foo")...
Logging problems when using modules individually
I'm making extensive use of the logging module in all my own modules. This works fine when I create a configuration for the logging module in my main routine. But when I want to test one of my modules individually in an interactive shell and logging.getLogger("foo") is executed I get the error: No handlers could be fo...
[ "It is explained in the Logging module How-To. You could create a helper module to be included wherever you perform any logging:\nimport logging\nlogging.getLogger('your_top_level_package').addHandler(logging.NullHandler())\n\n" ]
[ 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0007610792_logging_python.txt
Q: QT push button and a python lambda function I'm just trying to create a UI for my script in maya/py using QT Designer. The problem is that I want to use a lambda expression as a command for my buttons by adding a dynamic property with the type set to string, property name set to "+command" and lambda x: print('fo...
QT push button and a python lambda function
I'm just trying to create a UI for my script in maya/py using QT Designer. The problem is that I want to use a lambda expression as a command for my buttons by adding a dynamic property with the type set to string, property name set to "+command" and lambda x: print('fobar!') as the value. But running the code back in...
[ "How about:\nbutton_name.clicked.connect(lambda : print('foobar'))\n\n" ]
[ 0 ]
[]
[]
[ "designer", "maya", "python", "qt", "user_interface" ]
stackoverflow_0007611060_designer_maya_python_qt_user_interface.txt
Q: wxpython event not triggering I'm following the example given in http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/ I have a thread which is checking an sftp server for new files every 30 seconds. If it finds files, it uploads them to a db, and then it should trigger an update of certain GUI elemen...
wxpython event not triggering
I'm following the example given in http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/ I have a thread which is checking an sftp server for new files every 30 seconds. If it finds files, it uploads them to a db, and then it should trigger an update of certain GUI elements which will reload from the db. T...
[ "Events don't propagate to its children so if MyGrid is a child of your main frame, events posted in the main won't make it through to MyGrid. What you can do instead is bind the event handler directly to your function within the instance of MyGrid like so:\n\"\"\"from MainWindow\"\"\"\nself._workerthread = FtpThre...
[ 1, 0 ]
[]
[]
[ "events", "python", "wxpython" ]
stackoverflow_0007608666_events_python_wxpython.txt
Q: CherryPy Returning Status 301 on nsIXMLHttpRequest (but works fine for firefox HTTP request) I am developing a web API in using CherryPy. The intent is that it is accessed by JavaScript through nslXMLHttpRequest. When I access the API through Firefox (as though it were an ordinary-variety URL), the following appea...
CherryPy Returning Status 301 on nsIXMLHttpRequest (but works fine for firefox HTTP request)
I am developing a web API in using CherryPy. The intent is that it is accessed by JavaScript through nslXMLHttpRequest. When I access the API through Firefox (as though it were an ordinary-variety URL), the following appears in my logs: !!!SUCCESS!!! [my IP] - - [30/Sep/2011:08:30:19] "GET /myAPI/ HTTP/1.1" 200 11 "" "...
[ "Probably because /myAPI and /myAPI/ are not the same URI, so it's redirecting you from one to the other. You can fine-tune this behavior with http://docs.cherrypy.org/dev/refman/lib/cptools.html#cherrypy.lib.cptools.trailing_slash\n" ]
[ 4 ]
[]
[]
[ "ajax", "cherrypy", "python" ]
stackoverflow_0007610444_ajax_cherrypy_python.txt
Q: PIL - are there a any PIL solutions that will allow you to take a screenshot of a specified web page? Is there a way to take a screenshot using PIL of an specified HTML/Javascript page that resides on my server? I want to write a script that will change some parameters on that HTML page and then have PIL take scre...
PIL - are there a any PIL solutions that will allow you to take a screenshot of a specified web page?
Is there a way to take a screenshot using PIL of an specified HTML/Javascript page that resides on my server? I want to write a script that will change some parameters on that HTML page and then have PIL take screenshots of it. Any ideas? Examples would be truly appreciated.
[ "Do you absolutely have to use PIL? If not you might be able to get what you want using PyQT which has a built-in Webkit control.\nSee http://notes.alexdong.com/xhtml-to-pdf-using-pyqt4-webkit-and-headless for an example which converts html+css into a PDF without using a separate browser. The code is pretty short s...
[ 2 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0007611179_python_python_imaging_library.txt
Q: Python String to List with RegEx I would like to convert mystring into list. Input : "(11,4) , (2, 4), (5,4), (2,3) " Output: ['11', '4', '2', '4', '5', '4', '2', '3'] >>>mystring="(11,4) , (2, 4), (5,4), (2,3)" >>>mystring=re.sub(r'\s', '', mystring) #remove all whilespaces >>>print mystring (11,4),(2,4),(5,4),...
Python String to List with RegEx
I would like to convert mystring into list. Input : "(11,4) , (2, 4), (5,4), (2,3) " Output: ['11', '4', '2', '4', '5', '4', '2', '3'] >>>mystring="(11,4) , (2, 4), (5,4), (2,3)" >>>mystring=re.sub(r'\s', '', mystring) #remove all whilespaces >>>print mystring (11,4),(2,4),(5,4),(2,3) >>>splitter = re.compile(r'[\...
[ ">>> re.findall(r'\\d+', \"(11,4) , (2, 4), (5,4), (2,3) \")\n['11', '4', '2', '4', '5', '4', '2', '3']\n\n", "It would be better to remove whitespace and round brackets and then simply split on comma.\n", ">>> alist = ast.literal_eval(\"(11,4) , (2, 4), (5,4), (2,3) \")\n\n>>> alist\n((11, 4), (2, 4), (5, 4), ...
[ 8, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007611359_python_regex.txt
Q: Pydev with Scapy Gives "Unresolved Import" Error I'm trying to write a program that uses the scapy modules. I'm using PyDev for my development but it keeps giving me errors when I import certain parts of the Scapy module. I'm pretty sure I have my import paths in PyDev set up correctly. I've looked at some of t...
Pydev with Scapy Gives "Unresolved Import" Error
I'm trying to write a program that uses the scapy modules. I'm using PyDev for my development but it keeps giving me errors when I import certain parts of the Scapy module. I'm pretty sure I have my import paths in PyDev set up correctly. I've looked at some of the other questions involving "Unresolved Import" error...
[ "Have you tried adding 'scapy' to the forced builtins? See: http://pydev.org/manual_101_interpreter.html for details.\n", "I got a chance to play some more with this. I still don't know why PyDev gives me an import error when it works fine in the interpreter, however, I did find a way around it. To import thing...
[ 0, 0 ]
[]
[]
[ "pydev", "python", "scapy" ]
stackoverflow_0007600418_pydev_python_scapy.txt
Q: Django ImageField "Upload a valid image. The file you uploaded was either not an image or a corrupted image." I have PIL installed, however whenever I try to upload a .png file to an image field through the Django Admin for my model, I get this error: "Upload a valid image. The file you uploaded was either not an ...
Django ImageField "Upload a valid image. The file you uploaded was either not an image or a corrupted image."
I have PIL installed, however whenever I try to upload a .png file to an image field through the Django Admin for my model, I get this error: "Upload a valid image. The file you uploaded was either not an image or a corrupted image." Other image types work fine. I have tried several different PNG files. I have tried r...
[ "This issue was solved by using pip to install \"pillow\" instead of \"pil\" which allows easy deployment to virtualenv.\n", "When you compile PIL it should say if it has been compiled with PNG support or not, but if you have problems installing it yourself, I would recommend that you use the version that comes w...
[ 7, 3, 0 ]
[]
[]
[ "django", "python", "virtualenv" ]
stackoverflow_0007606614_django_python_virtualenv.txt
Q: Why is Eclipse python autocomplete adding the self parameter? I recently started to use PyDev and the method autocomplete seems to be stupid: I select the method name in the dropdown list, click enter and it completes the line adding the self parameter, but in Python you are not supposed to specify the self parame...
Why is Eclipse python autocomplete adding the self parameter?
I recently started to use PyDev and the method autocomplete seems to be stupid: I select the method name in the dropdown list, click enter and it completes the line adding the self parameter, but in Python you are not supposed to specify the self parameter when you call the methods!?
[ "If you are writing a new method in a Class, it does this. But not if you have previously decorated with for example @staticmethod, this is what gets autocompleted for me in PyDev:\ndef normal_method(): #nothing gets autoinserted\n pass\n\nclass Foo:\n def instance_method(self): #self gets autoinserted\n ...
[ 1 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0007611510_eclipse_pydev_python.txt
Q: Ctypes definition How could I write the definition copied bellow using ctypes? unsigned char* x = new unsigned char[10]; Thank you. A: Depending on how you need to use x, you probably want ctypes.create_string_buffer. x = ctypes.create_string_buffer(' ' * 10);
Ctypes definition
How could I write the definition copied bellow using ctypes? unsigned char* x = new unsigned char[10]; Thank you.
[ "Depending on how you need to use x, you probably want ctypes.create_string_buffer.\nx = ctypes.create_string_buffer(' ' * 10);\n\n" ]
[ 1 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0007611771_ctypes_python.txt
Q: Checking if Two Massive Python Dictionaries are Equivalent I have a massive python dictionary with over 90,000 entries. For reasons I won't get into, I need to store this dictionary in my database and then at a later point recompile dictionary from the database entries. I am trying to set up a procedure to verify...
Checking if Two Massive Python Dictionaries are Equivalent
I have a massive python dictionary with over 90,000 entries. For reasons I won't get into, I need to store this dictionary in my database and then at a later point recompile dictionary from the database entries. I am trying to set up a procedure to verify that my storage and recompilation was faithful and that my new ...
[ "The most obvious approach is of course:\nif oldDict != newDict:\n print \"**Failure to rebuild, new dictionary is different from the old\"\n\nThat ought to be the fastest possible, since it relies on Python's internals to do the comparison.\nUPDATE: It seems you're not after \"equal\", but something weaker. I thi...
[ 13, 2, 2 ]
[]
[]
[ "dictionary", "python", "python_2.7", "transformation" ]
stackoverflow_0007611854_dictionary_python_python_2.7_transformation.txt
Q: Matplotlib inset polar plot I'm trying to inset a polar plot inside a normal x vs y plot in cartesian coordinate. I know that inset can be obtained through pylab.axes as illustrated in this example. But I do not know how to specify this is a polar plot, possibly without any grid. Any help is welcomed A: Here you...
Matplotlib inset polar plot
I'm trying to inset a polar plot inside a normal x vs y plot in cartesian coordinate. I know that inset can be obtained through pylab.axes as illustrated in this example. But I do not know how to specify this is a polar plot, possibly without any grid. Any help is welcomed
[ "Here you have a working example.\nThe main point is to specify a new, smaller axes for the second figure\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import randn, convolve\n\n#data\nt = np.arange(0.0, 20.0, 0.001)\nr = np.exp(-t[:1000]/0.05) \nx = randn(len(t))\ns = convolve(x,r)[:len...
[ 5 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007610973_matplotlib_python.txt
Q: zc.buildout is using the wrong python I'm using zc.buildout to generate a script called "test". I'm using that script to call my own test runner. (The available test runners for buildout do not yet use the new "discovery" feature in Python 2.7.) Anyhow, here's the relevant section in my .cfg file: [test] recipe ...
zc.buildout is using the wrong python
I'm using zc.buildout to generate a script called "test". I'm using that script to call my own test runner. (The available test runners for buildout do not yet use the new "discovery" feature in Python 2.7.) Anyhow, here's the relevant section in my .cfg file: [test] recipe = buildout_script template = runtests.sh.in...
[ "In your bash script, your are relying upon $PATH to determine which python to use. To change which python is invoked, you have several choices:\n\nModify your environment to prefer a different version, i.e. in ~/.bashrc, add export PATH=/path/to/desired/python/bin:$PATH (of course with the appropriate substitutio...
[ 0, 0 ]
[]
[]
[ "egg", "python" ]
stackoverflow_0007612034_egg_python.txt
Q: Variables of form __something__ What is the purpose of python variables __something__ e.g. __name__, __file__ I often see them in real python programs. Is there a list of these variables? thank you A: PEP8 covers this: In addition, the following special forms using leading or trailing underscores are recogniz...
Variables of form __something__
What is the purpose of python variables __something__ e.g. __name__, __file__ I often see them in real python programs. Is there a list of these variables? thank you
[ "PEP8 covers this:\n\nIn addition, the following special forms using leading or trailing\n underscores are recognized (these can generally be combined with any\n case convention):\n\n_single_leading_underscore: weak \"internal use\" indicator. E.g.\n \"from M\n import *\" does not import objects whose name s...
[ 5, 1, 1 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0007612245_python_variables.txt
Q: How to verify date format using selenium How can I verify that a date displayed on the web page fits a particular format with Python bindings for Selenium-RC? A: I would grab the date (using whatever selector is appropriate), then try to parse it with Python's strftime. If the parser raises an exception the date...
How to verify date format using selenium
How can I verify that a date displayed on the web page fits a particular format with Python bindings for Selenium-RC?
[ "I would grab the date (using whatever selector is appropriate), then try to parse it with Python's strftime. If the parser raises an exception the date is likely incorrect.\n" ]
[ 0 ]
[]
[]
[ "python", "selenium_rc" ]
stackoverflow_0007578572_python_selenium_rc.txt
Q: Why isn't the exception caught by << try >>? I have a Python (Django) unit test FAIL from an exception, but the failing code is in a try / except block written for that exception. A similar block handles the exception when it is directly raised. This passes: # - - - - - - - - - - - - - - - - - - - - - - - - - - -...
Why isn't the exception caught by << try >>?
I have a Python (Django) unit test FAIL from an exception, but the failing code is in a try / except block written for that exception. A similar block handles the exception when it is directly raised. This passes: # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Code catches a directly raised ...
[ "Did you define your own ImmediateHttpResponse? (I so, do not do that.) It's possible to get the symptom you are describing if tastypie is raising a\ntastypie.exceptions.ImmediateHttpResponse while your unit test is testing for \na locally defined ImmediateHttpResponse.\nIf so, to fix the problem, delete your defin...
[ 3, 0 ]
[]
[]
[ "django", "exception_handling", "python", "tastypie", "unit_testing" ]
stackoverflow_0007612255_django_exception_handling_python_tastypie_unit_testing.txt
Q: python subprocess and unicode execv() arg 2 must contain only strings I have a django site where I need to call a script using subprocess. The subprocess call works when I'm using ascii characters but when I try to issue arguments that are utf-8 encoded, I get an error: execv() arg 2 must contain only strings. Th...
python subprocess and unicode execv() arg 2 must contain only strings
I have a django site where I need to call a script using subprocess. The subprocess call works when I'm using ascii characters but when I try to issue arguments that are utf-8 encoded, I get an error: execv() arg 2 must contain only strings. The string u'Wiadomo\u015b\u0107' is coming from a postgres db. This example ...
[ "You should encode the Unicode strings in the encoding your program expects. If you know the program expects UTF-8:\nu'Wiadomo\\u015b\\u0107'.encode('utf8')\n\nIf you don't know what encoding you need, you could try your platform's default encoding:\nu'Wiadomo\\u015b\\u0107'.encode()\n\n" ]
[ 17 ]
[]
[]
[ "python", "subprocess", "unicode" ]
stackoverflow_0007612727_python_subprocess_unicode.txt
Q: Django MakeMessages missing xgettext in Windows Running Django on Windows 7. I'm currently trying to translate a couple of Django templates using the instructions found in the django book chapter 19. I've added a translation tag to the template, loaded I18N, and modified django settings. Then I run django-admin.py...
Django MakeMessages missing xgettext in Windows
Running Django on Windows 7. I'm currently trying to translate a couple of Django templates using the instructions found in the django book chapter 19. I've added a translation tag to the template, loaded I18N, and modified django settings. Then I run django-admin.py makemessages -l en to create the po files. All folde...
[ "please see http://code.djangoproject.com/ticket/1157. you do not need cygwin. try these files: http://sourceforge.net/projects/gettext/files/\nEDIT:\nhttp://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/gettext-tools-0.17.zip\nhttp://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/gettext-runtime-0.17-1....
[ 16 ]
[]
[]
[ "django", "python", "windows_7", "xgettext" ]
stackoverflow_0007612259_django_python_windows_7_xgettext.txt
Q: why 'gst.Element.get_request_pad(self.filter, 'filter')' returns 'None' (gstreamer | python) I am new to gstreamer and its development. I am trying to mix RTP streams using Gstreamer Python. The client sends the different videotest sources and the mixing of these streams should happen on the receiver side using RT...
why 'gst.Element.get_request_pad(self.filter, 'filter')' returns 'None' (gstreamer | python)
I am new to gstreamer and its development. I am trying to mix RTP streams using Gstreamer Python. The client sends the different videotest sources and the mixing of these streams should happen on the receiver side using RTP. This should be possible for atleast four participants. The receiver side will have a videotestb...
[ "Here is the solution finally I found. :) \nI forgot to keep in mind that I have to use 'rtpbin' which I am receiving it from client. The Pad properties of 'gstrtpbin' ($gst-inspect gstrtpbin) are as follows. \nPad Templates:\n SINK template: 'recv_rtp_sink_%d'\n Availability: On request\n Has request_new_...
[ 0 ]
[]
[]
[ "gstreamer", "python" ]
stackoverflow_0007601573_gstreamer_python.txt
Q: gettext usage for 2 strings that are the same Is there a more compact way if I want 2 keys have the same value? This works: msgid "Next" msgstr "Pág. seguinte" msgid "Next page" msgstr "Pág. seguinte" I could imagine writing it like this instead but is it legal? msgid "Next", "Next page" msgstr "Pág. seguinte" ...
gettext usage for 2 strings that are the same
Is there a more compact way if I want 2 keys have the same value? This works: msgid "Next" msgstr "Pág. seguinte" msgid "Next page" msgstr "Pág. seguinte" I could imagine writing it like this instead but is it legal? msgid "Next", "Next page" msgstr "Pág. seguinte" I have more questions about gettext, what do you re...
[ "i think best option is split words in code like:\na = _('next')\nb = '%s %s' % ( _('next'), _('page') )\n\nand in .po\nmsgid \"Next\"\nmsgstr \"seguinte\"\nmsgid \"page\"\nmsgstr \"Pág.\"\n\nwhy you need to translate html special characters ? For example, &copy; on all languages ©\n" ]
[ -3 ]
[]
[]
[ "gettext", "internationalization", "multilingual", "python" ]
stackoverflow_0007612964_gettext_internationalization_multilingual_python.txt
Q: Difficulty installing and using Mercurial Chart extension Hi I'm having trouble installing and using the Mercurial ChartExtension When I installed it as per instructions First you need to install the extension; type this in your shell: python ./setup.py install Blockquote I then modified my mercurial.ini ...
Difficulty installing and using Mercurial Chart extension
Hi I'm having trouble installing and using the Mercurial ChartExtension When I installed it as per instructions First you need to install the extension; type this in your shell: python ./setup.py install Blockquote I then modified my mercurial.ini file as follows [extensions] chart=/path/to/chart.py B...
[ "Based on the changelog, the Chart extension has not been updated since late 2008. It would probably work if you tried using it with a version of Mercurial released around that same time (Mercurial v1.1.2 was released on Dec. 30, 2008).\nThe latest version of Mercurial is now v1.9.2. The API has changed (probably...
[ 0 ]
[]
[]
[ "mercurial", "python", "tortoisehg_2.0", "windows" ]
stackoverflow_0007610805_mercurial_python_tortoisehg_2.0_windows.txt
Q: How can I run a program in msys through Python? I've got a short python script that will eventually edit an input file, run an executable on that input file and read the output from the executable. The problem is, I've compiled the executable through msys, and can only seem to run it from the msys window. I'm wond...
How can I run a program in msys through Python?
I've got a short python script that will eventually edit an input file, run an executable on that input file and read the output from the executable. The problem is, I've compiled the executable through msys, and can only seem to run it from the msys window. I'm wondering if the easiest way to do this is to somehow use...
[ "\nFind where in the msys path libgcc_s_dw2-1.dll is. \nFind the environmental variable in MSYS that has that path in it.\nAdd that environmental variable to Windows.\n\n" ]
[ 1 ]
[]
[]
[ "msys", "python" ]
stackoverflow_0007613525_msys_python.txt
Q: Creating a minidump in a Python application (Windows) I'm working on a Python application. Sometimes the interpreter crashes when in a third party C++ DLL. I'm thinking about writing a Python extension that installs a handler for unhandled structured exceptions (Windows) in order to write a minidump to the disk an...
Creating a minidump in a Python application (Windows)
I'm working on a Python application. Sometimes the interpreter crashes when in a third party C++ DLL. I'm thinking about writing a Python extension that installs a handler for unhandled structured exceptions (Windows) in order to write a minidump to the disk and log the stack trace of every Python thread. Two questions...
[ "Check out FaultHandler on PyPI.\n", "I recently wanted to do the same thing and created minidumper to do so, and did a small write-up of it here.\n" ]
[ 1, 1 ]
[]
[]
[ "crash_dumps", "python", "stack_trace", "winapi" ]
stackoverflow_0007405915_crash_dumps_python_stack_trace_winapi.txt
Q: How to get the fatest way of getting the maximum values element-wised of "n" matrices in Python/Numpy? I had like to know the best fatest/optimized way of getting the maximum values element-wised of "n" matrices in Python/Numpy. For example: import numpy as np matrices=[np.random.random((5,5)) for i in range(10)] ...
How to get the fatest way of getting the maximum values element-wised of "n" matrices in Python/Numpy?
I had like to know the best fatest/optimized way of getting the maximum values element-wised of "n" matrices in Python/Numpy. For example: import numpy as np matrices=[np.random.random((5,5)) for i in range(10)] # the function np.maximum from numpy only works for two matrices. max_matrix=np.maximum(matrices[0],matrices...
[ "Use reduce:\nreduce(np.maximum, matrices)\n\nFrom the docs:\n\nreduce(function, iterable[, initializer])\nApply function of two arguments cumulatively to the items of iterable,\n from left to right, so as to reduce the iterable to a single value.\n For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculate...
[ 5, 3 ]
[]
[]
[ "matrix", "max", "numpy", "performance", "python" ]
stackoverflow_0007614084_matrix_max_numpy_performance_python.txt
Q: how to open many text files with python I have 800 text files about protein. Actually I should make a matrix 800 in 800 to compare interaction between proteins. I entered their names in a list. Because writing all names in program is difficult. Now I want to open them in the python programming to use. But I don’t...
how to open many text files with python
I have 800 text files about protein. Actually I should make a matrix 800 in 800 to compare interaction between proteins. I entered their names in a list. Because writing all names in program is difficult. Now I want to open them in the python programming to use. But I don’t know what the program is to do it. import cs...
[ "Do not write your filenames in code. Instead, do one of the following:\n\nStore your file names in a data store of some sort, like an XML file or database, and use that data store to open your files, or\nWrite a function that generates the file names based on existing information about the proteins.\n\nAlso, cons...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007613472_python.txt
Q: improving my python script I have an interesting python script (not sure if it has been done before) It uses import os os.system("say %s" % say) #and I have added; os.system("say -v whisper %s" % say) but now there are new voices in lion and i want to know how to get those voices and if there is a centralized ...
improving my python script
I have an interesting python script (not sure if it has been done before) It uses import os os.system("say %s" % say) #and I have added; os.system("say -v whisper %s" % say) but now there are new voices in lion and i want to know how to get those voices and if there is a centralized list.
[ "The manual doesn't doc which voices are available. But I believe the syntax is just using the name like so:\n> say -v Karen Hello\n\nI don't have access to my Mac right now but I found this list from here:\n\nAmerican English: Jill, Samantha and Tom \nAustralian English: Karen and Lee\nBritish English: Daniel, Em...
[ 4, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007614610_python.txt
Q: in python, how to match Strings based on Regular Expression and get the non-matching parts as a list? For example: I have a string "abcde2011-09-30.log", I want to check if this string matchs "(\d){4}-(\d){2}-(\d){2}" ( dont think it has correct syntax, but you get the idea). And I need to split the string into 3 ...
in python, how to match Strings based on Regular Expression and get the non-matching parts as a list?
For example: I have a string "abcde2011-09-30.log", I want to check if this string matchs "(\d){4}-(\d){2}-(\d){2}" ( dont think it has correct syntax, but you get the idea). And I need to split the string into 3 parts: (abcde),(e2011-09-30), (.log). How can I do it in python? Thanks.
[ "There's a split method in the re module that should work for you.\n>>> s = 'abcde2011-09-30.log'\n>>> re.split('(\\d{4}-\\d{2}-\\d{2})', s)\n('abcde', '2011-09-30', '.log')\n\nIf you don't actually want the date as part of the returned list, just omit the parentheses around the regular expression so that it doesn'...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007614634_python_regex.txt
Q: pyqt: long process in file open dialog I have little experience in GUI programming but I'm writing a GUI application with PyQt. With this application, user can open a binary file and do some editing with it. When the file is opened, I do some processing that takes a while (~15s). So when the user pick the file an...
pyqt: long process in file open dialog
I have little experience in GUI programming but I'm writing a GUI application with PyQt. With this application, user can open a binary file and do some editing with it. When the file is opened, I do some processing that takes a while (~15s). So when the user pick the file and press the "Open" button in the file open d...
[ "Load in the background showing the progress via a Gauge in the statusbar.\nTo to this, you can initiate the loading using QThread. Your thread class can look as follows (assuming parent will have an attribute progress):\nQtFileLoader(QtCore.QThread):\n def __init__(self,parent=None, filepath=None):\n QtC...
[ 2, 2, 1 ]
[]
[]
[ "pyqt4", "python", "qt" ]
stackoverflow_0007614830_pyqt4_python_qt.txt
Q: Flask's @before_request executes more than once I added an app.logger.error('test') inside my @app.before_request and noticed that there are up to 8 lines of test in my log per request, even if it's just abort(500). I just can't seem to find out why, what could cause this? A: If you run with app.debug = True and...
Flask's @before_request executes more than once
I added an app.logger.error('test') inside my @app.before_request and noticed that there are up to 8 lines of test in my log per request, even if it's just abort(500). I just can't seem to find out why, what could cause this?
[ "If you run with app.debug = True and serve media files (images, css, js etc.) from Flask, they also count as full requests. If that is not the case, then please provide some more information about your setup.\n" ]
[ 6 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0007615317_flask_python.txt
Q: python: unintentionally modifying parameters passed into a function A few times I accidentally modified the input to a function. Since Python has no constant references, I'm wondering what coding techniques might help me avoid making this mistake too often? Example: class Table: def __init__(self, fields, raw_da...
python: unintentionally modifying parameters passed into a function
A few times I accidentally modified the input to a function. Since Python has no constant references, I'm wondering what coding techniques might help me avoid making this mistake too often? Example: class Table: def __init__(self, fields, raw_data): # fields is a dictionary with field names as keys, and their typ...
[ "First general rule: don't modify containers: create new ones.\nSo don't modify your incoming dictionary, create a new dictionary with a subset of the keys.\nself.fields = dict( key, value for key, value in fields.items()\n if accept_key(key, data) )\n\nSuch methods are typically slightly more e...
[ 13, 4, 1, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0007379991_coding_style_python.txt
Q: How to iterate step with right shift in Python? Is it possible to use right shift as the step argument in xrange? Basically I'm trying to do this (pseudo-code) for i in xrange(35926661, 0, _value_>>6): //logic A: No. xrange always works by adding the third parameter. You cannot tell it to do something like a...
How to iterate step with right shift in Python?
Is it possible to use right shift as the step argument in xrange? Basically I'm trying to do this (pseudo-code) for i in xrange(35926661, 0, _value_>>6): //logic
[ "No.\nxrange always works by adding the third parameter. You cannot tell it to do something like a right shift instead.\nA while loop will work, there may be better solutions but its hard to say without more information about what you are doing.\n", "You can define a custom xrange-like function using a generator:...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007614927_python.txt
Q: How to set up multiple django versions on single apache service? I'm using Windows XP and want to know how can I create multiple django versions on a single apache service through virtual host(of course). I'm trying to do that with one instance of python too. Should i create 1 instance of python for each django ve...
How to set up multiple django versions on single apache service?
I'm using Windows XP and want to know how can I create multiple django versions on a single apache service through virtual host(of course). I'm trying to do that with one instance of python too. Should i create 1 instance of python for each django version or django needs only its eggs to work, so I can have several egg...
[ "You can do something like this in your httpd.conf\nNameVirtualHost 0.0.0.0:80\n<VirtualHost 0.0.0.0:80>\n ServerName myserver.com\n ServerAdmin myemail@gmail.com\n DocumentRoot \"/path/to/html/root\"\n ErrorLog \"/path/to/apache-error.log\"\n CustomLog \"/path/to/apache-access.log\" common\n\n Op...
[ 2, 1 ]
[]
[]
[ "apache", "django", "python" ]
stackoverflow_0007614940_apache_django_python.txt
Q: How to only print lines with unique fields? For example... if I had a file like this: A 16 chr11 36595888 A 0 chr1 155517200 B 16 chr1 43227072 C 0 chr20 55648508 D 0 chr2 52375454 D 16 chr2 73574214 D 0 chr3 93549403 E 16 chr3 3315671 I need to print only the lin...
How to only print lines with unique fields?
For example... if I had a file like this: A 16 chr11 36595888 A 0 chr1 155517200 B 16 chr1 43227072 C 0 chr20 55648508 D 0 chr2 52375454 D 16 chr2 73574214 D 0 chr3 93549403 E 16 chr3 3315671 I need to print only the lines which have a unique first column: B 16 chr1...
[ "in bash, assuming first column has fixed with (3):\nsort input-file.txt | uniq -u -w 3\n\n'-u' option prints only the unique lines and '-w 3' compares no more than the first 3 characters.\n", "How about this:\n#!/usr/bin/env python\nfrom collections import defaultdict\ndata = defaultdict(list)\nwith open('file',...
[ 7, 3, 1, 1, 0, 0 ]
[]
[]
[ "bash", "python", "unique" ]
stackoverflow_0007602174_bash_python_unique.txt
Q: Python screen scrape whole website I want to make a little program which will use every single something-meaning word from any website It's meant to be in python and I've heard about BeautifulSoup but I don't quite know how to use it for this purpose... little tutorial? :p Or is it just that easy as a regex? like:...
Python screen scrape whole website
I want to make a little program which will use every single something-meaning word from any website It's meant to be in python and I've heard about BeautifulSoup but I don't quite know how to use it for this purpose... little tutorial? :p Or is it just that easy as a regex? like: re.compile('<.*>(.*)<.*>') so everyth...
[ "Scrapy makes web-crawling easy. It also has great documentation and scrapy startproject command will build a skeleton project for you.\n", "Mechanize is a python library that allows you to perform http requests and even provides some ability to parse the html and extract the data you are looking for. It's major...
[ 1, 1 ]
[]
[]
[ "beautifulsoup", "html", "python", "screen_scraping" ]
stackoverflow_0007615532_beautifulsoup_html_python_screen_scraping.txt
Q: Downloading a file into memory I am writing a python script and I just need the second line of a series of very small text files. I would like to extract this without saving the file to my harddrive as I currently do. I have found a few threads that reference the TempFile and StringIO modules but I was unable t...
Downloading a file into memory
I am writing a python script and I just need the second line of a series of very small text files. I would like to extract this without saving the file to my harddrive as I currently do. I have found a few threads that reference the TempFile and StringIO modules but I was unable to make much sense of them. Currently...
[ "You open and close the output file in every iteration. \nWhy not simply do\nwith open(\"Summary.txt\", \"w\") as linkfile:\n while (count4 <= num_files):\n file_p = [directory,str(count4),'.txt']\n file_path = ''.join(file_p) \n cand_summary = linecache.getline(file_path, 2).strip() ...
[ 0, 0 ]
[]
[]
[ "python", "stringio", "temporary_files" ]
stackoverflow_0007615511_python_stringio_temporary_files.txt
Q: Class based GDClient use I study the document about Google API auth. And I little bit confused. In document written: import gdata.gauth import gdata.docs.client CONSUMER_KEY = 'example.com' CONSUMER_SECRET = 'abc123doremi' SCOPES = ['https://docs.google.com/feeds/', 'https://www.google.com/calendar/feeds/'] # ...
Class based GDClient use
I study the document about Google API auth. And I little bit confused. In document written: import gdata.gauth import gdata.docs.client CONSUMER_KEY = 'example.com' CONSUMER_SECRET = 'abc123doremi' SCOPES = ['https://docs.google.com/feeds/', 'https://www.google.com/calendar/feeds/'] # example of a multi-scoped to...
[ "When your code is called from a web request, self.request is request that came in. self.request.host is the hostname that the user called (i.e. your server).\nSo this code subsitutes your server name into the oauth_callback_url for sending to Google in the OAuth Request as the call back URL. If you don't want to d...
[ 0 ]
[]
[]
[ "google_api", "oauth", "python" ]
stackoverflow_0007609207_google_api_oauth_python.txt
Q: django querysets + memcached: best practices Trying to understand what happens during a django low-level cache.set() Particularly, details about what part of the queryset gets stored in memcached. First, am I interpreting the django docs correctly? a queryset (python object) has/maintains its own cache access to ...
django querysets + memcached: best practices
Trying to understand what happens during a django low-level cache.set() Particularly, details about what part of the queryset gets stored in memcached. First, am I interpreting the django docs correctly? a queryset (python object) has/maintains its own cache access to the database is lazy; even if the queryset.count i...
[ "Querysets are lazy, which means they don't call the database until they're evaluated. One way they could get evaluated would be to serialize them, which is what cache.set does behind the scenes. So no, this isn't a waste of time: the entire contents of your Tournament model will be cached, if that's what you want....
[ 27 ]
[]
[]
[ "django", "django_cache", "python" ]
stackoverflow_0007615357_django_django_cache_python.txt
Q: Syntax when dereferencing database-backed tree I'm using MongoDB, so my clusters of data are in dictionaries. Some of these contain references to other Mongo objects. For example, say I have a Person document which has a separate Employer document. I would like to control element access so I can automatically dere...
Syntax when dereferencing database-backed tree
I'm using MongoDB, so my clusters of data are in dictionaries. Some of these contain references to other Mongo objects. For example, say I have a Person document which has a separate Employer document. I would like to control element access so I can automatically dereference documents. I also have some data with dates,...
[ "Your first 2 options would require making a \"Person\" class and an \"Employer\" class, and using __dict__ to read values and setattr for writing values. This approach will be slower, but will be more flexible (you can add new methods, validation, etc.)\nThe simplest way would be to use only dictionaries (option 3...
[ 0, 0 ]
[]
[]
[ "coding_style", "mongodb", "python" ]
stackoverflow_0007178613_coding_style_mongodb_python.txt
Q: Get index from a list where the key changes, groupby I have a list that looks like this: myList = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3] What I want to do is record the index where the items in the list changes value. So for my list above it would be 3, 6. I know that using groupby like this: [len(list(group)) for key, g...
Get index from a list where the key changes, groupby
I have a list that looks like this: myList = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3] What I want to do is record the index where the items in the list changes value. So for my list above it would be 3, 6. I know that using groupby like this: [len(list(group)) for key, group in groupby(myList)] will result in: [4, 3, 3] but w...
[ "[i for i in range(len(myList)-1) if myList[i] != myList[i+1]]\n\nIn Python 2, replace range with xrange.\n", "Just use enumerate to generate indexes along with the list.\nfrom operator import itemgetter\nfrom itertools import groupby\nmyList = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3]\n\n[next(group) for key, group in grou...
[ 3, 3, 1 ]
[]
[]
[ "group_by", "indexing", "list", "python" ]
stackoverflow_0007615758_group_by_indexing_list_python.txt
Q: Methods which return values vs methods which directly set attributes in Python Which of the following classes would demonstrate the best way to set an instance attribute? Should they be used interchangeably based on the situation? class Eggs(object): def __init__(self): self.load_spam() def load_...
Methods which return values vs methods which directly set attributes in Python
Which of the following classes would demonstrate the best way to set an instance attribute? Should they be used interchangeably based on the situation? class Eggs(object): def __init__(self): self.load_spam() def load_spam(self): # Lots of code here self.spam = 5 or class Eggs(object)...
[ "I would prefer the second method. \nHere's why: \nProcedures with side effects tend to introduce temporal coupling. Simply put, changing the order in which you execute these procedures might break your code. Returning values and passing them to other methods in need of them makes inter-method communication explici...
[ 11, 0, 0 ]
[]
[]
[ "coding_style", "oop", "python" ]
stackoverflow_0007152617_coding_style_oop_python.txt
Q: What are your best practices for working with test data in Django? I currently use a single fixtures file per application, but as projects grow, the tests are taking far too long and I believe that the (now large) fixtures being loaded for each test class are at fault. I've avoided having lots of smaller fixtures ...
What are your best practices for working with test data in Django?
I currently use a single fixtures file per application, but as projects grow, the tests are taking far too long and I believe that the (now large) fixtures being loaded for each test class are at fault. I've avoided having lots of smaller fixtures because of concerns about duplication and maintenance, but I know think ...
[ "Yes you have hit on a problem with a large set of fixtures. The constant deserialization/loading does add up as your test suite grows. I would suggest writing utility functions to create data as you need it rather than relying on fixtures. For instance you might have a function to create a new auth.User like:\ndef...
[ 2, 0 ]
[]
[]
[ "django", "python", "tdd", "testing" ]
stackoverflow_0007613616_django_python_tdd_testing.txt
Q: ReportLab Two-Column TOC? I have a PDF I am generating using ReportLab. I am using the standard TableOfContents flowable, but am trying to split it up into two columns, so it will all fit on the first page. the content will only ever be on one level, so I am not worried about odd-looking indentations. Right now ...
ReportLab Two-Column TOC?
I have a PDF I am generating using ReportLab. I am using the standard TableOfContents flowable, but am trying to split it up into two columns, so it will all fit on the first page. the content will only ever be on one level, so I am not worried about odd-looking indentations. Right now I have the PageTemplate using 2...
[ "Well, color me embarrassed.\nFor anyone else having this problem, check your DocTemplate for allowSplitting. The default is 1, but I had changed mine to 0 and that was the reason.\n*facepalm*\n" ]
[ 2 ]
[]
[]
[ "python", "reportlab" ]
stackoverflow_0007615795_python_reportlab.txt
Q: Trouble deploying Django app to Heroku: name 'install' is not defined EDIT: I narrowed down the problem to the presence of the "distribute==0.6.10" line in the requirements.txt file. Removing that line fixes the problem, and haven't run into any errors from that line not being there... yet. I'm following the tutor...
Trouble deploying Django app to Heroku: name 'install' is not defined
EDIT: I narrowed down the problem to the presence of the "distribute==0.6.10" line in the requirements.txt file. Removing that line fixes the problem, and haven't run into any errors from that line not being there... yet. I'm following the tutorial here: http://devcenter.heroku.com/articles/django Everything was going ...
[ "Using a newer version of distribute fixed the problem.\ndistribute==0.6.21\n\n" ]
[ 3 ]
[]
[]
[ "django", "heroku", "python" ]
stackoverflow_0007592239_django_heroku_python.txt
Q: Python Error Codes are upshifted Consider a python script error.py import sys sys.exit(3) Invoking python error.py; echo $? yields the expected "3". However, consider runner.py import os result = os.system("python error.py") print result yields 768. It seems that somehow the result of python code has been lefts...
Python Error Codes are upshifted
Consider a python script error.py import sys sys.exit(3) Invoking python error.py; echo $? yields the expected "3". However, consider runner.py import os result = os.system("python error.py") print result yields 768. It seems that somehow the result of python code has been leftshifted by 8, but how these two situati...
[ "From the docs:\n\nOn Unix, the return value is the exit status of the process encoded in\n the format specified for wait(). Note that POSIX does not specify the\n meaning of the return value of the C system() function, so the return\n value of the Python function is system-dependent.\nos.wait()\nWait for comple...
[ 7, 5 ]
[]
[]
[ "python" ]
stackoverflow_0007616187_python.txt
Q: Running a process remotely using Python Is it possible to run a System process remotely , i.e. in the background using python? For e.g. I ave Scilab installed on my system, now I do something like this xx= os.system('scilab-adv-cli') in the python console. But this fires up an actual scilab comm...
Running a process remotely using Python
Is it possible to run a System process remotely , i.e. in the background using python? For e.g. I ave Scilab installed on my system, now I do something like this xx= os.system('scilab-adv-cli') in the python console. But this fires up an actual scilab command line interface. Though I need something l...
[ "If this is limited to Scilib, check out http://forge.scilab.org/index.php/p/sciscipy/\nwhich should let you do everything scilib can do from within python.\nAlso, while this doesn't solve your problem, you should considering using subprocess instead of os.system\nhttp://docs.python.org/library/subprocess.html#modu...
[ 1 ]
[]
[]
[ "python", "scilab" ]
stackoverflow_0007616215_python_scilab.txt
Q: when modification of the assigned variable will affect the value of original variable? >>> x = 10 >>> y = x >>> y = 100 >>> y # Changes on y will not be transferred to x 100 >>> x 10 >>> x2 = 'hello' >>> y2 = x2 >>> y2 = 'world' # Changes on y2 will not be transferred to x2 >>> y2 'world' >>> x2 'hello' >>>...
when modification of the assigned variable will affect the value of original variable?
>>> x = 10 >>> y = x >>> y = 100 >>> y # Changes on y will not be transferred to x 100 >>> x 10 >>> x2 = 'hello' >>> y2 = x2 >>> y2 = 'world' # Changes on y2 will not be transferred to x2 >>> y2 'world' >>> x2 'hello' >>> a = [1, 2] >>> b = a >>> b.append(3) # Changes on b will be transferred to a >>> b [1, 2, 3...
[ "\nIn some cases you are then rebinding one of the names, but not the other, so they now are bound to different objects.\ny = 100 # Rebind y. Doesn't change x.\ny2 = 'world' # Rebind y2. Doesn't change x2.\n\nIn other cases you are mutating the object. Then both names see the changes to the object.\nb.append(3...
[ 3, 2, 1, 1 ]
[ "I don't know python much but I would assume if the value is a primitve type the original variable it not affected. Otherwise the value is only a reference which will change the original variable.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0007615730_python.txt
Q: Python capture stdout from subprocess line by line I've read many of the questions related to this and learned a lot but I still haven't been able to solve my problem. I'm building a wxPython app that runs a c++ executable and displays the stdout from that executable in real time. I've run into several strange res...
Python capture stdout from subprocess line by line
I've read many of the questions related to this and learned a lot but I still haven't been able to solve my problem. I'm building a wxPython app that runs a c++ executable and displays the stdout from that executable in real time. I've run into several strange results trying to make this work. Here's my current setup/p...
[ "I only tested this on Windows, but it works in 2.6.6, 2.7.2, and 3.2.1:\nfrom __future__ import print_function\nfrom subprocess import PIPE, Popen\nfrom threading import Thread\nimport sys\n\ntry:\n from Queue import Queue, Empty\nexcept ImportError:\n from queue import Queue, Empty # python 3.x\n\nON_POSI...
[ 6 ]
[]
[]
[ "c", "c++", "multithreading", "python", "wxpython" ]
stackoverflow_0007608883_c_c++_multithreading_python_wxpython.txt
Q: Python - Better to have multiple methods or lots of optional parameters? I have a class which makes requests to a remote API. I'd like to be able to reduce the number of calls I'm making. Some of the methods in my class make the same API calls (but for different reasons), so I'ld like the ability for them to 'shar...
Python - Better to have multiple methods or lots of optional parameters?
I have a class which makes requests to a remote API. I'd like to be able to reduce the number of calls I'm making. Some of the methods in my class make the same API calls (but for different reasons), so I'ld like the ability for them to 'share' a cached API response. I'm not entirely sure if it's more Pythonic to use o...
[ "Normally when writing method one could argue that a method / object should do one thing and it should do it well. If your method get more and more parameters which require more and more ifs in your code that probably means that your code is doing more then one thing. Especially if those parameters trigger totally ...
[ 5, 2, 1, 1, 0 ]
[]
[]
[ "api", "caching", "coding_style", "optional_parameters", "python" ]
stackoverflow_0007150987_api_caching_coding_style_optional_parameters_python.txt
Q: Python Windows: correct virtualenv paths I'm new to virtualenv and not sure how to set up paths. My paths have been set to something like this: PYTHONPATH=C:\Python27\ PYTHONSTARTUP=C:\Python27\Scripts\startup.py PATH=%PYTHONPATH%;...;%PYTHONPATH%\Scripts Should I remove those paths for virtualenv's activate scri...
Python Windows: correct virtualenv paths
I'm new to virtualenv and not sure how to set up paths. My paths have been set to something like this: PYTHONPATH=C:\Python27\ PYTHONSTARTUP=C:\Python27\Scripts\startup.py PATH=%PYTHONPATH%;...;%PYTHONPATH%\Scripts Should I remove those paths for virtualenv's activate script to work correctly? If I can keep my paths t...
[ "First, you have your paths wrong. PYTHONPATH tells Python in what folders to look for Python modules and normally you don't put Python's installation folder in it. For keeping installation folder of Python there's different environment variable called PYTHONHOME. So instead of PYTHONPATH=C:\\Python27\\ you should ...
[ 3 ]
[ "Think you are fine just get on with virtual-env, (follow docs) but remember you must use cmd shell (NO POINT AND CLICKING!!) Took me a while before I realized that...\nOnce you have activated And installed what you want to in the virtual env,, you invoke scripts by \"python scriptname\"\n" ]
[ -4 ]
[ "python", "virtualenv", "windows" ]
stackoverflow_0005773682_python_virtualenv_windows.txt
Q: Conventions on creating constants in Python I am writing an application which needs to find out the schema of a database, across engines. To that end, I am writing a small database adapter using Python. I decided to first write a base class that outlines the functionality I need, and then implement it using classe...
Conventions on creating constants in Python
I am writing an application which needs to find out the schema of a database, across engines. To that end, I am writing a small database adapter using Python. I decided to first write a base class that outlines the functionality I need, and then implement it using classes that inherit from this base. Along the way, I n...
[ "\nwhat is the standard way of sharing such constants?\n\nThroughout the standard library, the most common way is to define constants as module-level variables using UPPER_CASE_WITH_UNDERSCORES names.\n\nwhat is the right way to create constants that can be combined? I am referring to MAP_FIXED | MAP_FILE | MAP_SHA...
[ 22, 18, 4, 3, 3 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0007078731_coding_style_python.txt
Q: ElementTree's iter() equivalent in Python2.6 I have this code with ElementTree that works well with Python 2.7. I needed to get all the nodes with the name "A" under "X/Y" node. from xml.etree.ElementTree import ElementTree verboseNode = topNode.find("X/Y") nodes = list(verboseNode.iter("A")) However, when I tr...
ElementTree's iter() equivalent in Python2.6
I have this code with ElementTree that works well with Python 2.7. I needed to get all the nodes with the name "A" under "X/Y" node. from xml.etree.ElementTree import ElementTree verboseNode = topNode.find("X/Y") nodes = list(verboseNode.iter("A")) However, when I tried to run it with Python 2.6, I got this error. ...
[ "Not sure if this is what you are looking for, as iter() appears to be around in 2.6, but there's getiterator()\nhttp://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getiterator\n", "Note that iter is available in Python 2.6 (and even 2.5 - otherwise, there'd be a notice in the ...
[ 20, 7 ]
[]
[]
[ "elementtree", "python", "python_2.6", "xml" ]
stackoverflow_0007616800_elementtree_python_python_2.6_xml.txt
Q: Python: print "word" in [] == False Going a bit mental here trying to work out what this does in python: print "word" in [] == False Why does this print False? A: Perhaps a more clear example of this unusual behaviour is the following: >>> print 'word' in ['word'] True >>> print 'word' in ['word'] == True Fals...
Python: print "word" in [] == False
Going a bit mental here trying to work out what this does in python: print "word" in [] == False Why does this print False?
[ "Perhaps a more clear example of this unusual behaviour is the following:\n>>> print 'word' in ['word']\nTrue\n>>> print 'word' in ['word'] == True\nFalse\n\n\nYour example is equivalent to:\nprint (\"word\" in []) and ([] == False)\n\nThis is because two boolean expressions can be combined, with the intention of a...
[ 11, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007616691_python.txt
Q: Is there any nipype interface for avscale (FSL script)? I am trying to use nipype to analyze transformation matrixes that were created by FSL. FSL has a script called "avscale" that analyzes those transformation matrixes (*.mat files). I was wondering whether nipype has any interface that wrap that script and enab...
Is there any nipype interface for avscale (FSL script)?
I am trying to use nipype to analyze transformation matrixes that were created by FSL. FSL has a script called "avscale" that analyzes those transformation matrixes (*.mat files). I was wondering whether nipype has any interface that wrap that script and enable to work with its output. Thanks
[ "Based on the docs and the current source the answer is no. Also, avscale has also not been mentioned on the nipy-devel mailing list since at least last February. It's possible that Nipype already wraps something else that does this (perhaps with a matlab wrapper?) You could try opening an issue or asking the the...
[ 1 ]
[]
[]
[ "nipy", "nipype", "python" ]
stackoverflow_0007616497_nipy_nipype_python.txt
Q: Python regex string matching? I'm having a hell of a time trying to transfer my experience with javascript regex to Python. I'm just trying to get this to work: print(re.match('e','test')) ...but it prints None. If I do: print(re.match('e','est')) It matches... does it by default match the beginning of the stri...
Python regex string matching?
I'm having a hell of a time trying to transfer my experience with javascript regex to Python. I'm just trying to get this to work: print(re.match('e','test')) ...but it prints None. If I do: print(re.match('e','est')) It matches... does it by default match the beginning of the string? When it does match, how do I us...
[ "re.match implicitly adds ^ to the start of your regex. In other words, it only matches at the start of the string.\nre.search will retry at all positions.\nGenerally speaking, I recommend using re.search and adding ^ explicitly when you want it.\nhttp://docs.python.org/library/re.html\n", "the docs is clear i th...
[ 58, 9 ]
[]
[]
[ "pattern_matching", "python", "regex" ]
stackoverflow_0007616998_pattern_matching_python_regex.txt
Q: How to save a mix of strings and numbers into text files in specified format using numpy.savetxt? with one array of strings and the other array of numbers, like str_arr = np.array(['object1_short', 'object2_intermidiate', 'object3_long']) and flt_arr = np.array([10.01234235, 11.01234235, 12.023432]) How can I sp...
How to save a mix of strings and numbers into text files in specified format using numpy.savetxt?
with one array of strings and the other array of numbers, like str_arr = np.array(['object1_short', 'object2_intermidiate', 'object3_long']) and flt_arr = np.array([10.01234235, 11.01234235, 12.023432]) How can I specified fmt in np.savetxt so that the text file will be object1 10.01 object2 11.01 object3 1...
[ "You can't make an ndarray of nonhomogeneous array types, so stacking str_arr and flt_arr won't work. You could start by converting flt_arr into an array of strs doing something like this:\n>>> np.char.mod(\"%4.2f\", flt_arr)\narray(['10.01', '11.01', '12.02'], \n dtype='|S5')\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007616838_numpy_python.txt
Q: What does TypeError: not all arguments converted during string formatting mean in python here is my first program it basically says stuff out loud and in different voices : import os print "Hello, Welcome to the speaking program" speak = raw_input("What would you like to say?\n") type = raw_input("Would you like\n...
What does TypeError: not all arguments converted during string formatting mean in python
here is my first program it basically says stuff out loud and in different voices : import os print "Hello, Welcome to the speaking program" speak = raw_input("What would you like to say?\n") type = raw_input("Would you like\n1. Normal Voice\n2. High Pitched\n3. Low Pitched?\n4. Whisper\n5. Indian Voice\n Please choose...
[ "You put a dollar sign instead of a percent sign:\nos.system(\"say -v sangeeta $s\" % speak)\n\nThis should be:\nos.system(\"say -v sangeeta %s\" % speak)\n\n" ]
[ 8 ]
[]
[]
[ "macos", "python", "terminal" ]
stackoverflow_0007617042_macos_python_terminal.txt
Q: How to scrape the 'More' portion of the Quora profile page? To determine the list of all topics on Quora, I decided to start from scraping the profile page with many topics followed, e.g. http://www.quora.com/Charlie-Cheever/topics. I scraped the topics from this page, but now I need to scrape the topics from the ...
How to scrape the 'More' portion of the Quora profile page?
To determine the list of all topics on Quora, I decided to start from scraping the profile page with many topics followed, e.g. http://www.quora.com/Charlie-Cheever/topics. I scraped the topics from this page, but now I need to scrape the topics from the Ajax page which is loaded when you click on 'More' button at the ...
[ "You can see it in your browser's dom inspector under Event Listeners. It's an anonymous function and looks like this:\nfunction (){return typeof d!==\"undefined\"&&!d.event.triggered?d.event.handle.apply(l.elem,arguments):b}\n\nThis looks like a difficult website to scrape, you might consider using selenium.\n" ]
[ 2 ]
[]
[]
[ "ajax", "python", "screen_scraping", "web_scraping" ]
stackoverflow_0007614478_ajax_python_screen_scraping_web_scraping.txt
Q: Open Source Software For Transcribing Speech in Audio Files Can anyone recommend reliable open source software for transcribing English speech in wav files? The two main programs I've researched are Sphinx and Julius, but I've never been able to get either to work, and the documentation with each on transcribing f...
Open Source Software For Transcribing Speech in Audio Files
Can anyone recommend reliable open source software for transcribing English speech in wav files? The two main programs I've researched are Sphinx and Julius, but I've never been able to get either to work, and the documentation with each on transcribing files is sketchy at best. I'm developing on 64-bit Ubuntu 10.04, w...
[ "\nWhy can't it read a wav?\n\nIt tells you that the file has wrong sampling rate (8000) instead of requested (16000). Sampling rate is very important for speech recognition software.\n\nWhy can't it read /dev/dsp?\n\nIn recent versions of Ubuntu pulseaudio framework is used instead of OSS. The version you are tryi...
[ 15 ]
[]
[]
[ "cmusphinx", "java", "python", "speech_recognition", "speech_to_text" ]
stackoverflow_0007613089_cmusphinx_java_python_speech_recognition_speech_to_text.txt
Q: Tell sage where to find libjpeg I have installed Sage on Mac OS X. It looks like it has PIL. The following code gives me an IOError.. import Image a = Image.open("pic.jpg") a.thumbnail((int(100), int(100))) This is the error I get. IOError Traceback (most recent call last) <ipyt...
Tell sage where to find libjpeg
I have installed Sage on Mac OS X. It looks like it has PIL. The following code gives me an IOError.. import Image a = Image.open("pic.jpg") a.thumbnail((int(100), int(100))) This is the error I get. IOError Traceback (most recent call last) <ipython console> in <module>() /sage/loc...
[ "The answer is to just reinstall PIL.\nsage.misc.package.install_package(\"pil\", force=True)\n\nIt was that simple & it just took a minute. Reinstalling it on my machine probably allowed it to find the location of the libraries on my machine.\n" ]
[ 2 ]
[]
[]
[ "jpeg", "python", "python_imaging_library", "sage" ]
stackoverflow_0007605281_jpeg_python_python_imaging_library_sage.txt
Q: Python object hierarchy, and REST resources? I am currently running into an "architectural" problem in my Python app (using Twisted) that uses a REST api, and I am looking for feedback. Warning ! long post ahead! Lets assume the following Object hiearchy: class Device(object): def __init__(): self._driver=Dr...
Python object hierarchy, and REST resources?
I am currently running into an "architectural" problem in my Python app (using Twisted) that uses a REST api, and I am looking for feedback. Warning ! long post ahead! Lets assume the following Object hiearchy: class Device(object): def __init__(): self._driver=Driver() self._status=Status() self._tasks=T...
[ "Rule 1. REST is about objects. Not methods.\n\nThe REST \"resources\" have become too fragmented \n\nFalse. Always false. REST resources are independent. They can't be \"too\" fragmented.\n\ninstead of having just a Device resource I now have all these resources:\nDevice DeviceStatus Driver DriverStatus \nWhi...
[ 4, 0 ]
[]
[]
[ "composition", "hierarchy", "python", "resources", "rest" ]
stackoverflow_0007614869_composition_hierarchy_python_resources_rest.txt
Q: Order of python notifications with notify() Let's say I have the following code: master_lock = Lock() x = Condition(master_lock) y = Condition(master_lock) z = Condition(master_lock) def foo_z(): with master_lock: x.notify() y.notify() z.wait() def foo_y(): with master_lock: x.notify() ...
Order of python notifications with notify()
Let's say I have the following code: master_lock = Lock() x = Condition(master_lock) y = Condition(master_lock) z = Condition(master_lock) def foo_z(): with master_lock: x.notify() y.notify() z.wait() def foo_y(): with master_lock: x.notify() z.notify() y.wait() When you notify one mon...
[ "No there is no assurance to the order since the code is executing in multiple threads.\n" ]
[ 0 ]
[]
[]
[ "locking", "multithreading", "python", "synchronization" ]
stackoverflow_0007616705_locking_multithreading_python_synchronization.txt
Q: python program that scans a page for a specific combination of pixels? I'm trying to write a python program that will take a screen shot and then scan the image for a specific combination of pixels, or pattern. For example: it takes a screen shot of a web page and scans the whole image for a 10X10 pixel pattern. I...
python program that scans a page for a specific combination of pixels?
I'm trying to write a python program that will take a screen shot and then scan the image for a specific combination of pixels, or pattern. For example: it takes a screen shot of a web page and scans the whole image for a 10X10 pixel pattern. It would also be nice if it could record the x-y position of the image on the...
[ "Take a look at some basic pattern recognition and machine vision literature. In order to address your question considerably more detail is needed.\n\nIs the pattern a binary image, a grayscale image, or a color image?\nHow often do you need to do this?\nHave you looked at the Python Imaging Library (PIL)?\nHow big...
[ 1 ]
[]
[]
[ "image", "pixel", "python", "scanning", "screen" ]
stackoverflow_0007617610_image_pixel_python_scanning_screen.txt
Q: Python read page from URL? Better documentation? I'm having quite a bit of trouble with Python's documentation. Is there anything like the Mozilla Developer Network for it? I'm doing a Python puzzle website and I need to be able to read the content of the page. I saw the following posted on a site: import urllib2 ...
Python read page from URL? Better documentation?
I'm having quite a bit of trouble with Python's documentation. Is there anything like the Mozilla Developer Network for it? I'm doing a Python puzzle website and I need to be able to read the content of the page. I saw the following posted on a site: import urllib2 urlStr = 'http://www.python.org/' try: fileHandle =...
[ "Using urllib.request.open(), as recommended in Dive into Python 3...\nPython 3.2.1 (default, Jul 24 2011, 22:21:06) \n[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import urllib.request\n>>> urlStr...
[ 4, 3 ]
[]
[]
[ "python", "url", "urllib" ]
stackoverflow_0007617661_python_url_urllib.txt
Q: How to write a file of ASCII bytes to a binary file as actual bytes? Trying to do an MD5 collision homework problem and I'm not sure how to write raw bytes in Python. I gave it a shot but just ended up with a .bin file with ASCII in it. Here's my code: fileWriteObject1 = open("md5One.bin", 'wb') fileWriteObject2 =...
How to write a file of ASCII bytes to a binary file as actual bytes?
Trying to do an MD5 collision homework problem and I'm not sure how to write raw bytes in Python. I gave it a shot but just ended up with a .bin file with ASCII in it. Here's my code: fileWriteObject1 = open("md5One.bin", 'wb') fileWriteObject2 = open("md5Two.bin", 'wb') fileReadObject1 = open('bytes1.txt', 'r') fileRe...
[ "If you want to write them as raw bytes, you can use the pack() method of the struct type.\nYou could write the MD5 out as 2 long long ints, but you'd have to write it in 2 8 byte sections\nhttp://docs.python.org/library/struct.html\nEdit:\nAn example:\nimport struct\n\nbytes = \"6F\"\nbyteAsInt = int(bytes, 16)\np...
[ 4, 0 ]
[]
[]
[ "ascii", "hex", "python" ]
stackoverflow_0007617198_ascii_hex_python.txt
Q: How to use Image.ANTIALIAS with resize() in GAE? I am using the script below to resize images. But I noticed that the resized image looses sharpness. According to this page Image.ANTIALIAS is the best "downsizing filter". But when I add the filter to the code images.resize(homepage.original_image, 200, 200, Image...
How to use Image.ANTIALIAS with resize() in GAE?
I am using the script below to resize images. But I noticed that the resized image looses sharpness. According to this page Image.ANTIALIAS is the best "downsizing filter". But when I add the filter to the code images.resize(homepage.original_image, 200, 200, Image.ANTIALIAS) I get AttributeError: type object 'Image'...
[ "The documentation you linked is for PIL but you're using the Google App Engine images API, the documentation for which is here: http://code.google.com/appengine/docs/python/images/functions.html\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "image", "python" ]
stackoverflow_0007617847_google_app_engine_image_python.txt
Q: TypeError: 'str' does not support the buffer interface - python I'm currently doing an online Python puzzle series, and I've gotten to a problem where you need to unload a pickled file. I read the documentation on it, but I kept getting TypeError: 'str' does not support the buffer interface ...so I search on Goog...
TypeError: 'str' does not support the buffer interface - python
I'm currently doing an online Python puzzle series, and I've gotten to a problem where you need to unload a pickled file. I read the documentation on it, but I kept getting TypeError: 'str' does not support the buffer interface ...so I search on Google and arrive at a question on SO with a similar problem. The answer ...
[ "Open the pickle file in binary mode: favorite_color = pickle.load(open(\"save.p\", \"rb\")).\n" ]
[ 13 ]
[]
[]
[ "pickle", "python", "python_3.x" ]
stackoverflow_0007617937_pickle_python_python_3.x.txt
Q: efficient way of printing lists to a table in a .txt file using python I want to create a text file which contains a table, created from lists. But, I don't want to have to do something like this: import string print >> textfile, string.rjust(listname[0],3), string.rjust(listname[1],3), The following code demonst...
efficient way of printing lists to a table in a .txt file using python
I want to create a text file which contains a table, created from lists. But, I don't want to have to do something like this: import string print >> textfile, string.rjust(listname[0],3), string.rjust(listname[1],3), The following code demonstrates the idea of what I would like to do, but doesn't work: import string l...
[ "If I'm understanding the problem correctly, you could just do this...\n>>> def print_table():\n... headers = ['One', 'Two', 'Three']\n... table = [['test1', 2, 3.0],\n... ['test4', 5, 6.0],\n... ['test7', 8, 9.0],\n... ]\n... print ''.join(column.rjust(10) for column...
[ 2, 1, 1 ]
[]
[]
[ "list", "printing", "python" ]
stackoverflow_0007617925_list_printing_python.txt
Q: 403 Forbidden Error for Python-Suds contacting Sharepoint I'm using Python's SUDs lib to access Sharepoint web services. I followed the standard doc from Suds's website. For the past 2 days, no matter which service I access, the remote service always returns 403 Forbidden. I'm using Suds 0.4 so it has built-in su...
403 Forbidden Error for Python-Suds contacting Sharepoint
I'm using Python's SUDs lib to access Sharepoint web services. I followed the standard doc from Suds's website. For the past 2 days, no matter which service I access, the remote service always returns 403 Forbidden. I'm using Suds 0.4 so it has built-in support for accessing Python NTLM. Let me know if anyone has a cl...
[ "Are you specifying the username as DOMAIN\\USER_ID as indicated in examples for the python-ntlm library? (Also see this answer).\n" ]
[ 1 ]
[]
[]
[ "python", "sharepoint", "suds" ]
stackoverflow_0007617900_python_sharepoint_suds.txt
Q: Interacting with native applications using python I'm a Python programmer and I was wondering if there's any module or framework that would allow me to interact with native Windows/Linux applications using python. Let's say on Windows I have MS Outlook, so would it be possible to let's say automate MS Outlook to c...
Interacting with native applications using python
I'm a Python programmer and I was wondering if there's any module or framework that would allow me to interact with native Windows/Linux applications using python. Let's say on Windows I have MS Outlook, so would it be possible to let's say automate MS Outlook to compose or check new emails? I understand that Linux and...
[ "For something like Outlook, the best bet is probably using Outlook's COM (Component Object Model) with Python COM libraries.\n", "Most applications have some kind of API.\nAnd most of those API's are accessible with C.\nTherefore, Python offers ctypes. \nThat's the lowest common denominator. Other API's are av...
[ 4, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007618023_python.txt
Q: Why can't I install psycopg2? (Python 2.6.4, PostgreSQL 8.4, OS X 10.6.3) ORIGINAL MESSAGE (now outdated): After running python setup.py install I get the following: Warning: Unable to find 'pg_config' filebuilding 'psycopg2._psycopg' extension gcc-4.0 -arch ppc -arch i386 -fno-strict-aliasing -fno-common -dynamic...
Why can't I install psycopg2? (Python 2.6.4, PostgreSQL 8.4, OS X 10.6.3)
ORIGINAL MESSAGE (now outdated): After running python setup.py install I get the following: Warning: Unable to find 'pg_config' filebuilding 'psycopg2._psycopg' extension gcc-4.0 -arch ppc -arch i386 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 - DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.2.1 (dt...
[ "(See edits below for your updated question)\nYou don't have the \"gcc4.0\" compiler executable on your machine, or the right version, or installed in a location that python can't find/use. XCode/Developer Tools (which include GCC) should be on your original OSX installation DVDs. \nSince you're humble enough to ca...
[ 8, 4, 3, 2, 2 ]
[]
[]
[ "macos", "postgresql", "psycopg2", "python" ]
stackoverflow_0003029274_macos_postgresql_psycopg2_python.txt
Q: How to get a win32 handle of an open file in python? I'm sure this is documented somewhere but i can't find it... My code is getting a python object from another library (that i can't modify), and i need to call some win32 api functions on it. Python returns something that isn't the os-level handle from file.filen...
How to get a win32 handle of an open file in python?
I'm sure this is documented somewhere but i can't find it... My code is getting a python object from another library (that i can't modify), and i need to call some win32 api functions on it. Python returns something that isn't the os-level handle from file.fileno(), my guess is that it gives MSVCRT's fileno. >>> ctype...
[ "I found the answer:\n>>> msvcrt.get_osfhandle(a.fileno())\n1956 # valid HANDLE\n\nThis is actually documented on http://docs.python.org/library/msvcrt.html , no idea how i missed it.\n", "win32file._get_osfhandle from the PyWin32 library will return what you want.\nwin32file._get_osfhandle(a.fileno()) returns th...
[ 12, 4 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0006135805_python_winapi.txt
Q: PyQt4 signals and slots I am writing my first Python app with PyQt4. I have a MainWindow and a Dialog class, which is a part of MainWindow class: self.loginDialog = LoginDialog(); I use slots and signals. Here's a connection made in MainWindow: QtCore.QObject.connect(self.loginDialog, QtCore.SIGNAL("aa(str)"), se...
PyQt4 signals and slots
I am writing my first Python app with PyQt4. I have a MainWindow and a Dialog class, which is a part of MainWindow class: self.loginDialog = LoginDialog(); I use slots and signals. Here's a connection made in MainWindow: QtCore.QObject.connect(self.loginDialog, QtCore.SIGNAL("aa(str)"), self.login) And I try to emit ...
[ "There are some concepts to be clarified\n[QT signal & slot] VS [Python signal & slot]\nAll the predefined signals & slots provided by pyqt are implemented by QT's c++ code. Whenever you want to have a customized signal & slot in Python, it is a python signal & slot. Hence there are four cases to emits a signal to ...
[ 27, 12, 3, 3, 1, 0, 0 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0002048098_pyqt_pyqt4_python_qt_qt4.txt
Q: Python: sequential calls to subprocess (in this case, espeak) I was wondering if there was a way to access espeak as you might in the command line: laptop:~$espeak say this line first say this line second ... Right now, the only ways I can do it in python is process = subprocess.Popen(['espeak'], stdin=subprocess...
Python: sequential calls to subprocess (in this case, espeak)
I was wondering if there was a way to access espeak as you might in the command line: laptop:~$espeak say this line first say this line second ... Right now, the only ways I can do it in python is process = subprocess.Popen(['espeak'], stdin=subprocess.PIPE ), followed either by process.communicate(expression) or pr...
[ "You could try calling process.stdin.write(expression) where expression has a newline at the end, and don't call process.stdin.close() until you're done with espeak.\nIf that doesn't work then add a process.stdin.flush() call after the write.\n" ]
[ 3 ]
[]
[]
[ "block", "communicate", "espeak", "python", "subprocess" ]
stackoverflow_0007618533_block_communicate_espeak_python_subprocess.txt
Q: Remove leading 0's for str(date) If I have a datetime object, how would I get the date as a string in the following format: 1/27/1982 # it cannot be 01/27/1982 as there can't be leading 0's The current way I'm doing it is doing a .replace for all the digits (01, 02, 03, etc...) but this seems very inefficient an...
Remove leading 0's for str(date)
If I have a datetime object, how would I get the date as a string in the following format: 1/27/1982 # it cannot be 01/27/1982 as there can't be leading 0's The current way I'm doing it is doing a .replace for all the digits (01, 02, 03, etc...) but this seems very inefficient and cumbersome. What would be a better w...
[ "You could format it yourself instead of using strftime:\n'{0}/{1}/{2}'.format(d.month, d.day, d.year) // Python 2.6+\n\n'%d/%d/%d' % (d.month, d.day, d.year)\n\n", "The datetime object has a method strftime(). This would give you more flexibility to use the in-built format strings. \nhttp://docs.python.org/libra...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007618863_python.txt
Q: Building an Inference Engine in Python I am seeking direction and attempting to label this problem: I am attempting to build a simple inference engine (is there a better name?) in Python which will take a string and - 1 - create a list of tokens by simply creating a list of white space separated values 2 - categor...
Building an Inference Engine in Python
I am seeking direction and attempting to label this problem: I am attempting to build a simple inference engine (is there a better name?) in Python which will take a string and - 1 - create a list of tokens by simply creating a list of white space separated values 2 - categorise these tokens, using regular expressions ...
[ "I'm very surprised that step #3 is the one giving you trouble...\nAssuming you can label/categorize properly each token (and that prior to categorization you can find the proper tokens, as there may be many ambiguous cases...), the \"Step #3\" problem seems one that could easily be tackled with a context free gram...
[ 6, 2 ]
[]
[]
[ "expert_system", "parsing", "python", "rule_engine" ]
stackoverflow_0002211967_expert_system_parsing_python_rule_engine.txt
Q: Python download all files from internet address? I want to download all files from an internet page, actually all the image files. I found the 'urllib' module to be what I need. There seems to be a method to download a file, if you know the filename, but I don't. urllib.urlretrieve('http://www.example.com/page', '...
Python download all files from internet address?
I want to download all files from an internet page, actually all the image files. I found the 'urllib' module to be what I need. There seems to be a method to download a file, if you know the filename, but I don't. urllib.urlretrieve('http://www.example.com/page', 'myfile.jpg') Is there a method to download all the fi...
[ "Here's a little example to get you started with using BeautifulSoup for this kind of exercise - you give this script a URL, and it will print out the URLs of images that are referenced from that page in the src attribute of img tags that end with jpg or png:\nimport sys, urllib, re, urlparse\nfrom BeautifulSoup im...
[ 7 ]
[]
[]
[ "http", "python", "url", "urllib" ]
stackoverflow_0007618993_http_python_url_urllib.txt
Q: python, create a filtered list from a text document Every time I try to run this program, Python IDLE responds by telling me that it is not responding and has to close. Any suggestions on how to improve this code to make it work the way I want? #open text document #filter out words in the document by appending to ...
python, create a filtered list from a text document
Every time I try to run this program, Python IDLE responds by telling me that it is not responding and has to close. Any suggestions on how to improve this code to make it work the way I want? #open text document #filter out words in the document by appending to an empty list #get rid of words that show up more than on...
[ "Some general help:\nInstead of\nfin = open('example.txt')\n\nYou should use\nwith open('example.txt', 'r') as fin:\n\nthen indent the rest of the code, but your version will work.\nL = []\nfor word in fin:\n\nIt doesn't iterate by word, but by line. If there is one word per line, each will still have a newline at ...
[ 4, 2, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007614039_python.txt