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: Python web service I'm doing server/client application similar to Ubuntu Landscape (http://www.canonical.com/enterprise-services/ubuntu-advantage/landscape) for my school project. The client part of application will send different informations (disk usage, packages etc.) to server. I know how to get informations a...
Python web service
I'm doing server/client application similar to Ubuntu Landscape (http://www.canonical.com/enterprise-services/ubuntu-advantage/landscape) for my school project. The client part of application will send different informations (disk usage, packages etc.) to server. I know how to get informations and hot I'll handle them ...
[ "Look into XMLRPC or JSON-RPC which is likely supported in some why by all language through modules or packages.\nSOAP is a complete bloat and widely considered as a failed hype.\n", "I recommend using flask or smisk. Both frameworks are REST based, powerful, lightweight and pythonic. Flask is probably more matur...
[ 2, 0 ]
[]
[]
[ "python", "twisted", "web_services" ]
stackoverflow_0006642999_python_twisted_web_services.txt
Q: Python : How to fill an array line by line? I have an issue with numpy that I can't solve. I have 3D arrays (x,y,z) filled with 0 and 1. For instance, one slice in the z axis : array([[1, 0, 1, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 1, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0], ...
Python : How to fill an array line by line?
I have an issue with numpy that I can't solve. I have 3D arrays (x,y,z) filled with 0 and 1. For instance, one slice in the z axis : array([[1, 0, 1, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 1, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0, 1], [1, 0, 0, 0, 0...
[ "Accessing NumPy array elements one by one is not very efficient. You may do better with just plain Python lists. They also have an index method which can search for the first entry of the value in the list.\nfrom numpy import *\n\na = array([[1, 0, 1, 0, 1, 1, 0, 0],\n [0, 0, 1, 1, 0, 1, 1, 0],\n [1, 0...
[ 4, 4, 2, 0 ]
[]
[]
[ "fill", "numpy", "python" ]
stackoverflow_0006626194_fill_numpy_python.txt
Q: Embedding Python Code in a Word Document? I am writing a manual using Word / LibreOffice's Writer. As part of the manual, I'd like to include python code snippets. Naturally, I want these to be included in a nice way. How can I paste python code into Word / LibreOffice's Writer while keeping its nice format? A: ...
Embedding Python Code in a Word Document?
I am writing a manual using Word / LibreOffice's Writer. As part of the manual, I'd like to include python code snippets. Naturally, I want these to be included in a nice way. How can I paste python code into Word / LibreOffice's Writer while keeping its nice format?
[ "Libre Office should be able to import HTML code. You can use any Highlighter that can output HTML highlighted code. You may try an online highlighter like http://www.tohtml.com/python/ for example.\nEdit:\nSomehow Libre Office is missing HTML code in the Paste Special menu, but here is some trick to get html into ...
[ 3 ]
[]
[]
[ "libreoffice", "ms_word", "python" ]
stackoverflow_0006643046_libreoffice_ms_word_python.txt
Q: I'm attempting to set ranges in a text file that I can associate search results with a particular chapter I know that there are more feasible approaches to solving this problem (db: mysql, oracle, etc...), and I have a mysql db file (KJV Bible), that I can search via PHP code. However, I want to open the Bible.txt...
I'm attempting to set ranges in a text file that I can associate search results with a particular chapter
I know that there are more feasible approaches to solving this problem (db: mysql, oracle, etc...), and I have a mysql db file (KJV Bible), that I can search via PHP code. However, I want to open the Bible.txt file in Python and search for certain strings and return the line and line number. Additionally, (the challeng...
[ "This is a very solid start. I've got some suggestions, though. \nFirst, your use of readlines is a bit inefficient. readlines creates a new list of lines from the file -- it stores the whole file in memory. But you don't have to do that; if all you want to do is iterate over the lines in a file, you can just say f...
[ 2, 1, 1, 1, 1 ]
[]
[]
[ "python", "range" ]
stackoverflow_0006642563_python_range.txt
Q: How can I create a list containing another list's elements in the middle in python? I have three lists. Two are returned from functions. The other list, list_c, is being created in the program out of some hardcoded options and some variables, and the contents of these lists. This list is a list of arguments to be ...
How can I create a list containing another list's elements in the middle in python?
I have three lists. Two are returned from functions. The other list, list_c, is being created in the program out of some hardcoded options and some variables, and the contents of these lists. This list is a list of arguments to be passed to another program, so the order is important. I need each item in list_a and list...
[ "How about this? You can append/concatenate lists with +\n['some', 'stuff'] + some_function() + ['more'] + some_other_function() + [variables]\n", "The most obvious way to do this is to use list concatenation:\nlist_c = list_c + list_a + ['more'] + list_b + ['var1', 'var2']\n\nFor what it's worth, itertools.chain...
[ 4, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006643101_list_python.txt
Q: Error when installing pycrypto I'm trying to install Fabric on my PC (with Windows + setuptools). It was giving me an error, since I have older version of pycrypto. When I was trying to install latest version I stumble upon "Unable to find vcvarsall.bat" error. I googled something about MinGW, so I installed that...
Error when installing pycrypto
I'm trying to install Fabric on my PC (with Windows + setuptools). It was giving me an error, since I have older version of pycrypto. When I was trying to install latest version I stumble upon "Unable to find vcvarsall.bat" error. I googled something about MinGW, so I installed that too. I've added it to my Windows PA...
[ "Well, it's so complicated because C (C++? Can't remember what they used at the moment, but I am pretty sure they used C) is much, much better at math than Python, so the math pieces of PyCrypto are all written in C. It does have a _slowmath module if the compiled versions aren't available, but it's name is telling...
[ 3 ]
[]
[]
[ "fabric", "mingw", "pycrypto", "python" ]
stackoverflow_0006643531_fabric_mingw_pycrypto_python.txt
Q: Encrypting 30 bit Number into 6 Character Alphanumeric String I'm looking for an approach to encrypt/obfuscate a 30 bit number. The results will be grouped into sets of 3 and visible to users as a 6 character alphanumeric encoded with a base32 alphabet, but the user should not be able to pick up a pattern in the...
Encrypting 30 bit Number into 6 Character Alphanumeric String
I'm looking for an approach to encrypt/obfuscate a 30 bit number. The results will be grouped into sets of 3 and visible to users as a 6 character alphanumeric encoded with a base32 alphabet, but the user should not be able to pick up a pattern in the alphnumeric strings. For example, the users could see 3 strings: ...
[ "Format preserving encryption might be helpful here.\nFor example, the cycle-walking method described in the paper \"Ciphers with Arbitrary Finite Domains\" by Black and Rogaway seems like a potential solution.\nE.g. use a 32-bit cipher (Skip32 by Greg Rose is an example).\nEncrypt your 30-bit input with the cipher...
[ 7, 1, 1 ]
[]
[]
[ "bit_manipulation", "cryptography", "encryption", "python", "security" ]
stackoverflow_0006640341_bit_manipulation_cryptography_encryption_python_security.txt
Q: How to write a html gui (django) for a python server module What's the way to go to build a HTML gui for eg a multiplexed tcp server in python? I am familiar with building websites with Django, but the thing i don't understand is, how is the tcp server part communicating with the Django related views? How could i ...
How to write a html gui (django) for a python server module
What's the way to go to build a HTML gui for eg a multiplexed tcp server in python? I am familiar with building websites with Django, but the thing i don't understand is, how is the tcp server part communicating with the Django related views? How could i implement the data sharing (do i see the wood for the trees)? The...
[ "Django is just Python, so anything you've written in Python can be imported and referenced in the 'views' that you write for Django to serve back as HTTP responses.\nIn answer to another part of your question, the way a HTTP server handling TCP connections communicates with the python framework is most commonly th...
[ 2, 2 ]
[]
[]
[ "django", "html", "python", "user_interface" ]
stackoverflow_0006642762_django_html_python_user_interface.txt
Q: Help with python regexp finding a string that does not end with a symbol I am trying to parse webpages to find links to special pages for instance if we had the below as input flowers that never end.')" onmouseout="return nd();" href="/flowers/images/download/01d6ac.html"><img src="http://static.rarbg.com/over/01...
Help with python regexp finding a string that does not end with a symbol
I am trying to parse webpages to find links to special pages for instance if we had the below as input flowers that never end.')" onmouseout="return nd();" href="/flowers/images/download/01d6ac.html"><img src="http://static.rarbg.com/over/01d6acc21110e68af7476bce50dec3c234343032.jpg" border="0 and on an other page ha...
[ "If for some reason you have to use regex, better use this expression: \n'href=\"/flowers/([^\"]+)\"[^>]'\n\nHowever your suffering will continue until you use a parser as you can read in the comments. \n" ]
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006643695_python_regex.txt
Q: Distributing Real-Time Market Data Using ZeroMQ / NFS? Suppose that you have a machine that gets fed with real-time stock prices from the exchange. These prices need to be transferred to 50 other machines in your network in the fastest possible way, so that each of them can run its own processing on the data. What...
Distributing Real-Time Market Data Using ZeroMQ / NFS?
Suppose that you have a machine that gets fed with real-time stock prices from the exchange. These prices need to be transferred to 50 other machines in your network in the fastest possible way, so that each of them can run its own processing on the data. What would be the best / fastest way to send the data over to th...
[ "I'm pretty sure sending with ZeroMQ will be substantially quicker than saving and loading files.\nThere are other ways to send information over the network, such as raw sockets (lower level), AMQP implementations like RabbitMQ (more structured/complicated), HTTP requests/replies, and so on. ZeroMQ is a pretty good...
[ 1, 1, 0 ]
[]
[]
[ "linux", "python", "zeromq" ]
stackoverflow_0006549488_linux_python_zeromq.txt
Q: Python HTML to PDF with floating divs Is there a way to convert XHTML/HTML with CSS to PDF with floating divs? I have tried pisa/xhtml2pdf in python and dompdf in PHP both are not able to do so. Is there any way? A: See html-tables-to-pdf-in-php-neither-dompdf-nor-html2ps-pdf-are-working. A possible path is to u...
Python HTML to PDF with floating divs
Is there a way to convert XHTML/HTML with CSS to PDF with floating divs? I have tried pisa/xhtml2pdf in python and dompdf in PHP both are not able to do so. Is there any way?
[ "See html-tables-to-pdf-in-php-neither-dompdf-nor-html2ps-pdf-are-working.\nA possible path is to use some Layout (Rendering) Engine, such as Webkit or Gecko.\nThe rendered HTML page can then be saved as PDF. An example of a tool that uses this method is the wkhtmltopdf project.\n(I know, this is not related to Pyt...
[ 4, 0 ]
[]
[]
[ "pdf_generation", "python" ]
stackoverflow_0002688325_pdf_generation_python.txt
Q: check if url exist at fanfiction.net I am trying to find out the last chapter number of a story at www.fanfiction.net just for fun. For this I thought that since it has a fixed pattern of url I will just increment the chapter number till the time that it gives me a url which does not exist. To find whether the url...
check if url exist at fanfiction.net
I am trying to find out the last chapter number of a story at www.fanfiction.net just for fun. For this I thought that since it has a fixed pattern of url I will just increment the chapter number till the time that it gives me a url which does not exist. To find whether the url existed I tried out the script at this st...
[ "Perhaps use cURL, read 100 bytes and just look for \"FanFiction.Net Message Type 1\" at the start of the data? \n", "That website isn't giving a 404 error, which renders all of those scripts useless. You will need to download the whole webpage and check whether it looks like a 404 page.\nI think just running:\ni...
[ 0, 0, 0 ]
[]
[]
[ "httplib", "python" ]
stackoverflow_0006644411_httplib_python.txt
Q: How to add contextual information to log lines from multiprocessing workers? I have a pool of worker processes (using multiprocessing.Pool) and want to log from these to a single log file. I am aware of logging servers, syslog, etc. but they all seem to require some changes to how my app is installed, monitored, l...
How to add contextual information to log lines from multiprocessing workers?
I have a pool of worker processes (using multiprocessing.Pool) and want to log from these to a single log file. I am aware of logging servers, syslog, etc. but they all seem to require some changes to how my app is installed, monitored, logs processed etc. which I would like to avoid. I am using CPython 2.6 on Linux. F...
[ "Filters can be applied to handlers as well as loggers - so you can just apply the filter to your QueueHandler. If this handler is attached to the root logger in your processes, then any logging by third party modules should also be handled by the handler, so you should get the context in those logged events, too.\...
[ 0 ]
[]
[]
[ "logging", "multiprocessing", "python" ]
stackoverflow_0006592561_logging_multiprocessing_python.txt
Q: MapReduce pairwise comparison of all lines in multiple files I'm getting started with using python's mrjob to convert some of my long running python programs into MapReduce hadoop jobs. I've gotten the simple word count examples to work and I conceptually understand the 'text-classification' example. However, I'm ...
MapReduce pairwise comparison of all lines in multiple files
I'm getting started with using python's mrjob to convert some of my long running python programs into MapReduce hadoop jobs. I've gotten the simple word count examples to work and I conceptually understand the 'text-classification' example. However, I'm having a little trouble figuring out the steps I need to do to get...
[ "Well, since nobody has come up with an answer I'll post my current work-around in-case anybody else out there needs it. I'm not sure how 'canocical' or efficient this is but its worked so far.\nI put the filename as the first item of each line of the file followed by a \\t followed by the rest of the data. For thi...
[ 1 ]
[]
[]
[ "mapreduce", "mrjob", "python" ]
stackoverflow_0006643521_mapreduce_mrjob_python.txt
Q: read from a text file. - Python My question: For example, my text file is call 'feed.txt'. and for inside, it likes that: 2 # two means 'there are two matrix in this file' 3 # three means 'the below one is a 3*3 matrix' 1 8 6 3 5 7 4 9 2 4 # four means 'the below one is a 4*4 matrix' 16 3 2 13 5 10 11 8 9 ...
read from a text file. - Python
My question: For example, my text file is call 'feed.txt'. and for inside, it likes that: 2 # two means 'there are two matrix in this file' 3 # three means 'the below one is a 3*3 matrix' 1 8 6 3 5 7 4 9 2 4 # four means 'the below one is a 4*4 matrix' 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 There are two matr...
[ "Okay, gonna take you through this step by step. If 'file' is your file name, try:\nmatrices = [] # The list you'll be keeping your matrices in\nwith open('file') as f:\n num_matrices = int(f.readline())\n for mat_index in range(num_matrices):\n temp_matrix = [] # The list yo...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006644529_python.txt
Q: In Python, Getting More Info About An IP Address I know about gethostbyaddr in Python and that is somewhat useful for me. I would like to get even more info about an ip address like one can find at various websites such as who hosts that ip address, the country of origin, ..., etc. I need to accomplish this prog...
In Python, Getting More Info About An IP Address
I know about gethostbyaddr in Python and that is somewhat useful for me. I would like to get even more info about an ip address like one can find at various websites such as who hosts that ip address, the country of origin, ..., etc. I need to accomplish this programmatically. Are there any built in commands for Pyth...
[ "You can use pywhois for retrieving whois information, i.e. name and contact details of the hosting organization/person. Note that whois information quality varies; usually, the domain name (found with gethostbyaddr) will get you way better results than the IP address.\nIf you need only geographic information, use ...
[ 5, 0 ]
[]
[]
[ "gethostbyaddr", "python", "pywhois", "reverse_dns" ]
stackoverflow_0006611298_gethostbyaddr_python_pywhois_reverse_dns.txt
Q: PyQt beforeInsert() signal I'm trying to use the beforeInsert() signal emitted by the QSqlRelationalTableModel in PyQt. However, even after I make edits to the model, the slot connected to the signal does't run. When exactly is the beforeInsert() signal emitted? Could someone show a working example of the use of b...
PyQt beforeInsert() signal
I'm trying to use the beforeInsert() signal emitted by the QSqlRelationalTableModel in PyQt. However, even after I make edits to the model, the slot connected to the signal does't run. When exactly is the beforeInsert() signal emitted? Could someone show a working example of the use of beforeInsert(), or beforeUpdate()...
[ "The documentation says \"This signal is emitted by insertRowIntoTable() before a new row is inserted into the currently active database table\". So it sounds like the signal is only emitted when insertRowIntoTable() is called, and not for any other type of model edit.\n" ]
[ 2 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0006634523_pyqt_python.txt
Q: how can i receive a signal when a Popen terminates? in python, i have a spawned shell process which i might stop manually , or it might terminate itself when it feels like it. can i receive a notification that it has completed, without polling it all the time? class Foo(object): def __init__(self): self....
how can i receive a signal when a Popen terminates?
in python, i have a spawned shell process which i might stop manually , or it might terminate itself when it feels like it. can i receive a notification that it has completed, without polling it all the time? class Foo(object): def __init__(self): self.running = False def start(self): import os fro...
[ "You should be able to install a handler for SIGCHLD. Read the documentation carefully, though; by registering interest in that signal, you are committing to handling child processes in the signal handler; anything that waits on the subprocess itself will block until all running children have been processes by the...
[ 3 ]
[]
[]
[ "popen", "python", "shell", "signals", "terminate" ]
stackoverflow_0006644928_popen_python_shell_signals_terminate.txt
Q: Given a bunch of ranges of numbers, get all the numbers within those ranges? In Python, you can get the numbers in a range by calling range(x,y). But given two ranges, say 5-15, and 10-20 how can you get all the numbers 5-20 without duplicates? The ranges may also be disjoint. I could concat all the results and th...
Given a bunch of ranges of numbers, get all the numbers within those ranges?
In Python, you can get the numbers in a range by calling range(x,y). But given two ranges, say 5-15, and 10-20 how can you get all the numbers 5-20 without duplicates? The ranges may also be disjoint. I could concat all the results and then uniquify the list, but is that the fastest solution?
[ ">>> a = range(5, 15)\n>>> b = range(10, 20)\n>>> print sorted(set(a + b))\n[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n\nOr if you want a more general expansion of the lists to their elements for inclusion in the set:\n>>> list_of_lists = [a, b]\n>>> print sorted(set(elem for l in list_of_lists for el...
[ 9, 2, 1, 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0006643747_algorithm_python.txt
Q: Use four CPUs to run a python script I'm running a python script that does some operations over a large graph, so I would like to take advantage of the 4 cores of my PC. Watching the task manager I can see that all CPUs are running but the total CPU usage is up to 50%. As I set this PC exclusively to run this scri...
Use four CPUs to run a python script
I'm running a python script that does some operations over a large graph, so I would like to take advantage of the 4 cores of my PC. Watching the task manager I can see that all CPUs are running but the total CPU usage is up to 50%. As I set this PC exclusively to run this script I would like to use its CPUs as much a...
[ "C Python has a rather generous lock that precludes most threaded operations from truly happening in parallel. You might want to look at the Multiprocessing module.\nOtherwise, you could use a Python implementation that allows for concurrent threading:\n\nIronPython\nJython\n\n", "Have a read through this module...
[ 8, 1 ]
[]
[]
[ "multicore", "python" ]
stackoverflow_0006645100_multicore_python.txt
Q: How to I lookup to fields in another table with the same parent (User) with Django templates? I'm pretty new to Django and Python. I've been doing a lot of reading and read through most of the tutorials and documentation. I've created a simple application and I'm stuck at a point where in a template, I want to be ...
How to I lookup to fields in another table with the same parent (User) with Django templates?
I'm pretty new to Django and Python. I've been doing a lot of reading and read through most of the tutorials and documentation. I've created a simple application and I'm stuck at a point where in a template, I want to be able to get fields from another model with the same parent. In this case I have a basic forum, with...
[ "Because ZProfile has a ForeignKey to User, you access it from User using .zprofile_set.0 (even though you specify unique=True). You'd be better off using a OneToOneField -- then you could use poll.author.zprofile.extra_info.\nDjango's auth app has support for user profiles which store additional information about ...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006644987_django_python.txt
Q: Receiving Arguments via Pointers in Python I have a class whose function defined like this. My intention is to send multiple arguments to it . For testing, I called it as :class_name("argument1","argument2"), and it says: __init__accepts atmost 1 arguments , 3 given def __init__(self, **options): for name in o...
Receiving Arguments via Pointers in Python
I have a class whose function defined like this. My intention is to send multiple arguments to it . For testing, I called it as :class_name("argument1","argument2"), and it says: __init__accepts atmost 1 arguments , 3 given def __init__(self, **options): for name in options: self.__dict__[name] = options[na...
[ "You want to use one asterisk instead of two. Double asterisks are for named arguments. There is a nice explanation in the python documentation if you are interested in reading further.\ndef __init__(self, *options):\n for name in options:\n self.__dict__[name] = name\n\nHowever, from your code I think ...
[ 5, 4, 3 ]
[]
[]
[ "arguments", "python" ]
stackoverflow_0006645311_arguments_python.txt
Q: More than one for-loop in a python while-loop I'm a python/coding newbie and I'm trying to put a two for loops into a while loop? Can I do this? How can I print out the dictionary mydict to make sure I am doing this correctly? I'm stuck. 40 minutes later. Not stuck anymore. Thanks everyone! def runloop(): whi...
More than one for-loop in a python while-loop
I'm a python/coding newbie and I'm trying to put a two for loops into a while loop? Can I do this? How can I print out the dictionary mydict to make sure I am doing this correctly? I'm stuck. 40 minutes later. Not stuck anymore. Thanks everyone! def runloop(): while uid<uidend: for row in soup.findAll('h1'...
[ "On nested loops:\nYou can nest for and while loops very deeply before python will give you an error, but it's usually bad form to go more than 4 deep. Make another function if you find yourself needing to do a lot of nesting. Your use is fine though.\nSome problems with the code:\n\nIt will never reach the print ...
[ 1, 0, 0 ]
[]
[]
[ "for_loop", "python", "while_loop" ]
stackoverflow_0006645300_for_loop_python_while_loop.txt
Q: mod_wsgi: import python modules with the same name This is a follow-up question to import python modules with the same name, but as the two are somewhat unrelated, it's probably better to ask a new question: I have several python projects and they all have a conf package: /some_folder/project_1/ conf/ __init...
mod_wsgi: import python modules with the same name
This is a follow-up question to import python modules with the same name, but as the two are somewhat unrelated, it's probably better to ask a new question: I have several python projects and they all have a conf package: /some_folder/project_1/ conf/ __init__.py some_source_file.py /another_folder/project_2...
[ "FWIW, this was dealt with on mod_wsgi mailing list and from memory turned out to be caused by presence of both a module and package with same name and was picking up wrong one.\n" ]
[ 0 ]
[]
[]
[ "import", "mod_wsgi", "python" ]
stackoverflow_0006631826_import_mod_wsgi_python.txt
Q: tkinter photoimage constructor I am forced to use the plain PhotoImage class, since I had too many troubles installing PIL on the osx machine I use - I can live with it, resorting to use just GIF files. Trouble is, there's a place where I really need to create a new image of a given color, size: just a simple colo...
tkinter photoimage constructor
I am forced to use the plain PhotoImage class, since I had too many troubles installing PIL on the osx machine I use - I can live with it, resorting to use just GIF files. Trouble is, there's a place where I really need to create a new image of a given color, size: just a simple colored square. There is some way to do ...
[ "from Tkinter import * #from tkinter\n\nroot = Tk()\ni = PhotoImage(width=100, height=100)\nl = Label(root, image=i)\nl.pack()\ni.put(\"{red}\", to=(4,6,80,80))\nroot.update()\nroot.after(3000)\ni.put(\"{blue}\", to=(4,6,80,80))\nroot.mainloop()\n\n" ]
[ 4 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006643536_python_tkinter.txt
Q: Accessing Kashoo API through Python and SUDS. Problem with time format in authentication token I'm trying to access this API https://www.kashoo.com/api-docs using SUDS in Python. The Python code I use is the following: >>> from suds.client import Client >>> client = Client('https://www.kashoo.com/api/v1?wsdl') >>>...
Accessing Kashoo API through Python and SUDS. Problem with time format in authentication token
I'm trying to access this API https://www.kashoo.com/api-docs using SUDS in Python. The Python code I use is the following: >>> from suds.client import Client >>> client = Client('https://www.kashoo.com/api/v1?wsdl') >>> token = client.service.doLogin('username', 'password', 'www.kashoo.com', 'en_US', 3000000) The aut...
[ "If you can produce a log of what is going \"over the wire\" as HTTP requests and responses, it might help diagnose the problem. You certainly seem to be doing the right thing.\nDo any other calls work? How about service.getMyBusinesses(token) ?\nAlso you can consider using the REST API instead of SOAP, see if th...
[ 0 ]
[]
[]
[ "python", "soap", "suds", "wsdl" ]
stackoverflow_0006640828_python_soap_suds_wsdl.txt
Q: what is a way to match any char that appears less than a given number of times with regex python? this is my pseudocode but I dont see that regex has this function, at least the way I am thinking of it: #!/usr/bin/env python import sys import os import re def main(): wantedchars = re.match([ANY CHAR THAT ...
what is a way to match any char that appears less than a given number of times with regex python?
this is my pseudocode but I dont see that regex has this function, at least the way I am thinking of it: #!/usr/bin/env python import sys import os import re def main(): wantedchars = re.match([ANY CHAR THAT APPEARS LESS THAN 8 TIMES], <text will be pasted here>) print wantedchars if __name__=='__main__': ...
[ "If the 8 chars aren't contiguous, here is a way to do it using Counter (Python2.7+)\n>>> from collections import Counter\n\n# You can get the letters as a list...\n>>> [k for k,v in Counter(\"<text xx will xx be xx pasted xx here>\").items() if v<8]\n['a', 'b', 'e', 'd', 'i', 'h', 'l', 'p', 's', 'r', 't', 'w', '<'...
[ 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006645578_python_regex.txt
Q: Problem in calling Python script from PHP This is my python script which creates a "test.txt" file when executed. when I execute using terminal (Ubuntu 11.04) root@gml-VirtualBox:/var/www/HMS# python test.py. It creates the "test.txt" in the /var/www/HMS directory as I expected. test.py: #!/usr/bin/env python d...
Problem in calling Python script from PHP
This is my python script which creates a "test.txt" file when executed. when I execute using terminal (Ubuntu 11.04) root@gml-VirtualBox:/var/www/HMS# python test.py. It creates the "test.txt" in the /var/www/HMS directory as I expected. test.py: #!/usr/bin/env python def init(): filename = "test.txt" file =...
[ "When you test the python script on the command line, you're running as root. Chances are you're not running the webserver as root (which is a good thing), and the webserver's user does not have appropriate permissions to create and/or write to that file.\n" ]
[ 1 ]
[]
[]
[ "php", "python" ]
stackoverflow_0006645801_php_python.txt
Q: How to order a Django QuerySet string property numerically? I have a QuerySet, and I would like to order them numerically. The issue is the data is stored as a String. I know how to do this in SQL or a list, but not a query set. Is this even possible? A: You'll probably need to fallback to Django's extra functio...
How to order a Django QuerySet string property numerically?
I have a QuerySet, and I would like to order them numerically. The issue is the data is stored as a String. I know how to do this in SQL or a list, but not a query set. Is this even possible?
[ "You'll probably need to fallback to Django's extra function. Perhaps:\nordered = (qs.extra(select={\"order_column\": \"CONVERT(column, INTEGER)\"})\n .order_by(\"order_column\"))\n\n(Assuming you're using MySQL)\n" ]
[ 4 ]
[]
[]
[ "django", "django_models", "python", "sorting", "sql_order_by" ]
stackoverflow_0006645781_django_django_models_python_sorting_sql_order_by.txt
Q: In Windows, Killing an application through Python I am trying to kill external running applications like Windows Paint, a .mp3 and similar programs through a python script. I open the program throughos.startfile. Any ideas how I can close the programs efficiently? I am using a Windows 7 machine. I'd appreciate the...
In Windows, Killing an application through Python
I am trying to kill external running applications like Windows Paint, a .mp3 and similar programs through a python script. I open the program throughos.startfile. Any ideas how I can close the programs efficiently? I am using a Windows 7 machine. I'd appreciate the help a lot! Thanks!
[ "As of Python 2.7 os.kill works on Windows. You could find the PID using this recipe.\n", "Popen will let you kill an opened process, but that won't prompt to save files, etc. \np = subprocess.Popen(['notepad', 'tmp.txt'])\n#later\np.kill()\n\n", "When you ask Windows to launch something with os.startfile(), y...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006645713_python.txt
Q: Google App Engine Python Unit Tests I'd like to write some Python unit tests for my Google App Engine. How can I set that up? Does someone happen to have some sample code which shows how to write a simple test? A: GAEUnit is a unit test framework that helps to automate testing of your Google App Engine applica...
Google App Engine Python Unit Tests
I'd like to write some Python unit tests for my Google App Engine. How can I set that up? Does someone happen to have some sample code which shows how to write a simple test?
[ "GAEUnit is a unit test framework that helps to automate testing of your Google App Engine application.\nUpdate: The Python SDK now provides a testbed module that makes service stubs available for unit testing. Documentation here.\n", "Google's Python SDK now allows for this via the unittest module. More details ...
[ 18, 3, 2, 1 ]
[]
[]
[ "google_app_engine", "python", "unit_testing" ]
stackoverflow_0002750911_google_app_engine_python_unit_testing.txt
Q: How does the Python range function have a default parameter before the actual one? So I'm writing a function that takes an optional list and extends it to the length specified. Rather than writing it as foo(n, list=None) I was wondering how I might emulate the behavior of Python's range function which works like: ...
How does the Python range function have a default parameter before the actual one?
So I'm writing a function that takes an optional list and extends it to the length specified. Rather than writing it as foo(n, list=None) I was wondering how I might emulate the behavior of Python's range function which works like: >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5, 10) [5, 6, 7, 8, 9] That is, ...
[ "Others have shown how it can be done using argument counting. If I were to implement it myself in Python, though, I'd do it more like this.\ndef range(start, limit=None, stride=1):\n if limit is None:\n start, limit = 0, start\n # ...\n\n", "They aren't real keyword arguments.\nIf there's one argume...
[ 12, 9, 8, 6, 0 ]
[]
[]
[ "default_value", "overloading", "python", "range" ]
stackoverflow_0006644537_default_value_overloading_python_range.txt
Q: How to get new value from function in Python? If I put in "Ab3" as a parameter, how would I go about to having the value "Ab4" returned to me? The goal of this function is to take the 3rd character of a string and add one to it, unless it is four, in which case it would not add one and just exit. I don't know how...
How to get new value from function in Python?
If I put in "Ab3" as a parameter, how would I go about to having the value "Ab4" returned to me? The goal of this function is to take the 3rd character of a string and add one to it, unless it is four, in which case it would not add one and just exit. I don't know how to obtain the "Ab4" that the function creates from...
[ "You simply missed return statement in your function, you need it since you are using string input which is immutable. You can use the following code:\ndef east(area):\n if area[-1] in '123':\n return area[:-1] + str(int(area[-1])+1)\n elif \"4\" == area[-1]:\n print 'no way'\n return are...
[ 5, 1, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0006646148_function_python.txt
Q: Memory leak when running python in Mac OS Terminal I just ran a python program in the Mac OS Terminal, and there is unusual memory leak. The program is simple like this: for i in xrange(1000000000, 2000000000, 10): i2 = i * i print i, i2, str(i2)[::2] if str(i2)[::2] == '1234567890': break When the pro...
Memory leak when running python in Mac OS Terminal
I just ran a python program in the Mac OS Terminal, and there is unusual memory leak. The program is simple like this: for i in xrange(1000000000, 2000000000, 10): i2 = i * i print i, i2, str(i2)[::2] if str(i2)[::2] == '1234567890': break When the program is running, it consumes more and more memory till i...
[ "This isn't a bug; it's actually a feature. Terminal.app, like many other terminal emulators, saves recent output in a buffer so that you can scroll back (with page up or the scroll bar). You can limit how large this is by going to Terminal -> Preferences -> Settings and setting the scrollback limit to something ot...
[ 14, 5 ]
[]
[]
[ "macos", "memory_leaks", "python", "terminal" ]
stackoverflow_0006646331_macos_memory_leaks_python_terminal.txt
Q: i have a list in my customer.txt how to create a search function to print out the whole customer information using python Hi i have a list in my customer.txt file: [1, 'Amin Milani Fard', 'Columbia College', 778] [33, 'Ali Sulemanji', 'Langara College', 4324442211] [32, 'Ali Sulemanji', 'Langara College', 43244422...
i have a list in my customer.txt how to create a search function to print out the whole customer information using python
Hi i have a list in my customer.txt file: [1, 'Amin Milani Fard', 'Columbia College', 778] [33, 'Ali Sulemanji', 'Langara College', 4324442211] [32, 'Ali Sulemanji', 'Langara College', 4324442211] [325, 'Ali Sulemanji', 'Langara College', 4324442211] [2, 'Yuvin Ng','Dougles College',77839922003] [3, 'Ali Sulemanji', 'L...
[ "A simple approach would be to iterate over the lines in the file using in to check for a match, and if a match is found use eval to return the line as a list.\ndef search(file_name, name):\n with open(file_name) as f:\n for line in f:\n if name in line:\n return eval(line) \n ...
[ 3, 0 ]
[ "Why not use a database instead of a flat file for storing the information? For example if you wanted to use a database called 'users', you could have something like\nimport _mysql\nconn = _mysql.connect('localhost','root','','users')\nwith open(filename) as fp:\n for line in fp:\n then fill your query w...
[ -1 ]
[ "python" ]
stackoverflow_0006637298_python.txt
Q: python list of hex numbers to string and write to file? I have a list of hex numbers I need to convert to string to write it to binary file. How can I do that? (convert the list of hex numbers to a string) A: converting to a string is easy >>> "aabbccddeeff".decode('hex') '\xaa\xbb\xcc\xdd\xee\xff' you don't ne...
python list of hex numbers to string and write to file?
I have a list of hex numbers I need to convert to string to write it to binary file. How can I do that? (convert the list of hex numbers to a string)
[ "converting to a string is easy\n>>> \"aabbccddeeff\".decode('hex')\n'\\xaa\\xbb\\xcc\\xdd\\xee\\xff'\n\nyou don't need to do anything special to write this to a file\n>>> with open(\"out.txt\", \"wb\") as f:\n... f.write(\"aabbccddeeff\".encode('hex'))\n\nFor Python3, it is slightly different\n>>> import binas...
[ 9 ]
[]
[]
[ "file", "hex", "list", "python", "string" ]
stackoverflow_0006646474_file_hex_list_python_string.txt
Q: How to make celeryd as daemon in Linux centos for django I am following this tutorial and i have made the file celeryd in /etc/default directory Now , i am try /etc/init.d/celeryd start and its not working. ERROR : file not found They have not written anything more on that page. what should i do 1) which file i ne...
How to make celeryd as daemon in Linux centos for django
I am following this tutorial and i have made the file celeryd in /etc/default directory Now , i am try /etc/init.d/celeryd start and its not working. ERROR : file not found They have not written anything more on that page. what should i do 1) which file i need to put in /etc/default/celeryd 2) My celeryd bin file is i...
[ "Did you copy these files to the /etc/init.d/ directory?\n" ]
[ 0 ]
[]
[]
[ "celery", "django", "linux", "python" ]
stackoverflow_0006645657_celery_django_linux_python.txt
Q: Can a variable be used inside a function without a Global declaration inside that function CODE 1: x=4 def func(): print("HELLO WORLD") y=x+2 print (y) print (x) # gives o/p as HELLO WORLD 6,4,4. func() print (x) CODE 2: x=4 def func(): print("HELLO ...
Can a variable be used inside a function without a Global declaration inside that function
CODE 1: x=4 def func(): print("HELLO WORLD") y=x+2 print (y) print (x) # gives o/p as HELLO WORLD 6,4,4. func() print (x) CODE 2: x=4 def func(): print("HELLO WORLD") y=x+2 x=x+2 # gives an error here print (y) prin...
[ "You can read global variables without explicitly declaring them as global (Code 1)\nBut you are not allowed to assign to a global variable without explicitely declaring it as global. (Code 2)\nThis is because there is no harm in reading, but when assigning you might get unexpected behaviour (especially if it's a l...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006646732_python.txt
Q: Why it is showing different output? x=4 def func(): print("HELLO WORLD") y=x+2 x=2 print (y) print (x) # OUTPUT IS 6,2,2 global x # global declaration is done here func() print (x) # outputs as 2 but why???? why not 4???? Wh...
Why it is showing different output?
x=4 def func(): print("HELLO WORLD") y=x+2 x=2 print (y) print (x) # OUTPUT IS 6,2,2 global x # global declaration is done here func() print (x) # outputs as 2 but why???? why not 4???? Why it shows the output as 6,2,2. Indeed i ...
[ "The global keyword indicates to the compiler that the variable is to be considered global throughout the function. It doesn't matter where it shows up in the function, so long as the compiler takes note of it.\n" ]
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0006646942_python.txt
Q: Django: How to access locale string among apps? There are two apps in my Django project root: app1/ app1/locale/ app2/ app2/locale/ I want to use locale string form app1 in app2, so I can have no duplicated msgid. Maybe, another solution is shared locale dir in project root dir: app1/ app2/ locale/ but I have to...
Django: How to access locale string among apps?
There are two apps in my Django project root: app1/ app1/locale/ app2/ app2/locale/ I want to use locale string form app1 in app2, so I can have no duplicated msgid. Maybe, another solution is shared locale dir in project root dir: app1/ app2/ locale/ but I have to rebuild many locale files ...
[ "You can make a symlink between them.\n" ]
[ 1 ]
[]
[]
[ "django", "locale", "python" ]
stackoverflow_0006646955_django_locale_python.txt
Q: How to change the permission of celeryd in django I have seen that when i execute celeryd via normal user then i get permission denied error /opt/python2.7/bin/celeryd But it executes with root user In the text it says that "Running celeryd with superuser privileges is not encouraged!") How can i assign previlege...
How to change the permission of celeryd in django
I have seen that when i execute celeryd via normal user then i get permission denied error /opt/python2.7/bin/celeryd But it executes with root user In the text it says that "Running celeryd with superuser privileges is not encouraged!") How can i assign previlege to user1 for celeryd
[ "You can add execute permissions for all users by running the following in a terminal:\nsudo chmod u+x /opt/python2.7/bin/celeryd\n" ]
[ 3 ]
[]
[]
[ "celery", "django_celery", "python" ]
stackoverflow_0006647080_celery_django_celery_python.txt
Q: Python os.waitpid throw `[Errno 10] No child processes` Following code return with [Errno 10] No child processes on windows platform (python version 2.7.2). import subprocess import os pid = subprocess.Popen(["cmd"]).pid os.waitpid(pid, 0) print 'process %d finished' % pid The same code works well on Linux. A: ...
Python os.waitpid throw `[Errno 10] No child processes`
Following code return with [Errno 10] No child processes on windows platform (python version 2.7.2). import subprocess import os pid = subprocess.Popen(["cmd"]).pid os.waitpid(pid, 0) print 'process %d finished' % pid The same code works well on Linux.
[ "Maby this will work- but I have no idea, why your code isn't working on Windows- everything looks fine:\nimport subprocess\nsubp = subprocess.Popen([\"cmd\"])\nsubp.wait()\nprint 'process %d finished' % subp.pid\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006647102_python.txt
Q: how to plot multiple pictures with pylab in python? i have the following code: import psycopg2 import pylab class Datenanzeige: def __init__(self): self.conn = psycopg2.connect("dbname='test' user='test' host='test' password='test'") self.cur = self.conn.cursor() self.site = ['FFF', 'PPP', 'DDD', 'K...
how to plot multiple pictures with pylab in python?
i have the following code: import psycopg2 import pylab class Datenanzeige: def __init__(self): self.conn = psycopg2.connect("dbname='test' user='test' host='test' password='test'") self.cur = self.conn.cursor() self.site = ['FFF', 'PPP', 'DDD', 'KKK'] self.plant = [1, 2, 3, 4, 5, 6] def anzeige(s...
[ "To do what you want, you need do one of two things:\n\nuse the clf() and cla() (clear figure and clear axes respectively) methods after you've saved your figures.\nCreate multiple figures, and then set the title and axes label on each figure. At the moment, you're using a default background figure that pylab gives...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0006647225_matplotlib_python.txt
Q: Python logging fails when open file descriptor message encountered I have the following Python code to create an lvm snapshot on a Linux machine. #!/usr/bin/env python3.1 import subprocess import logging logging.basicConfig(filename='/var/log/lvsnap.log', filemode='w', level=logging.DEBUG) lvm_vg = 'vg00-crunchb...
Python logging fails when open file descriptor message encountered
I have the following Python code to create an lvm snapshot on a Linux machine. #!/usr/bin/env python3.1 import subprocess import logging logging.basicConfig(filename='/var/log/lvsnap.log', filemode='w', level=logging.DEBUG) lvm_vg = 'vg00-crunchbang' lvm_name = 'root' lvm_snapshot_size = '100' def lvmCreateSnapshot(...
[ "You are not invoking the \"missing\" logging.debug since lvmCreateSnapshot returns zero and your if condition is therefore never met. Try\nif lvm_create_snapshot:\n logging.debug('Error creating lvm snapshot of %s/%s, exited with status %s', lvm_vg, lvm_name, lvm_create_snapshot)\nelse:\n logging.debug('crea...
[ 3 ]
[]
[]
[ "file_descriptor", "logging", "lvm", "python", "subprocess" ]
stackoverflow_0006647021_file_descriptor_logging_lvm_python_subprocess.txt
Q: Django South: Migrating FK from another table I was doing some system and my table design was like this: Table A: - ID - ForeignKey(C) Table B: - ID - ForeignKey(A) Table C: - ID Due to some requirement changes, I need to move ForeignKey(C) from A to B, so it goes like this: Table A: - ID Ta...
Django South: Migrating FK from another table
I was doing some system and my table design was like this: Table A: - ID - ForeignKey(C) Table B: - ID - ForeignKey(A) Table C: - ID Due to some requirement changes, I need to move ForeignKey(C) from A to B, so it goes like this: Table A: - ID Table B: - ID - ForeignKey(A) - ForeignKe...
[ "When doing this type of migration I always create 3 migrations:\n\ncreates the new field \n(a datamigration) copies the data from the old field to the new field (possibly with a transformation)\ndeletes the old field\n\nThis way I can use the auto schemamigration from south for the first and the third migration an...
[ 6 ]
[]
[]
[ "django", "django_south", "migration", "python" ]
stackoverflow_0006646659_django_django_south_migration_python.txt
Q: Constantly running python script, calling functions via terminal quick question that I'm never even sure is possible :3 I have a python script, a network script that connects to a server and remains connected until I either disconnect or it kicks me (which it normally shouldn't), which is constantly receiving data...
Constantly running python script, calling functions via terminal
quick question that I'm never even sure is possible :3 I have a python script, a network script that connects to a server and remains connected until I either disconnect or it kicks me (which it normally shouldn't), which is constantly receiving data and doing other tasks. I was curious if it's at all possible while th...
[ "The usual 'UNIX-way' to solve such problems is to poll or select on both the socket and the standard input file descriptors. You then handle network input on 'IN' event on the socket and terminal input on 'IN' event on the stdin file descriptor.\nThis is not portable to Windows (which sucks), but that is the most ...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0006645680_networking_python.txt
Q: Enforcing "no 2 same contiguous elements" in random list generation I have a set of 4 strings and want to generate a list of 16 elements, but with enforcing the rule (or obtaining the same result as enforcing such rule) to never have the same element repeated in two contiguous positions in the resulting list. Bein...
Enforcing "no 2 same contiguous elements" in random list generation
I have a set of 4 strings and want to generate a list of 16 elements, but with enforcing the rule (or obtaining the same result as enforcing such rule) to never have the same element repeated in two contiguous positions in the resulting list. Being almost a total newbie in Python I went to check the different methods i...
[ "Pseudocode algorithm:\n\nFor i in n (n being the amount of elements you want)\nGenerate the next element\nIf it's the same as the previous element, repeat 2\n\nUse random.choice to pick an element from a list of elements randomly.\nHere's a proof of concept Python code:\nimport random\nsources = ['a', 'b', 'c', 'd...
[ 6, 3, 2, 1, 1 ]
[]
[]
[ "algorithm", "list", "python", "random", "rules" ]
stackoverflow_0006647174_algorithm_list_python_random_rules.txt
Q: controlling Python script with usb midi controller I have a usb midi controller (uc-33e) and I have a working python script see below. I would like to be able to control the variables of the python script using my usb controller does anyone have an example of this? I would like to use the "midi learn" function to...
controlling Python script with usb midi controller
I have a usb midi controller (uc-33e) and I have a working python script see below. I would like to be able to control the variables of the python script using my usb controller does anyone have an example of this? I would like to use the "midi learn" function to automatically map a midi control to an object (like in ...
[ "You should take a look at pygame, which has an excellent and easy MIDI interface. After you get your controller configured, MIDI learn is simply a matter of listening to the first incoming CC and then saving the channel.\n" ]
[ 2 ]
[]
[]
[ "midi", "midi_interface", "python" ]
stackoverflow_0006524089_midi_midi_interface_python.txt
Q: Terminal Window in Windows Using Python I want to create a window like terminal window or like command prompt for my application using python in windows. I have searched in internet and found some programs. But Its all working in linux and unix machine. But its not working in windows. Because these programs requir...
Terminal Window in Windows Using Python
I want to create a window like terminal window or like command prompt for my application using python in windows. I have searched in internet and found some programs. But Its all working in linux and unix machine. But its not working in windows. Because these programs requires modules like (vte,termios). Its not availa...
[ "Bruce has one. check out and browse the source; I guess bruce/interpreter.py will be interesting.\n" ]
[ 0 ]
[]
[]
[ "python", "terminal", "window" ]
stackoverflow_0006648558_python_terminal_window.txt
Q: C++ Why can't the linker see my files? Building a native module for Node.js under Cygwin / Windows: I have a monkey.cc file with this: #include <monkey/monkey.h> running node-waf configure build I get the following 'configure' finished successfully (0.351s) Waf: Entering directory `/usr/src/build' [2/2] cxx_lin...
C++ Why can't the linker see my files?
Building a native module for Node.js under Cygwin / Windows: I have a monkey.cc file with this: #include <monkey/monkey.h> running node-waf configure build I get the following 'configure' finished successfully (0.351s) Waf: Entering directory `/usr/src/build' [2/2] cxx_link: build/default/monkey_1.o -> build/default...
[ "That's a linker error, not a compiler error. Do you have a definition for the function? (Not just a declaration.) And are you sure it's being linked in?\n", "Add monkey.lib='crypto' in the wscript.\n" ]
[ 3, 0 ]
[]
[]
[ "c++", "linker_errors", "node.js", "python", "waf" ]
stackoverflow_0006560619_c++_linker_errors_node.js_python_waf.txt
Q: How to access a variable which is declared in some other function? def main(): x=2 def cool(): y=4 nonlocal x print (x) It is showing an error as --nonlocal x is a invalid syntax--.And if I dont declare it as nonlocal it says undefined x. So, how do i acess a variabl...
How to access a variable which is declared in some other function?
def main(): x=2 def cool(): y=4 nonlocal x print (x) It is showing an error as --nonlocal x is a invalid syntax--.And if I dont declare it as nonlocal it says undefined x. So, how do i acess a variable which is in some other function ?Now how do i access x variable which...
[ "You can't.\nYou shouldn't. Doing so would just make it hard to read code because code from anywhere could read and modify your variables. By keeping access restricted to the one function it is easier to follow.\n", "Once you start needing attributes on a function, turn it into a functor:\nclass MainFactory(objec...
[ 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006648954_python.txt
Q: Security issues with a middleware screener page While my startup is in dark mode I want all access except access to / to go to a screener page where users have enter a password given to them by a representative. I've come up with the following simple middleware to perform the task. Just to be clear, this is intend...
Security issues with a middleware screener page
While my startup is in dark mode I want all access except access to / to go to a screener page where users have enter a password given to them by a representative. I've come up with the following simple middleware to perform the task. Just to be clear, this is intended to ensure that users agree to keep the site in con...
[ "Here is my solution. It is using not COOKIES but custom Auth Backend.\nStep 1\nIt's good to have a Django application for this:\nkey_auth/\n templates/\n key_auth_form.html # very simple form template\n __init__.py\n models.py\n urls.py\n views.py\n forms.py\n middleware.py\n backend...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006408399_django_python.txt
Q: Removing nested loops in numpy I've been writing a program to brute force check a sequence of numbers to look for euler bricks, but the method that I came up with involves a triple loop. Since nested Python loops get notoriously slow, I was wondering if there was a better way using numpy to create the array of val...
Removing nested loops in numpy
I've been writing a program to brute force check a sequence of numbers to look for euler bricks, but the method that I came up with involves a triple loop. Since nested Python loops get notoriously slow, I was wondering if there was a better way using numpy to create the array of values that I need. #x=max side length ...
[ "Try to use .empty and .fill (http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.fill.html)\n", "There are couple of things which could help, but probably only for large values of x. For starters use xrange instead of range, that will save creating a list you never need. You could also create empty...
[ 2, 1 ]
[]
[]
[ "nested_loops", "numpy", "python" ]
stackoverflow_0006649839_nested_loops_numpy_python.txt
Q: Confused with celeryd config file and daemon file for Django in Linux I am trying to integrate celeryd with djnago but i am stuck with its config file There are three files they are talking about. I need to know what should be the contents of those files My Celeryd executable is in /opt/python27/bin/celeryd There ...
Confused with celeryd config file and daemon file for Django in Linux
I am trying to integrate celeryd with djnago but i am stuck with its config file There are three files they are talking about. I need to know what should be the contents of those files My Celeryd executable is in /opt/python27/bin/celeryd There are three file i don't know what should be their contents celeryconfig.py ...
[ "When using celery with django, you should not use the celeryd executable directly. \nYou have to install django-celery and run the celery daemon as \n\npython manage.py celeryd\n\nAlso, you have to configure celery on the settings.py file opf your django project.\nGet more information at http://packages.python.org...
[ 1 ]
[]
[]
[ "django", "django_celery", "python" ]
stackoverflow_0006650229_django_django_celery_python.txt
Q: Crawler with Python? I'd like to write a crawler using python. This means: I've got the url of some websites' home page, and I'd like my program to crawl through all the website following links that stay into the website. How can I do this easily and FAST? I tried BeautifulSoup already, but it is really cpu consum...
Crawler with Python?
I'd like to write a crawler using python. This means: I've got the url of some websites' home page, and I'd like my program to crawl through all the website following links that stay into the website. How can I do this easily and FAST? I tried BeautifulSoup already, but it is really cpu consuming and quite slow on my p...
[ "I'd recommend using mechanize in combination with lxml.html. as robert king suggested, mechanize is probably best for navigating through the site. for extracting elements I'd use lxml. lxml is much faster than BeautifulSoup and probably the fastest parser available for python. this link shows a performance test of...
[ 6, 3, 3, 2 ]
[]
[]
[ "beautifulsoup", "bots", "python", "web_crawler" ]
stackoverflow_0006649001_beautifulsoup_bots_python_web_crawler.txt
Q: Gaierror from python smtplib This line is throwing a gaierror... any idea why? Could it be a firewall? smtp=smtplib.SMTP(host=EMAIL_HOST,port=EMAIL_PORT) I'm using gmail so the host is 'alt1.gmail-smtp-in.l.google.com', and the port is 587. A: Even if this weren't a gaierror (which, as AJ rightly says is a DNS ...
Gaierror from python smtplib
This line is throwing a gaierror... any idea why? Could it be a firewall? smtp=smtplib.SMTP(host=EMAIL_HOST,port=EMAIL_PORT) I'm using gmail so the host is 'alt1.gmail-smtp-in.l.google.com', and the port is 587.
[ "Even if this weren't a gaierror (which, as AJ rightly says is a DNS lookup error), that host doesn't work for me either.\nSpecifically, it hangs trying to connect and times out.\nHowever, the following seems to work:\nimport smtplib\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_PORT = 587\nsmtp=smtplib.SMTP(host=EMAIL_HOS...
[ 1 ]
[]
[]
[ "django", "gmail", "python", "smtp" ]
stackoverflow_0006650214_django_gmail_python_smtp.txt
Q: Python message oriented middleware (i.e. JMS for Python) What message oriented middle ware with a Python API are out there? What ones did you use and recommend (or not)? A: I remember that some people supposedly used spread for message queues http://www.spread.org/, but I don't have any personal experience with ...
Python message oriented middleware (i.e. JMS for Python)
What message oriented middle ware with a Python API are out there? What ones did you use and recommend (or not)?
[ "I remember that some people supposedly used spread for message queues http://www.spread.org/, but I don't have any personal experience with it.\n", "For ActiveMQ, there are\n\na Python client based on the OpenWire protocol at http://hiramchirino.com/old-blog/2009/07/openwire-python-client-for-activemq.html\nmany...
[ 1, 0, 0 ]
[]
[]
[ "jms", "message_queue", "messaging", "python" ]
stackoverflow_0001735283_jms_message_queue_messaging_python.txt
Q: Transform dictionaries to a list of dictionaries according to their values I have different dictionaries that I want to regroup into a list of dictionaries, taking into account their different values: Dictionaries : [{'language': 'de', 'suggestion': 'fressen', 'comment': 'for animals'}, {'language': 'de', 'suggest...
Transform dictionaries to a list of dictionaries according to their values
I have different dictionaries that I want to regroup into a list of dictionaries, taking into account their different values: Dictionaries : [{'language': 'de', 'suggestion': 'fressen', 'comment': 'for animals'}, {'language': 'de', 'suggestion': 'essen', 'comment': ''}, {'language': 'fr', 'suggestion': 'manger', 'comme...
[ "A straightforward solution, assuming all dicts's keys are same:\nld = [{'language': 'de', 'suggestion': 'fressen', 'comment': 'for animals'},\n{'language': 'de', 'suggestion': 'essen', 'comment': ''},\n{'language': 'fr', 'suggestion': 'manger', 'comment': ''},\n{'language': 'fr', 'suggestion': 'bouffer', 'comment'...
[ 4, 1, 1, 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0006649589_dictionary_list_python.txt
Q: send key code to field i want to simulate the pressing of the enter key using py-appscript i already found this, but it seems to only output the newline Translate Applescrip [key code 125 using command down] to appscript right now i want to press the enter key after the value has been set. Example, after entering ...
send key code to field
i want to simulate the pressing of the enter key using py-appscript i already found this, but it seems to only output the newline Translate Applescrip [key code 125 using command down] to appscript right now i want to press the enter key after the value has been set. Example, after entering the IP hit enter key. or sen...
[ "app('System Events').key_code(76). (Or key_code(36) or keystroke('\\r') if you meant ↩ instead of ⌤.)\nkeystroke and key_code don't ignore keys actually held down by the user, so you might need to add a delay if you're using a shortcut with modifier keys used to run the script.\n" ]
[ 0 ]
[]
[]
[ "applescript", "py_appscript", "python" ]
stackoverflow_0006645294_applescript_py_appscript_python.txt
Q: Can a Python list, set or dictionary be implemented invisibly using a database? The Python native capabilities for lists, sets & dictionaries totally rock. Is there a way to continue using the native capability when the data becomes really big? The problem I'm working on involved matching (intersection) of very ...
Can a Python list, set or dictionary be implemented invisibly using a database?
The Python native capabilities for lists, sets & dictionaries totally rock. Is there a way to continue using the native capability when the data becomes really big? The problem I'm working on involved matching (intersection) of very large lists. I haven't pushed the limits yet -- actually I don't really know what th...
[ "I'm not quite sure what you mean by native capabilities for lists, sets & dictionaries. However, you can create classes that emulate container types and sequence types by defining some methods with special names. That means that you could create a class that behaves like a list, but stores its data in a SQL databa...
[ 8, 2, 0 ]
[]
[]
[ "database", "google_app_engine", "list", "python", "volume" ]
stackoverflow_0006650275_database_google_app_engine_list_python_volume.txt
Q: Regex to convert path to URL I have this python script which is supposed to wrap all that look like a path within a tag to make an url out of it. def wrap(text, regex): start, end = '<a href="/static', '">Link to the file</a>' matchs = sorted([(s.start(), s.end()) for s in re.finditer(regex, text)], ...
Regex to convert path to URL
I have this python script which is supposed to wrap all that look like a path within a tag to make an url out of it. def wrap(text, regex): start, end = '<a href="/static', '">Link to the file</a>' matchs = sorted([(s.start(), s.end()) for s in re.finditer(regex, text)], reverse = True) for mat...
[ "It depends a bit on which characters you allow in path names, but this does the trick for your example:\nwrap('HA HA HA /services/nfs_qa/log.lol HO HO HO', '/services/nfs_qa/[^ ]*')\n'HA HA HA <a href=\"/static/services/nfs_qa/log.lol\">Link to the file</a> HO HO HO'\n\nThe [^ ] means anything but a space (the opp...
[ 2, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006650985_python_regex.txt
Q: Get all values from child elements of a dict as a list T = {'a': {'c': 'A', 'path': '/c'}, 'e': {'c': 'E', 'path': '/e'}, 's': {'c': 'S', 'path': '/s'}} I need all 'path' elements as a list. I know I can iterate through everything in a single for, but I would like to know other pythonic ways of extracting it. A:...
Get all values from child elements of a dict as a list
T = {'a': {'c': 'A', 'path': '/c'}, 'e': {'c': 'E', 'path': '/e'}, 's': {'c': 'S', 'path': '/s'}} I need all 'path' elements as a list. I know I can iterate through everything in a single for, but I would like to know other pythonic ways of extracting it.
[ "Think that there is no way except iterate so you can use the following code:\n[v['path'] for k,v in T.iteritems() if k in <top level keys to be used>]\n\nEDITED as per comments: I have used iteritems since it allows you to perform filter action using top level keys if neccessary, otherwise(if you don't care about ...
[ 4, 4 ]
[]
[]
[ "python" ]
stackoverflow_0006651194_python.txt
Q: Write new data into the middle of a file Possible Duplicate: How do I modify a text file in Python? It's easy to write a new file, append to it, etc. But how can I write to the middle of a file? I have an html report that is generated off of an automated process, and rather than rewrite the whole report, I w...
Write new data into the middle of a file
Possible Duplicate: How do I modify a text file in Python? It's easy to write a new file, append to it, etc. But how can I write to the middle of a file? I have an html report that is generated off of an automated process, and rather than rewrite the whole report, I want to just insert new data where it's new. ...
[ "Yes.\n\nRead the file in\nModify what you need\nOverwrite the file with the modified version\n\nIf the file is too big to fit into memory, read and write it line by line (or block by block, or whatever fits) into some temporary file, and then copy it instead of the original file.\n", "try fileObject.seek(offset[...
[ 6, 0, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0006650421_file_io_python.txt
Q: Sometimes garbled results sending base64 encoded images over TCP socket from python to node.js I'm trying to procedurally generate images in python to send to a node.js instance, so I can then deliver those images real-time to a browser through a websocket. My first test iteration was simply opening a jpeg file in...
Sometimes garbled results sending base64 encoded images over TCP socket from python to node.js
I'm trying to procedurally generate images in python to send to a node.js instance, so I can then deliver those images real-time to a browser through a websocket. My first test iteration was simply opening a jpeg file in my node.js server, encoding it into base64, and sending it to the browser using socket.io (on port ...
[ "regardless on how many writes was on client side of tcp socket and what were sizes of messages you generally don't have control on sizes of data chunks you'll get on serever's 'data' handler (tcp only guarantees they are in order). You need to frame your data manually (simplest way is to prefix with frame size and...
[ 2 ]
[]
[]
[ "node.js", "python", "sockets", "tcp", "websocket" ]
stackoverflow_0006651196_node.js_python_sockets_tcp_websocket.txt
Q: Creating dictionary from a list of special characters I'm working on this small script: basically it's mapping the list elements (with special characters in it) to its index to create a dictionary. #!/usr/bin/env python #-*- coding: latin-1 -*- ln1 = '?0>9<8~7|65"4:3}2{1+_)' ln2 = "(*&^%$£@!/`'\][=-#¢" refStr = ...
Creating dictionary from a list of special characters
I'm working on this small script: basically it's mapping the list elements (with special characters in it) to its index to create a dictionary. #!/usr/bin/env python #-*- coding: latin-1 -*- ln1 = '?0>9<8~7|65"4:3}2{1+_)' ln2 = "(*&^%$£@!/`'\][=-#¢" refStr = ln2+ln1 keyDict = {} for i in range(0,len(refStr)): ke...
[ "When you print a dictionary or list that contains strings Python will display the repr() of the strings. If you print repr(ln2) you'll see that nothing has changed: your dictionary key is just the latin-1 encoding of '£' &c. characters.\nIf you do:\nfor k in keyDict:\n print k, keyDict[k]\n\nthen the characters...
[ 6, 3 ]
[]
[]
[ "dictionary", "python", "sorteddictionary" ]
stackoverflow_0006651559_dictionary_python_sorteddictionary.txt
Q: javascript function not defined error I'm using Google App Engine SDK for Python. When I write Javascript functions in a separate .js file and include it in the .py file, I get the following errors in Chrome:- In .py file:- Uncaught reference error: initFunc is not defined. In .js file:- Uncaught syntax error: Une...
javascript function not defined error
I'm using Google App Engine SDK for Python. When I write Javascript functions in a separate .js file and include it in the .py file, I get the following errors in Chrome:- In .py file:- Uncaught reference error: initFunc is not defined. In .js file:- Uncaught syntax error: Unexpected token < Resource interpreted as scr...
[ "My guess is that you have both main.py and foo.js in the same root directory.\nYou should map a route for the static contents of your project like javascripts in the app.yaml config file:\n1.Create a directory called static/javascripts in the Root of your project\n2.Add the javascripts static section in your app....
[ 1 ]
[]
[]
[ "google_app_engine", "javascript", "python" ]
stackoverflow_0006650278_google_app_engine_javascript_python.txt
Q: Python/Django for an enterprise large scale web based system? My company is highly dependent on Java and jsf; All projects since I was hired are implemented using them. But most of those projects are facing problems related to performance and availability. So am finally considering a shift to other technologies an...
Python/Django for an enterprise large scale web based system?
My company is highly dependent on Java and jsf; All projects since I was hired are implemented using them. But most of those projects are facing problems related to performance and availability. So am finally considering a shift to other technologies and I have tried to research in the net, and im about to decide to tr...
[ "I have some doubts that you will gain performance by using Django or a Python based solution. I don't know the Glassfish server nor how it scales up but unless badly designed I don't see why it should perform badly.\nFrom the explanation of your performance issues, it doesn't seem to be a problem of language speed...
[ 6 ]
[]
[]
[ "high_availability", "performance", "python" ]
stackoverflow_0006651406_high_availability_performance_python.txt
Q: chaining Popen subprocesses properly i have a construct like the following: os.mkfifo('pipe.tmp') enc = Popen(['encoder', '-i', 'pipe.tmp']) cap = Popen(['capture', '-f', 'pipe.tmp']) here cap is a process which normally writes to a file (specified by -f), but i can get it to spew data to the screen by supplying ...
chaining Popen subprocesses properly
i have a construct like the following: os.mkfifo('pipe.tmp') enc = Popen(['encoder', '-i', 'pipe.tmp']) cap = Popen(['capture', '-f', 'pipe.tmp']) here cap is a process which normally writes to a file (specified by -f), but i can get it to spew data to the screen by supplying /dev/stdout as the output file. similarly...
[ "\n/dev/stdout gives you the stdout for the current process, so you should be just fine to use that. (there isn't really anything 'global' about /dev/stdout)\nThe size of the fifo in the first example depends on the configuration of your system (I'm not sure how to change that). But subprocess.Popen allows you to d...
[ 1 ]
[]
[]
[ "named_pipes", "pipe", "popen", "python", "subprocess" ]
stackoverflow_0006646945_named_pipes_pipe_popen_python_subprocess.txt
Q: Can't find the cause "TypeError: coercing to Unicode: need string or buffer, NoneType found" I'm getting this error from production server: File "/home/example/svn/libs/django/core/handlers/base.py", line 100, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/home/example...
Can't find the cause "TypeError: coercing to Unicode: need string or buffer, NoneType found"
I'm getting this error from production server: File "/home/example/svn/libs/django/core/handlers/base.py", line 100, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/home/example/svn/src/app/../app/libs/auth/decorators.py", line 125, in __call__ return self.view_func(reque...
[ "Focus on just this portion of the traceback. This looks like code you wrote.\n File \"/home/example/svn/src/app/../app/membership/decorators.py\", line 64, in __call__\n return self.view_func(request, *args, **kwargs)\n\n File \"/home/example/svn/src/app/../app/site/views/system/invoices.py\", line 168, in send...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006652077_django_python.txt
Q: MySQLdb to Excel I have a Django project which has a mysql database backend. How can I export contents from my db to an Excel (xls, xlsx) format? A: phpMyAdmin has an Export tab, and you can export in CSV. This can be imported into Excel. A: http://pypi.python.org/pypi/xlwt A: If you need a xlsx (excel 200...
MySQLdb to Excel
I have a Django project which has a mysql database backend. How can I export contents from my db to an Excel (xls, xlsx) format?
[ "phpMyAdmin has an Export tab, and you can export in CSV. This can be imported into Excel.\n", "http://pypi.python.org/pypi/xlwt \n", "If you need a xlsx (excel 2007) exporter, you can use openpyxl. Otherwise xlwt is an option.\n", "Openpyxl is a great choice,\nbut if you don't wanna go through a new thing y...
[ 0, 0, 0, 0 ]
[]
[]
[ "django", "excel", "mysql", "python" ]
stackoverflow_0006649990_django_excel_mysql_python.txt
Q: python: The correct way to assign a value from itertools.permutations()? The following code creates a multi dimensional list (not sure if that's the Pythonic was of saying it. PHP guy here) patterns.append(list(itertools.permutations('1234567',7))) the value of patterns becomes: ([ [1,2,3,4,5,6,7], [1,2,3...
python: The correct way to assign a value from itertools.permutations()?
The following code creates a multi dimensional list (not sure if that's the Pythonic was of saying it. PHP guy here) patterns.append(list(itertools.permutations('1234567',7))) the value of patterns becomes: ([ [1,2,3,4,5,6,7], [1,2,3,4,5,7,6], ... ]) What I want is for the result to be like this: ([1,2,3,4,5...
[ "If you need to get\n([1,2,3,4,5,6,7], [1,2,3,4,5,7,6]...)\n\nthan you can use:\nfrom itertools import permutations\npatterns = tuple(list(int(y) for y in x) for x in permutations('1234567',7))\n\nOR you can use xrange instead of '1234567' if you need to get numbers:\npatterns = tuple(list(x) for x in permutations(...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006652337_python.txt
Q: Python TkMessageBox Question not working! I have a button that writes output to a file. And checks if the file with that filename already exists. It is supposed to ask the user to override or not? But it is not working. If the user says No, then the program will still override the file. This is the code to pop up ...
Python TkMessageBox Question not working!
I have a button that writes output to a file. And checks if the file with that filename already exists. It is supposed to ask the user to override or not? But it is not working. If the user says No, then the program will still override the file. This is the code to pop up the MessageBox: if os.path.exists(self.file...
[ "You need to use a dialog that has yes/no or ok/cancel buttons, and you need to capture the return value of that dialog to know what the user clicked on. From that you can then decide whether to write to the file or not.\nFor example:\nimport Tkinter as tk\nimport tkMessageBox\n\nclass SampleApp(tk.Tk):\n def __...
[ 5, 0 ]
[]
[]
[ "python", "tkinter", "tkmessagebox" ]
stackoverflow_0006652263_python_tkinter_tkmessagebox.txt
Q: Naive and easiest way to decompose independent loop into parallel threads/processes I have a loop of intensive calculations, I want them to be accelerated using the multicore processor as they are independent: all performed in parallel. What the easiest way to do that in python? Let’s imagine that those calculatio...
Naive and easiest way to decompose independent loop into parallel threads/processes
I have a loop of intensive calculations, I want them to be accelerated using the multicore processor as they are independent: all performed in parallel. What the easiest way to do that in python? Let’s imagine that those calculations have to be summed at the end. How to easily add them to a list or a float variable? ...
[ "From my experience, multi-threading is probably not going to be a viable option for speeding things up (due to the Global Interpreter Lock).\nA good alternative is the multiprocessing module. This may or may not work well, depending on how much data you end up having to pass around from one process to another.\nAn...
[ 12, 1 ]
[]
[]
[ "parallel_processing", "python" ]
stackoverflow_0006652124_parallel_processing_python.txt
Q: Formatting File Paths I'm new to Python so I may be going about this completely wrong, but I'm having problems getting and changing to the directory of a file. My script takes in multiple file names that can be in any directory. In my script I need python to change to the directory of the file and then perform so...
Formatting File Paths
I'm new to Python so I may be going about this completely wrong, but I'm having problems getting and changing to the directory of a file. My script takes in multiple file names that can be in any directory. In my script I need python to change to the directory of the file and then perform some actions. However, I'm h...
[ "The last backslash isn't being automatically escaped because Python only escapes backslashes in regular strings when the following character does not form an escape sequence with the backslash. In fact, in your example, you would NOT get 'C:\\\\foo\\bar' from 'C:\\foo\\bar', you'd get 'C:\\x0coo\\x08ar'.\nWhat you...
[ 7, 3 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0006652498_file_io_python.txt
Q: How to get just the return value from a function in Python? I'm trying to learn programming through Python and I like to know if it's possible to get just the return value of a function and not its other parts. Here's the code: Let's say, this is the main function: variable_a = 5 while variable_a > 0 : ...
How to get just the return value from a function in Python?
I'm trying to learn programming through Python and I like to know if it's possible to get just the return value of a function and not its other parts. Here's the code: Let's say, this is the main function: variable_a = 5 while variable_a > 0 : input_user = raw_input(": ") if input_user == "A": ...
[ "The printing of \"Hello world\" is what's known as a side effect - something produced by the function which is not reflected in the return value. What you're asking for is how to call the function twice, once to produce the side effect and once to capture the function return value.\nIn fact you don't have to call ...
[ 7, 2 ]
[]
[]
[ "function", "loops", "python" ]
stackoverflow_0006652611_function_loops_python.txt
Q: How to get the current URL of a page in a Django template? I know there is another question with virtually the same title as mine but the solution in that one didn't work for me. My url is like this: http://domain.com/videos/dvd/1/ If I use either {{baseurl}} or {{ request.get_full_path }} I get just this part: h...
How to get the current URL of a page in a Django template?
I know there is another question with virtually the same title as mine but the solution in that one didn't work for me. My url is like this: http://domain.com/videos/dvd/1/ If I use either {{baseurl}} or {{ request.get_full_path }} I get just this part: http://domain.com/videos/ How can I get the entire url? I need t...
[ "You could get it in your view and pass it along into your template context so that it is available to you there.\nhttps://docs.djangoproject.com/en/1.3/ref/request-response/#django.http.HttpRequest.build_absolute_uri\nfull_url = request.build_absolute_uri(None)\n\n# pass full_url into the template context.\n\n" ]
[ 9 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006652584_django_python.txt
Q: AppEngine confusion - CGI, WSGI-compliant? I'm confused. If AppEngine is supposed to allow running of WSGI-employing apps .. # somewhere in a webapp.RequestHandler env = dict(os.environ.items()) for key, value in env.items(): self.response.out.write(key+': '+value+'<br/>') req_uri = wsgiref.util.request_uri(e...
AppEngine confusion - CGI, WSGI-compliant?
I'm confused. If AppEngine is supposed to allow running of WSGI-employing apps .. # somewhere in a webapp.RequestHandler env = dict(os.environ.items()) for key, value in env.items(): self.response.out.write(key+': '+value+'<br/>') req_uri = wsgiref.util.request_uri(env) .. then why does env not contain variables ...
[ "the environ which must contain wsgi specific keys is the environ passed to the wsgi application callable. PEP-333 does not require that this be the value os.environ. CGI applications will find that many of the keys will be in os.environ, because the gateway server has provided them, and the cgi to wsgi gateway i...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "python", "wsgi", "wsgiref" ]
stackoverflow_0006652452_google_app_engine_python_wsgi_wsgiref.txt
Q: Rounded corner border in wxPython Is there any way to design a rounded corner TextCtrl widget? Actually I am new to wxPython and I am used to swing. Like in swing, is their any way in wxPython too to customize the border of the widgets? A: wxPython uses native widgets for the most part. If they don't have a roun...
Rounded corner border in wxPython
Is there any way to design a rounded corner TextCtrl widget? Actually I am new to wxPython and I am used to swing. Like in swing, is their any way in wxPython too to customize the border of the widgets?
[ "wxPython uses native widgets for the most part. If they don't have a rounded version, then the answer is No. However, wxPython supports custom widgets, so you could create your own text control with whatever features you want. \n" ]
[ 0 ]
[]
[]
[ "python", "swing", "wxpython" ]
stackoverflow_0006651098_python_swing_wxpython.txt
Q: Explanation needed regarding explanation of hashable objects Mark Ransom answered on a SO question about hashes here in SO: [...] An object is hashable if it has a hash value which never changes during its lifetime. So by the official definition, anything mutable can't be hashable, even if it has a __hash__...
Explanation needed regarding explanation of hashable objects
Mark Ransom answered on a SO question about hashes here in SO: [...] An object is hashable if it has a hash value which never changes during its lifetime. So by the official definition, anything mutable can't be hashable, even if it has a __hash__() function. My statement about both requirements being necessar...
[ "Instances of this class are hashable if you promise never to reset id or name on them. You can't guarantee that these attributes will never be reset, by the Python principle that \"we are all consenting adults here\", but it would be very bad style to offer methods that reset the attributes that __hash__ relies on...
[ 11 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0006652878_hash_python.txt
Q: Python web service with Twisted This is connected with my previous question Python web service. I'll use Tornado to exchange information between server and clients. There will be one server and N clients. Clients will send information (disk usage, processes etc.) periodically (every 2 minutes or so). The data on c...
Python web service with Twisted
This is connected with my previous question Python web service. I'll use Tornado to exchange information between server and clients. There will be one server and N clients. Clients will send information (disk usage, processes etc.) periodically (every 2 minutes or so). The data on client side will be represented by cus...
[ "I recommend AMP. It's a very simple key-value pair based protocol, ideal for what you're doing. Perspective broker is another alternative.. but it's slightly complicated, and usually unnecessary.\nAMP runs directly over TCP (why bother with HTTP?), the serialization format is both minimal and logical. This makes i...
[ 8, 2, 1, 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0006649143_python_twisted.txt
Q: How does a python method automatically receive 'self' as the first argument? Consider this example of a strategy pattern in Python (adapted from the example here). In this case the alternate strategy is a function. class StrategyExample(object): def __init__(self, strategy=None) : if strategy: ...
How does a python method automatically receive 'self' as the first argument?
Consider this example of a strategy pattern in Python (adapted from the example here). In this case the alternate strategy is a function. class StrategyExample(object): def __init__(self, strategy=None) : if strategy: self.execute = strategy def execute(*args): # I know that the fi...
[ "You need to assign an unbound method (i.e. with a self parameter) to the class or a bound method to the object.\nVia the descriptor mechanism, you can make your own bound methods, it's also why it works when you assign the (unbound) function to a class:\nmy_instance = MyClass() \nMyClass.my_method = my_method\n...
[ 8, 8, 6, 1 ]
[]
[]
[ "methods", "oop", "python", "self" ]
stackoverflow_0006650906_methods_oop_python_self.txt
Q: Python loop through two files, do computation, then output 3 files I have 2 tab delimited files for example: file1: 12 23 43 34 433 435 76 76 file2: 123 324 53 65 12 457 54 32 I would like to loop through these 2 files, comparing every line of file1 with file2 and vice versa. If, for example, the 1st...
Python loop through two files, do computation, then output 3 files
I have 2 tab delimited files for example: file1: 12 23 43 34 433 435 76 76 file2: 123 324 53 65 12 457 54 32 I would like to loop through these 2 files, comparing every line of file1 with file2 and vice versa. If, for example, the 1st number of 1st line in file1 is the same as the 1st number of 2nd line i...
[ "I would suggest that you use the csv module to read your files like so (you might have to mess around with the dialect, see http://docs.python.org/library/csv.html for help:\nimport csv\none = csv.reader(open(file1, 'r'), dialect='excell')\ntwo = csv.reader(open(file2, 'r'), dialect='excell')\n\nthen you might fin...
[ 2, 2, 1, 1 ]
[]
[]
[ "file", "loops", "python" ]
stackoverflow_0006652617_file_loops_python.txt
Q: how do I export my lists into an excel compatible file? Today, on the basis of answers I got here, I wrote this little code to create a random list of 16 elements. import random sources = ['Prone', 'Supine', 'Halfway', 'HalfInv'] result = [random.choice(sources)] repeats = 0 fail = 0 while len(result) < 16: ...
how do I export my lists into an excel compatible file?
Today, on the basis of answers I got here, I wrote this little code to create a random list of 16 elements. import random sources = ['Prone', 'Supine', 'Halfway', 'HalfInv'] result = [random.choice(sources)] repeats = 0 fail = 0 while len(result) < 16: elem = random.choice(sources) repeats = result.count(elem...
[ "If you're looking for a more efficient way to get a randomly ordered list of 4-of-each of your list elements from sources, try random.shuffle(list):\n>>> import random\n>>> random.seed()\n>>> sources = ['Prone', 'Supine', 'Halfway', 'HalfInv']\n>>> copy1 = sources * 4\n>>> copy2 = sources * 4\n>>> copy1 == copy2\n...
[ 1, 0 ]
[]
[]
[ "excel", "python", "python_3.x", "text_files" ]
stackoverflow_0006653881_excel_python_python_3.x_text_files.txt
Q: Using conditions with django template tags/filters? If I'm using {% spaceless %}<html></html>{% endspaceless %} in my templates, but I only want the spaceless function on only when I'm not debugging, how can do this? I tried using {% if %}{% spaceless %}{% endif %} , but that's an error. Thanks! A: I wrote just...
Using conditions with django template tags/filters?
If I'm using {% spaceless %}<html></html>{% endspaceless %} in my templates, but I only want the spaceless function on only when I'm not debugging, how can do this? I tried using {% if %}{% spaceless %}{% endif %} , but that's an error. Thanks!
[ "I wrote just such a tag and put it on Django Snippets: http://djangosnippets.org/snippets/2405/ Enjoy!\n" ]
[ 3 ]
[]
[]
[ "django", "filter", "python", "tags", "templates" ]
stackoverflow_0006654215_django_filter_python_tags_templates.txt
Q: Parsing reStructuredText into HTML I'm making a framework in which I let developers describe their package using reStructuredText. I want to parse that reStructuredText into HTML so I can show it in a GUI. I'm familiar with the excellent Sphinx, but I've never otherwise parsed reStructuredText. I imagined somethin...
Parsing reStructuredText into HTML
I'm making a framework in which I let developers describe their package using reStructuredText. I want to parse that reStructuredText into HTML so I can show it in a GUI. I'm familiar with the excellent Sphinx, but I've never otherwise parsed reStructuredText. I imagined something like a function that takes a string of...
[ "Try something like this:\n>>> from docutils.core import publish_string\n>>> publish_string(\"*anurag*\", writer_name='html')\n\npublish_string accepts a strings and outputs a string or you can use publish_parts to get specific parts of html document e.g.\n>>> from docutils.core import publish_parts\n>>> print publ...
[ 68 ]
[]
[]
[ "docutils", "python", "python_sphinx", "restructuredtext" ]
stackoverflow_0006654519_docutils_python_python_sphinx_restructuredtext.txt
Q: Python pattern-matching. Match 'c[any number of consecutive a's, b's, or c's or b's, c's, or a's etc.]t' Sorry about the title, I couldn't come up with a clean way to ask my question. In Python I would like to match an expression 'c[some stuff]t', where [some stuff] could be any number of consecutive a's, b's, or ...
Python pattern-matching. Match 'c[any number of consecutive a's, b's, or c's or b's, c's, or a's etc.]t'
Sorry about the title, I couldn't come up with a clean way to ask my question. In Python I would like to match an expression 'c[some stuff]t', where [some stuff] could be any number of consecutive a's, b's, or c's and in any order. For example, these work: 'ct', 'cat', 'cbbt', 'caaabbct', 'cbbccaat' but these don't: 'c...
[ "Not thoroughly tested, but I think this should work:\nimport re\n\nwords = ['ct', 'cat', 'cbbt', 'caaabbct', 'cbbccaat', 'cbcbbaat', 'caaccbabbt']\npat = re.compile(r'^c(?:([abc])\\1*(?!.*\\1))*t$')\nfor w in words:\n print w, \"matches\" if pat.match(w) else \"doesn't match\"\n\n#ct matches\n#cat matches\n#cb...
[ 14, 6, 3, 0, 0 ]
[]
[]
[ "pattern_matching", "python", "regex" ]
stackoverflow_0006654147_pattern_matching_python_regex.txt
Q: What is an InstrumentedList in Python? During some set operations I encountered this error in Python: TypeError: unhashable type: 'InstrumentedList' What is an InstrumentedList in Python? I only found a few references related to SQLAlchemy. Is this a SQLAlchemy implementation of lists or something? By the way, i...
What is an InstrumentedList in Python?
During some set operations I encountered this error in Python: TypeError: unhashable type: 'InstrumentedList' What is an InstrumentedList in Python? I only found a few references related to SQLAlchemy. Is this a SQLAlchemy implementation of lists or something? By the way, it happens while doing: set(self.some_list) ...
[ "Yes, SQLAlchemy uses it to implement a list-like object which is aware of insertions and deletions of related objects to an object (via one-to-many and many-to-many relationships).\n", "Yes it's part of SQLAlchemy API. Here is the class reference:\nhttps://docs.sqlalchemy.org/en/20/orm/collection_api.html#sqlal...
[ 12, 8 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006654613_python_sqlalchemy.txt
Q: PDFPY splitting large PDF into multiple page files Apologies if this has been previously asked, but I couldn't find exactly what I am trying to do. I have a large PDF that consists of a batch of 100 2-page forms (each different form has a unique identifier). I would like to split this up so that pages 1-2 are in a...
PDFPY splitting large PDF into multiple page files
Apologies if this has been previously asked, but I couldn't find exactly what I am trying to do. I have a large PDF that consists of a batch of 100 2-page forms (each different form has a unique identifier). I would like to split this up so that pages 1-2 are in a new file, 3-4 in a new file, and so on. How would I edi...
[ "I think this is what you want. I haven't verified it, YMMV, etc.\nfrom pyPdf import PdfFileWriter, PdfFileReader\ninputpdf = PdfFileReader(file(\"abc.pdf\", \"rb\"))\n\nfor i in range(inputpdf.numPages // 2):\n output = PdfFileWriter()\n output.addPage(inputpdf.getPage(i * 2))\n if i * 2 + 1 < inputpdf.n...
[ 2 ]
[]
[]
[ "pdf", "python" ]
stackoverflow_0006655104_pdf_python.txt
Q: How to combine dictionary + list to form one sorted list Okay I have a dictionary that looks like this z = {'J': 50, 'Q': 30, 'F': 10) And a list that looks like this l = [('J', 20), ('Q', 10), ('F', 2)] How do I combine these into either a dictionary OR a list while keeping my original list sorted? I want somet...
How to combine dictionary + list to form one sorted list
Okay I have a dictionary that looks like this z = {'J': 50, 'Q': 30, 'F': 10) And a list that looks like this l = [('J', 20), ('Q', 10), ('F', 2)] How do I combine these into either a dictionary OR a list while keeping my original list sorted? I want something that looks like l = [('J', 20, 50), ('Q', 10, 30), ('F', ...
[ "z = {'J': 50, 'Q': 30, 'F': 10}\nl = [('J', 20), ('Q', 10), ('F', 2)]\nprint [(a, b, z[a]) for a, b in l]\n\ngives:\n[('J', 20, 50), ('Q', 10, 30), ('F', 2, 10)]\n\nBest not to name your list l. From PEP 8:\n\nNames to Avoid\nNever use the characters 'l' (lowercase letter el), 'O' (uppercase\n letter oh), or 'I'...
[ 6, 0, 0 ]
[]
[]
[ "dictionary", "list", "python", "sorting" ]
stackoverflow_0006655255_dictionary_list_python_sorting.txt
Q: How to enable django 1.2 with GAE I added the file appengine_config.py with this instruction webapp_django_version = '1.2' Here is some old stuff from my modules that I now wonder if I can remove? import os os.environ[u'DJANGO_SETTINGS_MODULE'] = u'conf' from google.appengine.dist import use_library use_library...
How to enable django 1.2 with GAE
I added the file appengine_config.py with this instruction webapp_django_version = '1.2' Here is some old stuff from my modules that I now wonder if I can remove? import os os.environ[u'DJANGO_SETTINGS_MODULE'] = u'conf' from google.appengine.dist import use_library use_library('django', '1.2') # Force Django to re...
[ "I'm not sure about the translation import. Everything else can go. I'm guessing that were you need the translation import, it should be done after first importing webapp.\n" ]
[ 2 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0006655442_django_google_app_engine_python.txt
Q: Advantage of using "x *= -1." over "x *= -1"? I'm looking at some Python numpy code, which contains lines like a = 1. # later on, `a` is multiplied by other floats x *= -1. (From what I hopefully correctly understand, 1. is equivalent to 1.0). Is there any reason to do this over a = 1 and x *= -1? I can understan...
Advantage of using "x *= -1." over "x *= -1"?
I'm looking at some Python numpy code, which contains lines like a = 1. # later on, `a` is multiplied by other floats x *= -1. (From what I hopefully correctly understand, 1. is equivalent to 1.0). Is there any reason to do this over a = 1 and x *= -1? I can understand it if I'm going to be dividing a and x by an inte...
[ "It's pretty much for clarity.\nWhile multiplying a float by an integer may incur a small performance hit (for converting the integer to a float), this depends on the compiler and also shouldn't be a large enough penalty to worry about (unless you are doing many such operations).\nHowever, it definitely scores poin...
[ 6, 0, 0 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0006655561_floating_point_python.txt
Q: Python equivalent for write in file like in shell Is there a way to write in file like in shell script but in python by doing something similar to this: cat >> document.txt <<EOF Hello world 1 var=$var Hello world 2 EOF ? A: If I understand the question correctly, you are referring to the here document feature ...
Python equivalent for write in file like in shell
Is there a way to write in file like in shell script but in python by doing something similar to this: cat >> document.txt <<EOF Hello world 1 var=$var Hello world 2 EOF ?
[ "If I understand the question correctly, you are referring to the here document feature in bash. I don't think there is a direct equivalent in Python, but you can enter multi-line strings using \"\"\" (triple quotes) to delimit the start and end, e.g.\n>>> long_string = \"\"\"First\n... Second\n... Third\"\"\"\n>>>...
[ 3, 2 ]
[]
[]
[ "bash", "python", "sh", "shell" ]
stackoverflow_0006655654_bash_python_sh_shell.txt
Q: Break on exception in pydev Is it possible to get the pydev debugger to break on exception? A: This was added by the PyDev author, under Run > Manage Python Exception Breakpoints A: On any exception? If my memory serves me right, in PyDev (in Eclipse) this is possible. EDIT: went through it again, checked pdb...
Break on exception in pydev
Is it possible to get the pydev debugger to break on exception?
[ "This was added by the PyDev author, under Run > Manage Python Exception Breakpoints\n", "On any exception?\nIf my memory serves me right, in PyDev (in Eclipse) this is possible.\n\nEDIT: went through it again, checked pdb documentation, can't find a way to set an exception breakpoint.\nIf I may suggest a really ...
[ 53, 17, 4 ]
[]
[]
[ "debugging", "eclipse", "exception", "pydev", "python" ]
stackoverflow_0000455552_debugging_eclipse_exception_pydev_python.txt
Q: Draw lines with settings for line cap and line join I need a library in Python which can draw lines with an option to choose line cap (e.g. round) and line join (e.g. round). I am looking for something what works like HTML5 Canvas Drawing capabilities. I looked at PIL, AggDraw and did not find the line cap and joi...
Draw lines with settings for line cap and line join
I need a library in Python which can draw lines with an option to choose line cap (e.g. round) and line join (e.g. round). I am looking for something what works like HTML5 Canvas Drawing capabilities. I looked at PIL, AggDraw and did not find the line cap and join options. Thank you. EDIT I found Cairo library, which I...
[ "With PyQt you can easily set those attributes and the application can be without a gui (e.g. just creating an image and saving for example to a file).\nJust check the QPainter documentation about setting antialiasing (with setRenderHints) and the documentation about the QPen class to set cap and join style.\nfrom ...
[ 3, 2 ]
[]
[]
[ "drawing", "html", "image", "python" ]
stackoverflow_0006655297_drawing_html_image_python.txt
Q: Using Ladon in Python 2.6 on windows I have been trying to create a web service out some python scripts, and haven't seemed to have had much luck. I am new to web services in general, but would really like to get this figured out. I'm on Windows 7 and use IIS7. The service also needs to be SOAP. I've read throu...
Using Ladon in Python 2.6 on windows
I have been trying to create a web service out some python scripts, and haven't seemed to have had much luck. I am new to web services in general, but would really like to get this figured out. I'm on Windows 7 and use IIS7. The service also needs to be SOAP. I've read through most posts that have anything to do wit...
[ "I must admit I normally use Linux for almost everything and I haven't tried Ladon on Windows for a while. I will spin up my windows installation later today and see if there is any trouble.\nYou wrote that ladon2.6ctl get's confused. Do you have an exception Traceback?\n", "To summarize the fix for anyone else i...
[ 1, 0 ]
[]
[]
[ "arcgis", "python", "soap", "web_services", "zsi" ]
stackoverflow_0006637956_arcgis_python_soap_web_services_zsi.txt
Q: Getting the key to the maximum component of a tuple in a dictionary of tuples I have a dictionary whose components are all 2-tuples (all integers) and I want to find the key to the tuple with the largest second component. How can I do this in Python 2.6? A: The following will do it (where d is your dictionary): ...
Getting the key to the maximum component of a tuple in a dictionary of tuples
I have a dictionary whose components are all 2-tuples (all integers) and I want to find the key to the tuple with the largest second component. How can I do this in Python 2.6?
[ "The following will do it (where d is your dictionary):\nmax(d.items(), key=lambda(k,v):v[1])[0]\n\nIn this solution, the key (if you pardon the pun) is to use the optional key argument to max.\n", "aix' answer is a good one. You can achieve the same without using lambdas if you prefer, though:\nimport operator\n...
[ 8, 2 ]
[]
[]
[ "dictionary", "max", "python", "tuples" ]
stackoverflow_0006655963_dictionary_max_python_tuples.txt
Q: Parsing .ashx file in python I'm trying to parse the url 'http://www.5min.com/handlers/SitemapHandler.ashx?type=videositemap&page=1' in python 2.7. The problem is when i open the url in urlopen, it doesn't display the source, it displays weird characters. It might be encoded. A: You are parsing the response of ...
Parsing .ashx file in python
I'm trying to parse the url 'http://www.5min.com/handlers/SitemapHandler.ashx?type=videositemap&page=1' in python 2.7. The problem is when i open the url in urlopen, it doesn't display the source, it displays weird characters. It might be encoded.
[ "You are parsing the response of webserver not a .ashx file. Open that url in your browser. That is what python will see when you open it with urlopen.\nFrom opening that these are the headers I got with the response:\nCache-Control:private\nContent-Encoding:gzip\nContent-Length:1100193\nContent-Type:application/...
[ 1 ]
[]
[]
[ "ashx", "parsing", "python" ]
stackoverflow_0006655991_ashx_parsing_python.txt
Q: Sorting by compare values in Python Newbie in Python need help! I have a file with a structure: [timestamp] [level] [source] message which contains following lines(for example): [Wed Oct 11 14:34:52 2000] [error] [client 127.0.0.1] error message [Wed Oct 11 18:56:52 2000] [warning] [client 127.0.0.1] error messag...
Sorting by compare values in Python
Newbie in Python need help! I have a file with a structure: [timestamp] [level] [source] message which contains following lines(for example): [Wed Oct 11 14:34:52 2000] [error] [client 127.0.0.1] error message [Wed Oct 11 18:56:52 2000] [warning] [client 127.0.0.1] error message [Wed Oct 11 22:15:52 2000] [critical] [...
[ "I would divide this into two parts:\n1) Write a function that, given a line of the file, returns the level number. Call this level_number for part 2.\n2) Use that function with the key parameter in your chosen sort call:\nwith open(fname) as f:\n sorted_lines = sorted(f, key=level_number)\n\nThe function for 1) c...
[ 4, 2, 2 ]
[]
[]
[ "compare", "python", "sorting" ]
stackoverflow_0006655707_compare_python_sorting.txt
Q: Using PIL to draw gradients with clipping masks? Does PIL (Python Imaging Library) have methods to draw linear gradients or/and set clipping paths? I've looked everywhere but I can't find any examples that demonstrate how to use either. Or are there any other graphics libraries that can do similar tasks? A: I'm ...
Using PIL to draw gradients with clipping masks?
Does PIL (Python Imaging Library) have methods to draw linear gradients or/and set clipping paths? I've looked everywhere but I can't find any examples that demonstrate how to use either. Or are there any other graphics libraries that can do similar tasks?
[ "I'm not sure about PIL, but since you asked about alternatives as well, here's an example of both linear gradients and clipping regions using wxPython.\nwxPython isn't strictly for image manipulation but it can get the job done.\nimport wx\n\ndef render(dc):\n dc.Clear()\n region = wx.RegionFromPoints([(256,...
[ 1 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0006654312_python_python_imaging_library.txt
Q: Problem with authentication in Pyramid (remember + authenticated_userid) I can't get Pyramid's basic authentication mechanism to work for me. Am I doing it wrong? To debug, I ran this block of code inside one of my views: print '$$$1', pyramid.security.remember(request, 12) print '$$$2', pyramid.security.unauthent...
Problem with authentication in Pyramid (remember + authenticated_userid)
I can't get Pyramid's basic authentication mechanism to work for me. Am I doing it wrong? To debug, I ran this block of code inside one of my views: print '$$$1', pyramid.security.remember(request, 12) print '$$$2', pyramid.security.unauthenticated_userid(request) print '$$$3', pyramid.security.authenticated_userid(req...
[ "\"remember\" just returns headers. You need to set these headers into the response. See also this section of Adding Authorization docs, particularly the code sample directly below in line 21 & 22.\n", "You are probably making the same mistake I was in reading the tutorial as stating that group_finder /only/ re...
[ 4, 1 ]
[]
[]
[ "authentication", "pyramid", "python" ]
stackoverflow_0005419533_authentication_pyramid_python.txt