content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Are there any alternatives to py2exe? Are there any alternatives to py2exe? A: pyInstaller is cross-platform and very powerful, with many third-party packages (matplotlib, numpy, PyQT4, ...) specially supported "out of the box", support for eggs, code-signing on Windows (and a couple other Windows-only goodies, ...
Are there any alternatives to py2exe?
Are there any alternatives to py2exe?
[ "pyInstaller is cross-platform and very powerful, with many third-party packages (matplotlib, numpy, PyQT4, ...) specially supported \"out of the box\", support for eggs, code-signing on Windows (and a couple other Windows-only goodies, optional binary packing... the works!-) The one big issue: the last \"released...
[ 59, 25, 20, 6 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0001689086_py2exe_python.txt
Q: AND in Python's slicing with modulus How can you fix the code? I am trying to have i % 3 == 1 and i != 16 unsuccessfully by data = "8|9|8|9|8|9|8|9|9|8|9|8|9|8|9|8" arra = map(int,data.split("|")) arra = sum(arra[1::3 and != 16]) for i in range(0, len(arra), 16)] | ...
AND in Python's slicing with modulus
How can you fix the code? I am trying to have i % 3 == 1 and i != 16 unsuccessfully by data = "8|9|8|9|8|9|8|9|9|8|9|8|9|8|9|8" arra = map(int,data.split("|")) arra = sum(arra[1::3 and != 16]) for i in range(0, len(arra), 16)] | |---// Problem here
[ "Try this:\narra = sum(a for i,a in enumerate(arra) if i %3==1 and i != 16)\n\nFor this kind of complex work, slice notation wont really do. But why do you assign back to arra? You wipe out your original list of values.\n", "Slices don't work like that.\nPaul McGuire has the correct code:\narra = sum(x for i, x...
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001690203_python.txt
Q: Sending a retrieved SMS using Python I am writing a Python script to read a SMS from the SIM memory, buffer it and send the same SMS to another number. I am executing this script on Telit GM862-GPS. The script I have written is : import MDM MDM.send('AT+CMGF=1\r', 10) # Changing to Text mode M...
Sending a retrieved SMS using Python
I am writing a Python script to read a SMS from the SIM memory, buffer it and send the same SMS to another number. I am executing this script on Telit GM862-GPS. The script I have written is : import MDM MDM.send('AT+CMGF=1\r', 10) # Changing to Text mode MDM.send('AT+CMGR=1\r',0) ...
[ "It looks like your program is waiting for a response that never arrives. That sort of thing is typical when a device doesn't think you have sent a complete command yet.\nI don't know the protocol you're using to communicate with that device, but it looks like a Hayes AT command set. Is it possible the device is ...
[ 1 ]
[]
[]
[ "python", "sms" ]
stackoverflow_0001689638_python_sms.txt
Q: Why we should perfer to store the serialized data not the raw code to DB? If we have some code(a data structure) which should be stored in DB, someone always suggests us to store the serialized data not the raw code string. So I'm not so sure why we should prefer the serialized data. Give a simple instance(in pyth...
Why we should perfer to store the serialized data not the raw code to DB?
If we have some code(a data structure) which should be stored in DB, someone always suggests us to store the serialized data not the raw code string. So I'm not so sure why we should prefer the serialized data. Give a simple instance(in python): we've got a field which will store a dict of python, like { "name" : "BMW...
[ "\nOr we can store the dict string\n directly to DB without serializing.\n\nThere is no such thing as \"the dict string\". There are many ways to serialize a dict into a string; you may be thinking of repr, possibly as eval as the way to get the dict back (you mention exec, but that's simply absurd: what statemen...
[ 10, 3, 3, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "database", "python", "serialization" ]
stackoverflow_0001685330_database_python_serialization.txt
Q: How do I fetch an XML document and parse it with Python twisted? I want a fast way to grab a URL and parse it while streaming. Ideally this should be super fast. My language of choice is Python. I have an intuition that twisted can do this but I'm at a loss to find an example. A: If you need to handle HTTP resp...
How do I fetch an XML document and parse it with Python twisted?
I want a fast way to grab a URL and parse it while streaming. Ideally this should be super fast. My language of choice is Python. I have an intuition that twisted can do this but I'm at a loss to find an example.
[ "If you need to handle HTTP responses in a streaming fashion, there are a few options.\nYou can do it via downloadPage:\nfrom xml.sax import make_parser\nfrom twisted.web.client import downloadPage\n\nclass StreamingXMLParser:\n def __init__(self):\n self._parser = make_parser()\n\n def write(self, byt...
[ 7, 0 ]
[]
[]
[ "python", "twisted", "xml" ]
stackoverflow_0001659380_python_twisted_xml.txt
Q: Is TCP Guaranteed to arrive in order? If I send two TCP messages, do I need to handle the case where the latter arrives before the former? Or is it guaranteed to arrive in the order I send it? I assume that this is not a Twisted-specific example, because it should conform to the TCP standard, but if anyone familia...
Is TCP Guaranteed to arrive in order?
If I send two TCP messages, do I need to handle the case where the latter arrives before the former? Or is it guaranteed to arrive in the order I send it? I assume that this is not a Twisted-specific example, because it should conform to the TCP standard, but if anyone familiar with Twisted could provide a Twisted-spec...
[ "As long as the two messages were sent on the same TCP connection, order will be maintained. If multiple connections are opened between the same pair of processes, you may be in trouble.\nRegarding Twisted, or any other asynchronous event system: I expect you'll get the dataReceived messages in the order that byte...
[ 54, 25, 20, 8 ]
[]
[]
[ "protocols", "python", "tcp", "twisted" ]
stackoverflow_0001691179_protocols_python_tcp_twisted.txt
Q: Location of Sphinx sources for my notes - WARNING: document isn't included in any toctree How can you fix the Sphinx's warning at the bottom? I am trying to have my Python notes in Sphinx. I have my notes in separate files at the same directory level as the index.rst. I get the following warnings after building HT...
Location of Sphinx sources for my notes - WARNING: document isn't included in any toctree
How can you fix the Sphinx's warning at the bottom? I am trying to have my Python notes in Sphinx. I have my notes in separate files at the same directory level as the index.rst. I get the following warnings after building HTML The warning /home/heo/S_codes/trig_functions.rst:: WARNING: document isn't included in any t...
[ "Are you aware of Sphinx's documentation? https://www.sphinx-doc.org\nSpecifically, read about the toctree directive: https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-toctree\nYou can have as many files as you want. Via toctree you can create a single document from many parts....
[ 6 ]
[]
[]
[ "glob", "python", "python_sphinx", "toctree" ]
stackoverflow_0001690757_glob_python_python_sphinx_toctree.txt
Q: Is there any benefit to returning a hash constructed with dict rather than just using the curly braces syntax? In some Python code I've read I keep noticing this code: return dict(somekey=somevalue) Does that have any benefit over: return {somekey:somevalue} I tend to say no, since both objects will belong to th...
Is there any benefit to returning a hash constructed with dict rather than just using the curly braces syntax?
In some Python code I've read I keep noticing this code: return dict(somekey=somevalue) Does that have any benefit over: return {somekey:somevalue} I tend to say no, since both objects will belong to the same dict type, but I may be wrong.
[ "\n>>> def foo(): return dict(a=1)\n...\n>>> def bar(): return {'a':1}\n...\n>>> import dis\n>>> dis.dis(foo)\n 1 0 LOAD_GLOBAL 0 (dict)\n 3 LOAD_CONST 1 ('a')\n 6 LOAD_CONST 2 (1)\n 9 CALL_FUNCTION 256\n ...
[ 15, 5, 2, 2, 1, 1 ]
[]
[]
[ "dictionary", "hash", "python" ]
stackoverflow_0001690517_dictionary_hash_python.txt
Q: optimizing this django code? I'm having some performance issues because I'm making a lot of query calls that I'm not sure how to reduce. user_item_rel_set is a m2m relation between user and items showing how much a user paid for a particular item. Each item can have multiple users and buyers, and I'm trying to ge...
optimizing this django code?
I'm having some performance issues because I'm making a lot of query calls that I'm not sure how to reduce. user_item_rel_set is a m2m relation between user and items showing how much a user paid for a particular item. Each item can have multiple users and buyers, and I'm trying to get the m2m relation for a particula...
[ "Some additional code from your model would help, because it's hard to see what the 'items' queryset contains.\nI will try to help anyway...\nBecause you've modeled a relationship between users and items, there is no need to iterate over every item in that queryset when you can simply select the subset that are int...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001691207_django_python.txt
Q: How to implement Symfony Partials or Components in Django? I've been developing in the Symfony framework for quite a time, but now I have to work with Django and I'm having problems with doing something like a "component" or "partial" in Symfony. That said, here is my goal: I have a webpage with lots of small wid...
How to implement Symfony Partials or Components in Django?
I've been developing in the Symfony framework for quite a time, but now I have to work with Django and I'm having problems with doing something like a "component" or "partial" in Symfony. That said, here is my goal: I have a webpage with lots of small widgets, all these need their logic - located in a "views.py" I gue...
[ "It sounds like what you're looking for is something like custom template tags...\nYou can write your own set of tags that process custom logic and return template chunks that are reusable in a very widget-like way.\n", "Assuming you are going to be using the components in different places on different pages I wo...
[ 3, 1 ]
[]
[]
[ "django", "python", "symfony1" ]
stackoverflow_0001691400_django_python_symfony1.txt
Q: Organizing Python projects with shared packages What is the best way to organize and develop a project composed of many small scripts sharing one (or more) larger Python libraries? We have a bunch of programs in our repository that all use the same libraries stored in the same repository. So in other words, a lay...
Organizing Python projects with shared packages
What is the best way to organize and develop a project composed of many small scripts sharing one (or more) larger Python libraries? We have a bunch of programs in our repository that all use the same libraries stored in the same repository. So in other words, a layout like trunk libs python utilit...
[ "The much better solution involves not storing all your projects and their shared dependencies in the same repository.\nUse one repository for each project, and externals for the shared libraries.\nMake use of tags in the shared library repositories, so consumer projects may use exactly the version they need in the...
[ 2, 1 ]
[]
[]
[ "code_organization", "python", "svn", "version_control" ]
stackoverflow_0001691495_code_organization_python_svn_version_control.txt
Q: Modulus in Python's slicing How can you fix the following code? I want to get the slice of elements that are i mod 5 == 1. data = "8|9|8|9|8|9|8|9|9|8|9|8|9|8|9|8" arra = map(int,data.split("|")) sums += [sum(arra[i % 5==1:(i + 4) % 5==1]) // Problem here for i in range(0, len(arra), 4)] A: ...
Modulus in Python's slicing
How can you fix the following code? I want to get the slice of elements that are i mod 5 == 1. data = "8|9|8|9|8|9|8|9|9|8|9|8|9|8|9|8" arra = map(int,data.split("|")) sums += [sum(arra[i % 5==1:(i + 4) % 5==1]) // Problem here for i in range(0, len(arra), 4)]
[ "sums += sum(arra[1::5])\n\nAnd it's spelled array. ;-)\n", "It's\nsums = sum(arra[1::5])\n\nIf you use +=, Python spects that the name sums is alreadey accesible:\nTraceback (most recent call last):\n File \"\", line 1, in \n sums += sum(arra[1::5])\nNameError: name 'sums' is not defined\n" ]
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001689984_python.txt
Q: python cProfile and profile models skip functions basically the cProfile module skips some functions when i run it, and the normal profile module produces this error. The debugged program raised the exception unhandled AssertionError "('Bad call', ('objects/controller/StageController.py', 9, '__init__'), <fram...
python cProfile and profile models skip functions
basically the cProfile module skips some functions when i run it, and the normal profile module produces this error. The debugged program raised the exception unhandled AssertionError "('Bad call', ('objects/controller/StageController.py', 9, '__init__'), <frame object at 0x9bbc104>, <frame object at 0x9bb438c>, <f...
[ "I've found the problem. Psyco\nthe 'ObjectControl' class which my 'StageControl' inherited has a simple:\nimport psyco\npsyco.full()\n\nINSIDE the class, which caused the error hence only the methods in the classes which inherited 'ObjectControl', caused the profiler to fail. i read somewhere it was a good idea to...
[ 2, 0 ]
[]
[]
[ "profiler", "python" ]
stackoverflow_0001688412_profiler_python.txt
Q: What is the default chunker for NLTK toolkit in Python? I am using their default POS tagging and default tokenization..and it seems sufficient. I'd like their default chunker too. I am reading the NLTK toolkit book, but it does not seem like they have a default chunker? A: You can get out of the box named entit...
What is the default chunker for NLTK toolkit in Python?
I am using their default POS tagging and default tokenization..and it seems sufficient. I'd like their default chunker too. I am reading the NLTK toolkit book, but it does not seem like they have a default chunker?
[ "You can get out of the box named entity chunking with the nltk.ne_chunk() method. It takes a list of POS tagged tuples:\nnltk.ne_chunk([('Barack', 'NNP'), ('Obama', 'NNP'), ('lives', 'NNS'), ('in', 'IN'), ('Washington', 'NNP')])\nresults in:\nTree('S', [Tree('PERSON', [('Barack', 'NNP')]), Tree('ORGANIZATION', [(...
[ 9, 8 ]
[]
[]
[ "chunking", "nlp", "nltk", "python" ]
stackoverflow_0001687510_chunking_nlp_nltk_python.txt
Q: Parsing output of apt-get install for progress bar I'm working on a simple GUI Python script to do some simple tasks on a system. Some of that work involves apt-get install to install some packages. While this is going on, I want to display a progress bar that should update with the progress of the download, using...
Parsing output of apt-get install for progress bar
I'm working on a simple GUI Python script to do some simple tasks on a system. Some of that work involves apt-get install to install some packages. While this is going on, I want to display a progress bar that should update with the progress of the download, using the little percentage shown in apt-get's interface in t...
[ "Instead of parsing the output of the apt-get, you can use python-apt to install packages. AFAIK it also has modules for reporting the progress.\n", "As I've often said, use pexpect, not subprocess etc, to run sub-processes when you need to get their continuous output. pexpect fools the subprocess into believing...
[ 6, 3 ]
[]
[]
[ "apt_get", "popen", "progress_bar", "python", "subprocess" ]
stackoverflow_0001692082_apt_get_popen_progress_bar_python_subprocess.txt
Q: Open web page with custom cookies in Python For example, I have cookies my_cookies = {'name': 'Albert', 'uid': '654897897564'} and I want to open page http://website.com opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) opener.addheaders.append(('User-agent', 'Mozilla/5.0 (compatible)')) opener.open('h...
Open web page with custom cookies in Python
For example, I have cookies my_cookies = {'name': 'Albert', 'uid': '654897897564'} and I want to open page http://website.com opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) opener.addheaders.append(('User-agent', 'Mozilla/5.0 (compatible)')) opener.open('http://website.com').read() How I can do this wit...
[ "You just need a few more steps:\nimport urllib2\nimport cookielib\n\ncp = urllib2.HTTPCookieProcessor()\ncj = cp.cookiejar\n\n# see cookielib.Cookie documentation for options description\ncj.set_cookie(cookielib.Cookie(0, 'a_cookie', 'a_value',\n '80', False, 'domain', True, False, '/...
[ 8 ]
[]
[]
[ "cookies", "python", "urllib2" ]
stackoverflow_0001692396_cookies_python_urllib2.txt
Q: What is a scripting engine? I've seen here that what sets a programming language apart from a scripting language is the scripting engine. But I don't understand how it works, so I don't know the difference. For example, I see code in Java calling methods in imported libraries, but it doesn't seem "different enough...
What is a scripting engine?
I've seen here that what sets a programming language apart from a scripting language is the scripting engine. But I don't understand how it works, so I don't know the difference. For example, I see code in Java calling methods in imported libraries, but it doesn't seem "different enough" from Python or Ruby code - both...
[ "There is no hard and fast line between a \"scripting language\" and a \"programming language\".\nProperties of \"scripting languages\" tend to include:\n\ngarbage-collected memory manager, with no need to explicitly allocate and free objects\nability to simply execute commands, without a bunch of boilerplate code....
[ 12, 6, 3, 2, 0, 0 ]
[]
[]
[ "java", "python", "ruby", "scripting" ]
stackoverflow_0001691201_java_python_ruby_scripting.txt
Q: Python internationalization, local setting independent I need the return of a strftime() call being in a language different at the one set on my local machine/OS. Is that possible to choose the language of the return? A: For solid i18n/L10N, usable by a server which must serve different localizations within the ...
Python internationalization, local setting independent
I need the return of a strftime() call being in a language different at the one set on my local machine/OS. Is that possible to choose the language of the return?
[ "For solid i18n/L10N, usable by a server which must serve different localizations within the same run, I keep recommending PyICU, the Python layer on top of ICU, the International Components for Unicode open-source package. Other approaches tend to be pretty limited and fragile:-(.\n", "Try the babel library: ht...
[ 1, 0 ]
[]
[]
[ "internationalization", "python" ]
stackoverflow_0001690857_internationalization_python.txt
Q: Agile Software Development in Python I have been trying to learn a cross platform language with a fast learning curve, and so it seemed obvious Python was the logical choice. I've never programmed before but I have been reading on pragmatic programming and agile development for quite some time. The question come...
Agile Software Development in Python
I have been trying to learn a cross platform language with a fast learning curve, and so it seemed obvious Python was the logical choice. I've never programmed before but I have been reading on pragmatic programming and agile development for quite some time. The question comes, "What is the single best choice to crea...
[ "For cross-platform GUI-based desktop software, my preference is Qt -- solid, mature, rich, great tools, strong underlying event-like approach (signals and slots). Having Nokia behind it doesn't hurt, of course.\nThe mature Python interface to that is PyQt, but if the alternative of GPL or for-pay licenses is a pr...
[ 3, 2, 2, 1, 0, 0 ]
[]
[]
[ "database", "frameworks", "open_source", "python" ]
stackoverflow_0001390868_database_frameworks_open_source_python.txt
Q: python or bash - adding " at beginning of line and ", at end of line I have text file with something like first line line nr 2 line three etc And i want to generate "first line", "line nr 2", "line three", I wonder how to do this in python or maybe in bash if it's easier/quicker. I know there is different code f...
python or bash - adding " at beginning of line and ", at end of line
I have text file with something like first line line nr 2 line three etc And i want to generate "first line", "line nr 2", "line three", I wonder how to do this in python or maybe in bash if it's easier/quicker. I know there is different code for opening file and different for reading only one line in python(?) but i...
[ "sed 's/.*/\"&\",/'\n\n", "For the reference, in case someone wants to do the same thing using python. There is a handy module fileinput that could be used like this:\nimport fileinput\nimport sys, os\n\nfor line in fileinput.input(inplace=True):\n sys.stdout.write('\"%s\",%s' % (line.rstrip(os.linesep), os.li...
[ 8, 6, 6, 5, 4, 1, 1, 0, 0 ]
[]
[]
[ "bash", "linux", "python" ]
stackoverflow_0001688952_bash_linux_python.txt
Q: How to profile a Django custom management command exclusively I would like to profile a custom management command that is relatively CPU intensive (renders an image using PIL). When I use the following command I get all sorts of Django modules (admin, ORM etc) in my profiling results: python -m cProfile manage.py ...
How to profile a Django custom management command exclusively
I would like to profile a custom management command that is relatively CPU intensive (renders an image using PIL). When I use the following command I get all sorts of Django modules (admin, ORM etc) in my profiling results: python -m cProfile manage.py testrender I have removed all imports that can potentially import ...
[ "I solved this problem the following way:\nfrom cProfile import Profile\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n ...\n\n def _handle(self, *args, **options):\n # Actual code I want to profile\n pass\n\n def handle(self, *args, **options):\n ...
[ 19, 1, 0 ]
[]
[]
[ "django", "profiling", "python" ]
stackoverflow_0001687125_django_profiling_python.txt
Q: How do I check if it's the homepage in a Plone website using ZPT? I want to change my website's header only it if's not the homepage. Is there a tal:condition expression for that? I've been reading this and can't find what I'm looking for... thanks! A: The best way is to use two really handy plone views that are...
How do I check if it's the homepage in a Plone website using ZPT?
I want to change my website's header only it if's not the homepage. Is there a tal:condition expression for that? I've been reading this and can't find what I'm looking for... thanks!
[ "The best way is to use two really handy plone views that are intended just for this purpose. The interface that defines them is at https://svn.plone.org/svn/plone/plone.app.layout/trunk/plone/app/layout/globals/interfaces.py, in case you want to check it out.\n<tal:block\n tal:define=\"our_url context/@@plone_co...
[ 6, 1, 0 ]
[]
[]
[ "plone", "python", "template_tal", "zope", "zpt" ]
stackoverflow_0000651009_plone_python_template_tal_zope_zpt.txt
Q: CSS parser + XHTML generator, advice needed Guys, I need to develop a tool which would meet following requirements: Input: XHTML document with CSS rules within head section. Output: XHTML document with CSS rules computed in tag attributes The best way to illustrate the behavior I want is as follows. Example in...
CSS parser + XHTML generator, advice needed
Guys, I need to develop a tool which would meet following requirements: Input: XHTML document with CSS rules within head section. Output: XHTML document with CSS rules computed in tag attributes The best way to illustrate the behavior I want is as follows. Example input: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0...
[ "Try premailer\ncode.dunae.ca/premailer.web\nMore info:\ncampaignmonitor.com\n", "While I do not know any specific tool to do this, here is the basic approach I would take: \nLoad as xml document \nExtract the css classes and styles from document \nFor each pair of css class and style \n  Construct xpath query fr...
[ 3, 1, 1, 0 ]
[]
[]
[ "css", "parsing", "python", "xhtml" ]
stackoverflow_0000781382_css_parsing_python_xhtml.txt
Q: Move or copy an entity to another kind Is there a way to move an entity to another kind in appengine. Say you have a kind defines, and you want to keep a record of deleted entities of that kind. But you want to separate the storage of live object and archived objects. Kinds are basically just serialized dicts in t...
Move or copy an entity to another kind
Is there a way to move an entity to another kind in appengine. Say you have a kind defines, and you want to keep a record of deleted entities of that kind. But you want to separate the storage of live object and archived objects. Kinds are basically just serialized dicts in the bigtable anyway. And maybe you don't need...
[ "Unless someone's written utilities for this kind of thing, the way to go is to read from one and write to the other kind!\n", "No - once created, the kind is a part of the entity's immutable key. You need to create a new entity and copy everything across. One way to do this would be to use the low-level google.a...
[ 1, 1 ]
[]
[]
[ "archive", "bigtable", "google_app_engine", "indexing", "python" ]
stackoverflow_0001693815_archive_bigtable_google_app_engine_indexing_python.txt
Q: Using md5 on BeautifulSoup result Im trying to use the md5 algorithm on web pages to avoid seeing duplicates. Is there an easy way to convert the result from beautifulsoup into a string which is digestible by md5? Many thanks A: Just turn it into a string with str: from BeautifulSoup import BeautifulSoup doc = "...
Using md5 on BeautifulSoup result
Im trying to use the md5 algorithm on web pages to avoid seeing duplicates. Is there an easy way to convert the result from beautifulsoup into a string which is digestible by md5? Many thanks
[ "Just turn it into a string with str:\nfrom BeautifulSoup import BeautifulSoup\ndoc = \"<html><h1>Heading</h1><p>Text\"\nsoup = BeautifulSoup(doc)\n\nstr(soup)\n\n(from the docs)\n" ]
[ 4 ]
[]
[]
[ "beautifulsoup", "md5", "python" ]
stackoverflow_0001694061_beautifulsoup_md5_python.txt
Q: Finding a logic bug in converting Python code to PHP The input 7|12|1|14|2|13|8|11|16|3|10|5|9|6|15|4 returns 0 by the PHP -code, while 1 by Python code: 1 means that the sums of the 4x4 magic square are the same, while 0 means the reverse. Python code is correct. The problem of the PHP code seems to be in the fu...
Finding a logic bug in converting Python code to PHP
The input 7|12|1|14|2|13|8|11|16|3|10|5|9|6|15|4 returns 0 by the PHP -code, while 1 by Python code: 1 means that the sums of the 4x4 magic square are the same, while 0 means the reverse. Python code is correct. The problem of the PHP code seems to be in the function divide's for -loop, since PHP gives too many sums. ...
[ "The problem is in your PHP line:\nfor ( $i = 0; $i < count( $sum ); $i++ ) {\n\nyou wanted:\nfor ( $i = 0; $i < count( $array ); $i++ ) {\n\nFix it in both places, and you get the right answer.\nBTW: You are only checking the main diagonals, but you can also check the other wrapping diagonals, and as Greg points o...
[ 2, 1, 1 ]
[]
[]
[ "php", "python" ]
stackoverflow_0001693945_php_python.txt
Q: Django: Ordering objects by their children's attributes Consider the models: class Author(models.Model): name = models.CharField(max_length=200, unique=True) class Book(models.Model): pub_date = models.DateTimeField() author = models.ForeignKey(Author) Now suppose I want to order all the books by, sa...
Django: Ordering objects by their children's attributes
Consider the models: class Author(models.Model): name = models.CharField(max_length=200, unique=True) class Book(models.Model): pub_date = models.DateTimeField() author = models.ForeignKey(Author) Now suppose I want to order all the books by, say, their pub_date. I would use order_by('pub_date'). But what...
[ "from django.db.models import Max\nAuthor.objects.annotate(max_pub_date=Max('books__pub_date')).order_by('-max_pub_date')\n\nthis requires that you use django 1.1\nand i assumed you will add a 'related_name' to your author field in Book model, so it will be called by Author.books instead of Author.book_set. its muc...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "database", "django", "django_models", "python", "sql" ]
stackoverflow_0001692322_database_django_django_models_python_sql.txt
Q: How to access the current table in Numbers? How do I access the current table in Numbers using py-appscript? For posterity, the program I created using this information clears all the cells of the current table and returns the selection to cell A1. I turned it into a Service using a python Run Shell Script in Aut...
How to access the current table in Numbers?
How do I access the current table in Numbers using py-appscript? For posterity, the program I created using this information clears all the cells of the current table and returns the selection to cell A1. I turned it into a Service using a python Run Shell Script in Automator and attached it to Numbers. from appscrip...
[ ">>> d = app('Numbers').documents.first() # reference to current top document\n\nEDIT: There doesn't seem to be a straight-forward single reference to the current table but it looks like you can find it by searching the current first document's sheets for a table with a non-null selection_range, so something like ...
[ 2 ]
[]
[]
[ "iwork", "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0001694060_iwork_py_appscript_python_sourceforge_appscript.txt
Q: Reasons to prefer zope 3 over grok I am familiar with zope 2 and think that zope 3 is superior in many ways, as far as I've used it (i.e. primarily with Five). Now I'm considering to dive deeper into zope 3. Would you recommend going even one step further and use grok instead, and if so, why? (and if not, why not?...
Reasons to prefer zope 3 over grok
I am familiar with zope 2 and think that zope 3 is superior in many ways, as far as I've used it (i.e. primarily with Five). Now I'm considering to dive deeper into zope 3. Would you recommend going even one step further and use grok instead, and if so, why? (and if not, why not? :)
[ "A good resource is http://plone.org/products/dexterity/documentation/manual/five.grok/referencemanual-all-pages . Plone is probably the biggest piece of software that uses zope3, so the fact that plone uses grok's way of configuring zope3 counts for something.\nI'd definitively recommend going one step further and...
[ 5 ]
[]
[]
[ "grok", "python", "zope" ]
stackoverflow_0001694309_grok_python_zope.txt
Q: Difference between ^ Operator in JS and Python I need to port some JS code which involves Math.random()*2147483648)^(new Date).getTime(). While it looks like for smaller numbers, the python function and the JS function are equivalent in function, but with large numbers like this, the values end up entirely differe...
Difference between ^ Operator in JS and Python
I need to port some JS code which involves Math.random()*2147483648)^(new Date).getTime(). While it looks like for smaller numbers, the python function and the JS function are equivalent in function, but with large numbers like this, the values end up entirely different. Python: >>> 2147483647 ^ 1257628307380 125707504...
[ "Python has unlimited-precision integers, while Javascript is using a 32-bit integer. You can manually apply a 32-bit limit to get the result you want:\ndef xor32bit(a, b):\n m = (a ^ b) % (2**32)\n if m > (2**16):\n m -= 2**32\n return m\n\n", "Easiest way would be to use ctypes to get the same ...
[ 7, 4 ]
[]
[]
[ "bit_manipulation", "javascript", "python", "xor" ]
stackoverflow_0001694507_bit_manipulation_javascript_python_xor.txt
Q: How do you generate random unique identifiers in a multi process and multi thread environment? Every solution I come up with is not thread save. def uuid(cls,db): u = hexlify(os.urandom(8)).decode('ascii') db.execute('SELECT sid FROM sessions WHERE sid=?',(u,)) if db.fetch(): u=cls.uuid(db) else: d...
How do you generate random unique identifiers in a multi process and multi thread environment?
Every solution I come up with is not thread save. def uuid(cls,db): u = hexlify(os.urandom(8)).decode('ascii') db.execute('SELECT sid FROM sessions WHERE sid=?',(u,)) if db.fetch(): u=cls.uuid(db) else: db.execute('INSERT INTO sessions (sid) VALUES (?)',(u,)) return u
[ "import os, threading, Queue\n\ndef idmaker(aqueue):\n while True:\n u = hexlify(os.urandom(8)).decode('ascii')\n aqueue.put(u)\n\nidqueue = Queue.Queue(2)\n\nt = threading.Thread(target=idmaker, args=(idqueue,))\nt.daemon = True\nt.start()\n\ndef idgetter():\n return idqueue.get()\n\nQueue is often the bes...
[ 5, 3, 3, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "mod_wsgi", "python", "sql" ]
stackoverflow_0001687344_mod_wsgi_python_sql.txt
Q: How to set selection for a table in Numbers? How do you set the selection for a table in Numbers using py-appscript? This seems like it should be really simple to do but the solution is frustratingly evasive. I can get the current selection: current_table.selection_range and I can get its cells: current_table....
How to set selection for a table in Numbers?
How do you set the selection for a table in Numbers using py-appscript? This seems like it should be really simple to do but the solution is frustratingly evasive. I can get the current selection: current_table.selection_range and I can get its cells: current_table.selection_range.cells() but trying to set() eithe...
[ "Looks like something like this works:\n>>> current_table.selection_range.set(to=current_table.ranges[u'B3:C10'])\n\nNote, looking at Number's script dictionary in AppleScript Editor or with ASDictionary, the property selection_range is defined as class range. So that's a clue that you need to come up with a refer...
[ 3 ]
[]
[]
[ "iwork", "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0001694478_iwork_py_appscript_python_sourceforge_appscript.txt
Q: How can I build the Boost.Python example on Ubuntu 9.10? I am using Ubuntu 9.10 beta, whose repositories contain boost 1.38. I would like to build the hello-world example. I followed the instructions here (http://www.boost.org/doc/libs/1_40_0/libs/python/doc/tutorial/doc/html/python/hello.html), found the exampl...
How can I build the Boost.Python example on Ubuntu 9.10?
I am using Ubuntu 9.10 beta, whose repositories contain boost 1.38. I would like to build the hello-world example. I followed the instructions here (http://www.boost.org/doc/libs/1_40_0/libs/python/doc/tutorial/doc/html/python/hello.html), found the example project, and issued the "bjam" command. I have installed bj...
[ "The problem comes from using Ubuntu package instead of boost compiled from source. You have to edit you Jamroot to say it to use global libboost-python, instead of looking for lib in relative boost source tree.\nSummarily you should have these lines at the beginning of your Jamroot:\nusing python ;\nlib libboost_p...
[ 4 ]
[]
[]
[ "boost", "python", "ubuntu" ]
stackoverflow_0001569490_boost_python_ubuntu.txt
Q: Converting a list of tuples into a dict I have a list of tuples like this: [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] I want to iterate through this keying by the first item, so, for example, I could print something like this: a 1 2 3 b 1 2 c 1 How would I go about doing this without keeping...
Converting a list of tuples into a dict
I have a list of tuples like this: [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] I want to iterate through this keying by the first item, so, for example, I could print something like this: a 1 2 3 b 1 2 c 1 How would I go about doing this without keeping an item to track whether the first item is t...
[ "l = [\n('a', 1),\n('a', 2),\n('a', 3),\n('b', 1),\n('b', 2),\n('c', 1),\n]\n\nd = {}\nfor x, y in l:\n d.setdefault(x, []).append(y)\nprint d\n\nproduces:\n{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}\n\n", "Slightly simpler...\nfrom collections import defaultdict\n\nfq = defaultdict(list)\nfor n, v in myList:\n ...
[ 46, 39, 11, 3, 3 ]
[]
[]
[ "dictionary", "iteration", "list", "python", "tuples" ]
stackoverflow_0000261655_dictionary_iteration_list_python_tuples.txt
Q: generating javascript string in python i have string stored in python variables, and i am outputting a html that contains javascript, and the i need to create javascript variables. for ex, in python title = "What's your name?" i use Cheetah to generate the html. Cheetah code: var title = '$title'; how do i escap...
generating javascript string in python
i have string stored in python variables, and i am outputting a html that contains javascript, and the i need to create javascript variables. for ex, in python title = "What's your name?" i use Cheetah to generate the html. Cheetah code: var title = '$title'; how do i escape this correctly so that a correct javascrip...
[ "You probably want JSON:\nimport simplejson as sj\nprint sj.dumps('What\\'s your name?') # => '\"What\\'s your name?\"'\n\nDon't generate js with cheetah, there are libraries.\n" ]
[ 4 ]
[ "Either just do title = title.replace(\"'\", \"\\\\'\") in Python before the title value gets to Cheetah, or add a custom filter to Cheetah for the purpose and invoke it in the template. Doing it on the Python side of things seems simpler, though.\n" ]
[ -2 ]
[ "cheetah", "javascript", "python" ]
stackoverflow_0001694939_cheetah_javascript_python.txt
Q: "".join(reversed(val)) vs val[::-1]...which is pythonic? So according to the Zen of Python ... Explicit is better than implicit...Sparse is better than dense...Readability counts...but then again Flat is better than nested...so then which is pythonic? val = "which is pythonic?" print("".join(reversed(val))) or p...
"".join(reversed(val)) vs val[::-1]...which is pythonic?
So according to the Zen of Python ... Explicit is better than implicit...Sparse is better than dense...Readability counts...but then again Flat is better than nested...so then which is pythonic? val = "which is pythonic?" print("".join(reversed(val))) or print(val[::-1]) I'm just a Java programmer learning Python so...
[ "My wife Anna has nicknamed x[::-1] \"the Martian Smiley\" -- I mostly bow to her (and her long experience in training &c, and studies in human psychology &c), when it comes to judging what's easy and natural for most people, and she absolutely loves the martial smiley. \"Just walk it backwards\" -- how much more ...
[ 45, 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001695385_python.txt
Q: Joomla and XMLRPC How do I get started with getting going with XML-RPC with joomla? I've been looking around for documentation and finding nothing... I'd like to connect to a joomla server, (after enabling the Core Joomla XML-RPC plugin), and be able to do things like login and add an article, and tweak all the pa...
Joomla and XMLRPC
How do I get started with getting going with XML-RPC with joomla? I've been looking around for documentation and finding nothing... I'd like to connect to a joomla server, (after enabling the Core Joomla XML-RPC plugin), and be able to do things like login and add an article, and tweak all the parameters of the article...
[ "the book \"Mastering Joomla 1.5 Extension and Framework Development\" has a nice explanation of that.\nJoomla has a fex XML-RPC plugins that let you do a few things, like the blogger API interface. (plugins/xmlrpc/blogger.php)\nYou should create your own XML-RPC plugin to do the custom things you want.\n" ]
[ 3 ]
[]
[]
[ "joomla", "python", "xml_rpc" ]
stackoverflow_0001694205_joomla_python_xml_rpc.txt
Q: How to create 3 dimensions matrix in numpy , like matlab a(:,:,:) How to create 3 dimensions matrix in numpy , like matlab a(:,:,:) . I try to convert matlab code that create 3d matrix to python by use numpy.array and i don't know how to create 3d matrix/array in numpy A: a=np.empty((2,3,5)) creates a 2x3x5 a...
How to create 3 dimensions matrix in numpy , like matlab a(:,:,:)
How to create 3 dimensions matrix in numpy , like matlab a(:,:,:) . I try to convert matlab code that create 3d matrix to python by use numpy.array and i don't know how to create 3d matrix/array in numpy
[ "a=np.empty((2,3,5))\n\ncreates a 2x3x5 array. (There is also np.zeros if you want the values initialized.)\nYou can also reshape existing arrays:\na=np.arange(30).reshape(2,3,5)\n\nnp.arange(30) creates a 1-d array with values from 0..29. The reshape() method returns an array containing the same data with a new sh...
[ 69 ]
[]
[]
[ "matlab", "numpy", "python" ]
stackoverflow_0001696135_matlab_numpy_python.txt
Q: Are all HttpError in python subclasses of IOError In our code we catch IOError and log it before reraising. I am getting a "connection reset by peer", but nothing in the logs. Is "connection reset by peer" a subclass of IOError in python? ..... File "/usr/lib/python2.5/httplib.py", line 1047, in readline ...
Are all HttpError in python subclasses of IOError
In our code we catch IOError and log it before reraising. I am getting a "connection reset by peer", but nothing in the logs. Is "connection reset by peer" a subclass of IOError in python? ..... File "/usr/lib/python2.5/httplib.py", line 1047, in readline s = self._read() File "/usr/lib/python2.5/httplib.p...
[ "The stack trace you pasted looks like some Exception of class error with arguments (104, 'Connection reset by peer).\nSo it looks like it's not a HTTPError exception at all. It looks to me like it's actually a socket.error. This class is indeed a subclass of IOError since Python 2.6.\nBut I guess that's not your q...
[ 2 ]
[]
[]
[ "ioerror", "python" ]
stackoverflow_0001696195_ioerror_python.txt
Q: Searching values of a list in another List using Python I'm a trying to find a sublist of a list. Meaning if list1 say [1,5] is in list2 say [1,4,3,5,6] than it should return True. What I have so far is this: for nums in l1: if nums in l2: return True else: return False This would be true ...
Searching values of a list in another List using Python
I'm a trying to find a sublist of a list. Meaning if list1 say [1,5] is in list2 say [1,4,3,5,6] than it should return True. What I have so far is this: for nums in l1: if nums in l2: return True else: return False This would be true but I'm trying to return True only if list1 is in list2 in th...
[ "try:\n last_found = -1\n for num in L1:\n last_found = L2.index(num, last_found + 1)\n return True\nexcept ValueError:\n return False\n\nThe index method of list L2 returns the position at which the first argument (num) is found in the list; called, like here, with a second arg, it starts looking in the li...
[ 7, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001695452_list_python.txt
Q: How to read .bin files? I exported a .bin file from RealFlow 4 and now need to be able to read it in Python, to make an importer. How do these files work? A: Here you go: import struct class Particle: """A single particle. Attributes added in BinFile.""" pass class BinFile: """Parse and store the ...
How to read .bin files?
I exported a .bin file from RealFlow 4 and now need to be able to read it in Python, to make an importer. How do these files work?
[ "Here you go:\nimport struct\n\nclass Particle:\n \"\"\"A single particle. Attributes added in BinFile.\"\"\"\n pass\n\nclass BinFile:\n \"\"\"Parse and store the contents of a RealFlow .bin file.\"\"\"\n def __init__(self, fname):\n self.bindata = open(fname, \"rb\").read()\n self.off = ...
[ 5, 2, 0 ]
[]
[]
[ "binary", "file", "python" ]
stackoverflow_0001696165_binary_file_python.txt
Q: What is the return value of subprocess.call()? I am not sure what the return value of subprocess.call() means. Can I safely assume a zero value will always mean that the command executed successfully? Is the return value equivalent to the exit staus of a shell command? For example, will the following piece of co...
What is the return value of subprocess.call()?
I am not sure what the return value of subprocess.call() means. Can I safely assume a zero value will always mean that the command executed successfully? Is the return value equivalent to the exit staus of a shell command? For example, will the following piece of code work for virtually any command on Linux? cmd = "...
[ "Yes, Subprocess.call returns \"actual process return code\". \nYou can check official documentation of Subprocess.call and Subprocess.Popen.returncode\n", "It is the return code, but keep in mind it's up to the author of the subprocess what the return code means. There is a strong culture of 0 meaning success, ...
[ 38, 13, 5 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0001696998_linux_python.txt
Q: Django/SQL: keeping track of who who read what in a forum I'm working on a not-so-big project in django that will among other things incorporate a forum system. I have most of the system at a more or less functioning state, but I'm still missing a feature to mark unread threads for the users when there are new pos...
Django/SQL: keeping track of who who read what in a forum
I'm working on a not-so-big project in django that will among other things incorporate a forum system. I have most of the system at a more or less functioning state, but I'm still missing a feature to mark unread threads for the users when there are new posts. The thing is I can't really think of a way to properly stor...
[ "You're much better off storing the \"read\" bit, not the \"unread\" bit. And you can store them not as relational data, but in a giant bit-blob. Then you don't have to modify the read data at all when new posts are added, only when a user reads posts.\n", "You might also simply store the last time a user was r...
[ 2, 1 ]
[]
[]
[ "database", "database_design", "django", "python", "sql" ]
stackoverflow_0001697045_database_database_design_django_python_sql.txt
Q: Clean input strings without using the django Form classes Is there a recommended way of using Django to clean an input string without going through the Django form system? That is, I'm writing code that delivers form input via AJAX so I'm skipping the whole Form model django offers. But I do want to clean the i...
Clean input strings without using the django Form classes
Is there a recommended way of using Django to clean an input string without going through the Django form system? That is, I'm writing code that delivers form input via AJAX so I'm skipping the whole Form model django offers. But I do want to clean the input prior to submission to the database.
[ "Django Form models aren't just about rendering forms, they're more about processing and sanitizing form (GET/POST) input, which is what you want to do. When the POST or GET data from your AJAX request reaches your server it's essentially indistinguishable from form data. I would advocate creating a Form model that...
[ 16 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001697508_django_python.txt
Q: How to open a pdb file in Python? I've got an e-book (viewable with isilo) in a pdb file. Is it possible to read it's contents with Python (perl, ruby, php)? A: PDB was designed for Palm pilots in the very beginning. isilo started kind of as a universal reader on PDAs so they've also implemented the PDB protocol...
How to open a pdb file in Python?
I've got an e-book (viewable with isilo) in a pdb file. Is it possible to read it's contents with Python (perl, ruby, php)?
[ "PDB was designed for Palm pilots in the very beginning. isilo started kind of as a universal reader on PDAs so they've also implemented the PDB protocol.\nFor python, you can use the Python PalmDB library. \n" ]
[ 4 ]
[]
[]
[ "palmdb", "pdb_palm", "python" ]
stackoverflow_0001697739_palmdb_pdb_palm_python.txt
Q: How to parse a custom string using optparse? How to parse a custom string using optparse, instead of command line argument? I want to parse a string that I get from using raw_input(). How can I use optparse for that? A: optparse expects a list of values that have been broken up shell-style (which is what argv[1:...
How to parse a custom string using optparse?
How to parse a custom string using optparse, instead of command line argument? I want to parse a string that I get from using raw_input(). How can I use optparse for that?
[ "optparse expects a list of values that have been broken up shell-style (which is what argv[1:] is). To accomplish the same starting with a string, try this:\nparser = optparse.OptionParser()\n# Set up your OptionParser\n\ninp = raw_input(\"Enter some crap: \")\n\ntry: (options, args) = parser.parse_args(shlex.spli...
[ 9, 4 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0001697761_optparse_python.txt
Q: Why does str.lstrip strip an extra character? >>> path = "/Volumes/Users" >>> path.lstrip('/Volume') 's/Users' >>> path.lstrip('/Volumes') 'Users' >>> I expected the output of path.lstrip('/Volumes') to be '/Users' A: lstrip is character-based, it removes all characters from the left end that are in that strin...
Why does str.lstrip strip an extra character?
>>> path = "/Volumes/Users" >>> path.lstrip('/Volume') 's/Users' >>> path.lstrip('/Volumes') 'Users' >>> I expected the output of path.lstrip('/Volumes') to be '/Users'
[ "lstrip is character-based, it removes all characters from the left end that are in that string.\nTo verify this, try this:\n\"/Volumes/Users\".lstrip(\"semuloV/\") # also returns \"Users\"\n\nSince / is part of the string, it is removed.\nYou need to use slicing instead:\nif s.startswith(\"/Volumes\"):\n s = s...
[ 34, 17, 16, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001687171_python_string.txt
Q: Matching tags in BeautifulSoup I'm trying to count the number of tags in the 'soup' from a beautifulsoup result. I'd like to use a regular expression but am having trouble. The code Ive tried is as follows: reg_exp_tag = re.compile("<[^>*>") tags = re.findall(reg_exp_tag, soup(cast as a string)) but re will not a...
Matching tags in BeautifulSoup
I'm trying to count the number of tags in the 'soup' from a beautifulsoup result. I'd like to use a regular expression but am having trouble. The code Ive tried is as follows: reg_exp_tag = re.compile("<[^>*>") tags = re.findall(reg_exp_tag, soup(cast as a string)) but re will not allow reg_exp_tag, giving an unexpect...
[ "If you've already parsed the HTML with BeautifulSoup, why parse it again? Try this:\nnum_tags = len(soup.findAll())\n\n", "Shouldn't that be \"<[^>]*>\" instead of \"<[^>*>\"?\n(the class needs to be closed with a ])\n" ]
[ 4, 1 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0001697774_beautifulsoup_python_regex.txt
Q: How to create Django FormWizard for one Model? I have Django Model with many fields which user must fill. If I'll create one ModelForm for this Model it will be big enough for one form. I want to split it using FormWizard. I think it's possible first to create forms dynamically and then create FormWizard using the...
How to create Django FormWizard for one Model?
I have Django Model with many fields which user must fill. If I'll create one ModelForm for this Model it will be big enough for one form. I want to split it using FormWizard. I think it's possible first to create forms dynamically and then create FormWizard using them. Is this good approach or is there any better way?...
[ "To me it seems fine.\nThe approach for creating partial forms is written in the docs.\nIn short:\nclass PartialAuthorForm(ModelForm):\n class Meta:\n model = Author\n fields = ('name', 'title')\n\nclass PartialAuthorForm(ModelForm):\n class Meta:\n model = Author\n exclude = ('bir...
[ 2 ]
[]
[]
[ "django", "django_forms", "formwizard", "python" ]
stackoverflow_0001697866_django_django_forms_formwizard_python.txt
Q: Which database should I use to store records, and how should I use it? I'm developing an application that will store a sizeable number of records. These records will be something like (URL, date, title, source, {optional data...}) As this is a client-side app, I don't want to use a database server, I just want the...
Which database should I use to store records, and how should I use it?
I'm developing an application that will store a sizeable number of records. These records will be something like (URL, date, title, source, {optional data...}) As this is a client-side app, I don't want to use a database server, I just want the info stored into files. I want the files to be readable from various langua...
[ "\nI am seeing two possibilities: sqlite\n and BerkeleyDB. As my use case is\n clearly not relational, I am tempted\n to go with BerkeleyDB, however I don't\n really know how I should use it to\n store my records, as it only stores\n key/value pairs.\n\nWhat you are describing is exactly what relational is ab...
[ 4, 2, 2, 1, 1, 0 ]
[]
[]
[ "c++", "database", "persistence", "python" ]
stackoverflow_0001697153_c++_database_persistence_python.txt
Q: Selective merge of two or more data files I have an executable whose input is contained in an ASCII file with format: $ GENERAL INPUTS $ PARAM1 = 123.456 PARAM2=456,789,101112 PARAM3(1)=123,456,789 PARAM4 = 1234,5678,91011E2 PARAM5(1,2)='STRING','STRING2' $ NEW INSTANCE NEW(1)=.TRUE. PAR1=123 [More data here...
Selective merge of two or more data files
I have an executable whose input is contained in an ASCII file with format: $ GENERAL INPUTS $ PARAM1 = 123.456 PARAM2=456,789,101112 PARAM3(1)=123,456,789 PARAM4 = 1234,5678,91011E2 PARAM5(1,2)='STRING','STRING2' $ NEW INSTANCE NEW(1)=.TRUE. PAR1=123 [More data here] $ NEW INSTANCE NEW(2)=.TRUE. [etcetera] In o...
[ "If you're already able to parse this format (I'd have tried it with pyParsing, but if you already have a working flexx/bison solution, that will be just fine), and the parsed data fit well in memory, then you're basically there. You can represent what you read from each file as a simple object with a dict for \"g...
[ 1 ]
[]
[]
[ "bison", "flex_lexer", "parsing", "python", "text_files" ]
stackoverflow_0001698188_bison_flex_lexer_parsing_python_text_files.txt
Q: Scipy loadmat only load integers? It seems I can only load everything as uint8 type, just with the following two lines, import scipy.io X1=scipy.io.loadmat('one.mat') all double precision numbers get transformed. I believe the creators of scipy are aware of the fact that floating-point numbers are much more common...
Scipy loadmat only load integers?
It seems I can only load everything as uint8 type, just with the following two lines, import scipy.io X1=scipy.io.loadmat('one.mat') all double precision numbers get transformed. I believe the creators of scipy are aware of the fact that floating-point numbers are much more common... So, what should I do? Thank you!
[ "What level matfile are you trying to read? According to the docs,\n\nv4 (Level 1.0), v6 and v7 to 7.2\n matfiles are supported.\nYou will need an HDF5 python library\n to read matlab 7.3 format mat files.\n Because scipy does not supply one, we\n do not implement the HDF5 / 7.3\n interface here.\n\nFor the s...
[ 1 ]
[]
[]
[ "mat_file", "python", "scipy" ]
stackoverflow_0001698223_mat_file_python_scipy.txt
Q: How to tame the location of third party contributions in Django I have a django project which is laid out like this... myproject apps media templates django registration sorl typogrify I'd like to change it to this... myproject apps media templates site-deps django registration sorl typogrify When I attempt...
How to tame the location of third party contributions in Django
I have a django project which is laid out like this... myproject apps media templates django registration sorl typogrify I'd like to change it to this... myproject apps media templates site-deps django registration sorl typogrify When I attempt it the 'site-dependencies' all break. Is there a way to imple...
[ "This looks like a job for virtualenv.\n\nA Primer on virtualenv\nWorking with Virtualenv\nUsing a Virtualenv Sandbox\nTools of the Modern Python Hacker: Virtualenv, Fabric and Pip\n\n", "PYTHONPATH searches in the order that the paths are listed\nPythonPath \"[ '/myproject', '/myproject/site-deps' ] + sys.path\"...
[ 3, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001309606_django_python.txt
Q: win32com and PAMIE web page open timeout currently im making some crawler script,one of problem is sometimes if i open webpage with PAMIE,webpage can't open and hang forever. are there any method to close PAMIE's IE or win32com's IE ? such like if webpage didn't response or loading complete less than 10sec or s...
win32com and PAMIE web page open timeout
currently im making some crawler script,one of problem is sometimes if i open webpage with PAMIE,webpage can't open and hang forever. are there any method to close PAMIE's IE or win32com's IE ? such like if webpage didn't response or loading complete less than 10sec or so . thanks in advance
[ "Just use, to initialize your PAMIE instance, PAMIE(timeOut=100) or whatever. The units of measure for timeOut are \"tenths of a second\" (!); the default is 3000 (300 seconds, i.e., 5 minutes); with 300 as I suggested, you'd time out after 10 seconds as you request.\n(You can pass the timeOut= parameter even when...
[ 2, 0 ]
[]
[]
[ "multithreading", "pamie", "python", "time" ]
stackoverflow_0001698362_multithreading_pamie_python_time.txt
Q: What is the fastest template system for Python? Jinja2 and Mako are both apparently pretty fast. How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ? A: Here are the results of the popular template engines for rendering a 10x1000 HTML table. Python 2.6.2 on a ...
What is the fastest template system for Python?
Jinja2 and Mako are both apparently pretty fast. How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?
[ "Here are the results of the popular template engines for rendering a 10x1000 HTML table.\nPython 2.6.2 on a 3GHz Intel Core 2\n\nKid template 696.89 ms\nKid template + cElementTree 649.88 ms\nGenshi template + tag builder 431.01 ms\nGenshi tag builder 389.3...
[ 104, 9, 3, 1 ]
[ "I think Cheetah might be the fastest, as it's implemented in C.\n" ]
[ -4 ]
[ "django_templates", "jinja2", "mako", "python", "template_engine" ]
stackoverflow_0001324238_django_templates_jinja2_mako_python_template_engine.txt
Q: What if setuptools isn't installed? I'm just learning the art of writing a setup.py file for my project. I see there's lots of talk about setuptools, which is supposed to be superior to distutils. There's one thing though that I fail to understand, and I didn't see it addressed in any tutorial I've read about this...
What if setuptools isn't installed?
I'm just learning the art of writing a setup.py file for my project. I see there's lots of talk about setuptools, which is supposed to be superior to distutils. There's one thing though that I fail to understand, and I didn't see it addressed in any tutorial I've read about this: What if setuptools isn't installed? I u...
[ "The standard way to distribute packages with setuptools includes an ez_setup.py script which will automatically download and install setuptools itself - on Windows I believe it will actually install an executable for easy_install. You can get this from the standard setuptools/easy_install distribution.\n", "In m...
[ 4, 2, 2, 1, 0, 0 ]
[]
[]
[ "deployment", "distutils", "python", "setuptools" ]
stackoverflow_0001666482_deployment_distutils_python_setuptools.txt
Q: BeautifulSoup is omitting body of page BeautifulSoup newbe... Need help Here is the code sample... from mechanize import Browser from BeautifulSoup import BeautifulSoup mec = Browser() #url1 = "http://www.wines.com/catalog/index.php?cPath=21" url2 = "http://www.wines.com/catalog/product_info.php?products_id=4866"...
BeautifulSoup is omitting body of page
BeautifulSoup newbe... Need help Here is the code sample... from mechanize import Browser from BeautifulSoup import BeautifulSoup mec = Browser() #url1 = "http://www.wines.com/catalog/index.php?cPath=21" url2 = "http://www.wines.com/catalog/product_info.php?products_id=4866" page = mec.open(url2) html = page.read() so...
[ "Yes. The HTML is bad. \nStep 1a, print soup.prettify() and see where it stops indenting correctly. \nStep 1b (if 1a doesn't work). Just print the raw through any HTML prettifying. I use BBEdit for things that confuse Beautiful Soup.\nLook closely at the HTML. There will be some kind of horrible error. Misplac...
[ 2, 2, 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "screen_scraping" ]
stackoverflow_0001698627_beautifulsoup_python_screen_scraping.txt
Q: Pythonic way to find a regular expression match Is there a more succinct/correct/pythonic way to do the following: url = "http://0.0.0.0:3000/authenticate/login" re_token = re.compile("<[^>]*authenticity_token[^>]*value=\"([^\"]*)") for line in urllib2.urlopen(url): if re_token.match(line): token = re_...
Pythonic way to find a regular expression match
Is there a more succinct/correct/pythonic way to do the following: url = "http://0.0.0.0:3000/authenticate/login" re_token = re.compile("<[^>]*authenticity_token[^>]*value=\"([^\"]*)") for line in urllib2.urlopen(url): if re_token.match(line): token = re_token.findall(line)[0] break I want to get t...
[ "Could you use Beautiful Soup for this? The code would essentially look something like so:\nfrom BeautifulSoup import BeautifulSoup\nurl = \"hhttp://0.0.0.0:3000/authenticate/login\"\npage = urlli2b.urlopen(page)\nsoup = BeautifulSoup(page)\ntoken = soup.find(\"input\", { 'name': 'authenticity_token'})\n\nSomething...
[ 6, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001698217_python_regex.txt
Q: Numpy, problem with long arrays I have two arrays (a and b) with n integer elements in the range (0,N). typo: arrays with 2^n integers where the largest integer takes the value N = 3^n I want to calculate the sum of every combination of elements in a and b (sum_ij_ = a_i_ + b_j_ for all i,j). Then take modulus N ...
Numpy, problem with long arrays
I have two arrays (a and b) with n integer elements in the range (0,N). typo: arrays with 2^n integers where the largest integer takes the value N = 3^n I want to calculate the sum of every combination of elements in a and b (sum_ij_ = a_i_ + b_j_ for all i,j). Then take modulus N (sum_ij_ = sum_ij_ % N), and finally ...
[ "try chunking it. your meshgrid is an NxN matrix, block that up to 10x10 N/10xN/10 and just compute 100 bins, add them up at the end. this only uses ~1% as much memory as doing the whole thing.\n", "Edit in response to jonalm's comment:\n\njonalm: N~3^n not n~3^N. N is max element in a and n is number of\n ele...
[ 7, 2, 1 ]
[]
[]
[ "math", "numpy", "python" ]
stackoverflow_0001697557_math_numpy_python.txt
Q: "Slice lists" and "the ellipsis" in Python; slicing lists and lists of lists with lists of slices Original question: Can someone tell me how to use "slice lists" and the "ellipsis"? When are they useful? Thanks. Here's what the language definition says about "slice_list" and "ellipsis"; Alex Martelli's answer p...
"Slice lists" and "the ellipsis" in Python; slicing lists and lists of lists with lists of slices
Original question: Can someone tell me how to use "slice lists" and the "ellipsis"? When are they useful? Thanks. Here's what the language definition says about "slice_list" and "ellipsis"; Alex Martelli's answer points out their origin, which is not what I had envisioned. [http://docs.python.org/reference/expressio...
[ "Slice lists and ellipsis were originally introduced in Python to supply nice syntax sugar for the precedessor of numpy (good old Numeric). If you're using numpy (no reason to go back to any of its predecessors!-) you should of course use them; if for whatever strange reason you're doing your own implementation of...
[ 11, 3, 1 ]
[]
[]
[ "list", "python", "python_itertools", "slice" ]
stackoverflow_0001698753_list_python_python_itertools_slice.txt
Q: Python data structure recommendation? I currently have a structure that is a dict: each value is a list that contains numeric values. Each of these numeric lists contain what (to borrow a SQL idiom) you could call a primary key containing the first three values which are: a year, a player identifier, and a team id...
Python data structure recommendation?
I currently have a structure that is a dict: each value is a list that contains numeric values. Each of these numeric lists contain what (to borrow a SQL idiom) you could call a primary key containing the first three values which are: a year, a player identifier, and a team identifier. This is the key for the dict. So ...
[ "Put your data into SQLite, and use its relational engine to do the work. You can create an in-memory database and not even have to touch the disk.\n", "Read up on Data Warehousing. Any book. \nRead up on Star Schema Design. Any book. Seriously. \nYou have several dimensions: Year, Player, Team. \nYou hav...
[ 4, 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001698734_python.txt
Q: Activate virtualenv via os.system() I'm writing a Python-based shell script to boilerplate a Django app with virtualenv, pip, and fabric. Should be straightforward enough, but it appears that I'm not able to activate and run commands in the virtualenv through the shell script. os.system('virtualenv %s --no-site-pa...
Activate virtualenv via os.system()
I'm writing a Python-based shell script to boilerplate a Django app with virtualenv, pip, and fabric. Should be straightforward enough, but it appears that I'm not able to activate and run commands in the virtualenv through the shell script. os.system('virtualenv %s --no-site-packages' % project_name) os.system('source...
[ "Each call to os.system runs the command in a new subshell, which has the same properties as the original python process.\nTry putting the commands into one string separated by semicolons.\n", "Just don't use \"source activate\" at all. It does nothing but alter your shell PATH to put the virtualenv's bin directo...
[ 11, 6, 5, 3 ]
[]
[]
[ "django", "fabric", "pip", "python", "virtualenv" ]
stackoverflow_0001691076_django_fabric_pip_python_virtualenv.txt
Q: UnicodeDecodeError with Django's request.FILES I have the following code in the view call.. def view(request): body = u"" for filename, f in request.FILES.items(): body = body + 'Filename: ' + filename + '\n' + f.read() + '\n' On some cases I get UnicodeDecodeError: 'ascii' codec can't decode by...
UnicodeDecodeError with Django's request.FILES
I have the following code in the view call.. def view(request): body = u"" for filename, f in request.FILES.items(): body = body + 'Filename: ' + filename + '\n' + f.read() + '\n' On some cases I get UnicodeDecodeError: 'ascii' codec can't decode byte 0xf0 in position 7470: ordinal not in range(128) ...
[ "Django has some utilities that handle this (smart_unicode, force_unicode, smart_str). Generally you just need smart_unicode.\nfrom django.utils.encoding import smart_unicode\ndef view(request):\n body = u\"\" \n for filename, f in request.FILES.items():\n body = body + 'Filename: ' + filename + '\\n...
[ 7, 4, 4, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001699126_django_python.txt
Q: regex in for loop How do you use a regex with a for loop in Python example data abc 1 xyz 0 abc 2 xyz 1 abc 3 xyz 2 How do you write regex for something like below for i in range(1, 3): re.match(abc +i xyz +(i-1)) A: This substitutes i into the first %s and i-1 into the second %s re.match("abc %s xyz %...
regex in for loop
How do you use a regex with a for loop in Python example data abc 1 xyz 0 abc 2 xyz 1 abc 3 xyz 2 How do you write regex for something like below for i in range(1, 3): re.match(abc +i xyz +(i-1))
[ "This substitutes i into the first %s and i-1 into the second %s\nre.match(\"abc %s xyz %s\"%(i,i-1), data)\n\nanother way to write it would be\nre.match(\"abc \"+str(i)+\" xyz \"+str(i-1), data)\n\n", "You can't make a single regex that includes math expressions which are evaluated at regex matching time. Howev...
[ 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001699467_python_regex.txt
Q: Python file manipulation Assume I have such folders rootfolder | / \ \ 01 02 03 .... | 13_itemname.xml So under my rootfolder, each directory represents a month like 01 02 03 and under these directories I have items with their create hour and item name such as 16_item1.xml, 24_item1.xml e...
Python file manipulation
Assume I have such folders rootfolder | / \ \ 01 02 03 .... | 13_itemname.xml So under my rootfolder, each directory represents a month like 01 02 03 and under these directories I have items with their create hour and item name such as 16_item1.xml, 24_item1.xml etc, as you may guess there are...
[ "Here are two methods doing what you ask (if I understood it properly). One with regex, one without. You choose which one you prefer ;)\nOne bit which may seem like magic is the \"setdefault\" line. For an explanation, see the docs. I leave it as \"an exercise to the reader\" to understand how it works ;)\nfrom os ...
[ 5, 0, 0 ]
[]
[]
[ "directory", "file", "pattern_matching", "python" ]
stackoverflow_0001699552_directory_file_pattern_matching_python.txt
Q: How to retrieve a directory of files from a remote server? If I have a directory on a remote web server that allows directory browsing, how would I go about to fetch all those files listed there from my other web server? I know I can use urllib2.urlopen to fetch individual files, but how would I get a list of all ...
How to retrieve a directory of files from a remote server?
If I have a directory on a remote web server that allows directory browsing, how would I go about to fetch all those files listed there from my other web server? I know I can use urllib2.urlopen to fetch individual files, but how would I get a list of all the files in that remote directory?
[ "If the webserver has directory browsing enabled, it will return a HTML document with links to all the files. You could parse the HTML document and extract all the links. This would give you the list of files.\nYou can use the HTMLParser class to extract the elements you're interested in. Something like this will w...
[ 5, 2 ]
[]
[]
[ "directory", "file", "python", "screen_scraping" ]
stackoverflow_0001699634_directory_file_python_screen_scraping.txt
Q: django, uni_form and python's __init__() function - how to pass arguments to a form? I'm having a bit of difficulty understanding how the python __init__( ) function works. What I'm trying to do is create a new form in django, and use the uni_form helper to display the form in a custom manner using fieldsets, howe...
django, uni_form and python's __init__() function - how to pass arguments to a form?
I'm having a bit of difficulty understanding how the python __init__( ) function works. What I'm trying to do is create a new form in django, and use the uni_form helper to display the form in a custom manner using fieldsets, however I'm passing an argument to the form that should slightly change the layout of the form...
[ "You have misunderstood the way classes work in Python. You're trying to run code inside a class but outside of any function, which is unlikely to work, especially if it depends on something that happens inside __init__. That code will be evaluated when the class is first imported, whereas __init__ happens when eac...
[ 4 ]
[]
[]
[ "django", "django_forms", "init", "python" ]
stackoverflow_0001700043_django_django_forms_init_python.txt
Q: Easy Python ASync. Precompiler? imagine you have an io heavy function like this: def getMd5Sum(path): with open(path) as f: return md5(f.read()).hexdigest() Do you think Python is flexible enough to allow code like this (notice the $): def someGuiCallback(filebutton): ... path = filebutton.get...
Easy Python ASync. Precompiler?
imagine you have an io heavy function like this: def getMd5Sum(path): with open(path) as f: return md5(f.read()).hexdigest() Do you think Python is flexible enough to allow code like this (notice the $): def someGuiCallback(filebutton): ... path = filebutton.getPath() md5sum = $getMd5Sum() ...
[ "You can use import hooks to achieve this goal...\n\nPEP 302 - New Import Hooks\nPEP 369 - Post Import Hooks\n\n... but I'd personally view it as a little bit nasty.\nIf you want to go down that route though, essentially what you'd be doing is this:\n\nYou add an import hook for an extension (eg \".thpy\")\nThat im...
[ 2, 1, 0 ]
[]
[]
[ "asynchronous", "compiler_construction", "python", "syntax" ]
stackoverflow_0001696152_asynchronous_compiler_construction_python_syntax.txt
Q: Python XPath Result displaying only [] Hey I have just started to use Python recently and I want to use it with a bit of xPath, the thing is when I print the result of the query I only get [] and I don't know why =S import libxml2, urllib doc = libxml2.parseDoc(urllib.urlopen("http://www.domain.com/").read())...
Python XPath Result displaying only []
Hey I have just started to use Python recently and I want to use it with a bit of xPath, the thing is when I print the result of the query I only get [] and I don't know why =S import libxml2, urllib doc = libxml2.parseDoc(urllib.urlopen("http://www.domain.com/").read()) result = doc.xpathEval("//th//td[(((count(...
[ "It could be that your XPath doesn't select any elements. For example, you are looking for td's inside th's, but those elements are peers, and shouldn't nest.\nWhy do you say (count(preceding-sibling::*) + 1) = 2 instead of count(preceding-sibling::*) = 1?\nIf you use a simpler XPath, do you get the results you ex...
[ 1, 0, 0 ]
[]
[]
[ "libxml2", "python", "xpath" ]
stackoverflow_0001694427_libxml2_python_xpath.txt
Q: Editing both sides of M2M in Admin Page First I'll lay out what I'm trying to achieve in case there's a different way to go about it! I want to be able to edit both sides of an M2M relationship (preferably on the admin page although if needs be it could be on a normal page) using any of the multi select interfaces...
Editing both sides of M2M in Admin Page
First I'll lay out what I'm trying to achieve in case there's a different way to go about it! I want to be able to edit both sides of an M2M relationship (preferably on the admin page although if needs be it could be on a normal page) using any of the multi select interfaces. The problem obviously comes with the revers...
[ "The reason why nothing happens automatically is that the \"projects\" field is not a part of the Tag model. Which means you have to do all the work yourself. Something like (in TagForm):\ndef __init__(self, *args, **kwargs):\n super(TagForm, self).__init__(*args, **kwargs)\n if 'instance' in kwargs:\n ...
[ 2 ]
[]
[]
[ "django", "django_admin", "django_forms", "m2m", "python" ]
stackoverflow_0001700202_django_django_admin_django_forms_m2m_python.txt
Q: How to unquote URL quoted UTF-8 strings in Python thestring = urllib.quote(thestring.encode('utf-8')) This will encode it. How to decode it? A: What about backtonormal = urllib.unquote(thestring) A: if you mean to decode a string from utf-8, you can first transform the string to unicode and then to any other ...
How to unquote URL quoted UTF-8 strings in Python
thestring = urllib.quote(thestring.encode('utf-8')) This will encode it. How to decode it?
[ "What about\nbacktonormal = urllib.unquote(thestring)\n\n", "if you mean to decode a string from utf-8, you can first transform the string to unicode and then to any other encoding you would like (or leave it in unicode), like this\nunicodethestring = unicode(thestring, 'utf-8')\nlatin1thestring = unicodethestrin...
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001700427_python.txt
Q: How to close not responsive Win32 Internet Explorer COM interface? actually this is not hang status, i mean..it slow response, so in that case, i would like to close IE and want to restart from start. so closing is no problem ,problem is ,how to set timeout ,for example if i set 15sec, if not webpage open less t...
How to close not responsive Win32 Internet Explorer COM interface?
actually this is not hang status, i mean..it slow response, so in that case, i would like to close IE and want to restart from start. so closing is no problem ,problem is ,how to set timeout ,for example if i set 15sec, if not webpage open less than 15 sec i want to close it and restart from start. is this possible t...
[ "To avoid blocking problem use IE COM object in a thread.\nHere is a simple but powerful example demonstrating how can you use thread and IE com object together. You can improve it for your purpose.\nThis example starts a thread a uses a queue to communicate with main thread, in main thread user can add urls to que...
[ 0 ]
[]
[]
[ "python", "win32com" ]
stackoverflow_0001700551_python_win32com.txt
Q: IPC between Python and C# I want to pass data between a Python and a C# application in Windows (I want the channel to be bi-directional) In fact I wanna pass a struct containing data about a network packet that I've captured with C# (SharpPcap) to the Python app and then send back a modified packet to the C# progr...
IPC between Python and C#
I want to pass data between a Python and a C# application in Windows (I want the channel to be bi-directional) In fact I wanna pass a struct containing data about a network packet that I've captured with C# (SharpPcap) to the Python app and then send back a modified packet to the C# program. What do you propose ? (I ra...
[ "Use JSON-RPC because the experience that you gain will have more practical use. JSON is widely used in web applications written in all of the dozen or so most popular languages.\n", "Why not use a simple socket communication, or if you wish you can start a simple http server, and/or do json-rpc over it.\n" ]
[ 2, 2 ]
[]
[]
[ "bidirectional", "c#", "ipc", "python", "rpc" ]
stackoverflow_0001700228_bidirectional_c#_ipc_python_rpc.txt
Q: Is it possible to redefine reverse in a Django project? I have some custom logic that needs to be executed every single time a URL is reversed, even for third-party apps. My project is a multitenant web app, and the tenant is identified based on the URL. There isn't a single valid URL that doesn't include a tenant...
Is it possible to redefine reverse in a Django project?
I have some custom logic that needs to be executed every single time a URL is reversed, even for third-party apps. My project is a multitenant web app, and the tenant is identified based on the URL. There isn't a single valid URL that doesn't include a tenant identifier. I already have a wrapper function around reverse...
[ "only way so that django reverse is replaced by ur_reverse is\ndjango.core.urlresolvers.reverse = ur_reverse\n\nor if you like decorator syntactic sugar\ndjango.core.urlresolvers.reverse = ur_reverse_decorator(django.core.urlresolvers.reverse )\n\nwhich i would not advice(and many will shout), unless you are not wi...
[ 5 ]
[]
[]
[ "decorator", "django", "monkeypatching", "python", "reverse" ]
stackoverflow_0001700577_decorator_django_monkeypatching_python_reverse.txt
Q: embed python in matlab mex file on os x I'm trying to embed Python into a MATLAB mex function on OS X. I've seen references that this can be done (eg here) but I can't find any OS X specific information. So far I can successfully build an embedded Python (so my linker flags must be OK) and I can also build example...
embed python in matlab mex file on os x
I'm trying to embed Python into a MATLAB mex function on OS X. I've seen references that this can be done (eg here) but I can't find any OS X specific information. So far I can successfully build an embedded Python (so my linker flags must be OK) and I can also build example mex files without any trouble and with the d...
[ "I think I found the answer - by including the mysterious apple linker flags:\n-undefined dynamic_lookup -bundle\n\nI was able to get it built and it seems to work OK. I'd be very interested if anyone has any references about these flags or library handling on OS X in general. Now I see them I remember being bitten...
[ 4 ]
[]
[]
[ "macos", "matlab", "mex", "python", "python_embedding" ]
stackoverflow_0001700628_macos_matlab_mex_python_python_embedding.txt
Q: How to install django-haystack using buildout I'm trying to convert a current Django project in development to use zc.buildout So far, I've got all the bits figured except for Haystack figured out. The Haystack source is available on GitHub, but I don't want to force users to install git. A suitable alternative ...
How to install django-haystack using buildout
I'm trying to convert a current Django project in development to use zc.buildout So far, I've got all the bits figured except for Haystack figured out. The Haystack source is available on GitHub, but I don't want to force users to install git. A suitable alternative seems to be to fetch a tarball from here That tarba...
[ "I figured this one out, without posting it to PyPI. (There is no actually tagged release version of django-haystack, so posting to to PyPI seems unclean. It's something the maintainer should and probably will handle better themselves.)\nThe relevant section is as follows:\n[haystack]\nrecipe = collective.recipe....
[ 4, 2, 1, 0 ]
[]
[]
[ "buildout", "python" ]
stackoverflow_0001134946_buildout_python.txt
Q: Environment on google Appengine does someone have an idea how to get the environment variables on Google-AppEngine ? I'm trying to write a simple Script that shall use the Client-IP (for Authentication) and a parameter (geturl or so) from the URL (for e.g. http://thingy.appspot.dom/index?geturl=www.google.at) I r...
Environment on google Appengine
does someone have an idea how to get the environment variables on Google-AppEngine ? I'm trying to write a simple Script that shall use the Client-IP (for Authentication) and a parameter (geturl or so) from the URL (for e.g. http://thingy.appspot.dom/index?geturl=www.google.at) I red that i should be able to get the C...
[ "To answer the actual question from the title of your post, assuming you're still wondering: to get environment variables, simple import os and the environment is available in os.environ.\n", "In short, assuming you're using webapp: you can get the client ip address via self.request.remote_addr and the parameter ...
[ 3, 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001700441_google_app_engine_python.txt
Q: Where is Python's "best ASCII for this Unicode" database? I have some text that uses Unicode punctuation, like left double quote, right single quote for apostrophe, and so on, and I need it in ASCII. Does Python have a database of these characters with obvious ASCII substitutes so I can do better than turning them...
Where is Python's "best ASCII for this Unicode" database?
I have some text that uses Unicode punctuation, like left double quote, right single quote for apostrophe, and so on, and I need it in ASCII. Does Python have a database of these characters with obvious ASCII substitutes so I can do better than turning them all into "?" ?
[ "Unidecode looks like a complete solution. It converts fancy quotes to ascii quotes, accented latin characters to unaccented and even attempts transliteration to deal with characters that don't have ASCII equivalents. That way your users don't have to see a bunch of ? when you had to pass their text through a legac...
[ 90, 26, 21 ]
[]
[]
[ "ascii", "python", "unicode" ]
stackoverflow_0000816285_ascii_python_unicode.txt
Q: Pragmatically adding give-aways/freebies to an online store Our business currently has an online store and recently we've been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the extra free items to their order after they checkout. O...
Pragmatically adding give-aways/freebies to an online store
Our business currently has an online store and recently we've been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the extra free items to their order after they checkout. Of course, it'd be nice to automate this entire process. I've been...
[ "Welcome to hell. Stay a while. ;) Ahem.\nDiscounts are a mess, so it's not surprising that you feel tainted by having to work with them. From a design point of view, the testing should be part of the Discount instance, i.e. there should be an appliesTo(cart) method and an apply(cart) method. The first tells you wh...
[ 2, 0 ]
[]
[]
[ "django", "e_commerce", "logic", "python" ]
stackoverflow_0001701956_django_e_commerce_logic_python.txt
Q: Python: complex list comprehensions where one var depends on another (x for x in t[1] for t in tests) I want to do something like: all = [ x for x in t[1] for t in tests ] tests looks like: [ ("foo",[a,b,c]), ("bar",[d,e,f]) ] So I want to have the result all = [a,b,c,d,e,f] My code does not work, Python says: ...
Python: complex list comprehensions where one var depends on another (x for x in t[1] for t in tests)
I want to do something like: all = [ x for x in t[1] for t in tests ] tests looks like: [ ("foo",[a,b,c]), ("bar",[d,e,f]) ] So I want to have the result all = [a,b,c,d,e,f] My code does not work, Python says: UnboundLocalError: local variable 't' referenced before assignment Is there any simple way to do that?
[ "It should work the other way around:\nall = [x for t in tests for x in t[1]]\n\n", "When in doubt, don't use list comprehensions.\nTry import this in your Python shell and read the second line:\nExplicit is better than implicit\n\nThis type of compounding of list comprehensions will puzzle a lot of Python progra...
[ 17, 5, 2, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0001700113_list_comprehension_python.txt
Q: PyGreSQL vs psycopg2 What is the difference between these two apis? Which one faster, reliable using Python DB API? Upd: I see two psql drivers for Django. The first one is psycopg2. What is the second one? pygresql? A: For what it's worth, django uses psycopg2. A: "PyGreSQL is written in Python only, easy to ...
PyGreSQL vs psycopg2
What is the difference between these two apis? Which one faster, reliable using Python DB API? Upd: I see two psql drivers for Django. The first one is psycopg2. What is the second one? pygresql?
[ "For what it's worth, django uses psycopg2.\n", "\"PyGreSQL is written in Python only, easy to deployed but slower.\"\nPyGreSQL contains a C-coded module, too. I haven't done speed tests, but they're not likely to be much different, as the real work will happen inside the database server.\n", "Licensing may be ...
[ 5, 4, 2, 2, 0 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0000413228_postgresql_python.txt
Q: What's going on with python 3k? Since I'm not strictly python developer please don't flame me just for the question. I'm wondering about Python 3k, that from my point of view, might be some kind of misconception. Or quite in-relevant step forward (I'm taking into account the 2.6 and 3k releases, which was almost o...
What's going on with python 3k?
Since I'm not strictly python developer please don't flame me just for the question. I'm wondering about Python 3k, that from my point of view, might be some kind of misconception. Or quite in-relevant step forward (I'm taking into account the 2.6 and 3k releases, which was almost one after another). Before the flame w...
[ "The OP appears to be surprised that a minor-release upgrade (which added some nifty features, basically broke zero existing code, and allowed trivial rebuilds of all existing third party libraries) happened overnight at their organization, while a major-release upgrade (requiring much more effort especially from t...
[ 9, 4, 3, 3, 2, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001700569_python_python_3.x.txt
Q: Is there a way to manually register a user with a py-transport server-side? I'm trying to write some scripts to migrate my users to ejabberd, but the only way that's been suggested for me to register a user with a transport is to have them use their client and discover the service. Certainly there is a way, rig...
Is there a way to manually register a user with a py-transport server-side?
I'm trying to write some scripts to migrate my users to ejabberd, but the only way that's been suggested for me to register a user with a transport is to have them use their client and discover the service. Certainly there is a way, right?
[ "\nGo through once for each transport\nand register yourself. Capture the\nXMPP packets. \nDump the transport\nregistration data from your current\nsystem into a csv file, xml file, or\nsomething else you can know the\nstructure.\nWrite a script\nusing jabberpy, xmpppy, pyxmpp, or\nwhatever, and emulate each of yo...
[ 0 ]
[]
[]
[ "ejabberd", "python", "xmpp" ]
stackoverflow_0000667510_ejabberd_python_xmpp.txt
Q: Something disturbing about PyDev content assist I created a simple class in Python as follows, from UserDict import UserDict class Person(UserDict): def __init__(self,personName=None): UserDict.__init__(self) self["name"]=personName In another module I try to instantiate an object of class Person and pr...
Something disturbing about PyDev content assist
I created a simple class in Python as follows, from UserDict import UserDict class Person(UserDict): def __init__(self,personName=None): UserDict.__init__(self) self["name"]=personName In another module I try to instantiate an object of class Person and print its doc and class attributes: import Person p = ...
[ "Not sure if anyone outside of the PyDev development team can really help you here, as this basically boils down to a feature question/request.\nI'd suggest creating an item on their Feature Request tracker or their bug tracker.\n", "EDIT:\nYour class Person is a so-called old-style class because it is subclassed...
[ 1, 1 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0001702255_eclipse_pydev_python.txt
Q: What does the brackets mean in python: table[r][pos+i]? This is the full code: def checkRow(table, r, pos, word): # done for you! for i in range(0, len(word)): if table[r][pos+i] != word[i]: return False return True I know the bracket mean the index value (in this case r some value of ...
What does the brackets mean in python: table[r][pos+i]?
This is the full code: def checkRow(table, r, pos, word): # done for you! for i in range(0, len(word)): if table[r][pos+i] != word[i]: return False return True I know the bracket mean the index value (in this case r some value of the index table) but what does a bracket next to another brac...
[ "It means that the value of table[r] is another array (an array within an array), which you are indexing into with [pos+i]. So it's the equivalent of:\nfoo = table[r]\nif foo[pos+i] != word[i]:\n\n", "table[r][pos+i]\nTo get the pos+i character of the string table[r]\n", "If r was length 2 and the pos was lengt...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001699342_python.txt
Q: What is suggested seed value to use with random.seed()? Simple enough question: I'm using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this default to the current time, but this is not ideal. It seems ...
What is suggested seed value to use with random.seed()?
Simple enough question: I'm using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this default to the current time, but this is not ideal. It seems like a string literal constant (similar to a password) would ...
[ "According to the documentation for random.seed:\n\nIf x is omitted or None, current system time is used; current system time is also used to initialize the generator when the module is first imported. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.u...
[ 14, 5, 3, 1, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0001703012_python_random.txt
Q: Basic Python loop question - problem reading a list from a text file I'm trying to read a list of items from a text file and format with square brackets and separators like this: ['item1','item2', .... 'last_item'] but I'm having trouble with the beginning and end item for which I always get: ...,'last_item','], ...
Basic Python loop question - problem reading a list from a text file
I'm trying to read a list of items from a text file and format with square brackets and separators like this: ['item1','item2', .... 'last_item'] but I'm having trouble with the beginning and end item for which I always get: ...,'last_item','], so I do not want the last ,' to be there. In python I've write: out_list...
[ "Read in all your lines and use the string.join() method to join them together.\nlines = open(file_in).readlines()\n\nout_list = \"['\" + \"','\".join(lines) + \"']\"\n\nAdditionally, join() can take any sequence, so reading the lines isn't necessary. The above code can be simplified as:\nout_list = \"['\" + \"','...
[ 4, 1, 0, 0, 0, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0001703471_loops_python.txt
Q: IPython in unbuffered mode Is there a way to run IPython in unbuffered mode? The same way as python -u gives unbuffered IO for the standard python shell A: From Python's man page: -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and...
IPython in unbuffered mode
Is there a way to run IPython in unbuffered mode? The same way as python -u gives unbuffered IO for the standard python shell
[ "From Python's man page:\n -u Force stdin, stdout and stderr to be totally unbuffered. On systems\n where it matters, also put stdin, stdout and stderr in binary mode.\n Note that there is internal buffering in xreadlines(), readlines()\n and file-object iterators (\"for line in sy...
[ 2, 0 ]
[]
[]
[ "ipython", "python" ]
stackoverflow_0001578592_ipython_python.txt
Q: Python threading test not working EDIT I solved the issue by forking the process instead of using threads. From the comments and links in the comments, I don't think threading is the right move here. Thanks everyone for your assistance. FINISHED EDIT I haven't done much with threading before. I've created a few si...
Python threading test not working
EDIT I solved the issue by forking the process instead of using threads. From the comments and links in the comments, I don't think threading is the right move here. Thanks everyone for your assistance. FINISHED EDIT I haven't done much with threading before. I've created a few simple example "Hello World" scripts but ...
[ "The MySQL DB driver isn't thread safe. You're using the same cursor concurrently from all threads.\nTry creating a new connection in each thread, or create a pool of connections that the threads can use (e.g. keep them in a Queue, each thread gets a connection, and puts it pack when it's done).\n", "You should b...
[ 8, 0, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001704085_multithreading_python.txt
Q: Python (and Django) best import practices Out of the various ways to import code, are there some ways that are preferable to use, compared to others? This link http://effbot.org/zone/import-confusion.htm in short states that from foo.bar import MyClass is not the preferred way to import MyClass under normal circu...
Python (and Django) best import practices
Out of the various ways to import code, are there some ways that are preferable to use, compared to others? This link http://effbot.org/zone/import-confusion.htm in short states that from foo.bar import MyClass is not the preferred way to import MyClass under normal circumstances or unless you know what you are doing....
[ "First, and primary, rule of imports: never ever use from foo import *.\nThe article is discussing the issue of cyclical imports, which still exists today in poorly-structured code. I dislike cyclical imports; their presence is a strong sign that some module is doing too much, and needs to be split up. If for whate...
[ 13, 6, 2 ]
[]
[]
[ "django", "python", "python_import" ]
stackoverflow_0001704058_django_python_python_import.txt
Q: Speeding Up the First Page Load in django When I update the code on my website I (naturally) restart my apache instance so that the changes will take effect. Unfortunately the first page served by each apache instance is quite slow while it loads everything into RAM for the first time (5-7 sec for this particular ...
Speeding Up the First Page Load in django
When I update the code on my website I (naturally) restart my apache instance so that the changes will take effect. Unfortunately the first page served by each apache instance is quite slow while it loads everything into RAM for the first time (5-7 sec for this particular site). Subsequent requests only take 0.5 - 1.5 ...
[ "The default for Apache/mod_wsgi is to only load application code on first request to a process which requires that applications. So, first step is to configure mod_wsgi to preload your code when the process starts and not only the first request. This can be done in mod_wsgi 2.X using the WSGIImportScript directive...
[ 32, 3 ]
[]
[]
[ "django", "mod_wsgi", "pageload", "performance", "python" ]
stackoverflow_0001702562_django_mod_wsgi_pageload_performance_python.txt
Q: Why is Maya 2009 TreeView control giving a syntax error on drag? I'm using the TreeView control in Maya 2009 but I'm getting a syntax error on drag and drop. My code is as follows (simplified for brevity): class View(event.Dispatcher): def __init__(self): self.window = cmds.window() tree_view =...
Why is Maya 2009 TreeView control giving a syntax error on drag?
I'm using the TreeView control in Maya 2009 but I'm getting a syntax error on drag and drop. My code is as follows (simplified for brevity): class View(event.Dispatcher): def __init__(self): self.window = cmds.window() tree_view = cmds.treeView( numberOfButtons=1, allowRepare...
[ "See http://download.autodesk.com/us/maya/2009help/CommandsPython/treeView.html: dragAndDropCommand is a STRING -- you're passing a bound method, Maya's using its repr. I'm not sure, but I suspect that string should name a top-level (module-level) function, not a bound method.\n", "As of Maya 2010 the treeView wi...
[ 1, 0 ]
[]
[]
[ "maya", "python", "syntax_error", "treeview" ]
stackoverflow_0000820697_maya_python_syntax_error_treeview.txt
Q: python: xml.etree.ElementTree, removing "namespaces" I like the way ElementTree parses xml, in particular the Xpath feature. I've an output in xml from an application with nested tags. I'd like to access this tags by name without specifying the namespace, is it possible? For example: root.findall("/molpro/job") i...
python: xml.etree.ElementTree, removing "namespaces"
I like the way ElementTree parses xml, in particular the Xpath feature. I've an output in xml from an application with nested tags. I'd like to access this tags by name without specifying the namespace, is it possible? For example: root.findall("/molpro/job") instead of: root.findall("{http://www.molpro.net/schema/mol...
[ "At least with lxml2, it's possible to reduce this overhead somewhat:\nroot.findall(\"/n:molpro/n:job\",\n namespaces=dict(n=\"http://www.molpro.net/schema/molpro2006\"))\n\n", "You could write your own function to wrap the nasty looking bits for example:\ndef my_xpath(doc, ns, xp);\n num = xp.coun...
[ 8, 5 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001703882_python_xml.txt
Q: Abandoned Apache process, how long will it go on? So lets say there's a server process that takes way too long. The client complains that it "times out." Correct me if I'm wrong, but this particular timeout could have to do with apache's timeout setting, but not necessarily. I believe this to be the case because w...
Abandoned Apache process, how long will it go on?
So lets say there's a server process that takes way too long. The client complains that it "times out." Correct me if I'm wrong, but this particular timeout could have to do with apache's timeout setting, but not necessarily. I believe this to be the case because when testing the page in question we couldn't get it to ...
[ "Correct. In a C apache module you can add a check like:\n/* r is the 'request_rec' object from apache */\nif (r->connection->aborted) {\n /* stop processing and return */\n}\n\nto verify that the client is still connected. Probably the python interface has something similar.\nAs for the loopback connection, it ...
[ 1 ]
[]
[]
[ "apache", "netstat", "python", "timeout" ]
stackoverflow_0001704710_apache_netstat_python_timeout.txt
Q: Find images with similar color palette with Python Suppose there are 10,000 JPEG, PNG images in a gallery, how to find all images with similar color palettes to a selected image sorted by descending similarity? A: Build a color histogram for each image. Then when you want to match an image to the collection, sim...
Find images with similar color palette with Python
Suppose there are 10,000 JPEG, PNG images in a gallery, how to find all images with similar color palettes to a selected image sorted by descending similarity?
[ "Build a color histogram for each image. Then when you want to match an image to the collection, simply order the list by how close their histogram is to your selected image's histogram.\nThe number of buckets will depend on how accurate you want to be. The type of data combined to make a bucket will define how you...
[ 11 ]
[]
[]
[ "colors", "image", "python" ]
stackoverflow_0001704793_colors_image_python.txt
Q: List of values to a sound file Im trying to engineer in python a way of transforming a list of integer values between 0-255 into representative equivalent tones from 1500-2200Hz. Timing information (at 1200Hz) is given by the (-1),(-2) and (-3) values. I have created a function that generates a .wav file and then ...
List of values to a sound file
Im trying to engineer in python a way of transforming a list of integer values between 0-255 into representative equivalent tones from 1500-2200Hz. Timing information (at 1200Hz) is given by the (-1),(-2) and (-3) values. I have created a function that generates a .wav file and then call this function with the paramete...
[ "Looks like you're trying to reinvent the wheel, be careful...\nIf you want to generate music from arrays then you can have a look at pyaudiere, a simple wrapper upon the audiere library. See the docs for how to open an array but it looks should like this : \nimport audiere\nd = audiere.open_device()\ns = d.open_ar...
[ 2, 0, 0 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0001118266_audio_python.txt
Q: How can I reduce memory usage of a Twisted server? I wrote an audio broadcasting server with Python/Twisted. It works fine, but the usage of memory grows too fast! I think that's because some user's network might not be good enough to download the audio in time. My audio server broadcast audio data to different l...
How can I reduce memory usage of a Twisted server?
I wrote an audio broadcasting server with Python/Twisted. It works fine, but the usage of memory grows too fast! I think that's because some user's network might not be good enough to download the audio in time. My audio server broadcast audio data to different listener's client, if some of them can't download the aud...
[ "You didn't say, but I'm going to assume that you're using TCP. It would be hard to write a UDP-based system which had ever increasing memory because of clients who can't receive data as fast as you're trying to send it.\nTCP has built-in flow control capabilities. If a receiver cannot read data as fast as you'd ...
[ 2 ]
[ "Make sure you're using Python's garbage collector and then go through and delete variables you aren't using.\n" ]
[ -5 ]
[ "memory_management", "python", "twisted" ]
stackoverflow_0001697009_memory_management_python_twisted.txt
Q: Can I use Django 1.1 with django-search-lucene for full-text searching, and if so, what resources/links/docs can I reference to get it up and running? A little background: I want to use Django Search with Lucene I have Django 1.1 w/ Python 2.5 installed MySQL 5.1 is being used My local machine is running Windows ...
Can I use Django 1.1 with django-search-lucene for full-text searching, and if so, what resources/links/docs can I reference to get it up and running?
A little background: I want to use Django Search with Lucene I have Django 1.1 w/ Python 2.5 installed MySQL 5.1 is being used My local machine is running Windows Vista x64, but we will deploy to Red Hat Linux Yes, I wish that right about now I was running Linux.
[ "I would recommend Apache SOLR, which is built on top of Lucene. The primary advantage is that it exposes an easy to use API, and can return a native Python object. Here is an example of how to call it from Python:\nparams = urllib.urlencode({ \n \"rows\": \"100\", \n \"fl\": \"id,name,score,addr...
[ 3 ]
[]
[]
[ "django", "django_search_lucene", "python" ]
stackoverflow_0001704278_django_django_search_lucene_python.txt
Q: Organize a python library as plugins I would like to create a library, say foolib, but to keep different subpackages separated, so to have barmodule, bazmodule, all under the same foolib main package. In other words, I want the client code to be able to do import foolib.barmodule import foolib.bazmodule but to di...
Organize a python library as plugins
I would like to create a library, say foolib, but to keep different subpackages separated, so to have barmodule, bazmodule, all under the same foolib main package. In other words, I want the client code to be able to do import foolib.barmodule import foolib.bazmodule but to distribute barmodule and bazmodule as two in...
[ "You may be looking for namespace packages. See also PEP 382.\n", "Yes, simply create a foolib directory, add an __init__.py to it, and make each sub-module a .py file.\n/foolib\n barmodule.py\n bazmodule.py\n\nthen you can import them like so:\nfrom foolib import barmodule\nbarmodule.some_function()\n\n" ...
[ 3, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0001705665_module_python.txt
Q: Python Form Processing alternatives django.forms is very nice, and does almost exactly what I want to do on my current project, but unfortunately, Google App Engine makes most of the rest of Django unusable, and so packing it along with the app seems kind of silly. I've also discovered FormAlchemy, which is an S...
Python Form Processing alternatives
django.forms is very nice, and does almost exactly what I want to do on my current project, but unfortunately, Google App Engine makes most of the rest of Django unusable, and so packing it along with the app seems kind of silly. I've also discovered FormAlchemy, which is an SQLAlchemy analog to Django forms, and I i...
[ "I've grown to love WTForms, it's simple, straightforward, and very flexible. It's part of my django-free web stack. \nIt's completely standalone, and carries over the good parts of django's form libraries, while imho having some things much better.\n", "I'm not sure what you mean by \"making most of the rest o...
[ 13, 3, 2, 1 ]
[]
[]
[ "forms", "google_app_engine", "python" ]
stackoverflow_0001705217_forms_google_app_engine_python.txt