text
stringlengths
226
34.5k
What does the underscore mean in python Question: Hi everyone as it obvious from my question I am like a brand new to python. I am so confused when I am reading the documentation on python or even here in the Stackoverflow forum... Why do they write like that from __future__ import division What does the underscore around the Future word mean ?? And Are we supposed to use it like that with the underscore in the python interpreter ? This is just one of tons of examples. Any help would be greatly appericated. Answer: According to [PEP 236](http://www.python.org/dev/peps/pep-0236/) where this module was proposed, the double underscores make it a reserved name. [5] This ensures that a future_statement run under a release prior to the first one in which a given feature is known (but >= 2.1) will raise a compile-time error rather than silently do a wrong thing. If transported to a release prior to 2.1, a runtime error will be raised because of the failure to import __future__ (no such module existed in the standard distribution before the 2.1 release, and the double underscores make it a reserved name).
Make clear button backspace by one in python tkinter calculator Question: I am making a calculator in python using tkinter. The calculator works very well apart from one thing. At the moment I have set the calculator to clear the display. I want to make it so that it clears the last number on the display. For example 564 would become 56. Any help greatly appreciated. #Import tkinter from Tkinter import * #Setup quit button def quit(): window.destroy() #What happens when you click the button def buttonclick(event): global calcvalue global savedvalue global operator pressed = "" if event.x >10 and event.x <70 and event.y > 50 and event.y < 110 : pressed = 7 if event.x >10 and event.x <70 and event.y > 120 and event.y < 180 : pressed = 4 if event.x >10 and event.x <70 and event.y > 190 and event.y < 250 : pressed = 1 if event.x >10 and event.x <70 and event.y > 260 and event.y < 320 : pressed = 0 if event.x >80 and event.x <140 and event.y > 50 and event.y < 110 : pressed = 8 if event.x >80 and event.x <140 and event.y > 120 and event.y < 180 : pressed = 5 if event.x >80 and event.x <140 and event.y > 190 and event.y < 250 : pressed = 2 if event.x >150 and event.x <210 and event.y > 50 and event.y < 110 : pressed = 9 if event.x >150 and event.x <210 and event.y > 120 and event.y < 180 : pressed = 6 if event.x >150 and event.x <210 and event.y > 190 and event.y < 250 : pressed = 3 if event.x >80 and event.x <140 and event.y > 260 and event.y < 320 : pressed = "equals" if event.x >150 and event.x <210 and event.y > 260 and event.y < 320 : pressed = "clear" if event.x >220 and event.x <280 and event.y > 50 and event.y < 110 : pressed = "divide" if event.x >220 and event.x <280 and event.y > 120 and event.y < 180 : pressed = "times" if event.x >220 and event.x <280 and event.y > 190 and event.y < 250 : pressed = "minus" if event.x >220 and event.x <280 and event.y > 260 and event.y < 320 : pressed = "plus" if pressed == 0 or pressed == 1 or pressed == 2 or pressed == 3 or pressed == 4 or pressed == 5 or pressed == 6 or pressed == 7 or pressed == 8 or pressed == 9 : calcvalue = calcvalue * 10 + pressed if pressed == "divide" or pressed == "times" or pressed == "minus" or pressed == "plus" : operator = pressed savedvalue = calcvalue calcvalue = 0 if pressed == "equals": if operator == "divide": calcvalue = savedvalue /calcvalue if operator == "times": calcvalue = savedvalue * calcvalue if operator == "minus": calcvalue = savedvalue - calcvalue if operator == "plus": calcvalue = savedvalue + calcvalue if pressed == "clear": calcvalue = 0 displayupdate() canvas.update() #Setup the display def displayupdate(): canvas.create_rectangle(10, 10, 370, 40, fill="white", outline="black") canvas.create_text(350, 25, text=calcvalue,font="Times 20 bold",anchor=E) #Setup the canvas/window def main(): global window global tkinter global canvas window = Tk() window.title("BIG Calculator") Button(window, text="Quit", width=5, command=quit).pack() canvas = Canvas(window, width= 380, height=330, bg = 'black') canvas.bind("<Button-1>", buttonclick) #Add the 1 2 3 4 5 6 7 8 9 0 buttons canvas.create_rectangle(10, 50, 100, 110, fill="white", outline="black") canvas.create_text(45, 80, text="7",font="Times 30 bold") canvas.create_rectangle(10, 120, 100, 180, fill="white", outline="black") canvas.create_text(45, 150, text="4",font="Times 30 bold") canvas.create_rectangle(10, 190, 100, 250, fill="white", outline="black") canvas.create_text(45, 220, text="1",font="Times 30 bold") canvas.create_rectangle(10, 260, 100, 320, fill="white", outline="black") canvas.create_text(45, 290, text="0",font="Times 30 bold") canvas.create_rectangle(80, 50, 170, 110, fill="white", outline="black") canvas.create_text(115, 80, text="8",font="Times 30 bold") canvas.create_rectangle(80, 120, 170, 180, fill="white", outline="black") canvas.create_text(115, 150, text="5",font="Times 30 bold") canvas.create_rectangle(80, 190, 170, 250, fill="white", outline="black") canvas.create_text(115, 220, text="2",font="Times 30 bold") canvas.create_rectangle(150, 50, 240, 110, fill="white", outline="black") canvas.create_text(185, 80, text="9",font="Times 30 bold") canvas.create_rectangle(150, 120, 240, 180, fill="white", outline="black") canvas.create_text(185, 150, text="6",font="Times 30 bold") canvas.create_rectangle(150, 190, 240, 250, fill="white", outline="black") canvas.create_text(185, 220, text="3",font="Times 30 bold") #SHow the = c + - x / buttons canvas.create_rectangle(80, 260, 170, 320, fill="white", outline="black") canvas.create_text(115, 290, text="=",font="Times 30 bold") canvas.create_rectangle(150, 260, 240, 320, fill="white", outline="black") canvas.create_text(185, 290, text="C",font="Times 30 bold") canvas.create_rectangle(220, 50, 370, 110, fill="white", outline="black") canvas.create_text(295, 80, text="Divide",font="Times 30 bold") canvas.create_rectangle(220, 120, 370, 180, fill="white", outline="black") canvas.create_text(295, 150, text="Times",font="Times 30 bold") canvas.create_rectangle(220, 190, 370, 250, fill="white", outline="black") canvas.create_text(295, 220, text="Minus",font="Times 30 bold") canvas.create_rectangle(220, 260, 370, 320, fill="white", outline="black") canvas.create_text(295, 290, text="Plus",font="Times 30 bold") #Make the whole calculator work canvas.create_rectangle(10, 10, 280, 40, fill="white", outline="black") global calcvalue calcvalue = 0 displayupdate() canvas.pack() window.mainloop() main() Answer: Briefly: you get ValueError because you try to do `int("clear")` in if pressed == "clear": calcvalue = calcvalue - int(pressed) / 10 You can do this: if pressed == "clear": calcvalue = int(calcvalue/10.0) Because you work only with integers and you use Python 2.x you can do even this: if pressed == "clear": calcvalue = calcvalue/10 In Python 2.x: * `integer/integer` gives always `integer` * `float/integer` and `integer/float` gives `float` In Python 3.x: * `integer/integer` gives always `float` * `integer//integer` gives always `integer` * * * By the way: You can this: if event.x >10 and event.x <70 ... replace with this: if 10< event.x <70 ... And this: if pressed == 0 or pressed == 1 or pressed == 2 or pressed == 3 or pressed == 4 or pressed == 5 or pressed == 6 or pressed == 7 or pressed == 8 or pressed == 9 : if pressed == "divide" or pressed == "times" or pressed == "minus" or pressed == "plus" : with this: if pressed in (0, 1, 2, 3, 4, 5, 6, 7, 8, 9): if pressed in ("divide", "times", "minus", "plus"): It is more readable.
combine two charts into the single PDF using ReportLab? Question: I'm using Django and Reportlabs to generate reports in PDF. I'm referring to [this tutorial](https://code.djangoproject.com/wiki/Charts). I read [this thread](http://stackoverflow.com/questions/9339572/how-to- combine-two-charts-into-the-single-pdf-using-reportlab) as well as [this thread](http://stackoverflow.com/questions/9696211/python-how-to-make- reportlab-move-to-next-page-in-pdf-output) also which says use `canv.showpage()` and then I'll be able to combine 2 charts in 1 pdf, but still I get only that chart which comes second in the code, in my case only line graph. How can I save 2 charts in 1 pdf? Here is my code. import barchart import linechart from django.http import HttpResponse from reportlab.graphics.shapes import Drawing from reportlab.graphics.charts.barcharts import VerticalBarChart from reportlab.graphics import renderPDF from reportlab.pdfgen import canvas def generate_report(request): #instantiate a drawing object canv = canvas.Canvas('output.pdf')#,pagesize=LETTER) canv.setPageCompression(0) d = barchart.MyBarChartDrawing() #extract the request params of interest. #I suggest having a default for everything. if 'height' in request: d.height = int(request['height']) if 'width' in request: d.width = int(request['width']) if 'numbers' in request: strNumbers = request['numbers'] numbers = map(int, strNumbers.split(',')) d.chart.data = [numbers] #bar charts take a list-of-lists for data if 'title' in request: d.title.text = request['title'] #get a GIF (or PNG, JPG, or whatever) binaryStuff = d.asString('pdf') #binaryStuff.save() #return HttpResponse(binaryStuff, 'image/pdf') #instantiate a drawing object canv.showPage() a = linechart.MyLineChartDrawing() #extract the request params of interest. #I suggest having a default for everything. a.height = 300 a.chart.height = 300 a.width = 300 a.chart.width = 300 a.title._text = request.session.get('Some custom title') a.XLabel._text = request.session.get('X Axis Labell') a.YLabel._text = request.session.get('Y Axis Label') a.chart.data = [((1,1), (2,2), (2.5,1), (3,3), (4,5)),((1,2), (2,3), (2.5,2), (3.5,5), (4,6))] labels = ["Label One","Label Two"] if labels: # set colors in the legend a.Legend.colorNamePairs = [] for cnt,label in enumerate(labels): a.Legend.colorNamePairs.append((a.chart.lines[cnt].strokeColor,label)) #get a GIF (or PNG, JPG, or whatever) binaryStuff1 = a.asString('pdf') canv.showPage() return HttpResponse(binaryStuff, 'pdf') The barchart and linechart code is same from [this site](https://code.djangoproject.com/wiki/Charts). How would I save in one pdf file only? Answer: Based on the code provided, you are getting only the Line Chart because you are only passing BinaryStuff to the response (look at the last 3 lines of your code). Try creating the graphs as images, drawing the images to the canvas, then returning the canvas as a PDF.
Intellij python no recoginiize lib Question: I use intellij with python plugin. when I want to import python libs like import random I got editor error. No module named random less... (Ctrl+F1) This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items. when I run the code every thing is ok what can I do to make the intelij recognize this libs? Answer: You may have fixed this by now, but I was having the same problem and finally solved it, so I figured I'd post the solution for anyone who came here by Googling/Binging the error message: I went to File > Project Structure > Modules, highlighted the main module, then pressed the plus sign and then "Python" under "Framework". Hope that helps you or someone else.
Interpret java strings containing integer literals (dec, hex & oct notation) as integer values Question: I'd like to convert string representations of integers to actual integer values. I do not know which radix/base is being used beforehand, so I cannot simply rely on methods/constructors that take the radix as an argument (like shown [here](http://stackoverflow.com/a/5886656/878469)). The strings may represent unsigned 64bit integers and other large numbers, so using `java.lang.Integer` is not an option. Is there a better way of doing what I'm attempting to do with code below? Are there constructors/methods available right there in java that would allow interpretation of a string as an integer literal on their own? I know Python offers to do this when the specified radix is `0` ([int()](http://docs.python.org/2/library/functions.html#int)). import java.math.BigInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LexicalIntegerCoverter { private static final Pattern pattern = Pattern.compile("(\\+|-)?(0(x)?)?([0-9a-fA-F]+)"); private Parts getParts(String lex) { // pun was not intended Matcher matcher = pattern.matcher(lex); boolean lookingAt = matcher.lookingAt(); if (lookingAt) { String sign = matcher.group(1); int radix; String prefix = matcher.group(2); if ("0".equals(prefix)) { radix = 8; } else if ("0x".equals(prefix)) { radix = 16; } else { radix = 10; } String numbers = matcher.group(4); return new Parts(sign, radix, numbers); } throw new NumberFormatException("Unknown lexical representation"); } public BigInteger getLexToInt(String lex) { Parts parts = getParts(lex.trim()); return new BigInteger(parts.getNumber(), parts.getRadix()); } public static void main(String[] args) { String hexLex = "0xf"; String hexLexPlus = "+0xf"; String hexLexMinus = "-0xf"; String octLex = "017"; String octLexPlus = "+017"; String octLexMinus = "-017"; String decLex = "15"; String decLexPlus = "+15"; String decLexMinus = "-15"; LexicalIntegerCoverter converter = new LexicalIntegerCoverter(); System.out.println(hexLex + " = " + converter.getLexToInt(hexLex)); System.out.println(hexLexPlus + " = " + converter.getLexToInt(hexLexPlus)); System.out.println(hexLexMinus + " = " + converter.getLexToInt(hexLexMinus)); System.out.println(octLex + " = " + converter.getLexToInt(octLex)); System.out.println(octLexPlus + " = " + converter.getLexToInt(octLexPlus)); System.out.println(octLexMinus + " = " + converter.getLexToInt(octLexMinus)); System.out.println(decLex + " = " + converter.getLexToInt(decLex)); System.out.println(decLexPlus + " = " + converter.getLexToInt(decLexPlus)); System.out.println(decLexMinus + " = " + converter.getLexToInt(decLexMinus)); } private static class Parts { private final String sign; private final int radix; private final String digits; public Parts(String sign, int radix, String digits) { this.sign = sign; this.radix = radix; this.digits = digits; } public String getSign() { return sign; } public int getRadix() { return radix; } public String getDigits() { return digits; } public String getNumber() { return (sign == null ? "" : sign) + digits; } @Override public String toString() { return getNumber() + "[" + radix + "]"; } } } P.S.: there's a lot of similar questions about this, where answers point to `Integer.parseInt(String, int)` or `BigInteger(String, int)`, but that's not the answer I'm looking for. I'd also prefer doing this without relying on third party libraries. I'm also aware of the fact that java allows integer literals to be defined in code, which is also not the answer I'm looking for (I actually need to convert strings that contain integer literals) - I would like to do what a java compiler does when it encounters such values. **Edit01** I said above that I'd prefer not using a third party library, but that doesn't mean it's not an option. Answer: BigInteger bi = new BigInteger(s, 16); This will parse string as a hexadecimal number, yuo just need to remove **0x** (or other) prefixes. Also take a look on DecimalFormat class of standart javaSE api <http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html>
fexpect breaks fabric scripts Question: I hot upon an requirement where I needed to automatically answer the prompt on remote machine and then I found fexpect after reading different stackoverflow questions. But the moment I include fexpect in my script it breaks the whole script! Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/fabric/main.py", line 743, in main *args, **kwargs File "/usr/local/lib/python2.7/dist-packages/fabric/tasks.py", line 368, in execute multiprocessing File "/usr/local/lib/python2.7/dist-packages/fabric/tasks.py", line 264, in _execute return task.run(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/fabric/tasks.py", line 171, in run return self.wrapped(*args, **kwargs) File "/etc/puppet/fabfile.py", line 165, in edit_sudoers run('echo "Current Permission of the file /etc/sudoers - "`stat -c "%a %n" /etc/sudoers`') File "/usr/local/lib/python2.7/dist-packages/ilogue/fexpect/api.py", line 15, in run wrappedCmd = wrapExpectations(cmd) File "/usr/local/lib/python2.7/dist-packages/ilogue/fexpect/internals.py", line 15, in wrapExpectations script = createScript(cmd) File "/usr/local/lib/python2.7/dist-packages/ilogue/fexpect/internals.py", line 39, in createScript for e in fabric.state.env.expectations: File "/usr/local/lib/python2.7/dist-packages/fabric/utils.py", line 184, in __getattr__ raise AttributeError(key) AttributeError: expectations The moment i write `from ilogue.fexpect import expect, expecting, run` fabric stops working with the above error message. I asked in fabric irc as well but I got to know that this might be because of some version related issues. Has anyone else encountered this error before? fexpect==0.2.post7 Fabric==1.8.0 Answer: Just import fexpect's `run` as `erun` and its `sudo` as `esudo`. When you use the fexpect `run` or `sudo` functions, you _must_ wrap those calls in a `with expecting(prompts):` context. This is a [known issue](https://github.com/ilogue/fexpect/issues/8) in fexpect, although there is a pull request, so it might be fixed by the time posterity reads this. One solution is to import fexpect's `run` function with a different name, e.g. `erun`, and use it only when you need the automatic prompt handling functionality: from fabric.api import run from ilogue.fexpect import expect, expecting, run as erun run(a_cmd) # Native Fabric run - should work fine prompts = [...] with expecting(prompts): erun(a_prompting_cmd) # fexpect run - should with fine inside expecting context Another thing that isn't explicitly stated in the fexpect documentation is that the `pexpect` package needs to be installed on the target system. Yet another fexpect gotcha is that the prompt strings are _regular expressions_ \-- the fexpect sample code is misleading about this.
python support vector machines Question: My question is related to this one - [How do I install libsvm for python under windows 7?](http://stackoverflow.com/questions/12877167/how-do-i-install-libsvm-for- python-under-windows-7) I'm basically trying to get the svm library to work in python. So, I downloaded and unzipped the libsvm-3.17 folder and went into the python directory (in command prompt) and typed python. Now, when trying: import svm I got an error saying that libsvm was not found. Based on the question linked here, I located the libsvm.dll and copied it to C:\Windows\System32. But now when I try the same thing I get another error - WindowsError: [Error 193] %1 is not a valid Win32 application. Can some one help me with this? Answer: You have a 64-bit vs. 32-bit mismatch. Perhaps you have a 64-bit OS but built the library with a 32-bit compiler. You'll need to rebuild the library with a matched compiler, or change your OS.
Python search path wrong, but only in Windows Question: I am creating a larger logical package spread out over many directories, like so: [projects root]/projectname1/lib/python/logicalpackage/__init__.py [projects root]/projectname1/lib/python/logicalpackage/projectname1/__init__.py [projects root]/projectname2/lib/python/logicalpackage/__init__.py [projects root]/projectname2/lib/python/logicalpackage/projectname2/__init__.py The idea is to be able to do this: import logicalpackage.projectname1 as p1 import logicalpackage.projectname2 as p2 after having a script in .bashrc or $profile (bash and PowerShell, respectively) that will glob over `[projects root]/*/lib/python/` and import the packages it finds. I know that [pkgutil](http://docs.python.org/2/library/pkgutil.html) is used for this, by sticking that snippet in `__init__.py` (`from pkgutil import extend_path; __path__ = extend_path(__path__, __name__`), and I can get everything to work fine across all systems when I do so. My question, though, is why when I _don't_ use pkgutil, this still works fine, but only on some platforms--particularly, in OSX and Ubuntu (10 and 12 that I've seen), it works, but in Windows (7) it doesn't. What I worry is that there is some side- effect of using pkgutil that I'm not considering. The specific non-working behavior is that PYTHONPATH appears to be constructed correctly after that script is run (in the `.bashrc` equivalent in PowerShell), i.e. I can debug print PYTHONPATH from within Python and it is identical to the path constructed on another platform. However, `from projectname1 import foo` succeeds, and `from projectname2 import bar` fails (presumably because projectname2 is globbed later by alpha). That's actually the behavior I would expect without pkgutil. Why isn't that the behavior in OSX and Ubuntu? Is this problem from some pathing mechanism of Windows or PowerShell, or the Python binaries as compiled on Windows, or something else entirely? EDIT: Adding the below for more clarity: # d:\projects> [Environment]::SetEnvironmentVariable("PYTHONPATH","d:\\projects\\projectname1\\lib\python;d:\\projects\\projectname2\\lib\\python;") # d:\projects> echo $env:PYTHONPATH # d:\\projects\\projectname1\\lib\python;e:\\projects\\projectname2\\lib\\python; # d:\projects> python import sys sys.path # => ['', '..python install dir..\\lib\\site-packages\\pip-1.2.1-py2.7.egg', 'd:\\projects\\projectname1\\lib\\python', 'd:\\projects\\projectname2\\lib\\python', ...usual stuff...] import logicalpackage logicalpackage.__path__ # => ['d:\\projects\\projectname1\\lib\\python\\logicalpackage'] import logicalpackage.projectname1 as p1 import logicalpackage.projectname2 as p2 # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # ImportError: No module named projectname2 # exit() replace the empty `__init__.py` with the pkgutils code mentioned above # d:\projects> python import sys sys.path # => ['', 'D:\\usr\\Python27_32bit\\lib\\site-packages\\pip-1.2.1-py2.7.egg', 'd:\\projects\\projectname1\\lib\\python', 'd:\\projects\\projectname2\\lib\\python', 'd:\\projects', '...etc...'] import logicalpackage logicalpackage.__path__ # => ['d:\\projects\\projectname1\\lib\\python\\logicalpackage', 'd:\\projects\\projectname2\\lib\\python\\logicalpackage'] import logicalpackage.projectname1 as p1 import logicalpackage.projectname2 as p2 Note: No exception. Having the exception go away after appending to the module path via pkgutil is the expected behavior (to me, and to [the documentation](http://docs.python.org/2/tutorial/modules.html))--Python shouldn't append to the module path unless I explicitly declare it. What I am wondering is why no exception occurs on Ubuntu (in other words, why it appends to the module path **without** being explicitly declared), whether or not I include the pkgutils snippet. Answer: So, here's what ended up being the issue. It turns out that `pkgutils.extend_path` will work for EVERY module within an extended logical package, as long as it is contained within the FIRST instance of that logical package in `PYTHONPATH`. In both environments, `PYTHONPATH` was being prepended with an `environment` module contained within `logicalpackage`, which included `extend_path`. In the Windows environment, that prepended path didn't actually contain anything. My failure was basically in not recognizing that `extend_path` will extend all over logical packages in `PYTHONPATH` even if particular modules within that logical package don't contain `extend_path`, as long as the first instance contains the `pkgutils` snippet.
How to use Bulk API to store the keywords in ES by using Python Question: I have to store some message in ElasticSearch integrate with my python program. Now what I try to store the message is: d={"message":"this is message"} for index_nr in range(1,5): ElasticSearchAPI.addToIndex(index_nr, d) print d That means if I have 10 message then I have to repeat my code 10 times. So what I want to do is try to make a script file or batch file. I check ElasticSearch Guide, BULK API is possible to use. <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs- bulk.html> The format should be something like below: { "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } } { "field1" : "value1" } { "delete" : { "_index" : "test", "_type" : "type1", "_id" : "2" } } { "create" : { "_index" : "test", "_type" : "type1", "_id" : "3" } } { "field1" : "value3" } { "update" : {"_id" : "1", "_type" : "type1", "_index" : "index1"} } { "doc" : {"field2" : "value2"} } what I did is: {"index":{"_index":"test1","_type":"message","_id":"1"}} {"message":"it is red"} {"index":{"_index":"test2","_type":"message","_id":"2"}} {"message":"it is green"} I also use curl tool to store the doc. $ curl -s -XPOST localhost:9200/_bulk --data-binary @message.json Now I want to use **my Python code** to store the file to the Elastic Search. Answer: from datetime import datetime from elasticsearch import Elasticsearch from elasticsearch import helpers es = Elasticsearch() actions = [] for j in range(0, 10): action = { "_index": "tickets-index", "_type": "tickets", "_id": j, "_source": { "any":"data" + str(j), "timestamp": datetime.now() } } actions.append(action) if len(actions) > 0: helpers.bulk(es, actions)
Why is the URL 404 not found with Django? Question: I have written a Django script that runs a Python parser to web s*e. I am sending the request to the Django script via AJAX. However, when the Ajax runs, it comes back as 404 not found for the URL. Why is this happening? My code is below: Ajax (with jQuery): //send a `post` request up to AWS, and then //insert the data into the paths $.post('/ca', function(data){ //evaluate the JSON data = eval ("(" + data + ")"); //insert the vars into the DOM var contentOne; contentOne = data.bridge_time; contentOne += 'min delay'; $('#timeone').html(contentOne); var contentTwo; contentTwo = data.tunnel_time; contentTwo += 'min delay'; $('#timetwo').html(contentTwo); //if this falls through, push an error. var tunnel_time = data.tunnel_time; var bridge_time = data.bridge_time; var tunnel = document.getElementById('tunnel'); var bridge = document.getElementById('bridge'); var tunnelText = document.getElementById('timeone'); var bridgeText = document.getElementById('timetwo'); //algo for the changing icons. Kudos to Vito if(tunnel_time<bridge_time){ tunnel.src="tunnel3.png"; bridge.src="bridge2r.png"; }else if( bridge_time<tunnel_time){ bridge.src="bridge21.png"; tunnel.src="tunnel2r.png"; }else{ bridge.src="bridge2n.png"; tunnel.src="tunnel2g.png"; } $.fail(function() { alert("We're sorry. We are having an error. Check back later."); }); }); My urls.py: from django.conf.urls.defaults import * from views import views urlpatterns = patterns('', (r'^/us', views.american_time), (r'^/ca', views.canadian_time), ) My `urls.py` and my `views.py` are in the same folder, if that makes any difference. They are just titled **views.py** and **urls.py**. Thank you! Answer: Try from django.conf.urls.defaults import * from views import views urlpatterns = patterns('', (r'^/us/$', views.american_time), (r'^/ca/$', views.canadian_time), ) Also you have to add the trailing slash in your JavaScript.
How to import/sync data to App Engine datastore without excessive datastore reads or timeouts Question: I am writing an application that uses a remote API that serves up a fairly static data (but still can update several times a day). The problem is that the API is quite slow, and I'd much rather import that data into my own datastore anyway, so that I can actually query the data on my end as well. The problem is that the results contain ~700 records that need to be sync'd every 5 hours or so. This involves adding new records, updating old records and deleting stale ones. I have a simple solution that works -- but it's slow as molasses, and uses 30,000 datastore read operations before it times out (after about 500 records). The worst part about this is that the 700 records are for a single client, and I was doing it as a test. In reality, I would want to do the same thing for hundreds or thousands of clients with a similar number of records... you can see how that is not going to scale. Here is my entity class definition: class Group(ndb.Model): groupid = ndb.StringProperty(required=True) name = ndb.StringProperty(required=True) date_created = ndb.DateTimeProperty(required=True, auto_now_add=True) last_updated = ndb.DateTimeProperty(required=True, auto_now=True) Here is my sync code (Python): currentTime = datetime.now() groups = get_list_of_groups_from_api(clientid) #[{'groupname':'Group Name','id':'12341235'}, ...] for group in groups: groupid = group["id"] groupObj = Group.get_or_insert(groupid, groupid=group["id"], name=group["name"]) groupObj.put() staleGroups = Group.query(Group.last_updated < currentTime) for staleGroup in staleGroups: staleGroup.delete() Answer: I can't tell you why you are getting 30,000 read operations. You should start by running appstats and profiling this code, to see where the datastore operations are being performed. That being said I can see some real inefficiencies in your code. For instance your delete stale groups code is horribly inefficient. You should be doing a keys_only query, and then doing batch deletes. What you are doing is really slow with lots of latency for each delete() in the loop. Also get_or_insert uses a transaction (also if the group didn't exist a put is already done, and then you do a second put()) , and if you don't need transactions you will find things will run faster. The fact that you are not storing any additional data means you could just blind write the groups (So initial get/read), unless you want to preserve `date_created`. Other ways of making this faster would be by doing batch gets/puts on the list of keys. Then for all the entities that didn't exist, do a batch put() Again this would be much faster than iterating over each key. In addition you should use a TaskQueue to run this set of code, you then have a 10 min processing window. After that further scaling can be achieved by splitting the process into two tasks. The first creates/updates the group entities. Once that completes you start the task that deletes stale groups - passing the datetime as an argument to the next task. If you have even more entities than can be processed in this simple model then start looking at MapReduce. But for starters just concentrate on making the job you are currently running more efficient.
Python -- Matplotlib redrawing lines without previous lines remaining Question: This class plots a curve in Matplotlib. The user mouse input section changes the `set_data()` for several `x,y` coordinates. The `P` and `Q` are resetting properly, it seems. However, when the `R` is not set with calculations using those same methods (`set_data()` or `set_x()` or `set_y()`), then this results in the error: `TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int'` When the `R` calculations are left in this results in the error: `AttributeError: 'list' object has no attribute 'set_xdata'` The whole class (it's a little big but the methods are interdependent and I don't want to leave out something that could be relevant here): from mpl_toolkits.axes_grid.axislines import SubplotZero import numpy as np import matplotlib.pyplot as plt from math import sqrt class ECC(object): def __init__(self,a,b,px,qx,qy): """ initialize input variables """ self.a = a self.b = b self.pxlam = px self.qxlam = qx self.invertQy = qy self.fig = plt.figure(1) self.ax = SubplotZero(self.fig, 111) self.xr = 0 self.yr = 0 def onclick(self, event): x = event.xdata if event.button == 1: self.pxlam = x if event.button == 3: self.qxlam = x pylam = self.ecclambda(self.pxlam,self.a,self.b) # calculate P from pxlam qylam = self.ecclambda(self.qxlam,self.a,self.b) # calculate Q from qxlam if self.invertQy == 1: qylam = -qylam # optional, inverts qy to negative on the plot plt.plot([self.pxlam,self.qxlam], [pylam,qylam], color = "c", linewidth=1) self.p = plt.plot([self.pxlam], [pylam], "mo")[0] self.q = plt.plot([self.qxlam], [qylam], "mo")[0] self.pt = plt.text(self.pxlam-0.25,pylam+0.5, '$P$') self.qt = plt.text(self.qxlam-0.25,self.qxlam+0.5, '$Q$') self.xr,self.yr = self.dataToPlotR(pylam,qylam) plt.plot([self.xr],[self.yr],"mo") plt.plot([self.xr],[-1*(self.yr)],"co") self.rxdata = [self.qxlam,self.xr]; self.rydata = [qylam,self.yr] self.r, = plt.plot(self.rxdata, self.rydata, color = "c", linewidth=1) #plt.plot([xr,xr], [yr,-yr], "x--") self.plotR(qylam) plt.text(self.xr+0.25,self.yr, '$-R$'); plt.text(self.xr+0.25,-1*(self.yr), '$R$') plt.text(-9,6,' P: (%s ,%s) \n Q: (%s ,%s) \n R: (%s ,%s) \n a: %s \n b: %s ' %(self.pxlam,pylam,self.qxlam,qylam,self.xr,-1*(self.yr),self.a,self.b), fontsize=10, color = 'blue',bbox=dict(facecolor='tan', alpha=0.5)) self.update() def update(self): pylam = self.ecclambda(self.pxlam,self.a,self.b) # calculate P from pxlam qylam = self.ecclambda(self.qxlam,self.a,self.b) # calculate Q from qxlam self.p.set_data([self.pxlam], [pylam]) self.q.set_data([self.qxlam], [qylam]) self.pt.set_x(self.pxlam-0.25) self.pt.set_y(pylam+0.5) self.qt.set_x(self.qxlam-0.25) self.qt.set_y(qylam+0.5) self.xr,self.yr = self.dataToPlotR(pylam,qylam) #self.rxdata.set_xdata([self.qxlam,self.xr]) # R calculations #self.rydata.set_ydata([qylam,self.yr]) # R calculations plt.gcf().canvas.draw() #self.plotR(self.xr,self.yr,qylam) The lines of code that I'm referring to above, as to whether the `R` methods are kept in or left out, are 2 commented out in the method `update()` and are commented afterward with `# R calculation`. I'm teaching myself Matplotlib right now, so I'm sure a junior programmer can see my obvious error in a very short time, but I've been at it for some time and getting nowhere fast. The main thing I want to do here is just get the lines and points to be redrawn after every click without any of the previously set points to remain on the graph. Similarly with the textbox on the upper left of the graph, the values should be reset there after every click and not rewrite themselves over each previous string of text. EDIT: I have tried `cla()` and `clf()` and they don't appear to work in this case. In fact, they may not even be necessary at any point in this program as `set_data()` methods I used should be enough to redraw based on the new data from every click. To prove that, just uncomment the entire `plotGraph()` method in my class and comment out the same code in `update()` and you'll see that the points `P` and `Q` will be set new after ever click. The real problem is the `R` point, the lines, and the text box on the upper left. Answer: Well, at first `self.rxdata` and `self.rydata` are lists, which have no `set_xdata` method, hence the error. Maybe you wanted to do something like `self.my_plot.set_xdata(...)`? Anyway, there's a ~~much clever~~ _other_ way to do this: `matplotlib` is object-oriented, meaning that it handles graph stuffs as objects; and as you can add things, you can [also remove some of them by calling their methods](http://stackoverflow.com/questions/5600370/python-matplotlib-add-and- remove-text-to-figure-using-button-events), but for this you need their reference. So, in your case, you just have to keep the references to the objects you dant to add/remove: * In `__init_()` definition, simply add a reference tracker: def __init__(...): (...) self.text = None * And use this reference in `onClick()` definition: if self.text is not None: # if text has already been drawn before, self.text.remove() # simply remove it self.text = plt.text(-9, 6, # and re-create it, keeping the reference ' P: (%s ,%s) \n Q: (%s ,%s) \n R: (%s ,%s) \n a: %s \n b: %s ' (...)) With this only addition, and keeping the two lines returning error commented, the text box is refreshed at every click on the graph. I think you get the point, and are able to reproduce this to every object you want to remove and recreate; there is no interest in re-drawing the ellipsis plot. * * * ## Edit after comment Ok, `remove` exits for all objects, but in fact, `plt.plot` return a list with one element. So, a solution is simply to create a list of all objects that will be refreshed, and to call this `remove` method for everyone of them: * in `__init__()`: def __init__(...): (...) self._tracker = [] * in `plotR()`, we have to return the references: def plotR(self,qylam): r1, = plt.plot([self.qxlam, self.xr], [qylam, self.yr], color = "c", linewidth=1) r2, = plt.plot([self.xr, self.xr], [self.yr, -1*(self.yr)], "x--") return r1, r2 * in `onClick()`, I propose the following code: def onclick(self, event): # removing elements that will be regenerated for element in self._tracker: #print "trying to remove", element element.remove() # reinitializing the tracker self._tracker = [] (...) _e1 = plt.plot([self.pxlam,self.qxlam], [pylam,qylam], color = "c", linewidth=1)[0] (...) _e2 = plt.plot([self.xr],[self.yr],"mo")[0] _e3 = plt.plot([self.xr],[-1*(self.yr)],"co")[0] (...) _e4, _e5 = self.plotR(qylam) _e6 = plt.text(self.xr+0.25,self.yr, '$-R$'); plt.text(self.xr+0.25,-1*(self.yr), '$R$') _e7 = plt.text(-9,6,' P: (%s ,%s) \n Q: (%s ,%s) \n R: (%s ,%s) \n a: %s \n b: %s ' %(self.pxlam,pylam,self.qxlam,qylam,self.xr,-1*(self.yr),self.a,self.b), fontsize=10, color = 'blue',bbox=dict(facecolor='tan', alpha=0.5)) (...) # adding in the tracker self._tracker.extend([self.p, self.q, self.pt, self.qt, self.r, _e1, _e2, _e3, _e4, _e5, _e6, _e7]) self.update() Does this solve the problem? Note: another solution could be to change parameters (position, data) of the objects, {edit} as shown by tcaswell's comment below and implemented in my other answer to the question.
How to implement session.add on this code: Question: So, I need some help to make this script run faster, below is my script. #!/usr/bin/env python import glob,os, csv from sqlalchemy import * count = 0 served_imsi = [] served_imei = [] served_msisdn = [] sgsn_address = [] ggsn_address = [] charging_id = [] apn_network = [] location_area_code = [] routing_area = [] cell_identity = [] service_area_code = [] s_charging_characteristics = [] plmn_id = [] path = '/home/cneps/cdr/*.cdr' for file in glob.glob(path): f = open(file) for lines in f: served_imsi.append(lines[17:17+16]) served_imei.append(lines[47:47+16]) served_msisdn.append(lines[65:65+18]) sgsn_address.append(lines[83:83+32]) ggsn_address.append(lines[115:115+32]) charging_id.append(lines[147:147+10]) apn_network.append(lines[157:157+63]) location_area_code.append(lines[296:296+4]) routing_area.append(lines[300:300+2]) cell_identity.append(lines[302:302+4]) service_area_code.append(lines[306:306+4]) s_charging_characteristics.append(lines[325:325+2]) plmn_id.append(lines[327:327+6]) db = create_engine('sqlite:///CDR.db',echo=False) metadata = MetaData(db) CDRS = Table('CDRS', metadata, autoload=True) i = CDRS.insert() while count < len(served_imei): i.execute(Served_IMSI=served_imsi[count], Served_IMEI=served_imei[count], Served_MSISDN=served_msisdn[count], SGSN_Address=sgsn_address[count], GGSN_Address=ggsn_address[count], Charging_ID=charging_id[count], APN_Network=apn_network[count], LAC=location_area_code[count], RAC=routing_area[count], Cell_Identity=cell_identity[count], Service_Area_Code=service_area_code[count], S_Charging_Characteristics=s_charging_characteristics[count], PLMN_ID=plmn_id[count]) count += 1 for files in glob.glob(path): os.remove(files) The code is fine. But it takes too long, I asked a friend, and he suggested using session.add to make things faster. The solution I came with was something like this: for item in lists: session.add(item) but that would work only for one list, and I have 14 lists. Does anyone have an idea of how to implement session.add to my code, instead of execute? Thank you! Answer: There are two (primary) ways you can use SQLAlchemy. The way that you are currently doing it is using the [SQLAlchemy Expression Language](http://docs.sqlalchemy.org/en/rel_0_9/core/tutorial.html) API. Using `session.Add` is part of the [Object Relational](http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html) API. They serve two separate purposes, and I would recommend reading some of the documentation to get an idea of the differences. The Object Relational API (more generally referred to as [ORM](http://en.wikipedia.org/wiki/Object-relational_mapping), or "Object Relational Mapper") uses the SQLAlchemy Expression Language underneath, so anything you can do in the ORM API you can do in the SQLAlchemy Expression API (although with different syntax). So, I'd recommend that unless you really need to, don't try to switch your code over to the other API quite yet. As an alternative to completely rewriting your code, note that you are doing this: CDRS = Table('CDRS', metadata, autoload=True) i = CDRS.insert() `i` becomes an [insert expression](http://docs.sqlalchemy.org/en/rel_0_9/core/tutorial.html#coretutorial- insert-expressions). You can use it to dynamically create insert statements. You can try this by printing out `i`: it will look like a SQL string with parameters (but note that the value is not actually a string; it is an object that helps automatically create a SQL string). When you pass that insert object over to the `execute` method (along with all of the parameters), the SQL string is generated an executed. Right now, you are using the execute method on the insert statement. The preferred way is to use the execute method on the engine. So, instead of... i.execute(...) ...you should do... db.execute(i, ...) The performance issue is that you are running into involves using `execute` once for each row. Thus, each INSERT is running in its own transaction, which could be slow. You could do something like... all_data = [] while count < len(served_imei): data = { 'Served_IMSI' : served_imsi[count], 'Served_IMEI' : served_imei[count], ... } all_data.append(data) count += 1 Now, `all_data` contains a list of dictionaries, with each dictionary containing the keys (column names) and the values (column values) for the insert statement. Then, you can use... db.execute(i, all_data) I would recommend enabling `echo` while you are working on this to learn what SQLAlchemy is doing under the hood: db = create_engine('sqlite:///CDR.db',echo=True) # Change `echo` from False to True Your next step would be to remove your two loops, and create the dictionary that I just showed directly from the section of the code where are reading from the file. For example: #!/usr/bin/env python import glob,os, csv from sqlalchemy import * db = create_engine('sqlite:///CDR.db',echo=False) metadata = MetaData(db) CDRS = Table('CDRS', metadata, autoload=True) insert_statement = CDRS.insert() all_data = [] path = '/home/cneps/cdr/*.cdr' for file in glob.glob(path): # Use "with" to automatically close "f" when we're done with it. with open(file) as f: for lines in f: d = { 'Served_IMSI' : lines[17:17+16], .... } all_data.append(d) # No need for that "while count < len(served_imei)" loop, we can now just do... db.execute(insert_statement, all_data)
Python Server on different IP address Question: So I have a web server that I can run using python, but I have a question. Can I change the IP address where the server runs the only one I can get to work is 127.0.0.1 which is the localhost address? I have already tried with no luck I want to use a unused one on my network. Here's the code: import sys import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler HandlerClass = SimpleHTTPRequestHandler ServerClass = BaseHTTPServer.HTTPServer Protocol = "HTTP/1.0" if sys.argv[1:]: port = int(sys.argv[1]) else: port = 8000 server_address = ('127.0.0.1', port) HandlerClass.protocol_version = Protocol httpd = ServerClass(server_address, HandlerClass) sa = httpd.socket.getsockname() print "Running server on", sa[0], "port", sa[1], "..." httpd.serve_forever() Answer: You can only use addresses that are bound to a network interface on the computer. You cannot use random addresses picked out of thin air.
Python Help: Creating a dict of {str:list of str} from csv file Question: I have to create a table in the format: `{str: list of str}` Opening a .csv file using the following code, I get: import csv cr = csv.reader(open("name.csv","r")) for row in cr: print(row) output: ['key1', 'key2', 'key3'] ['value1', 'value2', 'value3'] ['value4', 'value5', 'value6'] I essentially need to structure this into the format {'key1': ['value1', 'value4'], 'key2': ['value2', 'value5'], 'key3': ['value3', 'value6']} I'm stuck; I just can't think of a way to do this for it to work for any number of keys and values Answer: Use `zip()` to turn rows into columns, then make those into dictionary keys and values: import csv with open("name.csv", newline='') as infh: cr = csv.reader(infh) columns = {r[0]: list(r[1:]) for r in zip(*cr)} A quick demo of the last line: >>> cr = [ ... ['key1', 'key2', 'key3'], ... ['value1', 'value2', 'value3'], ... ['value4', 'value5', 'value6'], ... ] >>> {r[0]: list(r[1:]) for r in zip(*cr)} {'key3': ['value3', 'value6'], 'key2': ['value2', 'value5'], 'key1': ['value1', 'value4']} where `cr` stands in for the `csv.reader()` object. `zip(*iterable)` takes all elements in an iterable and transforms it like a matrix; columns become rows as each nested value is paired up with values from the other rows at the same position: >>> zip(*[[1, 2, 3], [4, 5, 6]]) [(1, 4), (2, 5), (3, 6)] and the dict comprehension `{key_expression: value_expression for targets in iterable}` produces a dictionary, where in the above code each first element in a column becomes the key, and the rest forms the value.
Struggling to understand Twisted in general and pb in particular Question: Could someone explain the difference between the following please. I am really struggling to grasp Deferred concept, I thought I had it as I have been doing examples all day. But I think i must be code blind. I'm sure its really simple. This works. from twisted.spread import pb from twisted.internet import reactor from twisted.python import util if __name__ == '__main__': def print_result(result): print result def add_numbers(obj, a, b): obj.callRemote("add_numbers", a, b) factory = pb.PBClientFactory() reactor.connectTCP("localhost", 8789, factory) d = factory.getRootObject() d.addCallback(lambda object: object.callRemote("add_numbers", 1, 2)) d.addErrback(lambda reason: 'error: '+str(reason.value)) d.addCallback(print_result) d.addErrback(lambda reason: 'error: '+str(reason.value)) d.addCallback(lambda _: reactor.stop()) d = factory.getRootObject() reactor.run() and this doesnt from twisted.spread import pb from twisted.internet import reactor from twisted.python import util if __name__ == '__main__': def print_result(result): print result def add_numbers(obj, a, b): obj.callRemote("add_numbers", a, b) factory = pb.PBClientFactory() reactor.connectTCP("localhost", 8789, factory) d = factory.getRootObject() d.addCallback(add_numbers, 1, 2) d.addErrback(lambda reason: 'error: '+str(reason.value)) d.addCallback(print_result) d.addErrback(lambda reason: 'error: '+str(reason.value)) d.addCallback(lambda _: reactor.stop()) d = factory.getRootObject() reactor.run() I cant for the life of me work out why, it crashes with this error: Unhandled error in Deferred: Unhandled Error Traceback (most recent call last): Failure: twisted.spread.pb.PBConnectionLost: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionLost'>: Connection to the other side was lost in a non-clean fashion: Connection lost. ] Server side code is from twisted.spread import pb from twisted.internet import reactor class Echoer(pb.Root): def remote_echo(self, st): print 'echoing:', st return st def remote_add_numbers(self, a, b): print 'adding:', a, b c = a + b return c if __name__ == '__main__': reactor.listenTCP(8789, pb.PBServerFactory(Echoer())) reactor.run() Answer: The difference between your working and broken examples is that the `lambda` expression implicitly returns its result. Its result is a `Deferred`, which means that the next callback in the chain will wait to execute until its result is available. If you change the definition of `add_numbers` to return the result of `callRemote`, like so: def add_numbers(obj, a, b): return obj.callRemote("add_numbers", a, b) Then your broken example will start working again.
Factory method of a python class returning implementation based on system and design issues Question: # 1) Introduction I have started the implementation of a tool in Python that gathers several system metrics (e.g. cpu utilisation, cpu saturation, memory errors etc.) and presents them to the end-user. This tool should ideally support as many platforms as possible (Linux, FreeBSD, Windows etc.). I have completed the implementation of this tool for a Linux system for a few metrics I consider important and I have just started to implement the same metrics for a FreeBSD system. This tool must be designed in a way that allows support for more **system metrics** and for more **platforms** in the future. Moreover, a **web-interface** will soon be added and will **receive data** from my tool. # 2) My design decisions so far For the above reasons, I have decided to implement the tool in **Python** (convenient to read data from different sources on many systems and ,well, I am somewhat more familiar with it :)) and I am following a **class structure** for each system metric (inheritance is important as some systems share features so there is no need to rewrite code). Moreover, I have decided that I have a valid use case for using a **factory method**. ## 2.1) Class structure Here is an example class diagram for CPU Metrics (simplified for the sake of the question): CpuMetrics (Abstract Base Class) / | \ / | \ / | \ / | \ / | \ / | \ LinuxCpuMetrics FreeBSDCpuMetrics WindowsCPUMetrics (per OS) / \ / \ / \ / \ / \ / \ / \ ArchLinuxCpuMetrics DebianLinuxCpuMetrics (sometimes important per Distro or Version) ## 2.2) Factory Method In the Abstract Base Class called **CpuMetrics** there are some abstract methods defined that should be implemented by inheriting classes and a **factory method** called get_impl(). I have done some research on when I should use a Factory Method (for example, answers such as [this](http://stackoverflow.com/a/14992545/2568511)) and I believe it is valid to use one in my case. For example, I want a client (e.g. my web interface) to call my tool to get CPU Utilisation metrics like this: cpu_metrics = CpuMetrics.get_impl() # factory method as an alternative constructor cpu_metrics.get_cpu_util() # It is completely transparent for the client which get_cpu_util() is returned. # 3) My concern and my question (finally) Following the above analyzed design, it is very important for my factory method to be informed about which system are we on now ("is this Linux, Windows? Which implementation should I bring now?"). Therefore, I have to **heavily rely** on functions such as `platform.system()` or its alternatives. So what my factory method does is (roughly again): def get_impl(): """Factory method returning the appropriate implementation depending on system.""" try: system = platform.system() # This returns: { Linux, Windows, FreeBSD, ... } system_class = getattr("cpu", system + "CpuMetrics" ) except AttributeError, attr_err: print ("Error: No class named " + system + "CpuMetrics in module cpu. ") raise attr_err return system_class() I feel **very uncomfortable** with this for two reasons: 1) I force a future programmer (or even myself) to follow a naming convention for his class. For example, if someone decides to extend my system, say, for Solaris he **absolutely has to** name his class `SolarisCpuMetrics`. 2) If in a future version of Python the values of `platform.system()` (or an other alternative I will choose to use) are modifiled, then I have to change my naming convention and modify my factory method a lot. So my **question** : is there a workaround for my concern ? Will my code become unreadable or my concern is not valid? If you believe there is one workaround, how much do I need to modify / refactor my code and change my design? I don not have experience in designing projects from scratch, so I could use any advice. Also, I have some more experience in Java. I try to think in a as much pythonic way as possible when writing Python, but sometimes fail to do a proper seperation between the two. Your constructive criticism is very desirable. Answer: Use a class decorator to enumerate classes. And override the [allocator](http://docs.python.org/3/reference/datamodel.html#object.__new__). sysmap = {} class metric: def __init__(self, system): self.system = system def __call__(self, cls): sysmap[self.system] = cls return cls class CpuMetrics: def __new__(self): cls = sysmap.get(platform.system) if not cls: raise RuntimeError('No metric class found!') else: return cls() ... ... @metric('Linux') class SomeLinuxMetrics(CpuMetrics): ... ... metrics = CpuMetrics()
python: square backet in character class Question: I'm trying to match square brackets (using character class) in python. But the following code is not successful. Does anybody know what is the correct way to do? #!/usr/bin/env python import re prog = re.compile('[\[]+') print prog.match('a[f') prog = re.compile('[\]]+') print prog.match('a]f') Answer: The issue isn't the square bracket, it's that `match` (as the docs put it) "[t]r[ies] to apply the pattern at the start of the string". You may want `search` instead: >>> prog = re.compile('[\[]+') >>> print prog.match('a[f') None >>> print prog.search('a[f') <_sre.SRE_Match object at 0xa7a7448> >>> print prog.search('a[f').group() [
Mastermind minimax algorithm Question: I am trying to implement in python Donald Knuth's algorithm for codebreaking mastermind in not more than 5 moves. I have checked my code several times, and it seems to follow the algorithm, as its stated here: <http://en.wikipedia.org/wiki/Mastermind_(board_game)#Five-guess_algorithm> However, I get that some of the secrets take 7 or even 8 moves to accomplish. Here is the code: #returns how many bulls and cows there are def HowManyBc(guess,secret): invalid=max(guess)+1 bulls=0 cows=0 r=0 while r<4: if guess[r]==secret[r]: bulls=bulls+1 secret[r]=invalid guess[r]=invalid r=r+1 r=0 while r<4: p=0 while p<4: if guess[r]==secret[p] and guess[r]!=invalid: cows=cows+1 secret[p]=invalid break p=p+1 r=r+1 return [bulls,cows] # sends every BC to its index in HMList def Adjustment(BC1): if BC1==[0,0]: return 0 elif BC1==[0,1]: return 1 elif BC1==[0,2]: return 2 elif BC1==[0,3]: return 3 elif BC1==[0,4]: return 4 elif BC1==[1,0]: return 5 elif BC1==[1,1]: return 6 elif BC1==[1,2]: return 7 elif BC1==[1,3]: return 8 elif BC1==[2,0]: return 9 elif BC1==[2,1]: return 10 elif BC1==[2,2]: return 11 elif BC1==[3,0]: return 12 elif BC1==[4,0]: return 13 # sends every index in HMList to its BC def AdjustmentInverse(place): if place==0: return [0,0] elif place==1: return [0,1] elif place==2: return [0,2] elif place==3: return [0,3] elif place==4: return [0,4] elif place==5: return [1,0] elif place==6: return [1,1] elif place==7: return [1,2] elif place==8: return [1,3] elif place==9: return [2,0] elif place==10: return [2,1] elif place==11: return [2,2] elif place==12: return [3,0] elif place==13: return [4,0] # gives minimum of positive list without including its zeros def MinimumNozeros(List1): minimum=max(List1)+1 for item in List1: if item!=0 and item<minimum: minimum=item return minimum #list with all possible guesses allList=[] for i0 in range(0,6): for i1 in range(0,6): for i2 in range(0,6): for i3 in range(0,6): allList.append([i0,i1,i2,i3]) TempList=[[0,0,5,4]] for secret in TempList: guess=[0,0,1,1] BC=HowManyBc(guess[:],secret[:]) counter=1 optionList=[] for i0 in range(0,6): for i1 in range(0,6): for i2 in range(0,6): for i3 in range(0,6): optionList.append([i0,i1,i2,i3]) while BC!=[4,0]: dummyList=[] #list with possible secrets for this guess for i0 in range(0,6): for i1 in range(0,6): for i2 in range(0,6): for i3 in range(0,6): opSecret=[i0,i1,i2,i3] if HowManyBc(guess[:],opSecret[:])==BC: dummyList.append(opSecret) List1=[item for item in optionList if item in dummyList] optionList=List1[:] # intersection of optionList and dummyList item1Max=0 for item1 in allList: ListBC=[] # [list of all [bulls,cows] in optionList for item2 in optionList: ListBC.append(HowManyBc(item1[:],item2[:])) HMList=[0]*14 # counts how many B/C there are for item2 in optionList for BC1 in ListBC: index=Adjustment(BC1) HMList[index]=HMList[index]+1 m=max(HMList)#maximum [B,C], more left - less eliminated (min in minimax) maxList=[i for i, j in enumerate(HMList) if j == m] maxElement=maxList[0] #index with max possibleGuess=[] if m>item1Max: #max of the guesses, the max in minimax item1Max=m possibleGuess=[i[:] for i in optionList if AdjustmentInverse(maxElement)==HowManyBc(item1[:],i[:])] nextGuess=possibleGuess[0][:] guess=nextGuess[:] BC=HowManyBc(guess[:],secret[:]) counter=counter+1 I get: for [5, 3, 3, 4] counter is 7 for [5, 4, 4, 5] counter is 8 If someone could help I would appreciate it very much! Thanks,mike Answer: ### 1\. What's wrong with your implementation There are four mistakes. 1. The comment is wrong on this line: m=max(HMList)#maximum [B,C], more left - less eliminated (min in minimax) This is actually the "max" in the minimax (which should have been clear from the call to `max`). You are trying to find the guess that _minimizes_ the _maximum size_ of the groups of possible secrets that yield the same evaluation. Here we are finding the maximum size of the groups, so that's the "max". 2. That mistake caused you to make this one: if m>item1Max: #max of the guesses, the max in minimax Here you need to take the min, not the max. 3. On the following lines you pick the first item among `optionList` that would generate the same evaluation as `item1`: possibleGuess=[i[:] for i in optionList if AdjustmentInverse(maxElement)==HowManyBc(item1[:],i[:])] nextGuess=possibleGuess[0][:] But that's not right: the guess we want here is `item1`, not some other guess that would generate the same evaluation! 4. Finally, you don't properly handle the case where `optionList` has only one remaining item. In this case all possible guesses are equally good at distinguishing among this item, so the minimax procedure doesn't differentiate between the guesses. In this case you should just guess `optionList[0]`. ### 2\. Other comments on your code 1. The variable names are poorly chosen. For example, what is `item1`? This is the guess that you are evaluating, so surely it should be called something like `possible_guess`? I suspect that your mistake §1.3 above was partly caused by this poor choice of variable name. 2. There's vast amounts of needless copying. All of your `[:]` are pointless and can be removed. The variable `List1` is also pointless (why not just assign to `optionList`?), as is `nextGuess` (which not just assign to `guess`?) 3. You build `dummyList` consisting of all possible secrets that would match the last guess, but then you throw away all the entries in `dummyList` that aren't also in `optionList`. So why not just loop over `optionList` and keep the entries that match? Like this: optionList = [item for item in optionList if HowManyBc(guess, item)==BC] 4. You build up a table `HMList` which counts the number of occurrences of each pattern of bulls and cows. You have noted the fact that there are 14 possible (bull, cow) pairs and so you've written the functions `Adjustment` and `AdjustmentInverse` to map back and forth between (bull, cow) pairs and their indices in the list. These functions could have much simpler implementations if you took a data- driven approach and used the built-in [`list.index`](http://docs.python.org/3/library/stdtypes.html#common-sequence- operations) method: # Note that (3, 1) is not possible. EVALUATIONS = [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (3, 0), (4, 0)] def Adjustment(evaluation): return EVALUATIONS.index(evaluation) def AdjustmentInverse(index): return EVALUATIONS[index] But after fixing mistake §1.3 above, you don't need `AdjustmentInverse` any more. And `Adjustment` could be avoided if you kept the counts in a [`collections.Counter`](http://docs.python.org/3/library/collections.html#collections.Counter) instead of a list. So instead of: HMList=[0]*14 # counts how many B/C there are for item2 in optionList for BC1 in ListBC: index=Adjustment(BC1) HMList[index]=HMList[index]+1 m=max(HMList) you could simply write: m = max(Counter(ListBC).values()) ### 3\. Improved code 1. Evaluating a guess (your function `HowManyBc`) can be reduced to just three lines using the class [`collections.Counter`](http://docs.python.org/3/library/collections.html#collections.Counter) from the standard library. from collections import Counter def evaluate(guess, secret): """Return the pair (bulls, cows) where `bulls` is a count of the characters in `guess` that appear at the same position in `secret` and `cows` is a count of the characters in `guess` that appear at a different position in `secret`. >>> evaluate('ABCD', 'ACAD') (2, 1) >>> evaluate('ABAB', 'AABB') (2, 2) >>> evaluate('ABCD', 'DCBA') (0, 4) """ matches = sum((Counter(secret) & Counter(guess)).values()) bulls = sum(c == g for c, g in zip(secret, guess)) return bulls, matches - bulls I happen to prefer using letters for the codes in Mastermind. `ACDB` is so much nicer to read and type than `[0, 2, 3, 1]`. But my `evaluate` function is flexible as to how you represent the codes and guesses, as long as you represent them as sequences of comparable items, so you can use lists of numbers if you prefer. Notice also that I've written some [doctests](http://docs.python.org/3/library/doctest.html): these are a quick way to simultaneously provide examples in the documentation and to test the function. 2. The function [`itertools.product`](http://docs.python.org/3/library/itertools.html#itertools.product) provides a convenient way to build the list of codes without having to write four nested loops: from itertools import product ALL_CODES = [''.join(c) for c in product('ABCDEF', repeat=4)] 3. Knuth's five-guess algorithm uses the [minimax principle](https://en.wikipedia.org/wiki/Minimax). So why not implement it by taking the [`min`](http://docs.python.org/3/library/functions.html#min) of a sequence of calls to [`max`](http://docs.python.org/3/library/functions.html#max)? def knuth(secret): """Run Knuth's 5-guess algorithm on the given secret.""" assert(secret in ALL_CODES) codes = ALL_CODES key = lambda g: max(Counter(evaluate(g, c) for c in codes).values()) guess = 'AABB' while True: feedback = evaluate(guess, secret) print("Guess {}: feedback {}".format(guess, feedback)) if guess == secret: break codes = [c for c in codes if evaluate(guess, c) == feedback] if len(codes) == 1: guess = codes[0] else: guess = min(ALL_CODES, key=key) Here's an example run: >>> knuth('FEDA') Guess AABB: feedback (0, 1) Guess BCDD: feedback (1, 0) Guess AEAC: feedback (1, 1) Guess AFCC: feedback (0, 2) Guess FEDA: feedback (4, 0)
Sprite outline and save Question: I am making a python script that can cut out sprites from a transparent background spritesheet. I want to cut out the sprites in a square or a rectangle. So far my idea is to: **1\. Get all pixel data from sheet.** **2\. Search for non-transparent pixels.** **3\. When such a pixel is found, start looking around it for other non- transparent pixels, so you can get the image correctly.** **4\. Append found pixels in a tuple, that then gets pushed into an image and saved.** ( **THE SPRITES MAY BE PLACED UNEVENLY ON THE SHEET** ) If the sprite is uneven, I will check its dimensions and then add a bit of transparent background to the sides of it, so it becomes a square or a rectangle. For example you have an image that is 53x47 I will add 19 and 25 pixels of transparent background to both sides of it so it becomes a rectangle. I am using PIL, if there is a better way to do it, feel free to share it. If you have a better way of doing it, share as well. This is my code so far, I can't understand how to add the transparent background on the sides and how to do the outlining correctly, also I can't seem to get the neighbourPixels function right and it makes a closed loop. from PIL import Image from sys import argv, exit # Functions def neighbourPixels(pixels, row, column): pixel = pixels[row, column] data = tuple() holder = tuple() while pixel != 0: if pixels[row+1, column][3] != 0: holder = pixels[row+1, column] data += (holder, ) pixel = pixels[row+1, column] print "In box 1" break elif pixels[row, column+1][3] != 0: holder = pixels[row, column+1] data += (holder, ) pixel = pixels[row+1, column] print "In box 2" elif pixels[row+1, column+1][3] != 0: holder = pixels[row+1, column+1] data += (holder, ) pixel = pixels[row+1, column] print "In box 3" elif pixels[row-1, column][3] != 0: holder = pixels[row-1, column] data += (holder, ) pixel = pixels[row+1, column] print "In box 4" elif pixels[row, column-1][3] != 0: holder = pixels[row, column-1] data += (holder, ) pixel = pixels[row+1, column] print "In box 5" elif pixels[row-1, column-1][3] != 0: holder = pixels[row-1, column-1] data += (holder, ) pixel = pixels[row+1, column] print "In box 6" elif pixels[row+1, column-1][3] != 0: holder = pixels[row+1, column-1] data += (holder, ) pixel = pixels[row+1, column] print "In box 7" elif pixels[row-1, column+1][3] != 0: holder = pixels[row-1, column+1] data += (holder, ) pixel = pixels[row+1, column] print "In box 8" else: print "Sprite has been outlined." pixel[3] = 0 sprite = Image.new("RGBA", (len(data), len(data))) sprite.putdata(data) return sprite # Main if len(argv) < 4: raise ValueError("Not enough arguments") # Inicialization & Declatation framesToCut = int(float(argv[2])) frameSize = int(float(argv[3])) frameToSave = Image.new("RGBA", (frameSize, frameSize)) frameCounter = 0 pixelTuple = tuple() currentTuple = tuple() # Preparing data sheet = Image.open(argv[1]) width, heigth = sheet.size pixels = sheet.load() # Manipulation for row in xrange(width): for column in xrange(heigth): # Searching for a pixel whos transparency is != 0 currentPixel = pixels[row, column] if currentPixel[3] != 0: print "Pixel found!" print "Finding the sprite!" sprite = findPixels(pixels, row, column) if frameCounter <= framesToCut: # left, upper, right, lower frameCounter += 1 sprite.save(str(frameCounter), "PNG") print "Sprite saved!" else: exit("Sprites were made O.o - Check 'em!") Answer: You may want to use scikit-image's marching squares [1]. The algorithm you are looking for is already implemented. [1] <http://scikit-image.org/docs/dev/auto_examples/plot_contours.html> edit: Once you have the contours using a grey-scaled image *r_grey*, just plot colored image and contours on top of each other. This example refers to the example given at the link above: # Find contours at a constant value of 0.8 contours = measure.find_contours(r_grey, 0.8) # Display the image and plot all contours found plt.imshow(r, interpolation='nearest') for n, contour in enumerate(contours): plt.plot(contour[:, 1], contour[:, 0], linewidth=2) The original code told you to use _r_ (the image) and plot it. This is what we continue to do. Remember: grey-scaled and colored image have the same coordinates.
How to move your code in codeskulptor from the browser to python 2.7? Question: I am learning a course on Coursera: "An Introduction to Interactive Programming in Python". I have written the whole of the code in the course in the browser and I have used a library called `simplegui` for all the GUI functionality. I want to move this over to IDLE and then edit and work on it from there. (I am also thinking of freezing the repository and then distributing it) Answer: You can download this github repository. [simplegui tk Library](https://github.com/IcyFlame/simpleguitk) And then place the file with the CodeSkulptor code inside a `.py` file and add the line at the beginning of the code: `import simpleguitk as simplegui` And then you are all set to run this application. For most of the time, It works fine. I have not yet checked it with sounds and images but I think you can get it to work with images too, in case it does not. I thank the author of this library: GitHub User dholm for the amazing functionality he has given us.
Why does dir of a module show no __dict__? (python) Question: For example: >>> import os >>> '__dict__' in dir(os) False But `os.__dict__` shows there is a `__dict__` attribute. Answer: Because `dir` uses a [specialized implementation](http://hg.python.org/cpython/file/30b3798782f1/Objects/object.c#l1829) for modules, which returns all the keys in the module's `__dict__`, and thus neglects to include the `__dict__` attribute itself. It is not clear from reading the source code whether this is intentional.
"Invalid tag name" error when creating element with lxml in python Question: I am using lxml to make an xml file and my sample program is : from lxml import etree import datetime dt=datetime.datetime(2013,11,30,4,5,6) dt=dt.strftime('%Y-%m-%d') page=etree.Element('html') doc=etree.ElementTree(page) dateElm=etree.SubElement(page,dt) outfile=open('somefile.xml','w') doc.write(outfile) And I am getting the following error output : dateElm=etree.SubElement(page,dt) File "lxml.etree.pyx", line 2899, in lxml.etree.SubElement (src/lxml/lxml.etree.c:62284) File "apihelpers.pxi", line 171, in lxml.etree._makeSubElement (src/lxml/lxml.etree.c:14296) File "apihelpers.pxi", line 1523, in lxml.etree._tagValidOrRaise (src/lxml/lxml.etree.c:26852) ValueError: Invalid tag name u'2013-11-30' I thought it of a Unicode Error, so tried changing encoding of **'dt'** with codes like 1. `str(dt)` 2. `unicode(dt).encode('unicode_escape')` 3. `dt.encocde('ascii','ignore')` 4. `dt.encode('ascii','decode')` and some others also, but none worked and same error msg generated. Answer: You get the error because element names are not allowed to begin with a digit in XML. See <http://www.w3.org/TR/xml/#sec-common-syn> and <http://www.w3.org/TR/xml/#sec-starttags>. The first character of a name must be a `NameStartChar`, which disallows digits. An element such as `<2013-11-30>...</2013-11-30>` is invalid. An element such as `<D2013-11-30>...</D2013-11-30>` is OK. If your program is changed to use ElementTree instead of lxml (`from xml.etree import ElementTree as etree` instead of `from lxml import etree`), there is no error. But I would consider that a bug. lxml does the right thing, ElementTree does not.
Python: Unsupported operand type(s) for &: 'NoneType' and 'NoneType' whilst using lambda Question: I'm currently using lambda to make a tkinter button do two things after each other: def classManip(): cManip = tk.Toplevel() cManip.title('Class Manipulator') cManip.minsize(400,100) cManip.maxsize(400,100) databaseEntry = ttk.Entry(cManip, width = 25) databaseEntry.place(relx = .5, rely = .375, anchor = "c") entrySubmit = ttk.Button(cManip, text = "Enter", width = 20, command = lambda : connectDatabase(databaseEntry.get()) & cManip.destroy()) entrySubmit.place(relx = .5, rely = .625, anchor="c") cManip.mainloop() this is the function from my main code; I have a button on my main tkinter window that has the command to run this function. The connect databaseEntry function is form another file named databaseManip in a folder named scripts which I import using: from scripts.databaseManip import connectDatabase and the code within that file is: import sqlite3, sys, os import tkinter as tk from win32api import GetSystemMetrics #connects or creates database def connectDatabase(name): name = str(name) screenWidth = GetSystemMetrics (0) screenHeight = GetSystemMetrics (1) if os.path.isfile("classDbFiles/" + name + ".db"): conn = sqlite3.connect("classDbFiles/" + name + ".db") tk.messagebox.showinfo(message="Connected to %s successfully" % (str(name + ".db")), title = "File Found") else: conn = sqlite3.connect("classDbFiles/" + name + ".db") tk.messagebox.showinfo(message = "The database file %s was created and opened successfully" % (str(name + ".db")), title = "Success") What I want for the program to do is to run the database function creating or opening the .db file and then to close the tkinter window afterwards and funnily enough it does actually work but it returns the error: Exception in Tkinter callback Traceback (most recent call last): File "E:\Program Files\Python\lib\tkinter\__init__.py", line 1475, in __call__ return self.func(*args) File "C:\Users\Patrick\Dropbox\Computing Project\mainApp.py", line 52, in <lambda> entrySubmit = ttk.Button(cManip, text = "Enter", width = 20, command = lambda : connectDatabase(databaseEntry.get()) & cManip.destroy()) TypeError: unsupported operand type(s) for &: 'NoneType' and 'NoneType' I have searched for an answer but nothing seems to be for lambda so I'm lost. What's wrng with the code? Answer: `&` doesn't do what you think it does. It finds the the bitwise `and` of two objects. Instead, try defining the function: def function(): connectDatabase(databaseEntry.get()) cManip.destroy() entrySubmit = ttk.Button(cManip, text="Enter", width=20, command=function) You could also replace the `&` with an `and`, which would work if the first function call does always only return `None` (or another false-valued value), **but this is a nasty, hacky, clever, and unreadable way of doing what you want** and will likely result in the confusion of you, and anyone reading your code.
Removing each element at the value in each key Question: sample_dict = {'i.year': ['1997', '1997'], 'i.month': ['March', 'April'], 'j.month': ['March', 'April'], 'j.year': ['1997', '2003']} How do we compare each element in i.year and j.year, and if the elements are equal to each other, than delete the element at that index in the value at each key and than move on to the next element and continue the process. The length of each value will always be the same. _With no use of imports_ So basically what I'm trying to say is this: For the sake of this question compare just the elements in i.year and j.year: -> {'i.year': ['1997', '1997'], 'i.month': ['March', 'April'], 'j.month': ['March', 'April'], 'j.year': ['1997', '2003']} -> The first element in i.year is equal to the first element in j.year, so delete the first element in each value in every key. We get: -> {'i.year': ['1997'], 'i.month': ['April'], 'j.month': ['April'], 'j.year': ['2003']} -> The element now in i.year and j.year is the same so we're done. Return that dictionary Another example: -> {'i.year': ['1997', '1997', '2009'], 'i.month': ['March', 'April', 'June'], 'j.month': ['March', 'April', 'June'], 'j.year': ['1997', '2003', '2010']} -> The first element in i.year is equal to the first element in j.year, so delete the first element in each value in every key. We get: -> {'i.year': ['1997', '2009'], 'i.month': ['April', 'June'], 'j.month': ['April', 'June'], 'j.year': ['2003', '2010']} -> Now the first element in i.year and j.year are different so we move to the next element which is '2009' and '2010' -> '2009' and '2010' are different so we move to the next element, since there's none we are done. Return that dictionary. Last example: -> {'i.year': ['1996', '1997', '2010'], 'i.month': ['March', 'April', 'June'], 'j.month': ['March', 'April', 'June'], 'j.year': ['1997', '2003', '2010']} -> The first element in i.year is not equal to the first element in j.year, so we move on to the next element. -> '1997' does not equal to '2003' so we move on to the next element -> '2010' is equal to '2010' so we delete each element in every key at the index We get: -> {'i.year': ['1996', '1997'], 'i.month': ['March', 'April'], 'j.month': ['March', 'April'], 'j.year': ['1997', '2003']} -> There are no more elements to move on to, so we are done, we return this dictionary. I have this idea but cant turn it into python code: For every element in i.month loop through every element in j.year, and if the elements are not equal loop through the entire dictionary and remove the element at that index. Answer: You can first find the indexes where the elements in `i.year` and `j.year` are different, and then iterate over dict and filter out items that are not at those indexes: def solve(d, *keys): indexes = [i for i, x in enumerate(zip(*(d[k] for k in keys))) if len(set(x)) != 1] return {k:[v[x] for x in indexes] for k, v in d.items()} **Demo:** >>> d = {'i.year': ['1997', '1997'], 'i.month': ['March', 'April'], 'j.month': ['March', 'April'], 'j.year': ['1997', '2003']} >>> solve(d, 'i.year', 'j.year') {'i.year': ['1997'], 'j.month': ['April'], 'i.month': ['April'], 'j.year': ['2003']} >>> d = {'i.year': ['1997', '1997', '2009'], 'i.month': ['March', 'April', 'June'], 'j.month': ['March', 'April', 'June'], 'j.year': ['1997', '2003', '2010']} >>> solve(d, 'i.year', 'j.year') {'i.year': ['1997', '2009'], 'j.month': ['April', 'June'], 'i.month': ['April', 'June'], 'j.year': ['2003', '2010']} >>> d = {'i.year': ['1996', '1997', '2010'], 'i.month': ['March', 'April', 'June'], 'j.month': ['March', 'April', 'June'], 'j.year': ['1997', '2003', '2010']} >>> solve(d, 'i.year', 'j.year') {'i.year': ['1996', '1997'], 'j.month': ['March', 'April'], 'i.month': ['March', 'April'], 'j.year': ['1997', '2003']}
Python: Converting a list of sets to a set Question: I am working on a programming project involving DFAs, and I've come across an error I can't seem to figure out how to bypass. In this section of code: from DFA import * def DAWG(): alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] f = open('lexicontest.txt', 'r') dictionary = list(f) accepts = [] for i in dictionary: if len(i) >= 3: accepts.append(i) D = from_word_list(accepts, alphabet) newStates = frozenset(D.mn_classes()) I get this error: Traceback (most recent call last): File "...\DAWG.py", line 31, in <module> DAWG() File "...\DAWG.py", line 19, in DAWG newStates = frozenset(D.mn_classes()) TypeError: unhashable type: 'set' This is because the method mn_classes() returns a list whose elements are sets. I am looking for a way to convert this list into a set, but I cannot do so right now because sets must be hashable. If anyone could give me advice on how to convert this list into a set, it would be greatly appreciated. I am using a DFA library designed by Andrew Badr found [here](https://github.com/reverie/python-automata) and [here](http://code.google.com/p/python-automata/). This is the code for the method mn_classes(): def mn_classes(self): """Returns a partition of self.states into Myhill-Nerode equivalence classes.""" changed = True classes = [] if self.accepts != []: classes.append(self.accepts) #nonaccepts = filter(lambda x: x not in self.accepts, self.states) nonaccepts = [x for x in self.states if x not in self.accepts] if nonaccepts != []: classes.append(str(nonaccepts)) while changed: changed = False for cl in classes: local_change = False for alpha in self.alphabet: next_class = None new_class = [] for state in cl: next = self.delta(state, alpha) if next_class == None: for c in classes: if next in c: next_class = c elif next not in next_class: new_class.append(state) changed = True local_change = True if local_change == True: old_class = [] for c in cl: if c not in new_class: old_class.append(c) classes.remove(cl) classes.append(old_class) classes.append(new_class) break return classes Answer: Your `mn_class` code looks suspicious to me, especially `classes.append(str(nonaccepts))` seems not to be a set in a list. Followint part is also dubious: if next_class == None: for c in classes: if next in c: next_class = c Answering the quesition your asked, "If anyone could give me advice on how to convert this list into a set" modulo "mn_classes() returns a list whose elements are sets" you can use `DAWG` approach, i.e. return list of frozensets in `mn_classes`: return map(frosenset, classes)
Python - merging of csv files with one axis in common Question: I need to merge two csv files, `A.csv` and `B.csv`, with one axis in common, extract: 9.358,3.0 9.388,2.0 and 8.551,2.0 8.638,2.0 I want the final file C.csv to have the following pattern: 8.551,0.0,2.0 8.638,0.0,2.0 9.358,3.0,0.0 9.388,2.0,0.0 How to you suggest to do it? Should I go for a for loop? Answer: import numpy as np dat1 = np.genfromtxt('dat1.txt', delimiter=',') dat2 = np.genfromtxt('dat2.txt', delimiter=',') dat1 = np.insert(dat1, 2, 0, axis=1) dat2 = np.insert(dat2, 1, 0, axis=1) dat = np.vstack((dat1, dat2)) np.savetxt('dat.txt', dat, delimiter=',', fmt='%.3f')
Connect HTTP POST request to an onclick using JavaScript Question: I am trying to make an HTTP POST request using javascript and connecting it to an onclick event. For example, if someone clicks on a button then make a HTTP POST request to `http://www.example.com/?test=test1&test2=test2`. It just needs to hit the url and can close the connection. I've messed around in python and got this to work. import urllib2 def hitURL(): urllib2.urlopen("http://www.example.com/?test=test1&test2=test2").close hitURL() I have read about some ways to make HTTP requests using JavaScript in this thread [JavaScript post request like a form submit](http://stackoverflow.com/questions/133925/javascript-post-request- like-a-form-submit), but think it's overkill for what I need to do. Is it possible to just say something like this: <button onclick=POST(http://www.example.com/?test=test1&test2=test2)>hello</button> Or build it in to an event listener. I know that is not anything real but I am just looking for a simple solution that non-technical people can use, follow directions, and implement. I honestly doubt there is something that simple out there but still any recommendations would be appreciated. Answer: You need to use `XMLHttpRequest` (see [MDN](https://developer.mozilla.org/en- US/docs/Web/API/XMLHttpRequest)). var xhr = new XMLHttpRequest(); xhr.open("POST", url, false); xhr.onload = // something document.getElementById("your_button's_ID").addEventListener("click", function() {xhr.send(data)}, false );
Can I put a filepath and then the file name/extension in place of this? Question: I am making a simple application in Python that downloads a file from a website. This application has to put said file in a specific location. import urllib urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3") In the above code, which I got from an answer on the question, [How do I download a file over HTTP using Python?](http://stackoverflow.com/questions/22676/how-do-i-download-a-file- over-http-using-python), I am guessing that "mp3.mp3" is the file that will be stored locally after it is downloaded from the URL. That brings me to my next question: can I put a filepath and then the file name/extension in place of "mp3.mp3"? Answer: Yes, that is how it works. The documentation for urllib can be found [here](http://docs.python.org/2/library/urllib.html).
python, "urlparse.urlparse(url).hostname" return None value Question: After loging in on a website I want to collect its links. This I do with this function (using mechanize and urlparse libraries): br = mechanize.Browser() . . #logging in on website . for link in br.links(): url = urlparse.urljoin(link.base_url, link.url) hostname = urlparse.urlparse(url).hostname path = urlparse.urlparse(url).path #print hostname #by printing this I found it to be the source of the None value mylinks.append("http://" + hostname + path) and I get this error message: mylinks.append("http://" + hostname + path) TypeError: cannot concatenate 'str' and 'NoneType' objects I am not sure on how to fix this, or even if it can be fixed at all. Is there any way to force the function to append even if it would produce a nonworking and weird result for the None value? Alternatively, what I'm really after in the link is what the link ends with. for example, the html code for one of the links look like this (what I am after is the world "lexik"): <td class="center"> <a href="http://UnimportantPartOfLink/lexik>>lexik</a> </td> so an alternative route would be if mechanize can just collect this value directly, bypassing the links and None value troubles Answer: Why not use a `try/except` block? try: mylinks.append("http://" + hostname + path) except TypeError: continue If there's an error, it would just skip the appending and go on with the loop. Hope this helps!
AttributeError: 'DatabaseWrapper' object has no attribute 'Database' Question: Version numbers are Django 1.6, Python 3.3.2 and Mac OS X 10.9 I create an app with this command python3 manage.py startapp lists Then in my lists/tests.py file I put this code from django.test import TestCase class SmokeTest(TestCase): def test_bad_maths(self): self.assertEqual(1 + 1, 3) then I run this command from the app root folder python3 manage.py test and this is the stack trace that comes back, it's not working correctly E ====================================================================== ERROR: test_bad_maths (lists.tests.SmokeTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 124, in ensure_connection self.connect() File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 111, in connect conn_params = self.get_connection_params() File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 85, in get_connection_params raise NotImplementedError NotImplementedError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 653, in supports_transactions self.connection.enter_transaction_management() File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 288, in enter_transaction_management if managed == self.get_autocommit(): File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 324, in get_autocommit self.ensure_connection() File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 124, in ensure_connection self.connect() File "/usr/local/lib/python3.3/site-packages/django/db/utils.py", line 86, in __exit__ db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__) AttributeError: 'DatabaseWrapper' object has no attribute 'Database' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 124, in ensure_connection self.connect() File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 111, in connect conn_params = self.get_connection_params() File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 85, in get_connection_params raise NotImplementedError NotImplementedError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.3/site-packages/django/test/testcases.py", line 178, in __call__ self._pre_setup() File "/usr/local/lib/python3.3/site-packages/django/test/testcases.py", line 749, in _pre_setup self._fixture_setup() File "/usr/local/lib/python3.3/site-packages/django/test/testcases.py", line 861, in _fixture_setup if not connections_support_transactions(): File "/usr/local/lib/python3.3/site-packages/django/test/testcases.py", line 848, in connections_support_transactions for conn in connections.all()) File "/usr/local/lib/python3.3/site-packages/django/test/testcases.py", line 848, in <genexpr> for conn in connections.all()) File "/usr/local/lib/python3.3/site-packages/django/utils/functional.py", line 49, in __get__ res = instance.__dict__[self.func.__name__] = self.func(instance) File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 664, in supports_transactions self.connection.leave_transaction_management() File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 317, in leave_transaction_management if managed == self.get_autocommit(): File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 324, in get_autocommit self.ensure_connection() File "/usr/local/lib/python3.3/site-packages/django/db/backends/__init__.py", line 124, in ensure_connection self.connect() File "/usr/local/lib/python3.3/site-packages/django/db/utils.py", line 86, in __exit__ db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__) AttributeError: 'DatabaseWrapper' object has no attribute 'Database' ---------------------------------------------------------------------- Ran 0 tests in 0.031s FAILED (errors=1) Answer: I have exact the same environment: * Mac OS X 10.9 * Python 3.3.2 * Django 1.6 I have virtualenv 1.10.1 installed and create one, install django and create the project and app: virtualenv-3.3 tt cd tt . bin/activate pip install django==1.6 django-admin.py startproject myproj cd myproj chmod +x manage.py ./manage.py startapp lists Now I pasted your code into lists/test.py and run the test with the default settings.py (database sqlite3, etc.) ./manage.py test and got the right results: Creating test database for alias 'default'... F ====================================================================== FAIL: test_bad_maths (lists.tests.SmokeTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/erevilla/tt/myproj/lists/tests.py", line 6, in test_bad_maths self.assertEqual(1 + 1, 3) AssertionError: 2 != 3 ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (failures=1) Destroying test database for alias 'default'... I can't reproduce your problem. Please check: * settings.py (what database are you using) * manage.py (for incorrect version) * DJANGO_SETTINGS_MODULE is undefined
How to call an ncurses based application using subprocess module in PyCharm IDE? Question: I would like to launch an ncurses based application from python using subprocess module. The ncurses based application is TABARI, an event extraction system. The result of event extraction is saved to a file. I would like to launch it from a python script, wait for it to terminate and then read the results file. A code sample is shown bellow: import subprocess proc = subprocess.Popen('TABARI -a ' + file, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print proc.communicate() The result of this code when running the program is PyCharm is: ('', 'Error opening terminal: unknown.\n') When I run the same code from a terminal initiated python interpreter (the same as is used within PyCharm), the output is: ('...lots of text...', '') I tried several things, including using shell=False, setting the bufsize to -1, and investigating os.environ variables. One suspicious difference between the os.environ output from PyCharm and the terminal is the 'TERM' variable, which does not exist in PyCharm and equals 'xterm' in terminal. I would appreciate any help. Answer: I don't know PyCharm or TABARI specifically, but from the error message it sounds like PyCharm is executing your code without connecting it to a terminal. Possibly it does this so it can just collect program output and display it in a GUI window, or because the authors don't feel like it's very clean to launch a terminal emulator like xterm and run your code inside that. From some of the other questions around here, it sounds like there isn't any really good way to make PyCharm provide a terminal-emulation environment when running your code. There are some suggestions [on this question](http://stackoverflow.com/questions/17008372/pycharm-how-to-launch- for-a-standard-terminal-to-solve-an-issue-with-curses), but they don't sound very satisfactory. The path of least resistance is probably just to run your program from the terminal each time. If that's unacceptable, you could have your code check to see if stdin is a terminal (`os.isatty(0)`), and if not, explicitly launch a terminal emulator like xterm and re-invoke your code under that. Or, if you don't actually need to interact with the subprocess while it runs, you could allocate your own pseudoterminal master/slave pair and run the code connected to the slave. These things are all more complicated than they probably should be, and a full explanation of all of it would take enough text to fill a whole manual, but here are some good resources: * [Wikipedia entry on Pseudo Terminals](http://en.wikipedia.org/wiki/Pseudo_terminal), for some very general background * [man page for xterm(1)](http://linux.die.net/man/1/xterm), for info on how to launch with a particular command instead of your shell * [man page for pty(7)](http://man7.org/linux/man-pages/man7/pty.7.html)\- explains the mechanics of interacting with pty/tty devices * [the Python pty module](https://docs.python.org/2/library/pty.html), in case you want to make a pseudoterminal master/slave pair and interact with it from plain Python * [an explanation from an old-ish Linux Kernel manual](http://www.win.tue.nl/~aeb/linux/lk/lk-10.html) regarding how process groups and sessions relate to terminal ownership * [an excerpt from Advanced Programming in the UNIX® Environment: Second Edition By W. Richard Stevens, Stephen A. Rago](http://infohost.nmt.edu/~eweiss/222_book/222_book/0201433079/ch09lev1sec6.html) with some more info about terminal control
fnmatch does not work with variables but with static strings Question: The following code does not find any of the patterns defined in the file `patterns`. #!/usr/bin/env python import os import fnmatch patternFile = open('patterns', 'r') patterns = patternFile.readlines() for filename in os.listdir('.'): for pattern in patterns: if fnmatch.fnmatch(filename, pattern): print "FOUND!" My `pattern` file looks like *test foo The following modified code with a static pattern string works. As expected, a file named `foofile` could be found. patternFile = open('patterns', 'r') patterns = patternFile.readlines() for filename in os.listdir('.'): if fnmatch.fnmatch(filename, '*test'): print "FOUND!" Does anybody know the problem? Answer: `readlines` includes newline character `\n` at the end of each line, you need to do: if fnmatch.fnmatch(filename, pattern.strip('\n\r'):
Split document into multiple files based on pattern Question: I'm trying to split a large text document of articles into multiple text files based on a boundary like this: `9 of 10 DOCUMENTS` at the beginning of each chunk. Everything after that pattern but before the next occurence should be written out to a new file. I can do it csplit using: `csplit -f split-docs/article -b "%02d.txt" -k articles.txt '/[0-9]* of [0-9]* DOCUMENTS/' {*}` but I'd also like to be able to do it in python. Thanks for your help. Answer: You can use [`itertools.groupby`](http://docs.python.org/2/library/itertools.html#itertools.groupby) here: **Demo:** >>> from itertools import groupby >>> import re >>> r = re.compile(r'\d+ of \d+ DOCUMENTS') >>> with open('abc1') as f: for k, g in groupby(f, key=lambda x:r.search(x)): if not k: print list(g) ... ['a\n', 'b\n'] ['c\n', 'd\n'] ['e\n', 'f\n'] where `abc1` contains: >>> !cat abc1 a b 1 of 3 DOCUMENTS c d 2 of 3 DOCUMENTS e f 3 of 3 DOCUMENTS
Unable to loop through JSON output from webservice Python Question: I have a web-service call (HTTP Get) that my Python script makes in which returns a JSON response. The response looks to be a list of Dictionaries. The script's purpose is to iterate through the each dictionary, extract each piece of metadata (i.e. "ClosePrice": "57.74",) and write each dictionary to its own row in Mssql. The issue is, I don't think Python is recognizing the JSON output from the API call as a list of dictionaries, and when I try a for loop, I'm getting the error `must be int not str`. I have tried converting the output to a list, dictionary, tuple. I've also tried to make it work with List Comprehension, with no luck. Further, if I copy/paste the data from the API call and assign it to a variable, it recognizes that its a list of dictionaries without issue. Any help would be appreciated. I'm using Python 2.7. Here is the actual http call being made: [http://test.kingegi.com/Api/QuerySystem/GetvalidatedForecasts?user=kingegi&market=us&startdate=08/19/13&enddate=09/12/13](http://test.kingegi.com/Api/QuerySystem/GetvalidatedForecasts?user=kingegi&market=us&startdate=08/19/13&enddate=09/12/13) Here is an abbreviated JSON output from the API call: [ { "Id": "521d992cb031e30afcb45c6c", "User": "kingegi", "Symbol": "psx", "Company": "phillips 66", "MarketCap": "34.89B", "MCapCategory": "large", "Sector": "basic materials", "Movement": "up", "TimeOfDay": "close", "PredictionDate": "2013-08-29T00:00:00Z", "Percentage": ".2-.9%", "Latency": 37.48089483333333, "PickPosition": 2, "CurrentPrice": "57.10", "ClosePrice": "57.74", "HighPrice": null, "LowPrice": null, "Correct": "FALSE", "GainedPercentage": 0, "TimeStamp": "2013-08-28T02:31:08 778", "ResponseMsg": "", "Exchange": "NYSE " }, { "Id": "521d992db031e30afcb45c71", "User": "kingegi", "Symbol": "psx", "Company": "phillips 66", "MarketCap": "34.89B", "MCapCategory": "large", "Sector": "basic materials", "Movement": "down", "TimeOfDay": "close", "PredictionDate": "2013-08-29T00:00:00Z", "Percentage": "16-30%", "Latency": 37.4807215, "PickPosition": 1, "CurrentPrice": "57.10", "ClosePrice": "57.74", "HighPrice": null, "LowPrice": null, "Correct": "FALSE", "GainedPercentage": 0, "TimeStamp": "2013-08-28T02:31:09 402", "ResponseMsg": "", "Exchange": "NYSE " } ] Small Part of code being used: import os,sys import subprocess import glob from os import path import urllib2 import json import time try: data = urllib2.urlopen('http://api.kingegi.com/Api/QuerySystem/GetvalidatedForecasts?user=kingegi&market=us&startdate=08/10/13&enddate=09/12/13').read() except urllib2.HTTPError, e: print "HTTP error: %d" % e.code except urllib2.URLError, e: print "Network error: %s" % e.reason.args[1] list_id=[x['Id'] for x in data] #test to see if it extracts the ID from each Dict print(data) #Json output print(len(data)) #should retrieve the number of dict in list Answer: **UPDATE** Answered my own question, here is the method below: `url = 'some url that is a list of dictionaries' #GetCall u = urllib.urlopen(url) # u is a file-like object data = u.read() newdata = json.loads(data) print(type(newdata)) # printed data type will show as a list print(len(newdata)) #the length of the list newdict = newdata[1] # each element in the list is a dict print(type(newdict)) # this element is a dict length = len(newdata) # how many elements in the list for a in range(1,length): #a is a variable that increments itself from 1 until a number var = (newdata[a]) print(var['Correct'], var['User'])`
Averaging column 2D array python Question: I have a 2D arraylist data which fills with a loop like this: data.append([TrueID,rssi]) after 8 times i got this value for data: data = [['469420270013002A', -90], ['469420270005000C', -89], ['469420270013002A', -94], ['4694202700270003', -53], ['469420270005000C', -91], ['469420270013002A', -92], ['4694202700270003', -55]] I want to calculate the average RSSI value of each TrueID and return the lowest RSSI value with its TrueID. So I need output: print "The weakest ID is " ID_result " with Rssi value of " rssi_result >>The weakest ID is '4694202700270003' with Rssi value of -54 It's necessary the 2D array fills until 20 values and continues like a FIFO system. All suggestions are welcome (even if you know other methods to get to the same result)! Thank you! Answer: Use [`collections.defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict) and `max`: >>> from collections import defaultdict >>> lis = [['469420270013002A', -90], ['469420270005000C', -89], ['469420270013002A', -94], ['4694202700270003', -53], ['469420270005000C', -91], ['469420270013002A', -92], ['4694202700270003', -55]] >>> d = defaultdict(list) >>> for k, v in lis: d[k].append(v) ... Now `d` contains: >>> d defaultdict(<type 'list'>, {'469420270005000C': [-89, -91], '4694202700270003': [-53, -55], '469420270013002A': [-90, -94, -92]}) Now use `max` and a dict comprehension to calculate the average and find out the max (key, value) pair: >>> max({k:sum(v)/float(len(v)) for k, v in d.items()}.items(), key=lambda x:x[1]) ('4694202700270003', -54.0)
Python, UnicodeEncodeError Question: Hello I've got this piece of code import urllib.request import string import time import gzip from io import BytesIO from io import StringIO from zipfile import ZipFile import csv import datetime from datetime import date import concurrent.futures den = date.today().replace(day=1) - datetime.timedelta(days=1) url = '' + den.strftime("%Y%m%d") + '_OB_ADR_csv.zip' data = urllib.request.urlopen(url).read() zipdata = BytesIO() zipdata.write(data) csvfile = open('./test.csv', 'w', newline='') csvwrite = csv.writer(csvfile, delimiter=';') with ZipFile(zipdata) as zip: for i, nazev in enumerate(zip.namelist()): if i == 0: continue csvstring = StringIO(str(zip.read(nazev), encoding='windows-1250')) csvreader = csv.reader(csvstring, delimiter=';') for j, row in enumerate(csvreader): if j == 0 and i != 1: continue csvwrite.writerow(row) csvfile.close() When i run it it sometimes throws "UnicodeEncodeError: 'ascii' codec can't encode character '\xf3' in position 1: ordinal not in range(128)" at "csvwrite.writerow(row)" How can I solve this issue? Thank you. EDIT: I run it under Python 3.3 Answer: You didn't tell csv.writer about the encoding. Take a look at the [pydocs for the csv module](http://docs.python.org/3.2/library/csv.html): > To decode a file using a different encoding, use the encoding argument of > open...[t]he same applies to writing in something other than the system > default encoding: specify the encoding argument when opening the output > file. You can see from the UnicodeEncodeError that Python thinks you want the file written in ascii. Just specify the encoding parameter and choose your desired encoding (my suggestion is `encoding='utf-8'`).
Python Joint Distribution of N Variables Question: So I need to calculate the joint probability distribution for N variables. I have code for two variables, but I am having trouble generalizing it to higher dimensions. I imagine there is some sort of pythonic vectorization that could be helpful, but, right now my code is very C like (and yes I know that is not the right way to write Python). My 2D code is below: import numpy import math feature1 = numpy.array([1.1,2.2,3.0,1.2,5.4,3.4,2.2,6.8,4.5,5.6,1.9,2.8,3.7,4.4,7.3,8.3,8.1,7.0,8.0,6.8,6.2,4.9,5.7,6.3,3.7,2.4,4.5,8.5,9.5,9.9]); feature2 = numpy.array([11.1,12.8,13.0,11.6,15.2,13.8,11.1,17.8,12.5,15.2,11.6,20.8,14.7,14.4,15.3,18.3,11.4,17.0,16.0,16.8,12.2,14.9,15.7,16.3,13.7,12.4,14.2,18.5,19.8,19.0]); #===Concatenate All Features===# numFrames = len(feature1); allFeatures = numpy.zeros((2,numFrames)); allFeatures[0,:] = feature1; allFeatures[1,:] = feature2; #===Create the Array to hold all the Bins===# numBins = int(0.25*numFrames); allBins = numpy.zeros((allFeatures.shape[0],numBins+1)); #===Find the maximum and minimum of each feature===# allRanges = numpy.zeros((allFeatures.shape[0],2)); for f in range(allFeatures.shape[0]): allRanges[f,0] = numpy.amin(allFeatures[f,:]); allRanges[f,1] = numpy.amax(allFeatures[f,:]); #===Create the Array to hold all the individual feature probabilities===# allIndividualProbs = numpy.zeros((allFeatures.shape[0],numBins)); #===Grab all the Individual Probs and the Bins===# for f in range(allFeatures.shape[0]): freqhist, binedges = numpy.histogram(allFeatures[f,:],bins=numBins,range=[allRanges[f,0],allRanges[f,1]],density=False); allBins[f,:] = binedges; allIndividualProbs[f,:] = freqhist; #===Create the joint probability array===# jointProbs = numpy.zeros((numBins,numBins)); #===Compute the joint probability distribution===# numElements = 0; for b1 in range(numBins): for b2 in range(numBins): for f1 in range(numFrames): for f2 in range(numFrames): if ( ( (feature1[f1] >= allBins[0,b1]) and (feature1[f1] <= allBins[0,b1+1]) ) and ((feature2[f2] >= allBins[1,b2]) and (feature2[f2] <= allBins[1,b2+1])) ): jointProbs[b1,b2] += 1; numElements += 1; jointProbs /= numElements; #===But what if I add the following===# feature3 = numpy.array([21.1,21.8,23.5,27.6,25.2,23.8,22.1,22.8,26.5,25.2,28.6,20.8,24.7,24.4,29.3,28.3,27.4,26.0,26.2,26.1,25.9,24.0,22.7,22.3,23.7,26.4,24.2,28.5,29.8,29.0]); How can I generalize the large loop? For N variables (features) this loop would be enormous. Is there a Pythonic way to do this easily? Answer: Check out the function `numpy.histogramdd`. This function can compute histograms in arbitrary numbers of dimensions. If you set the parameter `normed=True`, it returns the bin count divided by the bin hypervolume. If you'd prefer something more like a probability mass function (where everything sums to 1), just normalize it yourself. All together, you'll have something like: import numpy as np numBins = 10 # number of bins in each dimension data = np.random.randn(100000, 3) # generate 100000 3-d random data points jointProbs, edges = np.histogramdd(data, bins=numBins) jointProbs /= jointProbs.sum()
pycallgraph with pycharm does not work Question: I'm using mac os x and trying to setup pycallgraph. Ive installed pycallgraph with pip and graphviz with homebrew. Everything works from shell. But not from pycharm. from pycallgraph import PyCallGraph from pycallgraph import Config from pycallgraph import GlobbingFilter from pycallgraph.output import GraphvizOutput config = Config() config.trace_filter = GlobbingFilter(exclude=[ 'pycallgraph.*', ]) graphviz = GraphvizOutput(output_file='filter_exclude.png') with PyCallGraph(output=graphviz, config=config): def my_fun(): print "HELLO" my_fun() * * * /Users/user/Projects/py27/bin/python /Users/user/Projects/py27_django/test2.py Traceback (most recent call last): File "/Users/user/Projects/py27_django/test2.py", line 15, in <module> with PyCallGraph(output=graphviz, config=config): File "/Users/user/Projects/py27/lib/python2.7/site-packages/pycallgraph/pycallgraph.py", line 32, in __init__ self.reset() File "/Users/user/Projects/py27/lib/python2.7/site-packages/pycallgraph/pycallgraph.py", line 53, in reset self.prepare_output(output) File "/Users/user/Projects/py27/lib/python2.7/site-packages/pycallgraph/pycallgraph.py", line 97, in prepare_output output.sanity_check() File "/Users/user/Projects/py27/lib/python2.7/site-packages/pycallgraph/output/graphviz.py", line 63, in sanity_check self.ensure_binary(self.tool) File "/Users/user/Projects/py27/lib/python2.7/site-packages/pycallgraph/output/output.py", line 96, in ensure_binary 'The command "{}" is required to be in your path.'.format(cmd)) pycallgraph.exceptions.PyCallGraphException: The command "dot" is required to be in your path. Process finished with exit code 1 * * * Here: `/Users/user/Projects/py27/` -> virtualenv dir `/Users/user/Projects/py27_django/` -> project dir * * * What does it want from me? Answer: It worked for me in MacOS by installing **graphviz** using `brew install graphviz` and then testing **dot** by using **dot -v**. You can also download pkg from here: <http://www.graphviz.org/Download_macos.php>
Python Server-Client Communication with each other Question: I am trying to modify a tcp/ip server-client communication. Only the server can communicate with the client. I am trying to find an easy a way to send a message back to the server. Not a chat !! Just a server which will send data to a client and receive data from the client. I am using this example : Server: host="my_ip" port=4446 from socket import * s=socket() s.bind((host,port)) s.listen(1) print "Listening for connections.. " q,addr=s.accept() var = 1 while var == 1 : data=raw_input("Enter data to be send: ") q.send(data) s.close() Client: host="my_ip" port=4446 from socket import * s=socket(AF_INET, SOCK_STREAM) s.connect((host,port)) var = 1 while var == 1 : msg=s.recv(1024) print "Message from server : " + msg #response = "Message delivered" # Response to be send #s.sendto(response(host,port)) s.close() Answer: Python actual has a built in class to make your life a bit easier. <http://docs.python.org/2/library/socketserver.html>. I'm not sure I understand the second part of your question however; you can simply send data back to the server in the same way you had the server send data to the client.
error when renaming files in python Question: I am trying to rename some files, and i think python is well suited... the files have the pattern `xxx000xxx000abcde.jpg` (random numbers and letters followed by a specific letter sequence, say "abcde") and need to be renamed `xxx000xxx000.jpg` (without the "abcde" at the end) i tried import os for filename in os.listdir("C:/test/temp/jpg"): os.rename(filename, filename[:len(filename)-10]+".jpg") But i get an error "The system cannot find the file specified" what am i doing wrong ? Thank you stack trace: Traceback (most recent call last): File "C:\test\rename_jpg\rename_jpg.py", line 4, in <module> os.rename(filename, filename[:len(filename)-10]+".jpg") WindowsError: [Error 2] The system cannot find the file specified Press any key to continue . . . Answer: It's likely caused by the Python script not being in C:/test/temp itself. Python will look for the filenames in the directory it's being run from, meaning it will try to rename files that do no exist. You'd have to add the destination prefix to the filenames: os.rename("C:/test/temp/" + filename, "C:/test/temp/" + filename[:len(filename)-10]+".jpg")
Taking an argument from user (URL) Question: Does anyone know how I would be able to take the the URL as an argument in Python as page? Just to readline in the script, user inputs into the shell and pass it through as an argument just to make the script more portable? import sys, re import webpage_get def print_links(page): ''' find all hyperlinks on a webpage passed in as input and print ''' print '\n[*] print_links()' links = re.findall(r'(\http://\w+\.\w+[-_]*\.*\w+\.*?\w+\.*?\w+\.*[//]*\.*?\w+ [//]*?\w+[//]*?\w+)', page) # sort and print the links links.sort() print '[+]', str(len(links)), 'HyperLinks Found:' for link in links: print link def main(): # temp testing url argument sys.argv.append('http://www.4chan.org') # Check args if len(sys.argv) != 2: print '[-] Usage: webpage_getlinks URL' return # Get the web page page = webpage_get.wget(sys.argv[1]) # Get the links print_links(page) if __name__ == '__main__': main() Answer: It looks like you kind of got started with command line arguments but just to give you an example for this specific situation you could do something like this: def main(url): page = webpage_get.wget(url) print_links(page) if __name__ == '__main__': url = "" if len(sys.argv >= 1): url = sys.argv[0] main(url) Then run it from shell like this `python test.py http://www.4chan.org` Here is a tutorial on command line arguments which may help your understanding more than this snippet <http://www.tutorialspoint.com/python/python_command_line_arguments.htm> Can you let me know if I miss understood your question? I didn't feel to confident in the meaning after I read it.
Can't get MySQLDb to work in python on Mac is there other easier DB? Question: I am looking for a production database to use with python/django for web development. I've installed MySQL successfully. I believe the python connector is not working and I don't know how to make it work. Please point me in the right direction. Thanks. If I try importing `MySQLdb`: import MySQLdb I get the following exception. Traceback (most recent call last): File "/Users/vantran/tutorial/scrape_yf/mysql.py", line 3, in <module> import MySQLdb ImportError: No module named MySQLdb I've tried using MySQL but I am struggling with getting the connector package to install or work properly. <http://dev.mysql.com/downloads/file.php?id=414340> I've also tried to look at the other SO questions regarding installing MySQL python connectors, but they all seem to be unnecessarily complicated. I've also tried 1. <http://www.tutorialspoint.com/python/python_database_access.htm> 2. <http://zetcode.com/db/mysqlpython/> 3. <https://github.com/PyMySQL/PyMySQL> ...but nothing seems to work. Answer: If your problem is with the `MySQLdb` module, not the MySQL server itself, you might want to consider [`PyMySQL`](https://github.com/PyMySQL/PyMySQL) instead. It's much simpler to set up. Of course it's also somewhat different. The key difference is that it's a pure Python implementation of the MySQL protocol, not a wrapper around `libmysql`. So it has minimal requirements, but in a few use cases it may not be as performant. Also, since they're completely different libraries, there are a few rare things that one supports but not the other, and various things that they support differently. (For example, `MySQLdb` handles all MySQL warnings as Python warnings; `PyMySQL` handles them as information for you to process.)
python thread using start_new_thread not working Question: Im in need of a thread for my python app, in my test i have a counter with a timer simulating the loop i need to run, but the problem is that this loop calls fine from a basic python sample on the thread, but not working on my code, I must be calling the method wrong? here my code [with the problem] import thread import threading from threading import Thread import time from Tkinter import * from Tkinter import Tk import sys root = Tk() mainframe = Frame(root) # mainframe contained by root!, init class myclass(): def __init__(self): self.main() #atencion! es un loop! se quedara aqui! # en objC [self main] def submitForm(self,*args): print "submitalo" thread.start_new_thread( print_time, ("Thread-2", 4, )) def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) def main(self): print("from main") mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) # add subview mainframe mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) button = Button(mainframe, text='Submit', command=self.submitForm) button.grid(column=1 , row=3, sticky=(W,E)) #my loop root.mainloop() if __name__ == "__main__": myclass() And here the sample working code with thread import thread import time # Define a function for the thread def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) # Create two threads as follows try: thread.start_new_thread( print_time, ("Thread-1", 2, ) ) thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except: print "Error: unable to start thread" while 1: pass thanks Answer: thread.start_new_thread( print_time, ("Thread-2", 4, )) > NameError: global name 'print_time' is not defined I'm guessing that you meant `self.print_time`, the class method, instead of `print_time`, the global name that happens to be undefined.
error when trying to keep order of dictonary as it was found Question: I want the dictionary to be kept in the same order that the dates are found so the dictionary is order by date. I looked at [this python site](http://docs.python.org/2/library/collections.html#collections.OrderedDict) but the code does not work I get and error when trying to use this class. Any ideas why and how I can fix it? page = str('<OPTION VALUE="08/25/2013" >08/25/2013</OPTION><OPTIONVALUE="09/01/2013">09/01/2013</OPTION><OPTION VALUE="09/08/2013" >09/08/2013</OPTION><OPTION VALUE="09/15/2013" >09/15/2013</OPTION><OPTION VALUE="09/22/2013" >09/22/2013</OPTION><OPTION VALUE="09/29/2013" >09/29/2013</OPTION><OPTION VALUE="10/06/2013" >10/06/2013</OPTION><OPTION VALUE="10/13/2013" >10/13/2013</OPTION><OPTION VALUE="10/20/2013">10/20/2013</OPTION><OPTIONVALUE="10/27/2013">10/27/2013</OPTION><OPTION VALUE="11/03/2013" >11/03/2013</OPTION><OPTION VALUE="11/10/2013" >11/10/2013</OPTION><OPTION VALUE="11/17/2013" >11/17/2013</OPTION><OPTION VALUE="11/24/2013" >11/24/2013</OPTION><OPTION VALUE="12/01/2013" >12/01/2013</OPTION><OPTION VALUE="12/08/2013" >12/08/2013</OPTION><OPTION VALUE="12/15/2013" >12/15/2013</OPTION>OPTION VALUE="12/22/2013" >12/22/2013</OPTION><OPTION VALUE="12/29/2013" >12/29/2013</OPTION><OPTION VALUE="01/05/2014" >01/05/2014</OPTION><OPTION VALUE="01/12/2014" >01/12/2014</OPTION><OPTION VALUE="01/19/2014" >01/19/2014</OPTION><OPTION VALUE="01/26/2014" >01/26/2014</OPTION><OPTION VALUE="02/02/2014" >02/02/2014</OPTION><OPTION VALUE="02/09/2014" >02/09/2014</OPTION><OPTION VALUE="02/16/2014" >02/16/2014</OPTION><OPTION VALUE="02/23/2014" >02/23/2014</OPTION><OPTION VALUE="03/02/2014" >03/02/2014</OPTION><OPTION VALUE="03/09/2014" >03/09/2014</OPTION><OPTION VALUE="03/16/2014" >03/16/2014</OPTION><OPTION VALUE="03/23/2014" >03/23/2014</OPTION><OPTION VALUE="03/30/2014" >03/30/2014</OPTION><OPTION VALUE="04/06/2014" >04/06/2014</OPTION><OPTION VALUE="04/13/2014" >04/13/2014</OPTION><OPTION VALUE="04/20/2014" >04/20/2014</OPTION><OPTION VALUE="04/27/2014" >04/27/2014</OPTION><OPTION VALUE="05/04/2014" >05/04/2014</OPTION><OPTION VALUE="05/11/2014" >05/11/2014</OPTION><OPTION VALUE="05/18/2014" >05/18/2014</OPTION><OPTION VALUE="05/25/2014" >05/25/2014</OPTION><OPTION VALUE="06/01/2014" >06/01/2014</OPTION><OPTION VALUE="06/08/2014" >06/08/2014</OPTION><OPTION VALUE="06/15/2014" >06/15/2014</OPTION>') def web_link (enter_web_link): #11%2F10%2F2013 enter_web_link = enter_web_link.replace("/","%") #00%00%0000 add_twoF = enter_web_link[:3]+"2F"+ enter_web_link[3:] #00%2F00%0000 add_twoF_everywhere = add_twoF[:8] +"2F"+add_twoF[8:] add_twoF_everywhere = str(add_twoF_everywhere) return add_twoF_everywhere def search_13(page): starter = '<OPTION VALUE="' # find the postion where this starts start_link = page.find(starter) starter = len(starter) if start_link == -1: return None, 0, None start_link = start_link + starter end_date = start_link + 10 datetext = page[start_link: end_date] str_date = str(datetext) #this is hte actuall normal looking date dd/mm/yyyy enter_web_link = str_date # this will enter we_link function to change to percent signs endoflinkdate = web_link(enter_web_link) return str_date , end_date, endoflinkdate def getalllinks(page): links = {} while True: str_date,end_date,endoflinkdate = search_13(page) if str_date: links[str_date] ='link' + endoflinkdate page = page[end_date:] else: break return links work = getalllinks(page) print work class OrderedCounter(Counter, OrderedDict): #THIS DOES NOT WORK CAUSES ERRORS def __repr__(self): return '%s(%r)' % (self.__class__.__name__, OrderedDict(self)) def __reduce__(self): return self.__class__, (OrderedDict(self),) var1 = OrderedCounter(page,links) print var1 error: Traceback (most recent call last): File "schedule.py", line 43, in <module> class OrderedCounter(Counter, OrderedDict): NameError: name 'Counter' is not defined how is it not defined its a parameter? I want this as a dictionary as {date:link, date:link} I can get this but it is not in the same order of the dates in variable page. I want the order to be the same as the dates are found in variable page so 08/25/2013: link, 09/01/2013:link, I want to keep it in a dictionary because I paste it in a javascript website so I can enter a date and get the link and also have an ordered scroll down menu. Answer: If you want to use things from Python libraries, you need to import the library first: from collections import OrderedDict, Counter
Scan a webpage and get the video embed url only Question: I have a search engine on PHP that have indexed some movie sites., Now i want to get the video embed url on a given web page URL . and put it in an iframe. How will i get it ? using python? and integrate it in PHP ? but how will i pass the url from php to python and use the beautifulsoup? Here is what I'm trying now import BeautifulSoup html = '''http://www.kumby.com/avatar-the-last-airbender-book-3-chapter-5/''' soup = BeautifulSoup.BeautifulSoup(html) I've googled, but have not found any good information about this (probably because I don't know what this is called to search for), does anyone have any experience with this and knows how it can be done? Thanks! Answer: from bs4 import BeautifulSoup html = "http://www.kumby.com/avatar-the-last-airbender-book-3-chapter-5/" soup = BeautifulSoup(html) l = soup.findall("embed","object","param","video") for i in l: print i.string
Get all tagged text under li tags Question: I have list like: <ul> <li><strong>Text 1</strong></li> <li>Text 2</li> <li>Text 3</li> <li><strong>Text 4</strong></li> </ul> How i can get only values under strong tag using selenium webdriver in python? Answer: Assuming the data is always in the presented form, a simple regex will do: import re re.findall(r'<li><strong>([^<]*)</strong></li>', my_text)
How to generate a random graph given the number of nodes and edges? Question: I am using python with igraph library: from igraph import * g = Graph() g.add_vertices(4) g.add_edges([(0,2),(1,2),(3,2)]) print g.betweenness() I would like to generate a random graph with 10000 nodes and 100000 edges. The edges can be random. Please suggest a way to have random edges (using numpy.random.rand ) Answer: Do you have to use `numpy.random.rand`? If not, just use [`Graph.Erdos_Renyi`](http://igraph.sourceforge.net/doc/python/igraph.GraphBase- class.html#Erdos_Renyi), which lets you specify the number of nodes and edges directly: g = Graph.Erdos_Renyi(n=10000, m=100000)
Python Traceback: no error, yet no output from script Question: `enter code here`Im using Eclipse with PyDev and trying to get a simple script working: Edited Code: import time import os import json import tarfile source_config='/Users/brendanryan/scripting/brendan.json' backup_dir = '/myapp/target/' def main(): with open(source_config) as f: data = json.load(f) for entry in data["source_include"]: #base_filename = os.path.basename(entry) #source_dirs = [ name for name in os.listdir(entry) if os.path.isdir(os.path.join(entry, name)) ] full_dir = os.path.join(entry) tar = tarfile.open(os.path.join(backup_dir, '.tar.gzip'), 'w:gz') tar.add(full_dir) tar.close() if __name__ == '__main__': main() JSON: { "source_type": "folder", "tar_type": "gzip", "tar_max_age": "10", "source_include": ["/myapp/conf", "/myapp/db"], "target_path": "/myapp/target" } This is SUPPOSED to work. But it doesnt. When the code was broken, I had all sorts of Tracebacks to work with... and I DO mean all. Now, I just get ""... no errors, no output, no resulting .tar.gz, no nothing when I run it. Id be willing to try ANYTHING to get this to work right now... For the uninitiated, this is supposed to read the json (which are variables) and use that to select the source folders, then tar.gz them and place the resulting archives in another folder. I dont know how to do it, but it would be great to actually just take ALL the folders in the "source_include", tar.gz and name it with the current date. That would be AWESOME! Edit: Added main()... THANKS! So, with the edit, the traceback is now: Edit AGAIN: And NOW, no traceback. Again. No output... Foul language is gone (Eclipse says the code is cool now)... but no output. Al all, as in no reslutant archive. Back to square one. Answer: You don't actually seem to be calling the `main` function at all. To call a function, you need to use parentheses: `main()`. (And you shouldn't catch an exception if all you're going to do is print a useless canned message. Better to let the exception propagate so you can see what's actually going wrong.)
How to get the exit status set in a shell script in python Question: i want to get the exit status set in a shell script which has been called from python. the code is as below python script. result = os.system("/compile_cmd.sh") print result (compile_cmd.sh) javac @source.txt #i do some code here to get the no of compilation errors if [$error1 -e 0 ] then echo "\n********** JAVA compilation sucessfull **********" exit 0 else echo "\n** JAVA Compilation Error in file ** File not checked in to CVS **" exit 1 fi i am running this code. but no matter the what exit status i am returning, i am getting result var as 0 (i think its returning whether shell script was run successfully or not) Any idea how i can fetch the exit status that i am setting in the shell script in the python script?? Answer: import subprocess result = subprocess.Popen("./compile_cmd.sh") text = result.communicate()[0] returncode = result.returncode Taken from here: [How to get exit code when using Python subprocess communicate method?](http://stackoverflow.com/questions/5631624/how-to-get- exit-code-when-using-python-subprocess-communicate-method)
SOCKET ERROR: [Errno 111] Connection refused Question: I am using simple python lib for the SMTP But i am getting this error: import smtplib smtpObj = smtplib.SMTP('localhost') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/smtplib.py", line 249, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python2.7/smtplib.py", line 309, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python2.7/smtplib.py", line 284, in _get_socket return socket.create_connection((port, host), timeout) File "/usr/lib/python2.7/socket.py", line 571, in create_connection raise err socket.error: [Errno 111] Connection refused Using python-2.7 Answer: **Start a simple SMTP server with Python like so:** python -m smtpd -n -c DebuggingServer localhost:1025 **or you can also try gmail smtp setting** server = smtplib.SMTP(host='smtp.gmail.com', port=587)
How to export data (which is as result of Python program) from commmand line? Question: I am working on a Python program, and I have results on the command line. Now I need to do analysis on the results, so I need all results as exported in any format like either SQL, or Excel or CSV format. Can some tell me how can i do that ? import csv x1=1 x2=2 while True: show = [ dict(x1=x1+1 , x2=x2+2)] print('Received', show ) with open('large1.csv','w') as f1: writer=csv.writer(f1, delimiter=' ',lineterminator='\n\n',) writer.writerow(show) x1=x1+1 x2=x2+1 Here this is infinite loop and I want to have a csv file containing 2 column of x1 and x2. and with regularly updated all values of x1 and x2 row wise (1 row for 1 iteration) But by this code I'm getting a csv file which is named as 'large1.csv' and containing only one row (last updated values of x1 and x2). So how can I get my all values of x1 and x2 as row was in python. Answer: Have a look at the [open() documentation](http://docs.python.org/2/library/functions.html#open). Mode `w` will _truncate_ the file, which means it will replace the contents. Since you call that every loop iteration, you are continuously deleting the file and replacing it with a new one. Mode `a` appends to the file and is _maybe_ what you want. You also might consider opening the file outside of the loop, in that case `w` might be the correct mode.
shortest path from goal to root in directed graph with cycles python Question: I want to find the shortest path from `goal` to `root` working backwards My input for `root` is `{'4345092': ['6570646', '40586', '484']}` My input for `goal` is `{'886619': ['GOAL']}` My input for `path_holder` is an input but it gets converted to `dct` and is used for this function. I am getting stuck regarding the while loop as it creates the path for me backwards. Right now I can't get `q` to print because that part of the code isn't being ran. `dct` is basically a directed graph representation that contains cycles. I can't seem to figure out how to start from `GOAL` and end up at the `root` node. I was wondering if someone could help me figure this out thanks! dct: dct = { '612803266': ['12408765', '46589', '5880', '31848'], '8140983': ['7922972', '56008'], '7496838': ['612803266'], '1558536111': ['7496838'], '31848': ['DEADEND'], '1910530': ['8140983'], '242010': ['58644', '886619'], '727315568': ['DEADEND'], '12408765': ['DEADEND'], '56008': ['DEADEND'], '58644': ['DEADEND'], '886619': ['GOAL'], '40586': ['931', '727315568', '242010', '1910530'], '5880': ['1558536111'], '46589': ['DEADEND'], '6570646': ['2549003','43045', '13830'], '931': ['299159122'], '484': ['1311310', '612803266'], '1311310': ['DEADEND'], '7922972': ['DEADEND'] } my function: def backtrace(path_holder, root, goal): dct = {} for d in path_holder: dct.update(d) rootnode = root.keys()[0] goal = goal.keys()[0] path = [] path.append(goal) q = 0 while goal != rootnode: # find key that contains goal in list for i in dct: #iterate keys if i in dct: # prevent repeat of path continue for j in dct[i]: #iterate though children if j == goal: path.append(i) goal = i # look for new goal q += 1 print q #print goal # append key that has goal in the list # set goal to be the key that was appended # repeat return path Answer: Just find the paths and then invert them. **UPDATED:** Added "[]" to "DEADEND" and "GOAL" in end conditions. import copy as cp DCT = {...} # You already know what goes here. FOUND_PATHS = [] # In case of more than one path to GOAL. FOUND_REVERSE_PATHS = [] COUNTER = len(DCT) def back_track(root, target_path = [], counter=COUNTER): """ @param root: DCT key. @type root: str. @param target_path: Reference to the path we are constructing. @type target_path: list. """ global FOUND_PATHS # Avoiding cycles. if counter == 0: return # Some nodes aren't full generated. try: DCT[root] except KeyError: return # End condition. if DCT[root] == ['DEADEND']: return # Path found. if DCT[root] == ['GOAL']: FOUND_PATHS.append(target_path) # The normal path. reverse_path = cp.copy(target_path) reverse_path.reverse() FOUND_REVERSE_PATHS.append(reverse_path) # The path you want. return for node in DCT[root]: # Makes copy of target parh and add the node. path_copy = cp.copy(target_path) path_copy.append(node) # Call back_track with current node and the copy # of target_path. back_track(node, path_copy, counter=(counter - 1)) if __name__ == '__main__': back_track('4345092') print(FOUND_PATHS) print(FOUND_REVERSE_PATHS)
Django: Failing at creating tables Question: I can't change my models and create new tables if the old ones are deleted. I am using south and when I just added a new model to my models and created a new one, I used python manage.py migrate logins --fake Running migrations for logins: - Nothing to migrate. - Loading initial data for logins. Installed 0 object(s) from 0 fixture(s) Liubous-MacBook-Pro:Django_project_for_EGG yudasinal1$ python manage.py syncdb Syncing... Creating tables ... Installing custom SQL ... Installing indexes ... Installed 0 object(s) from 0 fixture(s) Synced: > django.contrib.admin > django.contrib.auth > django.contrib.contenttypes > django.contrib.sessions > django.contrib.messages > django.contrib.staticfiles Not synced (use migrations): - logins - south (use ./manage.py migrate to migrate these) Then I said: python manage.py migrate logins Running migrations for logins: - Nothing to migrate. - Loading initial data for logins. Installed 0 object(s) from 0 fixture(s) Nothing was actually changed and created, as when I accessed admin, it was written, that the table does not exist. So I decided to delete my database and create a new one, that failed as well: python manage.py sql logins BEGIN; CREATE TABLE "logins_department" ( "id" integer NOT NULL PRIMARY KEY, "name" varchar(200) NOT NULL ) ; CREATE TABLE "logins_game" ( "id" integer NOT NULL PRIMARY KEY, "name_of_the_game" varchar(200) NOT NULL ) ; CREATE TABLE "logins_info_game" ( "id" integer NOT NULL PRIMARY KEY, "info_id" integer NOT NULL, "game_id" integer NOT NULL REFERENCES "logins_game" ("id"), UNIQUE ("info_id", "game_id") ) ; CREATE TABLE "logins_info_department" ( "id" integer NOT NULL PRIMARY KEY, "info_id" integer NOT NULL, "department_id" integer NOT NULL REFERENCES "logins_department" ("id"), UNIQUE ("info_id", "department_id") ) ; CREATE TABLE "logins_info" ( "id" integer NOT NULL PRIMARY KEY, "organization_name" varchar(200) NOT NULL, "user_name" varchar(200) NOT NULL, "password" varchar(200) NOT NULL ) ; CREATE TABLE "logins_customuser_department" ( "id" integer NOT NULL PRIMARY KEY, "customuser_id" integer NOT NULL, "department_id" integer NOT NULL REFERENCES "logins_department" ("id"), UNIQUE ("customuser_id", "department_id") ) ; CREATE TABLE "logins_customuser_game" ( "id" integer NOT NULL PRIMARY KEY, "customuser_id" integer NOT NULL, "game_id" integer NOT NULL REFERENCES "logins_game" ("id"), UNIQUE ("customuser_id", "game_id") ) ; CREATE TABLE "logins_customuser" ( "user_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "auth_user" ("id") ) ; COMMIT; python manage.py syncdb Syncing... Creating tables ... Installing custom SQL ... Installing indexes ... Installed 0 object(s) from 0 fixture(s) Synced: > django.contrib.admin > django.contrib.auth > django.contrib.contenttypes > django.contrib.sessions > django.contrib.messages > django.contrib.staticfiles Not synced (use migrations): - logins - south (use ./manage.py migrate to migrate these) Liubous-MacBook-Pro:Django_project_for_EGG yudasinal1$ python manage.py schemamigration south --initial + Added model south.MigrationHistory Created 0003_initial.py. You can now apply this migration with: ./manage.py migrate south I migrated them(error again): python manage.py migrate south Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 285, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/South-0.8-py2.7.egg/south/management/commands/migrate.py", line 111, in handle ignore_ghosts = ignore_ghosts, File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/South-0.8-py2.7.egg/south/migration/__init__.py", line 200, in migrate_app applied_all = check_migration_histories(applied_all, delete_ghosts, ignore_ghosts) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/South-0.8-py2.7.egg/south/migration/__init__.py", line 79, in check_migration_histories for h in histories: File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 96, in __iter__ self._fetch_all() File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 854, in _fetch_all self._result_cache = list(self.iterator()) File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 220, in iterator for row in compiler.results_iter(): File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py", line 710, in results_iter for rows in self.execute_sql(MULTI): File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py", line 781, in execute_sql cursor.execute(sql, params) File "/Library/Python/2.7/site-packages/django/db/backends/util.py", line 69, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/Library/Python/2.7/site-packages/django/db/backends/util.py", line 53, return self.cursor.execute(sql, params) File "/Library/Python/2.7/site-packages/django/db/utils.py", line 99, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Library/Python/2.7/site-packages/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) File "/Library/Python/2.7/site-packages/django/db/backends/sqlite3/base.py", line 450, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: south_migrationhistory And so none of the tables were actually created. Here are my models: from django.db import models from django.contrib.auth.models import User, UserManager class Department(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class Game(models.Model): name_of_the_game = models.CharField(max_length=200) def __unicode__(self): return self.name_of_the_game class Info(models.Model): organization_name = models.CharField(max_length=200) user_name = models.CharField(max_length=200) password = models.CharField(max_length=200) game = models.ManyToManyField(Game) department = models.ManyToManyField(Department) def __unicode__(self): return self.organization_name+ ': '+ 'user name: ' +self.user_name+ ', '+ 'password: ' + self.password class CustomUser(User): department = models.ManyToManyField(Department) game = models.ManyToManyField(Game) objects = UserManager() Answer: This command is wrong: `python manage.py schemamigration south --initial` `schemamigration` creates files that describe the migration. South already ships its own migration files with the release. What you need is to create the migrations for your own app: `python manage.py schemamigration logins --initial` Then, I would reinstall south, just it case it broke when you created that migration: `pip uninstall south && pip install south` **EDIT** A pip uninstall doesn't remove that migration so you need to delete those files manually: `rm -rf /<OS dependent>/python2.7/site-packages/south` Finally apply the migrations: `python manage.py syncdb && python manage.py migrate`
Sympy integrate() does not produce output in the natural form of the common fraction Question: This code is taken from the Sympy tutorial: init_printing(use_unicode=False, wrap_line=False, no_global=True) x = Symbol('x') r = integrate(x**2 + x + 1, x) print(r) The output is: `x**3/3 + x**2/2 + x` It's correct, but in [tutorial](http://docs.sympy.org/dev/modules/integrals/integrals.html) the output was: 3 2 x x -- + -- + x 3 2 How can I reach this form of output? _If necessary:**IDE** is pyCharm, **python ver.** is 3.3_ Answer: You need a pretty printer `pprint` instead of normal `print`. Refer the Sympy Tutorial section [Printing](http://docs.sympy.org/0.7.0/tutorial.html#printing) >>> from sympy import * >>> init_printing(use_unicode=False, wrap_line=False, no_global=True) >>> x = Symbol('x') >>> r = integrate(x**2 + x + 1, x) >>> print(r) x**3/3 + x**2/2 + x >>> pprint(r) 3 2 x x -- + -- + x 3 2 **Note** For non string objects, [print statement](http://docs.python.org/2/reference/simple_stmts.html#the-print- statement) (Python 2.X) or the [print function](http://docs.python.org/2/library/functions.html#print) (Python 3.X) converts the object to string using the [rules for string conversion](http://docs.python.org/2/library/functions.html#str).
Import error when importing python file from same directory Question: I have the identical problem to the question posed here: [Django custom form ImportError even though file is in the same directory](http://stackoverflow.com/questions/20029305/django-custom-form- importerror-even-though-file-is-in-the-same-directory) This is from my urls.py in a django application: import bulkEdit ... ... urlpatters = patterns('', url(r'^engine/$', component_views.engine, name='engine'), ... url(r'^admin/', include(bulkEdit.urls)), My bulkEdit.py file is in the same directory as urls.py. The error I get is File "/home/context/work/riot/src/venv/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) ImportError: No module named bulkEdit I get the same error if I try from bulkEdit import urls as bulkEditUrls ... ... urlpatters = patterns('', url(r'^engine/$', component_views.engine, name='engine'), ... url(r'^admin/', include(bulkEditUrls)), bulkEdit is a file in the same directory as my urls.py file; file structure is Rapier |-component | |-__init__.py | |-admin.py | |-forms.py | |-models.py | |-views.py | |-Chassis | |-__init__.py | |-urls.py | |-bulkEdit.py | |-settings.py | |-views.py | |-manage.py here is what I have tried so far (In all of these cases, `'Chassis'` is in `INSTALLED_APPS`): Using Python 2.7, so I get a syntax error with import .bulkEdit I've also tried: url(r'^admin/', include(Chassis.bulkEdit.urls)), gives me `NameError: name 'Chassis' is not defined` url(r'^admin/', include("Chassis.bulkEdit.urls")), gives me `ImportError: No module named urls` url(r'^admin/', include("Chassis.bulkEdit")), gives me `ImproperlyConfigured: The included urlconf <module 'Chassis.bulkEdit' from '/home/userag/work/project/src/project/Chassis/bulkEdit.pyc'> doesn't have any patterns in it` url(r'^admin/', include(Chassis.bulkEdit)), gives me `NameError: name 'Chassis' is not defined` When I have import bulkEdit ... test = url(r'^admin/', include(bulkEdit.urls)) I get no error as long as it is not in the urlpatterns. When I add `test` to `urlpatterns` urlpatterns = patterns('', url(r'^engine/$', component_views.engine, name='engine'), ... test I get the error. Is there somewhere else I need to import bulkEdit due to me doing things with admin forms? Answer: Try relative import: from .bulkEdit import urls as bulkEditUrls
unicode error when importing csv file Question: i am using google app engine to import a csv file and insert it into a database but its giving me this error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xf0' in position 3: ordinal not in range(128) the file i'm importing is utf-8 the python code is utf-8 heres the form: site = "order" scripts = "" content = """ <div class="row" style="margin-top: 10px;"> <div class="large-12 columns"> <form enctype="multipart/form-data" method="post" action="import"> <select name="db"> <option value="users">Users</option> <option value="machines">Machines</option> <option value="company">Company</option> <option value="process">Order</option> <option value="status">Status</option> <option value="part">Part</option> <option value="machineType">Machine Type</option> <select> <input name="file" type="file"> <input type="submit" value="submit" class="button"> </form> </div> </div> """ template_values = { 'site': site, 'scripts': scripts, 'content': content, } template = JINJA_ENVIRONMENT.get_template('main.html') self.response.write(template.render(template_values)) And here is the post class: reader = csv.reader(StringIO.StringIO(self.request.get('file').decode('utf-8'))), database = self.request.get('db') for row in reader: for item in row: tiles = item[0].replace('&comma', ',').split(';') x = machineType( Description = tiles[0], ID = tiles[1], Brand = tiles[2], Type = tiles[3]) x.put() self.response.write("Row imported [" + tiles[0] + ", " + tiles[1] + ", " + tiles[2] + ", " + tiles[3] + "]</br>" ) Answer: This should work - `self.request.get('file').decode('utf-8').encode('ascii', 'ignore')`
Google App Engine has suddenly stopped working, with error 'you are likely missing the Python "PIL" module' Question: I've been developing apps on GAE (with Windows/Python) for over a year and although I'm no expert, I've always been able to get the apps to run! The app I'm currently working on was working fine on the localhost at lunchtime today. Without making any changes, I've come to it this evening and the app won't run in the App Engine launcher, comes up with a warning triangle when I try and gives the following in the log: INFO 2013-12-03 23:46:06,766 devappserver2.py:557] Skipping SDK update check. WARNING 2013-12-03 23:46:06,776 api_server.py:317] Could not initialize images API; you are likely missing the Python "PIL" module. Traceback (most recent call last): File "C:\Program Files (x86)\Google\google_appengine\dev_appserver.py", line 184, in <module> _run_file(__file__, globals()) File "C:\Program Files (x86)\Google\google_appengine\dev_appserver.py", line 180, in _run_file execfile(script_path, globals_) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 727, in <module> main() File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 720, in main dev_server.start(options) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 685, in start default_gcs_bucket_name=options.default_gcs_bucket_name) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\api_server.py", line 349, in setup_stubs simple_search_stub.SearchServiceStub(index_file=search_index_path)) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\api\search\simple_search_stub.py", line 607, in __init__ self.Read() File "C:\Program Files (x86)\Google\google_appengine\google\appengine\api\search\simple_search_stub.py", line 1020, in Read read_indexes = self._ReadFromFile() File "C:\Program Files (x86)\Google\google_appengine\google\appengine\api\search\simple_search_stub.py", line 994, in _ReadFromFile version, indexes = pickle.load(open(self.__index_file, 'rb')) EOFError 2013-12-03 23:46:06 (Process exited with code 1) I have tried running the Hello, World app as I know it was working fine before, as well as several other apps that I have developed which were all previously working fine, and all throw the same error. I just don't really understand what could have changed in the meantime. Any light that anyone can shed would be gratefully received! Answer: Forget about the PIL bit it's just a warning You need to read the stacktrace and the last line is the most important `File "C:\Program Files (x86)\Google\google_appengine\google\appengine\api\search\simple_search_stub.py", line 994, in _ReadFromFile version, indexes = pickle.load(open(self.__index_file, 'rb')) EOFError` From this is it tells me the search service can not open an index file and can't be started. Have you upgraded the SDK, moved something. I suggest you set the search indexes path explicitly and or clear the indexes. See command line --search_indexes_path SEARCH_INDEXES_PATH path to a file used to store search indexes (defaults to a file in --storage_path if not set) (default: None) --clear_search_indexes [CLEAR_SEARCH_INDEXES] clear the search indexes (default: False)`
urllib2.urlopen error on Box API - can't convert to proper string Question: I am trying to send a POST to the Box API but am having trouble with sending it through Python. It works perfectly if I use curl: curl https://view-api.box.com/1/sessions \ -H "Authorization: Token YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"document_id": "THE_DOCUMENT_ID", "duration": 60}' \ -X POST But with my python code I get a `HTTP Error 400: BAD REQUEST` headers = {'Authorization' : 'Token '+view_api_key, 'Content-Type' : 'application/json'} session_data = {"document_id" : doc_id, "duration": 60} session_data = urllib.urlencode(session_data) session_request = urllib2.Request("https://view-api.box.com/1/sessions", session_data, headers) session_response = urllib2.urlopen(session_request) The problem lies in my `session_data`. It needs to be a buffer in the standard application/x-www-form-urlencoded format (<http://docs.python.org/2/library/urllib2.html>), so I do a `urlencode`, however the output is `'duration=60&document_id=MY_API_KEY'`, which does not preserve { } format. Any ideas? Answer: For the View API (and the Content API), the body data, `session_data` in your code, needs to be encoded as [JSON](https://en.wikipedia.org/wiki/JSON). All you need to do is import the json module at the beginning of your code (i.e. `import json`) and then change session_data = urllib.urlencode(session_data) to session_data = json.dumps(session_data) dumps() converts the python dict into a JSON string. (as a sidenote, I would _highly_ recommend not using urllib and using the [Requests](http://www.python-requests.org/en/latest/) library instead.)
getting error in pos_tag using nltk in python Question: i am trying to `import nltk library` but getting error while using `nltk.pos_tag` nltk.pos_tag(y) Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> nltk.pos_tag(y) File "C:\Python27\lib\site-packages\nltk\tag\__init__.py", line 99, in pos_tag tagger = load(_POS_TAGGER) File "C:\Python27\lib\site-packages\nltk\data.py", line 605, in load resource_val = pickle.load(_open(resource_url)) ImportError: No module named numpy.core.multiarray Answer: You need numpy module and it seems you don't have it installed. If you read the steps of how to [install](http://nltk.org/install.html) nltk you can see that you need numpy.
Python. i need help programming Question: I am trying to write a program that i can enter text in to, then it will display the numbers that each letter in a sentence represents. eventually. i would like to be able to input a sentence and have it change it to "giberish". sort of like an encoder or something. any thoughts. a = 1 b = 2 c = 3 d = 4 e = 5 f = 6 g = 7 h = 8 i = 9 j = 10 k = 11 l = 12 m = 13 n = 14 o = 15 p = 16 q = 17 r = 18 s = 19 t = 20 u = 21 v = 22 w = 23 x = 24 y = 25 z = 26 text = eval(input("message: ")) print(text) Answer: import re numbers = map(ord, 'your message here') strNumber = map(lambda x:"%03d"%x, numbers) print ''.join(strNumber) # Output: 121111117114032109101115115097103101032104101114101 # Reverse: Decoding strNumber = re.findall(r"\d\d\d", "121111117114032109101115115097103101032104101114101") numbers = map(int, strNumber) chars = map(chr, numbers) print ''.join(chars) 1. Apply ord() on every character of the message to get ASCII value of character <http://docs.python.org/2/library/functions.html#ord> and <http://docs.python.org/2/library/functions.html#map> 2. Convert every number into a char-length 3 string 3. Merge all 3-char-length sub-strings to get encoded string # Another way of doing same thing: message = 'Your message here' codedMsg = '' for character in message: codedMsg = '%s%03d'%(codedMsg, ord(character)) print codedMsg
Changing python version in Maya Question: I am trying to update my Maya python version from 2.5 to 2.7. But I am having problems with it. I have followed the steps in this response: [How do I change the python version in Maya 2013?](http://stackoverflow.com/questions/14656593/how-do-i-change-the-python- version-in-maya-2013/14706115#14706115) Which seems very straight forward. The problem is that it is not working for me. I follwed this set of steps precisely: <http://acaciaecho.wordpress.com/2011/01/11/choose-python-inside-maya/> I had no problem at all doing what was explaind. The issue is that when I write the below in Maya the old version of python is still being recognized: import sys print sys.version The explanation does mention that they had the same issue occur but it doesn't really say how to correct it. It just says to check the paths which I did by writing this: print sys.path Which shows me one path being that of the old version of python (and many pointing to the new version). So I am guessing that one path needs to be changed. But how? Does anyone know how I can fix this issue? Answer: The link to the site you have there walks you through it pretty well however it misses a few key steps, I think, it's been a while since I've done this. I got it working with my Maya 2013 and python 2.7, which is indeed different from Maya's, regardless..it can be simplified to just creating a PYTHONHOME variable and setting it to the version of Python you want, i.e. C:\Python27. Then set your PYTHONPATH to $PYTHONPATH;C:\Program Files\Autodesk\MayaVersion\Python\DLLs;C:\Program Files\Autodesk\MayaVersion\Python\Lib\site-packages. You have to make sure to point python to Maya Python's DLLs and of course it's site-packages so that the interpreter can run properly and pymel and maya modules can be accessed. Let me know if that helped you out! :)
Exception display to the right of Command Line for PyQt/PySide callbacks/slots in Autodesk Maya Question: **Updated: to make it much clearer.** In the following code snippets, making use of Maya widgets through `pymel`, there is an error highlight on the right of Command Line. import pymel.core as pm def raiseError(): pm.select("ooxx") # ooxx doesn't exist print "Something after the exception." class pymelWindow(object): def __init__(self): self.mainWin = pm.window("test") with self.mainWin: mainForm = pm.formLayout() with mainForm: btn = pm.button(label='show error',command=pm.Callback(raiseError)) mainForm.redistribute() def show(self): self.mainWin.show() win = pymelWindow() win.show() Here attached is an snapshot of Maya 2011 (the same issue in Maya2014) with an error highlight (**in red**). ![Maya with error highlight to the right of Command Line.](http://i.stack.imgur.com/FKV2g.jpg) and here is the Stack Trace: # Error: Maya Node does not exist: u'ooxx' # Traceback (most recent call last): # File "/usr/autodesk/maya2014-x64/lib/python2.7/site-packages/pymel/internal/factories.py", line 778, in callback # res = origCallback( *newargs ) # File "/usr/autodesk/maya2014-x64/lib/python2.7/site-packages/pymel/internal/factories.py", line 701, in __call__ # return self.func(*self.args, **self.kwargs) # File "/dept/rdworks/drake/Desktop/pyqt_issues/testPyQtSpitError.py", line 119, in raiseError # pm.select("ooxx") # File "/usr/autodesk/maya2014-x64/lib/python2.7/site-packages/pymel/core/general.py", line 151, in select # raise TypeError, msg # MayaNodeError: Maya Node does not exist: u'ooxx' # However, when I switch to use PyQt/PySide for widgets with the following code snippets, there is no any visible _error highlight to the right of Command Line_! Does anyone know how to make PyQt/PySide version have the same GUI behaviours? import pymel.core as pm from PyQt4 import QtGui def raiseError(): pm.select("ooxx") # ooxx doesn't exist print "Something after the exception." class pyQtWindow(QtGui.QMainWindow): def __init__(self, parent = None): # init our ui using the MayaWindow as parent super(pyQtWindow, self).__init__(parent) self.centralWidget = QtGui.QWidget(self) self.setCentralWidget(self.centralWidget) self.centralLayout = QtGui.QVBoxLayout() self.centralWidget.setLayout(self.centralLayout) self.errorBtn = QtGui.QPushButton('show error') self.errorBtn.clicked.connect(raiseError) self.centralLayout.addWidget(self.errorBtn) win = pyQtWindow() win.show() ![Maya without error highlight to the right of Command Line!](http://i.stack.imgur.com/1YNKl.jpg) # Traceback (most recent call last): # File "/usr/autodesk/maya2014-x64/lib/python2.7/site-packages/pymel/internal/factories.py", line 701, in __call__ # return self.func(*self.args, **self.kwargs) # File "/dept/rdworks/drake/Desktop/pyqt_issues/testPyQtSpitError.py", line 119, in raiseError # pm.select("ooxx") # File "/usr/autodesk/maya2014-x64/lib/python2.7/site-packages/pymel/core/general.py", line 151, in select # raise TypeError, msg # pymel.core.general.MayaNodeError: Maya Node does not exist: u'ooxx' Answer: If you are using PyQt/PySide then the default behavior upon getting an exception wont display the error in red. I have no idea _why_ nor do I know of any switch which does that. In order the achieve that you'd have to change the `raiseError` function to something like this: def raiseError(): import maya.OpenMaya as om import traceback as tb import sys try: pm.select("ooxx") # ooxx doesn't exist except Exception as exc: msg = "".join(tb.format_exception(*sys.exc_info())) # or any custom msg om.MGlobal.displayError(msg) finally: print "Something after the exception." This way you'll get the red error display.
TypeError: 'NoneType' object has no attribute '__getitem__' Question: Hi So I created this function called runloopg(x,y,z) that produces a list but I can't call an item on the list: p=runloopg(10,0.1,6) <generator object rtpairs at 0x000000000BAF1F78> [(0,0,0,0,0,1), (0.01,0,0,0,0,1), (0.0062349,0.00781831,0,0,0,1), (-0.00222521,0.00974928,0,0,0,1), (-0.00900969,0.00433884,0,0,0,1), (0.0549583,-0.0712712,0,0,0,1), (0.0627244,-0.0645419,0,0,0,1), (0.0696727,-0.0569711,0,0,0,1), (0.0757128,-0.0486577,0,0,0,1), (0.0807659,-0.0397099,0,0,0,1), (0.084766,-0.0302444,0,0,0,1), (0.0876611,-0.0203847,0,0,0,1), (0.0894134,-0.0102592,0,0,0,1)] However when I call an item on my list as so: p[0] --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-240-a69904524460> in <module>() ----> 1 p[0] TypeError: 'NoneType' object has no attribute '__getitem__' This is the code for runloopg: import numpy import raytracer29 def rtpairs(R, N): for i in range(len(R)): r=R[i] n=N[i] for j in range(n): t = j*2*numpy.pi/n yield r,t def rtuniform(n, rmax, m): R=numpy.arange(0,rmax,rmax/n) N=numpy.arange(1, n*m, m) return rtpairs(R, N) def runloopg(n, rmax, m): #print rtuniform(n, rmax, m) bund = [] for r,t in rtuniform(n, rmax, m): myRay = raytracer29.Ray(r * numpy.cos(t), r * numpy.sin(t),0,0,0,1) bund.append(myRay) return bund Answer: You didn't post the relevant code - your function's definition - but very obviously this function returns `None`. **edit:** Ok from the snippet you posted `runloopg` does indeed return a list so the problem is elsewhere. I see that your snippet starts with a commented out `print` statement printing the return value of a call to `rtuniform`, and this matches what you posted of your interactive session. My guess is that you were executing an older version of the function that just printed and exited immediatly (implicitely returning `None`), then you edited your code but failed to properly reload your function.
Explicitly creating a new object in Python Question: I am trying to create new objects and store them in a dictionary. But it doesn't seem to be working the way I expect. class Fruit: name = '' facts = [] def __init__(self, FruitName): self.name = FruitName facts = [] def addfact(self, FruitName): if FruitName == 'banana': self.facts.append('bananas contain potassium') elif FruitName == 'orange': self.facts.append('These are some facts about oranges') else: self.facts.append('Unrecognized fruit submitted') Files = ['banana', 'orange', 'apple'] ObjLibrary = {} for File in Files: if not File in ObjLibrary: ObjLibrary[File] = Fruit(File) ObjLibrary[File].addfact(File) print ObjLibrary['banana'].facts print ObjLibrary['orange'].facts print ObjLibrary['apple'].facts I get the following output: ['bananas contain potassium', 'These are some facts about oranges', 'Unrecognized fruit submitted'] ['bananas contain potassium', 'These are some facts about oranges', 'Unrecognized fruit submitted'] ['bananas contain potassium', 'These are some facts about oranges', 'Unrecognized fruit submitted'] Now I suspect what's going on is that I'm not explicitly creating three objects the way I want, but just pointing all three items in the dictionary to the same object. My question is: why? On each pass of the loop, `File` should have a different value. More importantly, how to I get around it? In my "real" code, it's not practical to create a totally new variable to store each object. Thanks for your help. Casey Answer: The problem is that `facts` is a class variable, not an instance one. You should define it inside `__init__` (and remove the useless local variable declaration there): class Fruit: def __init__(self, FruitName): self.name = FruitName self.facts = [] def addfact(self, FruitName): ... Note Python is not Java, there is no need to "declare" attributes at the class level.
Importing a Flask-security instance into my views module breaks my webapp Question: I'm writing the sign up/sign in system for a ecommerce site, and using flask- security (<http://pythonhosted.org/Flask-Security/>) to handle the signup feature. Part of the basic setup requires the following signup.py module: from flask.ext.security import SQLAlchemyUserDatastore, Security from app.models import User, Role from app import app, db # Setup Flask Security user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) I then have to import the user_datastore and security objects into my views.py module as follows: from app.signup import user_datastore, security The thing is, as soon as I include the above import statement into my views module, my whole app crashes, and I get the following traceback error when I try to run my unit or behavior tests (edited for readability) ====================================================================== ERROR: Failure: AttributeError ('_FakeSignal' object has no attribute 'connect_via') ---------------------------------------------------------------------- Traceback (most recent call last): File "/Library/Python/2.7/site-packages/nose/loader.py", line 413, in loadTestsFromName addr.filename, addr.module) File "/Library/Python/2.7/site-packages/nose/importer.py", line 47, in importFromPath return self.importFromDir(dir_path, fqname) File "/Library/Python/2.7/site-packages/nose/importer.py", line 94, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/Users/faiyamrahman/programming/Python/WebApps/NibsNWhiskeyFull/tests/test_database.py", line 6, in <module> from app import app, db, models File "/Users/faiyamrahman/programming/Python/WebApps/NibsNWhiskeyFull/app/__init__.py", line 9, in <module> from app import views, models File "/Users/faiyamrahman/programming/Python/WebApps/NibsNWhiskeyFull/app/views.py", line 7, in <module> from app.signup import user_datastore File "/Users/faiyamrahman/programming/Python/WebApps/NibsNWhiskeyFull/app/signup.py", line 7, in <module> security = Security(app, user_datastore) File "/Users/faiyamrahman/programming/Python/WebApps/NibsNWhiskeyFull/flask/lib/python2.7/site-packages/flask_security/core.py", line 346, in __init__ self._state = self.init_app(app, datastore, **kwargs) File "/Users/faiyamrahman/programming/Python/WebApps/NibsNWhiskeyFull/flask/lib/python2.7/site-packages/flask_security/core.py", line 368, in init_app identity_loaded.connect_via(app)(_on_identity_loaded) AttributeError: '_FakeSignal' object has no attribute 'connect_via' I have no idea what this means. I've tried reading the flask-security documentation, but I don't understand why it's happening. Thanks to anyone who takes a stab at this! Answer: **Short Answer:** You are missing [blinker](https://pypi.python.org/pypi/blinker) library. **EDIT** : You confirmed that your virtual environment could not find blinker and you re- installed it. **Long Answer:** I think the error is coming from [Flask Signals](https://github.com/mitsuhiko/flask/blob/master/flask/signals.py). Look at this code from signals: signals_available = False try: from blinker import Namespace signals_available = True except ImportError: class Namespace(object): def signal(self, name, doc=None): return _FakeSignal(name, doc) So I think that the code tries to find the `blinker` library and in your case, it is not able to import it and hence it tries to use the `_FakeSignal` class. The `_FakeSignal` class does not have a `connect_via` attribute defined as you can see below class _FakeSignal(object): """If blinker is unavailable, create a fake class with the same interface that allows sending of signals but will fail with an error on anything else. Instead of doing anything on send, it will just ignore the arguments and do nothing instead. """ def __init__(self, name, doc=None): self.name = name self.__doc__ = doc def _fail(self, *args, **kwargs): raise RuntimeError('signalling support is unavailable ' 'because the blinker library is ' 'not installed.') send = lambda *a, **kw: None connect = disconnect = has_receivers_for = receivers_for = \ temporarily_connected_to = connected_to = _fail del _fail The `connect_via` attribute that Flask-Security is trying to load is actually provided by the `blinker` library and since no blinker, no connect_via. Hence it fails. So you should install blinker first. However, I think that Flask-Security code should also check for `blinker` before trying to use `connect_via`.
python 2.7's logging.info(string) and newline characters Question: Does python 2.7's logging.info(string) (import logging) automatically strip newline characters from the given string? If not, is there a command to make it behave like that? If so which command is that? Thank's a lot! Answer: No, it will not automatically strip newlines. You can remove them yourself by calling the `.replace()` method of the string: without_newlines = my_string.replace("\n", "") (Another, slightly more potentially efficient option is to use the deletion feature of `.translate()`, but `.replace()` may be more readable if you don't care about high levels of optimization.)
Printing out a random string (Python) Question: I am asked to produce a random string using a previously defined value. THREE_CHOICES = 'ABC' FOUR_CHOICES = 'ABCD' FIVE_CHOICES = 'ABCDE' import random def generate_answers(n: int) -> str: '''Generates random answers from number inputted ''' for i in range(0,n): return random.choice(FOUR_CHOICES) continue What I am trying to get happening here is, if I were to plug in 7 into the function I'd get something like "ABDCBBA" A random 7 character string from the specified letters. However, this code is returning only one random character no matter what number I put in (has to be non-zero). I don't know what to do here, can someone point me in the right direction? Answer: you could just return a list like this: def generate_answers(n): '''Generates random answers from number inputted ''' randoms = [random.choice(FOUR_CHOICES) for _ in range(0,n)] return randoms #return ''.join(randoms) to get string print generate_answers(7) this would print a list like this: `['D', 'D', 'D', 'B', 'A', 'A', 'C']` you could `join` the list if you want a string
ImportError: No module named tis_class Question: I've a Python3 script, normally works great. But I've this module error message in line 5 : pi@raspberrypi ~ $ python3 ScriptCompteur.py Traceback (most recent call last): File "ScriptCompteur.py", line 5, in <module> import tis_class as TIS ImportError: No module named tis_class Can you help me ? Below a part of the script : import requests import json import time import serial import tis_class as TIS #variables portserie='/dev/ttyUSB0' baudrate=9600 timeout_serial=2 temps_attente=10 #30 secondes periode=15 #mesure de l'information pendant cette periode sense_key="4bgd5Q8_6Oc4V8m2eDK_0g" sense_url="http://api.sen.se/events/" sense_head={'Content-type': 'application/json', 'sense_key':sense_key} sense_feed=26341 stick=TIS.TeleInfo(portserie,baudrate,timeout_serial) #initialisation minute_debut=time.strftime('%M') ... ... Answer: It didn't find the module `tis_class`. As this doesn't seem to be a commonly available library it's probably a custom module in your system. It can't be found either because it's not on the path where Python looks for modules, or because it itself imports something that has a syntax error, which in some cases gives errors like this.
How to call a Python function from Lua? Question: I want to run a python script from my lua file. How can I achieve this? Example: Python code #sum.py file def sum_from_python(a,b) return a+b Lua code --main.lua file print(sum_from_python(2,3)) Answer: Sounds like Lunatic-Python does exactly what you're looking for. There's a fork of [**lunatic-python**](https://github.com/bastibe/lunatic-python) that's better maintained than the original. I've contributed several bug fixes to it myself awhile back. So reusing your example, ### Python code: # sum.py def sum_from_python(a, b): return a + b ### Lua code: -- main.lua py = require 'python' sum_from_python = py.import "sum".sum_from_python print( sum_from_python(2,3) ) ### Outputs: lua main.lua 5 Most of the stuff works as you would expect but there are a few limitations to lunatic-python. 1. It's not really thread-safe. Using the python threading library inside lua will have unexpected behavior. 2. No way to call python functions with keyword arguments from lua. One idea is to emulate this in lua by passing a table but I never got around to implementing that. 3. Unlike lupa, lunatic-python only has one global lua state and one python VM context. So you can't create multiple VM runtimes using lunatic-python. As for lupa, note that it is a _python module_ only, which means you must use python as the host language -- it does not support the use-case where lua is the "driving" language. For example, you won't be able to use lupa from a lua interpreter or from a C/C++ application that embeds lua. OTOH, Lunatic-Python can be driven from either side of the bridge.
Import Error, When I import nltk.corpus.framenet in NLTK Python Question: I have to use framenet in nltk.corpus. So, I downloaded that corpus by using the nltk.download(). And the framenet directory is now C:\nltk_data\corpora\framenet_v15... But when I import that framenet, I can't. I can't find the reason. I want to some works as explained in here; <http://nltk.org/howto/framenet.html> >>> import nltk.corpus.framenet Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import nltk.corpus.framenet ImportError: No module named framenet Please, help me. Thanks. Answer: In your link it import as so: from nltk.corpus import framenet Have you tried that? EDIT: Version 3.0 and above of NLTK has framenet in the `nltk.corpus.reader` package, so it should be: from nltk.corpus.reader import framenet
I'm trying to time how long a key is held down using vPython Question: I'm writing a program for my physics final. Throughout the semester we have used vPython to model situations and get exact answers, etc. Our final project is to create a game using vPython that includes some type of physics. I chose to remake Bowman except with tanks. So you have a tank on the right hand of the screen and left hand of the screen with a wall in the middle. The object is to aim your cannon and shoot the right velocity to hit your opponent's tank. I have the a good chunk of the program complete however I am stuck on a few different things. First, how can I time a keystroke? I have it so I shoot from the each cannon however I want to be able to hold down a key and dependent on how long it's held down for the faster the initial velocity will be. Second, where would I incorporate gravity into the program? I have a general idea of how to but I just don't know which function to put it into. Lastly, I have a wall height being generated randomly each time the program is run. However sometimes the wall is so small you can't see it. Is there a way I can set a range of values for this? Here is my code: from visual import* from random import* scene.autoscale=False scene.width = 1500 scene.height = 800 scene.title='Tanks' def moveaup(gun): theta=arctan(gun.axis.y/gun.axis.x) dtheta=.1 if (theta<pi/2): theta=theta+dtheta if not (theta>pi/2): gun.axis=(cos(theta),sin(theta),0) else: gun.axis=vector(0,1,0) def moveadown(gun): theta=arctan(gun.axis.y/gun.axis.x) dtheta=.1 if (theta>0): theta=theta-dtheta gun.axis=(cos(theta),sin(theta),0) def movebup(gun): theta=arctan(gun.axis.y/gun.axis.x)+pi dtheta=.1 if (theta>pi/2): theta=theta-dtheta if not (theta<pi/2): gun.axis=(cos(theta),sin(theta),0) else: gun.axis=vector(0,1,0) def movebdown(gun): theta=arctan(gun.axis.y/gun.axis.x)+pi dtheta=.1 if (theta<pi): theta=theta+dtheta gun.axis=(cos(theta),sin(theta),0) def shoota(gun): vel = vector(1,1,0) bullet = sphere(pos=(gun.pos.x+gun.axis.x,gun.pos.y+gun.axis.y,0),radius=(.0785),color=color.yellow) bullet.v = vector(0,0,0) bullet.v = bullet.v+vel bulletlist.append(bullet) def shootb(gun): vel = vector(-1,1,0) bullet = sphere(pos=(gun.pos.x+gun.axis.x,gun.pos.y+gun.axis.y,0),radius=(.0785),color=color.green) bullet.v = vector(0,0,0) bullet.v = bullet.v+vel bulletlist.append(bullet) def bulletlistupdate(bulletlist): dt=.01 for a in bulletlist: a.pos=a.pos+a.v*dt def checks(agun,bgun): if scene.kb.keys: key=scene.kb.getkey() if key=='a': moveaup(agun) if key=='s': moveadown(agun) if key=='l': movebup(bgun) if key=='k': movebdown(bgun) if key=='d': shoota(agun) if key=='j': shootb(bgun) #enviroment ground = box(pos=(0,-8,0),size=(50,5,0),color=color.red) wall = box(pos=(0,-8,0),size=(.25,20*random(),0),color=color.red) #playerA abody = box(pos=(-11,-5.25,0),size=(.5,.5,0),color=color.blue) agun = cylinder(pos=(-11,-5.1,0),axis=(.8,.8,0),radius=(.08),color=color.blue) #playerB bbody= box(pos=(11,-5.25,0),size=(.5,.5,0),color=color.yellow) bgun = cylinder(pos=(11,-5.1,0),axis=(-.8,.8,0),radius=(.08),color=color.yellow) bulletlist = [] while True: rate(1000) checks(agun,bgun) bulletlistupdate(bulletlist) Any and all help is welcome! Thanks much! Answer: You can time things in python using the `time` module import time start = time.time() finish = time.time() print start # 1386269106.18 print finish # 1386269111.11 print (finish - start) # 4.9276599884 So when the player first starts pressing the button, save the time. Then save the time again when the player stops pressing the button. The difference between these two times is the number of seconds the player held the button. [Edit] If all you can do is check if the key is pressed down, you can get the time inside the main loop and calculate dt (the amount of time that has passed): t = time.time() while True: new_t = time.time() dt = new_t - t t = new_t rate(1000) checks(agun,bgun, dt) bulletlistupdate(bulletlist) Then pass dt to checks, and if the key is pressed down, you know the key has been held down for another `dt` seconds, and you can add it to your running total of time that it has been held down.
Python 3.3 GUI Program Question: Celsius to Fahrenheit-- Write a GUI program that converts Celsius temperatures to Fahrenheit temperatures. The user should be able to enter a Celsius temperature, click a button, and then see the equivalent Fahrenheit temperature. Use the following formula to make the conversion: F = 9/5C +32 F is the Fahrenheit temperature and C is the Celsius temperature. THIS IS THE CODE I HAVE SO FAR, THE ERROR I GET says "invalid literal for int() with base 10: ''" I need help getting it to run correctly. #import #main function from tkinter import * def main(): root=Tk() root.title("Some GUI") root.geometry("400x700") #someothersting="" someotherstring="" #enter Celcius L1=Label(root,text="Enter a Celcius temperature.") E1=Entry(root,textvariable=someotherstring) somebutton=Button(root, text="Total", command=convert(someotherstring)) somebutton.pack() E1.pack() L1.pack() root.mainloop()#main loop #convert Celcius to Fahrenheit def convert(somestring): thestring="" thestring=somestring cel=0 far=0 cel=int(thestring) far=(9/5*(cel))+32 print(far) Answer: Your main problem is this line; somebutton=Button(root, text="Total", command=convert(someotherstring)) ...which will call `convert(someotherstring)` immediately and assign the result to command. Since someotherstring is empty when this line is reached, it will fail to convert the value and fail the program. If you don't want it evaluated immediately but instead on button press, you can use a lambda as a command; somebutton=Button(root, text="Total", command=lambda: convert(E1.get())) ...which will eliminate the use of `someotherstring` completely and just call convert with the contents of `E1` when the button is clicked.
Python "Rock, Paper, Scissors" validation Question: I have been making a rock paper scissors game, and it works like a dream. However, when I try to add some validation in (shown with the `#`'s) my game doesn't work. I'm not sure why this is the case. My code is following: from random import randint from sys import exit computer = randint(1,3) r = "r" p = "p" s = "s" print ("The computer has chosen. Your turn") player = input ("r is Rock, p is Paper, and s is Scissors. Put your letter in HERE-----> ") #from here if (player != r or p or s): player = input ("That wasn't r, p, or s. Please try again. r is Rock, p is Paper, and s is Scissors. Put your letter in HERE-----> ") if (player != r or p or s) : print ("Can you srsly not understand that " + player + " is not r, p, or s? I give up") exit() #to here if (computer == 1): AI = ("rock") if (computer == 2): AI = ("paper") if (computer == 3): AI = ("scissors") if (player == r and computer == 1): print ("lol draw") exit() if (player == p and computer == 2): print ("lol draw") exit() if (player == s and computer == 3): print ("lol draw") exit() if (player == r and computer == 3): print ("You WIN!!!!!! AI chose " + AI) if (player == p and computer == 1): print ("You WIN!!!!!! AI chose " + AI) if (player == s and computer == 2): print ("You WIN!!!!!! AI chose " + AI) if (player == s and computer == 1): print ("You LOSE!!!!!! AI chose " + AI) if (player == r and computer == 2): print ("You LOSE!!!!!! AI chose " + AI) if (player == p and computer == 3): print ("You LOSE!!!!!! AI chose " + AI) Answer: The `or` operator again. player != r or p or s Should be player not in (r, p, s) or similar. **Explanation:** `A or B` evaluates to `A`, if `A` is considered true (truey). If `A` is considered falsy (e.g. `False`, `0`, `0.0`, `[]`, `''`), `A or B` evaluates to `B`. `player != r or p or s` is the same as `(player != r) or p or s`. Now `(player != r) or p or s` evaluates to `True` if `player != r` and to `p` otherwise. As both `True` and `p` are "truey", these two lines are equivalent: if player != r or p or s: if True:
Django Import-Export: Admin interface "TypeError at /" Question: I am trying to figure out how to use Django Import-Export, <https://pypi.python.org/pypi/django-import-export> by reading the docs <https://django-import- export.readthedocs.org/en/latest/getting_started.html#admin-integration> ## Admin Integration: The gap between the example code and its resulting photo that follows, seems to be vast for my elementary python knowledge. I have managed to code the following: geographical_system/**models.py** : from django.db import models from django.utils.translation import ugettext_lazy as _ class Regional_Units(models.Model): regional_unit = models.CharField( max_length=64, verbose_name=_(u'Regional Units')) def __unicode__(self): return u'%s' % (self.regional_unit) geographical_system/**resources.py** : from import_export import resources from geographical_system.models import Regional_Units from import_export.admin import ImportExportModelAdmin class Regional_Units_Resource(resources.ModelResource): class Meta(object): model = Regional_Units class Regional_Units_Resource_Admin(ImportExportModelAdmin): resouce_class = Regional_Units_Resource # Why originally commented out? #pass #Why pass? geographical_system/**admin.py** : from django.contrib import admin from geographical_system.models import Regional_Units from geographical_system.resources import Regional_Units_Resource_Admin admin.site.register(Regional_Units) admin.site.register(Regional_Units_Resource_Admin) # **Improvising here**, otherwise nothing would happen ## Resulting Error Of course, my improvisation `admin.site.register(Regional_Units_Resource_Admin)` resulted in the following message when visiting `http://127.0.0.1:8000/admin/geographical_system/regional_units/` TypeError at /admin/geographical_system/regional_units/ 'RenameBaseModelAdminMethods' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/admin/geographical_system/regional_units/ Django Version: 1.6 Exception Type: TypeError Exception Value: 'RenameBaseModelAdminMethods' object is not iterable Exception Location: /home/flyer/.virtualenvs/rara/lib/python2.7/site-packages/django/contrib/admin/sites.py in register, line 71 Python Executable: /home/flyer/.virtualenvs/rara/bin/python Python Version: 2.7.5 Python Path: ['/home/flyer/02/rara', '/home/flyer/.virtualenvs/rara/lib64/python27.zip', '/home/flyer/.virtualenvs/rara/lib64/python2.7', '/home/flyer/.virtualenvs/rara/lib64/python2.7/plat-linux2', '/home/flyer/.virtualenvs/rara/lib64/python2.7/lib-tk', '/home/flyer/.virtualenvs/rara/lib64/python2.7/lib-old', '/home/flyer/.virtualenvs/rara/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7', '/usr/lib/python2.7', '/usr/lib64/python2.7/lib-tk', '/home/flyer/.virtualenvs/rara/lib/python2.7/site-packages'] ## Questions * Why is this error appearing? * How could I end - up into this beautiful admin interface where Import and Export options are enabled? Answer: Although I'm not familiar with this particular app, what you should do is replace admin.site.register(Regional_Units) admin.site.register(Regional_Units_Resource_Admin) with admin.site.register(Regional_Units, Regional_Units_Resource_Admin) and if everything else is ok it should work. The admin `register()` method expects the Model as first argument and (optionally) a ModelAdmin class (or subclass) as second argument. Sidenote: since you're just starting with python/django try to comply with the conventions. This means do not use `_` between words in class Names (i.e. RegionalUnits is a suitable name) and try to place `ModelAdmin` declarations right inside the admin.py module (i.e. `RegionalUnitsResourceAdmin` should be declared in admin.py rather than being imported).
Pygame: Timer For Time Alive Question: Hello I am currently making a game in python and I am trying to make a timer which I have never attempted before, hence asking this question. What I really need to know is how to loop this small area where it says #Timer. Any help will be appreciated, thank you. import pygame, time import pygame.mixer from bullet import Bullet from constants import DIR_LEFT, DIR_RIGHT # Player class Player(pygame.sprite.Sprite): def __init__(self, x, y, gravity): pygame.mixer.init() # Player dimensions and position # Player image and animation self.images = [] self.images.append(pygame.image.load('images/Sprites/player.png')) self.images.append(pygame.image.load('images/Sprites/player2.png')) #~ self.images.append(pygame.image.load('ball1.png')) #~ self.images.append(pygame.image.load('ball2.png')) self.maxImage = len(self.images) self.currentImage = 0 self.jumpSound = pygame.mixer.Sound('sounds/jump.ogg') self.shootSound = pygame.mixer.Sound('sounds/laser.ogg') #~ self.rect = pygame.Rect(x, y, 80, 80) self.rect = self.images[0].get_rect() self.rect.x = x self.rect.y = y self.timeTarget = 10 self.timeNum = 0 self.velX = 0 self.velY = 0 self.health = 200 self.score = 0 self.alivetime = 0 self.second = 1000 self.direction = DIR_RIGHT # Jump and gravity self.jumping = False self.on_ground = False self.origJumpVel = 15 self.jumpVel = self.origJumpVel self.gravity = 0.5 # Jump inputs def do_jump(self): if self.jumping and not self.on_ground: self.velY = -self.jumpVel self.jumpVel -= self.gravity if self.on_ground: self.jumping = False self.jumpVel = self.origJumpVel self.velY = 0 self.on_ground = True def handle_events(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.jumpSound.play(0) if not self.jumping: self.jumping = True self.on_ground = False if event.key == pygame.K_s: self.shootSound.play(0) elif event.key == pygame.K_a: #pygame.transform.flip(self.images[self.currentImage], False, False) self.velX = -5 elif event.key == pygame.K_d: #pygame.transform.flip(self.images[self.currentImage], True, False) self.velX = +5 elif event.type == pygame.KEYUP: if event.key in (pygame.K_a, pygame.K_d): self.velX = 0 elif event.type == pygame.KEYUP: if event.key in (pygame.K_LEFT, pygame.K_RIGHT): bullet.velX = 0 # PLayer updates def update(self): #self.timeNum += 1 # Animations #if self.direction == DIR_LEFT: #if self.timeNum == self.timeTarget: #self.currentImage += 1 #if self.currentImage >= self.maxImage: #self.currentImage = 0 #self.timeNum = 0 # Timer if pygame.time.get_ticks() >= self.second: self.alivetime = +1 pygame.time.get_ticks() == 0 # Screen wrap if self.rect.right > 1280: self.rect.left = 0 elif self.rect.left < 0: self.rect.right = 1280 if self.velX < 0 and self.direction != DIR_RIGHT: # Moving right self.direction = DIR_RIGHT self.images[self.currentImage] = pygame.transform.flip(self.images[self.currentImage], True, False) elif self.velX > 0 and self.direction != DIR_LEFT: # Moving left self.direction = DIR_LEFT self.images[self.currentImage] = pygame.transform.flip(self.images[self.currentImage], True, False) # Player rendering def render(self, surface): surface.blit(self.images[self.currentImage], self.rect) Answer: Run `player.update()` in mainloop in every loop and Timer will loop too. **By The Way:** if you try to set tick to zero in this pygame.time.get_ticks() == 0 than you are wrong. You can't change number of ticks. Use this # __init__() self.time_to_change_alivetime = pygame.time.get_ticks() + self.second # update() if pygame.time.get_ticks() >= self.time_to_change_alivetime: self.alivetime += 1 self.time_to_change_alivetime += self.second or this (without `if`) # __init__() self.start_alivetime = pygame.time.get_ticks() # update() self.alivetime = (pygame.time.get_ticks() - self.start_alivetime) / self.second or more precisely (1 minute = 60 seconds = 60 000 milliseconds) # __init__() self.start_alivetime = pygame.time.get_ticks() # update() milliseconds = pygame.time.get_ticks() - self.start_alivetime self.alivetime_minutes = milliseconds / 60000 self.alivetime_seconds = (milliseconds % 60000) / self.second self.alivetime_milliseconds = milliseconds % self.second
Check if namedtuple with value x exists in list Question: I want to see if a namedtuple exists in a list, similar to: numbers = [1, 2, 3, 4, 5] if 1 in numbers: do_stuff() is there a pythonic (or not) way to do this? Something like: namedtuples = [namedtuple_1, namedtuple_2, namedtuple3] if (namedtuple with value x = 1) in namedtuples: do stuff() Answer: Use [`any`](http://docs.python.org/2/library/functions.html#any): **Demo:** >>> from collections import namedtuple >>> A = namedtuple('A', 'x y') >>> lis = [A(100, 200), A(10, 20), A(1, 2)] >>> any(a.x==1 for a in lis) True >>> [getattr(a, 'x')==1 for a in lis] [False, False, True]
Heroku / gunicorn / flask app says "Connection in use" Question: I have a Flask app that runs fine on local, but when I push to Heroku I get the error message: * Running on http://127.0.0.1:5000/ [INFO] Starting gunicorn 18.0 [ERROR] Connection in use: ('0.0.0.0', 8163) I tried the solution in [this question](http://stackoverflow.com/questions/16020749/heroku-app-runs-locally- but-gets-h12-timeout-error-uses-a-package), where gunicorn and werkzeug were fighting with each other, but adding a `__name__ == "__main__"` block to my master application file (`run.py`) didn't solve my error. [This SO post](http://stackoverflow.com/questions/16756624/gunicorn- connection-in-use-0-0-0-0-5000) suggested making sure my processes were all cleaned up. I did that but it still didn't work, so I actually deleted my entire heroku app and repushed and it still gives the same error. My `run.py` file looks like: #!pl_env/bin/python from app import app if __name__ == "__main__": app.run(debug=True, port=33507) # [33507 is the Flask port on Heroku] And my `Procfile` is: web: gunicorn run:app The `__init__.py` file in app is: from flask import Flask import os from flask.ext.login import LoginManager app = Flask(__name__) app.config.from_object('config') lm = LoginManager() lm.init_app(app) lm.login_view = 'login' from app import views Views has the meaty logic of the app in it, but I don't think there's anything in there that would mess with gunicorn. Here's the views.py imports just in case: from flask import Flask, render_template, flash, redirect from flask.ext.login import login_required, login_user from app import app, lm from forms import LoginForm I am definitely at a loss as to where to look now to figure out this connection error. Any thoughts on why it seems to think I'm already using `0.0.0.0`? Thank you Monica **EDIT:** I ran the app locally using `foreman start` and it worked cleanly in `0.0.0.0:5000`, so I think I'm having a Heroku problem **EDIT2:** I intentionally broke my view flow -- made an internal infinite reference -- and pushed it to see what would happen. I got the expected error logs, undid it, and pushed the rollback, and now it's working. I have absolutely no idea why that should work, except maybe that breaking it in an expected way flushed my gunicorn connections. If anyone has any explanations for this mystery, I would love them. Answer: app.run(host='0.0.0.0') might do the trick as explained [here](http://stackoverflow.com/questions/7023052/flask-configure-dev-server- to-be-visible-across-the-network)
comparing occurrence of strings in list in python Question: i'm super duper new in python. I'm kinda stuck for one of my class exercises. The question goes something like this: You have a file that contains characters i.e. words. (I'm still at the stage where all the terms get mixed up, I apologize if that is not the correct term) Example of the file.txt content: accbd The question asks me to import the file to python editor and make sure that no letter occurs more than letter that comes later than it in the alphabet. e.g. a cannot occur more frequently than b; b cannot occur more than c, and so on. In the example file, c occurs more frequently than d, so I need to raise an error message. Here's my pathetic attempt : def main(): f=open('.txt','r') # 1st import the file and open it. data = f.read() #2nd read the file words = list(data) #3rd create a list that contains every letter newwords = sorted(words) # sort according to alphabetical order I'm stuck at the last part which is to count that the former word doesn't occur more than the later word, and so on. I tried two ways but neither is working. Here's trial 1: from collections import counter for i in newwords: try: if counter(i) <=counter(i+1): print 'ok' else: print 'not ok between indexes %d and %d' % (i, i+1) except: pass The 2nd trial is similar for i in newwords: try: if newwords.count(i) <= newwords.count(i+1): print 'ok' else: print 'ok between indexes %d and %d' % (i, i+1) except: pass What is the correct way to compare the count for each word in sequential order? Answer: To be a little more clear: In [2]: string = 'accbd' In [3]: import collections In [4]: collections.Counter(string) Out[4]: Counter({'c': 2, 'a': 1, 'b': 1, 'd': 1}) Then it's just a for loop with enumerate(list_).
wxPython: binding wx.EVT_CHAR_HOOK disables TextCtrl backspace Question: I have a wx.TextCtrl and I want to be able to type in it, but also detect key presses such as UP, DOWN, RETURN, ESC. So I binded wx.EVT_KEY_DOWN to recognize any key press, and wx.EVT_CHAR_HOOK to do the same thing even when TextCtrl has focus. self.Bind(wx.EVT_KEY_DOWN, self.keyPressed) self.Bind(wx.EVT_CHAR_HOOK, self.keyPressed) Key presses UP, DOWN, RETURN, ESC were recognized and working fine, but due to binding EVT_CHAR_HOOK I cannot use LEFT RIGHT BACKSPACE SHIFT anymore when I type in the TextCtrl. Any suggestions? Answer: You should call `event.Skip()` at the end of the event handler to propagate it further. This works for me: import wx class MainWindow(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.panel = wx.Panel(self) self.text = wx.TextCtrl(self.panel) self.text.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) self.text.Bind(wx.EVT_KEY_UP, self.OnKeyUp) self.sizer = wx.BoxSizer() self.sizer.Add(self.text, 1) self.panel.SetSizerAndFit(self.sizer) self.Show() def OnKeyDown(self, e): code = e.GetKeyCode() if code == wx.WXK_ESCAPE: print("Escape") if code == wx.WXK_UP: print("Up") if code == wx.WXK_DOWN: print("Down") e.Skip() def OnKeyUp(self, e): code = e.GetKeyCode() if code == wx.WXK_RETURN: print("Return") e.Skip() app = wx.App(False) win = MainWindow(None) app.MainLoop()
cannot setup apache 2.2 with mod_wsgi and python 3.3? Question: This is error log when i'm trying to setup with Python 3.3, Apache 2.2 and use mod_wsgi-3.4.ap22.win32-py3.3.zip at <http://www.lfd.uci.edu/~gohlke/pythonlibs/> mod_wsgi (pid=4940): Target WSGI script 'C:/www/h.wsgi' cannot be loaded as Python module. mod_wsgi (pid=4940): Exception occurred processing WSGI script 'C:/www/h.wsgi'. Traceback (most recent call last):\r File "C:\\Python33\\Lib\\pkgutil.py", line 504, in find_loader\r return importlib.find_loader(fullname, path)\r File "C:\\Python33\\Lib\\importlib\\__init__.py", line 64, in find_loader\r loader = sys.modules[name].__loader__\r AttributeError: 'module' object has no attribute '__loader__'\r \r The above exception was the direct cause of the following exception:\r \r Traceback (most recent call last):\r File "C:/www/h.wsgi", line 5, in <module>\r application = Flask(__name__)\r File "C:\\Python33\\lib\\site-packages\\flask\\app.py", line 331, in __init__\r instance_path = self.auto_find_instance_path()\r File "C:\\Python33\\lib\\site-packages\\flask\\app.py", line 622, in auto_find_instance_path\r prefix, package_path = find_package(self.import_name)\r File "C:\\Python33\\lib\\site-packages\\flask\\helpers.py", line 661, in find_package\r loader = pkgutil.get_loader(root_mod_name)\r File "C:\\Python33\\Lib\\pkgutil.py", line 482, in get_loader\r return find_loader(fullname)\r File "C:\\Python33\\Lib\\pkgutil.py", line 510, in find_loader\r raise ImportError(msg.format(fullname, type(ex), ex)) from ex\r ImportError: Error while finding loader for '_mod_wsgi_293471048e599ca28a13db229cd884c8' (<class 'AttributeError'>: 'module' object has no attribute '__loader__')\r and Browser show "Internal Server Error". I don't know why because when i'm trying to setup with Python 2.7, Apache 2.2 and mod_wsgi-3.4.ap22.win32-py2.7.zip, it's OK Somebody help me, thank so much! P.s: httpd.conf settings <VirtualHost *:80> ServerName webmaster@localhost WSGIScriptAlias / C:/www/h.wsgi <Directory "C:/www"> Order allow,deny Allow from all </Directory> </VirtualHost> and my app from flask import Flask application = Flask(__name__) @application.route('/') def hello_world(): return "Hello" if __name__ == '__main__': application.run() it's work okay when i change to python 2.7 Answer: I would suggest asking about this on the #pocoo IRC channel: * <http://flask.pocoo.org/community/irc/> as that is where the Flask developers are. Flask appears dependent on the __loader__ attribute of the module under Python 3.3, but mod_wsgi doesn't currently add one. It is possible Apache/mod_wsgi needs to start adding one due to how the new module importer works, but also not sure if Flask should be tolerant of it not existing. Provides any details back here.
pyfits not working for windows 64 bit Question: I am using **windows 7 home basic 64 bit**. I wanted to work with **FITS file in python 3.3** so downloaded pyfits and numpy for 64 bit. **When I import pyfits** I get the following error: > Traceback (most recent call last): File "", line 1, in import pyfits as py > File "C:\Python33\lib\site-packages\pyfits__init__.py", line 26, in import > pyfits.core File "C:\Python33\lib\site-packages\pyfits\core.py", line 38, in > import pyfits.py3compat File "C:\Python33\lib\site- > packages\pyfits\py3compat.py", line 12, in import pyfits.util File > "C:\Python33\lib\site-packages\pyfits\util.py", line 29, in > import numpy as np File "C:\Python33\lib\site-packages\numpy__init__.py", > line 168, in from . import add_newdocs File "C:\Python33\lib\site- > packages\numpy\add_newdocs.py", line 13, in from numpy.lib import add_newdoc > File "C:\Python33\lib\site-packages\numpy\lib__init__.py", line 8, in from > .type_check import * File "C:\Python33\lib\site- > packages\numpy\lib\type_check.py", line 11, in import numpy.core.numeric as > _nx File "C:\Python33\lib\site-packages\numpy\core__init__.py", line 6, in > from . import multiarray ImportError: DLL load failed: %1 is not a valid > Win32 application. Answer: This is a problem importing numpy, not pyfits. You can tell because the traceback ended upon trying to import the numpy multiarray module. This error suggests that the numpy you have installed was not built for the same architecture as your Python installation.
How do I make stat_smooth work in ggplot-python? Question: That's my code: import pandas as pd import pandas.io.sql as sqlio from ggplot import * from db import conn sql = "SELECT * FROM history WHERE time > (NOW() - INTERVAL '1 day')::date" df = sqlio.read_frame(sql, conn) conn.close() lng = pd.melt(df[['time', 'players', 'servers']], id_vars='time') plt = ggplot(aes(x='time', y='value', colour='variable'), data=lng) + \ geom_line() + \ stat_smooth(colour='red', se=True) + \ ggtitle('Players and servers online over last 24h') + \ xlab("Time of the day") + \ ylab("Amount") ggsave(filename="day.svg", plot=plt) This is what the code generates: ![result](http://zduniak.net/wV9S6) The history table has 3 columns: * time - datetime * players - integer * servers - integer What I want is two smooth red lines drawn over black and orange ones. Somehow stat_smooth doesn't work at all. How can I make it work? Answer: Should be fixed as per these issues: <https://github.com/yhat/ggplot/pull/43> <https://github.com/yhat/ggplot/pull/170>
Python's assert_called_with, is there a wildcard character? Question: Suppose I have a class in python set up like this. from somewhere import sendmail class MyClass: def __init__(self, **kargs): self.sendmail = kwargs.get("sendmail", sendmail) #if we can't find it, use imported def def publish(): #lots of irrelevant code #and then self.sendmail(mail_to, mail_from, subject, body, format= 'html') So as you can see, I have sort of given myself the option to parameterize which function I use for self.sendmail Now in the test file. Class Tester(): kwargs = {"sendmail": MagicMock(mail_from= None, mail_to= None, subject= None, body= None, format= None)} self.myclass = MyClass(**kwargs) ##later on def testDefaultEmailHeader(): default_subject = "Hello World" self.myclass.publish() self.myclass.sendmail.assert_called() #this is doing just fine self.myclass.sendmail.assert_called_with(default_subject) #this is having issues For some reason I am getting the error message AssertionError: Expected call: mock('Hello World') Actual Call : mock('defaultmt', 'defaultmf', 'Hello World', 'default_body', format= 'html') So basically, the assert is expecting sendmail to be called with only one variable, when it ends up being called with all 5. The thing is, I don't care about what the other 4 variables are! I just want to make sure it is called with the correct subject. I tried the mock place holder ANY, and got the same thing self.myclass.sendmail.assert_called_with(ANY, ANY, 'Hello World', ANY, ANY) AssertionError: Expected call: mock(<ANY>, <ANY>, 'Hello World', <ANY>, <ANY>) Actual Call : mock('defaultmt', 'defaultmf', 'Hello World', 'default_body, 'format= 'html') Really unsure on how to proceed with this one. Anyone have any advice if we only care about one of the variable and want to ignore the rest? Answer: If you're calling `sendmail` with a named parameter `subject` then it's better to check whether the named argument matches what you expect: args, kwargs = self.myclass.sendmail.call_args self.assertEqual(kwargs['subject'], "Hello World") This does assume both implementations of `sendmail` have a named parameter called `subject`. If that's not the case you can do the same with a positional parameter: args, kwargs = self.myclass.sendmail.call_args self.assertTrue("Hello World" in args) You can be explicit about the position of the argument (i.e., the first argument or the third argument that's passed to `sendmail` but that depends on the implementation of `sendmail` being tested).
decrypt ssl encrypted data in python Question: I'm analyzing a packet capture with python using dpkt. The application layer is encrypted with ssl. I'd like to decrypt the ssl data (i.e., the tcp payload). I have the private key, so I should be able to use the key to decrypt the data. Here's my script: #!/bin/python import sys import dpkt def main(): if not len(sys.argv) == 2: print "need a pcap file" return 1 filename = sys.argv[1] f = open(filename) pcap = dpkt.pcap.Reader(f) framenum = 1 for ts, buf in pcap: if framenum == 123: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data ssl = tcp.data # decrypt ssl framenum += 1 if __name__ == '__main__': sys.exit( main() ) What can I put in place of that "decrypt ssl" comment to get the decrypted ssl bytes? I'm guessing there should be some library that can do this for me, but all my searches for ssl and python give information about writing socket programs that can receive ssl connections. I'm not interested in that. Rather, I need to decrypt data that is encrypted with ssl. Thanks! Answer: You're not likely going to find a ready-made library to do this. Decrypting from a packet dump is rather involved, and I believe the best featured tool right now is still [Wireshark](http://www.wireshark.org/). Note that you will also need to have the entire TLS session captured, from the handshake onward. Also, if the connection used an ephemeral mode which offers forward secrecy (anything with DHE or ECDHE), the data cannot be decrypted.
Scrapy SgmlLinkExtractor - Having trouble with recursively scraping Question: **Update: Apparently I can't answer my own question within 8 hours, but I got it to work. Thanks guys!** I am having trouble getting scrapy to crawl the links on the start_url. The following is my code below: from scrapy.selector import HtmlXPathSelector from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from dirbot.items import Website class mydomainSpider(CrawlSpider): name = "mydomain" allowed_domains = ["mydomain.com"] start_urls = ["http://www.mydomain.com/cp/133162",] """133162 category to crawl""" rules = ( Rule(SgmlLinkExtractor(allow=('133162', ), deny=('/ip/', ))), ) def parse(self, response): hxs = HtmlXPathSelector(response) sites = hxs.select('//html') items = [] for site in sites: item = Website() item['description'] = site.select('//meta[@name="Description"]/@content').extract() item['url'] = response.url item['title'] = site.xpath('/html/head/title/text()').extract() items.append(item) return items I am new to python and am open to any advice. Thank you for your time! Answer: I got it to work, thanks guys! from scrapy.selector import HtmlXPathSelector from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from wallspider.items import Website class mydomainSpider(CrawlSpider): name = "mydomain" allowed_domains = ["www.mydomain"] start_urls = ["http://www.mydomain/cp/133162",] rules = (Rule (SgmlLinkExtractor(allow=('133162', ),deny=('/ip/', 'search_sort=', 'ic=60_0', 'customer_rating', 'special_offers', ),) , callback="parse_items", follow= True), ) def parse_items(self, response): hxs = HtmlXPathSelector(response) sites = hxs.select('//*') items = [] for site in sites: item = Website() item['referer'] = response.request.headers.get('Referer') item['url'] = response.url item['title'] = site.xpath('/html/head/title/text()').extract() item['description'] = site.select('//meta[@name="Description"]/@content').extract() items.append(item) return items
Can't run PhantomJS in python via Selenium Question: I have been trying to run PhantomJS via selenium for past 3 days and have had no success. So far i have tried installing PhantomJS via npm, building it from source, installing via apt-get and downloading prebuilt executable and placing it in /usr/bin/phantomjs. Every time I was able to run this example script loadspeed.js : var page = require('webpage').create(), system = require('system'), t, address; if (system.args.length === 1) { console.log('Usage: loadspeed.js <some URL>'); phantom.exit(); } t = Date.now(); address = system.args[1]; page.open(address, function (status) { if (status !== 'success') { console.log('FAIL to load the address'); } else { t = Date.now() - t; console.log('Loading time ' + t + ' msec'); } phantom.exit(); }); and run it with 'phantomjs test.js <http://google.com>' and it worked just as it should. but running PhantomJS via selenium in this small python script produces errors: from selenium import webdriver browser = webdriver.PhantomJS() browser.get('http://seleniumhq.org') # python test.py Traceback (most recent call last): File "test.py", line 4, in <module> browser.get('http://seleniumhq.org/') File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 176, in get self.execute(Command.GET, {'url': url}) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 162, in execute response = self.command_executor.execute(driver_command, params) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/remote_connection.py", line 350, in execute return self._request(url, method=command_info[0], data=data) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/remote_connection.py", line 382, in _request resp = self._conn.getresponse() File "/usr/lib/python2.7/httplib.py", line 1045, in getresponse response.begin() File "/usr/lib/python2.7/httplib.py", line 409, in begin version, status, reason = self._read_status() File "/usr/lib/python2.7/httplib.py", line 373, in _read_status raise BadStatusLine(line) httplib.BadStatusLine: '' Replacing second LOC with browser = webdriver.Firefox() works fine. I am on Ubuntu 13.10 desktop and same error occurs on Ubuntu 13.04 aswell. Python: 2.7 PhantomJS: 1.9.2 What am I doing wrong here? Answer: There seems to be some issue introduced in newer Selenium, see <http://code.google.com/p/selenium/issues/detail?id=6690> I got a bit further using by using pip install selenium==2.37 Avoids the stack trace above. Still having problems with driver.save_screenshot('foo.png') resulting in an empty file though.
Empty list returned from ElementTree findall Question: I'm new to xml parsing and Python so bear with me. I'm using lxml to parse a wiki dump, but I just want for each page, its title and text. For now I've got this: from xml.etree import ElementTree as etree def parser(file_name): document = etree.parse(file_name) titles = document.findall('.//title') print titles At the moment titles isn't returning anything. I've looked at previous answers like this one: [ElementTree findall() returning empty list](http://stackoverflow.com/questions/9112121/elementtree-findall- returning-empty-list) and the lxml documentation, but most things seemed to be tailored towards parsing HTML. This is a section of my XML: <mediawiki xmlns="http://www.mediawiki.org/xml/export-0.7/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.7/ http://www.mediawiki.org/xml/export-0.7.xsd" version="0.7" xml:lang="en"> <siteinfo> <sitename>Wikipedia</sitename> <base>http://en.wikipedia.org/wiki/Main_Page</base> <generator>MediaWiki 1.20wmf9</generator> <case>first-letter</case> <namespaces> <namespace key="-2" case="first-letter">Media</namespace> <namespace key="-1" case="first-letter">Special</namespace> <namespace key="0" case="first-letter" /> <namespace key="1" case="first-letter">Talk</namespace> <namespace key="2" case="first-letter">User</namespace> <namespace key="3" case="first-letter">User talk</namespace> <namespace key="4" case="first-letter">Wikipedia</namespace> <namespace key="5" case="first-letter">Wikipedia talk</namespace> <namespace key="6" case="first-letter">File</namespace> <namespace key="7" case="first-letter">File talk</namespace> <namespace key="8" case="first-letter">MediaWiki</namespace> <namespace key="9" case="first-letter">MediaWiki talk</namespace> <namespace key="10" case="first-letter">Template</namespace> <namespace key="11" case="first-letter">Template talk</namespace> <namespace key="12" case="first-letter">Help</namespace> <namespace key="13" case="first-letter">Help talk</namespace> <namespace key="14" case="first-letter">Category</namespace> <namespace key="15" case="first-letter">Category talk</namespace> <namespace key="100" case="first-letter">Portal</namespace> <namespace key="101" case="first-letter">Portal talk</namespace> <namespace key="108" case="first-letter">Book</namespace> <namespace key="109" case="first-letter">Book talk</namespace> </namespaces> </siteinfo> <page> <title>Aratrum</title> <ns>0</ns> <id>65741</id> <revision> <id>349931990</id> <parentid>225434394</parentid> <timestamp>2010-03-15T02:55:02Z</timestamp> <contributor> <ip>143.105.193.119</ip> </contributor> <comment>/* Sources */</comment> <sha1>2zkdnl9nsd1fbopv0fpwu2j5gdf0haw</sha1> <text xml:space="preserve" bytes="1436">'''Aratrum''' is the Latin word for [[plough]], and &quot;arotron&quot; (αροτρον) is the [[Greek language|Greek]] word. The [[Ancient Greece|Greeks]] appear to have had diverse kinds of plough from the earliest historical records. [[Hesiod]] advised the farmer to have always two ploughs, so that if one broke the other might be ready for use. These ploughs should be of two kinds, the one called &quot;autoguos&quot; (αυτογυος, &quot;self-limbed&quot;), in which the plough-tail was of the same piece of timber as the share-beam and the pole; and the other called &quot;pekton&quot; (πηκτον, &quot;fixed&quot;), because in it, three parts, which were of three kinds of timber, were adjusted to one another, and fastened together by nails. The ''autoguos'' plough was made from a [[sapling]] with two branches growing from its trunk in opposite directions. In ploughing, the trunk served as the pole, one of the two branches stood upwards and became the tail, and the other penetrated the ground and, sometimes shod with bronze or iron, acted as the [[ploughshare]]. ==Sources== Based on an article from ''A Dictionary of Greek and Roman Antiquities,'' John Murray, London, 1875. ἄρατρον ==External links== *[http://penelope.uchicago.edu/Thayer/E/Roman/Texts/secondary/SMIGRA*/Aratrum.html Smith's Dictionary article], with diagrams, further details, sources. [[Category:Agricultural machinery]] [[Category:Ancient Greece]] [[Category:Animal equipment]]</text> </revision> </page> I've also tried iterparse and then printing the tag of the element it finds: for e in etree.iterparse(file_name): print e.tag but it complains about the e not having a tag attribute. EDIT: ![screenshot](http://i.stack.imgur.com/TPHkP.png) Answer: The problem is that you are not taking XML namespaces into account. The XML document (and all the elements in it) is in the `http://www.mediawiki.org/xml/export-0.7/` namespace. To make it work, you need to change titles = document.findall('.//title') to titles = document.findall('.//{http://www.mediawiki.org/xml/export-0.7/}title') The namespace can also be provided via the `namespaces` parameter: NSMAP = {'mw':'http://www.mediawiki.org/xml/export-0.7/'} titles = document.findall('.//mw:title', namespaces=NSMAP) This works in Python 2.7, but it is not explained in the [Python 2.7 documentation](http://docs.python.org/2.7/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.findall) (the [Python 3.3 documentation](http://docs.python.org/3.3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.findall) is better). See also <http://effbot.org/zone/element-namespaces.htm> and this SO question with answer: [Parsing XML with namespace in Python ElementTree](http://stackoverflow.com/q/14853243/407651). * * * The trouble with [`iterparse()`](http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.iterparse) is caused by the fact that this function provides `(event, element)` tuples (not just elements). In order to get the tag name, change for e in etree.iterparse(file_name): print e.tag to this: for e in etree.iterparse(file_name): print e[1].tag
tkinter and scrabble solver problems Question: I have had to learn python 3.3.3 for a logic and design class. I am extremely new at programming and the code below is the culmination of what ive learned on my own in 10 weeks. I had my program working fine at a procedural level with out a GUI. my program was a typical scrabble solver. I just am having a horrible time with tkinter. I need to take my input from the entry to the main module run through and input the results to a listbox. i even gave up on passing parameters from the class tot he main so i set the rack and results to a global var. I understand that this might be too much of hassle for someone to help but any help i get to get this done before finals would be greatly appreciated. thank you in advance. #only reason these are global is because im having trouble with tkinter and #passing the proper parameters to the main module global results global rack import tkinter as tk #class for GUI class application: def __init__(self): self.main=tk.Tk() #top fram includes rack label, rack entry, rack enter button and quit button self.top_frame = tk.Frame(self.main) self.main.title('Scrabble Solver') self.main.geometry('300x300') self.main.wm_iconbitmap('favicon.ico') self.racklbl = tk.Label(self.top_frame, text="Enter your rack") self.racklbl.pack() self.rackent=tk.Entry(self.top_frame) self.rackent.pack(side="left") self.rackbtn = tk.Button(self.top_frame, text = "Enter", command=self.getRackData) self.rackbtn.pack(side="left") self.top_frame.pack() #bottom frame includes listbox for results display and scrollbar self.bot_frame = tk.Frame(self.main) self.validlist = tk.Listbox(self.bot_frame, width=30) self.validlist.pack(side="left") self.scrollbar = tk.Scrollbar(self.bot_frame) self.scrollbar.pack(side="right", fill="y") self.QUIT = tk.Button(self.top_frame, text="QUIT", fg="red", command=self.main.destroy) self.QUIT.pack(side='left') self.bot_frame.pack() tk.mainloop() def showError(self): tk.messagebox.showinfo('You have entered too many letters') def getRackData(self): rack = input(self.rackent.get()) def main(): rack="" gui = application() #dictionary for the scores scores = {"A": 1, "C": 3, "B": 3, "E": 1, "D": 2, "G": 2, "F": 4, "I": 1, "H": 4, "K": 5, "J": 8, "M": 3, "L": 1, "O": 1, "N": 1, "Q": 10, "P": 3, "S": 1, "R": 1, "U": 1, "T": 1, "W": 4, "V": 4, "Y": 4, "X": 8, "Z": 10} #get the rack letters #rack = getRackLetters(gui) #call module to put file into an array rack = getRackLetters(rack,gui) putFileIntoArray(rack, scores) # function to get rack letters def getRackLetters(rack,gui): rack = rack.upper() #call function to verify number of letters entered verify= verifyRackLetters(rack) if verify == True: return rack else: gui.showError() main() #function to verify number of letters entered def verifyRackLetters(rack): if len(rack) <= 8: verify = True else: verify = False return verify #module to put file into an array def putFileIntoArray(rack, scores): words = [] file = open("dict.dat", "r") for line in file: line = line.strip() words.append(line) file.close() #call module to find and create an array of valid words then score them findValidWords(words, scores) # module to find and create an array of valid words then score them def findValidWords(words, rack, scores): valid = [] for word in words: candidate = True rack_letters = list(rack) for letter in word: if letter not in rack_letters: candidate = False else: rack_letters.remove(letter) #score the valid words and append to list if candidate == True: total = 0 for letter in word: total = total + scores[letter] valid.append([total, word]) #call module to sort and print the valid words list with scores scoreValidWords(valid) #module to sort and print the list def scoreValidWords(valid): valid.sort() for entry in valid: score = entry[0] word = entry[1] results.append(str(score) + " " + word) print(results) main() Answer: Although I removed the scrollbar ( I guess you will figure out how to add that too) I completely rewrote your code, to be more pythonic, and easier to read and write. However I tried to stick to your code as much as possible. I guess it is working now: ![enter image description here](http://i.stack.imgur.com/nGeYW.png) ![enter image description here](http://i.stack.imgur.com/syOh9.png) Here is the `dictionary.dat` I used: beast lemon ape apple sea pea orange bat And here is the code itself: # Import python modules import tkinter import tkinter.messagebox from collections import Counter # Module level constants SCORES = {'A': 1, 'C': 3, 'B': 3, 'E': 1, 'D': 2, 'G': 2, 'F': 4, 'I': 1, 'H': 4, 'K': 5, 'J': 8, 'M': 3, 'L': 1, 'O': 1, 'N': 1, 'Q': 10, 'P': 3, 'S': 1, 'R': 1, 'U': 1, 'T': 1, 'W': 4, 'V': 4, 'Y': 4, 'X': 8, 'Z': 10} class App(tkinter.Tk): def __init__(self, word_list, *args, **kwargs): # Initialize parent class by passing instance as first argument tkinter.Tk.__init__(self, *args, **kwargs) # Store values self.word_list = word_list # Setup main window self.title('Scrabble Solver') # Create widgets rack_label = tkinter.Label(self, text='Enter your rack') self.rack_entry = tkinter.Entry(self) rack_button = tkinter.Button(self, text='Enter', command=self.search) quit_button = tkinter.Button(self, text='Quit', command=self.quit) self.valid_list = tkinter.Listbox(self, width=40, font='Courier') # Place widgets rack_label.grid(row=0, column=0, sticky=tkinter.W) self.rack_entry.grid(row=1, column=0, sticky=tkinter.W) rack_button.grid(row=1, column=1, sticky=tkinter.W) quit_button.grid(row=1, column=2, sticky=tkinter.W) self.valid_list.grid(row=2, columnspan=3, sticky=tkinter.W) def run(self): # Enter event loop self.mainloop() def error(self): # Throw and error message dialog tkinter.messagebox.showinfo('You have entered too many letters!') def search(self): # Cleanup up valid list self.valid_list.delete(0, tkinter.END) # Get data of entry, and make them lower case rack = self.rack_entry.get().lower() # Check length of data if len(rack) <= 8: return self.find_valid_words(rack) self.error() def find_valid_words(self, rack): # Create a dictionary for valid words and its values valid = {} rack_chars = Counter(rack) for word in self.word_list: word_chars = Counter(word) if word_chars == word_chars & rack_chars: valid[word] = sum(SCORES[letter.upper()] for letter in word) # Sort the results and insert them into the list box if valid: for word, score in sorted(valid.items(), key=lambda v: v[1], reverse=True): self.valid_list.insert(tkinter.END, '{:<10} {}'.format(word, score)) else: self.valid_list.insert(tkinter.END, 'No results found.') if __name__ == '__main__': # Open dictionary file and scan for words with open('dictionary.dat', 'r') as f: all_words = [word for word in f.read().split()] # Create instance and call run method App(all_words).run()
Why is `poll.poll` faster than `epoll.poll`? Question: I thought `epoll` should be faster than `poll`, but when I do the following experiment, it turns out to be slower. First I set up 1 server socket with 10 client sockets connected. import socket server = socket.socket() server.bind(('127.0.0.1', 7777)) server.listen(1) clients = [socket.socket() for i in range(10)] for c in clients: c.connect(('127.0.0.1', 7777)) Then I registered all clients with both `poll` and `epoll`: import select ep = select.epoll() p = select.poll() for c in clients: p.register(c) ep.register(c) Finally I use `%timeit` in `IPython` to compare the runtime: %timeit p.poll() 1000000 loops, best of 3: 1.26 us per loop %timeit ep.poll() 1000000 loops, best of 3: 1.7 us per loop Maybe the number of sockets are still too small for `epoll` to beat `poll`, but I wonder what's in `epoll` that make it slower when there are not many sockets watched. Answer: The poll system call needs to copy your list of file descriptors to the kernel each time. This happens only once with epoll_ctl, but not every time you call epoll_wait. Also, epoll_wait is O(1) in respect of the number of descriptors watched1, which means it does not matter whether you wait on one descriptor or on 5,000 or 50,000 descriptors. poll, while being more efficient than select, still has to walk over the list every time (i.e. it is O(N) in respect of number of descriptors). And lastly, epoll can in addition to the "normal" mode work in "edge triggered" mode, which means the kernel does not need keep track of how much data you've read after you've been signalled readiness. This mode is more difficult to grasp, but somewhat more efficient.
python script for getting some columns of one excel into new one Question: ![enter image description here](http://i.stack.imgur.com/0URm9.png) I am new to Python. I have to create another Excel file from my test report Excel file. I need to create a new excel file as 'test result summery' with columns-values like `test case ID` and 'Function loop1', 'function loop2' which is result of resp test case etc from my test_report.xls (as in below image) Can anybody share some Python script for this? Answer: You can use csv lib for this. More information here: <http://docs.python.org/2/library/csv.html> You would start with something like: import csv outputfile = open('Your Desired File Name', 'wb') DataWriter = csv.writer(outputfile, delimiter=',', quotechar='|', quoting = csv.QUOTE_MINIMAL) DataWriter.writerow(['Test Case ID', 'Result']) DataWriter.writerow(#Some data that you want to add) outputfile.close() # Close the file
Get a text file specific field issue Question: I am working on python in order to use data mining on social media to analysis data . Now I have written a code which gives me information about Facebook most liked pages and I have stored information on a text file called `"pages.txt"` the following is a snapshot of my text file content : { "paging": { "next": "https://graph.facebook.com/search?limit=1&type=page&q=%26&locale=ar_AR&access_token=CAACEdEose0cBAFxVPV6lJ43O6MABoxVrrHlb01rBNmpVf8ZCK0M1QlsEJ6yRZBWlzjf0vA1eX6YdwNHF2TLZBsECdg6Q8mI3BH3n5QTMsi55KtkCtOCd36AVxjZA7PXBL3mZA6FsLZCNp9IZCItCI4YVhCeikubnwCLpE0nSTOcKXR8DUzcZA4qZCBW92yoCDFk2z0eZBNSUU6lgZDZD&offset=1&__after_id=6127898346" }, "data": [ { "category": "\u0627\u0644\u062a\u0639\u0644\u064a\u0645", "name": "The London School of Economics and Political Science - LSE", "category_list": [ { "id": "108051929285833", "name": "\u0627\u0644\u0643\u0644\u064a\u0629 \u0648\u0627\u0644\u062c\u0627\u0645\u0639\u0629" }, { "id": "187751327923426", "name": "\u0645\u0646\u0638\u0645\u0629 \u062a\u0639\u0644\u064a\u0645\u064a\u0629" } ], "id": "6127898346" } ] } Now I am wondering how can I get a specific field from it (e.g "id": "6127898346" ) ? I have tried a lot but I couldn't find a way to do . I have written this so far : ins = open( "pages.txt", "r" ) values = [] for line in ins: values.append(line) ins.close() print values but this gives me the whole line any help? Answer: This is JSON. You can get your data by loading it with the `json` module: import json with open(your_file).read() as content: data = json.loads(content) # manipulate your data `data` will be ordinary Python data structures such as nested lists, dict, strings and int, so you can manipulate them the usual way.
issue using r function with rpy2 Question: Sorry if my question is not clear enaugh. It is my first question on this site. When I do from rpy2.robjects import IntVector, Formula from rpy2 import robjects rr = Formula('gr_bmr~nationalite_france') myparams = {'family': 'binomial'} formula=robjects.r('gr_bmr~nationalite_simple') robjects.r['glm'](rr,data=bdd1,**myparams) I have this error: Erreur dans eval(expr, envir, enclos) : les valeurs de y doivent être 0 <= y <= 1 RRuntimeError Traceback (most recent call last) in () ----> 1 robjects.r['glm'](rr,data=bdd1,**myparams) /Library/Python/2.7/site-packages/rpy2/robjects/functions.pyc in call(self, *args, **kwargs) 84 v = kwargs.pop(k) 85 kwargs[r_k] = v ---> 86 return super(SignatureTranslatedFunction, self).call(*args, **kwargs) /Library/Python/2.7/site-packages/rpy2/robjects/functions.pyc in call(self, *args, **kwargs) 33 for k, v in kwargs.iteritems(): 34 new_kwargs[k] = conversion.py2ri(v) ---> 35 res = super(Function, self).call(*new_args, **new_kwargs) 36 res = conversion.ri2py(res) 37 return res RRuntimeError: Erreur dans eval(expr, envir, enclos) : les valeurs de y doivent être 0 <= y <= 1 I can translate in english if it is not clear. But, when i do the same thing in R, everything is working find: glm(gr_bmr~nationalite_france,family=binomial,data=bdd1) Call: glm(formula = gr_bmr ~ nationalite_france, family = binomial, data = bdd1) Coefficients: (Intercept) nationalite_franceoui -2.3609 -0.3604 Do you have any idea how to solve it? Answer: In you R code, `binomial` is a function while in your Python code it is a string. Try: from rpy2.robjects import Formula from rpy2.robjects.packages import importr rr = Formula('gr_bmr~nationalite_france') stats = importr('stats') myparams = {'family': stats.binomial} stats.glm(rr,data=bdd1,**myparams)
Python Pandas plotting title name passing string Question: How do I make the title name display 'AAPL Stock Price' without converting all my pandas data to matplotlib and numpy. import time from pylab import * import pandas as pd import numpy as np import matplotlib.pyplot as plt from pandas.io.data import * def Datapull(Stock): try: OHLC=DataReader(Stock,'yahoo',start='01/01/2010') OHLC['diff'] = OHLC.Open - OHLC.Close return OHLC print 'Retrieved', Stock time.sleep(5) except Exception, e: print 'Main Loop', str(e) def graph(stock): try: fig=plt.figure() mainplt=plt.subplot2grid((5,4), (0,0), rowspan=4, colspan=4) stock['Close'].plot(color='g').set_ylabel('Price') plt.title('Stock Price') plt.setp(mainplt.get_xticklabels(), visible=False) ax2=plt.subplot2grid((5,4), (4,0), rowspan=1, sharex=mainplt, colspan=4) ax2.grid(False) stock['Volume'].plot(color='c').set_ylabel('Volume') ax2.axes.yaxis.set_ticklabels([]) plt.setp(ax2.get_xticklabels(), rotation=45) plt.subplots_adjust(top=0.95, bottom=.14, right=.94, left=.09, wspace=.20, hspace=0 ) plt.show() except Exception, e: print 'Main Loop', str(e) Stock='AAPL' AAPL=Datapull(Stock) graph(AAPL) It should be plt.title(stock+'Stock Price') using numpy but I get an error message also suptitle does not work either Main Loop Could not operate ['Stock Price'] with block values [unsupported operand type(s) for +: 'numpy.ndarray' and 'str'] Answer: The way you load data, no name of symbols is saved. OHLC is just a DataFrame, to my knowledge it has no appropriate name attribute, where `AAPL` symbol can be stored. One possible method is to load `Panel`, note square brackets, converting stock_name to list of symbols: >>> stock_name = 'AAPL' >>> OHLC = pd.io.data.DataReader([stock_name],'yahoo',start='01/01/2010') >>> OHLC <class 'pandas.core.panel.Panel'> Dimensions: 6 (items) x 990 (major_axis) x 1 (minor_axis) Items axis: Open to Adj Close Major_axis axis: 2010-01-04 00:00:00 to 2013-12-06 00:00:00 Minor_axis axis: AAPL to AAPL >>> OHLC.axes[2] Index([u'AAPL'], dtype=object) and access underlying DataFrame with >>> OHLC.ix[:,:,'AAPL'] <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 990 entries, 2010-01-04 00:00:00 to 2013-12-06 00:00:00 Data columns (total 6 columns): Open 990 non-null values High 990 non-null values Low 990 non-null values Close 990 non-null values Volume 990 non-null values Adj Close 990 non-null values dtypes: float64(6) Or you can store symbol names yourself, >>> OHLC = (stock_name, pd.io.data.DataReader(stock_name,'yahoo',start='01/01/2010')) and access both df and name with >>> name, df = OHLC >>> name 'AAPL'
Add item to pandas.Series? Question: I want to add an integer to my `pandas.Series` Here is my code: import pandas as pd input = pd.Series([1,2,3,4,5]) input.append(6) When i run this, i get the following error: Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> f.append(6) File "C:\Python33\lib\site-packages\pandas\core\series.py", line 2047, in append verify_integrity=verify_integrity) File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 878, in concat verify_integrity=verify_integrity) File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 954, in __init__ self.new_axes = self._get_new_axes() File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1146, in _get_new_axes concat_axis = self._get_concat_axis() File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1163, in _get_concat_axis indexes = [x.index for x in self.objs] File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1163, in <listcomp> indexes = [x.index for x in self.objs] AttributeError: 'int' object has no attribute 'index' How can I fix that? Answer: Convert appended item to `Series`: >>> ds = pd.Series([1,2,3,4,5]) >>> ds.append(pd.Series([6])) 0 1 1 2 2 3 3 4 4 5 0 6 dtype: int64 or use `DataFrame`: >>> df = pd.DataFrame(ds) >>> df.append([6], ignore_index=True) 0 0 1 1 2 2 3 3 4 4 5 5 6 and last option if your index is without gaps, >>> ds.set_value(max(ds.index) + 1, 6) 0 1 1 2 2 3 3 4 4 5 5 6 dtype: int64 And you can use numpy as a last resort: >>> import numpy as np >>> pd.Series(np.concatenate((ds.values, [6])))
What does "module object is not callable" mean? Question: I'm using the .get_data() method with mechanize, which appears to print out the html that I want. I also check the type of what it prints out, and the type is 'str'. But when I try to parse the str with BeautifulSoup, I get the following error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-163-11c061bf6c04> in <module>() 7 html = get_html(first[i],last[i]) 8 print type(html) ----> 9 print parse_page(html) 10 # l_to_store.append(parse_page(html)) 11 # hfb_data['l_to_store']=l_to_store <ipython-input-161-bedc1ba19b10> in parse_hfb_page(html) 3 parse html to extract info in connection with a particular person 4 ''' ----> 5 soup = BeautifulSoup(html) 6 for el in soup.find_all('li'): 7 if el.find('span').contents[0]=='Item:': TypeError: 'module' object is not callable What exactly is 'module', and how do I get what get_data() returns into html? Answer: When you import BeatufilulSoup like this: import BeautifulSoup You are importing the module which contains classes, functions etc. In order to instantiate a BeautifulSoup class instance form the BeautifulSoup module you need to either import it or use the full name including the module prefix like yonili suggests in the comment above: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(html) or import BeautifulSoup soup = BeautifulSoup.BeautifulSoup(html)
What is the exception for this error: httperror_seek_wrapper: HTTP Error 404: Not Found? Question: I would like to handle the error: "httperror_seek_wrapper: HTTP Error 404: Not Found" And instead just return an empty string. But I'm not sure what the except statement should be. I apologize if there is a duplicate post, but none of the posts that popped up seemed to deal with excepting this error, but rather figuring out what had gone wrong at a deeper level. I, however, just want to pass along and return an empty string. Basically, I'm looking for what should go in the blank: try: .... except _____: .... Thanks! _____ Here is the code where the error gets thrown. --------------------------------------------------------------------------- httperror_seek_wrapper Traceback (most recent call last) <ipython-input-181-e2b68bf19ff9> in <module>() 5 6 for i in range(len(first)): ----> 7 student_html = get_stud_html(first[i],last[i],'Sophomore') 8 # print type(student_html) 9 # print parse_hfb_page(student_html) <ipython-input-177-9b1d4294820d> in get_stud_html(first, last, year) 60 #ideally will want to use a regex to do this in case there's more than one link on the page 61 stud_url = 'http://facebook.college.harvard.edu/'+links_lst[12] ---> 62 stud_html = br.open(stud_url) 63 return stud_html.get_data() 64 //anaconda/python.app/Contents/lib/python2.7/site-packages/mechanize-0.2.5-py2.7.egg/mechanize/_mechanize.pyc in open(self, url, data, timeout) 201 def open(self, url, data=None, 202 timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT): --> 203 return self._mech_open(url, data, timeout=timeout) 204 205 def _mech_open(self, url, data=None, update_history=True, visit=None, //anaconda/python.app/Contents/lib/python2.7/site-packages/mechanize-0.2.5-py2.7.egg/mechanize/_mechanize.pyc in _mech_open(self, url, data, update_history, visit, timeout) 253 254 if not success: --> 255 raise response 256 return response 257 httperror_seek_wrapper: HTTP Error 404: Not Found Answer: That is a `urllib2.HTTPError` exception. from urllib2 import HTTPError try: # ... except HTTPError: # ... You can see this in the [source of `_mechanize.py`](https://github.com/jjlee/mechanize/blob/master/mechanize/_mechanize.py#L228), where that same exception is caught and assigned to `response` to be re-raised later.
Read all files in a folder and also the filenames in python? Question: How to read all files and also the filenames? I am using MAC so is there any there a different way to give path on MAC in Python? Answer: Maybe something like this? Or os.listdir() is simpler if you don't need recursion. Even on Windows, Python abstracts away the differences between operating systems if you use it well. #!/usr/local/cpython-3.3/bin/python import os def main(): for root, dirs, files in os.walk('/home/dstromberg/src/outside-questions'): for directory in dirs: print('directory', os.path.join(root, directory)) for file_ in files: print('file', os.path.join(root, file_)) main() See <http://docs.python.org/3/library/os.html> for more info.
Subtracting two interleaved, differently based time-series arrays with numpy? Question: I have two datasets, `a[ts1]` and `b[ts2]`, where `ts1` and `ts2` are timestamps taken at different times (in different bases?). I wanted to plot `b[ts2]-a[ts1]`, but I think I made a mistake, in that the plotting software understood that I want `b[i]-a[i]` instead, where `i` is the index order of the value. So I wanted to make a small example of this with `numpy`, and I realized I have no idea whether, and how, `numpy` can perform this operation - but using vectors, and avoiding `for` loops. I have made an example (below), that defines `a[ts1]` and `b[ts2]` as `numpy` structured arrays titled `a_np` and `b_np`: array([(0.0, 0.0), (0.8865606188774109, 0.30000001192092896), (1.6939274072647095, 0.6000000238418579), (2.3499808311462402, 0.8999999761581421)], ... dtype=[('a', '<f4'), ('ts1', '<f4')]) array([(0.3973386585712433, 0.10000000149011612), (0.7788366675376892, 0.20000000298023224), (1.4347121715545654, 0.4000000059604645), (1.6829419136047363, 0.5)], ... dtype=[('b', '<f4'), ('ts2', '<f4')]) So my questions here are: * What is this class of arrays/problems called? Is it just "time-series" arrays? Basically, they describe a 1-D signal, but since timestamps have to be kept, it's a 2D array; and since the "time" column can have any meaning, I guess it can be generalized to interpolation of values of arrays in (value) column, over the "indexing" values in the (time/index) column. * Can `numpy` do a vectorized operation where the arrays are properly interpolated in "time", before being subtracted? Looking for info on this, I found [pandas: Python Data Analysis Library](http://pandas.pydata.org/); I guess I should use this instead, given it has a "time-series" functionality - but in this case, I don't need any fancy interpolation of sample values - just a "step" or "hold" one (basically, no interpolation); which is why I was wandering if `numpy` can do that in a vectorized fashion. Otherwise, the example below employs `for` loops. * * * The example will result with an image like this: ![array-timeseries](http://i.stack.imgur.com/tmH1O.png) Arrays `a` and `b` represent values taken at different times, which is indicated by their respective `impulses`; `a` is plotted with `lines` (so, linearly interpolated before plotting), but `b` with `steps` (to indicate the actual values that exist) The array `d1` represents the "original" difference `b[t]-a[t]` taken when constructing the array - obviously, I do not have access to this data in reality, so I have to work from the sampled values. In that case, the difference `b[ts2]-a[ts1]` is shown as the array/signal `d2`, again as `steps` to emphasize the errors being made in respect to the "original". This `d2` is what I'd like to calculate with `numpy` (but below, it is calculated in the same `for` loop). The error I made with my plotting software is getting an index-by-index difference of `b` and `a`, or `b[i]-a[i]`; this is shown as array/signal `e` \- and as shown, it is _way_ off from what it's otherwise supposed to represent. This is only the case if sampling intervals in the two signals are uneven; try `modulowith = 2` in the code, then `e` is actually not that bad - however, my real life case has uneven timestamps, so `b[i]-a[i]` doesn't help me at all. Here is the code, which also calls `gnuplot` (tested on Python 2.7, `numpy` 1.5 I think): import subprocess import math, random import numpy as np from pprint import pprint from numpy.lib.recfunctions import append_fields step = 0.1 modulowith = 3 # must init all arrays separately; # a=b=[] makes a==b by reference! ts1 = []; ts2 = [] ; tsd = [] valsa = []; valsb = []; valsd1 = []; valsd2 = [] stra = strb = strd1 = strd2 = "" ; kval1 = kval2 = 0 for ix in range(0, 100, 1): ts = ix*step val1 = 3.0*math.sin(ts) #+random.random() val2 = 2.0*math.sin(2.0*ts) if ( ix%modulowith == 0): ts1.append(ts) ; valsa.append(val1) stra += "%.03f %.06f\n" % (ts, val1) kval1 = val1 else: ts2.append(ts) ; valsb.append(val2) strb += "%.03f %.06f\n" % (ts, val2) kval2 = val2 tsd.append(ts) valb = val2 - val1 ; valsd1.append(valb) strd1 += "%.03f %.06f\n" % (ts, valb) valc = kval2 - kval1 ; valsd2.append(valc) strd2 += "%.03f %.06f\n" % (ts, valc) a_np = np.array( [(_valsa,) for _valsa in valsa], dtype=[('a','f4')] ) b_np = np.array( [(_valsb,) for _valsb in valsb], dtype=[('b','f4')] ) a_np = append_fields(a_np, names='ts1', data=ts1, dtypes='f4', usemask=False) b_np = append_fields(b_np, names='ts2', data=ts2, dtypes='f4', usemask=False) pprint(a_np[:4]) pprint(b_np[:4]) # e_np = np.subtract(b_np['b'],a_np['a']) # (via field reference) is same as doing: # e_np = np.subtract(np.array(valsa, dtype="f4"), np.array(valsb, dtype="f4")) # but for different sized arrays, must do: e_np = b_np['b'] - np.resize(a_np, b_np.shape)['a'] pprint(e_np[:4]) e_str = "" for ts, ie in zip(ts2, e_np): e_str += "%.03f %.06f\n" % (ts, ie) gpscript = """ plot "-" using 1:2 with lines lc rgb "green" t"a", \\ "" using 1:2 with impulses lc rgb "green" t"", \\ "" using 1:2 with steps lc rgb "blue" t"b", \\ "" using 1:2 with impulses lc rgb "blue" t"", \\ "" using 1:2 with lines lc rgb "red" t"d1", \\ "" using 1:2 with steps lc rgb "orange" t"d2", \\ "" using 1:2 with steps lc rgb "brown" t"e" - {0} e {0} e {1} e {1} e {2} e {3} e {4} e """.format(stra, strb, strd1, strd2, e_str) proc = subprocess.Popen( ['gnuplot','--persist'], shell=False, stdin=subprocess.PIPE, ) proc.communicate(gpscript) * * * Thanks to the answer by [@runnerup](http://stackoverflow.com/a/20449087/277826), here is a slightly verbose (for syntax example purposes) `numpy`-only solution: # create union of both timestamp arrays as tsz ntz = np.union1d(b_np['ts2'], a_np['ts1']) # interpolate `a` values over tsz a_z = np.interp(ntz, a_np['ts1'], a_np['a']) # interpolate `b` values over tsz b_z = np.interp(ntz, b_np['ts2'], b_np['b']) # create structured arrays for resampled `a` and `b`, # indexed against tsz timestamps a_npz = np.array( [ (tz,az) for tz,az in zip(ntz,a_z) ], dtype=[('tsz', 'f4'), ('a', 'f4')] ) b_npz = np.array( [ (tz,bz) for tz,bz in zip(ntz,b_z) ], dtype=[('tsz', 'f4'), ('b', 'f4')] ) # subtract resized array e_npz = np.subtract(b_npz['b'], a_npz['a']) e_str = "" # check: pprint(e_npz[:4]) # gnuplot string: for ts, ie in zip(ntz, e_npz): e_str += "%.03f %.06f\n" % (ts, ie) This is linearly interpolated, so it will be different from `d2` above, but still nicely fitting. If there wasn't for those `for` loops creating the arrays, then it is vectorized - and in principle I don't even have to create those arrays - just wanted to see how they will look like as structured ones.. In all, I guess I was hoping for a one-liner that would do this, with structured arrays (that is, handling field names as well). Answer: this is an attempt to sell you on switching to `pandas` : ) import numpy as np import pandas as pd import datetime as dt import matplotlib.pyplot as plt # one minute interval start = dt.datetime.now( ) end = start + dt.timedelta( minutes=1 ) # sin curve at seconds frequancy idx1 = pd.date_range( start, end, freq='S' ) ts1 = pd.Series( np.sin( np.linspace( 0, 4 * np.pi, len( idx1 ) ) ), index=idx1 ) # cosine curve at milisecond frequency idx2 = pd.date_range( start, end, freq='L' ) ts2 = pd.Series( np.cos( np.linspace( 0, 4 * np.pi, len( idx2 ) ) ), index=idx2 ) now `len( ts1 ) = 61` and `len( ts2 ) = 6001`, with different frequencies fig = plt.figure( figsize=(8, 6) ) ax = fig.add_axes( [.05, .05, .9, .9] ) ts1.plot( ax, color='DarkBlue' ) ts2.plot( ax, color='DarkRed' ) # reindex ts2 like ts1 ts2 = ts2.reindex_like( ts1 ) (ts1 - ts2).plot( ax, color='DarkGreen' ) and you get: ![time series](http://i.stack.imgur.com/T184l.png) **edit** : for interpolation purposes you may use nonparametric methods in statsmodels, so basically you may interpolate one series at the frequencies of the other one and then subtract the two: import statsmodels.api as sm n = 1000 x = np.linspace( 0, 1, n ) y = np.random.randn( n ).cumsum( ) z = sm.nonparametric.lowess( y, x, return_sorted=False, frac=.05) ax.plot( x, y, 'Blue', linestyle='--' ) ax.plot( x, z, color='DarkRed' ) ![bm](http://i.stack.imgur.com/DFyox.png)
Right way to write Unit-Tests in module? Question: I want to write tests for my main file,`calc.py`, with unittest in module file, `MyTests.py`. Here is my main python file, `calc.py`: import myTests def first(x): return x**2 def second(x): return x**3 def main(): one = first(5) two = second(5) if __name__ == "__main__": main() try: myTests.unittest.main() except SystemExit: pass And here is my `MyTests.py` file: import unittest import calc class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.testInput = 10 def test_first(self): output = calc.first(self.testInput) correct = 100 assert(output == correct) def test_second(self): output = calc.second(self.testInput) correct = 1000 assert(output == correct) When i run my `calc.py`, i get the following output: ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Why does unittest prints me that "Ran **0** test"? And what is the right way to write unittest in module? Answer: `unittests.main()` looks for `TestCase` instances _in the current module_. Your module has no such testcases; it only has a `myTests` global. Best practice is to run the tests _themselves_. Add the `__main__` section there to the `myTests.py` file: import unittest import calc class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.testInput = 10 def test_first(self): output = calc.first(self.testInput) correct = 100 assert(output == correct) def test_second(self): output = calc.second(self.testInput) correct = 1000 assert(output == correct) if __name__ == '__main__': unittest.main() and run `python myTests.py` instead. Alternatively, pass in the imported `myTests` module into `unittest.main()`. You may want to move the `import myTests` line _down_ into `__main__`, because you have a circular import too. That is fine in your case, `myTests` doesn't use any globals from `calc` outside of the test cases, but it is better to be explicit about this. if __name__ == "__main__": main() try: import myTests myTests.unittest.main(myTests) except SystemExit: pass