text
stringlengths
226
34.5k
Why isn't my webapp2 import / Google App Engine "Hello, World" working? Question: While I'm able to get my "Hello, World" program running on Google App Engine (GAE), it only works when I create a version that doesn't rely on the webapp2 import. Why isn't the import working? What I need to do to fix it? Version of helloworld.py that works: print 'Content-Type: text/plain' print '' print 'Hello, World!!' Version of helloworld.py that does not work: import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hello, World!') app = webapp2.WSGIApplication([('/', MainPage)], debug=True) This second version renders as a blank page. I think the problem is that the webapp2 import isn't working. When I run python from within the same directory as my hello world program from the command line I get the following: Brians-MacBook-Air-2:app_engine_hello_world brian$ python Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import webapp2 Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named webapp2 However, I see webapp2.py in the following directory: Brians-MacBook-Air-2:webapp2 brian$ pwd /Users/brian/Repos/app_engine_hello_world/build/webapp2 Also, I'm running python 2.7 installed in the following location: Brians-MacBook-Air-2:app_engine_hello_world brian$ which python /Library/Frameworks/Python.framework/Versions/2.7/bin/python EDIT: Adding my app.yaml file & some other potentially useful info... application: hello-world-cs253 version: 1 runtime: python27 api_version: 1 threadsafe: no handlers: - url: /.* script: helloworld.py I'm using version 1.7.0 - 2012-06-26 of the SDK / GAE Launcher Results are the same in Chrome, Firefox, and Safari Answer: You don't have to install webapp2. When you run the dev_appserver.py with the path to your project directory as the argument, it handles the importing of `webapp2`. Do you have a app.yaml in place, and is it correct? For Python2.7 you need to specify that you're using Python2.7. Runtime should be python27 application: your_app version: 1 runtime: python27 #important api_version: 1 threadsafe: true handlers: - url: /.* script: your_app.py What command are you running to run your program? Do this - you@your-computer:~/GAE_folder$ python dev_appserver.py /path/to/your/project/directory And then open `localhost:8080` on your browser. **EDIT -** I think I know what the problem is. It happened to me too when I first tried out the example given on the site. Add this bit of code to your `helloworld.py` file at the end - def main(): app.run() if __name__=='__main__': main()
python count number of ones in a binary image Question: What is the python module to count number of ones in a binary image ? to rephrase, I have a matrix that has only ones and zeros, it's of numpy array type and I want to know how many ones are there. Answer: You can simply use `sum`: >>> import numpy >>> n = numpy.random.randint(0, 2, size=(3,3)) >>> n array([[1, 0, 1], [0, 1, 1], [1, 1, 1]]) >>> n.sum() 7 Since bools have integer values of 0/1 for False/True, even if the array had elements that weren't 0 or 1 you could use a variant of this trick: >>> n = numpy.random.randint(0, 3, size=(3,3)) >>> n array([[2, 2, 0], [0, 2, 0], [1, 1, 0]]) >>> n == 1 array([[False, False, False], [False, False, False], [ True, True, False]], dtype=bool) >>> (n == 1).sum() 2
Quit function in python program Question: I have a program that runs in Python, without the console present (which is to say, I've compiled it using py2exe). I want people to be able to quit from the main menu, or by a particular key-press in-game (say, Shift+Q). I'm running it, for now, in Windows, though I am working on compiling Linux/Mac versions. Pressing the X button works if there's no 'while' loop running, it seems, and that closes it correctly, otherwise it seems to 'store' the close command wait until the current loop is closed. As for menu options, I've looked thoroughly through documentation and Stackoverflow and tried quit(), exit(), sys.exit() and every combination I can find, but every time I get: Traceback (most recent call last): File "alphatime.pyw", line 61177, in <module> File "alphatime.pyw", line 53970, in place_menu NameError: global name 'sys' is not defined if I try sys.exit, and then: Traceback (most recent call last): File "alphatime.pyw", line 61177, in <module> File "alphatime.pyw", line 53970, in place_menu NameError: global name 'quit' is not defined if I try just "quit()". I've heard about 'Raising' things like a need to close the program, but I'm not clear what that means (I'm new to Python) and how I would go about doing that. So, my question is two-fold. Firstly, is there something I can put in loops for recognizing keypresses something that will recognize the 'X' being clicked, and close? Secondly, is there an appropriate command that will just close the program? I cannot figure out why these commands don't work, and I've had quite a few complaints from people using the program that it crashes, or they have to ctrl-alt-del it, or whatever. I believe import os try: os._exit(return_code) except: pass would work, but at this point, I'm not sure I'm competent enough at python to deploy it appropriately. Thanks in advance! Answer: did you by any chance import sys because that should work!
Django - consecutive dumpdata calls fail, even though work correctly when run separately Question: I've run into an issue trying to set up automatic backups on my site. The problem boils down to the following. I open the Python shell and I call the dumpdata command twice. It **works** for the first time and it returns **empty list** the second time. After that all further dumpdata calls return empty list: >>> python manage.py shell >>> from django.core.management import call_command >>> call_command("dumpdata") [{"pk": 1, (...) // lots of data // >>> call_command("dumpdata") >>> [] To make it work again I need to restart the python shell. Edit: I use Django 1.4 and Python 2.6 Edit2: My current hypothesis is that the problem is related to this issue: <https://code.djangoproject.com/ticket/5423> \- identified 5 years ago and according to Django 1.5 release notes, to-be resolved in the next release. Does anybody have an idea how to workaround this issue without altering the 1.4 framework code being run on the machine? Edit3: However sql dump of the whole database is only 0.5 MB, which makes it rather unprobable that the serialization is running out of memory. And anyway, wouldn't I get an explicit error in such case? Edit4: Mystery solved. As Tomasz Gandor correctly determined, the problem was that shell executes the commands in one transaction, and after one of the commands causes DBError, further DB calls are ignored, as described here: <https://code.djangoproject.com/ticket/10813> . Why the DB error during the first dumpdata wasn't explicitely reported remains a mystery to me. Answer: I see that django is messing something with transactions. I executed a simple example under the debugger: # test.py from django.core.management import call_command call_command("dumpdata") print "\n---" call_command("dumpdata") print And called it like: DJANGO_SETTINGS_MODULE=settings python test.py > log.txt My log.txt ended with "---\n[]\n" After running it in the debugger i found, deep down in `django.core.management.commands.dumpdata.handle()` that model.objects.all() keeps returning []. I called model.objects.iterator(), and got the exception: (Pdb) list(model.objects.iterator()) *** Error in argument: '(model.objects.iterator())' (Pdb) p list(model.objects.iterator()) *** DatabaseError: DatabaseError('current transaction is aborted, commands ignored until end of transaction block\n',) (Pdb) So, I hacked together code, which plays with the transaction itself: # test.py version 2.0! #!/usr/bin/env python # from django.core.management import call_command import django.core.management as mgmt from django.db import transaction ''' try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) ''' @transaction.commit_manually def main(): # mgmt.call_command('dumpdata', use_base_manager=True) mgmt.call_command('dumpdata') transaction.rollback() print print '---' print """ mgmt._commands = None import sys reload(sys.modules['django.core.management.commands.dumpdata']) """ mgmt.call_command('dumpdata') transaction.rollback() print if __name__ == "__main__": main() This spits out the whole database - every time!
basic multiprocessing with python Question: I have found information on multiprocessing and multithreading in python but I don't understand the basic concepts and all the examples that I found are more difficult than what I'm trying to do. I have X independent programs that I need to run. I want to launch the first Y programs (where Y is the number of cores of my computer and X>>Y). As soon as one of the independent programs is done, I want the next program to run in the next available core. I thought that this would be straightforward, but I keep getting stuck on it. Any help in solving this problem would be much appreciated. Edit: Thanks a lot for your answers. I also found another solution using the joblib module that I wanted to share. Suppose that you have a script called 'program.py' that you want to run with different combination of the input parameters (a0,b0,c0) and you want to use all your cores. This is a solution. import os from joblib import Parallel, delayed a0 = arange(0.1,1.1,0.1) b0 = arange(-1.5,-0.4,0.1) c0 = arange(1.,5.,0.1) params = [] for i in range(len(a0)): for j in range(len(b0)): for k in range(len(c0)): params.append((a0[i],b0[j],c0[k])) def func(parameters): s = 'python program.py %g %g %g' % parameters[0],parameters[1],parameters[2]) command = os.system(s) return command output = Parallel(n_jobs=-1,verbose=1000)(delayed(func)(i) for i in params) Answer: You want to use [`multiprocessing.Pool`](http://docs.python.org/library/multiprocessing.html#using- a-pool-of-workers), which represents a "pool" of workers (default one per core, though you can specify another number) that do your jobs. You then submit jobs to the pool, and the workers handle them as they become available. The easiest function to use is [`Pool.map`](http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map), which runs a given function for each of the arguments in the passed sequence, and returns the result for each argument. If you don't need return values, you could also use `apply_async` in a loop. def do_work(arg): pass # do whatever you actually want to do def run_battery(args): # args should be like [arg1, arg2, ...] pool = multiprocessing.Pool() ret_vals = pool.map(do_work, arg_tuples) pool.close() pool.join() return ret_vals If you're trying to call external programs and not just Python functions, use [`subprocess`](http://docs.python.org/library/subprocess.html). For example, this will call `cmd_name` with the list of arguments passed, raise an exception if the return code isn't 0, and return the output: def do_work(subproc_args): return subprocess.check_output(['cmd_name'] + list(subproc_args))
java.io.FileNotFoundException: C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs\localhost_access_log.2012-07-12.txt (Access is denied) Question: I'm trying to test my servlet by running it on Tomcat. However, I get the above error (sometimes this error occurs, but earlier the servlet was running fine). A few facts: 1. I've looked thoroughly at the explanations given by [this similar problem](http://stackoverflow.com/questions/10207033/http-status-404-description-the-requested-resource-is-not-available-apache-t), as well as in [here](http://stackoverflow.com/questions/4728110/the-requested-resource-is-not-available-when-running-tomcat-7-0-after-downl), and [here](http://stackoverflow.com/questions/2280064/tomcat-started-in-eclipse-but-unable-to-connect-to-link-to-http-localhost8085) 2. When I attempt to restart Tomcat (from within Eclipse's "Servers" tab), I get some error log from the console: "SEVERE: Failed to open access log file [~\Tomcat 7.0\logs\localhost_access_log.2012-07-12.txt]" and at the very end of the log output, there's "INFO: SessionListener: sessionDestroyed('E9A6117FDF54752D80A1B9B72F2B83D3') -- see more info at the bottom of this text 1. I've looked at my log files at " C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs" and there is not file with contents similar to the ones in item (2) above 2. I 'deploy' my application through Eclipse (that is, during development, I depend on Eclipse to start Tomcat), only doing a real deployment when I have a stable version of my project by copying the appropriate java class files into Tomcat's /webapps/WEB-INF/classes folder and restarting Tomcat and most importantly, 5\. Typing in "http://localhost:8080" leads me to the Tomcat homepage (so I'm pretty sure the server is running), whereas "http://localhost:8080/MyProjectName/MyServlet" in the browser leads to the error shown this question's title. Any ideas/help? Thank you very much! See more of the error logs here >!Jul 12, 2012 6:18:18 PM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.7.0\jre\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre7/bin/client;C:/Program Files/Java/jre7/bin;C:/Program Files/Java/jre7/lib/i386;C:\Users\Kiptoo\introcs\java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32\wbem;C:\Program Files\MiKTeX 2.8\miktex\bin;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Program Files\Matlab\R2010a\runtime\win32;C:\Program Files\Matlab\R2010a\bin;C:\Program Files\TortoiseSVN\bin;C:\Program Files\QuickTime\QTSystem;C:\Users\Kiptoo\introcs\bin;C:\Users\Kiptoo\introcs\java\bin;C:\Python27;C:\Program Files\Eclipse;;. Jul 12, 2012 6:18:20 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["http-bio-8080"] Jul 12, 2012 6:18:20 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["ajp-bio-8009"] Jul 12, 2012 6:18:20 PM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 2050 ms Jul 12, 2012 6:18:20 PM org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina Jul 12, 2012 6:18:20 PM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/7.0.25 Jul 12, 2012 6:18:20 PM org.apache.catalina.valves.AccessLogValve open SEVERE: Failed to open access log file [C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs\localhost_access_log.2012-07-12.txt] java.io.FileNotFoundException: C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs\localhost_access_log.2012-07-12.txt (Access is denied) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:212) at org.apache.catalina.valves.AccessLogValve.open(AccessLogValve.java:1115) at org.apache.catalina.valves.AccessLogValve.startInternal(AccessLogValve.java:1222) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.StandardPipeline.startInternal(StandardPipeline.java:185) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1144) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:782) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1568) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1558) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) Jul 12, 2012 6:18:20 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\AndroidTest Jul 12, 2012 6:18:20 PM org.apache.catalina.core.StandardContext postWorkDirectory WARNING: Failed to create work directory [C:\Program Files\Apache Software Foundation\Tomcat 7.0\work\Catalina\localhost\AndroidTest] for context [/AndroidTest] Jul 12, 2012 6:18:21 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [175] milliseconds. Jul 12, 2012 6:18:21 PM org.apache.jasper.EmbeddedServletOptions <init> SEVERE: The scratchDir you specified: C:\Program Files\Apache Software Foundation\Tomcat 7.0\work\Catalina\localhost\AndroidTest is unusable. Jul 12, 2012 6:18:21 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\docs Jul 12, 2012 6:18:21 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\examples Jul 12, 2012 6:18:21 PM org.apache.catalina.core.ApplicationContext log INFO: ContextListener: contextInitialized() Jul 12, 2012 6:18:21 PM org.apache.catalina.core.ApplicationContext log INFO: SessionListener: contextInitialized() Jul 12, 2012 6:18:21 PM org.apache.catalina.core.ApplicationContext log INFO: ContextListener: attributeAdded('org.apache.jasper.compiler.TldLocationsCache', 'org.apache.jasper.compiler.TldLocationsCache@ff8399') Jul 12, 2012 6:18:21 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\host-manager Jul 12, 2012 6:18:22 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\manager Jul 12, 2012 6:18:22 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\ROOT Jul 12, 2012 6:18:22 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-bio-8080"] Jul 12, 2012 6:18:22 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-bio-8009"] Jul 12, 2012 6:18:22 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 2225 ms Jul 12, 2012 6:19:22 PM org.apache.catalina.core.ApplicationContext log INFO: SessionListener: sessionDestroyed('E9A6117FDF54752D80A1B9B72F2B83D3') Answer: > only doing a real deployment when I have a stable version of my project by > copying the appropriate java class files into Tomcat's /webapps/WEB- > INF/classes folder and restarting Tomcat Stop right there: you should never put any files into `webapps/WEB-INF` and expect anything good to come of it. Deploy your webapp properly, using a well- accepted packaging such as a WAR file or an exploded-WAR structure into the webapps directory. Second, the problem is obvious: `java.io.FileNotFoundException: C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs\localhost_access_log.2012-07-12.txt (Access is denied)`. Your Tomcat can't write to that file. Just because you are an admin doesn't mean that Tomcat can write to that directory: Tomcat doesn't play well with UAC as far as I know and you are trying to write to `Program Files` which generally requires some ugly UI credentials-entry hack. So, check your file (and directory) permissions. Check the uid of the Tomcat process: make sure they are all good. Finally, consider using `CATALINA_HOME` and `CATALINA_BASE` (read the documentation for how to do that) to fix all of your permissions issues.
Python Multithreading missing data Question: useI am working on a python script to check if the url is working. The script will write the url and response code to a log file. To speed up the check, I am using threading and queue. The script works well if the number of url's to check is small but when increasing the number of url's to hundreds, some url's just will miss from the log file. Is there anything I need to fix? My script is #!/usr/bin/env python import Queue import threading import urllib2,urllib,sys,cx_Oracle,os import time from urllib2 import HTTPError, URLError queue = Queue.Queue() ##print_queue = Queue.Queue() class NoRedirectHandler(urllib2.HTTPRedirectHandler): def http_error_302(self, req, fp, code, msg, headers): infourl = urllib.addinfourl(fp, headers, req.get_full_url()) infourl.status = code infourl.code = code return infourl http_error_300 = http_error_302 http_error_301 = http_error_302 http_error_303 = http_error_302 http_error_307 = http_error_302 class ThreadUrl(threading.Thread): #Threaded Url Grab ## def __init__(self, queue, print_queue): def __init__(self, queue,error_log): threading.Thread.__init__(self) self.queue = queue ## self.print_queue = print_queue self.error_log = error_log def do_something_with_exception(self,idx,url,error_log): exc_type, exc_value = sys.exc_info()[:2] ## self.print_queue.put([idx,url,exc_type.__name__]) with open( error_log, 'a') as err_log_f: err_log_f.write("{0},{1},{2}\n".format(idx,url,exc_type.__name__)) def openUrl(self,pair): try: idx = pair[1] url = 'http://'+pair[2] opener = urllib2.build_opener(NoRedirectHandler()) urllib2.install_opener(opener) request = urllib2.Request(url) request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 5.1; rv:13.0) Gecko/20100101 Firefox/13.0.1') #open urls of hosts resp = urllib2.urlopen(request, timeout=10) ## self.print_queue.put([idx,url,resp.code]) with open( self.error_log, 'a') as err_log_f: err_log_f.write("{0},{1},{2}\n".format(idx,url,resp.code)) except: self.do_something_with_exception(idx,url,self.error_log) def run(self): while True: #grabs host from queue pair = self.queue.get() self.openUrl(pair) #signals to queue job is done self.queue.task_done() def readUrlFromDB(queue,connect_string,column_name,table_name): try: connection = cx_Oracle.Connection(connect_string) cursor = cx_Oracle.Cursor(connection) query = 'select ' + column_name + ' from ' + table_name cursor.execute(query) #Count lines in the file rows = cursor.fetchall() total = cursor.rowcount #Loop through returned urls for row in rows: #print row[1],row[2] ## url = 'http://'+row[2] queue.put(row) cursor.close() connection.close() return total except cx_Oracle.DatabaseError, e: print e[0].context raise def main(): start = time.time() error_log = "D:\\chkWebsite_Error_Log.txt" #Check if error_log file exists #If exists then deletes it if os.path.isfile(error_log): os.remove(error_log) #spawn a pool of threads, and pass them queue instance for i in range(10): t = ThreadUrl(queue,error_log) t.setDaemon(True) t.start() connect_string,column_name,table_name = "user/pass@db","*","T_URL_TEST" tn = readUrlFromDB(queue,connect_string,column_name,table_name) #wait on the queue until everything has been processed queue.join() ## print_queue.join() print "Total retrived: {0}".format(tn) print "Elapsed Time: %s" % (time.time() - start) main() Answer: Python's threading module isn't really multithreaded because of the global interpreter lock, <http://wiki.python.org/moin/GlobalInterpreterLock> as such you should really use `multiprocessing` <http://docs.python.org/library/multiprocessing.html> if you really want to take advantage of multiple cores. Also you seem to be accessing a file simultatnously with open( self.error_log, 'a') as err_log_f: err_log_f.write("{0},{1},{2}\n".format(idx,url,resp.code)) This is really bad AFAIK, if two threads are trying to write to the same file at the same time or almost at the same time, keep in mind, their not really multithreaded, the behavior tends to be undefined, imagine one thread writing while another just closed it... Anyway you would need a third queue to handle writing to the file.
Python client won't reconnect to server Question: I'm sorry for my English, but I've some problems with my software and I need some help. But first of all, some code! Client side: if connessione.connect(host, port) == True: connect = True print 'connection granted' else: connect = False print 'connection refused' while 1: do_some_stuff_with_socket if connect == False: if connessione.connect(host, port) == True: connect = True Server side:(_found on the internet_) import socket port = 4000 host = '127.0.0.1' server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((host, port)) server_socket.listen(5) print "Type 'Q' or 'q' to QUIT" print "Server Waiting for client on port ", port while 1: client_socket, address = server_socket.accept() print "Connection from ", address while 1: server_data = raw_input("--> server: ") if server_data.lower() == 'q': client_socket.send(server_data) client_socket.close() break else: client_socket.send(server_data) client_data = client_socket.recv(1024) if client_data.lower() == 'q': print "Quit from client" client_socket.close() break else: print "<-- client: ", client_data break If I reboot/disconnect the server, the client does not reconnect. I used the `.terminate()` and `.close()` methods to close the socket. Answer: i have solved my problem by calling `.__init__()` method before the `.connect(host, port)` It is not elegant, but it works. Thanks to all
itertools functions not showing up in pydev quick fix Question: Using python 2.7.2 and pydev 2.5.0 and I can't seem to get eclipse to ever suggest any functions from itertools as suggestion. For example quick fixing the given the following: chain([1, 2, 3], [4, 5, 6]) Only gives logilab.common.compat as an option for quick fixing. Answer: This is a known issue: PyDev will currently only discover functions it has the source for (and as itertools is a builtin module which PyDev can't analyze, it won't give you auto-import completions for it... note: it does work though if you try to find the module 'itertools' and complete from it).
DrawingPanel.py Drawing a rubik's cube Question: using python i'd like to draw a rubik's cube based on this picture <http://vixra.files.wordpress.com/2010/0> ... s-cube.jpg this is my current code <http://pastebin.com/MfF07ze4> but i'd like the code to have at least 5 for loops and 5 functions that will aid in the creation of the cube. also i need help with the algorithms in creating the 3 points for the 1x1 cubes of the rubik's cube. Answer: I don't have the `drawingpanel` module, so this is untested: from drawingpanel import * panel = DrawingPanel(600, 600) from math import * import numpy as np class Projection(object): def __init__(self, origin, dx, dy, dz): self.o = np.matrix([origin[0], origin[1], 0.]) self.p = np.matrix([ [dx[0], dx[1], 0.], [dy[0], dy[1], 0.], [dz[0], dz[1], 0.] ]) def proj(self, x, y, z): res = self.o + np.matrix([x, y, z]) * self.p return (res[0,0], res[0,1]) This is a simple isometric 3d-to-2d projection - it takes a 3d coordinate and returns the corresponding 2d screen coordinate. proj = Projection((175,130), ( 50, -24), (-50, -24), ( 0, 70)).proj I create a specific projection - based on your image, I make the front corner of the cube the origin at (175,130). +X runs to the top right corner of the cube, and I make that corner point (3,0,0) to make it easy to subdivide the cube, which means that the screen projection of (1,0,0) is (215, 106), making dx (50, -24); then similarly for +Y to the top left corner and +Z to the bottom front corner. def make_poly_pts(*args): return [coord for pt in args for coord in proj(*pt)] This is a utility function - it takes a list of 3d points and returns a list of [x1, y1, x2, y2, ... xN, yN] coordinates to feed to create_polygon. # allow for a gap between stickers offs = 0.05 ooffs = 1. - offs # draw top face (XY) panel.canvas.create_polygon(*make_poly_pts((0,0,0), (3,0,0), (3,3,0), (0,3,0)), outline='black', fill='black') for i in xrange(3): for j in xrange(3): panel.canvas.create_polygon(*make_poly_pts((i+offs,j+offs,0), (i+ooffs,j+offs,0), (i+ooffs,j+ooffs,0), (i+offs,j+ooffs,0)), outline='black', fill='yellow') ... then the other two faces can be created similarly by swapping axes.
Billing aliens via POS printer and image print Question: I am trying to create a prototype to print bitmap data for a text file to my LAN enabled epson pos printer TM-T88V. While I have no problems to send text and text formatting instructions, I dont understand, what I have to do, to make my printer print the data of the [Arecibo message](http://en.wikipedia.org/wiki/Arecibo_message). first few lines: 00000010101010000000000 00101000001010000000100 10001000100010010110010 10101010101010100100100 00000000000000000000000 00000000000011000000000 00000000001101000000000 00000000001101000000000 00000000010101000000000 00000000011111000000000 00000000000000000000000 11000011100011000011000 10000000000000110010000 11010001100011000011010 11111011111011111011111 00000000000000000000000 00010000000000000000010 00000000000000000000000 00001000000000000000001 The message has 73 rows and 23 columns resulting in 1679 picture elements. Each of this elements is defined by either a 1 for black or a 0 as white and should be printed as a square of 8x8 (or 16x16) dots. the result would result in ![Arecibo message](http://www.satsig.net/seti/message-to-gliese-581.gif) From the printer's specifications: [![enter image description here](http://i.stack.imgur.com/AvZUp.jpg)](http://i.stack.imgur.com/AvZUp.jpg) While — as I said — the connecting and sending to the printer is no problem, I just dont get, what this instruction want to tell me. What would in the case of the Arecibo message be **What numbers do I have to send to the printer? Do I need to send every dot? What does`nL, nH specify the number of dots of the image data in the horizontal direction as (nL + nH × 256).` mean?** Here is my simple Python program I use for prototyping: # -*- coding: utf-8 -*- import struct import socket def sendInstructions(mySocket,l): for x in l: mySocket.send(struct.pack('h', *[x]),1) def emphasizeOn(mySocket): sendInstructions(mySocket,[27,33,48]) def emphasizeOff(mySocket): sendInstructions(mySocket,[27,33,0]) def lineFeed(mySocket,number): for i in range(number): sendInstructions(mySocket,[0x0a,]) def paperCut(mySocket): sendInstructions(mySocket,[29,86,0]) def sendText(mySocket,string): mySocket.send(string.encode('UTF-8')) def main(): mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.connect(('192.168.1.15',9100)) lines = ["Hello,","World!"] emphasizeOff(mySocket) lineFeed(mySocket,2) for l in lines: if lines.index(l) == 0: emphasizeOn(mySocket) else: emphasizeOff(mySocket) sendText(mySocket,l) lineFeed(mySocket,2) lineFeed(mySocket,4) paperCut(mySocket) mySocket.close() if __name__=="__main__": main() Answer: This command generates one horizontal strip of the image at a time. The strip is either 8 or 24 dots tall, depending on the value of m. nL and nH are the low and high bytes of an integer that specifies the width in dots of the horizontal strip of image. That width is computed as nL + nH * 256, so if you wanted the image to be 550 dots wide, then nH=2 and nL=38. The argument d is the bitmap data; if the image strip is 8 dots tall, then each byte represents one column in the strip. If the strip is 24 dots tall, then three bytes represent one column. So let's say you have arecibo in a WxH numpy array of ints, 1 or 0. You would: data = np.zeros((W, H), dtype=np.ubyte) ## (fill in data here) ## Use m=33 since this is apparently the only mode with ## square pixels and also the highest resolution ## (unless it prints too slowly for your liking) m = 33 nH = W // 256 ## note this is integer division, but SO's ## syntax hilighting thinks it looks like a comment. nL = W % 256 ## Divide the array into sections with shape Wx24: for n in range(data.shape[1] // 24): ## Note that if the image height is not a multiple of 24, ## you'll have to pad it with zeros somehow. strip = data[:, n*24:(n+1)*24] ## Convert each strip into a string of bytes: strip = strip.reshape(W, 3, 8) bytes = (strip * (2**np.arange(8)[np.newaxis, np.newaxis, :])).sum(axis=2) # magic byteString = bytes.astype(np.ubyte).tostring() ## Send the command to POS
How to run an xpath over html page in python? Question: I think using lxml library in python can help, but not able to find out how to do this?? Answer: A simple starting point... import lxml.html page = lxml.html.parse('http://www.google.com').getroot() print page.xpath('//a/@href')
Why can urlopen download a Google search page but not a Google Scholar search page? Question: I'm using **Python 3.2.3's** `urllib.request` module to download Google search results, but I'm getting an odd error in that `urlopen` works with links to Google search results, but not Google Scholar. In this example, I'm searching for `"JOHN SMITH"`. This code successfully prints HTML: from urllib.request import urlopen, Request from urllib.error import URLError # Google try: page_google = '''http://www.google.com/#hl=en&sclient=psy-ab&q=%22JOHN+SMITH%22&oq=%22JOHN+SMITH%22&gs_l=hp.3..0l4.129.2348.0.2492.12.10.0.0.0.0.154.890.6j3.9.0...0.0...1c.gjDBcVcGXaw&pbx=1&bav=on.2,or.r_gc.r_pw.r_qf.,cf.osb&fp=dffb3b4a4179ca7c&biw=1366&bih=649''' req_google = Request(page_google) req_google.add_header('User Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20120427 Firefox/15.0a1') html_google = urlopen(req_google).read() print(html_google[0:10]) except URLError as e: print(e) but this code, doing the same for Google Scholar, raises a `URLError` exception: from urllib.request import urlopen, Request from urllib.error import URLError # Google Scholar try: page_scholar = '''http://scholar.google.com/scholar?hl=en&q=%22JOHN+SMITH%22&btnG=&as_sdt=1%2C14''' req_scholar = Request(page_scholar) req_scholar.add_header('User Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20120427 Firefox/15.0a1') html_scholar = urlopen(req_scholar).read() print(html_scholar[0:10]) except URLError as e: print(e) Traceback: Traceback (most recent call last): File "/home/ak5791/Desktop/code-sandbox/scholar/crawler.py", line 6, in <module> html = urlopen(page).read() File "/usr/lib/python3.2/urllib/request.py", line 138, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python3.2/urllib/request.py", line 369, in open response = self._open(req, data) File "/usr/lib/python3.2/urllib/request.py", line 387, in _open '_open', req) File "/usr/lib/python3.2/urllib/request.py", line 347, in _call_chain result = func(*args) File "/usr/lib/python3.2/urllib/request.py", line 1155, in http_open return self.do_open(http.client.HTTPConnection, req) File "/usr/lib/python3.2/urllib/request.py", line 1138, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [Errno -5] No address associated with hostname> I obtained these links by searching in Chrome and copying the link from there. One commenter reported a 403 error, which I sometimes get as well. I presume this is because Google doesn't support scraping of Scholar. However, changing the User Agent string doesn't fix this _or the original problem_ , since I get `URLErrors` most of the time. Answer: [This PHP script](https://code.google.com/p/bioguid/source/browse/trunk/www/scholar_ris.php) seems to indicate you'll need to set some cookies before Google gives you results: /* Need a cookie file (scholar_cookie.txt) like this: # Netscape HTTP Cookie File # http://curlm.haxx.se/rfc/cookie_spec.html # This file was generated by libcurl! Edit at your own risk. .scholar.google.com TRUE / FALSE 2147483647 GSP ID=353e8f974d766dcd:CF=2 .google.com TRUE / FALSE 1317124758 PREF ID=353e8f974d766dcd:TM=1254052758:LM=1254052758:S=_biVh02e4scrJT1H .scholar.google.co.uk TRUE / FALSE 2147483647 GSP ID=f3f18b3b5a7c2647:CF=2 .google.co.uk TRUE / FALSE 1317125123 PREF ID=f3f18b3b5a7c2647:TM=1254053123:LM=1254053123:S=UqjRcTObh7_sARkN */ This is corroborated by [Python recipe for Google Scholar comment](http://code.activestate.com/recipes/523047-search-google- scholar/#c2), which includes a warning that Google detects scripts and will disable you if you use it too prolifically.
python example for reading multiple protobuf messages from a stream Question: I'm working with data from spinn3r, which consists of multiple different protobuf messages serialized into a byte stream: <http://code.google.com/p/spinn3r-client/wiki/Protostream> "A protostream is a stream of protocol buffer messages, encoded on the wire as length prefixed varints according to the Google protocol buffer specification. The stream has three parts: a header, the payload, and a tail marker." This seems like a pretty standard use case for protobufs. In fact, protobuf core distribution provides CodedInputStream for both C++ and Java. But, it appears that protobuf does not provide such a tool for python -- the 'internal' tools are not setup for this kind of external use: <https://groups.google.com/forum/?fromgroups#!topic/protobuf/xgmUqXVsK-o> So... before I go and cobble together a python varint parser and tools for parsing a stream of different message types: does anyone know of any tools for this? Why is it missing from protobuf? (Or am I just failing to find it?) This seems like a big gap for protobuf, especially when compared to thrift's equivalent tools for both 'transport' and 'protocol'. Am I viewing that correctly? Answer: I looks like the code in the other answer is potentially lifted from [here](https://code.google.com/r/avenka- co1/source/browse/src/python/varint.py?spec=svn2b97a552eb2c39cfe62b62dbc303b6e86c47ec4b&name=series34&r=2b97a552eb2c39cfe62b62dbc303b6e86c47ec4b). Check the licence before using this file but I managed to get it to read `varint32`s using code such as this: import sys import myprotocol_pb2 as proto import varint # (this is the varint.py file) data = open("filename.bin", "rb").read() # read file as string decoder = varint.decodeVarint32 # get a varint32 decoder # others are available in varint.py next_pos, pos = 0, 0 while 1: msg = proto.Msg() # your message type next_pos, pos = decoder(data, pos) msg.ParseFromString(data[pos:pos + next_pos]) if msg.type == proto.Msg.END: # example check for end break # use parsed message pos += next_pos print "done!" This is very simple code designed to load messages of a single type delimited by `varint32`s which describe the next message's size. Watch for the infinite loop and add error handling.
Transform filter function to Python code Question: I'm trying to understand how to transform a filter, in this case a Notch(stopband) filter, to Python but I don't know how. x(n)=-2*x(n)/(-0.9*x(n) -0.9*x(n-1)) Can anyone help me please? Thanks in advance. Answer: If you're using numpy arrays, this should work: x[1:]=-2*x[1:]/(-0.9*x[1:]-0.9*x[:-1]) this changes your array in place, but you could just as easily assign it to a new array. y=-2*x[1:]/(-0.9*x[1:]-0.9*x[:-1]) Note that your algorithm isn't really well defined for the 0th element, so my translation leaves `x[0]` unchanged. **EDIT** To change an iterable to a numpy array: import numpy as np x=np.array(iterable) #pretty easy :) although there could be more efficient ways depending on where "iterable" comes from.
How should I get Open Graph JSON object to pass in facepy class Question: I am trying to configure Open Graph in my app such that, when ever a person click a "link" in it, the app should "post" it on his feeds/ timeline/ activity. (_`I created open graph actions for these features and successfully added meta tags in the page`_). So, I am using `fandjango` and `facepy` to do this job. This is how my code looks.. from facepy import GraphAPI @csrf_exempt @facebook_authorization_required(permissions=["publish_actions"]) def ViewPage (request): access_token = request.facebook.user.oauth_token profile_id = request.facebook.user.facebook_id path = "/%d/feed" %profile_id # How should I get the OpenGraph JSON obj og_data = ?? graph = GraphAPI(access_token) graph.post(path, og_data) ... return render_to_response("view.html", context) How should I get the open graph JSON obj to pass in the above `graph` object as parameter so as to post data in feeds/ timeline/ activity? If this is not the way, how should I do it? **Edit 1:** when I tried graph = GraphAPI(request.facebook.user.oauth_token) graph.post("me/namespace:action") It showed me `OAuthError` Error Loc: C:\Python27\lib\site-packages\facepy\graph_api.py in _parse, line 274 graph = GraphAPI(request.facebook.user.oauth_token) graph.post("me/namespace:action", "object type") It showed me `TypeError` loc: same as previous **Edit 2:** Instead to using `request.facebook.user.oauth_token`, I directly used my [`access token`](https://developers.facebook.com/tools/access_token/) and the code worked.. graph = GraphAPI (my-hard-coded-access-token) graph.post("me/feed", message = "working!") However, when I tried graph.post("me/news.reads", article="working") It showed me error. Answer: > I created open graph actions You shouldn't be using `me/feed` then The OpenGraph calls are as follows me/[app_namespace]:[action_type]?[object_type]=[OBJECT_URL] So, to achieve the same just set the path to `me/[app_namespace]:[action_type]` graph.post( path = 'me/[app_namespace]:[action_type]', [object_type] = '[OBJECT_URL]' ) `og_data` is not a parameter in the call. So if your `object_type` is `recipe` then it would be graph.post(path, recipe) If you want to continue to use `me/feed` then it should be graph.post(path, link) as described at <http://developers.facebook.com/docs/reference/api/user/#posts> * * * You cannot do customs read actions like that, the proper call should be graph.post( path = 'me/news.reads', article = 'http://yourobjecturl/article.html' ) Please read the documentation <http://developers.facebook.com/docs/opengraph/actions/builtin/#read>
error when importing ijson module python Question: I need to parse some large (2 Gb+) files into python. I have tried it with the json module but I get a memory error as its methods all load the files at once. I then moved on into installing ijson which suposedly implements a iterator-based way of parsing the file. However when I run: import ijson I get exception : YAJL shared object not found. Has anyone found a similar issue? any help would be greatly appreciated Regards Answer: Thats an easy one, that is because you haven't installed the YAJL C library! ijson is a wrapper around the YAJL without it won't work.
Why is the unittest's assert methods slower than raw assertion? Question: unittest comes with many assert methods. I did a timeit test on using built-in Python `assert` and comparison operator vs built-in simple unittest assertion. #!/usr/bin/python import timeit s = """\ import unittest class TestRepomanManExtFunctions(unittest.TestCase): def test1(self): someObj = object() newObj = someObj self.assertEqual(someObj, newObj) def test2(self): str1 = '11111111111111111111111111111111111111' str2 = '33333333333333333333333333333333333333' self.assertNotEqual(str1, str2) if __name__ == '__main__': unittest.main() """ t = timeit.Timer(stmt=s) print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) s2 = """\ import unittest class TestRepomanManExtFunctions(unittest.TestCase): def test1(self): someObj = object() newObj = someObj assert someObj == newObj def test2(self): str1 = '11111111111111111111111111111111111111' str2 = '33333333333333333333333333333333333333' assert str1 != str2 if __name__ == '__main__': unittest.main() """ t = timeit.Timer(stmt=s2) print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) The results are yeukhon@yeukhon-P5E-VM-DO:/tests$ python t.py 1203.46 usec/pass 873.06 usec/pass yeukhon@yeukhon-P5E-VM-DO:tests$ vim t.py yeukhon@yeukhon-P5E-VM-DO:tests$ python t.py 1300.33 usec/pass 956.35 usec/pass yeukhon@yeukhon-P5E-VM-DO:tests$ python t.py 1208.82 usec/pass 865.18 usec/pass One advantage of using the unittest's built-in assert methods is that it tells the user what is actually being compared. An example from of my actual tests: ====================================================================== FAIL: test_000_write_to_file_directory_not_exist (__main__.TestRepomanManExtFunctions) Test writing content to a new file whose parent directory ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1224, in patched return func(*args, **keywargs) File "test_ext.py", line 71, in test_000_write_to_file_directory_not_exist self.assertNotEqual(mk_exists.call_args_list, exists_call_list) AssertionError: [call('/tmp/test/fake/')] == [call('/tmp/test/fake/')] Here is using simple `assert X = Y` ====================================================================== FAIL: test_000_write_to_file_directory_not_exist (__main__.TestRepomanManExtFunctions) Test writing content to a new file whose parent directory ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1224, in patched return func(*args, **keywargs) File "test_ext.py", line 72, in test_000_write_to_file_directory_not_exist assert exists_call_list != mk_exists.call_args_list AssertionError Besides this advantage, what other nice things can we do by utilising the built-in `self.assert_*(...)`? Why is the raw faster? I know accessing attribute and checking against a class is generally slower. But I want to know what's going on too? I hope this is a valid question. Thanks Answer: Probably the assert* function is slower because there is overhead in calling it (pushing parameters to stack, calling, popping return address from stack etc.), compared to the assert keyword which is executed inline. The assert* functions have some other nice properties as you have mentioned, like printing the expected and actual value. Are you asking out of curiosity or is this an actual problem? I'd be surprised to see any situation where the speed of asserts is a bottleneck.
Import Local module over global python Question: I have a 2 python files. One is trying to import the second. My problem is that the second is named math.py. I can not rename it. When I attempt to call a function that is located inside math.py, I can not because I end up with the global math module. How would I import my local file instead of the global. I am using Python 2.7, and this is(roughly) my import statment: cstr = "math" command = __import__(cstr) Later I try: command.in_math_py_not_global() **Edit:** a more complete example: def parse(self,string): clist = string.split(" ") cstr= clist[0] args = clist[1:len(clist)] rvals = [] try: command = __import__(cstr) try: rvals.extend(command.main(args)) except: print sys.exc_info() except ImportError: print "Command not valid" Answer: Python processes have a single namespace of loaded modules. If you (or _any other module_) has already loaded the standard `math` module for any reason, then trying to load it again with `import` or `__import__()` will simply return a reference to the already-loaded module. You should be able to verify this using `print id(math)` and comparing with `print id(command)`. Although you've stated that you are unable to change the name of `math.py`, I suggest you can. You are getting the name of the module to load from the user. You can modify this before actually using the `__import__()` function to add a prefix. For example: command = __import__("cmd_" + cstr) Then, rename `math.py` to `cmd_math.py` and you will avoid this conflict.
No autoincrement for Integer Primary key in sqlite3 Question: In the sqlite3 [faq](http://www.sqlite.org/faq.html#q1), it is mentioned that an integer primary key being fed a null value would autoincrement. But this is not happening for me. to replicate, a table in sqlite3, `CREATE TABLE dummy( serial_num INTEGER PRIMARY KEY, name TEXT);` and fill it using python, import sqlite3 as lite con = lite.connect('some.db') cur=con.cursor() data = "someone's name" cur.execute("INSERT INTO dummy VALUES(NULL, ?)", data) con.commit() The first attribute serial_num is being shown blank while the name attribute is fine. When I do `SELECT serial_num FROM dummy` I just get a bunch of blank spaces. What am I doing wrong? Answer: This is one of SQLite's quirks. From the [fine manual](http://www.sqlite.org/lang_createtable.html#primkeyconst): > According to the SQL standard, PRIMARY KEY should always imply NOT NULL. > Unfortunately, due to a long-standing coding oversight, this is not the case > in SQLite. Unless the column is an INTEGER PRIMARY KEY SQLite allows NULL > values in a PRIMARY KEY column. We could change SQLite to conform to the > standard (and we might do so in the future), but by the time the oversight > was discovered, SQLite was in such wide use that we feared breaking legacy > code if we fixed the problem. The documentation on [INTEGER PRIMARY KEY](http://www.sqlite.org/lang_createtable.html#rowid) is a little unclear about what precisely is required for a column to be this special INTEGER PRIMARY KEY that auto-increments but the reality is that the column needs to be NOT NULL if you want to use the NULL value to mean "give me the next auto- incrementing value" when inserting: create table dummy ( serial_num integer primary key not null, name text ); If you leave out the `not null`, you need to do your inserts like this: insert into dummy (name) values (?) to get the auto-increment value for `serial_num`. Otherwise, SQLite has no way of telling the difference between a NULL meaning "give me the next auto- increment value" and a NULL meaning "put a NULL value in `serial_num` because the column allows NULLs".
How do I check lists of numeric data for a certain number using an "if" statement in Python? Question: Currently, I am attempting to retrieve numeric data from different CSV files. I then place that data in lists in Python. However, I'm struggling to get Python to determine if there is a value in each separate list of data that is greater than a certain number. I need to be able to search each list separately for some value at which point Python should return some text of my choice. I'm not sure what I'm missing, but Python doesn't seem to be handling my syntax as I was hoping. import csv stocks = ['JPM','PG','KO','GOOG'] for stock in stocks: Data = open("%sMin.csv" % (stock), 'r') Ticker = [] for row in Data: Ticker.append(row.strip().split(',')) if Ticker > 735: print "%s Minimum" % (stock) I modified the code the other stock became Ticker to remove the confusion. Answer: There are three things wrong, preventing you from getting the result. 1. `stock` is a list of values, so you aren't able to directly do a numeric comparison to the list itself. 2. You are appending lists to the list. So even if you were operating on each value you will be comparing a list to an int. Either figure out which element to append, or add them all appropriately. 3. Find the max value in that list to compare to you int. First, append floats to your list: float(stock_value) Second, figure out which index of your split row is the numeric value. If they are all numeric values, then add them all to the list by extending: # only convert items to float that are not empty strings stock.extend(float(val) for val in row.strip().split(',') if val.strip()) If its say, the first column, add just that one: stock.append(float(row.strip().split(',')[0])) Third, if you simply want to know if a value greater than 735 is in your list, you can simply ask it for the max value of the list: if max(stock) > 735: print "%s Minimum" % (stock)
Python repeating CSV file Question: I'm attempting to load numerical data from CSV files in order to loop through the calculated data of each stock(file) separately and determine if the calculated value is greater than a specific number (731 in this case). However, the method I am using seems to make Python repeat the list as well as add quotation marks around the numbers ('500'), as an example, making them strings. Unfortunately, I think the final "if" statement can't handle this and as a result it doesn't seem to function appropriately. I'm not sure what's going on and why Python what I need to do to get this code running properly. import csv stocks = ['JPM','PG','GOOG','KO'] for stock in stocks: Data = open("%sMin.csv" % (stock), 'r') stockdata = [] for row in Data: stockdata.extend(map(float, row.strip().split(','))) stockdata.append(row.strip().split(',')[0]) if any(x > 731 for x in stockdata): print "%s Minimum" % (stock) Answer: Currently you're adding all columns of each row to a list, then adding to the end of that, the first column of the row again? So are all columns significant, or just the first? You're also loading all data from the file before the comparison but don't appear to be using it anywhere, so I guess you can shortcut earlier... If I understand correctly, your code should be this (or amend to only compare first column). Are you basically writing this? import csv STOCKS = ['JPM', 'PG', 'GOOG', 'KO'] for stock in STOCKS: with open('{}Min.csv'.format(stock)) as csvin: for row in csv.reader(csvin): if any(col > 731 for col in map(float, row)): print '{} minimum'.format(stock) break
Importing from sub-folder hierarchy in python Question: i am trying to import specified modules from test_file hierarchy something like : test_case1.py test_subsuite_2 test_sub_2.1.1.py test_suite2 is it possible to do a run import on this hierarchy /project/main.py /project/test_files test_files folder hierarchy is like this : test_files test_suite1 test_case1.py test_subsuite_1 test_sub1_1.py test_sub1_2.py test_subsuite_2 test_subsuite_2_1 test_sub_2.1.1.py test_sub2_1.py test_sub3_2.py test_suite2 test_case2.py test_subsuite2_1 test_sub21_1.py test_sub21_2.py test_subsuite2_2 test_sub22_1.py test_sub23_2.py Answer: Create an empty file called `__init__.py` in all you folders. Then you can import using `.` as a folder separator. [Documentation here.](http://docs.python.org/tutorial/modules.html#packages)
Python: Put values of variables into a new dictionary Question: I am looking for a solution to put the content of 2 variables into a dictionary. One variable should serve as the key, the other as the value. Here's my code: dom = parseString(data) macro=dom.getElementsByTagName('macro') for node in macro: d={} id_name=node.getElementsByTagName('id')[0].toxml() id_data=id_name.replace('<id>','').replace('</id>','') print (id_data) cl_name=node.getElementsByTagName('cl2')[0].toxml() cl_data=cl_name.replace('<cl2>','').replace('</cl2>','') print (cl_data) I would like to have a dictionary with id_data as the keys, and cl_data as the values without overwriting the old data when appending. How do I go on about this? Thanks in advance for any help! Answer: from collections import defaultdict d=defaultdict(list) dom = parseString(data) macro=dom.getElementsByTagName('macro') for node in macro: id_name=node.getElementsByTagName('id')[0].toxml() id_data=id_name.replace('<id>','').replace('</id>','') print (id_data) cl_name=node.getElementsByTagName('cl2')[0].toxml() cl_data=cl_name.replace('<cl2>','').replace('</cl2>','') print (cl_data) d[id_data].append(cl_data) The keys of `d` are the various `id_data`s, and the elements are lists with elements corresponding to each `id_data` found, in order. Of course, if you can be sure that all the `id_data`s are unique, you can use a regular dictionay: d={} for node in macro: ... d[id_data]=cl_data This differs from your original code in that I pulled the dictionary constructor out of the loop (You don't want to replace your dictionary each time in the loop) and actually I actually insert the elements into the `dict` although I'm guessing you did that too, you just don't show it.
django.core.exceptions.ImproperlyConfigured: App with label test could not be found? Question: I have a project structure as myApp/ apps/ tests/ __init__.py tests.py The `tests.py` looks as follows from django.test import TestCase class VideoTest(TestCase): def test_video_insert(self): self.assertTrue(true) When I try to test this from command-line, I do dirBeforeMyApp$python manage.py test test.VideoTest --settings=myApp.settings.dev I see the following error File "/Users/user/code/p/virtualenv/myApp/lib/python2.7/site-packages/django/db/models/loading.py", line 152, in get_app raise ImproperlyConfigured("App with label %s could not be found" % app_label) django.core.exceptions.ImproperlyConfigured: App with label test could not be found What is that I am not doing right here? Answer: well your app is called tests, plural.. You might want to avoid that name for obvious reasons anyway
Python: script to clean windows disk after % usage Question: I created a python script for cleaning old files on a windows disk. Now I want to improve that script and check if I went over a predefined disk usage and then delete files ... how I can do it? Here's my code: import os, time path = r"f:\backup" now = time.time() for f in os.listdir(path): if os.stat(f).st_mtime < now - 180 * 86400: if os.path.isfile(f): os.remove(os.path.join(path, f)) I need it because I've configured a backup of my computer on external disk and sometimes it can't do the backup because disk is full. Answer: I would recommend checking out this answer: [Cross-platform space remaining on volume using python](http://stackoverflow.com/questions/51658/cross-platform-space- remaining-on-volume-using-python) The nt implementation of the os module does not include the statvfs attribute, so you'd need to recreate that functionality using c_types.
python: display elapsed time on shell Question: When I run my Python script, there is some function that takes up to a few minutes to complete, so I want to display on the shell some kind of timer that informs the user on the time elapsed. Is there any such thing already ready to use in Python? Answer: One simplistic way is to include a clock in your [`sys.ps1`](http://docs.python.org/2/library/sys.html?highlight=sys.ps1#sys.ps1) prompt (the thing that normally defines the `>>>` prompt) From the documentation for [`sys.ps1`](http://docs.python.org/2/library/sys.html?highlight=sys.ps1#sys.ps1): > If a non-string object is assigned to either variable, its `str()` is re- > evaluated each time the interpreter prepares to read a new interactive > command; this can be used to implement a dynamic prompt. In [`~/.local/usercustomize.py`](http://www.doughellmann.com/PyMOTW/site/) (or more accurately, in whatever folder `python -c 'import site; print site.USER_BASE'` displays), you can add: import sys import datetime class ClockPS1(object): def __repr__(self): now = datetime.datetime.now() return str(now.strftime("%H:%M:%S >>> ")) sys.ps1 = ClockPS1() Then your prompt will look like this: 16:26:24 >>> import time 16:26:27 >>> time.sleep(10) 16:26:40 >>> It's not perfect, as the last time will be when the prompt appeared, not when the line was executed, but it might be of help. You could easily make this display the time in seconds between `__repr__` invokations, and show that in the prompt.
Python MemoryError when storing saved lists Question: I am new to python, so I apologize if this example is trivial. I am trying to write a simple script that will pase and extract parts of two large datafiles (~40gb each) into one resulting file with a slightly altered format. I originally tried to use readlines(), but that reads all of the files into memory, and our instance only has 28gb of memory. Using the sizehint parameter only parses a portion of the file. I am now iterating over the file. The problem is that I store the output of the text parsing in three lists that grow to be rather large, eclipsing the available memory. I thought this would just switch to using the swap, which would be fine, but it instead just exits with a "MemoryError". This works fine with small sample files, but chokes on our actual data. The script: import sys a = [] b = [] c = [] file1 = open(sys.argv[1],"r") for line in file1: if '@' in line: a.append(line.lstrip('@').rstrip('\n')) b.append(file1.next().rstrip('\n')) file1.close() file2 = open(sys.argv[2],"r") for line in file2: if '@' in line: c.append(file2.next().rstrip('\n')) file2.close() file3 = open(sys.argv[3],"w") for i in xrange(len(a)): file3.write("".join([">",a[i],'\n',b[i],":",c[i],"\n"])) What I have found online suggests creating some sort of database to store the variables, but that shouldn't be required. Do you have any ideas how I should deal with this? For completeness, this is what I'm trying to do (from our example test-data: file1: @Read.Salmonella_paratyphi_A_chromosome.29004.4835/1 TCGTGTACAGCATTCTTTATAGTGGAACGGTGACCGTACCGCAAAGCTGCGAAATCAACGCCGGACKIPPTCGTAG + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA file2: @Read.Salmonella_paratyphi_A_chromosome.29004.4835/1 TCGTGTACAGCATTCTTTATAGTGGAACGGTGACCGTACCGCAAAGCTGCGAAATCAACGCCGGACAAACGATTCT + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA file3 (output): >Read.Salmonella_paratyphi_A_chromosome.29004.4835/1 TCGTGTACAGCATTCTTTATAGTGGAACGGTGACCGTACCGCAAAGCTGCGAAATCAACGCCGGACKIPPTCGTAG:TCGTGTACAGCATTCTTTATAGTGGAACGGTGACCGTACCGCAAAGCTGCGAAATCAACGCCGGACAAACGATTCT Answer: Instead of parsing the files into the arrays (`a`, `b` and `c`), can you write into the file as you parse the files? Something like this pseudo'ish code: def get_line_with_at(a): while a: line = a.readline() if "@" in line: return line.strip() # Open all file handles a, b, c = [open(sys.argv[x + 1]) for x in range(3)] out = open(sys.argv[4]) while a and b and c: # Repeat until a, b, and file handles are exhausted chunk1 = get_line_with_at(a) chunk2 = b.next().strip() chunk3 = get_line_with_at(c) out.write( ">%s\n%s:%s\n" % (chunk1, chunk2, chunk3)) That way you should only have to load very little into memory (theoretically 4 file handles and the contents of the current lines)
Python - Facebook API - Need a working example Question: Ok, so i've googled around, i've found threads here on stackoverflow and i've checked the official Facebook wiki and.. and what not.. I now hope that one of you guys sits on a Facebook API sample code for Python. This is what i've got so far and all i get is "Invalid Signature" via PyFacebook which appears to be a dead project: from facebook import Facebook api_key = '123456789______' secret = '<proper secret key>' OTK = 'XXXXX' # <-- You get this from: https://www.facebook.com/code_gen.php?v=1.0&api_key=123456789______ long_term_key = None fb = Facebook(api_key, secret) def generate_session_from_onetime_code(fb, code): fb.auth_token = code return fb.auth.getSession() if not long_term_key: long_term_key = generate_session_from_onetime_code(fb, OTK)['session_key'] print 'Replace None with this in the .py file for long_term_key:' print long_term_key fb.session_key = long_term_key fb.uid = 000000001 # <-- Your user-id fb.signature = api_key # <-- This doesn't work at all, MD5 of what? #fb.validate_signature(fb) # <-- doesn't work either, prob need to pass MD5 handle? print fb.friends.get() # <-- Generates "Invalid Signature" "all" i want, is to retrieve my friends list for now, if there's a better API point me in the right direction but Facebook has officially declared their own Python SDK dead and pyfacebook is almost working for me but not quite.. So, please help. Answer: The [unofficial fork of the python sdk](https://github.com/pythonforfacebook/facebook-sdk) is still working fine for me. To retrieve your friends, generate an access token here: <https://developers.facebook.com/tools/access_token/> Limitations: * A user access token with user_friends permission is required to view the current person's friends. * This will only return any friends who have used (via Facebook Login) the app making the request. * If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person. Code > > import facebook > > token = 'your token' > > graph = facebook.GraphAPI(token) > profile = graph.get_object("me") > friends = graph.get_connections("me", "friends") > > friend_list = [friend['name'] for friend in friends['data']] > > print friend_list >
matching headers in fasta files with python Question: I have two files: the first is a fasta file with a header and sequence and the second is composed of only headers. File_1: >DF94KKQ1|265|D0M1LACXX|3|2103|4637|10742|1|N|0|TGACCA TTCCAAAGAAACATGGAAGACCCAGGACTTGGAGGCACCAGGCACCAGCACACAGGGGTA GGCACATGGCATGGTGTTGGTTGAAGTCTACTTTTCCCACC >DF94KKQ1|265|D0M1LACXX|3|2103|4565|10742|1|N|0|TGACCA TTAATTTTTTCAGGCAAGTTTTGTGGATTTCAGTGTGTAAGTCTTTCACCTCTTTGGTTA AATTTATTCCTATGTATTTTATTCCTTTAGATGCTATTATG >DF94KKQ1|265|D0M1LACXX|3|2103|4565|10742|2|N|0|TGACCA TTAATTTTTTCAGGCAAGTTTTGTGGATTTCAGTGTGTAAGTCTTTCACCTCTTTGGTTA AATTTATTCCTATGTATTTTATTCCTTTAGATGCTATTATG File_2: >DF94KKQ1|265|D0M1LACXX|3|2103|4565|10742|2|N|0|TGACCA >DF94KKQ1|265|D0M1LACXX|3|2103|4668|10746|1|N|0|TGACCA >DF94KKQ1|265|D0M1LACXX|3|2103|4668|10746|2|N|0|TGACCA >DF94KKQ1|265|D0M1LACXX|1|2207|10852|3331|2|N|0|TGACCA I want to match the header in File_2 with anything in File_1 that has the same exact characters up until the 7th '|'. I split the items in File_1 (each section of the header is indexed into a list). Anyline that begins with a '>' is placed into a variable: #!/usr/bin/env python import sys from Bio import SeqIO #Function, split header line into a list def getHeaderInfo(blastLine): myFields = blastLine.strip("\n").split("|") HeaderInfo = myFields[:6] return HeaderInfo input_file = sys.argv[1] #Get input file from the command line inFileName = sys.argv[1] #open the input file inFileHandle = open(inFileName) #loop over the input file line by line for thisLine in inFileHandle.readlines(): if thisLine [0] == '>': print getHeaderInfo(thisLine) HeaderInfo = getHeaderInfo(thisLine) I have been trying to find a method in which I can compare these same indexes in File_2 to return the following output: >DF94KKQ1|265|D0M1LACXX|3|2103|4565|10742|1|N|0|TGACCA TTAATTTTTTCAGGCAAGTTTTGTGGATTTCAGTGTGTAAGTCTTTCACCTCTTTGGTTA AATTTATTCCTATGTATTTTATTCCTTTAGATGCTATTATG >DF94KKQ1|265|D0M1LACXX|3|2103|4565|10742|2|N|0|TGACCA TTAATTTTTTCAGGCAAGTTTTGTGGATTTCAGTGTGTAAGTCTTTCACCTCTTTGGTTA AATTTATTCCTATGTATTTTATTCCTTTAGATGCTATTATG Several of the methods I have tried use an index, however, my key is not unique. How can I take the first six elements and make them my key or is there a better method than the current one I am attempting? Thank you. Answer: Does this do what you want? def make_key(line): return "|".join(line.split("|", 7)[ : 7]) + "|" header_set = set() with open("file_2.txt") as in_f: for line in in_f: header_set.add(make_key(line)) with open("file_1.txt") as in_f, open("file_3.txt", "w") as out_f: accept = False for line in in_f: if line.startswith(">"): key = make_key(line) accept = key in header_set if accept: out_f.write(line)
Problems with Hangman in Pygame Question: I'm trying to find out what is wrong with the folowing code: import pygame, sys, random, linecache from pygame.locals import * #Start Pygame, define Pygame objects pygame.init() hangmanSurfaceObj = pygame.display.set_mode((640,480), 0) clock = pygame.time.Clock() #Define colors redColor = pygame.Color(255,0,0) greenColor = pygame.Color(0,255,0) blueColor = pygame.Color(0,0,255) whiteColor = pygame.Color(255,255,255) blackColor = pygame.Color(0,0,0) tardisBlueColor = pygame.Color(16,35,114) bgColor = whiteColor #Import Images hangmanImage = pygame.image.load('hangmanResources/hangman.png') #Import sounds sadTromboneSound = pygame.mixer.music.load('hangmanResources/sadTrombone.mp3') #Import Font fontObj = pygame.font.Font('hangmanResources/Avenir_95_Black.ttf', 18) #Define global variables currentWord = 0 usrWord = '' screenWord = [] i = 0 currentChar = '' guesses = 0 def terminate(): pygame.quit() sys.exit() def drawRects(tries): if tries<=0: hangmanSurfaceObj.fill(bgColor, pygame.Rect(242,65,65,65)) if tries<=1: hangmanSurfaceObj.fill(bgColor, pygame.Rect(257,90,35,4)) if tries<=2: hangmanSurfaceObj.fill(bgColor, pygame.Rect(261,110,27,1)) if tries<=3: hangmanSurfaceObj.fill(bgColor, pygame.Rect(274,130,1,114)) if tries<=4: hangmanSurfaceObj.fill(bgColor, pygame.Rect(198,160,76,1)) if tries<=5: hangmanSurfaceObj.fill(bgColor, pygame.Rect(275,160,75,1)) if tries<=6: hangmanSurfaceObj.fill(bgColor, pygame.Rect(210,244,64,85)) if tries<=7: hangmanSurfaceObj.fill(bgColor, pygame.Rect(274,244,51,87)) def newGame(players): if players == 1: line_number = random.randint(0, 2283) usrWord = linecache.getline('hangmanResources/words.txt', line_number) usrWord = list(usrWord) del usrWord[-1] print(usrWord) screenWord = ['_']*len(usrWord) print(screenWord) def checkChar(usrWord): print('hi') i=0 addGuess = 1 print(len(usrWord)) while i <= (len(usrWord)-1): print('hi2') if currentChar.lower == usrWord[i]: print('hi3') screenWord[i] = currentChar addGuess = 0 return addGuess newGame(1) while True: gameRunning = 1 while gameRunning==1: for event in pygame.event.get(QUIT): terminate() for event in pygame.event.get(KEYDOWN): if event.key==K_ESCAPE: terminate() else: currentChar = event.unicode guesses +=checkChar(usrWord) print(currentChar) print(screenWord) msg = ''.join(screenWord) msgSurfaceObj = fontObj.render(msg, False, blackColor) msgRectObj = msgSurfaceObj.get_rect() msgRectObj.topleft = (10, 20) hangmanSurfaceObj.blit(msgSurfaceObj, msgRectObj) hangmanSurfaceObj.fill(bgColor) hangmanSurfaceObj.fill(blueColor, pygame.Rect(400,0,640,480)) hangmanSurfaceObj.blit(hangmanImage, (0,0)) if guesses<=7: drawRects(guesses) else: won=0 gameRunning = 0 pygame.display.update() clock.tick(30) newGame(1) It is supposed to be a hangman game with a hanging post showing, letter blanks showing, and a blue rectangle on the right (where game controls will eventually go). When I go to run it the hanging post appears, the blue rectangle on the left appears, and although no errors pop up, the letter blanks don't show up, and there is a strange blue box connected to the corner of the blue rectangle. More importantly, though, the problem that I'm having is that once you enter a character, the string which holds the data for the eventual on-screen output doesn't change. For instance, if the guess word is "Turtle" and I enter "t", then it should change from `['_','_','_','_','_','_']` to `['t','_','_','t','_','_']`, but it doesn't. I used Python 3.1.3 and Pygame 1.9.1. I searched the Python as well as Pygame documentations for the functions that I am using, but unfortunately I could find no recourse. The original file, as well as the resources, can be found [here](http://sourceforge.net/projects/hangman4pygame/files/ "Hangman for Pygame on SourceForge"). Thanks so much! Answer: You are blitting the phrase only during keydown then in every frame you clean the screen. At 30 fps you are lucky if you see a blink of the phrase. You should check the frase at key down but blit the frase on every frame. ... for event in pygame.event.get(KEYDOWN): if event.key==K_ESCAPE: terminate() else: currentChar = event.unicode guesses +=checkChar(usrWord) print(currentChar) print(screenWord) msg = ''.join(screenWord) # Clean background hangmanSurfaceObj.fill(bgColor) # Then blit message msgSurfaceObj = fontObj.render(msg, False, blackColor) msgRectObj = msgSurfaceObj.get_rect() msgRectObj.topleft = (10, 20) hangmanSurfaceObj.blit(msgSurfaceObj, msgRectObj) ... **Edit** About the blue rectangle attached to the control box, it's because you are making the control box 200px wide and then overwriting the first 100px with your drawRects() rountine. You can either make the control box 100px wide: hangmanSurfaceObj.fill(blueColor, pygame.Rect(400,0,640,480)) or modify drawRects() routine so the rects don't overlap the control box.
Connection appears accepted server-side but appears to be refused in my python script Question: I have a python script I am running to add a document to a collection for a remote mongodb database. The file is as follows: from pymongo import Connection ip = 'x.x.x.x' #edited out conn = Connection() db = conn['netmon'] users = db.users print 'number of users: ' + str(users.count()) if users.count() == 0: print 'Please create a new account.' t_user = raw_input('Username:') users.insert({'username':unicode(t_user)}) conn.close() When I run this script, I have some interesting behavior. In the server logs, it appears that the connection is accepted, the query is run, and then the connection is closed. # Mongodb logs 14:27:18 [initandlisten] connection accepted from 108.93.46.75:39558 #1 14:27:18 [conn1] run command admin.$cmd { ismaster: 1 } 14:27:18 [conn1] command admin.$cmd command: { ismaster: 1 } ntoreturn:1 reslen:71 0ms 14:27:18 [conn1] run command netmon.$cmd { count: "users", fields: null, query: {} } 14:27:18 [conn1] Accessing: netmon for the first time 14:27:18 [conn1] command netmon.$cmd command: { count: "users", fields: null, query: {} } ntoreturn:1 reslen:58 10ms 14:27:18 [conn1] end connection 108.93.46.75:39558 However, this is what I get from the python script: # Python error > python testmongo.py Traceback (most recent call last): File "testmongo.py", line 7, in <module> conn = Connection() File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 290, in __init__ self.__find_node() File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 586, in __find_node raise AutoReconnect(', '.join(errors)) pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused charles@charles-mbp:~/Desktop$ python testmongo.py Traceback (most recent call last): File "testmongo.py", line 7, in <module> conn = Connection() File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 290, in __init__ self.__find_node() File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 586, in __find_node raise AutoReconnect(', '.join(errors)) pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused charles@charles-mbp:~/Desktop$ python testmongo.py Traceback (most recent call last): File "testmongo.py", line 7, in <module> conn = Connection() File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 290, in __init__ self.__find_node() File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 586, in __find_node raise AutoReconnect(', '.join(errors)) pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused Some useful information: The remote server is a VPS running on OpenVZ. I know there are compatibility problems related to count() and iterators, but I (assumingly) fixed them by using the --smallfiles option, as well as limiting my nssize to 100. My firewall on both sides are completely open. I've also noticed that in the errors, autoreconnect is trying to connect to localhost, even though I specified a different IP address. Answer: You need to pass the IP - `conn = Connection(ip)`
issue converting python pandas DataFrame to R dataframe for use with rpy2 Question: I am having trouble converting a pandas DataFrame in Python to an R object, for future use in R using rpy2. The new pandas release 0.8.0 (released a few weeks ago) has a function to convert pandas DataFrames to R DataFrames. The problem is in converting the first column of my pandas DataFrame, which consists of python datetime objects (successively, in a time series). The conversion into an R dataframe returns an StrVector of the dates and times, rather than a vector of R datetime-type objects which I believe are called "POSIXct" objects. I know the command to convert a string of the type returned to a POSIXct, using the command "as.POSIXct('yyyy-mm-dd hh:mm:ss')". Unfortunately I have not been able to figure out the way to convert all these strings in the StrVector to POSIXct using python and rpy2. The dates need to be in the POSIXct format to be used with the TTR library in R. Below is the relevant python code: import pandas from pandas import * import pandas.rpy.common as com import rpy2.robjects as robjects r = robjects.r r.library('TTR') #library contains the function ADX, to be used later dataframe = read_csv('file_name', parse_dates = [0], names = ['Date','Col1','Col2','Col3'] #command makes 1st column into datetime.datetime object r_dataframe = com.convert_to_r_dataframe(dataframe) ADX = r['ADX'] #creating a name for an R function in python adx = ADX(r_dataframe) #will not work because the dates in r_dataframe are in a StrVector Further I do not believe that the StrVector can be iterated through to convert each object to a POSIXct object individually, due to the definition of a StrVector. Maybe there is a way to cast a StrVector to a generic one? Any help/insight into this matter is greatly appreciated. I am a novice programmer and have been working on this for a couple hours now to no avail. Thank you! Answer: The reason your `ADX` call fails is because it expects an xts or matrix-like object with 3 columns: High, Low, Close. Your object contains 4 columns. Drop the date column before passing `r_dataframe` to `ADX` and everything should work. You can then add the datetime column back to the `ADX` output. Or, if you can set the `row.names` attribute of your R data.frame to the values of the `Date` column and then remove the `Date` column, you can convert your R data.frame to an xts object by calling `as.xts(r.data.frame)`. Then you can pass that to `ADX` and convert the result back to a pandas DataFrame.
multiprocessing.Process - Variable as function Question: I am using the code below to parallelize the processing of a numpy array. The target function in this case performs a simple linear stretch on the input data. The array is segmented and then fed to the pool in chunks. This is working quite well thanks to the numerous parallel processing with python posts. pool = [multiprocessing.Process(target=linear_stretch, args= (shared_arr,slice(i, i+step), 35, 200, 2.0)) for i in range (0, y, step)] My question is, is it possible to do something like the following: stretch = Linear.linear_stretch() Where I create an object of the function (please correct my vocab!) and then call it in the multiprocessing.Process. The module that the function resides in currently looks like: Linear.py import numpy def linear_stretch(args): #Do some stuff Answer: Yes, like this: stretch = Linear.linear_stretch In Python, functions are already first-class objects and are capable of being manipulated like any other object, or passed by reference to another variable. Note that parentheses after a function or method signals the interpreter to call the function and pass the return value, which is why: stretch = Linear.linear_stretch() will not work as expected.
Django (or other pip package) in PyPy Question: I am attempting to get django working using pypy. I have everything setup and working great under python2.7 and python3.2 is not installed. I then installed pypy and attempted to run django: Traceback (most recent call last): File "app_main.py", line 51, in run_toplevel File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named django I noticed that pypy created its own site-packages folder, so I removed that and made a symlink to the site-packages folder in my python2.7 installation. This made no change. I have also noticed that it is not just a django problem, any pip installed package doesn't work. **python2.7 path:** ['', '/usr/lib/python27.zip', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/lib/python2.7/site-packages', '/usr/lib/python2.7/site-packages/setuptools-0.6c11.egg-info'] **pypy path** ['', '/opt/pypy/lib_pypy/__extensions__', '/opt/pypy/lib_pypy', '/opt/pypy/lib-python/2.7', '/opt/pypy/lib-python/2.7/lib-tk', '/opt/pypy/lib-python/2.7/plat-linux2'] Does anyone have any experience with this? Are symlinks allowed in this situation? If not is there something else that is used instead? I also attempted just copying the django folder into the site-packages folder before deleting it but had no success with that either. Thanks Answer: You really want to create a standalone environment for your web app. I suggest using [buildout](http://www.buildout.org/) or [virtualenv](http://www.virtualenv.org/). Managing system site-packages will bite you everytime. Good luck!
Is it possible to use pyGTK and Monkeyrunner in same script? Question: I started with importing GTK, and monkeyrunner: from com.android.monkeyrunner import MonkeyRunner import gtk ... when I run this with monkeyrunner in the SDK tools, it says `ImportError: No module named gtk`. When I run this with Python, it says `ImportError: No module named com.android.monkeyrunner`. Is there any way to set up a program that uses both modules? Answer: MonkeyRunner is built with Jython and it only has a small subset of the standard modules compiled in. If you would like to use MonkeyRunner with other python packages then you will need to use os.system or something like that in your MonkeyRunner program to call a separate python instance.
Runtime import with with multiple subdirectories in python Question: what is the best way to perform this type of import in python file to be imported which is available in location one/ne_one/one_two/" fielname : two.py def foo(): print "venkatttt!" main file : main.py s = __import__("one.one_one.one_two.two", fromlist=[]) function_class = getattr(s,"one_one") function_class1 = getattr(function_class,"one_two") function_class2 = getattr(function_class1,"two") print s print function_class print function_class1 print function_class2 function_class2.foo() output of this code: <module 'one' from '/opt/auto/src/ex/one/__init__.pyc'> <module 'one.one_one' from '/opt/auto/src/ex/one/one_one/__init__.pyc'> <module 'one.one_one.one_two' from '/opt/auto/src/ex/one/one_one/one_two/__init__.pyc'> <module 'one.one_one.one_two.two' from '/opt/auto/src/ex/one/one_one/one_two/two.py'> venkatttt! i am looking out for the best way to perform this import Answer: From your output, I can see you already have `__init__.py` files in each subdirectory, therefore, you can simply `import` them: $> from one.one_one.one_two.two import foo $> foo() If you want a handle for each module, you can import them separately: $> import one.one_one as function_class $> import one.one_one.one_two as function_class1 $> import one.one_one.one_two.two as function_class2 Finally, you can also define `__all__` in `one/__init__.py` and let this auto- imports happen automatically when `import one` is executed.
Layout of python code Question: I'm trying to learn the best way to arrange/define code. Taking the below as an example, I have to write the tkMessageBox command twice. I did try to create a def within getText() and refer to that, but it didn't work. Questions therefore please 1) How could I arrange the code such that I can place the tkMessageBox command in a def or something and refer to it even within getText() 2) Considering best practice, should this code be layed out differently? If so how/why? Thank you in advance import Tkinter as tk import tkMessageBox import base64 myText = 'empty' def getText(): global myText myText = inputBox.get() entered = "You entered: " + myText encoded = "We encoded: " + base64.encodestring(myText) Button1 = tk.Button(root, command = tkMessageBox.showinfo("Press me", entered)) Button1.pack() Button2 = tk.Button(root, command = tkMessageBox.showinfo("Press me", encoded)) Button2.pack() root.destroy() root = tk.Tk() # Text label simpleTitle = tk.Label(root) simpleTitle['text'] = 'Please enter your input here' simpleTitle.pack() # The entry box widget inputBox = tk.Entry(root) inputBox.pack() # The button widget button = tk.Button(root, text='Submit', command=getText) button.pack() tk.mainloop() Answer: I am not sure if you are asking about [refactoring](http://en.wikipedia.org/wiki/Code_refactoring) your code or not, but the ultimate style guide for laying out/formatting Python code is [**PEP 8 -- Style Guide for Python Code**](http://www.python.org/dev/peps/pep-0008/).
Django nonrel development server doesn't import amazon.api Question: I have a weird problem with Django nonrel's development server: I have installed [Amazon Simple Product API](https://github.com/yoavaviram/python-amazon-simple-product-api/ "Amazon Simple Product API") , and it works fine in the shell, I can import it there, and everything else seems to work fine. But when I try to import it into my website I get this: ImportError at / No module named amazon.apiRequest Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.3 Exception Type: ImportError Exception Value: No module named amazon.api Exception Location: /Users/Paulius/Desktop/Django-nonrel/projects/sort/phone/functions.py in <module>, line 3 Python Executable: /opt/local/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python Python Version: 2.7.2 Python Path: ['/Users/Paulius/Desktop/Django-nonrel/projects/sort', '/Users/Paulius/Desktop/Django-nonrel/projects/sort/djangoappengine/lib', '/usr/local/google_appengine', '/usr/local/google_appengine/lib/antlr3', '/usr/local/google_appengine/lib/enum', '/usr/local/google_appengine/lib/fancy_urllib', '/usr/local/google_appengine/lib/graphy', '/usr/local/google_appengine/lib/grizzled', '/usr/local/google_appengine/lib/httplib2', '/usr/local/google_appengine/lib/ipaddr', '/usr/local/google_appengine/lib/jinja2', '/usr/local/google_appengine/lib/markupsafe', '/usr/local/google_appengine/lib/oauth2', '/usr/local/google_appengine/lib/prettytable', '/usr/local/google_appengine/lib/protorpc', '/usr/local/google_appengine/lib/simplejson', '/usr/local/google_appengine/lib/sqlcmd', '/usr/local/google_appengine/lib/webapp2', '/usr/local/google_appengine/lib/webob', '/usr/local/google_appengine/lib/yaml/lib', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django_cms-2.2-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django_sekizai-0.5-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django_mptt-0.5.2-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/html5lib-0.95-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/South-0.7.4-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django_classy_tags-0.3.4.1-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django_floppyforms-0.4.7-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygeoip-0.2.3-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/six-1.1.0-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/distribute-0.6.27-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/bottlenose-0.4.0-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/python_amazon_simple_product_api-1.1.0-py2.7.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/PIL'] Server time: Tue, 17 Jul 2012 18:11:04 +0000 I'm using the same python version to run both the server and the shell, and I have no idea what's wrong. **Traceback:** Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.3 Python Version: 2.7.2 Installed Applications: ['django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'phone', 'django.contrib.admindocs', 'djangotoolbox', 'autoload', 'dbindexer', 'djangoappengine'] Installed Middleware: ('autoload.middleware.AutoloadMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/Users/Paulius/Desktop/Django-nonrel/projects/sort/django/core/handlers/base.py" in get_response 101. request.path_info) File "/Users/Paulius/Desktop/Django-nonrel/projects/sort/django/core/urlresolvers.py" in resolve 250. for pattern in self.url_patterns: File "/Users/Paulius/Desktop/Django-nonrel/projects/sort/django/core/urlresolvers.py" in _get_url_patterns 279. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/Paulius/Desktop/Django-nonrel/projects/sort/django/core/urlresolvers.py" in _get_urlconf_module 274. self._urlconf_module = import_module(self.urlconf_name) File "/Users/Paulius/Desktop/Django-nonrel/projects/sort/django/utils/importlib.py" in import_module 35. __import__(name) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in Decorate 676. return func(self, *args, **kwargs) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in load_module 1845. return self.FindAndLoadModule(submodule, fullname, search_path) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in Decorate 676. return func(self, *args, **kwargs) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in FindAndLoadModule 1717. description) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in Decorate 676. return func(self, *args, **kwargs) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in LoadModuleRestricted 1660. description) File "/Users/Paulius/Desktop/Django-nonrel/projects/sort/urls.py" in <module> 2. from phone.views import * File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in Decorate 676. return func(self, *args, **kwargs) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in load_module 1845. return self.FindAndLoadModule(submodule, fullname, search_path) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in Decorate 676. return func(self, *args, **kwargs) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in FindAndLoadModule 1717. description) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in Decorate 676. return func(self, *args, **kwargs) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in LoadModuleRestricted 1660. description) File "/Users/Paulius/Desktop/Django-nonrel/projects/sort/phone/views.py" in <module> 9. from functions import * File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in Decorate 676. return func(self, *args, **kwargs) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in load_module 1845. return self.FindAndLoadModule(submodule, fullname, search_path) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in Decorate 676. return func(self, *args, **kwargs) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in FindAndLoadModule 1717. description) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in Decorate 676. return func(self, *args, **kwargs) File "/usr/local/google_appengine/google/appengine/tools/dev_appserver_import_hook.py" in LoadModuleRestricted 1660. description) File "/Users/Paulius/Desktop/Django-nonrel/projects/sort/phone/functions.py" in <module> 3. from amazon.api import AmazonAPI Exception Type: ImportError at / Exception Value: No module named amazon.api Answer: dev_appserever modifies the environment so you don't include libraries in a way that won't be available when you deploy your project onto App Engine. You'll have to put the library in your actual project folder, or at least softlink to it from within your project folder.
Python - SQL Server call not using a transaction Question: I have a simple Python script where I send in a call to a SQL Server 2008 stored procedure which in turn uses bcp through xp_cmdshell. When I call the SP through management console, it works just fine. When I call it from the python script, it hangs up as the execution blocks the tempdb used for the bcp results. Is there a way to make the call from Python without using a transaction (as I think this additional add-on is locking up my call to hang). Here is my script: * * * import pyodbc as p def CallExportFiles(conn, procName): sql = "DECLARE @ret int EXEC @ret = [db].[dbo].[" + procName + "] @I_EMAILPROFILE = N\'SQL_AlertProfile\', @I_EMAILALERTS = N\'[email protected]\', @I_CUSTOMERID = N\'xxx\', @I_ENVIRO = N\'prod\', @I_COAFILENAME = N\'InvoiceGL\', @I_PERSONFILENAME = N\'Person\', @I_DELEGATESFILENAME = N\'Delegates\', @I_VENDORFILENAME = N\'InvoiceVendors\', @I_DIRECTORY = N\'\\\\xxx\\output\\yyy\\\', @I_ARCHIVEDIR = N\'\\\\xxx\\output\\yyy\\ARCHIVE\\\', @I_FAILUREDIR = N\'\\\\xxx\\output\\yyy\\FAILURE\\\' SELECT \'Return Value\' = @ret" dbCursor = conn.cursor() ##Locks on this next execute call dbCursor.execute(sql) dbCursor.commit() if __name__ == '__main__': #connectin to the db with SQL Authentification conn = p.connect(driver = '{SQL Server Native Client 10.0}', server = r'server', database = 'db', uid = 'sa', pwd = 'xxx') if (conn == False): print 'Error, did not connect to the database' else: CallExportFiles(conn, 'sp_export_files') conn.close() * * * The piece that locks up when called in the stored proc is on the execute here (NOTE: This Stored proc works fine called w/ the same string from Management Studio: * * * SELECT CONVERT(varchar(1),'Z') AS [SORT], CONVERT(varchar(64),'GLNumber') AS GLNUMBER, CONVERT(varchar(1000),'GLDescription') AS GLDESCRIPTION, CONVERT(varchar(4),'Type') AS [TYPE], CONVERT(varchar(100),'GLStatusFlag') AS GLSTATUSFLAG, CONVERT(varchar(100),'UDF1') AS UDF1, CONVERT(varchar(100),'UDF2') AS UDF2, CONVERT(varchar(100),'UDF3') AS UDF3, CONVERT(varchar(100),'UDF4') AS UDF4, CONVERT(varchar(100),'UDF5') AS UDF5 INTO ##BCP_Results1 INSERT INTO ##BCP_Results1([SORT],GLNUMBER,GLDESCRIPTION,[TYPE],GLSTATUSFLAG,UDF1,UDF2,UDF3,UDF4,UDF5) SELECT 'A', GLNUMBER, GLDESCRIPTION, [TYPE], GLSTATUSFLAG, UDF1, UDF2, UDF3, UDF4, UDF5 FROM dbname.DBO.GLACCOUNTS set @sqlstring = 'bcp "SELECT GLNUMBER,GLDESCRIPTION,[TYPE],GLSTATUSFLAG,UDF1,UDF2,UDF3,UDF4,UDF5 FROM ##BCP_Results1 ORDER BY [SORT] DESC " queryout '+@I_DIRECTORY+@I_COAFILENAME+'-'+@I_ENVIRO+'-'+@I_CUSTOMERID+'-'+CONVERT(CHAR(10),GETDATE(),23)+'-'+ LEFT(CONVERT(CHAR(5),GETDATE(),114),2)+'-'+ RIGHT(CONVERT(CHAR(5),GETDATE(),114),2)+'.txt -c -t^| -U sa -P xxxx -S xserverx\xdbx' EXECUTE master.dbo.xp_cmdshell @sqlstring drop table ##BCP_Results1 * * * Answer: Change the value of the [autocommit](http://code.google.com/p/pyodbc/wiki/FAQs#Connecting_fails_with_an_error_about_SQL_ATTR_AUTOCOMMIT) property and that should resolve the issue.
askdirectory() changes focus to different window Question: I am using Tkinter to build two windows. One the main one, pressing a button leads to the creation of the second window. This second window does not get focus immediately when it created. That I am able to fix by calling .focus_force(). However, when I call the askdirectory() function from tkFileDialog, the focus changes back to the first window. How can I prevent that focus switch from happening, without simply calling focus_force() all over the place? To replicate problem: from Tkinter import * from tkFileDialog import * class app: def __init__(self, master): Button(master, command = make_new).grid() def make_new(self): root = Tk() new = new_win(root) root.mainloop() #here the focus is on the first window class new_win: def __init__(self, master): f = askdirectory() #even after placing focus on second window, #focus goes back to first window here I am using Python 2.7.3. Thanks! Answer: the little-documented wm_attributes method might help: from Tkinter import * import tkFileDialog root = Tk() top = Toplevel() top.wm_attributes('-topmost', 1) top.withdraw() top.protocol('WM_DELETE_WINDOW', top.withdraw) def do_dialog(): oldFoc = top.focus_get() print tkFileDialog.askdirectory() if oldFoc: oldFoc.focus_set() b0 = Button(top, text='choose dir', command=do_dialog) b0.pack(padx=100, pady=100) def popup(): top.deiconify() b0.focus_set() b1 = Button(root, text='popup', command=popup) b1.pack(padx=100, pady=100) root.mainloop()
Reproduce the Unix cat command in Python Question: I am currently reproducing the following Unix command: cat command.info fort.13 > command.fort.13 in Python with the following: with open('command.fort.13', 'w') as outFile: with open('fort.13', 'r') as fort13, open('command.info', 'r') as com: for line in com.read().split('\n'): if line.strip() != '': print >>outFile, line for line in fort13.read().split('\n'): if line.strip() != '': print >>outFile, line which works, but there has to be a better way. Any suggestions? Edit (2016): This question has started getting attention again after four years. I wrote up some thoughts in a longer Jupyter Notebook [here](https://github.com/jbwhit/one- offs/blob/master/notebooks/2016-09-19_jbw_stackoverflow.ipynb). The crux of the issue is that my question was pertaining to the (unexpected by me) behavior of `readlines`. The answer I was aiming toward could have been better asked, and that question would have been better answered with `read().splitlines()`. Answer: The easiest way might be simply to forget about the lines, and just read in the entire file, then write it to the output: with open('command.fort.13', 'wb') as outFile: with open('command.info', 'rb') as com, open('fort.13', 'rb') as fort13: outFile.write(com.read()) outFile.write(fort13.read()) As pointed out in a comment, this can cause high memory usage if either of the inputs is large (as it copies the entire file into memory first). If this might be an issue, the following will work just as well (by copying the input files in chunks): import shutil with open('command.fort.13', 'wb') as outFile: with open('command.info', 'rb') as com, open('fort.13', 'rb') as fort13: shutil.copyfileobj(com, outFile) shutil.copyfileobj(fort13, outFile)
Python/Django mime multipart email using boundary Question: In Django(with python), how can I build an email that looks as follows: What I need is an e-mail that starts with: Content-Type: multipart/alternative; boundary="=_5f8686714d769f9476ce778798b84ff4" The boundary is the place to put plain text: --=_5f8686714d769f9476ce778798b84ff4 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7bit This e-mail is in HTML-format. Click the following link: http://www.company.nl/enews/7 --=_5f8686714d769f9476ce778798b84ff4 After that I need an related Content-Tye: Content-Type: multipart/related; boundary="=_e49477d06c604958b9b2bc038628a26f" The boundary is the place to put the html --=_e49477d06c604958b9b2bc038628a26f Content-Type: text/html; charset="ISO-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.= w3.org/TR/html4/loose.dtd"> <html style=3D"height: 100%"> <head>/head> <body></body> </html> --=_e49477d06c604958b9b2bc038628a26f Eventually it would look like this: Received: (qmail 6116 invoked by uid 48); 16 Jul 2012 18:00:49 +0200 Date: 16 Jul 2012 18:00:49 +0200 To: [email protected] Subject: Something MIME-Version: 1.0 From: Company <[email protected]> Content-Type: multipart/alternative; boundary="=_5f8686714d769f9476ce778798b84ff4" Message-ID: <[email protected]> --=_5f8686714d769f9476ce778798b84ff4 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7bit This e-mail is in HTML-format. Click the following link: http://www.company.nl/enews/7 --=_5f8686714d769f9476ce778798b84ff4 Content-Type: multipart/related; boundary="=_e49477d06c604958b9b2bc038628a26f" --=_e49477d06c604958b9b2bc038628a26f Content-Type: text/html; charset="ISO-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.= w3.org/TR/html4/loose.dtd"> <html style=3D"height: 100%"> <head>/head> <body></body> </html> --=_e49477d06c604958b9b2bc038628a26f I tried this with Django's EmailMessage(Alternatives), python MimeMultipart but I can't get it in the exact order. Answer: If you are trying to send a plain text and HTML version of an e-mail (where the plain text version just refers to an URL), the [EmailMultiAlternatives](https://docs.djangoproject.com/en/1.4/topics/email/#sending- alternative-content-types) class seems to work fine for me. A slightly modified version of the example from the docs: from django.core.mail import EmailMultiAlternatives subject, from_email, to = 'hello', '[email protected]', '[email protected]' text_content = 'This e-mail is in HTML-format. Click the following link:\n\nhttp://www.company.nl/enews/7' html_content = '<p>This is an <strong>HTML-format</strong> version.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() Results in this email (using the [console backend](https://docs.djangoproject.com/en/1.4/topics/email/#console- backend)): Content-Type: multipart/alternative; boundary="===============2514609180855632526==" MIME-Version: 1.0 Subject: hello From: [email protected] To: [email protected] Date: Wed, 18 Jul 2012 10:31:22 -0000 Message-ID: <[email protected]> --===============2514609180855632526== Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit This e-mail is in HTML-format. Click the following link: http://www.company.nl/enews/7 --===============2514609180855632526== Content-Type: text/html; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit <p>This is an <strong>HTML-format</strong> version.</p> --===============2514609180855632526==-- While it does not have the `multipart/related` Content-Type, it does work both on plain text (showing the link) and HTML clients (showing the HTML version).
Retrieving outlook Contacts via python Question: I am Trying to get Contacts out of `Outlook` using `Python`. The code is : import win32com.client import pywintypes o = win32com.client.Dispatch("Outlook.Application") ns = o.GetNamespace("MAPI") profile = ns.Folders.Item("Outlook") contacts = profile.Folders.Item("Contacts") but its giving error like this: Traceback (most recent call last): File "my_pro.py", line 7, in <module> profile = ns.Folders.Item("Outlook") File "C:\DOCUME~1\Manoj\LOCALS~1\Temp\gen_py\2.7\00062FFF-0000-0000-C000-00000 0000046x0x9x3\_Folders.py", line 70, in Item ret = self._oleobj_.InvokeTypes(81, LCID, 1, (9, 0), ((12, 1),),Index pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, u'Microsoft Of fice Outlook', u'The operation failed. An object could not be found.', None, 0, -2147221233), None) I cant understand why its throwing error as I Do have a profile named `Outlook` Thanks Answer: Here exists a python recipe to read contacts from outlook. Hope it would be useful. He is using GetDefaultFolder instead of Folders.Item function. <http://code.activestate.com/recipes/173216-import-outlook-contacts-using- win32com/>
How to Pass windows full title name with space using Pywinauto in python Question: I wanted to automate Adobe Reader menus, from pywinauto import application app = application.Application() app.start_(r"C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe") so after how to get complete windows title "Adobe Reader" & navigate to File menus Answer: Check the documentation: <http://pywinauto.googlecode.com/hg/pywinauto/docs/index.html> You can use [`MenuItems()`](http://pywinauto.googlecode.com/hg/pywinauto/docs/code/pywinauto.controls.HwndWrapper.html#pywinauto.controls.HwndWrapper.HwndWrapper.MenuItems) to retrieve the menu items of a Dialog
R fitdistr for Beta distribution: which starting parameters? Question: I need to fit my data into a Beta distribution and retrieve the alpha parameter. I'm trying to use R from python (rpy2) and my code looks like: from rpy2 import * from rpy2.robjects.packages import importr MASS = importr('MASS') #myVector is a Numpy array with values between 0 and 1 MASS.fitdistr(myVector,"beta") But I get this error: Error in function (x, densfun, start, ...) : 'start' must be a named list Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/rpy2/robjects/functions.py", line 82, in __call__ return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/rpy2/robjects/functions.py", line 34, in __call__ res = super(Function, self).__call__(*new_args, **new_kwargs) rpy2.rinterface.RRuntimeError: Error in function (x, densfun, start, ...) : 'start' must be a named list I can't seem to find any good documentation for R with detailed examples, so I only found [this](http://stat.ethz.ch/R-manual/R-patched/library/stats/html/Beta.html): > _**start_** A named list giving the parameters to be optimized with initial > values. This can be omitted for some of the named distributions (see > Details). ... Additional parameters, either for densfun or for optim. In > particular, it can be used to specify bounds via lower or upper or both. If > arguments of densfun (or the density function corresponding to a character- > string specification) are included they will be held fixed. I really have no clue as to: * what to put as a starting parameters and how that will affect my estimation * what syntax to use in Python, since `start=list(shape1=0.5, shape2=0.5)` won't do the trick Any hint? Answer: Ok, after a little bit more of digging, I found a solution: from rpy2.robjects import DataFrame starter= DataFrame({'shape1':0.5,'shape2':0.5}) x = MASS.fitdistr(myValues, "beta", start=starter))
Python TCPServer Question: I have a simple question. When I create a python TCPServer for example using the example code : import sys, SocketServer, os from multiprocessing import Pool, Queue class MyTCPHandler(SocketServer.BaseRequestHandler): def handle(self): # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() print "{} wrote:".format(self.client_address[0]) print self.data # just send back the same data, but upper-cased self.request.sendall(self.data.upper()) if __name__ == '__main__': pool = Pool(processes=2) HOST, PORT = "localhost", 9999 server = SocketServer.TCPServer((HOST,PORT), MyTCPHandler ) server.serve_forever() My question is : How can i pass to the function handle on the Class MyTCPHandler the Object Pool ? Thanks Answer: If you want to have a multithreading `TCPServer` you can use the `ThreadingMixIn` mixin class like this: import SocketServer class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass You can also have a fork based TCPServer by using `ForkingMixIn` in the same way as before. More info can be found in the [doc](http://docs.python.org/library/socketserver.html#asynchronous-mixins).
Load and show an image from the web in Python with Gtk 3? Question: I'm writing an app on Ubuntu 12.04 with Python and GTK 3. The problem I have is that I can't figure out how I should do to show a Gtk.Image in my app with an image file from the web. This is as far as I have come: from gi.repository import Gtk from gi.repository.GdkPixbuf import Pixbuf import urllib2 url = 'http://lolcat.com/images/lolcats/1338.jpg' response = urllib2.urlopen(url) image = Gtk.Image() image.set_from_pixbuf(Pixbuf.new_from_stream(response)) I think everything is correct except the last line. Answer: This will work; from gi.repository import Gtk from gi.repository.GdkPixbuf import Pixbuf from gi.repository import Gio import urllib2 url = 'http://lolcat.com/images/lolcats/1338.jpg' response = urllib2.urlopen(url) input_stream = Gio.MemoryInputStream.new_from_data(response.read(), None) pixbuf = Pixbuf.new_from_stream(input_stream, None) image = Gtk.Image() image.set_from_pixbuf(pixbuf)
Correct way to pause Python program Question: I've been using the input function as a way to pause my scripts print("something") wait = input("PRESS ENTER TO CONTINUE.") print("something") is there a formal way to do this? Answer: Seems fine to me (or `raw_input()` in Python 2.X). Alternatively you could use `time.sleep()` if you want to pause for a certain number of seconds. import time print("something") time.sleep(5.5) # pause 5.5 seconds print("something")
Efficient method for getting elementwise types in Python/Pandas Question: Following up on [a previous question](http://stackoverflow.com/questions/11548005/numpy-or-pandas-keeping- array-type-as-integer-while-having-a-nan-value), is there a preferred efficient manner to get the type of each object within a column? This is specifically for the case where the `dtype` of the column is `object` to allow for heterogeneous types among the elements of the column (in particular, allowing for numeric NaN without changing the data type of the other elements to `float`). I haven't done time benchmarking, but I am skeptical of the following immediately obvious way that comes to mind (and variants that might use `map` or `filter`). The use cases of interest need to quickly get info on the types of all elements, so generators and the like probably won't be an efficiency boon here. # df is a pandas DataFrame with some column 'A', such that # df['A'].dtype is 'object' dfrm['A'].apply(type) #Or np.dtype, but this will fail for native types. Another thought was to use the NumPy `vectorize` function, but is this really going to be more efficient? For example, with the same setup as above, I could try: import numpy as np vtype = np.vectorize(lambda x: type(x)) # Gives error without lambda vtype(dfrm['A']) Both ideas lead to workable output, but it's the efficiency I'm worried about. **Added** I went ahead and did a tiny benchmark in IPython. First is for `vtype` above, then for the `apply` route. I repeated it a dozen or so times, and this example run is pretty typical on my machine. The `apply()` approach clearly wins, so is there a good reason to expect that I won't get more efficient than with `apply()`? **For`vtype()`** In [49]: for ii in [100,1000,10000,100000,1000000,10000000]: ....: dfrm = pandas.DataFrame({'A':np.random.rand(ii)}) ....: dfrm['A'] = dfrm['A'].astype(object) ....: dfrm['A'][0:-1:2] = None ....: st_time = time.time() ....: tmp = vtype(dfrm['A']) ....: ed_time = time.time() ....: print "%s:\t\t %s"%(ii, ed_time-st_time) ....: 100: 0.0351531505585 1000: 0.000324010848999 10000: 0.00209212303162 100000: 0.0224051475525 1000000: 0.211136102676 10000000: 2.2215731144 **For`apply()`** In [50]: for ii in [100,1000,10000,100000,1000000,10000000]: ....: dfrm = pandas.DataFrame({'A':np.random.rand(ii)}) ....: dfrm['A'] = dfrm['A'].astype(object) ....: dfrm['A'][0:-1:2] = None ....: st_time = time.time() ....: tmp = dfrm['A'].apply(type) ....: ed_time = time.time() ....: print "%s:\t %s"%(ii, ed_time-st_time) ....: 100: 0.000900983810425 1000: 0.000159025192261 10000: 0.00117015838623 100000: 0.0111050605774 1000000: 0.103563070297 10000000: 1.03093600273 Answer: `Series.apply` and `Series.map` use a specialized Cython method (`pandas.lib.map_infer`) I wrote that is roughly 2x faster than using `numpy.vectorize`.
CryptoJS and Pycrypto working together Question: I'm encrypting a string in a web application using CryptoJS (v 2.3), and I need to decrypt it on the server in Python, so I'm using PyCrypto. I feel like I'm missing something because I can't can it working. Here's the JS: Crypto.AES.encrypt('1234567890123456', '1234567890123456', {mode: new Crypto.mode.CBC(Crypto.pad.ZeroPadding)}) // output: "wRbCMWcWbDTmgXKCjQ3Pd//aRasZ4mQr57DgTfIvRYE=" The python: from Crypto.Cipher import AES import base64 decryptor = AES.new('1234567890123456', AES.MODE_CBC) decryptor.decrypt(base64.b64decode("wRbCMWcWbDTmgXKCjQ3Pd//aRasZ4mQr57DgTfIvRYE=")) # output: '\xd0\xc2\x1ew\xbb\xf1\xf2\x9a\xb9\xb6\xdc\x15l\xe7\xf3\xfa\xed\xe4\xf5j\x826\xde(m\xdf\xdc_\x9e\xd3\xb1' Answer: Here is a version with CryptoJS 3.1.2. Always beware of the following things (use the same in both languages): * Mode of operation (CBC in this case) * Padding (Zero Padding in this case; better use PKCS#7 padding) * Key (the same derivation function or clear key) * Encoding (same encoding for key, plaintext, ciphertext, ...) * IV (generated during encryption, passed for decryption) If a string is passed as the `key` argument to the CryptoJS `encrypt()` function, the string is used to derive the actual key to be used for encryption. If you wish to use a key (valid sizes are 16, 24 and 32 byte), then you need to pass it as a WordArray. The result of the CryptoJS encryption is an OpenSSL formatted ciphertext string. To get the actual ciphertext from it, you need to access the `ciphertext` property on it. The IV must be random for each encryption so that it is semantically secure. That way attackers cannot say whether the same plaintext that was encrypted multiple times is actually the same plaintext when only looking at the ciphertext. JavaScript: var key = CryptoJS.enc.Utf8.parse('1234567890123456'); function encrypt(msgString, key) { // msgString is expected to be Utf8 encoded var iv = CryptoJS.lib.WordArray.random(16); var encrypted = Crypto.AES.encrypt(msgString, key, { iv: iv }); return iv.concat(encrypted.ciphertext).toString(CryptoJS.enc.Base64); } function decrypt(ciphertextStr, key) { var ciphertext = CryptoJS.enc.Base64.parse(ciphertextStr); // split IV and ciphertext var iv = ciphertext.clone(); iv.sigBytes = 16; iv.clamp(); ciphertext.words.splice(0, 4); // delete 4 words = 16 bytes ciphertext.sigBytes -= 16; // decryption var decrypted = CryptoJS.AES.decrypt({ciphertext: ciphertext}, key, { iv: iv }); return decrypted.toString(CryptoJS.enc.Utf8); } Python code: BLOCK_SIZE = 16 key = b"1234567890123456" def pad(data): length = BLOCK_SIZE - (len(data) % BLOCK_SIZE) return data + chr(length)*length def unpad(data): return data[:-ord(data[-1])] def encrypt(message, passphrase): IV = Random.new().read(BLOCK_SIZE) aes = AES.new(passphrase, AES.MODE_CBC, IV) return base64.b64encode(IV + aes.encrypt(pad(message))) def decrypt(encrypted, passphrase): encrypted = base64.b64decode(encrypted) IV = encrypted[:BLOCK_SIZE] aes = AES.new(passphrase, AES.MODE_CBC, IV) return unpad(aes.decrypt(encrypted[BLOCK_SIZE:])) * * * **Other considerations:** It seems that you want to use a passphrase as a key. Passphrases are usually human readable, but keys are not. You can derive a key from a passphrase with functions such as PBKDF2, bcrypt or scrypt. The code above is not fully secure, because it lacks authentication. Unauthenticated ciphertexts may lead to viable attacks and unnoticed data manipulation. Usually the an encrypt-then-MAC scheme is employed with a good MAC function such as HMAC-SHA256.
Integrating in Python using Sympy Question: I am currently using `Sympy` to help me perform mathematical calculations. Right now, I am trying to perform a numerical integration, but keep getting an error any time I run the script. Here is the script: from sympy import * cst = { 'qe':1.60217646*10**-19, 'm0':N(1.25663706*10**-6) } d = 3.6*10**-2 l = 20.3*10**-2 n = 217.0 I = 10.2 # Circum of loops circ = l/n; # Radius r = N( circ/(2*pi) ) # Flux through a ring a distance R from the ceter def flux(rad, I, loopRad): distFromWire = loopRad - rad bPoint = cst['m0']*I/(2*pi*distFromWire) return ( bPoint*2*pi*rad ) # Integrate from r=0 to r=wireRad x = Symbol('x') ig = Symbol('ig') ig = flux(x, I, r) print(ig) integrate(ig*x,x) I am sure there is probably something wrong with the actual physics/math, but right now I just want it to integrate. Here is the output I get when I run the script: 8.05359718208634e-5*x/(-6.28318530717959*x + 0.000935483870967742) Traceback (most recent call last): File "script.py", line 34, in <module> integrate(ig*x,x) File "C:\Python27\lib\site-packages\sympy\utilities\decorator.py", line 24, in threaded_func return func(expr, *args, **kwargs) File "C:\Python27\lib\site-packages\sympy\integrals\integrals.py", line 847, in integrate return integral.doit(deep = False) File "C:\Python27\lib\site-packages\sympy\integrals\integrals.py", line 364, in doit antideriv = self._eval_integral(function, xab[0]) File "C:\Python27\lib\site-packages\sympy\integrals\integrals.py", line 577, in _eval_integral parts.append(coeff * ratint(g, x)) File "C:\Python27\lib\site-packages\sympy\integrals\rationaltools.py", line 42, in ratint g, h = ratint_ratpart(p, q, x) File "C:\Python27\lib\site-packages\sympy\integrals\rationaltools.py", line 124, in ratint_ratpart H = f - A.diff()*v + A*(u.diff()*v).quo(u) - B*u File "C:\Python27\lib\site-packages\sympy\core\decorators.py", line 75, in __sympifyit_wrapper return func(a, sympify(b, strict=True)) File "C:\Python27\lib\site-packages\sympy\polys\polytools.py", line 3360, in __mul__ return f.mul(g) File "C:\Python27\lib\site-packages\sympy\polys\polytools.py", line 1295, in mul _, per, F, G = f._unify(g) File "C:\Python27\lib\site-packages\sympy\polys\polytools.py", line 377, in _unify F = f.rep.convert(dom) File "C:\Python27\lib\site-packages\sympy\polys\polyclasses.py", line 277, in convert return DMP(dmp_convert(f.rep, f.lev, f.dom, dom), dom, f.lev) File "C:\Python27\lib\site-packages\sympy\polys\densebasic.py", line 530, in dmp_convert return dup_convert(f, K0, K1) File "C:\Python27\lib\site-packages\sympy\polys\densebasic.py", line 506, in dup_convert return dup_strip([ K1.convert(c, K0) for c in f ]) File "C:\Python27\lib\site-packages\sympy\polys\domains\domain.py", line 85, in convert raise CoercionFailed("can't convert %s of type %s to %s" % (a, K0, K1)) sympy.polys.polyerrors.CoercionFailed: can't convert DMP([1, 0], ZZ) of type ZZ[_b1] to RR [Finished in 0.3s with exit code 1] EDIT: Alright, so I pulled out the numbers that the program was using and put it in wolfram alpha. Turns out that the integral doesn't converge, hence the error. I guess it WAS just a math error. Answer: It is a very bad idea to use a symbolic library for numerical work. Just use scipy/numpy. That being said, for such a simple integral you could have used sympy. However you should actually use sympy expressions, not dump everything in opaque functions. Firstly, learn how do variables in python work: ig = Symbol('ig') ig = flux(x, I, r) After this operation `ig` is not a Symbol any more, it is just the return value of `flux`. Define all your symbols and then make an expression out of them. The integral is sufficiently simple for sympy to handle it. Finally, integral as simple as `const*x/(x-const)` as in your case should be done by hand, not wasted on software. [EDIT]: I have rewritten it cleanly, and still sympy does not integrate correctly because of a bug. You could report it on the mailing list or issue tracker and they will try to correct it. That being said, the expression is so simple that it can be integrated by hand. [EDIT2]: In [5]: integrate(a*x/(b*x+c), x) Out[5]: ⎛ ⎛ 2 ⎞⎞ ⎜x c⋅log⎝b ⋅x + b⋅c⎠⎟ a⋅⎜─ - ─────────────────⎟ ⎜b 2 ⎟ ⎝ b ⎠
Can I bind multiple servers to the same TCP port? Question: I would expect having multiple servers on the same port would cause problems. In fact I want it to throw an exception when I try to start two servers on the same port. The problem is, it seems more than happy to start multiple servers on the same port. I can have many instances of the following code running just fine with no exceptions. import BaseHTTPServer import SimpleHTTPServer import sys def main(): try: server = BaseHTTPServer.HTTPServer(('127.0.0.1',5000), SimpleHTTPServer.SimpleHTTPRequestHandler) print "On port: " + str(server.socket.getsockname()[1]) except Exception, e: print e server.serve_forever() if __name__ == "__main__": main() All of which claim to be on port 5000. How can I get it to throw an exception if it tries to use a port that is already taken? Edit: This is Python 2.6.4 Edit 2: [http://www.youtube.com/watch?v=rVOG3JdbHAM&feature=youtu.be](http://www.youtube.com/watch?v=rVOG3JdbHAM&feature=youtu.be) Because people seem to think what I am explaining is not possible? Or I am totally misunderstanding people. Either way, this video should clear it up. I start two servers, neither of them print out any exceptions. When I close the first, the second starts working. Why is this happening? I would expect the 2nd server to simply never start and print an exception. Is this not what should happen? Answer: I tried to execute your code and the second instance returned, [Errno 98] Address already in use as it should. Python 2.6 on SuSE Linux. Can check with netstat utility whether port 5000 is really taken?
Which module should I import to use a PyHKEY? Question: I'm attempting to win32api.RegLoadKey part of the pywin32 extension, however, I am assuming I need to create a PyHKEY first. But I don't know which module PyHKEY is in. The documentation is equally useless. <http://docs.activestate.com/activepython/2.4/pywin32/PyHKEY.html> Note also that the documentation which is there does note that a PyHKEY is just a PyHANDLE, which is just an int, but using a int in the call causes Exception: `error: (6, 'RegLoadKey', 'The handle is invalid.')` Any help would be greatly appreciated! A quick update: import win32api handle = int() win32api.RegLoadKey(handle, "tempKey", "C:\\Users\\Default\\NTUSER.dat") Answer: Python is dynamic; you don't "use" types unless you create your own object, otherwise you use objects given to you. [`win32api.RegOpenKeyEx()`](http://docs.activestate.com/activepython/2.4/pywin32/win32api__RegOpenKeyEx_meth.html) will give you a key object you can use, or, as the documentation for `win32api.RegLoadKey()` states, you can use one of 4 predefined constants to load a hive root.
VPython Install Issues Question: I'm trying to import the visual module for 64-bit python. Unfortunately, I keep getting the following error: > ImportError: numpy.core.multiarray failed to import > > Traceback (most recent call last): > > File "C:\python\color_space.py", line 2, in > > > from visual import scene, color, sphere > > > File "C:\Python27\lib\site-packages\visual__init__.py", line 1, in > > > from .visual_all import * > > > File "C:\Python27\lib\site-packages\visual\visual_all.py", line 1, in > > > from vis import version > > > File "C:\Python27\lib\site-packages\vis__init__.py", line 3, in > > > from .cvisual import (vector, dot, mag, mag2, norm, cross, rotate, > > > ImportError: numpy.core.multiarray failed to import I've uninstalled my 64-bit version of python and tried the 32-bit version of python with a 32-bit visual module, to no success. Now I've reverted to 64-bit. Any ideas on how to fix this? Answer: It seems that you may not have numpy installed. You can download it here: <http://www.scipy.org/Download/> Or it might not be in your python directory.
Latitude and Longitude to Address Question: I have about 8000 + Latitudes and Longitudes. I need to extract(reverse code), them to location, possibly city. Initially I checked with Google Maps, but according to their terms we should not hit their services with our scripts. Even the OpenStreetMaps doesnt allow us to hit their servers repeatedly. They have some time limit. So, I downloaded the latitudes and logitudes for locations. I wrote a python script, import tabular as tb import csv citiesLatLongData = tb.tabarray(SVfile="D:/latitude-longitude/citieslatlong.csv") allData = tb.tabarray(SVfile="C:/Users/User/Desktop/alldata.csv") latlonglocs = {'a1':"Car Nicobar",'a2':"Port Blair",'a3':"Hyderabad",'a4':"Kadapa",'a5':"Puttaparthi", 'a6':"Rajahmundry",'a7':"Tirupati",'a8':"Vijayawada",'a9':"Vishakhapatnam",'a10':"Itanagar", 'a11':"Dibrugarh",'a12':"Dispur",'a13':"Guwahati",'a14':"North Lakhimpur",'a15':"Silchar", 'a16':"Gaya",'a17':"Patna",'a18':"Chandigarh",'a19':"Raipur",'a20':"Silvassa", 'a21':"Daman",'a22':"Bawana",'a23':"New Delhi",'a24':"Mormugao",'a25':"Panaji", 'a26':"Ahmedabad",'a27':"Bhavnagar",'a28':"Bhuj",'a29':"Gandhinagar",'a30':"Jamnagar", 'a31':"Kandla",'a32':"Rajkot",'a33':"Vadodara",'a34':"Hisar",'a35':"Bilaspur", 'a36':"Dharamsala",'a37':"Kulu",'a38':"Shimla",'a39':"Jammu",'a40':"Srinagar",'a41':"Jamshedpur", 'a42':"Ranchi",'a43':"Bangalore",'a44':"Belgaum",'a45':"Bellary",'a46':"Hubli Dharwad", 'a47':"Mandya",'a48':"Mangalore",'a49':"Mysore",'a50':"Cochin",'a51':"Kozhikode", 'a52':"Thiruvananthapuram",'a53':"Bingaram Island ",'a54':"Kavaratti",'a55':"Bhopal",'a56':"Gwalior", 'a57':"Indore",'a58':"Jabalpur",'a59':"Khandwa",'a60':"Satna",'a61':"Ahmadnagar", 'a62':"Akola",'a63':"Aurangabad",'a64':"Jalna",'a65':"Kolhapur",'a66':"Mumbai", 'a67':"Nagpur",'a68':"Nasik",'a69':"Pimpri",'a70':"Pune",'a71':"Solapur", 'a72':"Imphal",'a73':"Shillong",'a74':"Aizawl",'a75':"Kohima",'a76':"Bhubaneswar", 'a77':"Jharsuguda",'a78':"Karaikal",'a79':"Mahe",'a80':"Pondicherry",'a81':"Yanam", 'a82':"Amritsar",'a83':"Pathankot",'a84':"Jaipur",'a85':"Jodhpur",'a86':"Kota", 'a87':"Udaipur",'a88':"Gangtok",'a89':"Chennai",'a90':"Coimbatore",'a91':"Madurai", 'a92':"Nagercoil",'a93':"Thiruchendur",'a94':"Thiruvannaamalai",'a95':"Thoothukudi", 'a96':"Tiruchirappalli",'a97':"Tirunelveli",'a98':"Vellore",'a99':"Agartala", 'a100':"Agra",'a101':"Allahabad",'a102':"Bareilly",'a103':"Gorakhpur",'a104':"Jhansi", 'a105':"Kanpur",'a106':"Lucknow",'a107':"Varanasi",'a108':"Dehradun",'a109':"Pantnagar", 'a110':"Kolkata",'a111':"Siliguri"} latlongs = {'a1':[9.15,92.8167],'a2':[11.6667,92.7167],'a3':[17.45,78.4667],'a4':[14.4833,78.8333], 'a5':[14.1333,77.7833],'a6':[16.9667,81.7667],'a7':[13.65,79.4167],'a8':[16.5333,80.8], 'a9':[17.7,83.3],'a10':[27.0833,93.5667],'a11':[27.4833,95.0167],'a12':[26.0833,91.8333], 'a13':[26.1667,91.5833],'a14':[27.2333,94.1167],'a15':[24.8167,92.8],'a16':[24.75,84.95], 'a17':[25.6,85.1],'a18':[30.7333,76.75],'a19':[21.2333,81.6333],'a20':[20.2833,73], 'a21':[20.4167,72.85],'a22':[28.7833,77.0333],'a23':[28.5667,77.1167],'a24':[15.3833,73.8167], 'a25':[15.3833,73.8167],'a26':[23.0333,72.6167],'a27':[21.75,72.2],'a28':[23.25,69.6667], 'a29':[23.3333,72.5833],'a30':[22.4667,70.0667],'a31':[23.0333,70.2167],'a32':[22.3,70.7833], 'a33':[22.3,73.2667],'a34':[29.1667,75.7333],'a35':[31.25,76.6667],'a36':[32.2,76.4], 'a37':[31.9667,77.1],'a38':[31.1,77.1667],'a39':[32.7,74.8667],'a40':[34.0833,74.8167], 'a41':[22.8167,86.1833],'a42':[23.3167,85.3167],'a43':[12.9833,77.5833],'a44':[15.85,74.6167], 'a45':[15.15,76.85],'a46':[15.35,75.1667],'a47':[12.55,76.9],'a48':[12.9167,74.8833], 'a49':[12.3,76.65],'a50':[9.95,76.2667],'a51':[11.25,75.7667],'a52':[8.46667,76.95], 'a53':[10.9167,72.3333],'a54':[10.5833,72.65],'a55':[23.2833,77.35],'a56':[26.2333,78.2333], 'a57':[22.7167,75.8],'a58':[23.2,79.95],'a59':[21.8333,76.3667],'a60':[24.5667,80.8333], 'a61':[19.0833,74.7333],'a62':[20.7,77.0667],'a63':[19.85,75.4],'a64':[19.8333,75.8833], 'a65':[16.7,74.2333],'a66':[19.1167,72.85],'a67':[21.1,79.05],'a68':[19.8933,73.8], 'a69':[18.55,73.8167],'a70':[18.5333,73.8667],'a71':[17.6667,75.9],'a72':[24.7667,93.9], 'a73':[25.55,91.85],'a74':[23.6667,92.6667],'a75':[25.6667,94.1167],'a76':[20.25,85.8333], 'a77':[21.5833,84.08333],'a78':[10.95,79.7833],'a79':[11.7,75.5333],'a80':[11.9333,79.8833], 'a81':[16.7333,82.2167],'a82':[31.6333,74.8667],'a83':[32.2833,75.65],'a84':[26.8167,75.8], 'a85':[29.1667,75.7333],'a86':[25.15,75.85],'a87':[24.5667,73.6167],'a88':[27.3333,88.6167], 'a89':[13,80.1833],'a90':[11.0333,77.05],'a91':[9.83333,78.0833],'a92':[8.16667,77.4333], 'a93':[8.48333,78.1167],'a94':[12.2167,79.0667],'a95':[8.78333,78.1333],'a96':[10.7667,78.7167], 'a97':[8.73333,77.7],'a98':[12.9167,79.15],'a99':[23.8833,91.25],'a100':[27.15,77.9667], 'a101':[25.45,81.7333],'a102':[28.3667,79.4],'a103':[26.75,83.3667],'a104':[29.1667,75.7333], 'a105':[26.4,80.4],'a106':[26.75,80.8833],'a107':[25.45,83],'a108':[30.3167,78.0333], 'a109':[29.0833,79.5],'a110':[22.65,88.45],'a111':[26.6333,88.3167] } for eachOne in allData: for eachTwo in latlongs: eachOne_Coordinates_Latitude = eachOne['COORDINATES-Latitude'] latlongs_eachTwo_Latitude_Plus = int(latlongs[eachTwo][0]) + 0.18 latlongs_eachTwo_Latitude_Minus = int(latlongs[eachTwo][0]) - 0.18 eachOne_Coordinates_Longitude = eachOne['COORDINATES-Longitude'] latlongs_eachTwo_Longitude_Plus = int(latlongs[eachTwo][1]) + 0.18 latlongs_eachTwo_Longitude_Minus = int(latlongs[eachTwo][1]) - 0.18 if ( (eachOne_Coordinates_Latitude < latlongs_eachTwo_Latitude_Plus) and (latlongs_eachTwo_Latitude_Plus > latlongs_eachTwo_Latitude_Minus) ) and ( (eachOne_Coordinates_Longitude < latlongs_eachTwo_Longitude_Plus) and (eachOne_Coordinates_Longitude > latlongs_eachTwo_Longitude_Minus) ): someDict.setdefault((eachOne_Coordinates_Latitude,eachOne_Coordinates_Longitude),[]).append(latlongs[eachTwo]) for each in someDict: print each,':', min(someDict[each]) **MY PROBLEM:** As you know, the latitudes and longitudes that we get from external sources does not exactly match with the latitudes and longitudes that we have. I heard somewhere that they wont match and there will be some error percentage or something. I need some guidance from anyone. I request someone to please point me in the right direction or if you know any packages or scripts that does this. I would be extremely thankful to you. Answer: This sounds a lot like a "Closest point problem". You have N points (cities) and M locations (your 8000 coordinates). For each of the M locations, you want to categorize the location by its closest city. There are a number of solutions for the [Nearest Neighbor Search](http://en.wikipedia.org/wiki/Closest_point_query), but the simplest one is a linear search: function getClosestCity(Coordinate location){ bestCity = cities[0]; foreach(city in cities){ if (distance(bestCity.location, location) < distance(city.location, location)){ bestCity = city; } } return bestCity; }
matplotlib - control capstyle of line collection/large number of lines Question: Similarly to a [previous question](http://stackoverflow.com/questions/11312579/networkx-draw-networkx- edges-capstyle) of mine, I'd like to control the capstyle of lines being drawn using matplotlib. However, I have an extremely large number of lines, and drawing with anything other than a line collection takes way too long. Are there any workarounds to control the capstyle of lines in a line collection in a generic way (or alternatively, super fast ways of drawing a large number of `Line2D` lines). For instance, I've tried using the matplotlib rc settings via: import matplotlib as mpl mpl.rcParams['lines.solid_capstyle'] = 'round' mpl.rcParams['lines.solid_joinstyle'] = 'round' But this doesn't appear to have any affect. From the docstring for `collections.py`: > The classes are not meant to be as flexible as their single element > counterparts (e.g. you may not be able to select all line styles) but they > are meant to be fast for common use cases (e.g. a large set of solid line > segemnts) Which explains _why_ I can't seem to control various parameters, but I still want to do it! I've had a look at the code for the AGG backend (`_backend_agg.cpp`: not that I really understand it), and it appears that line_cap and line_join are controlled by `gc.cap` and `gc.join`, where gc comes from the `GCAgg` class. Does anyone know how one can control this from Python? Am I asking the right question here? Perhaps that are easier ways to control these parameters? Any help is greatly appreciated... I'm desperate to get this working, so even crazy hacks are welcome! Thanks, Carson Answer: I was struggling with the same issue. I ended up plotting a scatter plot on top of my line collection. It's not perfect, but it may work for your application. There's a few subtleties - below is a working example. import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection x = np.random.random(10) y = np.random.random(10) z = np.arange(0,10) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) fig = plt.figure() ax = fig.add_subplot(111) linewidth = 10 cmap = plt.get_cmap('jet') norm = plt.Normalize(np.min(z), np.max(z)) color = cmap(norm(z)) lc = LineCollection(segments, linewidths=linewidth, cmap=cmap, norm=norm) lc.set_array(z) lc.set_zorder(z.tolist()) ax.add_collection(lc) ax.scatter(x,y,color=color,s=linewidth**2,edgecolor='none', zorder=(z+2).tolist())
TypeError with PAMIE Question: I am getting a TypeError with a very simple script on PAMIE, and I'm not sure what I can do. I had found an answer suggesting that the library, `pywin32` might not have set a `self` argument for this particular method (`getElementsByTagName`) but I don't know for sure, as I don't know where to find the definition of it. from PAM30 import PAMIE ie = PAMIE() ie.navigate('google.com') ie.getButtons() ie.quit() print 'done' The error is: Traceback (most recent call last): File "c:\pamie1.py", line 1, in <module> from PAM30 import PAMIE File "C:\Python27\Lib\site-packages\PAM30.py", line 678, in getButtons return self.getElementsList("input", filter) File "C:\Python27\Lib\site-packages\PAM30.py", line 939, in getElementsList elements = self._ie.Document.getElementsByTagName(tag) TypeError: getElementsByTagName() takes exactly 1 argument (2 given) Here's the offending line in `PAM30` elements = self._ie.Document.getElementsByTagName(tag) where `_ie_` is self._ie = win32com.client.dynamic.Dispatch('InternetExplorer.Application') I'm using Windows 7x64 with Python2.7 32bit Answer: [sourceforge bug link](http://sourceforge.net/tracker/index.php?func=detail&aid=3562879&group_id=78018&atid=551954) "Workaround" seems to be enable Compatibility View (`Tools > Compatibility View settings > Display all websites in Compatibility View`). it is a bug of IE.
Best Method to Find Multiple String Occurrences in Python Question: I need to be pointed in the right direction for this problem I'm working on: Let's say I'm reading output from a C program as follows: while True: ln = p.stdout.readline() if '' == ln: break #do stuff here with ln And my output looks like this line for line: TrnIq: Thread on CPU 37 TrnIq: Thread on CPU 37 but will be moved to CPU 44 IP-Thread on CPU 33 FANOUT Thread on CPU 37 Filter-Thread on CPU 38 but will be moved to CPU 51 TRN TMR Test 2 Supervisor Thread on CPU 34 HomographyWarp Traking Thread[0] on CPU 26 I want to capture "TrnIq: Thread on" and "37" as 2 separate variables: a string and a number from output "TrnIq: Thread on CPU 37". Its pretty well the same for the other lines to, for example capture "HomographyWarp Traking Thread[0] on" and the # "26" from "HomographyWarp Traking Thread[0] on CPU 26". The only real challenge is for lines like this: "Filter-Thread on CPU 38 but will be moved to CPU 51" on this line I need "Filer-Thread" and the # "51" not the first # "38". Python has so many different ways to do this I dont even know where to start! Thanks in advance! Answer: The following should return a tuple of the information assuming `ln` is a single line of your data (edited to include converting the CPU value to an int): match = re.match(r'(.*?)(?: on CPU.*)?(?: (?:on|to) CPU )(.*)', ln).groups() if match: proc, cpu = match.groups() cpu = int(cpu) Example: >>> import re >>> for ln in lines: ... print re.match(r'(.*?)(?: on CPU.*)?(?: (?:on|to) CPU )(.*)', ln).groups() ... ('TrnIq: Thread', '37') ('TrnIq: Thread', '44') ('IP-Thread', '33') ('FANOUT Thread', '37') ('Filter-Thread', '51') ('TRN TMR Test 2 Supervisor Thread', '34') ('HomographyWarp Traking Thread[0]', '26') Explanation: (.*?) # capture zero or more characters at the start of the string, # as few characters as possible (?: on CPU.*)? # optionally match ' on CPU' followed by any number of characters, # do not capture this (?: (?:on|to) CPU ) # match ' on CPU ' or ' to CPU ', but don't capture (.*) # capture the rest of the line Rubular: <http://www.rubular.com/r/HqS9nGdmbM>
Copy a file line by line in python Question: I am writing a python program to copy a file line by line into a new file. The code I have is below in which I am using a loop to copy the file line by line. However since the number of lines in the file may change, is there a way to copy a file line by line in python without using a loop which relies on numbers, and instead relies on the something like the EOF character to terminate the loop? import os import sys i = 0 f = open("C:\\Users\\jgr208\\Desktop\\research_12\\sap\\beam_springs.$2k","r") copy = open("C:\\Users\\jgr208\\Desktop\\research_12\\sap\\copy.$2k","wt") #loop that copies file line by line and terminates loop when i reaches 10 while i < 10: line = f.readline() copy.write(str(line)) i = i +1 f.close() copy.close() Answer: You can iterate over lines in a file object in Python by iterating over the file object itself: for line in f: copy.write(line) From the [docs on file objects](http://docs.python.org/tutorial/inputoutput.html#methods-of-file- objects): > An alternative approach to reading lines is to loop over the file object. > This is memory efficient, fast, and leads to simpler code: >>> for line in f: print line,
Ubuntu pass information to a text file during process execution Question: My issue is that I have a function call it function1 which runs indefinitely. The function itself echo's "hello" every 1 second. Using the command: function1 >> temp.txt Every 1 second if I am to view the file temp.txt I should see a new line with "hello". However what's happening is that the function doesn't write to the file until its finished running. Therefore if I am to kill the function nothing will be written. Does anyone know of something I can do in this situation that will basically dynamically update temp.txt? I have a python script set up the following way: while [1>0]: print "hello" time.sleep(1) Therefore this will always be running. Now I call this in a bash script python pythonscript.py >> temp.txt If I `kill` the process no data is logged. Answer: You are going to want to flush the buffer after each print. import time import sys while [1>0]: print "hello" sys.stdout.flush() time.sleep(1) This will also work on other operating systems.
SSL Connection Using .pem Certificate With Python Question: I'm trying to establish successful communication over an HTTPS connection using authentication. I'm using Python 2.7 w/ Django 1.4 on Ubuntu 12.04. The API documentation I'm following has specific requirements for authentication. Including the `Authentication` header you'll find below and sending certificate information. This is the code: import httplib import base64 HOST = 'some.host.com' API_URL = '/some/api/path' username = '1234' password = '5678' auth_value = base64.b64encode('WS{0}._.1:{1}'.format(username, password)) path = os.path.join(os.path.dirname(__file__), 'keys/') pem_file = '{0}WS{1}._.1.pem'.format(path, username) xml_string = '<some><xml></xml><stuff></stuff></some>' headers = { 'User-Agent' : 'Rico', 'Content-type' : 'text/xml', 'Authorization' : 'Basic {0}'.format(auth_value), } conn = httplib.HTTPSConnection(HOST, cert_file = pem_file) conn.putrequest("POST", API_URL, xml_string, headers) response = conn.getresponse() I'm getting the following error: Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view 77. return view_func(*args, **kwargs) File "/home/tokeniz/tokeniz/gateway_interface/views.py" in processPayment 37. processCreditCard = ProcessCreditCard(token, postHandling) File "/home/tokeniz/tokeniz/gateway_interface/credit_card_handling.py" in __init__ 75. self.processGateway() File "/home/tokeniz/tokeniz/gateway_interface/credit_card_handling.py" in processGateway 95. gateway = Gateway(self) File "/home/tokeniz/tokeniz/gateway_interface/first_data.py" in __init__ 37. self.postInfo() File "/home/tokeniz/tokeniz/gateway_interface/first_data.py" in postInfo 245. response = conn.getresponse() File "/usr/lib/python2.7/httplib.py" in getresponse 1018. raise ResponseNotReady() Exception Type: ResponseNotReady at /processPayment/ Exception Value: Why am I getting this error? UPDATE 1: I've been using the `.pem` file they gave me (Link Point Gateway) but have read that the certificate file should contain both the certificate and the RSA private key. Is that correct? I tried to send a `.pem` file containing both and received the following error: Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view 77. return view_func(*args, **kwargs) File "/home/tokeniz/tokeniz/gateway_interface/views.py" in processPayment 37. processCreditCard = ProcessCreditCard(token, postHandling) File "/home/tokeniz/tokeniz/gateway_interface/credit_card_handling.py" in __init__ 75. self.processGateway() File "/home/tokeniz/tokeniz/gateway_interface/credit_card_handling.py" in processGateway 95. gateway = Gateway(self) File "/home/tokeniz/tokeniz/gateway_interface/first_data.py" in __init__ 37. self.postInfo() File "/home/tokeniz/tokeniz/gateway_interface/first_data.py" in postInfo 251. conn.request('POST', self.API_URL, self.xml_string, headers) File "/usr/lib/python2.7/httplib.py" in request 958. self._send_request(method, url, body, headers) File "/usr/lib/python2.7/httplib.py" in _send_request 992. self.endheaders(body) File "/usr/lib/python2.7/httplib.py" in endheaders 954. self._send_output(message_body) File "/usr/lib/python2.7/httplib.py" in _send_output 814. self.send(msg) File "/usr/lib/python2.7/httplib.py" in send 776. self.connect() File "/usr/lib/python2.7/httplib.py" in connect 1161. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file) File "/usr/lib/python2.7/ssl.py" in wrap_socket 381. ciphers=ciphers) File "/usr/lib/python2.7/ssl.py" in __init__ 141. ciphers) Exception Type: SSLError at /processPayment/ Exception Value: [Errno 336265225] _ssl.c:351: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib I can't tell if this is a step forward or backward. UPDATE 2: I've tried to pass both a certificate file and a key file when creating the connection object. conn = httplib.HTTPSConnection(HOST, cert_file = pem_file, key_file = key_file) I get the following error: Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view 77. return view_func(*args, **kwargs) File "/home/tokeniz/tokeniz/gateway_interface/views.py" in processPayment 37. processCreditCard = ProcessCreditCard(token, postHandling) File "/home/tokeniz/tokeniz/gateway_interface/credit_card_handling.py" in __init__ 75. self.processGateway() File "/home/tokeniz/tokeniz/gateway_interface/credit_card_handling.py" in processGateway 95. gateway = Gateway(self) File "/home/tokeniz/tokeniz/gateway_interface/first_data.py" in __init__ 37. self.postInfo() File "/home/tokeniz/tokeniz/gateway_interface/first_data.py" in postInfo 252. conn.request('POST', self.API_URL, self.xml_string, headers) File "/usr/lib/python2.7/httplib.py" in request 958. self._send_request(method, url, body, headers) File "/usr/lib/python2.7/httplib.py" in _send_request 992. self.endheaders(body) File "/usr/lib/python2.7/httplib.py" in endheaders 954. self._send_output(message_body) File "/usr/lib/python2.7/httplib.py" in _send_output 814. self.send(msg) File "/usr/lib/python2.7/httplib.py" in send 776. self.connect() File "/usr/lib/python2.7/httplib.py" in connect 1161. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file) File "/usr/lib/python2.7/ssl.py" in wrap_socket 381. ciphers=ciphers) File "/usr/lib/python2.7/ssl.py" in __init__ 141. ciphers) Exception Type: SSLError at /processPayment/ Exception Value: [Errno 336265225] _ssl.c:351: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib If I try and combine the certificate file and key file and send it as the certificate argument I receive the same error. Answer: It would seem that some of the "higher level" libraries in Python are not equipped to handle this kind of authentication connection. After many days of attempts I was finally able to come up with a solution going down to the socket level. host = 'some.host.com' service = '/some/api/path' port = 443 # Build the authorization info username = '1234' password = '5678' path = '/path/to/key/files/' pem_file = '{0}WS{1}._.1.pem'.format(path, username) key_file = '{0}WS{1}._.1.key'.format(path, username) auth = base64.b64encode('WS{0}._.1:{1}'.format(username, password)) ## Create the header http_header = "POST {0} HTTP/1.0\nHost: {1}\nContent-Type: text/xml\nAuthorization: Basic {2}\nContent-Length: {3}\n\n" req = http_header.format(service, host, auth, len(xml_string)) + xml_string ## Create the socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn = ssl.wrap_socket(sock, keyfile = key_file, certfile = pem_file) conn.connect((host, port)) conn.send(req) response = '' while True: resp = conn.recv() response += resp if (resp == ''): break I hope someone finds this useful. This particular implementation was to interface with Link Point Gateway with Python (not supported by First Data (Link Point)). Talk about a nightmare this whole project has been. haha Anyway, for anyone having trouble using Link Point please be advised that the `.key` file they provide you is not sufficient for creating a connection in Python. `openssl rsa -in orig_file.key -out new_file.key` Then use the `new_file.key` instead.
Django Installation Error : Question: Trying to create the first project. First got the below error when I ran, django-admin.py startproject mysite then I tried, django-admin.py Also symlinked the path and its in the path. But I still get the error. . . . File "/Users/Satha/django-trunk/django/bin/django-admin.py", line 7, in execfile(**file**) File "/Users/Satha/django-trunk/django/bin/django- admin.py", line 4, in from pkg_resources import require; require('Django==1.5.dev20120720114244') File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 666, in require needed = self.resolve(parse_requirements(requirements)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 546, in resolve requirements = list(requirements)[::-1] # set up the stack File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2438, in parse_requirements yield Requirement(project_name, specs, extras) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2465, in **init** self.unsafe_name, project_name = project_name, safe_name(project_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 1113, in safe_name return re.sub('[^A-Za-z0-9.]+', '-', name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 151, in sub File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 231, in _compile RuntimeError: maximum recursion depth exceeded while calling a Python object Answer: Unless you have some specific reason, you should probably not be using an unstable dev version of django (1.5). Though I am not exactly sure why you are having problems even with the dev branch, as it installs fine for me and creates a project equally as easily. I recommend trying to first remove the dev version, and then install django via `easy_install` or `pip` which will get you v1.4. [Installation Instructions here](https://docs.djangoproject.com/en/1.4/topics/install/#installing-an- official-release-with-pip) If after installing django 1.4, if you still have this issue, try creating a [virtualenv](http://www.virtualenv.org/en/latest/index.html), which will make an isolated environment in a directory, and then install django in that.
python subprocess as normal user Question: I have a script that needs to be run as a super user: $ sudo ./python-script.py Within this script, I do some other things that _do not_ require super user privileges. $ os.mkdir('somefolder') What is the best/most efficient way of creating the directory as non-root user? Should I let the script make the directory as root user, and then change permissions on it? Answer: `os.mkdir` does allow you to specify the permissions explicitly: os.mkdir(path [, mode=0777]) And you also have the option of running `os.chown` to set the user and group os.chown(path, uid, gid) You can probably get the original user like this (but it might be platform specific?) import os original_user = os.environ.get('SUDO_USER') original_uid = os.environ.get('SUDO_UID') original_gid = os.environ.get('SUDO_GID')
Is there a python json library can convert json to model objects, similar to google-gson? Question: The standard python json module only can convert json string to dict structures. But I prefer to convert json to a model object strutures with their "parent- child" relationship. I use google-gson in Android apps but don't know which python library could do this. Answer: You could let the json module construct a dict and then use an [`object_hook`](http://docs.python.org/library/json.html#module-json) to [transform the dict into an object](http://stackoverflow.com/questions/1305532/convert-python-dict-to- object), something like this: >>> import json >>> >>> class Person(object): ... firstName = "" ... lastName = "" ... >>> >>> def as_person(d): ... p = Person() ... p.__dict__.update(d) ... return p ... >>> >>> s = '{ "firstName" : "John", "lastName" : "Smith" }' >>> o = json.loads(s, object_hook=as_person) >>> >>> type(o) <class '__main__.Person'> >>> >>> o.firstName u'John' >>> >>> o.lastName u'Smith' >>>
Python - how to create a random string 8 bytes long? Question: > **Possible Duplicate:** > [python random string generation with upper case letters and > digits](http://stackoverflow.com/questions/2257441/python-random-string- > generation-with-upper-case-letters-and-digits) I need to create a random string that is 8 bytes long in python. rand_string = ? How do I do that? Thanks Answer: import os rand_string = os.urandom(8) Would create a random string that is 8 characters long.
How can I further shorten this Python script which copies the contents of one file to another file? Question: I'm reading Zed Shaw's "Learn Python The Hard Way". I'm up to exercise 17 ( <http://learnpythonthehardway.org/book/ex17.html> ) and hit the wall on extra credit #'s 2 & 3\. Zed wants me to shorten the script by eliminating anything that isn't necessary (he claims he can get it to run with just one line in the script). Here is the original script... from sys import argv from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s" % (from_file, to_file) # we could do these two on one line too, how? input = open(from_file) indata = input.read() print "The input file is %d bytes long" % len(indata) print "Does the output file exist? %r" % exists(to_file) print "Ready, hit RETURN to continue, CTRL-C to abort." raw_input() output = open(to_file, 'w') output.write(indata) print "Alright, all done." output.close() input.close() Here's what I was able to shorten the script to and still get it to run properly (by properly I mean that the script successfully copies the intended text to the intended file)... from sys import argv from os.path import exists script, from_file, to_file = argv input = open (from_file) indata = input.read () output = open (to_file, 'w') output.write (indata) I got rid of the print commands and the two close commands (please excuse if I'm using "command" incorrectly...I'm painfully new to coding and haven't gotten the jargon down yet). Anything else I try to further shorten the script produces errors. For example, I tried to combine the "input" and "indata" commands into one line like so... input = open (from_file, 'r') Then I changed any "indata" references in the script to "input"... from sys import argv from os.path import exists script, from_file, to_file = argv input = open (from_file, 'r') output = open (to_file, 'w') output.write (input) But I get the following TypeError... new-host:python Eddie$ python ex17.py text.txt copied.txt Traceback (most recent call last): File "ex17.py", line 10, in <module> output.write (input) TypeError: expected a character buffer object How would you go about shortening the script further...or shortening it down to just one line, as Zed suggests he can do? Answer: The current error you get is due to this: input = open (from_file, 'r') output.write (input) [write()](http://docs.python.org/library/stdtypes.html?highlight=write#file.write) wants a string as parameter, you are giving it a file object. Also, since you are trying to eliminate redundant things/shorten your code, small item, the default mode for [opening](http://docs.python.org/library/functions.html#open) files is `'r'`ead, to that doesn't have to be specified when opening files for reading. Also consider using the `with` construct to open and manage your files. The advantage is that the files will be closed for you automatically when you are done, or an exception is encountered, so no explicit `close()` is required. E.g., with open('data.txt') as input: ## all of your file ops here The [**PEP08 -- Style Guide for Python**](http://www.python.org/dev/peps/pep-0008/) (a "must read" for Python programmers) suggests not space between a function and the opening `(`. I'm not sure a goal of one-line always results in a better or more readable solution, so that should be kept in mind.
Programmatically login to OKC Question: I'm trying to programatically login to OKCupid ([www.okcupid.com/login](http://www.okcupid.com/login))in order to fetch scrape some user data. I've tried to put together a python script to do this, but seem to be doing something wrong. The behavior I'd like from this sample script is to login, follow a redirect to the homepage then print the HTML response. Here's what I have so far: import urllib, urllib2, cookielib # cookie storage cj = cookielib.CookieJar() opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj), urllib2.HTTPRedirectHandler ) # Useragent opener.addheaders.append(('User-agent','Mozilla/4.0')) url = 'http://www.okcupid.com/login' login_data = urllib.urlencode({ 'username':'myusername', 'password':'mypassword', }) req = urllib2.Request(url,login_data) resp = urllib2.urlopen(req) the_page = resp.read() print the_page Answer: based on what you are doing, here's an example of what i'm doing to login, then go to messages and save all usernames import urllib, urllib2, cookielib import re # cookie storage cj = cookielib.CookieJar() opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj), urllib2.HTTPRedirectHandler ) # Useragent opener.addheaders.append(('User-agent','Mozilla/4.0')) url = 'http://www.okcupid.com/login' login_data = urllib.urlencode({ 'username':'Mobius1', 'password':'raptor22', }) urllib2.install_opener(opener) res = opener.open(url, login_data) print res.url #should be http://www.okcupid.com/home if successful res.close() #navigate profile after successful login res = opener.open('http://www.okcupid.com/messages') the_page = res.read() #read content at URL #find all usernames from page content with pattern /profile/username? UserNameList = re.findall(r'/profile/([\w\.-]+)?', the_page) print UserNameList with open('OkC_messages.html', 'w') as fid: #save the_page as html fid.write(the_page)
How can I display an image in Python 3 using tkinter/ttk? Question: The nub of the matter is, what am I doing wrong in the following code snippet? from tkinter import * from tkinter.ttk import * root = Tk() myButton = Button(root) myImage = PhotoImage(myButton, file='myPicture.gif') myButton.image = myImage myButton.configure(image=myImage) root.mainloop() The error message I get from idle3 is as follows: >>> Traceback (most recent call last): File "/home/bob/Documents/Python/tkImageTest.py", line 9, in <module> myButton.configure(image=myImage) File "/usr/lib/python3.2/tkinter/__init__.py", line 1196, in configure return self._configure('configure', cnf, kw) File "/usr/lib/python3.2/tkinter/__init__.py", line 1187, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) TypeError: __str__ returned non-string (type Button) >>> This error message has me stumped, I simply don't understand what it is trying to say. Any ideas? I would also appreciate suggestions for changes... Answer: The error seems to point to the `myButton` argument passed to `PhotoImage`. As you noted in your comment, `PhotoImage` was treating the widget object as a string (there are several options of type string; see a list of PhotoImage options [here](http://www.pythonware.com/library/tkinter/introduction/x6716-options.htm)). Your code will work if you implement that line without referencing the `myButton` object: myImage = PhotoImage(file='myPicture.gif') I'm not certain you need to alter the `PhotoImage` constructor. Look at the `PhotoImage` docs to determine the valid options (i.e. resource names) for that class. Quoting the help file: > Help on class PhotoImage in module tkinter: > > class PhotoImage(Image) > > > | Widget which can display colored images in GIF, PPM/PGM format. > | > | Method resolution order: > | PhotoImage > | Image > | builtins.object > | > | Methods defined here: > | > | __getitem__(self, key) > | # XXX config > | > | __init__(self, name=None, cnf={}, master=None, **kw) > | Create an image with NAME. > | > | Valid resource names: data, format, file, gamma, height, palette, > | width. > * * * FYI: The easiest way to get to the docs from Python at the command line or from IDLE: from tkinter import PhotoImage help(PhotoImage) And lastly, another useful link about this class is at <http://tkinter.unpythonic.net/wiki/PhotoImage>.
Importing matplotlib on Ubuntu Question: So I downloaded and installed matplotlib. The weird things is that I can run the examples fine when they were placed in home/user/Desktop but when I moved them to home/user/Documents, they stopped working and I get the below message. Is there something special about the Documents folder that they prevent matplotlib from importing? Traceback (most recent call last): File "contour_manual.py", line 4, in <module> import matplotlib.pyplot as plt File "/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 23, in <module> from matplotlib.figure import Figure, figaspect File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 18, in <module> from axes import Axes, SubplotBase, subplot_class_factory File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes.py", line 8454, in <module> Subplot = subplot_class_factory() File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes.py", line 8446, in subplot_class_factory new_class = new.classobj("%sSubplot" % (axes_class.__name__), AttributeError: 'module' object has no attribute 'classobj' Answer: Do you have a file `new.py` in your `Documents` folder, by any chance? If you have, try renaming it to something else. The matplotlib module `axes.py` imports `new`, and if you have a file `new.py` lying around in your Documents folder, that will cause Python to load it instead of the built-in `new` module.
Youtube in Webkit/Python/GTK app Question: I'm trying to do a python(2.7)/GTK+ app, and I have a window, containing a WebKit WebView. from gi.repository import Gtk, WebKit class MainWindow: def __init__( self ): self.builder = Gtk.Builder() self.builder.add_from_file("youtubeWindow.ui") self.main_window = self.builder.get_object("main_window") self.scrl_window = self.builder.get_object("scrl_window") self.webview = WebKit.WebView() self.scrl_window.add(self.webview) self.webview.show() self.webview.open("http://youtu.be/o-akcEzQ6Y8") self.main_window.show_all() Gtk.main() tube_window = MainWindow() When I run my app I get the folowing error: > ERROR: Invalid browser function table. Some functionality may be restricted. > java version "1.6.0_24" OpenJDK Runtime Environment (IcedTea6 1.11.3) > (6b24-1.11.3-1ubuntu0.12.04.1) OpenJDK 64-Bit Server VM (build 20.0-b12, > mixed mode) ** Message: console message: undefined @0: TypeError: > 'undefined' is not an object The page loads, but I can't play my video :( (The video box is all black and doesn't have any play button, nothing) The UI is made in Glade and the XML file generated by Glade, youtubeWindow.ui is: <?xml version="1.0" encoding="UTF-8"?> <interface> <!-- interface-requires gtk+ 3.0 --> <object class="GtkWindow" id="main_window"> <property name="can_focus">False</property> <property name="type_hint">menu</property> <child> <object class="GtkScrolledWindow" id="scrl_window"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="shadow_type">in</property> <child> <placeholder/> </child> </object> </child> </object> </interface> Can you please help me? Thanks! Answer: I've found the solution to your problem. The error message from OpenJDK is irrevelant, it comes from the Java browser plugin and has no effect on what you're trying to do. Far more important, you make a simple mistake. You simply don't show your window! Add a self.main_window.show_all() before the call to `Gtk.main()` and your window is shown, Youtube video playback starts and everything works properly.
How to install and run pandas python library in Eclipse Juno? Question: I am using pydev plugin in Eclipse Juno for my python programming in windows 7 and i am using python 3.2, it works fine while running python application which using standard python packages. For my one of my project i have to use pandas library, for that i download and install numpy and pandas Windows installer for python 3. But while running even a small program it shows error message. i am a beginner in python. So anyone have any idea about how to install and test pandas in Windows 7 by using eclipse, just pass it to me. The error message is like this: Traceback (most recent call last): import numpy File "C:\Python32\lib\site-packages\numpy\__init__.py", line 137, in <module> from . import add_newdocs File "C:\Python32\lib\site-packages\numpy\add_newdocs.py", line 9, in <module> from numpy.lib import add_newdoc File "C:\Python32\lib\site-packages\numpy\lib\__init__.py", line 4, in <module> from .type_check import * File "C:\Python32\lib\site-packages\numpy\lib\type_check.py", line 8, in <module> import numpy.core.numeric as _nx File "C:\Python32\lib\site-packages\numpy\core\__init__.py", line 40, in <module> from numpy.testing import Tester File "C:\Python32\lib\site-packages\numpy\testing\__init__.py", line 8, in <module> from unittest import TestCase File "C:\Python32\lib\unittest\__init__.py", line 59, in <module> from .case import (TestCase, FunctionTestCase, SkipTest, skip, skipIf, File "C:\Python32\lib\unittest\case.py", line 6, in <module> import pprint EOFError: EOF read where not expected Thanks in advance for your time Answer: I think you have Install panda: here you can find panda package for windows here <https://pypi.python.org/pypi/pandas#downloads>
Check if a directory exists in a zip file with Python Question: Initially I was thinking of using `os.path.isdir` but I don't think this works for zip files. Is there a way to peek into the zip file and verify that this directory exists? I would like to prevent using `unzip -l "$@"` as much as possible, but if that's the only solution then I guess I have no choice. Answer: You can check for the directories with [ZipFile.namelist()](http://docs.python.org/library/zipfile.html#zipfile.ZipFile.namelist). import os, zipfile dir = "some/directory/" z = zipfile.ZipFile("myfile.zip") if dir in z.namelist(): print "Found %s!" % dir
Python SciPy FFT function - Input? Question: I am currently writing some code which is supposed to perform FFT on a set of data. I have a python list of points and I can easily create a time list. When I run fft(datalist), I get the 'TypeError: 'numpy.ndarray' object is not callable' error. I think (but please correct me) the issue is that the list is one dimension and they have no attachment to time at all by using that one line of code above. My question is, do I have to input a two dimensional array with time and data points? or am I completely wrong and have to rethink? Thanks, Mike Edit - forgot to add some code. The t=time. Could it be because the number of entries in the array isnt equal to 2^n where N is an integer? sample_rate=10.00 t=r_[0:191.6:1/sample_rate] S = fft([mylist]) print S Answer: The Numpy and SciPy fft functions are looking to have numpy arrays as input, not native python lists. Also they work just fine with lengths that are not powers of two. You probably just need to cast your list as an array before passing it to the fft. From your example code above try: from numpy.fftpack import fft from numpy import array """ However you generate your list goes here """ S = fft(array([mylist]))
How to determine whether a year is a leap year in Python? Question: I am trying to make a simple calculator to determine whether or not a certain year is a leap year. By definition, a leap year is divisible by four, but not by one hundred, unless it is divisible by four hundred. Here is my code: def leapyr(n): if n%4==0 and n%100!=0: if n%400==0: print n, " is a leap year." elif n%4!=0: print n, " is not a leap year." print leapyr(1900) When I try this inside the Python IDLE, the module returns **None**. I am pretty sure that I should get **1900 is a leap year**. Answer: import calendar print calendar.isleap(1900) Python provides this functionality already in the library module 'calendar'.
Python:Importing moduel Attribute Error,LPTHW ex47: Question: I'm doing ex47 from Learn python the hard way[This is the exercise](http://learnpythonthehardway.org/book/ex47.html) And this is my code: from nose.tools import* from ex47.game import Room def test_room(): gold = Room("GoldRoom", """This room has gold in it you can grab. there's a door to the north.""") assert_equal(gold.name, "GoldRoom") assert_equal(gold.paths, {}) def test_room_paths(): center = Room("Center", "Test room in the center.") north = Room("North", "test room in the north.") south = Room("south", "test room in the south.") center.add_paths({'north': north, 'south': south}) assert_equal(center.go('north'), north) assert_equal(center.go('south'), south) def test_map(): start = Room("Start", "You can go west and down a hole.") west = Room("Trees", "There are trees here, you can go east.") down = Room("Dungeon", "It's dark down here, you can go up.") start.add_paths({'west': west, 'down': down}) west.add_paths({'east': start}) down.add_paths({'up': start}) assert_equal(start.go('west'), west) asset_equal(start.go('west').go('east'), start) assert_equal(start.go('down').go('up'), start) However when test this code using nosetest this is what I get: Traceback <most recent call last>: File "c:\Python31\lib\site-packages\nose\case.py", line 197,in runtest self.test<*self.arg> File "C:\path\Ex47\skeleton\tests\ex47_tests.py", line 28, in test_map start.add_paths<{'west': west, 'down':down>} AttributeError: 'Room' object has no attribute 'add_paths' * * * Ran 3 tests in 0.030s FAILED <errors=2> But this seems to be ridiculous since add_paths worked fine in test_room_paths(). This has driven me crazy(google hasn't helped neither copying the code from the book either). Please Help!! I'm using python 3.1, windows 7 Please don't use too much programming Lingo.(I'm very new to programming). here is the code for game.py just in case you need it. class Room(object): def __init__(self, name, description): self.name = name self.description = description self.paths = {} def go(self, direction): return self.paths.get(direction, None) def add_paths(self, paths): self.paths.update(paths) Answer: You state, "add_paths worked fine in test_room_paths()", but you are assuming the tests are run in the order you've written them. They often are run in alphabetical order, meaning test_room_paths hasn't executed yet. Your Room code looks incorrect, you have `def add_paths` indented under `def __init__`, meaning `add_paths` is a function defined locally in `__init__`, rather than another method in your class. Be sure all the `def` keywords in your class are lined up.
Python MMTK "There is no program associated with ..pdb files, please install a suitable viewer" Question: I'm new to programming and computer world. I'm trying to study biomolecular simulations with MMTK. I run it in Windows 7 and I have already installed this software: * python-2.5.4 * numpy-1.6.2-win32-superpack-python2.5 * netCDF4-0.8.2.win32-py2.5 * ScientificPython-2.9.0.win32-py2.5 * MMTK-2.6.0.win32-py2.5 * pywin32-217.win32-py2.7 When I run this [protein.py](http://structure.usc.edu/mmtk/Examples/MolecularDynamics/protein.py) mmtk sample, all seems to be OK. It show the numbers of 1000 process steps. But when I run a script with the `view` method, like this: from MMTK import * molecule = Molecule('water') molecule.view() Then I get this message: There is no program associated with ..pdb files, please install a suitable viewer After searching for some answers on the internet I got this information: "A viewer for PDB files can be defined by the environment variable PDBVIEWER. For showing a PDB file, MMTK will execute a command consisting of the value of this variable followed by a space and the name of the PDB file." And my doubt is: how define a viewer for PDB files by the environment variable PDBVIEWER? What would be the variable value? This issue of the environment variables seems to me so simple as the mystery of life's emergence on Mars. I know how to change it, but I don't know **what** to change or **when** change it. Reading the Wikipedia articles on the subject didn't help me too much. So what I'd like to know is: how **exactly** to modify the system variable in **this** case? I must add a new variable (PDBVIEWER) or just one more path to an existing variable? What is the value path to PDBVIEWER (should not it be C:\Windows\System32)? This is my current variable value: Variable's name: Path Variables's value: C:\Program Files (x86)\PC Connectivity Solution\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Windows Live\Shared;%PYTHON_HOME%;%PYTHON_HOME%\Scripts;C:\Program Files (x86);C:\Python27\; C:\Python27\Scripts;C:\Python25\DLLs I also have this Python variable: `PYTHON_HOME` with this variable's value: `C:\Python27` (though I'm using Python25 with MMTK). This question may seem trivial to an experienced programmer. But the answer to it can be very useful to others. There is a large number of biologists, biochemists and pharmacists interested in using computational methods to their problems. These professionals do not always have a computer scientist in the vicinity (especially if they are in an underdeveloped country). Overcoming this initial frustrating phase of bugs and installation problems can be crucial in the scientific career of many people. And the answer to this question will help them. Thanks in advance. If this forum is not appropriate for questions of this level, please give me a feedback. Answer: Google says <http://spdbv.vital-it.ch/> is a PDB viewer. You need to install that or something else you find that can view PDB files. Assuming the installer for that doesn't just go set that environment variable for you (which it may), you'd then need to set the variable PDBVIEWER to be the path to an executable that can view PDBs presumably. So, say, C:\SwissPDBViewer\view.exe hypothetically speaking.
Use entire scope as input in plugin in Sublime Text 2 Question: One of the nice things about Textmate was the ability to pipe the contents of an entire scope into a command, like so: ![Textmate screenshot](http://i.stack.imgur.com/Yiekh.png) You could then specify the scope to be used, such as `meta.class.python` or whatever. I'm trying to write a small plugin that will pipe the entire current scope in as the input for the plugin (for example (not exactly what I'm trying to do, but close), a function that lets you comment out an entire Python class without selecting it all) Using the current selection(s) as input is quite easy: import sublime, sublime_plugin import re class DoStuffWithSelection(sublime_plugin.TextCommand): def run(self, edit): for region in self.view.sel(): if not region.empty(): changed = region # Do something to the selection self.view.replace(edit, region, changed) # Replace the selection I've scoured the Sublime Text plugin API for some way to do something like `for region in self.view.scope()`, but without success. Is there a way, then, to use the contents of the current scope under the cursor as input for a plugin function? Or, even better, a way to use the entire scope if there isn't a selection, but use the selection if there is one. Thanks! Answer: If you want to get text that you select, the following code snippet is an example. if not region.empty(): selectText = self.view.substr(region) ... If you want to get text where the cursor is located, the following code snippet is an example. if region.empty(): lineRegion = self.view.line(region) lineText = self.view.substr(lineRegion) ... To get more information, see <http://net.tutsplus.com/tutorials/python- tutorials/how-to-create-a-sublime-text-2-plugin/> and <http://www.sublimetext.com/docs/api-reference>.
Using Flask, trying to get AJAX to update a span after updating mongo record, but it's opening a new page Question: Feel like I am stumbling over something fairly simple here. I am not understanding something about AJAX and Flask. I have a project wherein I display mongodb records in the browser, which has been working fine. I added functionality for users to increment votes on a record; to Vote it up if they like it. But originally I was then refreshing the entire page with the new vote, using a redirect, which is clumsy. So I am trying to get AJAX to send the data over to the mongodb record and then update the span where I want the votes to appear without having to reload the entire page. Problem is, the setup I have going, while still updating the record, is now loading a new page with the HTML i want returned only to the span where the vote tally should be (that is, it's loading a new page with only the word "test" in it (the test value I am currently returning)). The jQuery (the library I am using) is loading fine and there are no other problems (as far as I can tell). I have the relevant HTML and JS here: <!-- All Standard HTML up here, removed for simplicity --> <script> $('#vote_link').bind('click', function(e){ e.preventDefault(); var url = $(this).attr('href'); $('#vote_tally').load(url); }); </script> <a href='/vote_up/{{ item._id }}' id='vote_link'>Vote for Me!</a><br> Likes: <span id='vote_tally'>{{ item.votes }}</span> <!-- All Standard HTML down here, removed for simplicity --> and the python is here: from flask import Flask, render_template, request, redirect, flash, jsonify #from mongokit import Connection, Document #from flask.ext.pymongo import PyMongo from pymongo import Connection#, json_util #from pymongo.objectid import ObjectId #this is deprecated import bson.objectid '''my pymongo connection - removed for simplicity''' '''bunch of other routes - also removed for same reason''' #increment a vote @app.route('/vote_up/<this_record>') def vote_up(this_record): vandalisms.update({'_id':bson.objectid.ObjectId(this_record)}, {"$inc" : { "votes": 1 }}, upsert=True) ''' also trying to return value for votes field from mongo record, but one step at a time here ''' #result = vandalisms.find({'_id':bson.objectid.ObjectId(this_record)}, {'votes':1}) result = 'test' return result I am also having trouble figuring out how to return the individual vote value for the specified mongodb record back to the browser, even with jsonify (which returns {"votes":'_id'}, but that's another issue. Hopefully someone can help me understand how to make AJAX work for me with Flask in this regard. Thanks in advance, **Edit-24Jul2012-2:27PM CST:** I suspect that the jQuery isn't even activating. It seems to be loading the new page based on the link's href attribute, hence it's no use to have `e.prevenDefault();` when that's not being run. Furthermore, an `alert('I have been clicked');` never runs when the click event takes place. Again, the jQuery is loaded, but the click event is not activating the jQuery, and I don't know why not. Answer: My guess (based on your edit) is that you have more than one element on the page with the ID of `vote_link` \- this is not allowed in HTML (the ID property must be unique across the document). If you want to have multiple links sharing the same behavior use a class instead (`$(".vote_link")` for example).
Python: convert string to byte array Question: Say that I have a 4 character string, and I want to convert this string into a byte array where each character in the string is translated into its hex equivalent. e.g. str = "ABCD" I'm trying to get my output to be array('B', [41, 42, 43, 44]) Is there a straightforward way to accomplish this? Answer: encode function can help you here, encode returns an encoded version of the string In [44]: str = "ABCD" In [45]: [elem.encode("hex") for elem in str] Out[45]: ['41', '42', '43', '44'] or you can use array module In [49]: import array In [50]: print array.array('B', "ABCD") array('B', [65, 66, 67, 68])
Problems using etree in Python scraper Question: I'm a newbie in Python looking to build a screen scraper in Scraperwiki but I'm struggling with an error I can't work out how to fix. Essentially, I want to parse an xml file but can't work out how to have my gp_indicators_scrape function access the getroot() method. Can anyone fix it, and more importantly, point me towards an explanation so I can avoid the problem in future? Here's the scraper: <https://scraperwiki.com/scrapers/choiceshu1> The key bits of code: import lxml.html import urlparse from urlparse import urlparse from lxml.etree import etree def gp_indicators_scrape(org_URL): indicator_xml = etree.parse(org_URL) root = lxml.etree.getroot(indicator_XML) print root html = scraperwiki.scrape(combined_URL_for_first_scrape) print html root = lxml.html.fromstring(html) links = root.cssselect("dd a") And here's the error when it runs Line 5 - from lxml.etree import etree ImportError: cannot import name etree Answer: `from lxml.etree import etree` should be `from lxml import etree` Also, just noticed - `lxml.etree.getroot(...)` \- you can drop the `lxml.` if you use the import above, and normally you call `getroot()` on the object returned via `etree.parse` (or similar). NB: I haven't looked at code in the provided link...
Python Running an Excel Macro Question: I am trying to use python to run an excel macro and then close excel. I have the following: import win32com.client import os xl = win32com.client.DispatchEx("Excel.Application") wb = xl.workbooks.open("X:\Location\Location2\File1.xlsm") xl.run("File1.xlsm!WorkingFull") xl.Visible = True wb.Close(SaveChanges=1) xl.Quit My script will Open and close fine if I take out the xl.run("File1.xlsm!WorkingFull") When I run this I get the following error: Traceback (most recent call last): File "C:\Python27\File1.py", line 6, in xl.run("File1.xlsm!WorkingFull") File "", line 2, in run com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'File1.xlsm!WorkingFull'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None) I have macros enabled and I know its in the workbook, what is the problem? Answer: please see below the code for running an Excel macro using python. You can find this code in this [Site - Link](https://sites.google.com/site/exceldriven/selenium-webdriver/python- scripts/run-an-excel-macro-using-python). Use this site for other references for excel, vba and python scripts which might be helpful in the future. from __future__ import print_function import unittest import os.path import win32com.client class ExcelMacro(unittest.TestCase): def test_excel_macro(self): try: xlApp = win32com.client.DispatchEx('Excel.Application') xlsPath = os.path.expanduser('C:\test1\test2\test3\test4\MacroFile.xlsm') wb = xlApp.Workbooks.Open(Filename=xlsPath) xlApp.Run('macroName') wb.Save() xlApp.Quit() print("Macro ran successfully!") except: print("Error found while running the excel macro!") xlApp.Quit() if __name__ == "__main__": unittest.main()
List integration as argument (beginner) Question: I am writing a script in python, but I am a beginner (started yesterday). Basically, I just create chunks that I fill with ~10 pictures, align them, build the model, and build the texture. Now I have my chunks and I want to align them... From the [manual](http://downloads.agisoft.ru/pdf/photoscan_python_api.pdf): > `PhotoScan.alignChunks(chunks, reference, method=’points’, accuracy=’high’, > preselection=False)` > > Aligns specified set of chunks. > > **Parameters** > > * chunks (list) – List of chunks to be aligned. > * reference (Chunk) – Chunk to be used as a reference. > * method (string) – Alignment method in [’points’, ‘markers’]. > * accuracy (string) – Alignment accuracy in [’high’, ‘medium’, ‘low’]. > * preselection (boolean) – Enables image pair preselection. > > > Returns Success of operation. > > Return type `boolean` I tried to align the chunks, but the script throws an error at line 26: > TypeError: expected a list of chunks as an argument Do you have any idea how I can make it work? This is my current code: import PhotoScan doc = PhotoScan.app.document main_doc = PhotoScan.app.document chunk = PhotoScan.Chunk() proj = PhotoScan.GeoProjection() proj.init("EPSG::32641") gc = chunk.ground_control gc.projection = proj working_path = "x:\\New_agisoft\\ok\\Optical\\" for i in range (1,3): new_chunk = PhotoScan.Chunk() new_chunk.label = str(i) loop = i*10 loo = (i-1)*10 doc.chunks.add(new_chunk) for j in range (loo,loop): file_path = working_path + str(j) + ".jpg" new_chunk.photos.add(file_path) gc = new_chunk.ground_control gc.loadExif() gc.apply() main_doc.active = len(main_doc.chunks) - 1 doc.activeChunk.alignPhotos(accuracy="low", preselection="ground control") doc.activeChunk.buildModel(quality="lowest", object="height field", geometry="smooth", faces=50000) doc.activeChunk.buildTexture(mapping="generic", blending="average", width=2048, height=2048) PhotoScan.alignChunks(,1,method="points",accuracy='low', preselection=True) Answer: PhotoScan.alignChunks(,1,method="points",accuracy='low', preselection=True) ^ Before the ',' you need the chunks!
Is it possible to draw graphs on a given image using NetworkX? Question: Is it possible to draw graphs on a given image (instead of on an empty figure) by using the python package NetworkX? Answer: Perhaps you can try this but it requires matplotlib: import matplotlib.pyplot as plt import matplotlib.image as mpimg import networkx as nx G = nx.cycle_graph(2) pos = {0:[0,0], 1:[ 300, 300]} plt.figure(1) img=mpimg.imread('/home/stinkbug.png') plt.imshow(img) nx.draw(G,pos) plt.savefig('/home/test.png') I used the stink bug on this [page](http://matplotlib.sourceforge.net/users/image_tutorial.html). Using networkx by itself might be a little tricky. Perhaps you could set the image you want as a node (say node 0) and then position the node at origin (0,0). Finally, orient the other nodes from your graph on top of them. I haven't tried it myself but its an idea that popped into my head.
Python wrapper script to let a program be executed remotely with no blocking Question: I am looking for a wrapper script to run a program which is called remotely by a SSH command which terminates without waiting for the result of the program. Here is my code: #!/usr/bin/python import sys import os, subprocess def main(): print "PID_last_child", os.getpid() argpass = ['main_p.py'] for a in sys.argv: if a.find("wrapper.py") == -1: argpass.append(a) pid = subprocess.Popen(argpass).pid print "PID for the actual process: ", pid if __name__ == "__main__": print "PID_MAIN:", os.getpid() try: pid = os.fork() print "FORK1: ", pid if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, "fork failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) os.chdir('/') os.setsid() os.umask(0) try: pid = os.fork() print "FORK2: ", pid if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, "fork failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) main() I suppose using double forking, i should be able to do that... but no luck so far. Any thoughts on this is greatly appreciated. Answer: I fully credit this link for the answer in bash syntax: [How to starting process as daemon using ssh command?](http://www.unix.com/shell-programming- scripting/70523-how-starting-process-daemon-using-ssh-command.html) You don't even need to double-fork. The issue is that the stdout is still connected. Here is the python approach: **wrapper.py** import subprocess import os def main(): pid = subprocess.Popen(['nohup', '/path/to/main_p.py'], stdout = open(os.devnull, 'w+', 0), stderr = subprocess.STDOUT ).pid print pid if __name__ == "__main__": main() And then the ssh command would call this wrapper: ssh server /path/to/wrapper.py You just need to redirect stdout -> devull, and the process will return right away.
Python: change CWD of script bundled with py2app Question: My script works fine when ran with `python`, but after I build it with `py2app`, files and folders are created in `.app/Contents/Resources`. I use `os.getcwd()` to find out where the script is located. How can I fix this and make sure my files are created in the app containing directory? **Hacky fix** Here's a hack that works: if re.search('([^/]+$)', cwd).group(0) == "Resources": mkFldr(cwd[0:-27] + fldr) #this is a try except function sanExt(extPath, str(cwd[0:-27] + fldr + "/" + extName + "_san.csv")) else: mkfldr(fldr) sanExt(extPath, str(cwd + "/" + fldr + "/" + extName + "_san.csv")) Answer: If I understand what you're asking correctly I use something similar to the following to handle this. The 'frozen' part changes the behaviour depending on whether you're running the script or a py2exe/py2app executable. import sys import os.path frozen = getattr(sys, 'frozen', '') if frozen: MyFolder = os.path.dirname(sys.executable) else: Myfolder = os.getcwd()
__init__() takes at least 2 arguments (1 given) When Migrating using South with Custom Fields Question: **i am new to south and i followed their documentation and after initializing south migrations, after running** manage.py migrate appname **for the following custom models Models i added introspection rules as follows** Models: class DependentIntegerField(models.IntegerField): def __init__(self, default_callable, *args, **kwargs): self.default_callable = default_callable super(DependentIntegerField, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): if not add: return super(DependentIntegerField, self).pre_save(model_instance, add) return self.default_callable(model_instance) class Level(models.Model): group = models.ForeignKey(Level_Group) number = models.IntegerField(unique=True)#null=True, blank=True threshold = DependentIntegerField(lambda mi:mi.number*50,null=False,blank=True) def __str__(self): return '%s' %(self.number) def get_fib(self): return fib(self.number+3) class Gallery (models.Model): contractor = models.ForeignKey(Contractor) image = StdImageField(upload_to='GalleryDB', size=(640, 480,True)) Title = models.CharField(max_length=250,null=True,blank = True) Caption = models.CharField(max_length=1000,null=True,blank=True) Introspection Rules : add_introspection_rules([ ( [Level], # Class(es) these apply to [], # Positional arguments (not used) { # Keyword argument "threshold": ["threshold", {}], }, ), ], ["^shoghlanah\.models\.DependentIntegerField"]) add_introspection_rules([ ( [Gallery], # Class(es) these apply to [], # Positional arguments (not used) { # Keyword argument "image": ["image"], "upload_to": ["GalleryDB"] }, ), ], ["^stdimage\.fields\.StdImageField"]) Traceback Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 232, in execute output = self.handle(*args, **options) File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/management/commands/migrate.py", line 107, in handle ignore_ghosts = ignore_ghosts, File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/migration/__init__.py", line 219, in migrate_app success = migrator.migrate_many(target, workplan, database) File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/migration/migrators.py", line 235, in migrate_many result = migrator.__class__.migrate_many(migrator, target, migrations, database) File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/migration/migrators.py", line 310, in migrate_many result = self.migrate(migration, database) File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/migration/migrators.py", line 133, in migrate result = self.run(migration) File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/migration/migrators.py", line 99, in run south.db.db.current_orm = self.orm(migration) File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/migration/migrators.py", line 260, in orm return migration.orm() File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/utils/__init__.py", line 62, in method value = function(self) File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/migration/base.py", line 427, in orm return FakeORM(self.migration_class(), self.app_label()) File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/orm.py", line 45, in FakeORM _orm_cache[args] = _FakeORM(*args) File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/orm.py", line 124, in __init__ self.models[name] = self.make_model(app_label, model_name, data) File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/orm.py", line 317, in make_model field = self.eval_in_context(code, app, extra_imports) File "/Library/Python/2.7/site-packages/South-0.7.5-py2.7.egg/south/orm.py", line 235, in eval_in_context return eval(code, globals(), fake_locals) File "<string>", line 1, in <module> TypeError: __init__() takes at least 2 arguments (1 given) i am little sure it's from the field `DependentIntegerField` but i don't know which `__init__` is it trying to call and i tried "threshold": ["threshold", {"ldefault_callable":default_callable}], but i get NameError: name 'default_callable' is not defined and i have no clues how to fix this, any help is appreciated. Answer: # How to pass callable argument to field used in south You have such field class and you want to make it work with south --- problem is with default_callable argument that is a callable and cannot be frozen. class DependentIntegerField(models.IntegerField): def __init__(self, default_callable, *args, **kwargs): self.default_callable = default_callable super(DependentIntegerField, self).__init__(*args, **kwargs) ## Ignore this argument What about leaving this argument altogether --- make it optional on the field and remove this argument from intrspection rules (so south with ignore it's existence) --- I gather that callable argument won't change database behaviour of field --- and that is the only thing south is concerned with. Either allow nulls in this argument (and make the field fail when performing database operations --- like saving model instance --- with null `default_callable`. It will be OK during south run because south doesn't save any models --- it just creates database tables, and during normal operations model definitions will be taken from `models.py` file that will have `default_callable` set. # Pass information about what function to call In some module create a dictionary od `default_callable` functions that are accessible by string keys. Change your field so: class DependentIntegerField(models.IntegerField): def __init__(self, default_callable="foo.bar", *args, **kwargs): self.default_callable = default_callable #it it string now! super(DependentIntegerField, self).__init__(*args, **kwargs) @property def default_fun(self): return registry[self.default_callable] Where registry is this dictionary of all default functions.
Python does not detect .pyc files Question: I am using Python 3.2 (both for building and executing), and here is my question. I intend to ship my python application with the following setup: There is a main script (say, `Main.py`), that is using a compiled module, say `Module1.pyc`). To be precise, the directory structure is: .\Main.py .\__pycache__\Module1.cpython-32.pyc When I use the python interpreter to run the main script, it fails to find the module with the following error: Traceback (most recent call last): File "Main.py", line 10, in <module> import Module1 ImportError: No module named Module1 * * * Note that I have added the current directory to `PYTHONPATH` environment variable, and is part of `sys.path`. Also, the inner `__pycache__` directory is also added, and is visible in `sys.path`. Not sure why Module1 is not found. Am guessing, it could be because of the different file name - Module1.cpython-32.pyc? But, then that is how the Python 3.2 interpreter generates it. Answer: Have a look at [PEP-3147](http://www.python.org/dev/peps/pep-3147/). They describe how the python-lookup mechanism works. ![enter image description here](http://i.stack.imgur.com/CuOXk.png) So in your concrete case: Put the file Module1.pyc directly in the root folder.
Best lightweight, responsive GUI framework Linux Question: I've bought a Raspberry Pi, featuring a 300 Mhz CPU, but it does has a pretty good GPU. It can even run XBMC. I want to program a GUI for it, which needs to be responsive and good-looking, while taking optimal use of the hardware available (which isn't too good, unfortunately..). The Raspberry Pi runs Debian minimal, and I've put the X Windowing System on it, the rest is up to me to code. What is the best way to dive into this? I've already looked into HTML5 and jQuery (via Python and PyWebkit), but they seem to be too CPU-intensive (unless someone knows how to get (Py)WebKit use the GPU, instead of the CPU). To avoid confusion, this system will be hooked up to televisions and the like, and will be primarily pointed on home entertainment. I don't want this to be a desktop or desktop-like system, I'd just like to know what you guys think would work smooth on the Raspberry Pi box, so that I can program my UI upon that framework. Answer: Having done a custom non-desktop UI on underpowered hardware (litl.com) and having hacked on both GTK and Clutter a fair bit, I'd reframe the question slightly. The main issue is you MUST use the GPU rather than be "lightweight" - usually when something says it's lightweight that just means it doesn't have many features or something. Too vague a word. The key is GPU. The hard part about using the GPU is a working driver. I don't know what the raspberry pi people have focused on here. For ARM in general the most reliable way to get a working driver might be to use Android; maybe not the stock Android UI but their drivers and basic framework, then replace the UI. X11 drivers, if they exist are often broken on ARM. This is the real problem with X, rather than lightweight vs heavyweight. By broken, I mean maybe the driver kinda boots and runs a desktop, but it's slow in important cases or missing things like hardware video decoding. Short answer: use the framework (and window system) with the best 3D driver that supports your features you need, like video decode. Again, I haven't looked at raspberry pi but I bet there are only one or two choices that meet this criterion.
Getting docstrings from Python package __init__ - based imports Question: I have several modules that are within a Python package: # my_package contents __init__.py module1.py module2.py Within my `__init__.py`, I'm importing these modules so that they will be accessible once the package is imported by my users. # __init__.py import module1 import module2 My question is: how do I programatically access the docstrings for each of my defined functions within each of these modules? I've seen [others](http://stackoverflow.com/a/1270639/655787) use a form of this: getattr(module, key). __doc__ but I can't get it to work for me. Any ideas? EDIT: A little more background... we're trying to extract content (one of the important things is the docstrings) from our python packages with the intent of using that as content for documentation. My boss has something already set up that we're trying to feed into. Ideally, I'd like to have a `package.module.function docstring` result EDIT2: Here's what is currently **not** working: #my package is named 'tpp' import tpp for script in dir(tpp): if not "__" in script: #not a builtin... docstrings1 = getattr( tpp, script).__doc__ docstrings2 = " ".join(docstrings1.split())#clean out any newline chars print script, docstrings EDIT3: To get a picture of where the docstrings are and how we've organized things: import inspect import tpp inspect.getdoc(tpp) #returns None inspect.getdoc(tpp.module1) #returns None inspect.getdoc(tpp.module1.function1) #'DOCSTRING TEXT FOUND!' **Ultimately, I'd like to get a list like ['module1', 'function1', 'DOCSTRING TEXT FOUND!'] Answer: Use [inspect.getdoc(object)](http://docs.python.org/library/inspect.html#inspect.getdoc) to get the docstring of an object. Use [inspect.isfunction](http://docs.python.org/library/inspect.html#inspect.isfunction) to check if an object is a function. import inspect for variable in vars(module).values(): if inspect.isfunction(variable): print(inspect.getdoc(variable)) Note that inspect.getdoc returns None when there is no docstring for the object and so the code will print None if there is no docstring for the function.
Running wexpect on windows Question: I have installed wexpect on windows7, now when i am trying to run any command, i am getting below error. I am using MKS toolkit, so ls is a valid command. >>> import pexpect >>> pexpect.run('ls ') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\site-packages\winpexpect-1.5-py2.7.egg\pexpect.py", line 219, in run child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env) File "C:\Python27\lib\site-packages\winpexpect-1.5-py2.7.egg\pexpect.py", line 429, in __init__ self._spawn (command, args) File "C:\Python27\lib\site-packages\winpexpect-1.5-py2.7.egg\pexpect.py", line 516, in _spawn raise ExceptionPexpect ('The command was not found or was not executable: %s .' % self.command) pexpect.ExceptionPexpect: The command was not found or was not executable: ls. Can some one please help Answer: Very late reply, but I also faced this problem recently. Many reasons for failure or probably, wexpect.py needs modification (at least for my case) Pl check pexpect_error.txt file generated in the same directory of wexpect.py file. It forks 'python.exe' hence 'python.exe' must be in path (no other name of exe is permitted). You must be in the same directory of wexpect.py (lib file name must be wexpect.py not pexpect.py) when you are executing your py script. The cmd (with extension .exe/.com/.bat), must be working at your windows/shell command prompt . Check that (eg actually in Windows when we run 'ls', it is actually running ls.exe/com, in py script, mention as 'ls.exe') Last but not least: In my case, console window for Window OS creation was failing (found from pexpect_error.txt), hence I changed below line 2397, make Y coordinate of rect small instead of 70 eg 24 worked for me
Issue building cx_Oracle - libclntsh.so.11.1 => not found Question: I'm trying to build cx_Oracle for a Python 2.7.2 and Oracle 11g installation but the built cx_Oracle.so cannot find libclntsh.so.11.1 so importing cx_Oracle in Python fails. /mypath/cx_Oracle-5.1.1/build/lib.linux-x86_64-2.7-11g]$ ldd cx_Oracle.so libclntsh.so.11.1 => not found libpthread.so.0 => /lib64/libpthread.so.0 (0x00002ae9be290000) libc.so.6 => /lib64/libc.so.6 (0x00002ae9be4ab000) /lib64/ld-linux-x86-64.so.2 (0x000000389b600000) I have **libclntsh.so.11.1** in my Oracle client installation directory: /apps/oracle/client/11.2.0.1/home1/lib]$ ls -l libclntsh.so* libclntsh.so -> /apps/oracle/client/11.2.0.1/home1/lib/libclntsh.so.11.1 libclntsh.so.11.1 And the cx_Oracle setup.py is picking this lib dir up: /mypath/cx_Oracle-5.1.1]$ python2.7 setup.py build /apps/oracle/client/11.2.0.1/home1/ running build running build_ext building 'cx_Oracle' extension gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/apps/oracle/client/11.2.0.1/home1/rdbms/demo -I/apps/oracle/client/11.2.0.1/home1/rdbms/public -I/apps/bweb/python-2.7.2/include/python2.7 -c cx_Oracle.c -o build/temp.linux-x86_64-2.7-11g/cx_Oracle.o -DBUILD_VERSION=5.1.1 In file included from /apps/oracle/client/11.2.0.1/home1/rdbms/public/oci.h:3024, from cx_Oracle.c:10: /apps/oracle/client/11.2.0.1/home1/rdbms/public/ociap.h:10788: warning: function declaration isn't a prototype /apps/oracle/client/11.2.0.1/home1/rdbms/public/ociap.h:10794: warning: function declaration isn't a prototype gcc -pthread -shared build/temp.linux-x86_64-2.7-11g/cx_Oracle.o -L/apps/oracle/client/11.2.0.1/home1/lib -lclntsh -o build/lib.linux-x86_64-2.7-11g/cx_Oracle.so Is something obviously wrong with this setup? Thanks **UPDATE** My **LD_LIBRARY_PATH** contains the lib directory above with **libclntsh.so.11.1** $ echo $LD_LIBRARY_PATH /apps/oracle/client/11.2.0.1/lib This doesn't seem to make any difference. I rebuild the cx_Oracle.so file and it still shows `libclntsh.so.11.1 => not found` when I run `$ ldd cx_Oracle.so`. **Python failing to load the built module:** Python 2.7.2 (default, Jan 19 2012, 14:38:32) [GCC 3.4.6 20060404 (Red Hat 3.4.6-11)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cx_Oracle Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: libclntsh.so.11.1: cannot open shared object file: No such file or directory **SOLVED** The issue was related to the **LD_LIBRARY_PATH** environment variable. Due to restrictions on the setup I'm working with (corp env) I had to build cx_Oracle as another user (system account). i.e. I was running this: $ sudo -u username python27 setup.py build So even though **LD_LIBRARY_PATH** was set correctly for me, my version wasn't used when command was executed as a different user. I was able to build successfully by moving the source code to a location where I had permissions and running the build as my user. Answer: Add `/apps/oracle/client/11.2.0.1/home1/lib/` to your `LD_LIBRARY_PATH` environment variable execute the command below in the terminal before running python or add it into your `.bashrc` export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/apps/oracle/client/11.2.0.1/home1/lib/
python module resides in a repository whose name contains dash characters Question: I know name of the module should not have a dash. Here is my repository structure my-repo-name/ src/ tests/ __init__.py tests.py fab/ __init__.py fabfile.py README.rst __init__.py In my tests, I need to import fabfile.py to run a test. But because the name has a dash, I can't do `from my-module-name.fab.fabfile import X,Y,Z` or relative import because it's a non-package. Any recommendation how to do this without hacking with `__import__(...)` or adding it to the sys path? Should I just add another directory? Answer: Use [`importlib.import module`](http://docs.python.org/library/importlib.html#importlib.import_module): import importlib fabfile = importlib.import_module('my-repo-name.fab.fabfile', None) X = fabfile.X But you should really just change the name of the repository. To transition, you can create a temporary [symlink](http://en.wikipedia.org/wiki/Symlink) with $ mv my-repo-name my_repo_name $ ln -s my_repo_name my-repo-name
How can I step to use the python debugger to break at every function call? Question: I want to closely monitor the chain of function calls which are called from a certain function. import pdb; pdb.set_trace() res = api.InsertVideoEntry(video_entry, video) I'm looking for a way to easily see that `api.insertVideoEntry(video_entry, video)` calls `foo()` which calls `bar()` which calls `baz()`, Here's a really crude diagram to show what I mean. I don't need it in this form, but this is the kind kind of information I'm looking for. api.insertVideoEntry() foo() bar() baz() baz2() log() finish() Answer: This was an interesting learning experience to write up. Maybe you can use the code shown here? [This demonstration](http://ideone.com/W3scL) should give you an idea of the type of output you can expect when using `trace`. # Functions to trace # ================== def baz(): pass def baz2(): pass def bar(): baz() baz2() def log(): pass def foo(): bar() log() def finish(): pass def insertVideoEntry(): foo() finish() # Names to trace # ============== names = list(locals()) # Machinery for tracing # ===================== import os import sys def trace(start, *names): def tracefunc(frame, event, arg): if event == 'call': code = frame.f_code name = code.co_name if name in names: level = -start while frame: frame = frame.f_back level += 1 print('{}{}.{}()'.format( ' ' * level, os.path.splitext(os.path.basename(code.co_filename))[0], name)) return tracefunc sys.settrace(tracefunc) # Demonstration of tracing # ======================== trace(2, *names) insertVideoEntry() If you are interested in a recursive demo, you might like [this variation](http://ideone.com/ltcnQ8) with a called arguments readout: import os import sys def main(discs): a, b, c = list(range(discs, 0, -1)), [], [] line = '-' * len(repr(a)) print(a, b, c, sep='\n') for source, destination in towers_of_hanoi(discs, a, b, c): destination.append(source.pop()) print(line, a, b, c, sep='\n') def towers_of_hanoi(count, source, via, destination): if count > 0: count -= 1 yield from towers_of_hanoi(count, source, destination, via) yield source, destination yield from towers_of_hanoi(count, via, source, destination) def trace(start, *names): def tracefunc(frame, event, arg): if event == 'call': code = frame.f_code name = code.co_name if name in names: level = -start args = ', '.join(repr(frame.f_locals[name]) for name in code.co_varnames[:code.co_argcount]) while frame: frame = frame.f_back level += 1 print('{}{}.{}({})'.format( ' ' * (level * 4), os.path.splitext(os.path.basename(code.co_filename))[0], name, args)) return tracefunc sys.settrace(tracefunc) if __name__ == '__main__': trace(3, 'main', 'towers_of_hanoi') main(3)
Python: Read from and write to a CSV file Question: I am trying to read data from a CSV file (A), extract data, and write that to a different CSV file (B). In the new file B, I want to have two columns. Column 1 to list names of column 1 in file A and column 2 to list the count of column 1 in file A. So for example, if the file A looks like this without ':' (they are lined up in two columns): Animal: Gender Rabbit: Male Dog: Male Rabbit: Female Cat: Male Cat: Male Dog: Female Dog: Male Turtle: Male I want the output in file B to look like this (actually in different columns without ':' again): Animal: Count Cat: 2 Dog: 3 Rabbit: 2 Turtle: 1 This is the very first time I am doing anything like this and this is what I have so far, but I am failing in having the data printed out in file B and have the "count" done correctly. Could anybody please help me with this? import csv ReadData=csv.reader(open('C:\Users\..\FileA.csv','rb'), delimiter=',') def column(ReadData, i): return [row[i] for row in ReadData] for line in ReadData: WriteData=csv.writer(open('C:\Users\..\FileB.csv','wb'), delimiter=' ', quotechar=':', quoting=csv.QUOTE_ALL) print column(ReadData,1) Thank you for your help in advance! Answer: To do the counting in Python >=2.7, see [this example for `collections.Counter`](http://stackoverflow.com/a/3496860/1307866). With a `collections.defaultdict`, see [here](http://stackoverflow.com/a/2161791/1307866). In your call to `csv.writer`, the `quotechar=':'` is probably an error (this would make `WriteData.writerow(['Hello World', 12345]`) emit ":Hello World: 12345", as if the colon was a quotation mark. Also note that your function `column(ReadData, i)` consumes `ReadData`; subsequent calls to ReadData will probably return an empty list (not tested). This is not a problem for your code (at least not now). This is a solution without the CSV module (after all, these files do not look too much like CSV): import collections inputfile = file("A") counts = collections.Counter() for line in inputfile: animal = line.split(':')[0] counts[animal] += 1 for animal, count in counts.iteritems(): print '%s: %s' % (animal, count)
Eclipse unresolved external with geopy Question: import csv from geopy import geocoders import time g = geocoders.Google() spamReader = csv.reader(open('locations.csv', 'rb'), delimiter='\t', quotechar='|') f = open("output.txt",'w') for row in spamReader: a = ', '.join(row) #exactly_one = False time.sleep(1) try: place, (lat, lng) = g.geocode(a) except (ValueError, geocoders.google.GQueryError, geocoders.google.GeocoderResultError, geocoders.google.GBadKeyError, geocoders.google.GTooManyQueriesError): #print("Error: geocode failed on input %s with message %s"%(a, error_message) f.write("exception") continue b = str(place) + "," + "[" + str(lat) + "," + str(lng) + "]" + "\n" print b f.write(b) The code I have above works great from the command prompt. I am wondering why when I try to run the script through Eclipse that I keep getting the "Unresolved import: geopy". I have tried to add it somehow under Project->properties->PYTHONPATH but I am having a bear of time finding out how to get Eclipse to recognize the fact that Geopy is installed to 'C:\Python27\Lib\site-packages\geopy-0.94.2-py2.7.egg'. My version of Eclipse is Juno running on Windows 7 with the JDK7u4 powering it. What should I do about this problem? Answer: It appears that under Project->Properties->PyDev - PYTHONPATH there is an area with a tab called "External Libraries". There then is a button to add a zip/jar/egg. The "egg" in question is actually a directory which in my installation is located under: C:\Python27\Lib\site-packages\geopy-0.94.2-py2.7.egg So it is added and then Eclipse Juno will allow for the module to be used in the code.
Is there a way to simulate python random.shuffle of a queue using a pseudorandom sequence or hash function? Question: I'm building an application based around a task queue: it serves a series of tasks to multiple, asynchronously connected clients. The twist is that the **tasks must be served in a random order**. My problem is that the algorithm I'm using now is computationally expensive, because it relies on many large queries and transfers from the database. I have a strong hunch that there's a cheaper way to achieve the same result, but I can't quite see the solution. Can you think of a clever fix for this problem? Here's the (computationally expensive) algorithm I'm using now: When the client queries for a new task... 1. Query the database for "unfinished" tasks 2. Put all tasks in a list 3. Shuffle the list (using random.shuffle) 4. Flag the first task as "in progress" 5. Send the task parameters to the client for completion When the client finishes the task... 6a. Record the result and flag the task as "finished." If the client fails to finish the task by some deadline... 6b. Re-flag the task as "unfinished." Seems like we could do better by replacing steps 1, 2, and 3, with pseudorandom sequences or hash functions. But I can't quite figure out the whole solution. Ideas? Other considerations: * In case it's important, I'm using python and mongodb for all of this. (Mongodb doesn't have some clever "use find_one to efficiently return a random matching entry" usage, does it?) * The term "queue" is a little misleading. All the tasks are stored in subfields of a single collection within the mongodb. The length (total number of tasks) in the collection is known and fixed at the outset. * If it's necessary, it might be okay to let the same task be assigned multiple times, as long as the occurrence is rare. But instances of this kind would need to be very rare, because completing each task is costly. * I have identifying information on each client, so we know exactly who originates each task request. Answer: There _is_ an easy way to get a random document from MongoDB! See [Random record from MongoDB](http://stackoverflow.com/questions/2824157/random-record-from- mongodb) If you don't want a task to be picked twice, you could mark the task as active and not select it.
Why doesn't PIL load locally while running Google App Engine Python 2.7 Mac OSX? Question: I am using Google App engine on Mac OSX 10.7.4. When I load PIL from the commandline, everything works fine. However, when I load it from the GAE local environment, i.e.: > import Image Gives me the error: > ImportError: No module named Image This line works fine: > from google.appengine.api import images So I don't believe there's a problem with my installation. The app works fine when I deploy it to GAE. Also, I load the PIL library in app.yaml: libraries: - name: webapp2 version: "2.5.1" - name: lxml version: latest - name: PIL version: latest - name: numpy version: latest I am also using python in /usr/bin/python, 2.7.1. I have PIL installed using: brew install pip pip install pil Answer: You need to use: `from PIL import Image`.
Iteration of calendar.month_name can't be parsed by strptime() Question: Here's something that seems a little silly: `datetime.strptime()` is happy to accept an iterated list of month names when I just create a list by hand (`months = ['January','February']`) but not when I iterate over a list of months created by `calendar.month_name` even though both return `<type 'str'>` Broken code: import datetime import calendar for month in calendar.month_name: print datetime.datetime.strptime(month,"%B") Error: `ValueError: time data '' does not match format '%B'` Working code: import datetime months = ['January','February','March'] for month in months: print datetime.datetime.strptime(month,"%B") Result: 1900-01-01 00:00:00 1900-02-01 00:00:00 1900-03-01 00:00:00 What's going on here? Is this a behavior of python's `for` loop I am not familiar with? Answer: Try doing `print( list(calendar.month_name) )` and it will become obvious pretty quickly why this fails ... (mainly because the first element yielded is an empty string). Note that the reason the first month yielded is an empty string is because they want `month_names[1]` to correspond to `January` as is the common convention (see the [documentation](http://docs.python.org/library/calendar.html?highlight=calendar#calendar.month_name)) You _could_ do something like this: a = list( calendar.month_names )[1:] or this also works in Cpython at least (although it isn't clear in the documentation if it should): a = calendar.month_names[1:]
Subtract values in one list from corresponding values in another list - Python Question: I have two lists: A = [2, 4, 6, 8, 10] B = [1, 3, 5, 7, 9] How do I subtract each value in one list from the corresponding value in the other list and create a list such that: C = [1, 1, 1, 1, 1] Thanks. Answer: The easiest way is to use a list comprehension C = [a - b for a, b in zip(A, B)] or `map()`: from operator import sub C = map(sub, A, B)