text
stringlengths
226
34.5k
Python Pandas: how to turn a DataFrame with "factors" into a design matrix for linear regression? Question: If memory servies me, in R there is a data type called factor which when used within a DataFrame can be automatically unpacked into the necessary columns of a regression design matrix. For example, a factor containing True/False/Maybe values would be transformed into: 1 0 0 0 1 0 or 0 0 1 for the purpose of using lower level regression code. Is there a way to achieve something similar using the pandas library? I see that there is some regression support within Pandas, but since I have my own customised regression routines I am really interested in the construction of the design matrix (a 2d numpy array or matrix) from heterogeneous data with support for mapping back and fort between columns of the numpy object and the Pandas DataFrame from which it is derived. Update: Here is an example of a data matrix with heterogeneous data of the sort I am thinking of (the example comes from the Pandas manual): >>> df2 = DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],'c' : np.random.randn(7)}) >>> df2 a b c 0 one x 0.000343 1 one y -0.055651 2 two y 0.249194 3 three x -1.486462 4 two y -0.406930 5 one x -0.223973 6 six x -0.189001 >>> The 'a' column should be converted into 4 floating point columns (in spite of the meaning, there are only four unique atoms), the 'b' column can be converted to a single floating point column, and the 'c' column should be an unmodified final column in the design matrix. Thanks, SetJmp Answer: There is a new module called patsy that solves this problem. The quickstart linked below solves exactly the problem described above in a couple lines of code. * <http://patsy.readthedocs.org/en/latest/overview.html> * <http://patsy.readthedocs.org/en/latest/quickstart.html> Here is an example usage: import pandas import patsy dataFrame = pandas.io.parsers.read_csv("salary2.txt") #salary2.txt is a re-formatted data set from the textbook #Introductory Econometrics: A Modern Approach #by Jeffrey Wooldridge y,X = patsy.dmatrices("sl ~ 1+sx+rk+yr+dg+yd",dataFrame) #X.design_info provides the meta data behind the X columns print X.design_info generates: > DesignInfo(['Intercept', > 'sx[T.male]', > 'rk[T.associate]', > 'rk[T.full]', > 'dg[T.masters]', > 'yr', > 'yd'], > term_slices=OrderedDict([(Term([]), slice(0, 1, None)), (Term([EvalFactor('sx')]), slice(1, 2, None)), > (Term([EvalFactor('rk')]), slice(2, 4, None)), > (Term([EvalFactor('dg')]), slice(4, 5, None)), > (Term([EvalFactor('yr')]), slice(5, 6, None)), > (Term([EvalFactor('yd')]), slice(6, 7, None))]), > builder=<patsy.build.DesignMatrixBuilder at 0x10f169510>)
Using django to run python scripts with password arguments Question: I need to create a web interface that will prompt for a username, password, and "record id" to run a separate python script using those credentials, and then spit back a generated file. The separate script I wrote takes a username/password (and ID) to connect to an Oracle database (using cx_Oracle), gathers the relevant information, generates a PDF and saves it to a preset location. It spits out the location of the filename when it's done. My thought was to create a django app that takes the following 3 parameters: * Username * Password * ID (this will be used to determine which records to fetch for the PDF) Django will feed the parameters to the script by calling subprocess. I would put this into my view like so: # ... import subprocess # ... def login_view(request): username = password = '' if request.POST: username = request.POST.get('username') password = request.POST.get('password') record_id = request.POST.get('record_id') output = subprocess.check_output([ "python", "myscript.py", "-id", record_id, "-u", username, "-p", password ]) # The output will look like: # File /path/to/1234567.pdf saved fname = output.split(' ')[1] if fname.endswith('.pdf'): # Get the filename without the /path/to junk in front fname_nopath = fname.split('/')[-1] file = open(fname, 'rb') content = file.read() file.close response = HttpResponse(content, mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=%s' % fname_nopath return response else: response = HttpResponse(output) return response I think this method is a little "clunky", and I would think there's a more elegant approach to take. Another way I was thinking about would be to import the external script directly into my views.py file, then call its main function using the username, password, and record ID passed from django. This way I can avoid the subprocess machinery. If needed I can create a separate main() function in the script, have it return a filestring, and use that for both opening/serving the file through django. The only problem is this interface is going to be used pretty frequently by users. To require them to login every time to generate a PDF report for each record_id is a bit of a pain. Ideally I would like to keep the users logged in (I think I would have to maintain a cx_Oracle cursor separately, and pass that into the script). My feeling is that this is overcomplicating things. Is there a better way to do this or did I miss something? Answer: 1) You should use django forms for handling user passed parameters. 2) You could save username/password in user's session- this way users won't need to enter them again. 3) This really depends on how much record id's you have, but you could show a list of available record id's by querying the database.
post-ing a file using python requests and json Question: I've been given the following curl command as part of API documentation, and I'm trying to implement it using the requests library. curl -v --cookie cookie.txt -X POST -H 'Accept: application/json' -F 'spot[photo]'[email protected] -F 'spot[description]'=spot_description -F 'spot[location_id]'=9 -F 'spot[categories][]'='See the Sights' -F 'spot[categories][]'='Learn Something' http://some.server.com/api/v1/spots my python code looks something like this: import requests import json _user = 'redacted' _password = 'redacted' _session = requests.session() _server = 'http://some.server.com' _hdr = {'content-type': 'application/json', 'accept': 'application/json'} _login_payload = { 'user': { 'email': _user, 'password': _password } } r = _session.post(_server + "/users/sign_in", data=json.dumps(_login_payload), headers=_hdr) print json.loads(r.content) _spot_payload = { 'spot': { 'photo': '@rails.gif', 'description': 'asdfghjkl', 'location_id': 9, 'categories': ['See the Sights',] } } r = _session.post(_server + '/api/v1/spots', data=json.dumps(_spot_payload), headers=_hdr) print json.loads(r.content) I've heard tell that you can use open('file').read() to post files, but the json encoder doesn't much like this, and I'm not sure about a way around it. Answer: C:\>cat file.txt Some text. When you issue this command: C:\>curl -X POST -H "Accept:application/json" -F "spot[photo][email protected]" -F "spot[description]=spot_description" http://localhost:8888 what's being sent looks like this: > POST / HTTP/1.1 User-Agent: curl/7.25.0 (i386-pc-win32) libcurl/7.25.0 > OpenSSL/0.9.8u zlib/1.2.6 libssh2/1.4.0 Host: localhost:8888 Accept: > application/json Content-Length: 325 Expect: 100-continue Content-Type: > multipart/form-data; boundary=----------------------------e71aebf115cd > > \------------------------------e71aebf115cd Content-Disposition: form-data; > name="spot[photo]"; filename="file.txt" Content-Type: text/plain > > Some text. \------------------------------e71aebf115cd Content-Disposition: > form-data; name="spot[description]" > > spot_description \------------------------------e71aebf115cd-- As you can see curl sends request with `Content-Type` set to `multipart/form- data;` Requests [support](http://docs.python- requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file) sending files using the same `Content-Type`. You should use `files` argument for this. (2.7) C:\>python Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> requests.__version__ '0.11.1' >>> requests.post('http://localhost:8888', files={'spot[photo]': open('file.txt', 'rb')}, data={'spot[description]': 'spot_description'}) <Response [200]> And what's being sent looks like this: POST http://localhost:8888/ HTTP/1.1 Host: localhost:8888 Content-Length: 342 Content-Type: multipart/form-data; boundary=192.168.1.101.1.8000.1334865122.004.1 Accept-Encoding: identity, deflate, compress, gzip Accept: */* User-Agent: python-requests/0.11.1 --192.168.1.101.1.8000.1334865122.004.1 Content-Disposition: form-data; name="spot[description]" Content-Type: text/plain spot_description --192.168.1.101.1.8000.1334865122.004.1 Content-Disposition: form-data; name="spot[photo]"; filename="file.txt" Content-Type: text/plain Some text. --192.168.1.101.1.8000.1334865122.004.1--
Django Multi-table Inheritance, Django-model-utils errors Question: I am working on a hobby project for my garage shop. I was directed to django- model-utils for what I need. (I have serial CNC machines, serial machines have two flow control methods) I have a parent class of SerialMachine (defines address, baud rate, generic RS-232 definition) Then I have HardwareFlowControlMachine model which inherits from SerialMachine (defines CTS/DTR/etc) So when I put machine name into a form (say machine 001) I have a function that get's machine settings. def getMachineSettings(machine): from src.apps.cnc.models import SerialMachine machineSettings = SerialMachine.objects.get(machineName=machine).select_subclasses() return machineSettings I get this exception: DatabaseError: no such column: cnc_hardwareflowcontrolmachine.serialmachine_ptr_id Now for testing I only have one machine in SoftwareFlowControlMachine (none in Hardware) I thought maybe HardwareFlowControlMachine needed at least one object for whatever reason. So when I go to /admin/ and try to add a machine to either SoftwareFlowControlMachine or HardwareFlowControlMachine I get this exception: HardwareFlowControlMachine: DatabaseError at /admin/cnc/hardwareflowcontrolmachine/ no such column: cnc_hardwareflowcontrolmachine.serialmachine_ptr_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/cnc/hardwareflowcontrolmachine/ Django Version: 1.4 Exception Type: DatabaseError Exception Value: no such column: cnc_hardwareflowcontrolmachine.serialmachine_ptr_id Exception Location: C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 337 Python Executable: C:\Python27\python.exe Python Version: 2.7.2 SoftwareFlowControlMachine: DatabaseError at /admin/cnc/softwareflowcontrolmachine/ no such column: cnc_softwareflowcontrolmachine.serialmachine_ptr_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/cnc/softwareflowcontrolmachine/ Django Version: 1.4 Exception Type: DatabaseError Exception Value: no such column: cnc_softwareflowcontrolmachine.serialmachine_ptr_id Exception Location: C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 337 Python Executable: C:\Python27\python.exe Python Version: 2.7.2 Let me know if I need to provide more info. I am really not sure what I am missing Answer: I got it working. I'm still unclear on why it happened though. A mistake I made is instead of machineSettings = SerialMachine.objects.get(machineName=machine).select_subclasses() I needed this machineSettings = SerialMachine.objects.get_subclass(machineName=machine) I also just deleted my database and remade it. Hope this helps others too
Python BeautifulSoup double question mark in xml definition Question: I thought it must be a bug so i issued a bug report [here](https://bugs.launchpad.net/beautifulsoup/+bug/984258). On the other hand i might be missing something so i need another look on the code. The problem is, when i initialize BeautifulSoup with contents of an .xhtml file, xml definition gets two question marks at the end of it. Can you reproduce the problem? Is there a way to avoid it? Am i missing a function, a method, an argument or something? **Edit0:** It's BeautifulSoup 4 on python 2.x. **Edit1:** Why downvote? * * * The problem: <?xml version="1.0" encoding="UTF-8"??> Terminal Output: >>> from bs4 import BeautifulSoup as bs >>> with open('example.xhtml', 'r') as f: ... txt = f.read() ... soup = bs(txt) ... >>> print txt <?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"/> </head> <body> </body> </html> >>> print soup <?xml version="1.0" encoding="UTF-8"??> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"/> </head> <body> </body> </html> Answer: Consider using an XML parser: soup = bs(txt, 'xml')
Using Global variables in Threads in Python Question: I am in a situation where i want to put a thread in a loop depending on a variable which is being changed in one of the called function in the thread.Here is what i want. error= 0 while( error = 0) run_thread = threading.Thread(target=self.run_test,args=(some arguments)) if ( error = 0) continue else: break Now run test calls a function say A and A calls B and B calls C. def A() B() def B() c() def c() global error error = 1 This is what i want to do but i cant work this out. If i try to print error i get an error in code. Can anybody please help me on this? i am a beginner and need to get over this Answer: error = False def A(): B() def B(): c() def c(): global error error = True def run_test(): while not error: A() print "Error!" import threading run_thread = threading.Thread(target=run_test,args=()) run_thread.start() However, its better to subclass thread and re-implement run(), and also use exceptions: def A(): raise ValueError("Bad Value") import threading class StoppableThread(threading.Thread): def __init__(self, *args, **kwargs): self.stop = False def run(self): while not self.stop: A() #Will raise, which will stop the thread 'exceptionally' def stop(self): #Call from main thread, thread will eventually check this value and exit 'cleanly' self.stop = True
Send bash environment variable back to python fabric Question: I am attempting to pass a bash environment variable back into my fabric function like this:- from fabric.api import env def env_localhost(): "All the environment variables relating to your localhost" project_home = local('echo $PROJECT_HOME') print 111, project_home But it doesn't seem to be able to retrieve the stdout results and assign it to my python `project_home` variable. What's the correct way to do this right? Answer: Do it like this: import os os.getenv("PATH")
C# .NET interoperabillity with managed Python (CPython) -> any problems? Question: I am working on a design of an application. The Core should be written in C# but i also want to use some already finished CPython modules (un-managed). So I am interested in the interoperability (Call CPython method from C# and Call C# from CPython). And if there are problems, because C# runs within the .NET runtime (managed) and CPython directly un-managed. I already investigated this issue with Google and came out to these solutions: * Use IronPython via DLR + "CPython extension" + maybe "IronClad" and call from IronPython the CPython modules and vice versa -> are these modules executed managed or unmanaged ? Are There any problems if i want to use C# classes and methods from CPython ? * Use "Python for .NET" -> the same question as above. What do you think, which way would be better ? or do you have another solution ? And the last but maybe most important question, did I understand the above mentioned points right, or do I mess up ? Many thanks in advance !! Answer: I think you misunderstand Python. It's an interpreted1 language. You just provide the text source files and the interpreter will execute them. There is a difference between the _language_ Python and the _implementations_ CPython, IronPython, Jython, PyPy, what have you. Each of them attempts to implement the language Python as accurately as possible, while also adding implementation-specific functionality. This is just like how, say, the C# compiler was written in C++. For example, any (pure) Python file can be executed by the IronPython interpreter. But if you know that you're going to use IronPython, you can use the special IronPython features that let you into the .NET library. Now, most Python doesn't use any of the implementation-specific functionality, so it doesn't matter what you use to run it. Some Python does, though. 1Well, it's compiled into .pyc files... but then "compile" isn't really a well-defined term anyway. * * * Why does this matter to you? Well, you have a bunch of Python source code that you want to use with the .NET framework. If that code doesn't use any of the CPython-specific features -- such as using C extension modules -- then you can just run it in IronPython.
python compare words Question: I have stuck with following problem: I am trying to get subject and compare from email (it's saved on disk, email in UTF-8) import re def check_subj(): subj = "" file = open("/home/hikaru/Desktop/sub.eml", "r") for line in file: try: a = re.search("Subject:\ ", line, re.IGNORECASE) a = line[a.end():] subj = a break except AttributeError: pass return subj print(check_subj()) if check_subj() == 'sub': print("yay") Everything seems fine to me, "print" successfully shows me "sub", but comparison won't print "yay" for me. I can't understand why -( Answer: An end of line, as suggested, is the probable cause of your problem. Here is a more robust solution (the loop only) for line in file: match = re.search("Subject:\ (.*)", line, re.IGNORECASE) if match: subj = match.group(1) break
Basic indentation - Python Question: #RockPS import random Choices=['R','P','S'] UserScore=0 CpuScore=0 Games=0 while Games<6: UserChoice=input('Rock, paper or scissors? (Type R, P or S respectively)') if UserChoice in Choices: Games+=1 CpuChoice = random.choice(Choices) if UserChoice == 'S' and CpuChoice == 'P': UserScore+=1 if UserChoice == 'P' and CpuChoice == 'R': UserScore+=1 if UserChoice == 'R' and CpuChoice == 'S': UserScore+=1 if UserChoice == 'S' and CpuChoice == 'R': CpuScore+=1 if UserChoice == 'P' and CpuChoice == 'S': CpuScore+=1 if UserChoice == 'R' and CpuChoice == 'P': CpuScore+=1 print(UserScore, CpuScore) if UserScore>CpuScore: print('Well done, you won!') if UserScore==CpuScore: print('You tied!') if UserScore<CpuScore: ('Unlucky, you lost.') I'm new to Python so it's likely I've missed something obvious. The program runs fine. It's a Rock, Paper or Scissors game. 5 games are played and the scores are listed at the end of the game. At the moment, it only says 1 0, 0 0, or 0 1 either way, only counting 1 game. I'm not sure why this is. I think that it is to do with my indentation as I don't see a problem with my loop. Answer: Here's what's going on: this part of your code while Games<6: UserChoice=input('Rock, paper or scissors? (Type R, P or S respectively)') if UserChoice in Choices: Games+=1 executes 6 times, but all the remaining lines from here down: CpuChoice = random.choice(Choices) if UserChoice == 'S' and CpuChoice == 'P': UserScore+=1 if UserChoice == 'P' and CpuChoice == 'R': UserScore+=1 only execute once, after the loop iterations are complete. All of the `if UserChoice ==` lines should be indented so that they are part of the loop body.
python string to function: globals() vs sys.module vs dictionary Question: I want to know what is the best way to map the string to a function. so far I know I can use: 1. globals()[func_string] 2. sys.modules[__name__] 3. funcs_dictionary["func_string" : func] Here is the code: >>> def foo(arg): ... print "I'm foo: %s" % arg ... >>> def bar(arg): ... print "I'm bar: %s" % arg ... >>> >>> foo <function foo at 0xb742c7d4> >>> bar <function bar at 0xb742c80c> >>> globals()[func_string]: >>> def exec_funcs_globals(funcs_string): ... for func_string in funcs_string: ... func = globals()[func_string] ... func("from globals() %s" % func) ... >>> exec_funcs_globals(["foo", "bar"]) I'm foo: from globals() <function foo at 0xb742c7d4> I'm bar: from globals() <function bar at 0xb742c80c> >>> sys.modules[__name__]: >>> import sys >>> >>> def exec_funcs_thismodule(funcs_string): ... thismodule = sys.modules[__name__] ... for func_string in funcs_string: ... func = getattr(thismodule, func_string) ... func("from thismodule %s" % func) ... >>> exec_funcs_thismodule(["foo", "bar"]) I'm foo: from thismodule <function foo at 0xb742c7d4> I'm bar: from thismodule <function bar at 0xb742c80c> >>> funcs_dictionary["func_string" : func]: >>> funcs = { ... "foo" : foo, ... "bar" : bar ... } >>> >>> def exec_funcs_dict(funcs_string): ... for func_string in funcs_string: ... func = funcs[func_string] ... func("from thismodule %s" % func) ... >>> exec_funcs_dict(["foo", "bar"]) I'm foo: from thismodule <function foo at 0xb742c7d4> I'm bar: from thismodule <function bar at 0xb742c80c> Originally I was worry about the sys.modules[__name__] will reload the modules and hurt the performance. But the code above seem to show that the function pointers are the same, so I guess I don't have to worry about it? What is the best use case for the option 1, 2, 3? Answer: Using _globals()_ is the normal way to access (and store) variables you want to access globally. Otherwise, the usual choice is to implement a dispatch dictionary (like your option 3). I've not seen the _sys.modules_ approach used anywhere.
Can't close Excel completely using win32com on Python Question: This is my code, and I found many answers for [VBA](http://en.wikipedia.org/wiki/Visual_Basic_for_Applications), .NET framework and is pretty strange. When I execute this, Excel closes. from win32com.client import DispatchEx excel = DispatchEx('Excel.Application') wbs = excel.Workbooks wbs.Close() excel.Quit() wbs = None excel = None # <-- Excel Closes here But when I do the following, it does not close. excel = DispatchEx('Excel.Application') wbs = excel.Workbooks wb = wbs.Open('D:\\Xaguar\\A1.xlsm') wb.Close(False) wbs.Close() excel.Quit() wb = None wbs = None excel = None # <-- NOT Closing !!! I found some possible answer in Stack Overflow question _[Excel process remains open after interop; traditional method not working](http://stackoverflow.com/questions/8977571/excel-process-remains- open-after-interop-traditional-method-not-working)_. The problem is that is not Python, and I don't find `Marshal.ReleaseComObject` and `GC`. I looked over all the demos on `...site-packages/win32com` and others. Even it does not bother me if I can just get the PID and kill it. I found a workaround in _[Kill process based on window name (win32)](http://python.6.n6.nabble.com/Kill-process-based-on-window-name- win32-td1042063.html)_. May be not the proper way, but a workround is: def close_excel_by_force(excel): import win32process import win32gui import win32api import win32con # Get the window's process id's hwnd = excel.Hwnd t, p = win32process.GetWindowThreadProcessId(hwnd) # Ask window nicely to close win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) # Allow some time for app to close time.sleep(10) # If the application didn't close, force close try: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p) if handle: win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle) except: pass excel = DispatchEx('Excel.Application') wbs = excel.Workbooks wb = wbs.Open('D:\\Xaguar\\A1.xlsm') wb.Close(False) wbs.Close() excel.Quit() wb = None wbs = None close_excel_by_force(excel) # <--- YOU #@#$# DIEEEEE!! DIEEEE!!! Answer: Try this: wbs.Close() excel.Quit() del excel # this line removed it from task manager in my case
How Do I Read a Multi-line File of JSON and Count Words in Specific Field in Python Question: I have a file with many hundreds of lines of json encoded tweets pulled from python-tweetstreamer. The lines look like: {"favorited": false, "in_reply_to_user_id": null, "contributors": null, "truncated": false, "text": "kasian pak weking :| RT @veNikenD: Kasian kenapa???RT @SaputraJordhy: kasian \u256e(\u256f_\u2570)\u256d RT @veNikenD: Tak ingin lg kudengar kata2 yg tak ......", "created_at": "Tue Apr 03 14:07:59 +0000 2012", "retweeted": false, "in_reply_to_status_id": null, "coordinates": null, "in_reply_to_user_id_str": null, "entities": {"user_mentions": [{"indices": [24, 33], "screen_name": "veNikenD", "id": 64910664, "name": "Ve Damayanti", "id_str": "64910664"}, {"indices": [54, 68], "screen_name": "SaputraJordhy", "id": 414675856, "name": "jordhy_ynwa", "id_str": "414675856"}, {"indices": [88, 97], "screen_name": "veNikenD", "id": 64910664, "name": "Ve Damayanti", "id_str": "64910664"}], "hashtags": [], "urls": []}, "in_reply_to_status_id_str": null, "id_str": "187179645026836481", "in_reply_to_screen_name": null, "user": {"follow_request_sent": null, "profile_use_background_image": true, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/418679759/Young_Minato_and_Kushina_by_HaNa7.jpg", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1953774147/Untitled1_normal.png", "profile_sidebar_fill_color": "DDEEF6", "is_translator": false, "id": 414675856, "profile_text_color": "1c181c", "followers_count": 46, "protected": false, "location": "", "default_profile_image": false, "listed_count": 0, "utc_offset": 25200, "statuses_count": 409, "description": "never walk alone", "friends_count": 76, "profile_link_color": "0084B4", "profile_image_url": "http://a0.twimg.com/profile_images/1953774147/Untitled1_normal.png", "notifications": null, "show_all_inline_media": false, "geo_enabled": false, "profile_background_color": "C0DEED", "id_str": "414675856", "profile_background_image_url": "http://a0.twimg.com/profile_background_images/418679759/Young_Minato_and_Kushina_by_HaNa7.jpg", "screen_name": "SaputraJordhy", "lang": "id", "profile_background_tile": true, "favourites_count": 0, "name": "jordhy_ynwa", "url": null, "created_at": "Thu Nov 17 10:41:05 +0000 2011", "contributors_enabled": false, "time_zone": "Jakarta", "profile_sidebar_border_color": "C0DEED", "default_profile": false, "following": null}, "place": null, "retweet_count": 0, "geo": null, "id": 187179645026836481, "source": "<a href=\"https://embr.in\" rel=\"nofollow\">embr</a>"} {"favorited": false, "in_reply_to_user_id": 441527150, "contributors": null, "truncated": false, "text": "@akoriko1046 \u5bdd\u308b\u306e\uff1f\u3000\u5f85\u3063\u3066\u50d5\u3082\u884c\u304f\u3088\u2026\u5e03\u56e3\u307e\u3067\u304a\u59eb\u69d8\u62b1\u3063\u3053\u3057\u3066\u3044\u3063\u3066\u3042\u3052\u308b", "created_at": "Tue Apr 03 14:07:59 +0000 2012", "retweeted": false, "in_reply_to_status_id": 187179532103598080, "coordinates": null, "in_reply_to_user_id_str": "441527150", "entities": {"user_mentions": [{"indices": [0, 12], "screen_name": "akoriko1046", "id": 441527150, "name": "\u30a2\u30b3\u30ea\u30b3", "id_str": "441527150"}], "hashtags": [], "urls": []}, "in_reply_to_status_id_str": "187179532103598080", "id_str": "187179645014253568", "in_reply_to_screen_name": "akoriko1046", "user": {"follow_request_sent": null, "profile_use_background_image": true, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/440543906/122004876_org.jpg", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1870697453/__________bg_normal.jpg", "profile_sidebar_fill_color": "DDEEF6", "is_translator": false, "id": 513679998, "profile_text_color": "333333", "followers_count": 169, "protected": false, "location": "\u3042\u306a\u305f\u306e\u96a3", "default_profile_image": false, "listed_count": 2, "utc_offset": 32400, "statuses_count": 6024, "description": "\u8584\u685c\u9b3c\u6c96\u7530\u7dcf\u53f8\u306e\u975e\u516c\u5f0fbot\u3067\u3059\u7518\u7518/\u30a8\u30ed\u8a2d\u5b9a\u3000\uff8c\uff6b\uff9b\uff70\u306e\u518d\u306f\u5fc5\u305a\u8aac\u660e\u66f8\u3092\u4e00\u8aad\u4e0b\u3055\u3044http://www.pixiv.net/novel/show.php?id=934499 \u624b\u52d5\u3067\u30d5\u30a9\u30ed\u8fd4\u3057\u3092\u884c\u3063\u3066\u307e\u3059\u3000\u7a00\u306b\u4e2d\u306b\u7ba1\u7406\u4eba\u304c\u3044\u307e\u3059\u3000\u7ba1\u7406\u4eba@akanemam1 18\u7981\u7dcf\u53f8\u2192 @sou_oki_18bot", "friends_count": 166, "profile_link_color": "0084B4", "profile_image_url": "http://a0.twimg.com/profile_images/1870697453/__________bg_normal.jpg", "notifications": null, "show_all_inline_media": false, "geo_enabled": false, "profile_background_color": "C0DEED", "id_str": "513679998", "profile_background_image_url": "http://a0.twimg.com/profile_background_images/440543906/122004876_org.jpg", "screen_name": "sou_oki_bot", "lang": "ja", "profile_background_tile": false, "favourites_count": 1, "name": "\u7dcf\u53f8(bot)", "url": null, "created_at": "Sat Mar 03 22:36:15 +0000 2012", "contributors_enabled": false, "time_zone": "Irkutsk", "profile_sidebar_border_color": "C0DEED", "default_profile": false, "following": null}, "place": null, "retweet_count": 0, "geo": null, "id": 187179645014253568, "source": "<a href=\"http://twittbot.net/\" rel=\"nofollow\">twittbot.net</a>"} {"favorited": false, "in_reply_to_user_id": 141448885, "contributors": null, "truncated": false, "text": "@nobuttu3 \u6642\u9593\u304c\u904e\u304e\u308b\u306e\u304c\u7269\u51c4\u304f\u65e9\u3044\u3067\u3059\u3088\u306d\u2026", "created_at": "Tue Apr 03 14:07:59 +0000 2012", "retweeted": false, "in_reply_to_status_id": 187179547098234880, "coordinates": null, "in_reply_to_user_id_str": "141448885", "entities": {"user_mentions": [{"indices": [0, 9], "screen_name": "nobuttu3", "id": 141448885, "name": "\u306e\u4ecf \uf8ff \u30bf\u30ab\u30cf\u30b7", "id_str": "141448885"}], "hashtags": [], "urls": []}, "in_reply_to_status_id_str": "187179547098234880", "id_str": "187179645047799808", "in_reply_to_screen_name": "nobuttu3", "user": {"follow_request_sent": null, "profile_use_background_image": true, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/424878981/tw_hvt_nz.jpg", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1223811261/twitter_icon_normal.png", "profile_sidebar_fill_color": "daecf4", "is_translator": false, "id": 97481308, "profile_text_color": "663B12", "followers_count": 436, "protected": false, "location": "\u6771\u4eac\u90fd\u53f0\u6771\u533a", "default_profile_image": false, "listed_count": 20, "utc_offset": 32400, "statuses_count": 63704, "description": "\u591a\u5206PG\u3001\u6642\u3005SE\u307d\u3044\u4ed5\u4e8b\u3092\u3057\u3066\u3044\u307e\u3059\u3002\u30e9\u30ce\u30d9\u597d\u304d\u3001\u97f3\u697d\u597d\u304d(\u7279\u5b9a\u306e\u5206\u91ce\u3067\u3059\u304c)\u3002\u30bd\u30b3\u30bd\u30b3\u306e\u983b\u5ea6\u3067\u79cb\u8449\u539f\u306b\u3044\u305f\u308a\u3082\u3057\u307e\u3059\u3002 ", "friends_count": 896, "profile_link_color": "1F98C7", "profile_image_url": "http://a0.twimg.com/profile_images/1223811261/twitter_icon_normal.png", "notifications": null, "show_all_inline_media": false, "geo_enabled": false, "profile_background_color": "ffffff", "id_str": "97481308", "profile_background_image_url": "http://a0.twimg.com/profile_background_images/424878981/tw_hvt_nz.jpg", "screen_name": "xi6", "lang": "ja", "profile_background_tile": false, "favourites_count": 4473, "name": "\u3055\u304f", "url": null, "created_at": "Thu Dec 17 16:55:25 +0000 2009", "contributors_enabled": false, "time_zone": "Tokyo", "profile_sidebar_border_color": "C6E2EE", "default_profile": false, "following": null}, "place": null, "retweet_count": 0, "geo": null, "id": 187179645047799808, "source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iOS</a>"} {"favorited": false, "in_reply_to_user_id": null, "contributors": null, "truncated": false, "text": "#ImSingleBecause lolz I'm not. Happily taken by @GarrettBettler &lt;33 I love him, forever :)", "created_at": "Tue Apr 03 14:07:59 +0000 2012", "retweeted": false, "in_reply_to_status_id": null, "coordinates": null, "in_reply_to_user_id_str": null, "entities": {"user_mentions": [{"indices": [48, 63], "screen_name": "GarrettBettler", "id": 460816116, "name": "Garrett Bettler", "id_str": "460816116"}], "hashtags": [{"indices": [0, 16], "text": "ImSingleBecause"}], "urls": []}, "in_reply_to_status_id_str": null, "id_str": "187179645039427584", "in_reply_to_screen_name": null, "user": {"follow_request_sent": null, "profile_use_background_image": true, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/452188318/tanja_beach_2007_001.JPG", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/1971847266/image_normal.jpg", "profile_sidebar_fill_color": "f6ffd1", "is_translator": false, "id": 461432420, "profile_text_color": "333333", "followers_count": 222, "protected": false, "location": "", "default_profile_image": false, "listed_count": 0, "utc_offset": null, "statuses_count": 2334, "description": "", "friends_count": 192, "profile_link_color": "0099CC", "profile_image_url": "http://a0.twimg.com/profile_images/1971847266/image_normal.jpg", "notifications": null, "show_all_inline_media": false, "geo_enabled": false, "profile_background_color": "FFF04D", "id_str": "461432420", "profile_background_image_url": "http://a0.twimg.com/profile_background_images/452188318/tanja_beach_2007_001.JPG", "screen_name": "LeahOswalt", "lang": "en", "profile_background_tile": false, "favourites_count": 86, "name": "Leah Oswalt", "url": null, "created_at": "Wed Jan 11 20:07:24 +0000 2012", "contributors_enabled": false, "time_zone": null, "profile_sidebar_border_color": "fff8ad", "default_profile": false, "following": null}, "place": null, "retweet_count": 0, "geo": null, "id": 187179645039427584, "source": "<a href=\"http://twitter.com/#!/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>"} {"favorited": false, "in_reply_to_user_id": 434884235, "contributors": null, "truncated": false, "text": "@nomimushi_ttk \u3068\u30fc\u3084\u3082\u7d20\u6575\u3060\u3051\u3069\u306e\u307f\u3080\u3057\u306e\u30a2\u30a4\u30b3\u30f3\u5929\u4f7f\u3059\u304e\u3066", "created_at": "Tue Apr 03 14:07:59 +0000 2012", "retweeted": false, "in_reply_to_status_id": 187179241664815105, "coordinates": null, "in_reply_to_user_id_str": "434884235", "entities": {"user_mentions": [{"indices": [0, 14], "screen_name": "nomimushi_ttk", "id": 434884235, "name": "\u306e\u307f\u3080\u3057", "id_str": "434884235"}], "hashtags": [], "urls": []}, "in_reply_to_status_id_str": "187179241664815105", "id_str": "187179645026836480", "in_reply_to_screen_name": "nomimushi_ttk", "user": {"follow_request_sent": null, "profile_use_background_image": true, "profile_background_image_url_https": "https://si0.twimg.com/images/themes/theme1/bg.png", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/2023688835/6222d8ae387e6fb5b220895d2fd2d41a_normal.gif", "profile_sidebar_fill_color": "DDEEF6", "is_translator": false, "id": 365471550, "profile_text_color": "333333", "followers_count": 308, "protected": false, "location": "\u5b66\u5712\u30a2\u30ea\u30b9\u306b\u518d\u71b1\u306a\u3046", "default_profile_image": false, "listed_count": 17, "utc_offset": 32400, "statuses_count": 25562, "description": "\uff8c\uff9e\uff9a10/\u3046\u305f\u30d7\u30ea/HTF/\u3044\u306c\u307c\u304f\u306a\u3069\u306b\u304a\u71b1/\u5d50\u306e\u5927\u91ce\u304f\u3093\u3059\u304d\uff01\u64ec\u4eba\u5316\u3082\u3050\u3082\u3050/\u30a4\u30ca\u30a4\u30ec/RKRN/pkmn/\uff83\uff86\uff8c\uff9f\uff98/\u4e59\u5973\uff79\uff9e\uff70\u5168\u822c\u3082 [\u30bf\u30ab\u4e38\u3055\u3093\u30e2\u30b0\u30e2\u30b0\u30da\u30c3\u3063\u3066\u3057\u968a\u54e1No.2\uff3c\u526f\u968a\u9577\uff0f]\u3000\u898f\u5236\u57a2\u3010@ao_sanagi_2\u3011\u30a2\u30a4\u30b3\u30f3\u306f\u3068\u30fc\u3084\u304b\u3089\uff01", "friends_count": 284, "profile_link_color": "0084B4", "profile_image_url": "http://a0.twimg.com/profile_images/2023688835/6222d8ae387e6fb5b220895d2fd2d41a_normal.gif", "notifications": null, "show_all_inline_media": false, "geo_enabled": false, "profile_background_color": "C0DEED", "id_str": "365471550", "profile_background_image_url": "http://a0.twimg.com/images/themes/theme1/bg.png", "screen_name": "ao_sanagi", "lang": "ja", "profile_background_tile": false, "favourites_count": 1071, "name": "\u8475@\u6284\u82b1\u306e\u5ac1", "url": null, "created_at": "Wed Aug 31 14:07:23 +0000 2011", "contributors_enabled": false, "time_zone": "Tokyo", "profile_sidebar_border_color": "C0DEED", "default_profile": true, "following": null}, "place": null, "retweet_count": 0, "geo": null, "id": 187179645026836480, "source": "<a href=\"http://www.movatwi.jp\" rel=\"nofollow\">\u30e2\u30d0\u30c4\u30a4 / www.movatwi.jp .</a>"} My end goal is to count the number of times a specific word occurs in the "text" field of all the tweets. I have tried a number of different approaches with varying degrees of success but here's where I'm at: import fileinput import json import sys import os line = [] inputfilename = sys.argv[1] for line in fileinput.input([inputfilename]): tweettext = json.loads(line).get('text').split() print tweettext This loops through the file and splits the text up into the individual words from each lines "text" field but does not create a single list of words. To add to the issue when it runs into a blank line it fails: [u'RT', u'@keenakan:', u'kamu', u'tidak', u'perlu', u'memperjuangkan', u'aku.', u'Yang', u'perlu', u'ialah', u'aku', u'dan', u'kamu', u'yang', u'memperjuangkan', u'kita.', u'-@commaditya'] [u'RT', u'@TheRealToxicBoi:', u'#LiesBeforeSex', u"I'll", u'be', u'Gentle!'] [u'@coliriostar', u'Quer', u'GANHAR', u'R$', u'300,00', u'em', u'vale', u'compra?', u'SIGA', u'@eucompronanet', u'e', u'saiba', u'como', u'participar,', u'\xe9', u'simples', u'e', u'r\xe1pido!', u'at\xe9', u'+', u'ci'] Traceback (most recent call last): File "newexample.py", line 11, in <module> tweettext = json.loads(line).get('text').split() AttributeError: 'NoneType' object has no attribute 'split' Can anyone suggest a solution? edit: Based on the first comment I've edited the code as follows based on my understanding: import fileinput import json import sys import os line = [] tw = 0 inputfilename = sys.argv[1] for line in fileinput.input([inputfilename]): line = line.strip(); if not line: continue tweettext = json.loads(line).get('text') if not json.loads(line).get('text'): continue words = tweettext.split() print words tw = len(words) print "total number of words", tw my output is looking better, at least I'm not getting the "Attribute Error: NoneType" anymore. Now the output seems to consist of individual dictionaries instead of just one large dict. Again my goal is count how many times each word occurs and I'm not sure how to do that unless they are all in one dict. Here's a sample of the output at this point: [u'L', u'Lawliet', u'(Sweets', u'Addict)', u'+', u'Kenshin', u'Himura', u'(Samurai)', u'+', u'Kyon', u'(Lazy', u'and', u'Carefree', u'Bum)', u'=', u'Sakata', u'Gintoki', u'xD', u'May...', u'http://t.co/LD4E1j1v'] [u'Yay', u'~', u'I', u'have', u'ice~I', u'can', u'reach', u'the', u'ice', u'maker!', u'ch', u'sees', u'gaps', u'in', u'the', u'freezer', u'as', u'a', u'challenge', u'and', u"it's", u'usually', u'full', u'to', u'busting.', u'But', u'not', u'now', u'Haha!'] [u'Hoi'] [u'everyones', u'on', u'twitter.'] total number of words 429023 I would guess that I can probably setup counters for each word within the for loop somehow.? As you you can see the total word count works fine because it adds the number of words from each line, but I can't quite see how I would do it to determine unique words like: len(set(words)) EDIT: Here's my final solution: import fileinput import json import sys import os from collections import defaultdict line = [] tw = 0 inputfilename = sys.argv[1] word_count = defaultdict(int) for line in fileinput.input([inputfilename]): line = line.strip(); if not line: continue tweettext = json.loads(line).get('text') if not json.loads(line).get('text'): continue words = tweettext.split() tw += len(words) for word in words: word_count[word]+=1 print word_count print "total number of words", tw Answer: You seem to be on right track just add error checking e.g. Check if a line is blank before looading it as json , also strip the line just to be sure e.g. line = line.strip(); if not line: continue Check if json data has really any text in it if not json.loads(line).get('text'): continue After that you should loop thru words and may be create a dict e.g. word_count = defaultdict(int) for line in file: # get words and add them to dict for word in words: word_count[word]+=1
Python TypeError when building query string Question: I am building a query string. query = "SELECT seqid, date, name, steamid, team, text, type, '%s' as triggerword, '%s' as weight FROM chatlogs WHERE date > '%s' AND text LIKE '%%%s%%' ORDER BY DATE" % (word, weight, self.setting['LAST_RUN_TIME'], word) If I print the string, it returns correctly: SELECT seqid, date, name, steamid, team, text, type, 'hunting_term' as triggerword, '0.01' as weight FROM chatlogs WHERE date > '2012-04-18 23:47:58.439124' AND text LIKE '%hunting_term%' ORDER BY DATE However, it then fails with a TypeError exception: TypeError: not enough arguments for format string Full code: import database mysqldb = database.Connection('localhost','mydb',user='myuser',password='mypass') word = 'hunting_term' weight = 0.01 setting = dict({'LAST_RUN_TIME':'2012-04-18 23:47:58.439124'}) query = "SELECT seqid, date, name, steamid, team, text, type, '%s' as triggerword, '%s' as weight FROM chatlogs WHERE date > '%s' AND text LIKE '%%%s%%' ORDER BY DATE" % (word, weight, setting['LAST_RUN_TIME'], word) print query for message in mysqldb.query(query): # This is the line it throws the exception on print "A row" database is from the [tornado](https://github.com/facebook/tornado/blob/master/tornado/database.py) package Answer: The issue here is that the eventual call to MySQLdb looks something like this: query = "SELECT seqid, date, name, steamid, team, text, type, 'hunting_term' as triggerword, '0.01' as weight FROM chatlogs WHERE date > '2012-04-18 23:47:58.439124' AND text LIKE '%hunting_term%' ORDER BY DATE" db.cursor().execute(query, ()) The first argument to `db.cursor().execute()` should be a format string, and the second argument should be the replacements for that format string, you can see this in the [MySQLdb docs](http://mysql- python.sourceforge.net/MySQLdb.html#some-examples). In other words it will execute the following code: query % () As you can see, this will cause the same TypeError: >>> query % () Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: not enough arguments for format string This means that any literal `%` that you want MySQL to see needs to be a `%%` when it is seen by `db.cursor().execute()`, so you should be able to fix this by changing your original format string to the following: query = "SELECT seqid, date, name, steamid, team, text, type, '%s' as triggerword, '%s' as weight FROM chatlogs WHERE date > '%s' AND text LIKE '%%%%%s%%%%' ORDER BY DATE" % (word, weight, self.setting['LAST_RUN_TIME'], word) However the correct way to do this is to let MySQLdb perform the substitutions for you, which would change your code to the following: query = "SELECT seqid, date, name, steamid, team, text, type, %s as triggerword, %s as weight FROM chatlogs WHERE date > %s AND text LIKE %s ORDER BY DATE" parameters = (word, weight, setting['LAST_RUN_TIME'], '%%%s%%' % word) for message in mysqldb.query(query, *parameters): print "A row"
Python UDF for piglatin script not finding re module Question: I'm having trouble creating a UDF for a piglatin script I'm using. My problem is that when I run the script with `pig script.pig` I get the following error: [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1121: Python Error. Traceback (most recent call last): File "utils.py", line 3, in <module> import re ImportError: No module named re And on my "utils.py" script, I'm importing the module like so: `import re` Why is it not finding the `re` module and how can I fix it? **Edit** I should note that if I run the python script directly using the `python` command, I don't get an error saying that it couldn't find the `re` module. **Edit 2** Ok, based on the comments, I installed jython (which wasn't installed on my system) and here are the outputs of `print sys.path` for my script: _Using python_ ['/home/hduser/bqmScripts/betsScripts', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/local/lib/python2.6/dist-packages'] _Using Jython_ ['', '/usr/share/jython/Lib', '/usr/lib/site-python', '__classpath__'] _Using pig_ ['/pig/lib/Lib', '__classpath__', '__pyclasspath__/'] After seeing this, I tried to add the missing path elements from jython into the pig version, and what I get now is this: File "utils.py", line 8, in <module> import re File "/usr/share/jython/Lib/re.py", line 7, in <module> import sre, sys File "/usr/share/jython/Lib/sre.py", line 97, in <module> import sre_compile File "/usr/share/jython/Lib/sre_compile.py", line 17, in <module> assert _sre.MAGIC == MAGIC, "SRE module mismatch" AssertionError: SRE module mismatch **SOLVED** To solve my latest error message I looked for the version of jython that my pig installation was using (2.5) and installed that one manually. That fixed the issue. Answer: `re` is part of the stdlib, therefore either your Python installation is broken or incomplete, or something has damaged the contents of `sys.path`.
subprocess: PyDev console vs. cmd.exe Question: I'm trying to call a process from python using subprocess.call as shown below: from subprocess import call exePath = 'C:\\Test\\EXE.exe' inPath = 'C:\\Test\\IN.in' outPath = 'C:\\Test\\OUT.out' call([exePath, inPath, outPath]) This prints a few lines from EXE.exe followed by "The handle is invalid" -- but as a string, not as an error, which makes me think it might be a message from the EXE.exe: Unzipping Solution... 0.0% The handle is invalid. However when I open cmd.exe and paste in: C:\Test\EXE.exe C:\Test\IN.in C:\Test\OUT.out it works fine. Can someone point me in the right direction? Thanks! I'm running Python 2.7 64-bit on Windows 7. **EDIT:** It looks now like a problem in PyDev where the console cannot handle the the stdout from the process overwriting lines. The code runs fine from IDLE. Still looking for a fix for PyDev... Answer: I think you're having this issue because PyDev is not a real terminal (i.e.: in Python, os.isatty() will return False when run from PyDev). If the exe really relies on having a terminal, currently there's not much that PyDev can do... For now, you can make your call from Python as: In windows: popen = subprocess.Popen(['myexe', 'params'], creationflags=subprocess.CREATE_NEW_CONSOLE) popen.wait() In Linux (as the CREATE_NEW_CONSOLE is not available): args = ['xterm', '-e'] + ['myexe', 'params'] popen = subprocess.Popen(args) popen.wait() so that it works regardless of who's calling it :) I think Aptana Studio does have an actual terminal replacement, but there's no PyDev integration to launch things on it...
copy function in class definition in python Question: Im doing a class for polynomial and i have a problem with a copy function. It suppose to create a copy of the Poly object and return a reference to the new Poly object. Im really stuck on this copy idea. Thanks for any help class Poly: def __init__ (self, p): self.a = p self.deg= len(p) -1 if len(p) == 1 and p[0] == 0: self.deg = -1 def evalPoly(self,x0): ''' evaluates the polynomial at value x''' b=0 for coefficients in reversed(self.a): b=b*x0+int(coefficients) return b def polyPrime(self): '''replaces the coeffiecients of self with the coefficients of the derivative polynomial ''' if self.deg == 0: return np.zeroes(1,float), 0 else: newdeg=self.deg-1 p=[i*self.a[i] for i in range(1,self.deg+1)] p=str(p)[1: -1] p=eval(p) return p def copy(self): return Poly(self.a) I'm stuck on how to create a copy of the Poly object and return a reference to the new Poly object Answer: I think the problem you are having is that as `self.a` is a list then you are passing a reference to that list in the instantiation of the new Poly object. You should copy the list and give that copy to instantiate the object: import copy class Poly: ... def copy(self): return Poly(copy.copy(self.a))
What's the best way to load large JSON lists in Python? Question: I have access to a set of files (around 80-800mb each). Unfortunately, there's only one line in every file. The line contains exactly one JSON object (a list of lists). What's the best way to load and parse it into smaller JSON objects? Answer: There is already a similar post [here](http://stackoverflow.com/q/7052947/1332690). Here is the solution they proposed: import json with open('file.json') as infile: o = json.load(infile) chunkSize = 1000 for i in xrange(0, len(o), chunkSize): with open('file_' + str(i//chunkSize) + '.json', 'w') as outfile: json.dump(o[i:i+chunkSize], outfile)
Access information of containing list in python Question: I'm writing a script that can help me documenting our network rooms. The idea behind that script is that a room is a list, that contains several lists for the racks. The rack lists contain lists called module with the servers/switches/etc. in the module list are the actual ports with the cable numbers. For example: [04/02, [MM02, [1, #1992, 2, #1993, 3, #1567 ....], MM03, [1, #1234 .....]], 04/03, [MM01, .........]]] `04/02` = First Rack `MM02` = First module in that rack `1` = Port number `#1992` = Cable number I hope you get the idea. The script I wrote compares the cable numbers in the room list, and looks if there are duplicates. Now it gets tricky: It should then replace the cable number with the rack and module of the other port. That should be pretty easy, because module and rack are the first elements of those lists that contain the port, but I don't know how to get access to the information. (I'm a noob in programming) Answer: As mentioned in the commends, the much better data structure to use here is nested [`dict`s](http://docs.python.org/library/stdtypes.html#mapping-types- dict): data = { "04/02": { "MM02": {1: "#1992", 2: "#1993", 3: "#1567", ...}, "MM03": {1: "#1234", ...}, ... }, "04/03": { "MM01": ... ... }, ... } Then you simply do `data["04/02"]["MM02"] = {1: "#1992", 2: "#1993", 3: "#1567", ...}` to replace values, however, this has the disadvantage of meaning you need to manually create the sub-dictionaries - there are, however, [solutions to this problem](http://stackoverflow.com/questions/10218486/set- nested-dict-value-and-create-intermediate- keys/10218652#comment13126770_10218652) e.g: from functools import partial from collections import defaultdict tripledict = partial(defaultdict, partial(defaultdict, dict)) mydict = tripledict() mydict['foo']['bar']['foobar'] = 25 These not only have advantages in readability and usability, but also speed of access.
Determine which version of OpenCV Question: I want to write to short code snippet in python, to determine which version of OpenCV has been installed in my System. How do i do it ? Thank you. Answer: >>> from cv2 import __version__ >>> __version__ '$Rev: 4557 $' If that doesn't work then, use `cv` instead of `cv2`.
python beginner - faster way to find and replace in large file? Question: I have a file of about 100 million lines in which I want to replace text with alternate text stored in a tab-delimited file. The code that I have works, but is taking about an hour to process the first 70K lines.In trying to incrementally advance my python skills, I am wondering whether there is a faster way to do this. Thanks! The input file looks something like this: > CHROMOSOME_IV ncRNA gene 5723085 5723105 . - . ID=Gene:WBGene00045518 > CHROMOSOME_IV ncRNA ncRNA 5723085 5723105 . - . Parent=Gene:WBGene00045518 and the file with replacement values looks like this: > WBGene00045518 21ur-5153 Here is my code: infile1 = open('f1.txt', 'r') infile2 = open('f2.txt', 'r') outfile = open('out.txt', 'w') import re from datetime import datetime startTime = datetime.now() udict = {} for line in infile1: line = line.strip() linelist = line.split('\t') udict1 = {linelist[0]:linelist[1]} udict.update(udict1) mult10K = [] for x in range(100): mult10K.append(x * 10000) linecounter = 0 for line in infile2: for key, value in udict.items(): matches = line.count(key) if matches > 0: print key, value line = line.replace(key, value) outfile.write(line + '\n') else: outfile.write(line + '\n') linecounter += 1 if linecounter in mult10K: print linecounter print (datetime.now()-startTime) infile1.close() infile2.close() outfile.close() Answer: You should split your lines into "words" and only look up these words in your dictionary: >>> re.findall(r"\w+", "CHROMOSOME_IV ncRNA gene 5723085 5723105 . - . ID=Gene:WBGene00045518 CHROMOSOME_IV ncRNA ncRNA 5723085 5723105 . - . Parent=Gene:WBGene00045518") ['CHROMOSOME_IV', 'ncRNA', 'gene', '5723085', '5723105', 'ID', 'Gene', 'WBGene00045518', 'CHROMOSOME_IV', 'ncRNA', 'ncRNA', '5723085', '5723105', 'Parent', 'Gene', 'WBGene00045518'] This will eliminate the loop over the dictionary you do for every single line. Here' the complete code: import re with open("f1.txt", "r") as infile1: udict = dict(line.strip().split("\t", 1) for line in infile1) with open("f2.txt", "r") as infile2, open("out.txt", "w") as outfile: for line in infile2: for word in re.findall(r"\w+", line): if word in udict: line = line.replace(word, udict[word]) outfile.write(line) **Edit** : An alternative approach is to build a single mega-regex from your dictionary: with open("f1.txt", "r") as infile1: udict = dict(line.strip().split("\t", 1) for line in infile1) regex = re.compile("|".join(map(re.escape, udict))) with open("f2.txt", "r") as infile2, open("out.txt", "w") as outfile: for line in infile2: outfile.write(regex.sub(lambda m: udict[m.group()], line))
Python writing results out to a file Question: I have the following script which thanks to the help of everyone is almost done as it now prints out the results to the screen. I am also looking to add one more step which will take this same screen output and dump it to a text file. I thought this was done with `file.write()` but dont know how to get it to write the information from results to a file. Please help, I am very new to python so I am a bit lost and trying to figure it out from the book. This now prints out but just the last line of what is being returned by the query. Ultimately it is probably just printing one line and then overwriting it again and again so I need it to print the whole of the fetch all or results import adodbapi # Connect to the SQL DB conn = adodbapi.connect("Provider=SQLOLEDB; SERVER=xx.x.xx.x; Initial Catalog=master_db;User Id=user; Password=pass; ") curs = conn.cursor() # Execute SQL procedure things_referencing" curs.execute('util.things_procedure', ) results = curs.fetchall() for row in results: print row f = open('test.txt', 'w') s = str(row) f.write(s) f.close() conn.close() Answer: Each "row" in the "results" tuple is a record tuple. How you want to format this data is up to you, but at the most basic level you can convert it to a string with `str(row)` Now go read the python docs on how to read and write files: <http://docs.python.org/tutorial/inputoutput.html> **Update** Referring to your new code example, you are doing the for loop and printing each row, and then you are opening a file and only writing the last value that row was assigned from your for loop. Your for loop that prints is unrelated to the write operation you then do. `row` had been assigned every value of `results`, but you only used the last assigned value, once. What you should do is first open the file, then start your loop, writting every value of row: with open('test.txt', 'w') as f: for row in results: print row f.write("%s\n" % str(row)) If you use the `with` context, it will automatically close the file for you once you leave that scope. Instead of only converting to a string using `str` you can use string formatting, and add a newline character.
checking shared libraries for non default loaders Question: `ldd` is a good simple way to check for shared libraries a given executable is or will be using. However it does not always work as expected. For example, see the following shell snippet that demonstrates how it "fails" to found the libreadline "dependency" into the python binary I've tried many other distributions, but I'm copying from Tikanga $ lsb_release -a LSB Version: :core-4.0-amd64:core-4.0-ia32:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-ia32:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-ia32:printing-4.0-noarch Distributor ID: RedHatEnterpriseServer Description: Red Hat Enterprise Linux Server release 5.6 (Tikanga) Release: 5.6 Codename: Tikanga See what `ldd` does on the default installed `python` (from official repositories). $ which python /usr/bin/python $ ldd `which python` libpython2.4.so.1.0 => /usr/lib64/libpython2.4.so.1.0 (0x00000030e6200000) libpthread.so.0 => /lib64/libpthread.so.0 (0x00000030e0e00000) libdl.so.2 => /lib64/libdl.so.2 (0x00000030e0a00000) libutil.so.1 => /lib64/libutil.so.1 (0x00000030ee800000) libm.so.6 => /lib64/libm.so.6 (0x00000030e0600000) libc.so.6 => /lib64/libc.so.6 (0x00000030e0200000) /lib64/ld-linux-x86-64.so.2 (0x00000030dfe00000) $ ldd `which python` | grep readline $ Nothing found about readline. Now I do know from interactive usage that this binary does have realine functionality, so let't try to see where it's coming from. $ python & [1] 21003 $ Python 2.4.3 (#1, Dec 10 2010, 17:24:35) [GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2 Type "help", "copyright", "credits" or "license" for more information. [1]+ Stopped python Started an interactive python session in background (pid 21003) $ lsof -p 21003 COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME python 21003 ddvento cwd DIR 0,33 16384 164304 /glade/home/ddvento/loader-test python 21003 ddvento rtd DIR 8,3 4096 2 / python 21003 ddvento txt REG 8,3 8304 6813419 /usr/bin/python python 21003 ddvento mem REG 8,3 143600 8699326 /lib64/ld-2.5.so python 21003 ddvento mem REG 8,3 1722304 8699327 /lib64/libc-2.5.so python 21003 ddvento mem REG 8,3 615136 8699490 /lib64/libm-2.5.so python 21003 ddvento mem REG 8,3 23360 8699458 /lib64/libdl-2.5.so python 21003 ddvento mem REG 8,3 145824 8699445 /lib64/libpthread-2.5.so python 21003 ddvento mem REG 8,3 247544 6821551 /usr/lib64/libreadline.so.5.1 python 21003 ddvento mem REG 8,3 15840 8699446 /lib64/libtermcap.so.2.0.8 python 21003 ddvento mem REG 8,3 1244792 6833317 /usr/lib64/libpython2.4.so.1.0 python 21003 ddvento mem REG 8,3 18152 8699626 /lib64/libutil-2.5.so python 21003 ddvento mem REG 8,3 56446448 6832889 /usr/lib/locale/locale-archive python 21003 ddvento mem REG 8,3 21808 6965997 /usr/lib64/python2.4/lib-dynload/readline.so python 21003 ddvento mem REG 8,3 25464 6901074 /usr/lib64/gconv/gconv-modules.cache python 21003 ddvento 0u CHR 136,1 3 /dev/pts/1 python 21003 ddvento 1u CHR 136,1 3 /dev/pts/1 python 21003 ddvento 2u CHR 136,1 3 /dev/pts/1 $ lsof -p 21003 | grep readline python 21003 ddvento mem REG 8,3 247544 6821551 /usr/lib64/libreadline.so.5.1 python 21003 ddvento mem REG 8,3 21808 6965997 /usr/lib64/python2.4/lib-dynload/readline.so Bingo! Here it is readline! However, this technique works only when the library is effectively loaded, so for example it does not find `/usr/lib64/libtcl8.4.so` until the python process does not run something like `from Tkinter import *` So I have two questions: 1. I believe the problem with `ldd` is that it assumes the usage of the standard loader, whereas very likely python is using its own special loader (so that you don't have to relink the executable every time you install a new python module that is not pure python but has some c/c++/fortran code). Is this correct? 2. Clearly, if an executable is using its own loader, there is no obvious answer to the question "how to find all the possible libraries this executable may load": it depends on what the loader does. But is there a way to find out what libraries may be loaded by python? PS: related to 1. If you are landing on this question you should already know the following, but if don't you should: see how simple is to completely mess up `ldd` output (messing it up only partially is a little harder): $ cat hello.c #include <stdio.h> int main() { printf("Hello world.\n"); return 0; } $ gcc -static hello.c -o loader $ gcc -Wl,--dynamic-linker,./loader hello.c -o hello $ ./hello Hello world. $ ldd ./hello Hello world. Answer: Python, Perl, and other interpreted languages do load things dynamically using `dlopen()`. (This is not the same thing as replacing the standard loader; they are still using that, and in fact `dlopen()` is a hook into the standard loader on ELF-based systems.) There is no standard registry for loadable modules. Python uses its own rules to determine where extension modules can be loaded from (look at `sys.path`), including those which have associated shared objects. Perl uses different rules. Apache uses still different rules, etc. So to summarize the answers to your questions: 1. not exactly 2. no
Python - getting text from html Question: How to extract text 'ROYAL PYTHON' from this html code in a nice way? I've been looking for the solution for 4hours and I haven't found anything really relevant and working. <div class="definicja"><a href="javascript: void(0);" onclick="play('/mp3/1/81/c5ebfe33a08f776931d69857169f0442.mp3')" class="ikona_sluchaj2"></a> <a href="/slownik/angielsko_polski/,royal+python">ROYAL PYTHON</a></div> Answer: As Joel Cornett mentioned, using [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) like this: from bs4 import BeautifulSoup html = '''<div class="definicja"><a href="javascript: void(0);" onclick="play('/mp3/1/81/c5ebfe33a08f776931d69857169f0442.mp3')" class="ikona_sluchaj2"></a> <a href="/slownik/angielsko_polski/,royal+python">ROYAL PYTHON</a></div>''' soup = BeautifulSoup(html) print soup.getText()
How to create an ICMP traceroute in Python Question: I am trying to implement an ICMP based Traceroute in Python. I found a very helpful guide ( <https://blogs.oracle.com/ksplice/entry/learning_by_doing_writing_your> ) that has allowed me to create a UDP based Traceroute (code below) so just needs modification. I have tried changing the send socket to ICMP however I can't get anything to run without exceptions. Note - The below code works however this is a UDP traceroute (sends a UDP packet and receives an ICMP one) and I need my program to send an ICMP packet and receive an ICMP packet. This is because these days firewalls are smarter than they used to be and don't always send an ICMP response after receiving a UDP packet for a random port. Essentially the UDP socket needs to be changed for an ICMP one. I guess this isn't the most common thing to try and achieve and am having trouble researching on the net on how to do this. If anybody can provide some insight it would be REALLY appreciated :-) Main point to remember is that traceroutes work by setting the TTL so if the solution is to use an ICMP library then it needs to have a configurable TTL :-) #!/usr/bin/python import socket def main(dest_name): dest_addr = socket.gethostbyname(dest_name) port = 33434 max_hops = 30 icmp = socket.getprotobyname('icmp') udp = socket.getprotobyname('udp') ttl = 1 while True: recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp) send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl) recv_socket.bind(("", port)) send_socket.sendto("", (dest_name, port)) curr_addr = None curr_name = None try: _, curr_addr = recv_socket.recvfrom(512) curr_addr = curr_addr[0] try: curr_name = socket.gethostbyaddr(curr_addr)[0] except socket.error: curr_name = curr_addr except socket.error: pass finally: send_socket.close() recv_socket.close() if curr_addr is not None: curr_host = "%s (%s)" % (curr_name, curr_addr) else: curr_host = "*" print "%d\t%s" % (ttl, curr_host) ttl += 1 if curr_addr == dest_addr or ttl &gt; max_hops: break if __name__ == "__main__": main('google.com') Answer: Here is the solution using Scapy - thanks to KillianDS. Sending the ping ans,unans=sr(IP(dst="www.google.com",ttl=X)/ICMP()) Accessing the reply ans.summary(lambda (s,r): r.sprintf("%IP.src%") )
Unexpected whitespace in python generated strings Question: I am using Python to generate an ASCII file composed of very long lines. This is one example line (let's say line 100 in the file, '[...]' are added by me to shorten the line): {6 1,14 1,[...],264 1,270 2,274 2,[...],478 1,479 8,485 1,[...]} If I open the ASCII file that I generated with ipython: f = open('myfile','r') print repr(f.readlines()[99]) I do obtain the expected line printed correctly ('[...]' are added by me to shorten the line): '{6 1,14 1,[...],264 1,270 2,274 2,[...],478 1,479 8,485 1,[...]}\n' On the contrary, if I open this file with the program that is suppose to read it, it will generate an exception, complaining about an unexpected pair after 478 1. So I tried to open the file with _vim_. Still _vim_ shows no problem, but if I copy the line as printed by _vim_ and paste it in another text editor (in my case _TextMate_), this is the line that I obtain ('[...]' are added by me to shorten the line): {6 1,14 1,[...],264 1,270 2,274 2,[...],478 1,4 79 8,485 1,[...]} This line indeed has a problem after the pair 478 1. I tried to generate my lines in different ways (concatenating, with cStringIO, ...), but I always obtain this result. When using the cStringIO, for example, the lines are generated as in the following (even though I tried to change this, as well, with no luck): def _construct_arff(self,attributes,header,data_rows): """Create the string representation of a Weka ARFF file. *attributes* is a dictionary with attribute_name:attribute_type (e.g., 'num_of_days':'NUMERIC') *header* is a list of the attributes sorted (e.g., ['age','name','num_of_days']) *data_rows* is a list of lists with the values, sorted as in the header (e.g., [ [88,'John',465],[77,'Bob',223]]""" arff_str = cStringIO.StringIO() arff_str.write('@relation %s\n' % self.relation_name) for idx,att_name in enumerate(header): try: name = att_name.replace("\\","\\\\").replace("'","\\'") arff_str.write("@attribute '%s' %s\n" % (name,attributes[att_name])) except UnicodeEncodeError: arff_str.write('@attribute unicode_err_%s %s\n' % (idx,attributes[att_name])) arff_str.write('@data\n') for data_row in data_rows: row = [] for att_idx,att_name in enumerate(header): att_type = attributes[att_name] value = data_row[att_idx] # numeric attributes can be sparse: None and zeros are not written if ((not att_type == constants.ARRF_NUMERIC) or not ((value == None) or value == 0)): row.append('%s %s' % (att_idx,value)) arff_str.write('{' + (','.join(row)) + '}\n') return arff_str.getvalue() **UPDATE** : As you can see from the code above, the function transforms a given set of data to a special arff file format. I noticed that one of the attributes I was creating contained numbers as strings (e.g., '1', instead of 1). By forcing these numbers into integers: features[name] = int(value) I recreated the arff file successfully. However I don't see how this, which is a value, can have an impact on the formatting of *att_idx*, which is always an integer, as also pointed out by @JohnMachin and @gnibbler (thanks for your answers, btw). So, even if my code runs now, I still don't see why this happens. How can the value, if not properly transformed into _int_ , influence the formatting of something else? [This file](http://db.tt/7rJt9bYU) contains the wrongly formatted version. Answer: The built-in function [repr](http://docs.python.org/library/functions.html#repr) is your friend. It will show you unambiguously what you have in your file. Do this: f = open('myfile','r') print repr(f.readlines()[99]) and edit your question to show the result. Update: As to how it got there, it is impossible to tell, because **it cannot have been generated by the code that you showed**. The value `37` should be a value of att_idx which comes from `enumerate()` and so must be an int. You are formatting this int with %s ... 37 can't become `3rubbish7`. Also that should generate att_idx in order 0, 1, etc etc but you are missing many values and there is nothing conditional inside your loop. **Please show us the code that you actually ran.** **Update** : And again, this code won't run: for idx,att_name in enumerate(header): arff_str.write("@attribute '%s' %s\n" % (name,attributes[att_name])) because `name` is not defined; you probably mean `att_name`. Perhaps we can short-circuit all this stuffing about: post a copy of your output file (zipped if it's huge) on the web somewhere so that we can see for ourselves what might be disturbing its consumers. Please do edit your question to say which line(s) exhibits(s) the problem. By the way, you say some of the data is string rather than integer, and the problem goes away if you coerce the data to `int` by doing `features[name] = int(value)` ... what is 'features'?? What is 'name'?? Are any of those strings `unicode` instead of `str`? **Update 2 (after bad file posted on net)** No info supplied on which line(s) exhibits(s) the problem. As it turned out, no lines exhibited the described problem with attribute 479. I wrote this checking script: import re, sys # sample data line: # {40 1,101 3,319 2,375 2,525 2,530 bug} # Looks like all data lines end in ",530 bug}" or ",530 other}" pattern1 = r"\{(?:\d+ \d+,)*\d+ \w+\}$" matcher1 = re.compile(pattern1).match pattern2 = r"\{(?:\d+ \d+,)*" matcher2 = re.compile(pattern2).match bad_atts = re.compile(r"\D\d+\s+\W").findall got_data = False for lino, line in enumerate(open(sys.argv[1], "r"), 1): if not got_data: got_data = line.startswith('@data') continue if not matcher1(line): print print lino, repr(line) m = matcher2(line) if m: print "OK up to offset", m.end() print bad_atts(line) Sample output (wrapped at column 80): 581 '{2 1,7 1,9 1,12 1,13 1,14 1,15 1,16 1,17 1,18 1,21 1,22 1,24 1,25 1,26 1,27 1,29 1,32 1,33 1,36 1,39 1,40 1,44 1,48 1,49 1,50 1,54 1,57 1,58 1,60 1,67 1,68 1,69 1,71 1,74 1,75 1,76 1,77 1,80 1,88 1,93 1,101 ,103 6,104 2,109 20,110 3,11 2 2,114 1,119 17,120 4,124 39,128 5,137 1,138 1,139 1,162 1,168 1,172 18,175 1,1 76 6,179 1,180 1,181 2,185 2,187 9,188 8,190 1,193 1,195 2,196 4,197 1,199 3,201 3,202 4,203 5,206 1,207 2,208 1,210 2,211 1,212 5,213 1,215 2,216 3,218 2,220 2 ,221 3,225 8,226 1,233 1,241 4,242 1,248 5,254 2,255 1,257 4,258 4,260 1,266 1,2 68 1,269 3,270 2,271 5,273 1,276 1,277 1,280 1,282 1,283 11,285 1,288 1,289 1,29 6 8,298 1,299 1,303 1,304 11,306 5,308 1,309 8,310 1,315 3,316 1,319 11,320 5,32 1 11,322 2,329 1,342 2,345 1,349 1,353 2,355 2,358 3,359 1,362 1,367 2,368 1,369 1,373 2,375 9,377 1,381 4,382 1,383 3,387 1,388 5,395 2,397 2,400 1,401 7,407 2 ,412 1,416 1,419 2,421 2,422 1,425 2,427 1,431 1,433 7,434 1,435 1,436 2,440 1,4 49 1,454 2,455 1,460 3,461 1,463 1,467 1,470 1,471 2,472 7,477 2,478 11,479 31,4 82 6,485 7,487 1,490 2,492 16,494 2,495 1,497 1,499 1,501 1,502 1,503 1,504 11,5 06 3,510 2,515 1,516 2,517 3,518 1,522 4,523 2,524 1,525 4,527 2,528 7,529 3,530 bug}\n' OK up to offset 203 [',101 ,'] 709 '{101 ,124 2,184 1,188 1,333 1,492 3,500 4,530 bug}\n' OK up to offset 1 ['{101 ,'] So it looks like the attribute with `att_idx == 101` can sometimes contain the empty string `''`. You need to sort out how this attribute is to be treated. It would help your thinking if you unwound this Byzantine code: if ((not att_type == constants.ARRF_NUMERIC) or not ((value == None) or value == 0)): _Aside: that "expletive deleted" code won't run; it should be ARFF, not ARRF_ into: if value or att_type != constants.ARFF_NUMERIC: or maybe just `if value:` which will filter out all of `None`, `0`, and `""`. Note that `att_idx == 101` corresponds to the attribute "priority" which is given a STRING type in the ARFF file header: [line 103] @attribute 'priority' STRING By the way, your statement about `features[name] = int(value)` "fixing" the problem is very suspicious; `int("")` raises an exception. It may help you to read the warning at the end of this [wiki section about sparse ARFF files](http://weka.wikispaces.com/ARFF+%28stable+version%29#Sparse%20ARFF%20files).
Django admin page missing styling when deployed on Apache Question: I deployed my Django project on Apache but when I navigate to the admin page, it doesn't seem to have the same formatting as the test server that is included with Django. I have tinkered around with the configurations and soft links quite a bit but have had no success thus far. I'm hoping that someone more experienced than me in Django and Apache can spot check my issue and diagnose the problem. Find below the steps I took while installing Django as well as the contents of the configuration files. installation process svn co http://code.djangoproject.com/svn/django/trunk/ /usr/share/django chown -R www-data:www-data /usr/share/django ln -s /usr/share/django/django /usr/lib/python2.6/dist-packages/django ln -s /usr/share/django/django/bin/django-admin.py /usr/local/bin/django-admin.py mkdir /var/www/mydjango/django_projects mkdir /var/www/mydjango/django_templates mkdir /var/www/mydjango/media ln -s /usr/share/django/django/contrib/admin/media /var/www/mydjango/admin_media django-admin.py startproject /var/www/mydjango/django_projects/mydjango /var/www/mydjango/django_projects/mydjango/manage.py collectstatic --noinput (I've added the static files generated to /usr/share/django/django/contrib/admin/media since it was empty) settings.py MEDIA_ROOT = '/var/www/mydjango/media/admin/' (I've also tried '/var/www/mydjango/media/') MEDIA_URL = 'http://mydjango.mydomain.com/media/admin/' STATIC_ROOT = '' STATIC_URL = '/static/' http.conf Alias /admin_media/ /var/www/mydjango/admin_media/ Alias /media/ /var/www/mydjango/media/ <Directory "/admin_media/"> Order deny,allow Allow from all </Directory> <Directory "/media/"> Order deny,allow Allow from all </Directory> WSGIScriptAlias / /var/www/apache/django.wsgi <Directory /var/www/apache/> Order deny,allow Allow from all </Directory> django.wsgi import os import sys path = '/var/www/mydjango/django_projects/mydjango' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'mydjango.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() Answer: Moderna Django versions do not look for admin stuff in MEDIA_URL. Use [collectstatic](https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/).
How to set default PS1 value for interactive python? Question: I'm attempting to colorize my python interpreter to help visually separate text noise. So if I start interactive python it gives me plain text. I can do this: import sys sys.ps1 = "\033[0;34m>>> \033[0m" sys.ps2 = "\033[1;34m... \033[0m" However if I exit the interpreter and go back in the values revert to their default, which isn't surprising in the slightest. My question is how would I save these values and use them as the default? Answer: If the environment variable `PYTHONSTARTUP` is defined when Python starts (in interactive mode), Python will read and execute that file. Look at the `ENVIRONMENT VARIABLES` section of [this document](http://docs.python.org/using/cmdline.html) for more information. So if you put your `sys.ps1` commands into `~/.pythonrc.py` and pointed `PYTHONSTARTUP` at that file... export PYTHONSTARTUP=~/.pythonrc.py ...you would be all set. You may also want to check out [ipython](http://ipython.org/), which is a Python interactive interpreter with all sorts of fancy features and customization possibilities.
Modifying python programs (python 2.7) Question: I have a question concerning coding in python for a homework assignment, but I need to mention first that I've never coded in python before. The assignment is supposed to get us used to basics, so apologies ahead of time for the lack of knowledge (and really long post). Our job is to modify the file randline.py (given here in its originality): import random, sys from optparse import OptionParser class randline: def __init__(self, filename): f = open(filename, 'r') self.lines = f.readlines() f.close() def chooseline(self): return random.choice(self.lines) def main(): version_msg = "%prog 2.0" usage_msg = """%prog [OPTION]... FILE Output randomly selected lines from FILE.""" parser = OptionParser(version=version_msg, usage=usage_msg) parser.add_option("-n", "--numlines", action="store", dest="numlines", default=1, help="output NUMLINES lines (default 1)") options, args = parser.parse_args(sys.argv[1:]) try: numlines = int(options.numlines) except: parser.error("invalid NUMLINES: {0}". format(options.numlines)) if numlines < 0: parser.error("negative count: {0}". format(numlines)) if len(args) != 1: parser.error("wrong number of operands") input_file = args[0] try: generator = randline(input_file) for index in range(numlines): sys.stdout.write(generator.chooseline()) except IOError as (errno, strerror): parser.error("I/O error({0}): {1}". format(errno, strerror)) if __name__ == "__main__": main() We need to make it so that the program can take in multiple files, instead of just one, but the program still has to treat all the files as if they were one large file. Also, if one of the files does not end in a new line, we have to append a new line. I tried this, but the issue is that this adds a new line to the end of each file, regardless of if it ends in a new line originally or not. Plus my syntax is wrong to begin with. I get an error everytime I try to run the modified program. And I also have to add new options. I have unique working, but another option I'm supposed to make is without-replacement, which makes it so that the each output line only appears at max the number of times it appeared as input (if we don't use the -u option, the only time the output can be a duplicate is if it was a duplicate in the input file to begin with). I know my method is wrong, since sets automatically get rid of all duplicates and I only want it so the output lines write without replacement. But I have no idea what else I can use. import random, sys, string from optparse import OptionParser version_msg = "%prog 2.0" usage_msg = """%prog [OPTION]... FILE Output randomly selected lines from FILE""" parser = OptionParser(version=version_msg, usage=usage_msg) parser.add_option("-n", "--numlines", action="store", dest="numlines", default=1, help="output NUMLINES lines (default 1)") parser.add_option("-u", "--unique", action="store_true", dest="unique", default=False, help="ignores duplicate lines in a file") parser.add_option("-w", "--without-replacement", action="store_true", dest="without", default=False, help="prints lines without replacement") options, args = parser.parse_args(sys.argv[1:]) without = bool(options.without) unique = bool(options.unique) try: numlines = int(options.numlines) except: parser.error("invalid NUMLINES: {0}". format(options.numlines)) def main(): if numlines < 0: parser.error("negative count: {0}". format(numlines)) ##Here is one of the major changes input_file = args[0] count = 0 while (count < len(args)-1): input_file = input_file + '\n' + args[count + 1] count = count + 1 ##And here try: generator = randline(input_file) for index in range(numlines): if options.without: line = generator.chooseline() if line not in no_repeat: sys.stdout.write(line) no_repeat.add(line) else: sys.stdout.write(generator.chooseline()) except IOError as (errno, strerror): parser.error("I/O error({0}): {1}". format(errno, strerror)) class randline: def __init__(self, filename): if unique: uniquelines = set(open(filename).readlines()) f = open(filename, 'w').writelines(set(uniquelines)) f = open(filename, 'r') if without: countlines = len(f.readlines()) if (countlines < numlines): parser.error("too few lines in input". format(without)) self.lines = f.readlines() f.close() def chooseline(self): return random.choice(self.lines) if __name__ == "__main__": main() To sum, I can't get it to read multiple files properly (while still treating all the files as one long file) and the without-replacement option doesn't work correctly either. EDIT: Ah, I realized since I was passing file names in the argument list so even though they're only text files, they're not treated as strings. I tried to change it, but it still doesn't work exactly: input_file = args[0] count = 0 content = open(args[0]).read() while (count < len(args) - 1): content = content + open(args[count + 1]).read() count = count + 1 open(input_file, 'wb').write(content) try: generator = randline(input_file) It keeps adding an extra newline between the two files. I want to the files joined line by line, but I get a blank line between where the first file ends and the second one begins. EDIT 2.0: Oh wait, got it. Whoops. I just need help with the without- replacement option. I think I should split it line by line and store it in a list to check against every time? Is there a more efficient way (only using the modules I've already written, we can't use anything else) Answer: First of all, you need to read the first input file. So you need to open() the first input file you read as well. To add the newline, modify the while loop to check if the file (after you open() it) has a new line at the end, and if it doesn't, put one there. In order to implement the without replacement option, you need some way to check if you already have read a line. In order to split a file you've read in by lines, just use input.split('\n') Your randline constructor is getting passed the contents of the files, so what it's trying to do in the constructor doesn't make sense. Sorry if this answer doesn't seem to make sense; I've gone through and tried to point out different things you need to fix. I can't comment on stuff because I have no reputation, so I have to post an answer :. Let me know if this helps! * * * To do without replacement, i would make a dictionary that holds strings as keys, and ints as values. Loop through all the input text, and every time you see a line, add it to the dictionary and increment the associated integer. Then, when you call chooseline, check to make sure that the value in the dictionary for the string you got from picking a random line is greater than 0. If it is, decrement the associated value, and then return the string you picked. Otherwise, pick a new line. * * * Reply to Edit 2.0: You can do that. Then, everytime you pick a random line, you remove it from the list. I think that would work.
BeautifulSoup incorrectly parses page and doesn't find links Question: Here is a simple code in python 2.7.2, which fetches site and gets all links from given site: import urllib2 from bs4 import BeautifulSoup def getAllLinks(url): response = urllib2.urlopen(url) content = response.read() soup = BeautifulSoup(content, "html5lib") return soup.find_all("a") links1 = getAllLinks('http://www.stanford.edu') links2 = getAllLinks('http://med.stanford.edu/') print len(links1) print len(links2) Problem is that it doesn't work in second scenario. It prints 102 and 0, while there are clearly links on the second site. BeautifulSoup doesn't throw parsing errors and it pretty prints markup ok. I suspect it maybe caused by first line from source of med.stanford.edu which says that it's xml (even though content-type is: text/html): <?xml version="1.0" encoding="iso-8859-1"?> I can't figure out how to set up Beautiful to disregard it, or workaround. I'm using html5lib as parser because I had problems with default one (incorrect markup). Answer: When a document claims to be XML, I find the lxml parser gives the best results. Trying your code but using the lxml parser instead of html5lib finds the 300 links.
Python: Use lru_cache on lambda function, or other ways to create cache for lambda function Question: Is there anyway to make it work? func=i_want_it_to_cache_everything(lambda a,b:a+b) And it **has to be done in one line**... Update2: I figured out the solution (thanks to everyone who replied!). But... There is an interesting phenomenon: caching slows down program? import functools,datetime,timeit @functools.lru_cache(maxsize=50000) def euclidean_distance3(p1,p2): return (p1[0]-p2[0])**2+(p1[1]-p2[1])**2+(p1[2]-p2[2])**2+(p1[3]-p2[3])**2 euclidean_distance=(functools.lru_cache(maxsize=50000)(lambda p1,p2: (p1[0]-p2[0])**2+(p1[1]-p2[1])**2+(p1[2]-p2[2])**2+(p1[3]-p2[3])**2)) euclidean_distance2=lambda p1,p2: (p1[0]-p2[0])**2+(p1[1]-p2[1])**2+(p1[2]-p2[2])**2+(p1[3]-p2[3])**2 print(datetime.datetime.now()) def test1(): for z in range(50): for i in range(200): for j in range(200): euclidean_distance((i,i,i,i),(j,j,j,j)); def test2(): for z in range(50): for i in range(200): for j in range(200): euclidean_distance2((i,i,i,i),(j,j,j,j)); def test3(): for z in range(50): for i in range(200): for j in range(200): euclidean_distance3((i,i,i,i),(j,j,j,j)); t1=timeit.Timer(test1) print(t1.timeit(1)) t2=timeit.Timer(test2) print(t2.timeit(1)) t3=timeit.Timer(test3) print(t3.timeit(1)) print(euclidean_distance.cache_info()) print(euclidean_distance3.cache_info()) output: 9.989034592910151 4.936129879313011 10.528836308312947 CacheInfo(hits=1960000, misses=40000, maxsize=50000, currsize=40000) CacheInfo(hits=1960000, misses=40000, maxsize=50000, currsize=40000) Answer: >>> from functools import lru_cache >>> x = lru_cache()(lambda a,b:a+b) >>> x(2,3) 5 >>> x(4,2) 6 >>> x(2,3) 5 >>> x.cache_info() CacheInfo(hits=1, misses=2, maxsize=100, currsize=2)
Python- Import Multiple Files to a single .csv file Question: I have 125 data files containing two columns and 21 rows of data and I'd like to import them into a single .csv file (as 125 pairs of columns and only 21 rows). This is what my data files look like: ![enter image description here](http://i.stack.imgur.com/BAXMY.png) I am fairly new to python but I have come up with the following code: import glob Results = glob.glob('./*.data') fout='c:/Results/res.csv' fout=open ("res.csv", 'w') for file in Results: g = open( file, "r" ) fout.write(g.read()) g.close() fout.close() The problem with the above code is that all the data are copied into only two columns with 125*21 rows. Any help is very much appreciated! Answer: This should work: import glob files = [open(f) for f in glob.glob('./*.data')] #Make list of open files fout = open("res.csv", 'w') for row in range(21): for f in files: fout.write( f.readline().strip() ) # strip removes trailing newline fout.write(',') fout.write('\n') fout.close() Note that this method will probably fail if you try a large number of files, I believe the default limit in Python is 256.
MySQL and Python charset error Question: I am currently working on formatting data between CSV files and an mySQL database. I am using the MySQLdb library to manage the connection, but it seems to be some problems with formatting. I have to admit that I'm not a very experienced in neither mySQL or Python, but with a pragmatic approach most have been working out great until now. #!/usr/bin/python # -*- coding: utf-8 -*- import MySQLdb QUERY = "SELECT * FROM searches WHERE searchdate BETWEEN '2011-08-08' AND '2011-08-14';" conn = MySQLdb.connect (unix_socket = '/opt/local/var/run/mysql5/mysqld.sock',host = "localhost", user = "username", passwd= "passwd", db="db") c = conn.cursor() c.execute(QUERY) for row in c.fetchall(): print row This is the script which extracts the records from the database. Later in the process I want to extract the data from each of the line and format this into a CSV, but for the moment my problem is that the data printed to screen looks like this: ('\xc3\xa6nima', ' 1', ' 12782027', ' 35', datetime.date(2011, 8, 13)) ('\xc3\xa6nima', ' 1', ' 12823616', ' 59', datetime.date(2011, 8, 10)) ('\xc3\xa6oc', ' 1', ' 13078573', ' 55', datetime.date(2011, 8, 14)) ('\xc3\xa6re', ' 1', ' 12516300', ' 35', datetime.date(2011, 8, 8)) ('\xc3\xa6re v\xc3\xa6re deg', ' 1', ' 13145801', ' 59', datetime.date(2011, 8, 13)) ('\xc3\xa6re v\xc3\xa6re deg og lammet', ' 1', ' 13145801', ' 59', datetime.date(2011, 8, 13)) ('\xc3\xa6re v\xc3\xa6re jesu navn', ' 1', ' 13136667', ' 59', datetime.date(2011, 8, 11)) ('\xc3\xa6rlig vuggevise', ' 1', ' 12386933', ' 35', datetime.date(2011, 8, 12)) ('\xc3\xa6ror aleina', ' 1', ' 12867037', ' 35', datetime.date(2011, 8, 12)) ('\xc3\xa6sj', ' 1', ' 13130891', ' 59', datetime.date(2011, 8, 8)) ('\xc3\xa6thenor', ' 1', ' 12555673', ' 35', datetime.date(2011, 8, 10)) What I'm now having problems to understand is how I should get the data in a compatible format. So I guess I want to know how I can access and alter the charset in the database to UTF-8, and whether I need to rebuild all the data or if there is an automatic way of dealing with this issue. I would also be greatfull if anyone could point me in a direction of how I could format the datatime.date with a built-in function (I know I could regex and rebuild, but there is probably a more elegant solution). In advance thank you for your help! Answer: In your first column, some of the characters are not printable, so it is converted into hex chars. The last column in a datetime object. Python provides strftime function to convert it into string. for row in c.fetchall(): print row[0], row[1], row[2], row[3], row[4].strftime('%Y-%m-%d') will work. Also, you can write to a file using file.write(",".join((row[0], row[1], row[2], row[3], row[4].strftime('%Y-%m-%d')))) where, file is file object. It will write as comma separated column. Here you can see the original characters in file when you open it.
How do I import a module one level above and use the most recent definitions? Question: **tests.py** import unittest import sys import os sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import my_module.ext print sys.path print dir(my_module.ext) But `dir` gives me the old functions. A month ago I `easy_install` an older version, and when I run `python tests.py` I get all the old functions instead. I need the new definitions which are currently living in `my_module.ext` ../ - my_module/ - __init__.py - ext.py - core.py - lib.py - tests - tests.py Any idea how to achieve this? Thanks. The reason of not installing it is because it's a good practice to run tests before deploying the library. FYI, they are not classes. `my_module` can be built into an egg. Answer: Try sys.path.insert(0, /path/to/module) rather than sys.path.append
Converting malloc'ed buffers from C to Python without copy using Cython? Question: In Cython, say I have a C function that returns a large buffer allocated with malloc() and expected to be freed later with free(). Now I need to pass this buffer to Python as a (bytes) str object, which would acquire ownership of it, and call free() later when the str object goes away. Is this possible and how? Answer: Have a look at <https://gist.github.com/1249305> for a implementation using numpy. If numpy is not an option then something like this could work, using a memoryview: from libc.stdlib cimport free cimport fn # in here is the c function with signature: char * char_ret(int n); cdef class BuffWrap: cdef long siz cdef char * _buf cdef char[:] arr def __cinit__(self, long siz): self.siz = siz self._buf = fn.char_ret(siz) # storing the pointer so it can be freed self.arr = <char[:siz]>self._buf def __dealloc__(self): free(self._buf) self.arr = None # here some extras: def __str__(self): if self.siz<11: return 'BuffWrap: ' + str([ii for ii in self.arr]) else: return ('BuffWrap: ' + str([self.arr[ii] for ii in range(5)])[0:-1] + ' ... ' + str([self.arr[ii] for ii in range(self.siz-5, self.siz)])[1:]) def __getitem__(self, ind): """ As example of magic method. Implement rest of to get slicing http://docs.cython.org/src/userguide/special_methods.html#sequences-and-mappings """ return self.arr[ind] Note the method `__dealloc__` which will free the memory held by the pointer when all references to an instance of `BuffWrap` disappear and it gets garbage collected. This automatic deallocation is a good reason to wrap the whole thing in a class. I couldn't figure out how one could use the returned pointer and use it for the buffer of, say, a bytearray. If someone knows, I'd be interested to see.
Subprocess Popen not working with pythonw.exe Question: I want to be able to get the contents of stdout and stderr when I run the following script on windows using pythonw.exe: import subprocess import sys import os import string import time tmpdir = 'c:/temp' cmd = 'dir c:' tmpfile = "tmp_%f" % (time.time()) tmpfile = os.path.normpath(os.path.join(tmpdir,tmpfile)) tmpfile2 = tmpfile+".bat" tmpfile3 = tmpfile+".txt" fa = open(tmpfile2,'w') fa.write("@ECHO OFF > NUL\n") fa.write('call '+cmd+"\n") fa.close() wcmd = [] wcmd.append(tmpfile2) startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW fb = open(tmpfile3,'w') fb.write("\n") fb.write(tmpfile2+"\n") try: procval = subprocess.Popen(wcmd, startupinfo=startupinfo, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate() fb.write(str(procval)+"\n") fb.write("Sucess") fb.close() except: fb.write(str(procval)+"\n") fb.write("Failure") fb.close() When I execute it using python.exe I get the expected output. When I run it using pythonw.exe I end up on the exception side. If I run the popen with just the command and the startupinfo flags the command will successfully complete but no access to the data in the child processs. Everything that I read stated that this should work but must be missing something. Any help would be greatly appreciated. Thanks, Randy Answer: This is possibly a bug when using pythonw.exe pythonw.exe starts a daemon process which doesn't have the normal access to the standard file descriptors. The only thing you would need to do in your script is to specifically set the 3rd fd for stdin: p = subprocess.Popen(wcmd, startupinfo=startupinfo, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE) procval = p.communicate()
Reading a list of lists from a file as list of lists in python Question: I collected data in the form of list of lists and wrote the data into a text file. The data in the text file looks like [[123231,2345,888754],[223467,85645]] I want to read it back and store in a list of lists in my program. But when I do `read()` from the file and try creating a flat list then it takes everything as a string and the interpretation changes totally and i am not able to query the result I get after reading as normal list of lists in python. Can someone help me with reading the file and storing in the same format as list of lists? Thank you! Answer: This looks like valid [JSON](http://docs.python.org/library/json.html). So you can simply do: import json with open(myfilename) as f: lst = json.load(f) To store your "list of lists" in a file, do with open(myfilename, "w") as f: json.dump(lst, f)
How to set a charset in email using smtplib in Python 2.7? Question: I'm writing a simple smtp-sender with authentification. Here's my code SMTPserver, sender, destination = 'smtp.googlemail.com', '[email protected]', ['[email protected]'] USERNAME, PASSWORD = "user", "password" # typical values for text_subtype are plain, html, xml text_subtype = 'plain' content=""" Hello, world! """ subject="Message Subject" from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL) # from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption) from email.MIMEText import MIMEText try: msg = MIMEText(content, text_subtype) msg['Subject']= subject msg['From'] = sender # some SMTP servers will do this automatically, not all conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) try: conn.sendmail(sender, destination, msg.as_string()) finally: conn.close() except Exception, exc: sys.exit( "mail failed; %s" % str(exc) ) # give a error message It works perfect, untill I try to send non-ascii symbols (russian cyrillic). How should i define a charset in a message to make it show in a proper way? Thanks in advance! UPD. I've changed my code: text_subtype = 'text' content="<p>Текст письма</p>" msg = MIMEText(content, text_subtype) msg['From']=sender # some SMTP servers will do this automatically, not all msg['MIME-Version']="1.0" msg['Subject']="=?UTF-8?Q?Тема письма?=" msg['Content-Type'] = "text/html; charset=utf-8" msg['Content-Transfer-Encoding'] = "quoted-printable" … conn.sendmail(sender, destination, str(msg)) So, first time I spectify text_subtype = 'text', and then in header I place a msg['Content-Type'] = "text/html; charset=utf-8" string. Is it correct? **UPDATE** Finally, I've solved my message problem You should write smth like msg = MIMEText(content.encode('utf-8'), 'plain', 'UTF-8') Answer: from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def contains_non_ascii_characters(str): return not all(ord(c) < 128 for c in str) def add_header(message, header_name, header_value): if contains_non_ascii_characters(header_value): h = Header(header_value, 'utf-8') message[header_name] = h else: message[header_name] = header_value return message ............ msg = MIMEMultipart('alternative') msg = add_header(msg, 'Subject', subject) if contains_non_ascii_characters(html): html_text = MIMEText(html.encode('utf-8'), 'html','utf-8') else: html_text = MIMEText(html, 'html') if(contains_non_ascii_characters(plain)): plain_text = MIMEText(plain.encode('utf-8'),'plain','utf-8') else: plain_text = MIMEText(plain,'plain') msg.attach(plain_text) msg.attach(html_text) This should give you your proper encoding for both text and headers regardless of whether your text contains non-ASCII characters or not. It also means you won't automatically use base64 encoding unnecessarily.
Matplotlib: linewidth is added to the length of a line Question: When I draw a line segment in matplotlib the linewidth seems to be added to the length of the line. Below my code (not the most pythonic code, but it should do the trick). Am I doing something wrong or is this just a feature of matplotlib? import matplotlib.pyplot as plt import numpy as np L1=100 L2=75 L3=100 Y=3 N=5 l_prev=0 for l,c in zip(np.linspace(0,L1,N),range(N)) : plt.plot([l_prev,l],[0,0],'r',linewidth=20) l_prev=l l_prev=L1 for l,c in zip(np.linspace(L1,L1+L2,N),range(N)) : plt.plot([l_prev,l],[Y,Y],'g',linewidth=1) l_prev=l l_prev=L1 for l,c in zip(np.linspace(L1,L1+L3,N),range(N)) : p = plt.plot([l_prev,l],[-Y,-Y],'b',linewidth=10) l_prev=l plt.axvspan(xmin=L1,xmax=L1) plt.axis([-5,205,-5,5]) plt.show() What I expected to see is three line segments: `[0,L1], [L1,L2] and [L1,L3]`. But the first line `[0,L1]` extends to `L1` \+ 'the diameter'.... Answer: It looks like the default `solid_capstyle` is `projecting`, which isn't the one you want: plt.figure() plt.plot([0, 100], [5, 5], linewidth=50, linestyle="-", c="blue", solid_capstyle="butt") plt.plot([0, 100], [15, 15], linewidth=50, linestyle="-", c="red", solid_capstyle="round") plt.plot([0, 100], [25, 25], linewidth=50, linestyle="-", c="purple", solid_capstyle="projecting") plt.axvline(x=100, c="black") plt.xlim(0, 125) plt.ylim(0, 30) plt.savefig("cap.png") ![enter image description here](http://i.stack.imgur.com/bHIub.png)
How to upload image files to ipython notebook for further image processing Question: Instead of working with generated plots and graphs I want to use existing pictures to perform image processing on them. In [`sage`](http://www.sagemath.org/) one writes: from pylab import imread image = imread(DATA+"image.png") The [official help introduction](http://ipython.org/ipython- doc/dev/interactive/htmlnotebook.html) is silent regarding this task / use- case / problem. Answer: After googleing and trying for 30 mins, I found out, that is actually quite simple. The notebook has file access to the folder it was launched from. So if one started it in one's `home` folder one can access all the files from the `home` folder directly. from pylab import imread image = imread("image.png")
Using IPython interchangeably with code module if IPython exists Question: In an existing code snippet, I have import sys from code import InteractiveConsole class FileCacher: "Cache the stdout text so we can analyze it before returning it" def __init__(self): self.reset() def reset(self): self.out = [] def write(self, line): self.out.append(line) def flush(self): output = '\n'.join(self.out) self.reset() return output class Shell(InteractiveConsole): "Wrapper around Python that can filter input/output to the shell" def __init__(self): self.stdout = sys.stdout self.cache = FileCacher() InteractiveConsole.__init__(self) return def get_output(self): sys.stdout = self.cache def return_output(self): sys.stdout = self.stdout def push(self, line): self.get_output() # you can filter input here by doing something like # line = filter(line) InteractiveConsole.push(self, line) self.return_output() output = self.cache.flush() # you can filter the output here by doing something like # output = filter(output) print output # or do something else with it return if __name__ == '__main__': sh = Shell() sh.interact() How do I modify this to use IPython's interactive shell if IPython is available without changing the rest of the code if possible. I attempted swapping out line 2 `from code import InteractiveConsole` with `from IPython.core import interactiveshell as InteractiveConsole` but obviously, it's not a directly interchangeable class. What's the best way to do this (with minimal change to the rest of the code base) with a try except and using `IPython` in preference over `code` module when `IPython` exists? Answer: Here's my own attempt:- import sys from code import InteractiveConsole class FileCacher: "Cache the stdout text so we can analyze it before returning it" def __init__(self): self.reset() def reset(self): self.out = [] def write(self, line): self.out.append(line) def flush(self): output = '\n'.join(self.out) self.reset() return output class Shell(InteractiveConsole): "Wrapper around Python that can filter input/output to the shell" def __init__(self): self.stdout = sys.stdout self.cache = FileCacher() InteractiveConsole.__init__(self) return def get_output(self): sys.stdout = self.cache def return_output(self): sys.stdout = self.stdout def push(self, line): self.get_output() # you can filter input here by doing something like # line = filter(line) InteractiveConsole.push(self, line) self.return_output() output = self.cache.flush() # you can filter the output here by doing something like # output = filter(output) print output # or do something else with it return if __name__ == '__main__': try: import IPython IPython.embed() except: sh = Shell() sh.interact() which seems to work fine but I probably lost the `cache` and `stdout` custom methods/functionalities. Any criticism, edits and improvement suggestions welcome!
Difference in FFT between IDL and Python Question: I'm passing some simple IDL code to Python. However the returned FFT values form the SciPy/NumPy packages is different than the IDL one and I can't find out why. Reducing it all to a simple example of 8 elements I found that the SciPy/NumPy routines return values that are 8 (2^3) times bigger than the IDL ones (a normalization problem I thought). Here is the example code (copied from [here](http://scipy.org/Numpy_Example_List#head-3630ad1b5548a4e75ae976d678853e3a197c84fe)) in both languages: ## IDL signal = ([-2., 8., -6., 4., 1., 0., 3., 5.]) fourier = fft(signal) print, fourier returns > ( 1.62500, 0.00000) ( 0.420495, 0.506282) ( 0.250000, 0.125000) ( -1.17050, > -1.74372) ( -2.62500, -0.00000) ( -1.17050, 1.74372) ( 0.250000, -0.125000) > ( 0.420495, -0.506282) ## Python from scipy.fftpack import fft import numpy as N … signal = N.array([-2., 8., -6., 4., 1., 0., 3., 5.]) fourier = fft(signal) print fourier returns > [ 13. +0.j , 3.36396103 +4.05025253j, 2. +1.j , -9.36396103-13.94974747j, > -21. +0.j , -9.36396103+13.94974747j, 2. -1.j , 3.36396103 -4.05025253j] I did it with the NumPy package and I got the same results. I tried also `print fft(signal, 8 )` just in case but it returned the same, as expected. However that's not all, coming back to my real array of 256 elements I found that the difference was no longer 8 or 256, but 256*8! it's just insane. Although I worked around the problem I NEED to know why there is that difference. **Solved:** It was just the normalization, at some point I divided the IDL 256 array by a factor of 8 that I forgot to remove. In Dougal's answer there is the documentation that I missed. Answer: IDL and numpy use slightly different definitions of the DFT. Numpy's is (from [the documentation](http://docs.scipy.org/doc/numpy/reference/routines.fft.html#implementation- details)): ![](http://docs.scipy.org/doc/numpy/_images/math/dd1819fee3d9660e590d152f0c7cb7aa0c441ff1.png) ![](http://docs.scipy.org/doc/numpy/_images/math/6bbd972502306a4225d33ac6919fc6fc8244f67d.png) while IDL's is (from [here](http://www.physics.nyu.edu/grierlab/idl_html_help/F4.html)): ![](http://www.physics.nyu.edu/grierlab/idl_html_help/images/Fa8.gif) Numpy's `m` is the same as IDL's `x`, `k` is `u`, `n` is `N`. I think `a_m` and `f(x)` are the same thing as well. So the factor of `1/N` is the obvious difference, explaining the difference of 8 in your 8-elt case. I'm not sure about the 256*8 one for the 256-elt case; could you maybe post the original array and both outputs somewhere? (Does this happen for all 256-elt arrays? What about other sizes? I don't have IDL....)
TypeError: coercing to Unicode: need string or buffer, type found Question: I'm trying to write a code that will read a file and make some manipulations on it. the code: def assem(file): import myParser from myParser import Parser import code import symboleTable from symboleTable import SymboleTable newFile = "Prog.hack" output = open(newFile, 'w') input = open(file, 'r') prsr=Parser(input) while prsr.hasMoreCommands(): str = "BLANK" if(parser.commandType() == Parser.C_COMMAND): str="111"+code.comp(prsr.comp())+code.dest(prsr.dest())+code.jump(prsr.jump())+"\n" output.write(str) prsr.advance() the error i get: Traceback (most recent call last): File "assembler.py", line 11, in <module> input = open(file, 'r') TypeError: coercing to Unicode: need string or buffer, type found how i run the program: python assembler.py Add.asm where Add.asm id the file i want to read, all modules are in the same library, including the .asm file. Answer: You have multiple problems. Firstly, your indentation is inconsistent. That means that the imports are considered as part of the `assem` function, but nothing else is. Literally the first thing that you have to know about Python is that indentation is significant. Secondly, you're using a built-in function name, `file`, for the name of your variable. Don't do that. Thirdly, you don't actually call the `assem` function. But because of your first problem, the first unindented lines are executed on startup. So when the line `input = open(file, 'r')` is reached, `file` still refers to the built-in function, not your variable (which isn't defined at this point). Finally, although this isn't actually causing your problem, you don't need to do both `import myParser` and `from myParser import Parser`. Pick one.
Python issue with multiple loops and thread Question: I'm not a python programmer, but I got a snip of code that was working perfectly, but I need to modify it to loop trough files and get some data and do the same task. Apparently it work fine, but on the end of the first line obtained it crashes like this: python x.py -H SSH-Hosts.txt -U Users.txt -P passlist.txt ************************************* *SSH Bruteforcer Ver. 0.2 * *Coded by Christian Martorella * *Edge-Security Research * *[email protected] * ************************************* Username file: Users.txt Password file: passlist.txt ************************************* HOST: 192.168.1.3 Username: bob Trying password... zzzzzz Username: john Trying password... Traceback (most recent call last): File "x.py", line 146, in <module> test(sys.argv[1:]) File "x.py", line 139, in test test_thread(name) File "x.py", line 81, in test_thread thread.join() Zxcvbnm The application is a small tool that test for weak SSH accounts, we were target of several brute-force attacks recently and we blocked all of them, but we also want to test periodically for weak accounts, since the applications available (such as Medusa) crashed I decided to modify this one that works fine on our systems, but pass host per host and user per user is not very realistic for us. It's NOT a unauthorized test, I'm member of the IT and we are doing it to prevent BREACHES! import thread import time from threading import Thread import sys, os, threading, time, traceback, getopt import paramiko import terminal global adx global port adx="1" port=22 data=[] i=[] term = terminal.TerminalController() paramiko.util.log_to_file('demo.log') print "\n*************************************" print "*"+term.RED + "SSH Bruteforcer Ver. 0.2"+term.NORMAL+" *" print "*Coded by Christian Martorella *" print "*Edge-Security Research *" print "*[email protected] *" print "*************************************\n" def usage(): print "Usage: brutessh.py options \n" print " -H: file with hosts\n" print " -U: file with usernames\n" print " -P: password file \n" print " -p: port (default 22) \n" print " -t: threads (default 12, more could be bad)\n\n" print "Example: brutessh.py -h 192.168.1.55 -u root -d mypasswordlist.txt \n" sys.exit() class force(Thread): def __init__( self, name ): Thread.__init__(self) self.name = name def run(self): global adx if adx == "1": passw=self.name.split("\n")[0] t = paramiko.Transport(hostname) try: t.start_client() except Exception: x = 0 try: t.auth_password(username=username,password=passw) except Exception: x = 0 if t.is_authenticated(): print term.DOWN + term.GREEN + "\nAuth OK ---> Password Found: " + passw + term.DOWN + term.NORMAL t.close() adx = "0" else: print term.BOL + term.UP + term.CLEAR_EOL + passw + term.NORMAL t.close() time.sleep(0) i[0]=i[0]-1 def test_thread(names): i.append(0) j=0 while len(names): try: if i[0]<th: n = names.pop(0) i[0]=i[0]+1 thread=force(n) thread.start() j=j+1 except KeyboardInterrupt: print "Attack suspended by user..\n" sys.exit() thread.join() def test(argv): global th global hostname global username th = 12 if len(sys.argv) < 3: usage() try : opts, args = getopt.getopt(argv,"H:U:P:p:t:") except getopt.GetoptError: usage() for opt,arg in opts : if opt == '-U': username = arg elif opt == '-H': hostname =arg elif opt == '-P': password = arg elif opt == '-p': port = arg elif opt == "-t": th = arg try: h = open(hostname, 'r') except: print "Can't open file with hostnames\n" sys.exit() try: u = open(username, "r") except: print "Can't open username file\n" sys.exit() try: f = open(password, "r") except: print "Can't open password file\n" sys.exit() print term.RED + "Username file: " +term.NORMAL + username + "\n" +term.RED + "Password file: " +term.NORMAL+ password print "*************************************\n\n" hostfile = h.readlines() for hostname in hostfile: print "HOST: " + hostname.rstrip('\n') userfile = u.readlines() for username in userfile: print "Username: " + username.rstrip('\n') print "Trying password...\n" name = f.readlines() #starttime = time.clock() test_thread(name) #stoptime = time.clock() #print "\nTimes -- > Init: "+ str(starttime) + " End: "+str(stoptime) print "\n" if __name__ == "__main__": try: test(sys.argv[1:]) except KeyboardInterrupt: print "Attack suspended by user...\n" sys.exit() How to fix this issue? Thank you. Answer: import thread ... from threading import Thread not sure why you decided to import two classes with almost identical names. seems dangerous! i think you need Thread.join() not thread.join() since threading has a join call but the thread does not.
Match an element of every line Question: I have a list of rules for a given input file for my function. If any of them are violated in the file given, I want my program to return an error message and quit. * Every gene in the file should be on the same chromosome Thus for a lines such as: NM_001003443 chr11 + 5997152 5927598 5921052 5926098 1 5928752,5925972, 5927204,5396098, NM_001003444 chr11 + 5925152 5926098 5925152 5926098 2 5925152,5925652, 5925404,5926098, NM_001003489 chr11 + 5925145 5926093 5925115 5926045 4 5925151,5925762, 5987404,5908098, etc. Each line in the file will be variations of this line Thus, I want to make sure every line in the file is on chr11 Yet I may be given a file with a different list of chr(and any number of numbers). Thus I want to write a function that will make sure whatever number is found on chr in the line is the same for every line. Should I use a regular expression for this, or what should I do? This is in python by the way. Such as: chr\d+ ? I am unsure how to make sure that whatever is matched is the same in every line though... I currently have: from re import * for line in file: r = 'chr\d+' i = search(r, line) if i in line: but I don't know how to make sure it is the same in every line... **In reference to sajattack's answer** fp = open(infile, 'r') for line in fp: filestring = '' filestring +=line chrlist = search('chr\d+', filestring) chrlist = chrlist.group() for chr in chrlist: if chr != chrlist[0]: print('Every gene in file not on same chromosome') Answer: Just read the file and have a while loop check each line to make sure it contains `chr11`. There are string functions to search for substrings in a string. As soon as you find a line that returns false (does not contain `chr11`) then break out of the loop and set a flag `valid = false`. import re fp = open(infile, 'r') fp.readline() tar = re.findall(r'chr\d+', fp.readline())[0] for line in fp: if (line.find(tar) == -1): print("Not valid") break This should search for a number in the line and check for validity.
Python beautifulsoup iterate over table Question: I am trying to scrape table data into a CSV file. Unfortunately, I've hit a road block and the following code simply repeats the TD from the first TR for all subsequent TRs. import urllib.request from bs4 import BeautifulSoup f = open('out.txt','w') url = "http://www.international.gc.ca/about-a_propos/atip-aiprp/reports-rapports/2012/02-atip_aiprp.aspx" page = urllib.request.urlopen(url) soup = BeautifulSoup(page) soup.unicode table1 = soup.find("table", border=1) table2 = soup.find('tbody') table3 = soup.find_all('tr') for td in table3: rn = soup.find_all("td")[0].get_text() sr = soup.find_all("td")[1].get_text() d = soup.find_all("td")[2].get_text() n = soup.find_all("td")[3].get_text() print(rn + "," + sr + "," + d + ",", file=f) This is my first ever Python script so any help would be appreciated! I have looked over other question answers but cannot figure out what I am doing wrong here. Answer: You're starting at the top level of your document each time you use `find()` or `find_all()`, so when you ask for, for example, all the "td"` tags you're getting all the "td" tags _in the document,_ not just those in the table and row you have searched for. You might as well not search for those because they're not being used the way your code is written. I think you want to do something like this: table1 = soup.find("table", border=1) table2 = table1.find('tbody') table3 = table2.find_all('tr') Or, you know, something more like this, with more descriptive variable names to boot: rows = soup.find("table", border=1).find("tbody").find_all("tr") for row in rows: cells = row.find_all("td") rn = cells[0].get_text() # and so on
Capturing images from a camera in Python: easy, reliable, cross-platform Question: What is the most suitable way to capture a still image from Python and convert to a PIL image? Google gives me numerous ways with OpenCV and lesser-known libraries. I want an easy, reliable, mature, cross-platform library for this purpose. And with minimal dependencies and extra packages. * * * If possible, it must also support [displaying live images](http://stackoverflow.com/questions/3596960/any-quick-python-gui-to- display-live-images-from-camera) with major windowing toolkits, although the performance (frame rate, clarity) is not important. Answer: I use gphoto2 and with subprocess. But it should be possible to access this library from ctypes, if you prefer this.
Python Fast Input Output Using Buffer Competitive Programming Question: I have seen people using buffer in different languages for fast input/output in Online Judges. For example this <http://www.spoj.pl/problems/INTEST/> is done with C like this: #include <stdio.h> #define size 50000 int main (void){ unsigned int n=0,k,t; char buff[size]; unsigned int divisible=0; int block_read=0; int j; t=0; scanf("%lu %lu\n",&t,&k); while(t){ block_read =fread(buff,1,size,stdin); for(j=0;j<block_read;j++){ if(buff[j]=='\n'){ t--; if(n%k==0){ divisible++; } n=0; } else{ n = n*10 + (buff[j] - '0'); } } } printf("%d",divisible); return 0; How can this be done with python? Answer: import sys file = sys.stdin size = 50000 t = 0 while(t != 0) block_read = file.read(size) ... ... Most probably this will not increase performance though – Python is interpreted language, so you basically want to spend as much time in native code (standard library input/parsing routines in this case) as possible. TL;DR either use built-in routines to parse integers or get some sort of 3rd party library which is optimized for speed.
Django 1.4 Development Environment with zc.buildout Question: I am trying to create a dev environment for the Django 1.4 project using the following guide: <http://www.stereoplex.com/blog/a-django-development-environment-with-zc- buildout> **virtualenv** part of the guide runs ok with the following output: virtualenv project New python executable in project\Scripts\python.exe Installing setuptools................done. Installing pip...................done. After that I am able to activate dev environment. Now I create directory named **Source** , download the **bootstrap.py** to it and create a **buildout.cfg** with the following content: [buildout] parts = And run bootstrap.py for the following result: Creating directory 'C:\\Dropbox\\XYZ\\project\\Source\\bin'. Creating directory 'C:\\Dropbox\\XYZ\\project\\Source\\parts'. Creating directory 'C:\\Dropbox\\XYZ\\project\\Source\\eggs'. Creating directory 'C:\\Dropbox\\XYZ\\project\\Source\\develop-eggs'. Generated script 'C:\\Dropbox\\XYZ\\project\\Source\\bin\\buildout'. Here comes the problem part - **Installing Django** I configure the buildout.cfg to the following and run bin\buildout created by bootstrap: [buildout] parts = django [django] recipe = djangorecipe version = 1.4 After running bin\buildout i get the following error: (project) C:\Dropbox\XYZ\project\Source>bin\buildout.exe Traceback (most recent call last): File "C:\Dropbox\XYZ\project\Source\bin\buildout-script.py", line 15, in <module> import site # imports custom buildout-generated site.py File "C:\Dropbox\XYZ\project\Source\parts\buildout\site.py", line 601, in <module> main() File "C:\Dropbox\XYZ\project\Source\parts\buildout\site.py", line 584, in main known_paths = addsitepackages(known_paths) File "C:\Dropbox\XYZ\project\Source\parts\buildout\site.py", line 328, in addsitepackages import pkg_resources ImportError: No module named pkg_resources Although if I run python directly in project environment I can import pkg_resources with no error: (project) C:\Dropbox\XYZ\project\Source>python Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import pkg_resources >>> pkg_resources <module 'pkg_resources' from 'C:\Dropbox\XYZ\project\lib\site-packages\setuptools-0.6c11-py2.7.egg\pkg_resources.py'> I am completely struck here. Any suggestions? Answer: I don't have the definitive answer, but here are some brainstorm thoughts: * Why the virtualenv? Buildout itself provides isolation, so no virtualenv is needed. Could you re-try with just a bootstrap.py and your buildout.cfg? So just run bootstrap.py with your system python? * Do you have buildout installed globally, perhaps? They can interfere. * The latest 1.5.2 buildout has some problems with site.py files in some situations, which is a possible reason for it failing inside a virtualenv. Could you try the special 1.4.4 bootstrap mentioned in <http://pypi.python.org/pypi/zc.buildout/1.5.2#system-python-and-zc-buildout-1-5> ? * `bin/buildout -vvv` gives you much more debugging info. An additional comment: the `version` setting in djangorecipe is deprecated in the latest versions of djangorecipe. You can remove it. If you want to pin Django you have to pin it in your buildout's `[version]` list.
Is there a universal way of iterating over a set or values of a dict in Python 2.7? Question: I expect the collection to be either a set or a dict. Problem is that: for element in collection: print element will give me the elements if collection is a set, but indexes if collection is a dict. What I want is a one-liner that will iterate over dict values. Is that possible? Answer: The most foolproof way to test for a mapping is to use `isinstance` on [`collections.Mapping`](http://docs.python.org/library/collections.html#collections.Mapping): import collections for element in (collection.values() if isinstance(collection, collections.Mapping) else collection): If you need to do that frequently (you shouldn't, or you probably have a design issue), you could move it into a function: def values(collection): return (collection.values() if isinstance(collection, collections.Mapping) else collection) for element in values(collection):
Recording and asserting an empty mock list in python unittest Question: I'm using `unittest` and `mock` (Michael Foord's module) to test some python code. I have something like this (this is a proof of concept that could be rewritten more cleanly, but my real code needs to behave like that `foo` function): import unittest from mock import patch def foo(): my_list = [] class Test(unittest.TestCase): def test_foo(self): with patch('__main__.my_list', new=[], create=True) as baz: baz.extend(['foo', 'bar']) self.assertEqual(foo(), None) self.assertListEqual([], baz) if __name__ == '__main__': unittest.main() So the problem is that my `baz` mock object doesn't change accordingly after the `foo()` call and the last assertion fails. If I use `my_list.remove(x)` in `foo()` then I can see the changes in my test case, but I just want to empty that list, I don't want to pass through every element of the list then remove it, no, I want a fast empty operation. How can I check if my mock object is emptied without using `.remove(x)`, but using the current implementation of function `foo`? Answer: So, I end up answering my own question... The solution was to use `my_list[:] = []` in `foo`. But I also realized that passing `create=True` is bad because if that list doesn't exist (exactly the case of this POC) it will be created and I'll possibly test broken code that passes the tests.
Using pymongo tailable cursors dies on empty collections Question: Hoping someone can help me understand if I'm seeing an issue or if I just don't understand mongodb tailable cursor behavior. I'm running mongodb 2.0.4 and pymongo 2.1.1. Here is an script that demonstrates the problem. #!/usr/bin/python import sys import time import pymongo MONGO_SERVER = "127.0.0.1" MONGO_DATABASE = "mdatabase" MONGO_COLLECTION = "mcollection" mongodb = pymongo.Connection(MONGO_SERVER, 27017) database = mongodb[MONGO_DATABASE] if MONGO_COLLECTION in database.collection_names(): database[MONGO_COLLECTION].drop() print "creating capped collection" database.create_collection( MONGO_COLLECTION, size=100000, max=100, capped=True ) collection = database[MONGO_COLLECTION] # Run this script with any parameter to add one record # to the empty collection and see the code below # loop correctly # if len(sys.argv[1:]): collection.insert( { "key" : "value", } ) # Get a tailable cursor for our looping fun cursor = collection.find( {}, await_data=True, tailable=True ) # This will catch ctrl-c and the error thrown if # the collection is deleted while this script is # running. try: # The cursor should remain alive, but if there # is nothing in the collection, it dies after the # first loop. Adding a single record will # keep the cursor alive forever as I expected. while cursor.alive: print "Top of the loop" try: message = cursor.next() print message except StopIteration: print "MongoDB, why you no block on read?!" time.sleep(1) except pymongo.errors.OperationFailure: print "Delete the collection while running to see this." except KeyboardInterrupt: print "trl-C Ya!" sys.exit(0) print "and we're out" # End So if you look at the code, it is pretty simple to demonstrate the issue I'm having. When I run the code against an empty collection (properly capped and ready for tailing), the cursor dies and my code exits after one loop. Adding a first record in the collection makes it behave the way I'd expect a tailing cursor to behave. Also, what is the deal with the StopIteration exception killing the cursor.next() waiting on data? Why can't the backend just block until data becomes available? I assumed the await_data would actually do something, but it only seems to keep the connection waiting a second or two longer than without it. Most of the examples on the net show putting a second While True loop around the cursor.alive loop, but then when the script tails an empty collection, the loop just spins and spins wasting CPU time for nothing. I really don't want to put in a single fake record just to avoid this issue on application startup. Answer: This is known behavior, and the 2 loops "solution" is the accepted practice to work around this case. In the case that the collection is empty, rather than immediately retrying and entering a tight loop as you suggest, you can sleep for a short time (especially if you expect that there will soon be data to tail).
How to create managers for the worker threads? Question: The code works fine for a single "manager", which basically launches some HTTP GETs to a server. But I've hit a brick wall. How do I create 2 managers now, each with its own Download_Dashlet_Job object and tcp_pool_object? In essence, the managers would be commanding their own workers on two seperate jobs. This seems to be a really good puzzle for learning Python classes. import workerpool from urllib3 import HTTPConnectionPool class Download_Dashlet_Job(workerpool.Job): def __init__(self, url): self.url = url def run(self): request = tcp_pool_object.request('GET', self.url, headers=headers) tcp_pool_object = HTTPConnectionPool('M_Server', port=8080, timeout=None, maxsize=3, block=True) dashlet_thread_worker_pool_object = workerpool.WorkerPool(size=100) #this section emulates a single manager calling 6 threads from the pool but limited to 3 TCP sockets by tcp_pool_object for url in open("overview_urls.txt"): job_object = Download_Dashlet_Job(url.strip()) dashlet_thread_worker_pool_object.put(job_object) dashlet_thread_worker_pool_object.shutdown() dashlet_thread_worker_pool_object.wait() Answer: First, `workerpool.WorkerPool(size=100)` creates 100 worker threads. In the comment below, you're saying you want 6 threads? You need to change that to 6. In order to create a second pool, you need to create another pool. You can also create another job class, and just add this different type of job to the same pool, if you prefer.
Creating instance names from a list (Python) Question: I've got a function that builds a random number of object instances. For the sake of demonstrating the general idea, we're going to pretend that this is an algorithm to build a series of nethack-like rooms. The requirements are such that I won't know how many instances there will be in advance; these are generated randomly and on-the-fly. As a brief note: I am fully aware that the following code is nonfunctional, but it should (hopefully!) demonstrate my aims. import random class Levelbuild(object): def __init__(self): self.l1 = dict({0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h',8:'i'}) # Pick a random number between 4 and 9. for i in range(random.randint(4,9)): self.l1[i] = Roombuilder() If we assume that the chosen random integer is 5, the ideal result would be 5 Roombuilder() instances; labeled a, b, c, d, and e, respectively. Is there a simple way of doing this? Is there a way to do this period? \--Edit-- A giant "thank you" to Nick ODell for his answer. This isn't a complete copy/paste-- but it's a variation that works for what I need; import random class Room(object): def __init__(self): self.size = (5,5) class Level(object): def __init__(self): roomnames = ['a','b','c','d','e','f','g','h','i'] self.rooms = {} for i in range(random.randint(4, 9)): self.rooms[roomnames[i]] = Room() Rather than build each "room" by hand, I can now... test = Level() print test.rooms['a'].size >>> (5,5) Answer: import string import random class Levelbuild(object): def __init__(self,min_room_count,max_room_count): rooms_temp = [new RoomBuilder() for i in range(random.randint(min_room_count,max_room_count))] self.l1 = dict(zip(string.ascii_lowercase, rooms_temp)) Note: This will fail silently if given more than 26 rooms.
Get return value of ruby function in python Question: I have a ruby script that gets executed by a python script. From within the python script I want to access to return value of the ruby function. Imagine, I would have this **ruby script** _test.rb_ : class TestClass def self.test_function(some_var) if case1 puts "This may take some time" # something is done here with some_var puts "Finished" else # just do something short with some_var end return some_var end end Now, I want to get the return value of that function into my **python script** , the printed output should go to stdout. I tried the following (**example 1**): from subprocess import call answer = call(["ruby", "-r", "test.rb", "-e", "puts TestClass.test_function('some meaningful text')"]) However, this gives me the whole output on stdout and `answer` is just the exit code. Therefore i tried this (**example 2**): from subprocess import check_output answer = check_output(["ruby", "-r", "test.rb", "-e", "puts TestClass.test_function('some meaningful text')"]) This gives me the return value of the function in the _else case_ (see test.rb) almost immediately. However, if _case1_ is true, `answer` contains the whole output, but while running test.rb nothing gets printed. Is there any way to get the return value of the ruby function and the statements printed to stdout? Ideally, the solution requires no additional modules to install. Furthermore, I can't change the ruby code. Edit: Also tried this, but this also gives no output on stdout while running the ruby script (**example 3**): import subprocess process = subprocess.Popen(["ruby", "-r", "test.rb", "-e", "puts TestClass.test_function('some meaningful text')"], stdout=subprocess.PIPE) answer = process.communicate() I also think that this is no matter of flushing the output to stdout in the ruby script. Example 1 gives me the output immediately. Answer: Another way of doing this, without trying to call the ruby script as an external process is to set up a xmlrpc (or jsonrpc) server with the Ruby script, and call the remote functions from Python jsonrpc client (or xmlrpc)- the value would be available inside the Python program, nad even the sntax used would be just like you were dealing with a normal Python function. Setting up such a server to expose a couple of functions remotely is very easy in Python, and should be the same from Ruby, but I had never tried it.
Finding the location of a given arc distance along a parameterized curve in python Question: I have a parameterized 2D curve: (x,y) = f(t) The function f is arbitrary but differentiable and hence I can figure out the differential arc length ds along the curve at any point using standard formulas. I can also get the total arc length S(t) from the beginning to any point on the curve by integrating the differential arc length formula numerically. I can control the accuracy of the calculation. I want to find locate the point (x,y) that has a total arc length S = D from the beginning of the curve. Even better if the implementation were in python. I will be doing this many times, and it is part of a computational application where I need tight control of accuracy and some confidence of convergence. I don't know if root finding is the best approach, but my question is the equivalent of a root finding problem for g(t) = S(t) - D where the function g(t) is not evaluated exactly because S(t) isn't. Inexact function evaluation messes not only with accuracy but also the monotonicity of g(t). I tried doing tight numerical integration from the outset but it takes forever. I'm pretty sure to converge to my required tolerance the root finding algorithm would have to lazily control the integration accuracy as it proceeded, demanding sloppy evaluation at the outset and increasing accuracy as the root algorithm converges. Is there such a thing readily available? Is there an alternative clever way to do it? Appreciate the help Answer: Can you post some code, and tell us what's wrong with it? Here is my version that calculate the t where S(t) == D: from scipy.integrate import quad from scipy.optimize import fsolve from math import cos, sin, sqrt, pi def circle_diff(t): dx = -sin(t) dy = cos(t) return sqrt(dx*dx+dy*dy) def sin_diff(t): dx = 1 dy = cos(t) return sqrt(dx*dx+dy*dy) def curve_length(t0, S, length): return quad(S, 0, t0)[0] - length def solve_t(curve_diff, length): return fsolve(curve_length, 0.0, (curve_diff, length))[0] print solve_t(circle_diff, 2*pi) print solve_t(sin_diff, 7.640395578)
Python 3.x: Using string.maketrans() in order to create a unicode-character transformation Question: I would like to write the following code: import string frm = b'acdefhnoprstuw' to = 'אקדיפהנופרסתאו' trans_table = string.maketrans(frm, to) hebrew_phrase = 'fear cuts deeper than swords'.translate(trans_table) The above code doesn't work because the `to` parameter to `string.maketrans(frm, to)` has to be a byte sequence, not a string. The problem is that byte sequences can only contain ASCII literal characters. Therefore I cannot make a transformation which translates English strings to Hebrew strings. The reason is that `string.maketrans()` retruns a bytes object. Is there an elegant way to use the `string.maketrans()` and `translate()` functions (or equivalent functions that work with unicode) for my task? Answer: You need to use str.maketrans(), which takes two str as arguments. >>> frm = 'acdefhnoprstuw' >>> to = 'אקדיפהנופרסתאו' >>> trans_table = str.maketrans(frm, to) >>> hebrew_phrase = 'fear cuts deeper than swords'.translate(trans_table) >>> hebrew_phrase 'פיאר קאתס דייפיר תהאנ סוורדס' String.maketrans still existed in Python 3.1, but that's just because they missed moving it to bytes.maketrans() in 3.0. It was deprecated in 3.1 already and in 3.2 it is gone.
python virtualenv: why can I still import old modules in clean/new virtualenv Question: I'm starting a new Python project, and I want to work with **virtualenv** to have a clean start. After setting one up though, I can still import old modules that I have not installed for the new virtualenv - why? I created one with: virtualenv ~/virtualenvs/mynewproject --no-site-packages now i activate with `source bin/activate` Now when I start a python interpreter (by just typing `python`), I thought that it will use the python interpreter in my virtualenv, and my pythonpath would have been set to the site-packages path of my virutalenv's python (/virtualenvs/mynewporject/lib/python2.7/site-packages), and nothing else. However, when I look at sys.path, all the old, system-wide packages are available, and I can import them fine - which is what I don't want. What am I missing here? Answer: Check your `PYTHONPATH` environment variable which probably points to where you have the older version of your package. This variable always comes first in your `sys.path` so make sure you either clear it or change it to point to the virtualenv which you activate.
os.walk raises "unknown exception" in Eclipse/PyDev when path is a windows mapped network drive Question: I am trying to write a module that searches for different files on mapped drives in a Windows environment. This works perfectly in PythonWin and Idle but raises an exception _"Unknown exception when splitting input. Press any key to quit"_ when run in Eclipse/Pydev. L:\ i a mapped network drive import os path = "L:\\" for (path, dirs, files) in os.walk(path): print dirs If I set `path = "C:\\"` this works great. Any ideas what differs Eclipse/PyDev from Idle? Answer: The one thing that I know PyDev does differently is a site customization... Try removing it just to see if it may fix things: Rename: `plugins\org.python.pydev_XXX\pysrc\pydev_sitecustomize\sitecustomize.py` to `__sitecustomize.py` and do the launch to see if that may be the issue...
Python packages and imports - clarification needed Question: The import function of Python still confuses me sometimes. Here's an example: My project has the following package structure: Project/ src/ example/ __init__.py an_example.py top/ __init__.py lin/ __init__.py factory.py In `an_example.py`, I'd like to write from top import lin if __name__ == '__main__': a = lin.factory.AClass() However, this fails with: a = lin.factory.AClass() AttributeError: 'module' object has no attribute 'factory' `an_example.py` works when written like this: from top.lin import factory if __name__ == '__main__': a = factory.AClass() Can you explain to me why it is wrong to write the import statement like the first version? I'd prefer a fully qualified name like `lin.factory.AClass` to `factory.AClass`. Answer: This is because, unless you tell `lin` to import `factory` in `__init__.py`, then `factory` is not in the `lin` namespace. E.g: Presume your existing project structure, with an_example.py containing: from top import lin lin.factory.AClass() With `top/lin/__init__.py` blank, we get `ImportError: No module named factory`. With `top/lin/__init__.py` containing `import top.lin.factory`, we get no error. When you ask to use `factory.AClass()`, it works because it is defined there. Likewise, you need to define factory in `lin` if you want to use it from there.
python lxml unavailable in dev_appserver(gae,windows) Question: I have installed lxml yet. It works fine in IDLE. But when I start an basic app described below with dev_appserver.py ,server returns error "No module named lxml". import webapp2,lxml class MainPage(webapp2.RequestHandler): def get(self): self.response.out.write("test") app = webapp2.WSGIApplication([("/(.*)", MainPage)],debug=True) How can I resolve this?? Thanks!! Answer: Assumingly you're using Python 2.7 runtime. This runtime provides a fine way for configuring libraries. Please add libraries section in your app.yaml as follows: libraries: - name: lxml version: latest For more details, please see: <https://developers.google.com/appengine/docs/python/python27/using27#Configuring_Libraries>
Removing an application kills my Django admin interface Question: I had a `login` app which I was using. It had a table in my sqlite3 database. I decided I didn't need it anymore and I removed `'login',` from my INSTALLED_APPS and I deleted the app directory. However, now whenever I go to `/admin` I get: ImportError at /admin/ No module named login Is this because there is still a `login` table? How can I get rid of that? I tried `python manage.py dbshell` and `drop table login;` but it said a table named `login` didn't exist. Answer: The `ImportError` means there is an `import login` or `from ... import login` statement that Python can not fulfill. You could check in the printed traceback for the location of the statement. It probably in some admin.py file inside installed apps. If the error occurs during login to `/admin/`, you could check `AUTHENTICATION_BACKENDS` in settings per Lovelive's suggestion. The error has no relationship w/ Database table normally.
Limiting scope of Python import Question: I have some code that looks like this: from pyparsing import Word, alphas, Optional, ... # Do stuff ... # And at the end, save a result to the outside world. parser = ... # Now use parser but don't use anything else from pyparsing again. I like having the convenience of calling `from <package> import <etc>`, but I only want it to be used in a very small segment of code. I am afraid I am contributing to namespace pollution because I have a number of small snippets like this in the same file. What is the Pythonic way of handling this situation? I am still just kind of playing around with it, so I would rather not write and rewrite`pyparsing.` so many times. Answer: The usual ways to control namespace pollution are 1. Delete the variables after use 2. Use the __all__ variable 3. Use import-as to underscored variable names These techniques are all used by the core developers in the standard library. For example, the _decimal_ module: * starts out with [private name imports](http://hg.python.org/cpython/file/2.7/Lib/decimal.py#l139) such as `import math as _math` etc. * Later it does work to setup a threading environment followed by [variable deletion](http://hg.python.org/cpython/file/2.7/Lib/decimal.py#l402) using `del sys, MockThreading`. * In addition, it [defines an __all__ variable](http://hg.python.org/cpython/file/2.7/Lib/decimal.py#l118) to make clear what the public API is. Taken together, these techniques keep the namespace as clean as a whistle.
declarations within python class equivalent to _init_? Question: I was wondering if the declarations put at the top of the python class are equivalent to statements in `__init__`? For example import sys class bla(): print 'not init' def __init__(self): print 'init' def whatever(self): print 'whatever' def main(): b=bla() b.whatever() return 0 if __name__ == '__main__': sys.exit( main() ) The output is: not init init whatever As a sidenote, right now I also get: Fatal Python error: PyImport_GetModuleDict: no module dictionary! This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. Any ideas on why this is? Thank you in advance! Answer: No, it's not equivalent. The statement `print 'not init'` is run while the class `bla` is being defined, even before you instantiate an object of type `bla`. >>> class bla(): ... print 'not init' ... def __init__(self): ... print 'init' not init >>> b = bla() init
Error when running simple python script Question: When I run the following: import sys if __name__ == '__main__': print 'before exit' sys.exit(0) The output is: before exit Exception in thread Thread-1 (most likely raised during interpreter shutdown): Traceback (most recent call last): I don't know why the exception occurs, but it was suggested that it could be an improper installation of Python. I was wondering if anyone knew of a way to fix this? I am running Windows 7 x64, but with an x32 install of everything. Answer: I agree with the commenters that suggest you have a bad python install (an exception thrown running something so simple is a clear indication of corruption). But reinstalling need not be painful. Here's what I would do. First, rename your python directory (on windows its something like c:\python2.x) Next, install fresh copy of python (be sure it's the same version you already were running) Finally, copy the Site-packages folder from previous installation into the new install.
Python: parse commandline Question: I'm writing a CLI application in python with is used by means of a rather elaborate commandline language. The idea is very similar to find(1) which arguably has the same property. Currently, the parser is completely handwritten using a handmade EBNF description language. The problem is that this language is very awkward to use because I have to write everything as python structures. I also feel that my program is still way too bloated because of the parsing. Is there any lib that features ease of use, and a true description language (input as string/document) for commandline parsing? From the syntax tree, I would like to directly map each item to a class instance. Naturally, I don't want a tokenizer, or at least the tokenizer must map straight from commandline arguments to tokens. Thanks for all suggestions! _UPDATE_ : The whole point of my program is to generate objects and pass them through any number of filters (possibly unpure/effectful actions) that might or might not output the objects again, or might even output objects of another type. The general idea is obviously gleaned from find(1). An example commandline would be: ~/picdb.py -sqlselect 'select * from pics where dirname like "testdir%"' -tagged JoSo -updateFromFile [ -resx +300 -or -resX +200 -resY +500 ] -printfXml '<jpegfile><src>%fp</src><DateTimeOriginal>%ed</DateTimeOriginal><Manufacturer>%eM</Manufacturer><Model>%em</Model></jpegfile>%NL' Answer: This is a very tricky problem...You can "bind" actions to commandline arguments using argparse quite easily (e.g. create a class, operate on a previously created class ...). Here's a silly example of that...(argument --foo creates an object, argument --bar modifies the object created by --foo). from argparse import ArgumentParser,Action class Foo(object): def __init__(self,*args): self.args=args def __str__(self): return str(self.args) class FooAction(Action): def __call__(self,parser,namespace,values,option_string=None): setattr(namespace,self.dest,Foo(*values)) #Add Foo to the options... class BarAction(Action): def __call__(self,parser,namespace,values,option_string=None): FooObj=getattr(namespace,'foo') #raises an error if foo isn't in namespace... #In this way, BarAction is like a filter on the #object created by foo. FooObj.args=tuple(list(FooObj.args)+list(values)) #append to the list of args. parser=ArgumentParser() parser.add_argument('--foo',nargs='*',action=FooAction,help="Foo!") parser.add_argument('--bar',nargs='*',action=BarAction,help="Bar! : Must be used after --foo") namespace=parser.parse_args("--foo Hello World --bar Nice Day".split()) print (namespace) print (namespace.foo) However, this is a little different from yours in that `-argument` is not really possible with argparse, only `-a` or `--argument`. That may already be a deal breaker for you, I'm not sure... The next difficulty is dealing with the brackets... `[` and `]`. If you can treat those as arguments to a different commandline option, you might be OK...You might be able to set up a second parser to parse out the inside portions -- but I've never tried anything like that before... (If anyone else has any ideas about how to deal with the brackets, I'd be very interested to hear them). As far as `optparse` and `getopt` are concerned, I'm pretty sure that anything you can do with them, you can do with argparse, which is why I've left them out of the discussion.
wxPython caret move event Question: What event is called when the caret inside a TextCtrl / Styled TextCtrl has its position changed? I need to bind the event to show in the status bar, the current position of the caret. Answer: Try binding the `wx.EVT_KEY_UP` event with the `wx.TextCtrl` object like this: import wx class MyForm(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "Show Caret Position", size=(400, 140)) panel = wx.Panel(self, wx.ID_ANY) sizer = wx.BoxSizer(wx.VERTICAL) text = wx.StaticText(panel, -1, "Text:", (10, 22)) self.textCtrl = wx.TextCtrl( panel, -1, "", (50,5), size=(250, 50), style=wx.TE_MULTILINE ) self.textCtrl.SetInsertionPoint(0) self.textCtrl.Bind(wx.EVT_KEY_UP,self.onTextKeyEvent) self.textCtrl.Bind(wx.EVT_LEFT_UP,self.onTextKeyEvent) self.statusbar = self.CreateStatusBar(1) panel.SetSizerAndFit(sizer, wx.VERTICAL) def onTextKeyEvent(self, event): statusText = "Caret Position: "+str(self.textCtrl.GetInsertionPoint()) self.SetStatusText(statusText,0) event.Skip() #Run application if __name__ == "__main__": app = wx.PySimpleApp() frame = MyForm() frame.Show() app.MainLoop() I've tested on `Windows 7` environment with `Python 2.7` \+ `wxPython 2.8`. ![Here is how it should look like](http://i.stack.imgur.com/Z7iqN.png)
python multiprocessing pool Assertion Error in interpreter Question: I am writing a sample program to test the usage of multiprocessing pool of workers in python 2.7.2+ This is the code i have written in the python ubuntu interpreter >>> from multiprocessing import Pool >>> def name_append(first_name,last_name): ... return first_name+" "+last_name ... >>> from functools import partial >>> partial_name_append=partial(name_append,'kiran') >>> partial_name_append('acb') 'kiran acb' >>> abc='kiran' >>> pool=Pool(processes=4) >>> pool.map(partial_name_append,abc) ['kiran k', 'kiran i', 'kiran r', 'kiran a', 'kiran n'] >>> pool.close() >>> pool.join() >>> pool.map(partial_name_append,abc) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/multiprocessing/pool.py", line 226, in map assert self._state == RUN AssertionError After i got pickle errors, over my pool of workers code for large data sets, i am trying to do small examples and try to figure out what is the error. I dont understand why the same statement 'pool.map' doesn't work, when it has worked above. I think i have executed the 'pool map' correctly but i dont understand the reason. Is this error related to "PicklingError: Can't pickle : attribute lookup **builtin**.function failed" Can someone help me out ? Thanks Answer: You typed: >>> pool.close() [from the docs:](http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.close) > close() > > Prevents any more tasks from being submitted to the pool. Once all the tasks > have been completed the worker processes will exit. Of course you can't use the pool anymore, you closed it.
How to markup a transparent pygtk pycairo window and save the combined image? Question: I am trying to develop a transparent window on which I can markup ANYTHING that is on my screen (including dynamic). My final goal is to overlay graphs in online scientific publications, click and accumulate points along curves and eventually use generator functions to curve-fit to the points gathered. This will include putting up lines and axes, tick marks, and other goodies. However, I am trying to keep the question code very simple. The code below does the transparency part fairly well (please criticize and correct). I have done extensive research to understand how to save the contents of the transparent window, and failed. I have tried to figure out how to overlay anything at all (drawing primitives) and failed. I seek any and all advice to move this project forward, and intend to make the final code open source. Please help. #!/usr/bin/env python """ trans.py Transparent window with markup capability. Goals: 1. make a transparent window that dynamically updates (working). 2. draw opaque points, lines, text, and more (unimplemented). 3. save window overlayed by opaque points to png (unimplemented). 4. toggle overlay on/off (unimplemented). 5. make cursor XOR of CROSSHAIR (unimplemented). """ import pygtk pygtk.require('2.0') import gtk, cairo class Transparency(object): def __init__(self, widget, index): self.xy = widget.get_size() self.cr = widget.window.cairo_create() self.index = index def __enter__(self): self.cr.set_operator(cairo.OPERATOR_CLEAR) self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *self.xy) self.cr.rectangle(0.0, 0.0, *self.xy) self.cr.fill() return self.cr, self.surface def __exit__( self, exc_type, exc_val, exc_tb ): filename = '%08d.png' % (self.index) with open(filename, 'w+') as png: self.surface.write_to_png(png) print filename self.cr.set_operator(cairo.OPERATOR_OVER) class Expose(object): def __init__(self): self.index = 0 def __call__(self, widget, event): with Transparency(widget, self.index) as (cr, surface): # cr and surface are available for drawing. pass self.index += 1 def main(): x, y = 201, 201 win = gtk.Window(gtk.WINDOW_TOPLEVEL) win.connect("destroy", lambda w: gtk.main_quit()) win.set_decorated(True) win.set_app_paintable(True) win.set_size_request(x, y) win.set_colormap(win.get_screen().get_rgba_colormap()) win.connect('expose-event', Expose()) win.realize() win.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.DIAMOND_CROSS)) win.show() gtk.main() if __name__ == "__main__": main() UPDATE! Got most of what I needed working except the BIG one. How do you save the image formed by the combination of the underlying window and the transparent overlay? Points can be layed down and overlay can be toggled using keyboard only controls in vi-style. Here is the latest source: #!/usr/bin/env python """ trans.py Transparent window with markup capability. Goals: 1. make a transparent window that dynamically updates (working). 2. draw opaque points, lines, text, and more (working). 3. save window overlayed by opaque points to png (unimplemented). 4. toggle overlay on/off (working). 5. make cursor XOR of CROSSHAIR (using pixel-wise crosshair instead). 6. enable keyboard input in original emacs function table style (working). """ import pygtk pygtk.require('2.0') import gtk, cairo from math import pi class Transparency(object): index = 0 def __init__(self, widget): self.xy = widget.get_size() self.cr = widget.window.cairo_create() self.storing = False def __enter__(self): self.cr.set_operator(cairo.OPERATOR_CLEAR) self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *self.xy) self.cr.rectangle(0.0, 0.0, *self.xy) self.cr.fill() return self.cr, self.surface def __exit__( self, exc_type, exc_val, exc_tb ): if self.storing: filename = '%08d.png' % (Transparency.index) with open(filename, 'w+') as png: self.surface.write_to_png(png) print filename self.cr.set_operator(cairo.OPERATOR_OVER) Transparency.index += 1 class Expose(object): def __init__(self, window, xy): self.keep, self.points, self.bare = False, set(), False self.window = window self.X, self.Y = self.xy = xy self.x1, self.y1 = self.x0, self.y0 = self.xy[0]/2, self.xy[1]/2 self.window.connect("key_press_event", self.key_press_event) self.window.set_events(gtk.gdk.KEY_PRESS_MASK) self.window.set_flags(gtk.HAS_FOCUS | gtk.CAN_FOCUS) self.window.grab_focus() # function table for keyboard driving self.function = [[self.noop for a in range(9)] for b in range(256)] self.function[ord('q')][0] = self.quit # q for quit self.function[ord('h')][0] = self.lf # h for left (vi-style) self.function[ord('j')][0] = self.dn # j for down (vi-style) self.function[ord('k')][0] = self.up # k for up (vi-style) self.function[ord('l')][0] = self.rt # l for right (vi-style) self.function[ord('h')][2] = self.lf # h for left (vi-style) with point self.function[ord('j')][2] = self.dn # j for down (vi-style) with point self.function[ord('k')][2] = self.up # k for up (vi-style) with point self.function[ord('l')][2] = self.rt # l for right (vi-style) with point self.function[ord('.')][0] = self.mark # . for point self.function[ord(',')][0] = self.state # , to toggle overlay def __call__(self, widget, event): self.xy = widget.get_size() self.x0, self.y0 = self.xy[0]/2, self.xy[1]/2 with Transparency(widget) as (cr, surface): if not self.bare: self.point( cr, surface) self.aperture( cr, surface) self.positions(cr, surface) self.crosshair(cr, surface) def aperture(self, cr, surface): cr.set_operator(cairo.OPERATOR_OVER) cr.set_source_rgba(0.5,0.0,0.0,0.5) # dim red transparent cr.arc(self.x0, self.y0, self.x0, 0, pi*2) cr.fill() return self def position(self, cr, surface, x, y, chosen): cr.set_operator(cairo.OPERATOR_OVER) #r, g, b, a = (0.0,0.0,0.0,1.0) if chosen else (0.0,0.0,1.0,0.5) r, g, b, a = (0.0,0.0,0.0,1.0) cr.set_source_rgba(r,g,b,a) cr.rectangle(x, y, 1, 1) cr.fill() def crosshair(self, cr, surface): for dx, dy in [(-2,-2),(-1,-1),(1,1),(2,2),(-2,2),(-1,1),(1,-1),(2,-2)]: x, y = self.x1 + dx, self.y1 + dy if 0 0)) def dn(self, c, n): self.newxy(0, +int(self.y1 0), 0) def rt(self, c, n): self.newxy(+int(self.x1 127 else key def key_press_event(self, widget, event): keyname = gtk.gdk.keyval_name(event.keyval) mask = (1*int(0 != (event.state&gtk.gdk.; SHIFT_MASK))+ 2*int(0 != (event.state&gtk.gdk.CONTROL;_MASK))+ 4*int(0 != (event.state&gtk.gdk.; MOD1_MASK))) self.keep = 0 != (mask & 2) self.function[self.accept(event.keyval)][mask](keyname, event.keyval) self(widget, event) return True def main(): x, y = xy = [201, 201] window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("destroy", gtk.main_quit) window.set_decorated(True) window.set_app_paintable(True) window.set_size_request(x, y) window.set_colormap(window.get_screen().get_rgba_colormap()) window.connect('expose-event', Expose(window, xy)) window.realize() window.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.DIAMOND_CROSS)) window.show() gtk.main() if __name__ == "__main__": main() Answer: This does not answer your specific question but I figure: why re-invent the wheel? My suggestion is that you use an advanced screenshot application like Shutter to capture windows or selections. Shutter will provide you with a browseable gallery of your "saved" windows with the ability to edit and web- publish, as well as automatically storing images in dedicated folders (by project, desired resolution, etc) according to user defined profiles.
Python permutation Question: How would I accomplish the following in python: first = ['John', 'David', 'Sarah'] last = ['Smith', 'Jones'] combined = ['John Smith', 'John Jones', 'David Smith', 'David Jones', 'Sarah Smith', 'Sarah Jones'] Is there a method to combine all permutations? Answer: [`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product) import itertools combined = [f + ' ' + l for f, l in itertools.product(first, last)]
How do I find the Subsets of given Set in Sage? Question: I have code that looks like this: def Z(m,n): return CartesianProduct(IntegerRange(m),IntegerRange(n)) for v in Subsets(Z(2,2)): print v However, when I try to run it, I get the following error: Traceback (most recent call last): File "x.py", line 13, in <module> for v in Subsets(Z(_sage_const_2 ,_sage_const_2 )): File "/opt/sage-4.8-linux-64bit-ubuntu_10.04.3_lts-x86_64-Linux/local/lib/python2.6/site-packages/sage/combinat/subset.py", line 234, in __iter__ lset = __builtin__.list(self.s) File "/opt/sage-4.8-linux-64bit-ubuntu_10.04.3_lts-x86_64-Linux/local/lib/python2.6/site-packages/sage/sets/set.py", line 650, in __iter__ for x in self.set(): File "/opt/sage-4.8-linux-64bit-ubuntu_10.04.3_lts-x86_64-Linux/local/lib/python2.6/site-packages/sage/sets/set.py", line 719, in set return set(self.object()) TypeError: unhashable type: 'list' What is the canonical way of getting the set of all subsets of an arbitrary Set? Answer: `CartesianProduct` returns a list of lists, e.g.: >>> print list(Z(2,2)) [[0, 0], [0, 1], [1, 0], [1, 1]] But `Subsets` can't cope with the elements being lists (it converts its argument to a `set` internally, and a set in Python is implemented as a hash set, hence the error about "unhashibility"). To fix this, you should convert the internal lists to tuples: for v in Subsets(tuple(l) for l in Z(2,2)): print v Note that this is using a generator expression (rather than a list comprehension) to avoid constructing an intermediate list. (One could also use `map(tuple, Z(2,2))` or `import itertools` `iterools.imap(tuple, Z(2,2))` in place of the generator expression, but the solution given above is the most Pythonic.)
get image from website Question: I try to improve a [recipe](http://manual.calibre-ebook.com/news.html) for [calibre](http://calibre-ebook.com/) and replace the default cover image with the cover image of the current newspaper issue. The way to go has something to do with `get_cover_url` ([link](http://manual.calibre- ebook.com/news_recipe.html#calibre.web.feeds.news.BasicNewsRecipe.get_cover_url)). There are two problems: 1. The URL of the cover image changes every day. 2. I know virtually nothing about python. I hope for a solution like this (in pseudo-code): OPEN URL "http://epaper.derstandarddigital.at/"; coverElement = (SEARCH HTML-ELEMENT "<img>" WITH ID "imgPage2" AND CLASS "page"); coverUrl = (GET HTML-ATTRIBUTE "src" FROM coverElement); RETURN coverUrl; Would there be a way to achieve this in python*) (using only python standard libraries)? *) Calibre-Recipes seem to be python code [edit] here's the solution a friend of mine offered: #!/usr/bin/env python import urllib from time import strftime def get_cover_url(self): highResolution = True date = strftime("%Y/%Y%m%d") # it is also possible for the past #date = '2012/20120503' urlP1 = 'http://epaper.derstandarddigital.at/' urlP2 = 'data_ep/STAN/' + date urlP3 = '/V.B1/' urlP4 = 'paper.htm' urlHTML = urlP1 + urlP2 + urlP3 + urlP4 htmlF = urllib.urlopen(urlHTML) htmlC = htmlF.read() # URL EXAMPLE: data_ep/STAN/2012/20120504/V.B1/pages/A3B6798F-2751-4D8D-A103-C5EF22F7ACBE.htm # consists of part2 + part3 + 'pages/' + code # 'pages/' has length 6, code has lenght 36 index = htmlC.find(urlP2) + len(urlP2 + urlP3) + 6 code = htmlC[index:index + 36] # URL EXAMPLE HIGH RESOLUTION: http://epaper.derstandarddigital.at/data_ep/STAN/2012/20120504/pagejpg/A3B6798F-2751-4D8D-A103-C5EF22F7ACBE_b.png # URL EXAMPLE LOW RESOLUTION: http://epaper.derstandarddigital.at/data_ep/STAN/2012/20120504/pagejpg/2AB52F71-11C1-4859-9114-CDCD79BEFDCB.png urlPic = urlP1 + urlP2 + '/pagejpg/' + code if highResolution: urlPic = urlPic + '_b' urlPic = urlPic + '.png' return urlPic if __name__ == '__main__': print get_cover_url(None) Answer: You can use the `lxml` library to extract elements from an HTML document. The basic framework will look something like this: import urllib import lxml.html fd = urllib.urlopen('http://epaper.derstandarddigital.at/') doc = lxml.html.parse(fd) matches = doc.xpath('//img[@id="imgPage2]') if matches: print matches[0].get('src') ...however, the URL you've provided does not actually result in a document with any `<img>` tags. It is almost entirely a bunch of Javascript.
Getting variables from Scapy using Python Question: Hi I need help trying to access elements in what seems to be a tuple that scapy is returning. The code is below. ans,unans=sr(IP(dst="www.google.com",ttl=5)/ICMP(),verbose=0) ans.summary(lambda (s,r): r.sprintf("%IP.src%") ) If I enter Scapy and type both of these commands manually it will return a single IP address. However I am running it from inside a Python script and need to store that IP address as a variable. This may be a stupid question and I am just learning Scapy, but how would I store this IP address as a variable using scapy? I am wanting to achieve something like the below. #!/usr/bin/python from scapy.all import * ans,unans=sr(IP(dst="www.google.com",ttl=5)/ICMP(),verbose=0) SourceIP = ans.summary(lambda (s,r): r.sprintf("%IP.src%") ) Answer: If you ever need the value of a layer use the getlayer method. So just change things to: ans = sr1(IP(dst="www.google.com",ttl=5)/ICMP(),verbose=0) address = ans.getlayer(IP).src There is also another method to if a layer exists that returns true or false. Here is an example of that one. if ans.haslayer(IP): print "Packet has the layer IP"
exiting a running command in python Question: I'm new to python. I'm writing a script that calls a command line tool and displays the output from the command on the screen. The issue is that after the command runs it doesn't exit on it's own, it requires manual typing of ctrl-c to stop and continue on with the rest of the python script. Does anyone know how I could get it to stop on it's own and continue on with the rest of the script? cmd ='./ppshelper -sms "15062929382" warning' os.system(cmd) print "SMS sent" "SMS sent" is not printed until the user presses ctrl-c Thanks Answer: Use [`Popen`](http://docs.python.org/library/subprocess.html#popen-objects) from subprocess import Popen p = Popen(['/full/path/to/ppshelper', '-sms', '15062929382','warning']) p.terminate()
When attempting to upload a UTF-8 text file to Google Drive with the Google API client for python, I get a UnicodeDecodeError Question: **This question is still unsolved! Please answer if you know** **Bug** I have filed a bug here [http://code.google.com/p/google-api-python- client/issues/detail?id=131&thanks=131&ts=1335708962](http://code.google.com/p/google- api-python-client/issues/detail?id=131&thanks=131&ts=1335708962) While working on my [gdrive-cli](http://github.com/tom-dignan/gdrive-cli) project, I ran into this error attempting to upload a UTF-8 markdown file, using the "text/plain" mime-type. I also tried with "text/plain;charset=utf-8" and got the same result. Here is the stacktrace I got: Traceback (most recent call last): File "./gdrive-cli", line 155, in <module> handle_args(args) File "./gdrive-cli", line 92, in handle_args handle_insert(args.insert) File "./gdrive-cli", line 126, in handle_insert filename) File "/home/tom/Github/gdrive-cli/gdrive/gdrive.py", line 146, in insert_file media_body=media_body).execute() File "/usr/local/lib/python2.7/dist-packages/apiclient/http.py", line 393, in execute headers=self.headers) File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 401, in new_request redirections, connection_type) File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1544, in request (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1294, in _request (response, content) = self._conn_request(conn, request_uri, method, body, headers) File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1231, in _conn_request conn.request(method, request_uri, body, headers) File "/usr/lib/python2.7/httplib.py", line 955, in request self._send_request(method, url, body, headers) File "/usr/lib/python2.7/httplib.py", line 989, in _send_request self.endheaders(body) File "/usr/lib/python2.7/httplib.py", line 951, in endheaders self._send_output(message_body) File "/usr/lib/python2.7/httplib.py", line 809, in _send_output msg += message_body UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 4518: ordinal not in range(128) And the command I had to issue to generate it was: gdrive-cli --insert README.md "readme file" none "text/plain" README.md You can get the exact README.md file at the time this problem occurred here, <http://tomdignan.com/files/README.md> The relevant code from the SDK examples follows. The parameters going in are in order: a service instance, "README.md", "readme file", None (python keyword), "text/plain", and "README.md" def insert_file(service, title, description, parent_id, mime_type, filename): """Insert new file. Args: service: Drive API service instance. title: Title of the file to insert, including the extension. description: Description of the file to insert. parent_id: Parent folder's ID. mime_type: MIME type of the file to insert. filename: Filename of the file to insert. Returns: Inserted file metadata if successful, None otherwise. """ media_body = MediaFileUpload(filename, mimetype=mime_type) body = { 'title': title, 'description': description, 'mimeType': mime_type } # Set the parent folder. if parent_id: body['parentsCollection'] = [{'id': parent_id}] try: file = service.files().insert( body=body, media_body=media_body).execute() # Uncomment the following line to print the File ID # print 'File ID: %s' % file['id'] return file except errors.HttpError, error: print "TRACEBACK" print traceback.format_exc() print 'An error occured: %s' % error return None Answer: Traceback: ... resp = pool.request(method, page, fields = fields) File "/usr/lib/python2.7/site-packages/urllib3-dev-py2.7.egg/urllib3/request.py", line 79, in request **urlopen_kw) File "/usr/lib/python2.7/site-packages/urllib3-dev-py2.7.egg/urllib3/request.py", line 139, in request_encode_body **urlopen_kw) File "/usr/lib/python2.7/site-packages/urllib3-dev-py2.7.egg/urllib3/connectionpool.py", line 415, in urlopen body=body, headers=headers) File "/usr/lib/python2.7/site-packages/urllib3-dev-py2.7.egg/urllib3/connectionpool.py", line 267, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib64/python2.7/httplib.py", line 958, in request self._send_request(method, url, body, headers) File "/usr/lib64/python2.7/httplib.py", line 992, in _send_request self.endheaders(body) File "/usr/lib64/python2.7/httplib.py", line 954, in endheaders self._send_output(message_body) File "/usr/lib64/python2.7/httplib.py", line 812, in _send_output msg += message_body UnicodeDecodeError: 'ascii' codec can't decode byte 0x8b in position 181: ordinal not in range(128) urllib3 filepost.py: def encode_multipart_formdata(fields, boundary=None): ... body = BytesIO() ... return body.getvalue(), content_type request.py: def request(self, method, url, fields=None, headers=None, **urlopen_kw): ... else: return self.request_encode_body(method, url, fields=fields, headers=headers, **urlopen_kw) def request_encode_body(self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw): ... if encode_multipart: body, content_type = encode_multipart_formdata(fields or {}, boundary=multipart_boundary) ... headers = headers or {} headers.update({'Content-Type': content_type}) return self.urlopen(method, url, body=body, headers=headers, **urlopen_kw) httplib httplib.py: def _send_request(self, method, url, body, headers): ... if body and ('content-length' not in header_names): self._set_content_length(body) ... def _set_content_length(self, body): # Set the content-length based on the body. thelen = None try: thelen = str(len(body)) except TypeError, te: # If this is a file-like object, try to # fstat its file descriptor try: thelen = str(os.fstat(body.fileno()).st_size) except (AttributeError, OSError): # Don't send a length if this failed if self.debuglevel > 0: print "Cannot stat!!" if thelen is not None: self.putheader('Content-Length', thelen) ... def _send_output(self, message_body=None): ... if isinstance(message_body, str): msg += message_body message_body = None self.send(msg) if message_body is not None: #message_body was not a string (i.e. it is a file) and #we must run the risk of Nagle self.send(message_body) ... def send(self, data): ... blocksize = 8192 if hasattr(data,'read') and not isinstance(data, array): if self.debuglevel > 0: print "sendIng a read()able" datablock = data.read(blocksize) while datablock: self.sock.sendall(datablock) datablock = data.read(blocksize) else: self.sock.sendall(data) My script.py: #!/usr/bin/env python from io import BytesIO data = BytesIO() print type(data.getvalue() **$./script.py** **< type 'str'>** My solution: #!/usr/bin/python from urllib3 import HTTPConnectionPool, filepost from io import BytesIO, SEEK_SET pool = HTTPConnectionPool('web') archive_name = '/var/archives/mock.tar.gz' fields = {'uploadedfile' : (archive_name, open(archive_name).read())} value, content_type = filepost.encode_multipart_formdata(fields) headers = {'Content-Type' : content_type, 'Content-Length' : len(value)} # or any temporary file. without Content-Length data = BytesIO() data.write(value) data.seek(0, SEEK_SET) resp = pool.urlopen('POST', '/upload/uploader.php', data, headers) print resp.status **$./upload.py** **200** **/var/www/upload# ls** **mock.tar.gz upload.html upload.php**
Connect to Database via proxy a python script Question: I have a python script that connects to a remote MySQL database using the python library MySQLdb. It works fine but how can I get it to connect through a proxy that I'm behind when at work. I can connect via the command line in ssh, but how do I get the python script to use the proxy settings. There doesnt seem to be any options in the MySQLdb commands for proxy configurations. import MySQLdb as mdb conn=mdb.connect(host='mysite.com',user='myuser',passwd='mypassword',db='mydb') cursor = conn.cursor() Answer: I think setting the port on the connect command would work. conn = mdb.connect(host='slkds.com', port='9000', user='user', passwd='wd', db='my') or you can set a system proxy for what ever you are running on and then the scrip will work
Slow image processing with Python and PIL Question: I'm trying to sort the pixels of images in order of RGB values. Being new to Python i tried this: from PIL import Image source = Image.open("source.jpg") colors = source.getcolors(source.size[0] * source.size[1]) #maxcolor value =256, get all colors with source.size[0] * source.size[1] pixels = [] for i, color in colors: pixels.extend(i * [color]) pixels.sort() new = Image.new('RGB', source.size) new.putdata(pixels) new.save("new.png") It works quiet well for small files around 40x40 pixels. But the goal was to use it on photos with up to 3000x2000 resolution, i tried running it but after two hours there was still no end in sight. Can the code be optimized, did i do something completly wrong or is Python simply not suited for that kind of task? Answer: Indentation in Python is key, otherwise you can run code you wouldn't for each iteration. Here you are saving your file each time you loop as your image generation is indented. Instead, try: from PIL import Image source = Image.open("source.jpg") colors = source.getcolors(source.size[0] * source.size[1]) #maxcolor value =256, get all colors with source.size[0] * source.size[1] pixels = [] for i, color in colors: pixels.extend(i * [color]) pixels.sort() new = Image.new('RGB', source.size) new.putdata(pixels) new.save("new.png")
Can't get Flask running using Passenger WSGI on Dreamhost shared hosting Question: I'm trying to get a Flask "hello world" application working on a Dreamhost shared server, following the [instructions on their wiki](http://wiki.dreamhost.com/Flask), but I'm not having any luck. My Flask application is the "hello world" one from the [Flask quickstart guide](http://flask.pocoo.org/docs/quickstart/): from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run() Which I've got in a file called "hello.py" in a folder called mysite, as per the DH wiki instructions. My passenger_wsgi.py file is: import sys, os INTERP = os.path.join(os.environ['HOME'], 'flask_env', 'bin', 'python') if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) sys.path.append(os.getcwd()) from mysite import hello as application I've tried running the commands in a Python console, and last import line failed until I added the `__init__.py` file to the mysite directory. When I try and access the website I just get a 500 error (and nothing in the logs unfortunately, unless they're in logs I can't get to as this is a shared server...). As this is the most basic of setups (i.e., copied and pasted from a wiki), I can't help feeling that I'm missing something really simple. Or perhaps this isn't possible on a shared server? Answer: Does answering my own question mean I'm talking to myself? Anyway - I seem to have fixed it. Rather than find a nice helpful error message, I went through all the steps again one at a time, and it turns out it was an import error in the `passenger_wsgi.py` file. As the app is in the `mysite` subdirectory, the line: from mysite import hello as application should have been (and in fact, now is): from mysite.hello import app as application And it works. Which is nice.
wxPython 2.9 on Mac Os X Question: I am using Enthought Python Distribution (7.2, 64-bit). It comes without wxPython (which is quite important). However, wxPython-2.9 seems to support 64-bit Cocoa interface, so I gave it a try. Actually, it all went good: the command python build-wxpython.py --osx_cocoa --mac_framework --install successfully compiled, and even got into EPD site-packages. However, a simple wxPython code import wx wx.App() fails with the following error: This program needs access to the screen. Please run with a Framework build of python, and only when you are logged in on the main display of your Mac. Can you give me some advice how to cure this? EPD is clearly a Python Framework (i.e., looking at /Library/Frameworks/EPD64.framework and /Library/Frameworks/Python.framework convinces me in it) but this wxPython build does not know about that. The version of wxPython is 2.9.3.1 Answer: Using a wrapper script like this should setup your environment in such a way that wxPython works correctly: #!/bin/bash # Real Python executables to use PYVER=2.7 PYTHON=/Library/Frameworks/Python.framework/Versions/$PYVER/bin/python$PYVER # Figure out the root of your EPD env ENV=`$PYTHON -c "import os; print os.path.abspath(os.path.join(os.path.dirname(\"$0\"), '..'))"` # Run Python with your env set as Python's PYTHONHOME export PYTHONHOME=$ENV exec $PYTHON "$@" Just dump it in a file, give it executable permission and use it to launch your wxPython app instead of the python executable.
Is there a way to set the Pygame icon in the taskbar? set_icon() only seem to affect the small icon in the actual window Question: While running my program the icon I configured with `pygame.display.set_icon(icon)` displays only in the window. In the taskbar the default python icon remains the same. Is there a way to change that? Source: import pygame from pygame.locals import * import sys, os import time pygame.init() # Load Images try: bg = os.getcwd() + '\\images\\background.png' background = pygame.image.load(bg).convert() except: print 'Error: Could not find background.png' try: logo = os.getcwd() + '\\images\\logo.png' c_logo = pygame.image.load(logo).convert() except: print 'Error: Could not find logo.png' try: about_dialog_infile = os.getcwd() + '\\images\\about_dialog[alpha].png' about_dialog = pygame.image.load(about_dialog_infile).convert_alpha() except: pass i_icon = os.getcwd() + '\\images\\icon.png' icon = pygame.image.load(i_icon) pygame.display.set_icon(icon) pygame.display.set_caption("Test program") screenSize =(640,480) screen = pygame.display.set_mode(screenSize,0,32) pygame.display.set_caption('My Test Program') while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() # sys.exit() if event.type == MOUSEBUTTONDOWN: check_click(about, event.pos) screen.blit(background, (0,0)) pygame.display.update() Answer: I finally figured it out. As far as I can tell, the only way to actually set that icon in the taskbar is during packaging. With pyinstaller for example, you would call `python pyinstaller.py --icon=icon.ico` Where icon is the icon you want displayed in the task bar.
Solving Puzzle in Python Question: I got one puzzle and I want to solve it using Python. > Puzzle: > > A merchant has a 40 kg weight which he used in his shop. Once, it fell from > his hands and was broken into 4 pieces. But surprisingly, now he can weigh > any weight between 1 kg to 40 kg with the combination of these 4 pieces. > > So question is, what are weights of those 4 pieces? Now I wanted to solve this in Python. The only constraint i got from the puzzle is that sum of 4 pieces is 40. With that I could filter all the set of 4 values whose sum is 40. import itertools as it weight = 40 full = range(1,41) comb = [x for x in it.combinations(full,4) if sum(x)==40] `length of comb = 297` Now I need to check each set of values in `comb` and try all the combination of operations. Eg if `(a,b,c,d)` is the first set of values in `comb`, I need to check `a,b,c,d,a+b,a-b, .................a+b+c-d,a-b+c+d........` and so on. I tried a lot, but i am stuck at this stage, ie how to check all these combination of calculations to each set of 4 values. **Question :** 1) I think i need to get a list all possible combination of `[a,b,c,d] and [+,-]`. 2) does anyone have a better idea and tell me how to go forward from here? Also, I want to do it completely without help of any external libraries, need to use only standard libraries of python. **EDIT** : Sorry for the late info. Its answer is (1,3,9,27), which I found a few years back. I have checked and verified the answer. EDIT : At present, `fraxel`'s answer works perfect with `time = 0.16 ms`. A better and faster approach is always welcome. Regards ARK Answer: **Earlier walk-through anwswer:** We know `a*A + b*B + c*C + d*D = x` for all `x` between 0 and 40, and `a, b, c, d` are confined to `-1, 0, 1`. Clearly `A + B + C + D = 40`. The next case is `x = 39`, so clearly the smallest move is to remove an element (it is the only possible move that could result in successfully balancing against 39): `A + B + C = 39`, so `D = 1`, by neccessity. next: `A + B + C - D = 38` next: `A + B + D = 37`, so `C = 3` then: `A + B = 36` then: `A + B - D = 35` `A + B - C + D = 34` `A + B - C = 33` `A + B - C - D = 32` `A + C + D = 31`, so `A = 9` Therefore `B = 27` So the weights are `1, 3, 9, 27` Really this can be deduced immediately from the fact that they must all be multiples of 3. **Interesting Update:** So here is some python code to find a minimum set of weights for any dropped weight that will span the space: def find_weights(W): weights = [] i = 0 while sum(weights) < W: weights.append(3 ** i) i += 1 weights.pop() weights.append(W - sum(weights)) return weights print find_weights(40) #output: [1, 3, 9, 27] To further illustrate this explaination, one can consider the problem as the minimum number of weights to span the number space `[0, 40]`. It is evident that the number of things you can do with each weight is trinary /ternary (add weight, remove weight, put weight on other side). So if we write our (unknown) weights `(A, B, C, D)` in descending order, our moves can be summarised as: ABCD: Ternary: 40: ++++ 0000 39: +++0 0001 38: +++- 0002 37: ++0+ 0010 36: ++00 0011 35: ++0- 0012 34: ++-+ 0020 33: ++-0 0021 32: ++-- 0022 31: +0++ 0100 etc. I have put ternary counting from 0 to 9 alongside, to illustrate that we are effectively in a trinary number system (base 3). Our solution can always be written as: 3**0 + 3**1 +3**2 +...+ 3**N >= Weight For the minimum N that this holds true. The minimum solution will ALWAYS be of this form. Furthermore, we can easily solve the problem for large weights and find the minimum number of pieces to span the space: **A man drops a known weight W, it breaks into pieces. His new weights allow him to weigh any weight up to W. How many weights are there, and what are they?** #what if the dropped weight was a million Kg: print find_weights(1000000) #output: [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 202839] Try using permutations for a large weight and unknown number of pieces!!
Python script to fetch URL protected by DES/kerberos Question: I have a Python script that does an automatic download from a URL once a day. Recently the authentication protecting the URL was changed. To get it to work with Internet Explorer I had to enable DES for Kerberos by adding SupportedEncryptionTypes " 0x7FFFFFFF" in a registry entry somewhere. Then it prompts me for my domain/user/password in IE when I browse to the site. My python code that was working before is: def __build_ntlm_opener(self): passman = HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, self.answers_url, self.ntlm_username, self.ntlm_password) ntlm_handler = HTTPNtlmAuthHandler(passman) opener = urllib.request.build_opener(ntlm_handler) opener.addheaders= [ #('User-agent', 'Mozilla/5.0 (Windows NT 6.0; rv:5.0) Gecko/20100101 Firefox/5.0') ('User-agent', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)') ] return opener Now the code is failing with a simple 401 when using the opener: urllib.error.HTTPError: HTTP Error 401: Unauthorized I don't know much about Kerberos or DES but from what I see so far I can't figure out if urllib supports using these. Is there any 3rd party library or trick I can use to get this working again? Answer: You could try using selenium's webdriver to directly drive a browser. I do that sometimes when I want to scrape sites that are dynamically generated. Here's a code example for opening a page and entering a password from selenium import webdriver b = webdriver.Chrome() b.get('http://www.example.com') username_field = b.find_element_by_id('username') username_field.send_keys('my_username') password_field = b.find_element_by_id('password') password_field.send_keys('secret') login_button = b.find_element_by_link_text('login').click() That would get you past a typical login screen of a web site. Then b.page_source Will give you the source code for the page. Even if it was mainly generated with Javascript. The source code is very simple to parse: <http://code.google.com/p/selenium/source/browse/trunk/py/selenium/webdriver/remote/webelement.py>
python, Json and string indices must be integers, not str Question: I am using Python, and I sent a request to a URL and received a reply using httplib2. The reply I got was in JSon, how do I access a specific parameter. What I have at the moment is: resp, content = parser.request(access_token_uri, method = 'POST', body = params, headers = headers) raise Exception(content['access_token']) and I get the error string indices must be integers, not str How do I do it? Thanks Answer: Well if the response type is json and it comes in type str. If you are running 2.4 of Python use simplejson if 2.6 use json: import json # Your code retdict = json.loads(content) Then treat it like a dictionary. accesstoken = retdict['access_token']
very slow cython classes? Question: This code which contains cython classes: cdef class Bench: cdef long n def __cinit__(self, long n): self.n = n cpdef int factors(self): n = self.n cdef int fac = 0 cdef unsigned long i for i in range(2, n): if n % i == 0: fac += 1 return fac if __name__ == "__main__": print "hw" which I called like this after compiling to a python extension: from time import time t1 = time() import factors_class ben = factors_class.Bench(1000000007) print ben.factors() t2 = time() print t2 - t1 and it prints out 207.374788046 (Seconds) but the pure python version (with just the function and a call to it) runs in ~ 77s and a cython code without class structure runs in ~ 10.2s class-less version in cython: cdef int factors(unsigned long n): cdef int fac = 0 cdef unsigned long i for i in range(2, n): if n % i == 0: fac += 1 return fac print factors(1000000007) if __name__ == "__main__": print "hw" Python version: def factors(n): fac = 0 for i in xrange(2, n): if n % i == 0: fac += 1 return fac print factors(10000007) I want to use cython classes for my library but, they seem to be very slow compared to functional style programming in cython. Clearly something is wrong in my cython class code. How can I improve its speed? To summarise the benchmark results: Cython class : 206s Cython : 10.2s python : 77s Answer: declare a type for local variable n: cdef long n = self.n
Python: getting lowest integer in list of tuples Question: My current plan is to determine which is the first entry in a number of [Tkinter](http://wiki.python.org/moin/TkInter) listboxes highlighted using `.curselection()` and combining all of the resulting tuples into a list, producing this: tupleList = [(), (), ('24', '25', '26', '27'), (), (), (), ()] I'm wondering as to how to determine the lowest integer. Using `.min(tupleList)` returns only `()`, being the lowest entry in the list, but I'm looking for a method that would return 24. What's the right way to get the lowest integer in any tuple in the list? Answer: >>> from itertools import chain >>> nums = [(), (), ('24', '25', '26', '27'), (), (), (), ()] >>> min(map(int,chain.from_iterable(nums))) 24
Using Beautiful Soup to convert CSS attributes to individual HTML attributes? Question: I'm trying to write a program that will take an HTML file and make it more email friendly. Right now all the conversion is done manually because none of the online converters do exactly what we need. This sounded like a great opportunity to push the limits of my programming knowledge and actually code something useful so I offered to try to write a program in my spare time to help make the process more automated. I don't know much about HTML or CSS so I'm mostly relying on my brother (who does know HTML and CSS) to describe what changes this program needs to make, so please bear with me if I ask a stupid question. This is totally new territory for me. Most of the changes are pretty basic -- if you see tag/attribute X then convert it to tag/attribute Y. But I've run into trouble when dealing with an HTML tag containing a style attribute. For example: <img src="http://example.com/file.jpg" style="width:150px;height:50px;float:right" /> Whenever possible I want to convert the style attributes into HTML attributes (or convert the style attribute to something more email friendly). So after the conversion it should look like this: <img src="http://example.com/file.jpg" width="150" height="50" align="right"/> Now I realize that not all CSS style attributes have an HTML equivalent, so right now I only want to focus on the ones that do. I whipped up a Python script that would do this conversion: from bs4 import BeautifulSoup import re class Styler(object): img_attributes = {'float' : 'align'} def __init__(self, soup): self.soup = soup def format_factory(self): self.handle_image() def handle_image(self): tag = self.soup.find_all("img", style = re.compile('.')) print tag for i in xrange(len(tag)): old_attributes = tag[i]['style'] tokens = [s for s in re.split(r'[:;]+|px', str(old_attributes)) if s] del tag[i]['style'] print tokens for j in xrange(0, len(tokens), 2): if tokens[j] in Styler.img_attributes: tokens[j] = Styler.img_attributes[tokens[j]] tag[i][tokens[j]] = tokens[j+1] if __name__ == '__main__': html = """ <body>hello</body> <img src="http://example.com/file.jpg" style="width:150px;height:50px;float:right" /> <blockquote>my blockquote text</blockquote> <div style="padding-left:25px; padding-right:25px;">text here</div> <body>goodbye</body> """ soup = BeautifulSoup(html) s = Styler(soup) s.format_factory() Now this script will handle my particular example just fine, but it's not very robust and I realize that when put up against real world examples it will easily break. My question is, how can I make this more robust? As far as I can tell Beautiful Soup doesn't have a way to change or extract individual pieces of a style attribute. I guess that's what I'm looking to do. Answer: For this type of thing, I'd recommend an HTML parser (like BeautifulSoup or lxml) in conjunction with a specialized CSS parser. I've had success with [the cssutils package](http://pypi.python.org/pypi/cssutils/). You'll have a much easier time than trying to come up with regular expressions to match any possible CSS you might find in the wild. For example: >>> import cssutils >>> css = 'width:150px;height:50px;float:right;' >>> s = cssutils.parseStyle(css) >>> s.width u'150px' >>> s.height u'50px' >>> s.keys() [u'width', u'height', u'float'] >>> s.cssText u'width: 150px;\nheight: 50px;\nfloat: right' >>> del s['width'] >>> s.cssText u'height: 50px;\nfloat: right' So, using this you can pretty easily extract and manipulate the CSS properties you want and plug them into the HTML directly with BeautifulSoup. Be a little careful of the newline characters that pop up in the `cssText` attribute, though. I think cssutils is more designed for formatting things as standalone CSS files, but it's flexible enough to mostly work for what you're doing here.
Create and stream a large archive without storing it in memory or on disk Question: I want to allow users to download an archive of multiple large files at once. However, the files and the archive may be too large to store in memory or on disk on my server (they are streamed in from other servers on the fly). I'd like to generate the archive as I stream it to the user. I can use Tar or Zip or whatever is simplest. I am using django, which allows me to return a generator or file-like object in my response. This object could be used to pump the process along. However, I am having trouble figuring out how to build this sort of thing around the zipfile or tarfile libraries, and I'm afraid they may not support reading files as they go, or reading the archive as it is built. This answer on [converting an iterator to a file-like object](http://stackoverflow.com/questions/6657820/python-convert-an-iterable- to-a-stream) might help. `tarfile#addfile` takes an iterable, but it appears to immediately pass that to `shutil.copyfileobj`, so this may not be as generator-friendly as I had hoped. Answer: You can do it by generating and streaming a zip file with no compression, which is basically to just add the headers before each file's content. You're right, the libraries don't support this, but you can hack around them to get it working. This code wraps zipfile.ZipFile with a class that manages the stream and creates instances of zipfile.ZipInfo for the files as they come. CRC and size can be set at the end. You can push data from the input stream into it with put_file(), write() and flush(), and read data out of it to the output stream with read(). import struct import zipfile import time from StringIO import StringIO class ZipStreamer(object): def __init__(self): self.out_stream = StringIO() # write to the stringIO with no compression self.zipfile = zipfile.ZipFile(self.out_stream, 'w', zipfile.ZIP_STORED) self.current_file = None self._last_streamed = 0 def put_file(self, name, date_time=None): if date_time is None: date_time = time.localtime(time.time())[:6] zinfo = zipfile.ZipInfo(name, date_time) zinfo.compress_type = zipfile.ZIP_STORED zinfo.flag_bits = 0x08 zinfo.external_attr = 0600 << 16 zinfo.header_offset = self.out_stream.pos # write right values later zinfo.CRC = 0 zinfo.file_size = 0 zinfo.compress_size = 0 self.zipfile._writecheck(zinfo) # write header to stream self.out_stream.write(zinfo.FileHeader()) self.current_file = zinfo def flush(self): zinfo = self.current_file self.out_stream.write(struct.pack("<LLL", zinfo.CRC, zinfo.compress_size, zinfo.file_size)) self.zipfile.filelist.append(zinfo) self.zipfile.NameToInfo[zinfo.filename] = zinfo self.current_file = None def write(self, bytes): self.out_stream.write(bytes) self.out_stream.flush() zinfo = self.current_file # update these... zinfo.CRC = zipfile.crc32(bytes, zinfo.CRC) & 0xffffffff zinfo.file_size += len(bytes) zinfo.compress_size += len(bytes) def read(self): i = self.out_stream.pos self.out_stream.seek(self._last_streamed) bytes = self.out_stream.read() self.out_stream.seek(i) self._last_streamed = i return bytes def close(self): self.zipfile.close() Keep in mind that this code was just a quick proof of concept and I did no further development or testing once I decided to let the http server itself deal with this problem. A few things you should look into if you decide to use it is to check if nested folders are archived correctly, and filename encoding (which is always a pain with zip files anyway).
how to add image with text in qlistwidget pyqt4 python? Question: How to add image/icon with text in a qlistwidget in pyqt4 python? I want to add an icon with text just like a chat system. thanks Answer: I have tried this right now and it works, supposing you have a file named tick.png in the same folder as this script. import sys from PyQt4 import QtGui, QtCore from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon def main(): app = QtGui.QApplication(sys.argv) window = QDialog() list = QListWidget( window ) itm = QListWidgetItem( "Tick" ); itm.setIcon(QIcon(r"tick.png")); list.addItem(itm); window.show( ) sys.exit(app.exec_()) if __name__ == '__main__': main() The chat-like-icon system may be different from this, but right now I don't see a way to have a QListWidgetItem with multiple smileys and text. You may think of smileys as a particular case of a QListWidgetItem where the text is blank and only the icon is present. Another solution is using a read-only QTextEdit as chatboard and have the user typing its text + icon + text (etc.) in a separate editable QTextEdit. Then, when he presses the send button, append everything he typed to the read-only QTextEdit. import sys from PyQt4 import QtGui, QtCore from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon, QTextEdit, QTextDocumentFragment def main(): app = QtGui.QApplication(sys.argv) window = QDialog() list = QListWidget( window ) textEditor = QTextEdit( window ); textEditor.setReadOnly( True ) tick_icon = QTextDocumentFragment.fromHtml(r"<img src='tick.png'>"); textEditor.insertPlainText ( " ValiumKnight writes: " ) textEditor.textCursor().insertFragment(tick_icon); textEditor.insertPlainText ( " Hello World " ) textEditor.textCursor().insertFragment(tick_icon); textEditor.textCursor().insertFragment(tick_icon); textEditor.textCursor().insertFragment(tick_icon); window.show( ) sys.exit(app.exec_()) if __name__ == '__main__': main() Bye!
Python: Unresolved import error for sqlite3 in PyDev in Eclipse Question: import sqlite3 generates: Unused import: sqlite3 Unresolved import: sqlite3 sqlite3 Found at: DatabaseTests import sqlite3 However, this works perfectly in the terminal when using the python command- line. I am running on a Mac Mountain Lion, with the default installation of Python. I am using PyDev in Eclipse Indigo. Answer: This is a very old thread but I don't see the solution I found for this problem so I'll post it in hopes that somebody sees this and can then solve the problem: you need to add 'sqlite3' (without the quotatios) in the 'forced builtins' tab in Window>Preferences>PyDev>Python Interpreter
importing simple program using pyqt4 and python Question: from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, \ QLabel, QVBoxLayout, QWidget from PyQt4 import QtGui import sys import subprocess class MainWindow1(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) button = QPushButton('NotePad') label = QLabel('MainWindow1') centralWidget = QWidget() vbox = QVBoxLayout(centralWidget) vbox.addWidget(label) vbox.addWidget(button) self.setCentralWidget(centralWidget) button.clicked.connect(self.LaunchNotepad) # Some code here - including import subprocess def LaunchNotepad(self): returncode = subprocess.call(['python', 'notepad.py']) if __name__ == '__main__': app = QApplication(sys.argv) mainwindow1 = MainWindow1() mainwindow1.show() sys.exit(app.exec_()) that code creates a main window with a button, when i press the button i would like it to import my file called "notepad", (I think it does) however it opens it and closes it straight away. I need to be able to use the program notepad until i close it in which case it should revert back to the original window. Eventually i will have 3 or 4 buttons importing 3 or 4 different programs I dont think there is an error in notepad because when i only have the statement "import notepad" it runs perfectly note: the notepad file is just a simple text program (much like the "notepad" program on windows pcs) thanks in advance edit here is note pad code: import sys import os import datetime as dt from PyQt4 import QtGui from PyQt4 import * class Notepad(QtGui.QMainWindow): def __init__(self): super(Notepad, self).__init__() self.initUI() def initUI(self): newAction = QtGui.QAction('New', self) newAction.setShortcut('Ctrl+N') newAction.setStatusTip('Create new file') newAction.triggered.connect(self.newFile) saveAction = QtGui.QAction('Save', self) saveAction.setShortcut('Ctrl+S') saveAction.setStatusTip('Save current file') saveAction.triggered.connect(self.saveFile) openAction = QtGui.QAction('Open', self) openAction.setShortcut('Ctrl+O') openAction.setStatusTip('Open a file') openAction.triggered.connect(self.openFile) closeAction = QtGui.QAction('Close', self) closeAction.setShortcut('Ctrl+Q') closeAction.setStatusTip('Close Notepad') closeAction.triggered.connect(self.close) menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(newAction) fileMenu.addAction(saveAction) fileMenu.addAction(openAction) fileMenu.addAction(closeAction) #help menu helpMenu = menubar.addMenu('&Help') aboutAction = QtGui.QAction('About', self) aboutAction.setShortcut('Ctrl+A') aboutAction.setStatusTip('About') helpMenu.addAction(aboutAction) aboutAction.triggered.connect(self.about) self.text = QtGui.QTextEdit(self) self.setCentralWidget(self.text) self.setGeometry(300,300,300,300) self.setWindowTitle('Notepad') self.show() self.statusBar() def newFile(self): self.text.clear() def saveFile(self): filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File', os.getenv('HOME')) f = open(filename, 'w') filedata = self.text.toPlainText() f.write(filedata) f.close() def openFile(self): filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME')) f = open(filename, 'r') filedata = f.read() self.text.setText(filedata) f.close() self.setGeometry(300,300,300,300) self.setWindowTitle('Notepad') self.show() def closeEvent(self, event): reply = QtGui.QMessageBox.question(self, 'Message', "Are you sure to quit?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: event.accept() else: event.ignore() def about(self, event): reply = QtGui.QMessageBox.question(self, 'About Task Manager', "This is a notepad todo list program written by craig murch") return Notepad if __name__ == '__main__': app = QtGui.QApplication(sys.argv) notepad = Notepad() sys.exit(app.exec_()) EDIT: The edited code above now does want i want it to do however it loads the cmd as well which i dont want to, how do i stop it loading the cmd? Answer: Well, in your Notepad code you have sys.exit(app.exec_()) This will close the _entire process_. So if you're importing it from your parent window then yeah, it should be closing your application. Also, regardless of which GUI framework you use it's always a bad idea to mix mainloops in the same process. Instead, you should use `subprocess` to call your other application: # Some code here - including import subprocess import os def LaunchNotepad(self): self.DoSomething() #Or whatever you want to do before your program launches returncode = subprocess.call(['pythonw', 'notepad.py'], stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w')) self.ShowMe() #Won't run until notepad finishes if not returncode: self.ShowError("Notepad exited abnormally!") That's a pretty basic example of what you could do.
Python: CheckBox-es in QTableWidget's column Question: I've just started to work with python, so I run into problem. I've searched everywhere, but I couldn't find similar example. So, the problem is following: I made a simple GUI using QT-Designer. QTableWidget is being filled out by clicking on button Analyse. (as you can see on the picture) [link for picture](http://desmond.imageshack.us/Himg41/scaled.php?server=41&filename=picuu.png&res=landing) When I select one checkBox the rest of them are being selected randomly, and I don't know why. As I said, I'm new at Python, so the good explanation would mean a lot to me. Here is the source code: import sys from PyQt4 import QtGui,QtCore from IDCS import * class MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.connect(self.ui.analyseButton, QtCore.SIGNAL('clicked()'), self.doAnalyse) self.connect(self.ui.quitButton, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def doAnalyse(self): self.ui.tableWidget.setRowCount(10) chkBoxItem = QtGui.QTableWidgetItem() chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) chkBoxItem.setCheckState(QtCore.Qt.Unchecked) for i in range(10): self.ui.tableWidget.setItem(i, 0, chkBoxItem) self.ui.tableWidget.setItem(i, 1, QtGui.QTableWidgetItem("description %s" % (i+1))) self.ui.tableWidget.setItem(i, 2, QtGui.QTableWidgetItem("name %s" % (i+1))) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyForm() myapp.show() sys.exit(app.exec_())e Answer: You are making only one instance of the CheckBox and putting it in 10 different places and that is wrong. You have to make 10 instances of CheckBox, and you will do that by moving those 3 lines of code, in which you are creating instance of CheckBox, under the for loop below.
Python: can a class instance evaluate to any type? Question: A class can act as a string through its __str__ method, or as a function via its __call__ method. Can it act as, say, a list, or a tuple? class A (object): def __???__ (self): return (1, 2, 3) >>> a = A() >>> a * 3 (1, 2, 3, 1, 2, 3, 1, 2, 3) **EDIT...** Here's a better example to help clarify the above. class Vector (object): def __init__ (self): self.vec = (1,2,3) def __???__ (self): # something like __repr__; non-string return self.vec class Widget (object): def __init__ (self): self.vector = Vector() >>> w = Widget() >>> w.vector (1, 2, 3) # not a string representation (at least, before being repr'd here) Basically, I want something like __repr__ that doesn't return a string, but returns a tuple (or list) when I simply invoke the name pointing to the Vector instance, but I don't want to lose the rest of the abilities in the instance, like access to other properties and methods. I also don't want to have to use `w.vector.vec` to get to the data. I want vector to act like a tuple attribute of w, while still being able to do something like `w.vector.whatever()`, or overriding __mul__ so I can scale the vector via `w.vector * 5`. Possible? Answer: Depending on what your goal is, you can create a class that inherits from built-in classes like `list` or `tuple`: >>> class A(tuple): ... def speak(self): ... print "Bark!" ... >>> a = A((1,2,3)) # extra parens needed to distinguish single tuple arg from 3 scalar args >>> a * 3 (1, 2, 3, 1, 2, 3, 1, 2, 3) >>> a.speak() Bark! Given your Vector use case, subclassing tuple might well do the trick. import math class Vector(tuple): def magnitude(self): return math.sqrt( self[0]*self[0]+self[1]*self[1]+self[2]*self[2] )
Python multiplication table syntax differences Question: So I'm learning python as a beginner and have been using How to Think Like a Computer Scientist for python 3. I'm on the chapter about iteration, doing the coding from my own brain instead of copy/pasting so I remember it easier. When doing the last part of the multiplication table section, I got the same output as the lesson showed, but it seems like mine is cleaner (fewer arguments). I'm still trying to get the hang of tracing programs, so I'm having a hard time wrapping my head around the differences. I was hoping someone could let me know if my code is less efficient or more error prone somehow than the text's version and help end this headache ;). def print_multiples(n, high): #This is the e-book version for i in range(1, high+1): print(n * i, end=' ') print() def print_mult_table(high): for i in range(1, high+1): print_multiples(i, i+1) #They changed high+1 to i+1 to halve output [Source](http://openbookproject.net/thinkcs/python/english3e/iteration.html "e-book source") It seems like their result would have too many +1's, since i+1 would become 'high' in print_multiples and then end up adding +1 again in print_multiples' loop. (I also noticed they kept the end=' ' instead of a end='\t' which threw off alignment. def print_multiples(n): #n is the number of columns that will be made '''Prints a line of multiples of factor 'n'.''' for x in range(1, n+1): #prints n 2n 3n ... until x = n+1 print(n * x, end='\t') #(since x starts counting at 0, print() #n*n will be the final entry) def print_mult_table(n): #n is the final factor '''Makes a table from a factor 'n' via print_multiples(). ''' for i in range(1, n+1): #call function to print rows with i print_multiples(i) #as the multiplier. This is mine. The elementary comments were for my benefit trying to keep the tracing straight in my head. My functions make a lot more sense to me, but there could be some difference. I don't really understand why the book decided to make two arguments for print_multiples() since 1 seems sufficient to me...I also changed most of the variables since they were using 'i' and 'high' multiple times to demonstrate local vs global. I re-used n, though, since it would be the same final number in both cases. There might be more efficient ways to do this type of thing, but I'm still on iteration. Just hoping to try to get a feel for what works and what doesn't and this one is bugging me. Answer: (Note: right, you're running Python 3.x) Your code is simpler and makes more sense to me, too. Theirs is correct, but its intention is not quite the same, so its output is different. Carefully compare the outputs of both and see if you can notice the pattern of difference. Your code is slightly more "efficient", but printing stuff to the screen takes a (relatively) long time, and your program prints slightly less than theirs. To measure efficiency, you can "profile" code in Python to see how long things take. Below is the code I ran to a) inspect the difference in source text and output b) profile the code to see which was faster. You might try running it. Good luck! import cProfile def print_multiples0(n, high): #This is the e-book version for i in range(1, high+1): print(n * i, end=' ') print() def print_mult_table0(high): for i in range(1, high+1): print_multiples0(i, i+1) #They changed high+1 to i+1 to halve output def print_multiples1(n): #n is the number of columns that will be made '''Prints a line of multiples of factor 'n'.''' for x in range(1, n+1): #prints n 2n 3n ... until x = n+1 print(n * x, end='\t') #(since x starts counting at 0, print() #n*n will be the final entry) def print_mult_table1(n): #n is the final factor '''Makes a table from a factor 'n' via print_multiples(). ''' for i in range(1, n+1): #call function to print rows with i print_multiples1(i) #as the multiplier. def test( ) : print_mult_table0( 10) print_mult_table1( 10) cProfile.run( 'test()')
Split string by multiple separators? Question: > **Possible Duplicate:** > [Python: Split string with multiple > delimiters](http://stackoverflow.com/questions/4998629/python-split-string- > with-multiple-delimiters) Can I do something similar in Python? Split method in VB.net: Dim line As String = "Tech ID: xxxxxxxxxx Name: DOE, JOHN Account #: xxxxxxxx" Dim separators() As String = {"Tech ID:", "Name:", "Account #:"} Dim result() As String result = line.Split(separators, StringSplitOptions.RemoveEmptyEntries) Answer: Given a bad data format like this, you could try `re.split()`: >>> import re >>> mystring = "Field 1: Data 1 Field 2: Data 2 Field 3: Data 3" >>> a = re.split(r"(Field 1:|Field 2:|Field 3:)",mystring) ['', 'Field 1:', ' Data 1 ', 'Field 2:', ' Data 2 ', 'Field 3:', ' Data 3'] Your job would be much easier if the data was sanely formatted, with quoted strings and comma-separated records. This would admit the use of the `csv` module for parsing of comma-separated value files. Edit: You can filter out the blank entries with a list comprehension. >>> a_non_empty = [s for s in a if s] >>> a_non_empty ['Field 1:', ' Data 1 ', 'Field 2:', ' Data 2 ', 'Field 3:', ' Data 3']
python mechanize FormNotFoundError Question: I am working on mechanize to fetch form element import mechanize br = mechanize.Browser() br.set_handle_robots(False) br.open("http://www.bnm.gov.my/index.php?ch=12&pg=622") br.select_form(name="Rates") But this is throwing error: FormNotFoundError: no form matching name 'Rates' Even though there is <form onsubmit="return validate();" method="get" action="index.php" name="Rates"> can some one help on this Thanks in advance Answer: Try selecting the form with the nr param: select_form(self, name=None, predicate=None, nr=None) I guess that page has only 1 form, so try nr=0. If there is no form in the page, then it probably means that it was added using Javascript. And, in that case, mechanize won't be enough. You will have to use Selenium or Spynner.
How to optimize a wxpython GUI (without threading preferably)? hints for code below? Question: My GUI with following code does not have threads.The image display hogs up lots of memory and GUI is blocked ,and I can only call one function at a time.Please suggest simple hacks to make the GUI faster.Anyways The Image processing tasks like Clustering takes 5-6 mins. import wx import sys import os import matplotlib import OpenGL import PIL import time from spectral.graphics.hypercube import hypercube from spectral import * init_graphics() class RedirectText(object): def __init__(self,awxTextCtrl): self.out=awxTextCtrl def write(self,string): self.out.WriteText(string) class Frame(wx.Frame): def __init__(self, title,*args,**kwargs): wx.Frame.__init__(self, None, title=title, size= (1000,85),style=wx.MINIMIZE_BOX|wx.CLOSE_BOX|wx.RESIZE_BORDER|wx.SYSTEM_MENU|wx.CAPTION|wx.CLIP_CHILDREN) self.Bind(wx.EVT_CLOSE, self.OnClose) panel=wx.Panel(self,-1) self.button=wx.Button(panel,label="Open",pos=(0,0),size=(50,30)) self.button1=wx.Button(panel,label="Save",pos=(51,0),size=(50,30)) self.button2=wx.Button(panel,label="ROI",pos=(102,0),size=(50,30)) self.button3=wx.Button(panel,label="Tone",pos=(153,0),size=(50,30)) self.slider=wx.Slider(panel,pos=(204,0)) self.button4=wx.Button(panel,label="Header",pos=(305,0),size=(50,30)) self.button5=wx.Button(panel,label="Cluster",pos=(356,0),size=(50,30)) self.button6=wx.Button(panel,label="Cube",pos=(407,0),size=(50,30)) self.button7=wx.Button(panel,label="Gaussian",pos=(458,0),size=(50,30)) self.Bind(wx.EVT_BUTTON, self.OnCubeClick,self.button5) self.Bind(wx.EVT_BUTTON, self.OnHeadClick,self.button4) self.Bind(wx.EVT_BUTTON, self.OnSaveClick,self.button1) self.Bind(wx.EVT_BUTTON, self.OnButtonClick,self.button) self.Bind(wx.EVT_BUTTON, self.OnCClick,self.button6) self.Bind(wx.EVT_BUTTON, self.OnGClick,self.button7) #self.std=wx.TextCtrl(panel,pos=(0,31), size=(500,-1)) self.loc=wx.TextCtrl(panel,pos=(700,0), size=(300,-1)) self.status = wx.TextCtrl(panel,-1,'Choose file',pos=(800,22),size=(200,-1)) #redir=RedirectText(self.std) #sys.stdout=redir def OnButtonClick(self,event): wild="HSi Files|*.lan*|All Files|*.*" dlg=wx.FileDialog(self,message="Choose a File",wildcard=wild,style=wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: time.sleep(0.5) self.loc.SetValue(dlg.GetPath()) dlg.Destroy() self.Onview() def Onview(self): filepath=self.loc.GetValue() img=image(filepath) time.sleep(1) view(img) time.sleep(1) self.status.SetValue('View Ready') def OnHeadClick(self,event): filepath=self.loc.GetValue() img=image(filepath) self.status.SetValue(img.shape) def OnCubeClick(self,event): time.sleep(0.2) self.status.SetValue('Clustering') filepath=self.loc.GetValue() img= image(filepath).load() (m, c) = cluster(img, 20) view_indexed(m) self.status.SetValue('Clustering View Ready') def OnCClick(self,event): self.status.SetValue('Cube view') time.sleep(5) filepath=self.loc.GetValue() img= image(filepath).load() hypercube(img, bands=[29, 19, 9]) def OnGClick(self,event): self.status.SetValue('Gaussian procesing') time.sleep(30) filepath=self.loc.GetValue() gt=image(filepath).read_band(0) img=image(filepath) classes = create_training_classes(img,gt) gmlc = GaussianClassifier(classes) clMap = gmlc.classify_image(img) view_indexed(clMap) self.status.SetLabel('Gaussian Ready') def OnSaveClick(self,event): self.status.SetValue('Save File') wild="HSi Files|*.lan*|All Files|*.*" dlg=wx.FileDialog(self,message="Save AS",wildcard=wild,style=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: path=dlg.GetPath() self.Save(path) self.file=path dlg.Destroy() def OnClose(self, event): dlg = wx.MessageDialog(self, "Do you really want to close BBvw ?", "Confirm Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION) result = dlg.ShowModal() dlg.Destroy() if result == wx.ID_OK: self.Destroy() app = wx.App(redirect=False) top = Frame("BBvw") top.Show() app.MainLoop() Answer: Long running processes should always go into separate threads. Otherwise they will block the GUI's mainloop. If displaying the image is taking up lots of memory, then I'm guessing you're displaying high res photos at full resolution. Try creating a set of lower resolution photos for displaying instead (like thumbnails or something). Unless you need the full resolution displayed, don't do it.
avoid user abort python subprocesses Question: I want the process i initiate through the script to run on webserver even if user closes the page. It doesn't seem to be working with this: #!/usr/bin/env python # -*- coding: UTF-8 -*- import cgi,cgitb,subprocess print "Content-Type: text/plain;charset=utf-8" print form = cgi.FieldStorage() ticker = form['ticker'].value print subprocess.Popen(['/usr/bin/env/python','options.py',ticker]) Please help! Thanks! Answer: I guess this is wrong: '/usr/bin/env/python' it should be usually: '/usr/bin/env python' but better use this: >>> import sys >>> sys.executable # contains the executable running this python process 'C:\\Python27\\pythonw.exe' I use to do it like this: p = subprocess.Popen([sys.executable,'options.py',ticker])
lightweight unit testing in python Question: I'm considering using Python to teach introductory programming, and I'm looking for a lightweight unit testing framework. I've taken a look at unittest, and--as far as I can tell--it looks insanely _non_ -lightweight. For example, here's what I'd like to be able to write: import unittest def f(x): return x+2 checkEqual(f(3),5) ... and _nothing else_. To show you where I'm coming from, this is what I'd write in Racket's beginning student language: (define (f x) (+ x 2)) (check-expect (f 3) 5) ... and that's it. Surely someone's written this tool, and I'm just not finding it? (Apologies in advance for any appearance of flame-baiting. This is a serious question.) SELF-EDIT: Before anyone points this out: yes, I could write def checkEqual(a,b): print(a==b) ; I'm looking for something with a bit more: it should be able to check numbers with tolerances, it should have support for printing only failed test cases, it should be able to tell you how many test cases failed. Again, I'm confident that this code can be written; I'm just trying to avoid re- inventing the wheel. Answer: I would recommend [Doctest](http://docs.python.org/library/doctest.html). Your example would look like: def f(x): """ >>> f(3) 5 """ return x + 2 Why?: 1. It's super simple: "when I run this thing I should get this answer back" 2. It works on the function level - which might allow you to introduce testing even before classes 3. Mirrors the interactive Python experience.
Python dict using dot notation and chaining Question: Ideally what I am aiming to accomplish is a class that extends (or is very similar to) a `dict` in Python with the additional capabilities: * Dot-Notation capable for setting and getting values * Key-Value capabilities like `dict` (i.e. setitem,getitem) * Can chain dot-notated operations The goal is if I have something like `example = DotDict()` I could do the following against it `example.configuration.first= 'first'` and it would instantiate the appropriate DotDict instances under `example` with the really painful caveat being that if the operation is not assignment it should simply raise a `KeyError` like a `dict` would do Here is what I have naively assembled class DotDict(dict): def __getattr__(self, key): """ Make attempts to lookup by nonexistent attributes also attempt key lookups. """ import traceback import re s= ''.join(traceback.format_stack(sys._getframe(1),1)) if re.match(r' File.*\n.*[a-zA-Z]+\w*\.[a-zA-Z]+[a-zA-Z0-9_. ]*\s*=\s*[a-zA-Z0-9_.\'"]+',s): self[key] = DotDict() return self[key] return self[key] def __setattr__(self, key, value): if isinstance(value,dict): self[key] = DotDict(value) self[key] = value It works except for some common edge cases, I must say that I absolutely hate this method and there must be a better way. Looking at the stack and running a regular expression on the last line is not a good way to accomplish this. The heart of the matter is that Python interprets lines of code left to right so when it arrives at a statement like `a.b.c = 3` it's first operation is a `getattr(a,b)` and not a `setattr` so I can't determine easily if the last operation in the stack of operations is an assignment. What I would like to know is if there is a good way to determine the last operation in the stack of operations or at least if it's a `setattr`. Edit: This is the solution that I came up with thanks to user1320237's recommendation. class DotDict(dict): def __getattr__(self, key): """ Make attempts to lookup by nonexistent attributes also attempt key lookups. """ if self.has_key(key): return self[key] import sys import dis frame = sys._getframe(1) if '\x00%c' % dis.opmap['STORE_ATTR'] in frame.f_code.co_code: self[key] = DotDict() return self[key] raise AttributeError('Problem here') def __setattr__(self, key, value): if isinstance(value,dict): self[key] = DotDict(value) self[key] = value There's a little bit more in the actual implementation but it does an awesome job. The way it works is that it inspects the last frame in the stack and checks the byte code for a STORE_ATTR operation which means that the operation being performed is of the `a.b.this.doesnt.exist.yet = 'something'` persuasion. I would be curious if this could be done on other interpreters outside of CPython. Answer: You may need to overwrite **getattribute** for those edge cases and then use the object.__getattribute__ Have a look at the module [dis](http://docs.python.org/library/dis.html). But what you wrote is nicer than disassembling. >>> import dis >>> def g(): a.b.c = 4 >>> dis.dis(g) 2 0 LOAD_CONST 1 (4) 3 LOAD_GLOBAL 0 (a) 6 LOAD_ATTR 1 (b) 9 STORE_ATTR 2 (c) 12 LOAD_CONST 0 (None) 15 RETURN_VALUE
Media Play/Pause Simulation Question: My keyboard contains a row of buttons for various non-standard keyboard tasks. These keys contain such functions as modifying the volume, playing or pausing, and skipping tracks. How can I simulate a basic play/pause with Python? I am on Windows, by the way. Answer: I would use [pywin32](http://starship.python.net/crew/mhammond/win32/Downloads.html). Bundled with the installation is a large number of API-docs (usually placed at something like `C:\Python32\Lib\site-packages`.) It essentially wraps a lot of stuff in the Win32-library which is used for many low-levels tasks in Windows. After installing it you could use the wrapper for [keybd_event](http://msdn.microsoft.com/en- us/library/windows/desktop/ms646304.aspx). _You could also use`SendInput` instead of `keybd_event` but it doesn't seem to be wrapped by PyWin32. `SendMessage` is also an option but more cumbersome._ You'll need to look up the virtual scan code for those special buttons, since I doubt the char-to-code mapping functions will help you here. You can find the reference [here](http://msdn.microsoft.com/en- us/library/windows/desktop/dd375731.aspx). Then it is a simple matter of calling the function. The snippet below pauses Chuck Berry on my computer. >>> import win32api >>> VK_MEDIA_PLAY_PAUSE = 0xB3 >>> hwcode = win32api.MapVirtualKey(VK_MEDIA_PLAY_PAUSE, 0) >>> hwcode 34 >>> win32api.keybd_event(VK_MEDIA_PLAY_PAUSE, hwcode) `MapVirtualKey` gives us the hardware scan code which `keybd_event` needs (or more likely, the keyboard driver.) Note that all this is snapped up by the keyboard driver, so you don't really have any control where the keystrokes are sent. With `SendMessage` you can send them to a specific window. It usually doesn't matter with media keys since those are intercepted by music players and such.