text
stringlengths
226
34.5k
How to pass commands to gdb from python Question: I have launched GDB using subprocess.call methond in python .Can any one help how to pass commands to gdb (like 'info threads') from python script. Answer: It is better to use [Pexpect](https://pexpect.readthedocs.org/en/latest/) module if you want to interact with interactive shells. But I suggest you to use Python bindings that shipped with gdb. infothreads.py: import gdb gdb.execute('info threads') gdb.execute('continue') Run it using `-x` option of gdb: gdb -x infothreads.py -p 21686 Documentation on Python bindings may be found here: [Python API](https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html#Python-API)
Parse arbitary date formats in Python (including rfc3164) Question: PHP has the amazing [strtotime()](http://php.net/strtotime) function which takes pretty much anything and turns it into a time. I'm looking for something similar in Python? As an example of why: I'm parsing syslogs which have the dumbest format ever (aka [rfc3164](http://www.ietf.org/rfc/rfc3164.txt)) which omits a year and includes a space-padded day-of-month. Currently in Python I'm doing this: import datetime d='Mar 5 09:10:11' # as an example # first remove the space, if it exists if d[4] == ' ': d = d[0:4] + d[5:] # append this year (I know, it could be last year around Dec/Jan!) d = str(datetime.datetime.now().year) + ' ' + d # now we can feed it strptime date = datetime.strptime(d, "%Y %b %d %H:%M:%S") This is really ugly. Is there a better way? Answer: I think you are looking for the [`dateutils`](http://labix.org/python- dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2) module: In [12]: d = 'Mar 5 09:10:11' In [13]: import dateutil In [14]: dateutil.parser.parse(d) Out[14]: datetime.datetime(2015, 3, 5, 9, 10, 11)
Can voluptuous code pass pylint? Question: I run `pylint -E` as part of the tests on my Python project to ensure that errors don't creep into untested code. Generally this works quite well. But recently I've been running into problems with [voluptuous](https://pypi.python.org/pypi/voluptuous) and pylint. The problem is that pylint thinks that the values returned by voluptuous Schemas are lists, which is simply not the case. Here's a toy program: import voluptuous MyType = voluptuous.Schema({ 'q': str }) def foo(bar): bar = MyType(bar) q = bar.get('q') print q foo({'q': '1324'}) It runs just fine: $ python toy.py 1234 pylint, however, flags the `.get()` call: $ pylint -E toy.py No config file found, using default configuration ************* Module toy E: 11, 8: Instance of 'list' has no 'get' member (no-member) How can I get this program to pass `pylint -E`? Answer: One option is to ignore the `voluptuous` module entirely, e.g. $ pylint -E --ignored-modules=voluptuous toy.py (passes) If would be nice if `pylint` understood `voluptuous` better, though.
Python scatter - change marker style based on entity Question: I'm struggling for days trying to resolve this problem: I have cartesian coordinates on the y-axis (for depth from 0 to 1) and numbers with different values on the x axis (the numbers are the firing rate of different cells populations at the given depth on y axis, so they vary randomly). I would like to show bigger size of markers in the scatterplot corresponding to a bigger x-axis value (firing rate). Thank you for any suggestion. This is the code (not working). import matplotlib.pyplot as plt import numpy as np import matplotlib.cbook as cbook x = np.genfromtxt('x_dex.csv', delimiter=',') y = np.genfromtxt('z_dex.csv', delimiter=',') array = [i for i in x if i > 4] array.sort() s = [30*2**n for n in range(len(array))]; plt.subplot(212) plt.scatter(x,y,s=s) plt.show() This is unfortunately not showing the correct relation between size of marker and depth. Answer: The line where you compute your 'size' values looks incorrect to me: s = [30*2**n for n in range(len(array))]; This will give you a list containing: s = [30*2**0, 30*2**1, 30*2**2, ..., 30*2**(len(array) - 1)] The values bear no relation to `y`, so I assume this is not what you intended. Maybe you meant something more like this: s = 30 * 2 ** y * * * There are actually several other issues here: * Don't give your variables names like `array` \- this can lead to confusion with `numpy.array`. It's even worse in this case, since `array` is actually not an array but a Python `list`! * Since you're dealing with numpy arrays, it's much faster to use vectorization rather than list comprehensions. For example, you could use: array = x[x > 4] rather than array = [i for i in x if i > 4] * After your list comprehension `array = [i for i in x if i > 4]`, `array` will have a different number of elements to `y` if there are elements in `array` that are less than 4. * `array.sort()` will sort the list _in place_ , which means that the order of the elements in `array` will no longer match the order of elements in `y`. * In fact, sorting seems rather pointless in this situation - since you're making a scatter plot the order of the points should not matter. * You're not writing MATLAB code any more, so there's no need to end lines on a semicolon (although it won't do any harm if you do). * * * Here's my educated guess at what you're trying to do: import matplotlib.pyplot as plt import numpy as np x = np.genfromtxt('x_dex.csv', delimiter=',') y = np.genfromtxt('z_dex.csv', delimiter=',') # get the set of indices that will sort x in ascending order, apply these # to both x & y order = np.argsort(x) x_sorted = x[order] y_sorted = y[order] # keep only xy pairs where x > 4 valid = x_sorted > 4 x_valid = x_sorted[valid] y_valid = y_sorted[valid] # compute the sizes s = 30 * 2 ** y_valid # plot plt.subplot(212) plt.scatter(x_valid, y_valid, s=s) plt.show()
Python failing to import module from script Question: If I start python and input `import tables` it works fine but when I run `python m_BlackrockLib.py` (which has `import os, struct, tables, pickle, re, shutil` as it's first line) I get the error `ImportError: No module named tables`. I can see that tables is present in `/usr/local/anaconda/lib/python2.7/site-package` so I'm not sure what is causing this error. Can anyone see the issue? Answer: I needed to add `import conda` to the script above the other imports because I have `tables` installed in anaconda
How to map structured data to schemaRDD in Spark? Question: I've asked this question differently before but there are some changes so I thought asking it again as a new question. I have a structured data which only part of it is in json format but I need to map the entire data to an schemaRDD. The data looks like this: > 03052015 04:13:20 > {"recordType":"NEW","data":{"keycol":"val1","col2":"val2","col3":"val3"} Each line starts with date followed by time and a json formatted text. I need to map not only the text in json but also the date and time into the same structure. I tried it in Python but obviously it doesn't work because Row does not take an RDD (jsonRDD in this case). from pyspark.sql import SQLContext, Row sqlContext = SQLContext(sc) orderFile = sc.textFile(myfile) orderLine = orderFile.map(lambda line: line.split(" ", 2)) anotherOrderLine = orderLine.map(lambda p: Row(date=p[0], time=p[1], content=sqlContext.jsonRDD(p[3]))) schemaOrder = sqlContext.inferSchema(anotherOrderLine) schemaOrder.printSchema() for x in schemaOrder.collect(): print x The goal is to be able to run a query like this against the schemaRDD: select date, time, data.keycol, data.val1, data.val2, data.val3 from myOrder How can I map the entire line to a schemaRDD? Any help is appreciated? Answer: The sqlContext.jsonRDD creates a schema rdd from an RDD containing strings where each string contains a JSON representation. This code sample is from the SparkSQL documentation (<https://spark.apache.org/docs/1.2.0/sql-programming- guide.html>): val anotherPeopleRDD = sc.parallelize("""{"name":"Yin","address":{"city":"Columbus","state":"Ohio"}}""" :: Nil) val anotherPeople = sqlContext.jsonRDD(anotherPeopleRDD) One of the cool things about jsonRDD is the fact that you can provide and additional parameter stating the JSONs schema, which should improve performance your performance. This can be don by creating an schemaRDD (just load a sample document) and then call the schemaRDD.schema method to get the schema.
How to copy text file in python Question: Here's what I want to do: import copy def printtext(swefile): for row in swefile: print(row) text = open("wordsv.txt","r",encoding="utf-8") text2 = copy.copy(text) printtext(text) print(text2.readlines()) But it is not possible, TypeError: cannot serialize '_io.TextIOWrapper' object. So I wonder if there is a good method for "cloning" the text variable, so that I could print all the lines again. I know that I could just read the file again, but that answer does not solve the bigger problem I have so any suggestion on how to get this done is helpful. * * * Here's the larger context as I haven't been able to solve my problem with your suggestions: with open(textfilename, "r", encoding = "utf-8") as swefile: for row in swefile: word = row.strip() tempfile = copy.copy(swefile) l = getFurthest(word,tempfile) The thing that I want to happen here is that i want to send the portion of `swefile` that has not been read yet (i.e. iterated over yet by the for loop) to `getFurthest()`! And I can't send `swefile` because that will make the whole thing read so the iterations in the for loop will stop, right? So how can I send only the portion of the textfile that has been read to `getFurthest()` while still being able to iterate over the rest of it after? Answer: If you're trying to avoid re-opening the file, but want to read it twice, you can use [`seek()`](https://docs.python.org/3/library/io.html#io.IOBase.seek): import copy def printtext(swefile): for row in swefile: print(row) text = open("wordsv.txt","r",encoding='utf-8') printtext(text) text.seek(0) printtext(text) If you just care about the text, you can do this: import copy def printtext(swefile): for row in swefile: print(row) text = open("wordsv.txt","r",encoding='utf-8').readlines() text2 = copy.copy(text) printtext(text) printtext(text2) Here `text` is a list of the lines in `wordsv.txt`, and you then copy the list into text2 (i.e. changing `text` won't change `text2`).
wxPython -- BoxSizers not placing things correctly Question: I can't figure out what I'm doing wrong. I just made the jump from Tkinter to wxPython and I'm trying to figure out BoxSizers. I'd look this question up, but I don't even know what to look up. This panel is filling the space of a Frame, it's supposed to show a line of text with a progressbar underneath it and that's all supposed to take up the bottom 1/5 of the panel or so, centered horizontally (eventually I'm going to add a background image behind it). But what happens is I only see the text and only about 40% down from the top, aligned to the left edge of the window. Here's the code: class KhPanel(wx.Panel): def __init__(self, parent, configSet, selectWindow): wx.Panel.__init__(self, parent=parent) self.frame = parent self.configSet = configSet whichWindow = getattr(self, selectWindow) whichWindow() def configWindow(self): gaugeWidth = (1/5)*self.configSet["width"] gaugeHeight = (1/10)*self.configSet["height"] gaugeMax = 100 topBuffer = (8/10)*self.configSet["height"] itemSep = (1/16)*self.configSet["height"] vSizer = wx.BoxSizer(wx.VERTICAL) textSizer = wx.BoxSizer(wx.HORIZONTAL) progressSizer = wx.BoxSizer(wx.HORIZONTAL) configText = wx.StaticText(self, label="STUFF", style=wx.ALIGN_CENTER) configProgressBar = wx.Gauge(self, range=gaugeMax, size=(gaugeWidth, gaugeHeight)) textSizer.Add(configText, 1, wx.ALIGN_CENTER, 0) progressSizer.Add(configProgressBar, 1, wx.ALIGN_CENTER, 1) vSizer.Add(textSizer, 1, wx.TOP, topBuffer) vSizer.Add(progressSizer, 1, wx.TOP, itemSep) self.SetSizer(vSizer) vSizer.Fit(self) return If you need the info, configSet.width and height are the width and height of the parent window (currently 340 x 270). And selectWindow, in this case, is "configWindow" Answer: Running this code, the `gaugeWidth` and `gaugeHeight` are both getting set to zero, which is why the progressbar is not showing. This is due to the fact that you are doing integer math here, so 1 divided by 5 is 0. Same with 1/10. Just change those lines to: gaugeWidth = (1/5.0)*self.configSet["width"] gaugeHeight = (1/10.0)*self.configSet["height"] Then the gauge will appear. Here's some fully runnable code, slightly modified from your unrunnable original: import wx class KhPanel(wx.Panel): def __init__(self, parent, configSet): wx.Panel.__init__(self, parent=parent) self.frame = parent self.configSet = configSet self.configWindow() def configWindow(self): gaugeWidth = (1/5.0)*self.configSet["width"] gaugeHeight = (1/10.0)*self.configSet["height"] gaugeMax = 100 topBuffer = (8/10)*self.configSet["height"] itemSep = (1/16)*self.configSet["height"] vSizer = wx.BoxSizer(wx.VERTICAL) textSizer = wx.BoxSizer(wx.HORIZONTAL) progressSizer = wx.BoxSizer(wx.HORIZONTAL) configText = wx.StaticText(self, label="STUFF", style=wx.ALIGN_CENTER) configProgressBar = wx.Gauge(self, range=gaugeMax, size=(gaugeWidth, gaugeHeight)) textSizer.Add(configText, 1, wx.ALIGN_CENTER, 0) progressSizer.Add(configProgressBar, 1, wx.ALIGN_CENTER, 1) vSizer.Add(textSizer, 1, wx.TOP, topBuffer) vSizer.Add(progressSizer, 1, wx.TOP, itemSep) self.SetSizer(vSizer) vSizer.Fit(self) class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Test") config = {'width':340, 'height':270} panel = KhPanel(self, config) self.Show() if __name__ == "__main__": app = wx.App() frame = MyFrame() app.MainLoop()
AttributeError: 'NoneType' object has no attribute 'shape' Question: import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread('AB.jpg') mask = np.zeros(img.shape[:2] , np.uint8) bgdModel = np.zeros((1,65), np.float64) fgdModel = np.zeros((1,65), np.float64) rect = (300 , 120 , 470 , 350) #this modifies mask cv2.grabCut(img,mask,rect,bgdModel, fgdModel , 5 , cv2.GC_INIT_WITH_RECT) #If mask==2 or mask==1 , mask2 get 0, otherwise it gets 1 as 'uint8' type mask2 = np.where((mask==2) | (mask==0),0,1).astype('uint8') #adding additional dimension for rgb to the mask, by default it gets 1 #multiply with input image to get the segmented image img_cut = img*mask2[: , : , np.newaxis] plt.subplot(211),plt.imshow(img) plt.title('Input Image') , plt.xticks([]),plt.yticks([]) plt.subplot(212),plt.imshow(img_cut) plt.title('Grab cut'), plt.xticks([]),plt.yticks([]) plt.show() on compiling I get this error : python img.py AB.jpg Traceback (most recent call last): File "img.py", line 6, in <module> mask = np.zeros(img.shape[:2] , np.uint8) AttributeError: 'NoneType' object has no attribute 'shape' Answer: First of all python img.py AB.jpg will not work as you expect (load AB.jpg from the current directory). The file to load is hardcoded in line 6 of the provided example: to work as intended, it should be something like this: import sys img = cv2.imread(sys.argv[1]) The error is returned because AB.jpg does not exist in the directory img.py is being run from (the current working directory), and there is no verification for a missing file before trying to read it.
Python 2.7 writing strings elements (character) to a binary file Question: I am using Python 2.7 to access an API that returns JSON with a single key="ringtone_file" and an associated value that is an mp3 file encoded for transport via HTTP. I created a bogus mp3 file consisting of 256 bytes in order from 0x00 through 0xff and the returned file appears below. {"ringtone_file":"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"} I accessed the API using the following code minus exception handing code import requests response = requests.get(url) dict = response.json() print dict This yields the following output {u'ringtone_file': u'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'} What I desire to do is write each character or hex value of this string to a file in binary format. I desire the result to be a file of size 256 bytes where the first byte in the file has value 0 and the last byte has value 255. I can't change the API. Can someone suggest a reasonable way of accomplishing this with Python 2.7. I attempted to do what was obvious to me which was to open a file for writing in binary mode and then writing the unicode string to the file. The error message from the codec indicates I can't write values between and including 128 and 255. Answer: Since the string value is Unicode, you have to encode the string to write it to a file. The `latin1` codec directly maps to the first 256 Unicode characters, so use `.encode('latin1')` on the string. Example: >>> s=u'\x00\x01\x02\xfd\xfe\xff' >>> s u'\x00\x01\x02\xfd\xfe\xff' # Unicode string >>> s.encode('latin1') '\x00\x01\x02\xfd\xfe\xff' # Now a byte string.
How to save a list of ojects that contains a list as member to file by using pickle python? Question: I have the following class: class Document: _queryID = "" _name = [] _docId = "" * * * In the code I create a list called listDocuments. I fill the list with objects of type Document. import pickle if __name__ == "__main__": listDocuments = [] for i in range(0,10): e = Document() e._queryID = str(i) e._docId = str(i+1) e._name.append("h"+str(i)) listDocuments.append(e) save_data(listDocuments, "Variations.dat") list = load_data("Variations.dat") for obj in listEntities: print obj._queryID + "==>"+ obj._docId for var in obj._name: print var +" " print "----\n" * * * I used the following functions taken from [Python: how to save a list with objects in a file](http://stackoverflow.com/questions/17076873/python-how-to- save-a-list-with-objects-in-a-file): #save list of variations def save_data(data, path): with open(path, "wb") as f: pickle.dump(data, f) #load list of variations (Correctd after comments thank you) def load_data(var_file): try: with open(var_file) as f: listDocument = pickle.load(f) except: listDocument = [] return listDocument * * * * As output I can only print the _queryID. What am I missing? I cannot print the list _name nor the _docID Answer: Okay, a few issues. First: def load_data(var_file): try: with open(var_file) as f: listDocument = pickle.load(f) except: listDocuments = [] return listDocuments You use both `listDocument` and `listDocuments`. (Note one has a trailing `s`). Also, you're using these the variable `listDocuments` in the outer program which is hiding your errors. Let's rename the variable inside the function to `data` like the `save_data` function does. We'll also rename `var_file` to `path` for the same consistency reason. Consider: def load_data(path): data = [] try: with open(path) as f: data = pickle.load(f) except: pass return data Next, you're using `list` which is a reserved built-in -- lets change that to `lst`. So now you have: class Document: _queryID = "" _name = [] _docId = "" def save_data(data, path): with open(path, "wb") as f: pickle.dump(data, f) #load list of variations def load_data(path): data = [] try: with open(path) as f: data = pickle.load(f) except: pass return data import pickle if __name__ == "__main__": listDocuments = [] for i in range(0,10): e = Document() e._queryID = str(i) e._docId = str(i+1) e._name.append("h"+str(i)) listDocuments.append(e) save_data(listDocuments, "Variations.dat") lst = load_data("Variations.dat") for elem in lst: print elem._queryID print elem._docId print elem._name print "---" Which works, and prints: 0 1 ['h0', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9'] --- 1 2 ['h0', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9'] --- 2 3 ['h0', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9'] --- 3 4 ['h0', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9'] --- 4 5 ['h0', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9'] --- 5 6 ['h0', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9'] --- 6 7 ['h0', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9'] --- 7 8 ['h0', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9'] --- 8 9 ['h0', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9'] --- 9 10 ['h0', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9'] --- **EDIT** Per your edit, you have no `listEntities` variable -- I think you mean (the recently renamed) `lst`: for obj in lst: print obj._queryID + "==>"+ obj._docId for var in obj._name: print var +" " print "----\n" Lastly, if you're wondering why the `_name` variable is the same for all instances of the `Document` class, it's because you're declaring `_name` as a class attribute (so its the same for all instances), not an instance attribute. You could replace the `Document` class definition with: class Document: def __init__(self): self._name = [] And you'll probably be happier with the results: 0==>1 h0 ---- 1==>2 h1 ---- 2==>3 h2 ---- 3==>4 h3 ---- 4==>5 h4 ---- 5==>6 h5 ---- 6==>7 h6 ---- 7==>8 h7 ---- 8==>9 h8 ---- 9==>10 h9 ----
How to attribut a different variable to each element of list Question: Watch out I am a beginner. My question is: can I ask Python to attribut a different variable to each element of a list. I created one list of questions and one list of answer lst_questions = ['6+11', '3+3', '9+10', '2+7', '11+8', '9+3', '11+9', '3+3', '2+4', '7+4', '4+8', '3+9'] lst_reponses = [17, 6, 19, 9, 19, 12, 20, 6, 6, 11, 12, 12] var1 = 0 var2 = 0 var3 = 0 var4 = 0 var5 = 0 var6 = 0 var7 = 0 var8 = 0 var9 = 0 var10 = 0 var11 = 0 var12 = 0 a = 0 b = 0 c = 0 d = 0 e = 0 f = 0 g = 0 h = 0 i = 0 j = 0 k = 0 l = 0 And I want to have: def apply_solution(lst): a = lst.index(var1) b = lst.index(var2) c = lst.index(var3) d = lst.index(var4) e = lst.index(var5) f = lst.index(var6) g = lst.index(var7) h = lst.index(var8) i = lst.index(var9) j = lst.index(var10) k = lst.index(var11) l = lst.index(var12) #Solution lst[a], lst[b], lst[c], lst[d], lst[e], lst[f], lst[g], lst[h], lst[i], lst[j], lst[k], lst[l] = lst[a], lst[k], lst[j], lst[i], lst[h], lst[g], lst[f], lst[e], lst[d], lst[c], lst[b], lst[l] #Verification indice #print a,b,c return lst print apply_solution(lst_reponses) Obviously, I receive error: a = lst.index(var1) ValueError: 0 is not in list How can I attribute each element of lst_reponses to var1 ... var12 I hope I make myself clear. Answer: Use a dict if you want to associate values: lst_questions = ['6+11', '3+3', '9+10', '2+7', '11+8', '9+3', '11+9', '3+3', '2+4', '7+4', '4+8', '3+9'] lst_reponses = [17, 6, 19, 9, 19, 12, 20, 6, 6, 11, 12, 12] data = dict(zip(lst_questions,lst_reponses)) {'2+4': 6, '2+7': 9, '3+3': 6, '9+10': 19, '6+11': 17, '3+9': 12, '9+3': 12, '11+9': 20, '11+8': 19, '7+4': 11, '4+8': 12} To ask a user question and verify: from random import choice # "3+2" etc.. keys and correct result as value data = dict(zip(lst_questions, lst_reponses)) # get random key question = choice(data.keys()) inp = raw_input("What is {}".format(question)) # is user answer match the value if int(inp) == data[question]: print("Well done") else: print("Incorrect")
Python Tkinter check radio button state before proceed Question: I have this code which is working import Tkinter as tk from Tkinter import * LARGE_FONT= ("Verdana", 12) class ChangePages(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack() container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (MainPage, Page01, Page02): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(MainPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() #MainPage class MainPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) button1=Button(self,text='Go To Page 1',fg='blue',font=('Helvetica',26),height=5, width=20,command=lambda: controller.show_frame(Page01)).grid(row=1,column=1) #Page01 class Page01(tk.Frame): def __init__(self, parent, controller): option1 = IntVar() option2 = IntVar() option3 = IntVar() tk.Frame.__init__(self, parent) f = Frame(self) f.pack(side='left') label1=Label(f,text='Select options',fg='blue', font=("Arial", 36, "bold"),width=54, relief='solid').grid(row=1,column=1,columnspan=3) labelspacing=Label(f,text='Option 1 ',font=("Arial", 18, "bold"),width=20,height=1).grid(row=2,column=1) labelspacing=Label(f,text='Option 2 ',font=("Arial", 18, "bold"),width=20,height=1).grid(row=2,column=2) labelspacing=Label(f,text='Option 3',font=("Arial", 18, "bold"),width=20,height=1).grid(row=2,column=3) buttonoption11=Radiobutton(f, text="Option 1 - A", variable=option1, value=1, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20).grid(row=3,column=1) buttonoption21=Radiobutton(f, text="Option 2 - A", variable=option2, value=1, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20).grid(row=3,column=2) buttonoption31=Radiobutton(f, text="Option 3 - A", variable=option3, value=1, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20).grid(row=3,column=3) buttonoption12=Radiobutton(f, text="Option 1 - B", variable=option1, value=2, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20).grid(row=4,column=1) buttonoption22=Radiobutton(f, text="Option 2 - B", variable=option2, value=2, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20).grid(row=4,column=2) buttonoption32=Radiobutton(f, text="Option 3 - B", variable=option3, value=2, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20).grid(row=4,column=3) buttonoption23=Radiobutton(f, text="Option 2 - C", variable=option2, value=3, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20).grid(row=5,column=2) buttonnback=Button(f,text='Back',fg='blue',font=('Helvetica',26),height=1,width=15,command=lambda: controller.show_frame(MainPage)).grid(row=10,column=1) buttonnext=Button(f,text='Next',fg='blue',font=('Helvetica',26),height=3,width=15,command=lambda: controller.show_frame(Page02)).grid(row=10,column=2) #Page02 class Page02(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Page 02!!!", font=LARGE_FONT) label.pack(pady=10,padx=10) button1 = tk.Button(self, text="Back to Home", command=lambda: controller.show_frame(MainPage)) button1.pack() button2 = tk.Button(self, text="Page 01", command=lambda: controller.show_frame(PageSub35t)) button2.pack() #Root loop app = ChangePages() app.mainloop() What I want to do is: When the user presses next in pag01, I want to check the states of radio buttons. For example if the user chose "Option 1 -A" and "Option 2 -C", I want to popup a message saying "You are not allowed to choose 2c! You can choose 2c only if 1B is selected" and not let him to go to page02. Answer: I understand your problem and how you want to solve it. But, from an user experience point of view there is a better way of doing this. Instead of showing the user options that the user can't choose and displaying error messages, it is better to **only show the user what he can choose**. Scenario example: > User selected Option 1 -A > > The Radio button Option 2 -C turns grey(disabled) Here is a demo: #very bad code #http://stackoverflow.com/questions/28900100/python-tkinter-check-radio-button-state-before-proceed/28901595#28901595 try:#3.X import tkinter as tk except ImportError:#2.X import Tkinter as tk #use ttk cascade style techniques instead !!! LARGE_FONT= ("Verdana", 12) class ChangePages(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack() #use grid everywhere container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (MainPage, Page01, Page02): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(MainPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class MainPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) button1 = tk.Button(self,text='Go To Page 1',fg='blue',font=('Helvetica',26),height=5, width=20,command=lambda: controller.show_frame(Page01)).grid(row=1,column=1) class Page01(tk.Frame): def __init__(self, parent, controller): option1 = tk.IntVar() option2 = tk.IntVar() option3 = tk.IntVar() tk.Frame.__init__(self, parent) f = tk.Frame(self) f.pack(side='left') label1 = tk.Label(f,text='Select options',fg='blue', font=("Arial", 36, "bold"),width=54, relief='solid').grid(row=1,column=1,columnspan=3) #not used #labelspacing = tk.Label(f,text='Option 1 ',font=("Arial", 18, "bold"),width=20,height=1).grid(row=2,column=1) #labelspacing = tk.Label(f,text='Option 2 ',font=("Arial", 18, "bold"),width=20,height=1).grid(row=2,column=2) #labelspacing = tk.Label(f,text='Option 3',font=("Arial", 18, "bold"),width=20,height=1).grid(row=2,column=3) buttonoption21 = tk.Radiobutton(f, text="Option 2 - A", variable=option2, value=1, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20) buttonoption21.grid(row=3,column=2) buttonoption22 = tk.Radiobutton(f, text="Option 2 - B", variable=option2, value=2, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20) buttonoption22.grid(row=4,column=2) buttonoption32 = tk.Radiobutton(f, text="Option 3 - B", variable=option3, value=2, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20) buttonoption32.grid(row=4,column=3) buttonoption23 = tk.Radiobutton(f, text="Option 2 - C", variable=option2, value=3, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20) buttonoption23.grid(row=5,column=2) # this entire list is affected by switch_all_button() list_conditional = [buttonoption21, buttonoption22, buttonoption32, buttonoption23] def switch_button(button, active=True): if button is not None: button['state'] = {True: tk.NORMAL, False: tk.DISABLED}[active] #here you can also unselect def switch_all_button(active=True): for button in list_conditional: switch_button(button, active=active) def after_option_command(what_button_should_be_disabled=None): def after_option(): switch_all_button(active=True) switch_button(what_button_should_be_disabled, active=False) return after_option # to update the state of other buttons after 1 is pressed # use command=after_option_command(button_x) in the constructor buttonoption11 = tk.Radiobutton(f, command=after_option_command(buttonoption23), text="Option 1 - A", variable=option1, value=1, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20) buttonoption11.grid(row=3,column=1) buttonoption12 = tk.Radiobutton(f, command=after_option_command(), text="Option 1 - B", variable=option1, value=2, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20) buttonoption12.grid(row=4,column=1) buttonnback = tk.Button(f,text='Back',fg='blue',font=('Helvetica',26),height=1,width=15,command=lambda: controller.show_frame(MainPage)).grid(row=10,column=1) buttonnext = tk.Button(f,text='Next',fg='blue',font=('Helvetica',26),height=3,width=15,command=lambda: controller.show_frame(Page02)).grid(row=10,column=2) class Page02(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Page 02!!!", font=LARGE_FONT) label.pack(pady=10,padx=10) button1 = tk.Button(self, text="Back to Home", command=lambda: controller.show_frame(MainPage)) button1.pack() button2 = tk.Button(self, text="Page 01", command=lambda: controller.show_frame(PageSub35t)) button2.pack() #Root loop app = ChangePages() app.mainloop() You don't need to import tkinter twice. Use this syntax try: # 3.X import tkinter as tk except ImportError: # 2.X import Tkinter as tk will force you to use `tk.` every time you are using a tkinter object explicit better than implicit. It will also work with Python 3. #Page02 class Page02(tk.Frame): this is a useless comment because it doesn't add value. The code is poor quality, but here's how to fix it: * Follow PEP8 * Do not use classes as keys for dicts * Instead of describing the look inside your main code, do it outside or on top of the file using `ttk` and `ttk.Style()` * Widget.grid method returns None, which means `buttonoption11 = tk.Radiobutton(f, command=after_option_command(buttonoption23), text="Option 1 - A", variable=option1, value=1, indicatoron=0, fg='blue',font=('Helvetica',26),height=1, width=20).grid(row=3,column=1)` * buttonoption11 is not a `tk.Radiobutton` but `None` * use .grid everywhere unless you have a very good reason not to * use for loops to create similar widgets **Warning** the code I gave is not fixed, do not use it before you apply all tips given above edit: works as expected in the comment, read the comments to extend the API
Django REST || Python? Class attributes as a key-value pair array Question: I'm currently doing the [Django REST Framework tutorial](http://www.django- rest-framework.org/tutorial/1-serialization/) and I came across something when testing that confused me. >>> snippet =Snippet(code='foo = "bar"\n') >>> snippet.save() >>> snippet = Snippet(code='print "hello, world"\n') >>> snippet.save() >>> serializer = SnippetSerializer(snippet) >>> serializer.data >>> {'style': 'friendly', 'code': u'print "hello, world"\n', 'language': 'python', 'title': u'', 'linenos': False, 'pk': 2} Specifically that last line. I don't define a `data` class or instance attribute. The `SnippetSerializer` class is defined as the following: from django.forms import widgets from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): pk = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={'base_template': 'textarea.html'}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') def create(self, validated_data): """ Create and return a new 'Snippet' instance, given the validated data. """ return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing 'Snippet' instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() return instance I see that the `SnippetSerializer` class is relatives with `serializers.Serializer` (right?), but it doesn't seem there is a `data` attribute there either. It obviously works and allows me to access all of `SnippetSerializers` attributes as a key-value pair array. I just couldn't find documentation of this anywhere. Is `data` a reserved word in python? Is this something unique to Django REST? Or is there some inheritance that I'm not seeing? Thank you in advance! Answer: `data` is a property on the BaseSerializer class, from which Serializer inherits. See [the code](https://github.com/tomchristie/django-rest- framework/blob/master/rest_framework/serializers.py#L200).
Issue with Selenium and Tableau Server Question: Trying to change a filter on tableau dashboard hosted on tableau server through selenium script. Need to know whether there are some restrictions on tableau server or do we have any work around for the same. Here is the code: from selenium import webdriver from selenium.webdriver.support import ui from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome('C:\\Python27\\Scripts\\chromedriver.exe') driver.get("PATH Name") dropdowmclick = driver.find_element_by_class_name("tabComboBoxName") dropdowmclick.click() time.sleep(20) driver.close() Require help here. Answer: Selenium is a browser automation tool and mimics real user actions on the page. Generally speaking, it doesn't matter what is there under test in the browser. Just one specific note about `tableau`: since it uses AJAX a lot and different parts of a page are loaded asynchronously, you would have to use [Explicit Waits](http://selenium-python.readthedocs.org/en/latest/waits.html#explicit- waits) a lot - avoid hardcoded time sleep intervals and explicitly wait for specific elements before interacting with them.
Errors when I start the Python shell, errors from a script I ran a week ago Question: I've been learning python and I there is a problem with my Python interactive shell on one of my systems. It runs a script on every python-interactive-mode start(without arguments). I don't know where to look for a process that does this, I've programmed a lot of small scripts on this system, and I can see what script is messing around, When I do this: user@Host ~/Python Scripts> python I get: Python 3.4.2 (default, Feb 21 2015, 22:19:02) [GCC 4.9.2 20150212 (Red Hat 4.9.2-6)] on linux Type "help", "copyright", "credits" or "license" for more information. # ! / u s r / b i n / e n v p y t h o n finished Failed calling sys.__interactivehook__ Traceback (most recent call last): File "/usr/local/opt/python-3.4.2/lib/python3.4/site.py", line 396, in register_readline import rlcompleter File "/usr/local/opt/python-3.4.2/lib/python3.4/rlcompleter.py", line 161, in <module> readline.set_completer(Completer().complete) AttributeError: 'module' object has no attribute 'set_completer' >>> quit() Here is the file I ran, and is run on every python start: #!/usr/bin/env python try: number = int(input("Enter a number: ")) print(number) aFile = open('modules.py') for i in aFile: print(aFile.readline(), end=' ') except ValueError: print('Not a number, please re-enter:') number = int(input('Enter a number: ')) print(number) except IOError: print('Cannot open file') print('finished') What is causing this and how do I fix it? EDIT #1 The system is Fedora 21, the file modules.py and the script that runs on start of the interactive shell are scripts that have never been edited on a Windows system. The system has not been rebooted for 11 day's. Here is: ~/Python Scripts> file tryexcept.py tryexcept.py: Python script, ASCII text executable EDIT #2 I have a readline.py in my current working directory: ~/Python Scripts> ls | grep readline readline.py Answer: The last part of `rlcompleter.py` trys to import readline and then runs the line you error on. try: import readline except ImportError: pass else: readline.set_completer(Completer().complete) # Release references early at shutdown (the readline module's # contents are quasi-immortal, and the completer function holds a # reference to globals). atexit.register(lambda: readline.set_completer(None)) There must be a `readline.py` file somewhere in your path that you are importing instead of the actual python module. If you don't have a readline.py but once had then look for a `readline.pyc` file. Put a `import readline;print(readline.__file__)` in your interpreter and see what exactly you are importing
How to append the logs in python Question: There are two files named file1 and file2 in the python project. In file1.py , Iam capturing the log to file 'sample.log' and executing the file2.py through os.system() command. In file2.py, I am opening the sample log file sample.log in appending mode and sending logs to that file. I have executed the file1.py, even though I have opened the log file(file2.py) in append mode , I am unable to see the file2.py log. File2 contents are overridden by file1 contents. How Can I append file2.py logs with file1.py logs in sample.log? **file1.py** import logging import os logFile = 'sample.log' logging.basicConfig( filename = logFile,filemode = 'w',level = logging.DEBUG,format = '%(asctime)s - %(levelname)s: %(message)s',\ datefmt = '%m/%d/%Y %I:%M:%S %p' ) logging.debug("Starting of the file1") os.system("python file2.py") for i in range(0,2): logging.debug("Iam in file1") **file2.py:** import logging logFile = 'sample.log' logging.basicConfig( filename = logFile,filemode = 'a',level = logging.DEBUG,format = '%(asctime)s - %(levelname)s: %(message)s',\ datefmt = '%m/%d/%Y %I:%M:%S %p' ) for i in range(0,2): logging.debug("Iam in file2") Need the output like this > 03/06/2015 08:02:03 PM - DEBUG: Starting of the file1 > > 03/06/2015 08:02:03 PM - DEBUG: Iam in file2 > > 03/06/2015 08:02:03 PM - DEBUG: Iam in file2 > > 03/06/2015 08:02:03 PM - DEBUG: Iam in file1 > > 03/06/2015 08:02:03 PM - DEBUG: Iam in file1 but getting like this: > 03/06/2015 08:02:49 PM - DEBUG: Starting of the file1 > > 03/06/2015 08:02:49 PM - DEBUG: Iam in file1 > > 03/06/2015 08:02:49 PM - DEBUG: Iam in file1 Could someone help in this to get my expected output, Thanks in Advance Answer: There are two main faults with your approach: 1. There should only be one logger on a file. If you are going to use `os.system` you'll have to use two log files because you can't open a duplicate Logger handle in file2.py. 2. You have different write-modes which causes a race condition. It could be that your `filemode='a'` completes all of its writes and then `filemode='w'` overwrites the log file from the start, clearing all previously written "file2" logging output.
Why do I have to open my csv twice? Question: Assume I have a csv file where I first need to get the number of rows in order to initialize an array. Then I want to fill the array with the rows from the file (but only some columns): import csv import numpy with open('a_csv_file', 'rb') as f: num_row = sum(1 for row in f) myarray = numpy.empty(shape=(num_row, 50), dtype=numpy.int16) infileReader = csv.reader(f) for row in infileReader: row_number = infileReader.line_num - 1 my_array[row_number] = [int(row[7])] + row[21:70] However, the script doen't enter the row-loop. But `print infileReader` is confirms the existence of `infileReader`. Now I open `a_csv_file.csv` twice, but I think that's not pythonic: with open('a_csv_file', 'rb') as f: num_row = sum(1 for row in f) myarray = numpy.empty(shape=(num_row, 50), dtype=numpy.int16) with open('a_csv_file', 'rb') as f: infileReader = csv.reader(f) for row in infileReader: row_number = infileReader.line_num - 1 my_array[row_number] = [int(row[7])] + row[21:70] Why do I have to open the csv file twice? Answer: When you iterate through the file (to count the length), your position in the file is left at the end. When you try and iterate over it again, there is nothing left so the loop is not entered. Before you create the `csv.reader` call `f.seek(0)` to return to the start. See the docs for the `seek` method [here](https://docs.python.org/3.4/library/io.html#io.IOBase.seek)
Redirect with HttpResponseRedirect to another function in python Question: I have a function : def drawback(request,problem_id) and I want in the end of this function to redirect to another page that is called from function def show(request,problem_id) I tried with return HttpResponseRedirect(reverse('show',kwargs={'problem_id':10})) return HttpResponseRedirect(reverse('show',kwargs={'problem_id':'10'})) return HttpResponseRedirect(reverse('show',args=[10])) return HttpResponseRedirect(reverse('show',args=(10)) Everything I found in other sites. But I receive the error Exception Type: NoReverseMatch Exception Value: Reverse for 'show' with arguments '()' and keyword arguments '{'problem_id': '10'}' not found. or Exception Value: Reverse for 'show' with arguments '(u'10',)' and keyword arguments '{}' not found. This function and page works when I call it through html with a button. When I try to redirect from drawback function is not working. urls.py from django.conf.urls.defaults import * from views import * import settings from django.conf import settings as rootsettings urlpatterns = patterns('', # authentication (r'^start_auth', start_auth), (r'^after_auth', after_auth), # screens (r'^problems/codelookup$', code_lookup), # TESTING (r'^problems/test$', test_message_send), (r'^donnorsTool/$', problem_list), (r'^problems/delete/(?P<problem_id>[^/]+)', archived_problem), (r'^problems/edit/(?P<problem_id>[^/]+)', edit_problem), (r'^problems/restore/(?P<problem_id>[^/]+)', restore_problem), (r'^problems/new$', new_problem), (r'^problems/archived$', archived_problems), (r'^donnorsTool/show/(?P<problem_id>[^/]+)', show), (r'^donnorsTool/consent/(?P<problem_id>[^/]+)/(?P<counter>[^/]+)', consent), (r'^donnorsTool/withdraw/(?P<problem_id>[^/]+)/(?P<counter>[^/]+)', withdraw), # static ## WARNING NOT FOR PRODUCTION (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': rootsettings.SERVER_ROOT_DIR + settings.STATIC_HOME}), ) Answer: Just call it like a function : def drawback(request,problem_id) ... ... return show(request,10)
How to interact with python's subprocess as a continuous session Question: I need to implement a filter in python, which pick out specific outputs from a Linux command-line dictionary tool. I need to: 1. Get a set of words from a file 2. Lookup each word: 1) if word not contains, skip it; 2) else if it is a verb, save the definition. To test the code, I wrote two python file: # name.py import sys while True: print 'name => Q: what is your name?' sys.stdout.flush() name = raw_input() if name == 'Exit': break print 'name => A: your name is ' + name sys.stdout.flush() # test.py import subprocess child = subprocess.Popen(r'python name.py', stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True) commandlist = ['Luke\n', 'Mike\n', 'Jonathan\n', 'Exit\n'] for command in commandlist: child.stdin.write(command) child.stdin.flush() output = child.stdout.readline() print 'From PIPE: ' + output while child.poll() is None: print 'NOT POLL: ' + child.stdout.readline() child.wait() The output is From PIPE: name => Q: what is your name? From PIPE: name => A: your name is Luke From PIPE: name => Q: what is your name? From PIPE: name => A: your name is Mike # these lines need to start with "From PIPE" ... NOT POLL: name => Q: what is your name? NOT POLL: name => A: your name is Jonathan NOT POLL: name => Q: what is your name? NOT POLL: The later output is read during the `while` loop rather than the `for` loop in `test.py`. What is the reason? Due to the demand, I need to get the whole output each time it input a new command. It seems like a dialog session. So the `subprocess.communicate()` is useless there, for it always terminates current subprocess. How to implement this demand? Answer: The basic reason `subprocess` insists you use `.communicate()` is because it's possible for deadlock to occur otherwise. Suppose you're writing to the process's stdin, while the process is writing to its stdout. If the pipe buffers fill up, the writes will block until a read occurs. Then you're both waiting for each other and no progress can be made. There are several ways to deal with this: 1. Use separate threads. Assign one to stdin and the other to stdout. That way, if one pipe blocks, you're still servicing the other. 2. Use `select` to multiplex over the pipes. Only interact with pipes which are ready for you. You should also enable `O_NONBLOCK` on the pipes using `fcntl`, so you don't accidentally fill the buffers. Used correctly, this will prevent the pipes from ever blocking, so you can't deadlock. **This doesn't work under Windows** , because you can only do `select` on sockets there.
How do I select a random element from a 2d list Question: I'm trying to select a random element in a 2D list in python. I'm creating a blackjack game. > I'm aware of how long and non-optimized this code is, but I'm new to > programming and I want to make mistakes to learn. > > Here's the initial code that I have set up. I create the suits (spades, > clubs, hearts, diamonds). I append it to the list called list_of_cards which > was initialized as an empty array. > > Then I have another list called player_card for the player to view. Here it > is in reference. list_of_suits= [] #Creating list of cards player_card = [] king_of_spades = 10 #Creating face cards for the spades deck. queen_of_spades = 10 jack_of_spades = 10 king_of_clubs = 10 queen_of_clubs = 10 jack_of_clubs = 10 king_of_hearts = 10 queen_of_hearts = 10 jack_of_hearts = 10 king_of_diamonds = 10 queen_of_diamonds = 10 jack_of_diamonds = 10 ace_of_spades = [1,11] # Aces are either 1 or 11 ace_of_clubs = [1,11] ace_of_hearts = [1,11] ace_of_diamonds = [1,11] spades = [ace_of_spades,2,3,4,5,6,7,8,9,10, jack_of_spades, queen_of_spades, king_of_spades] clubs = [ace_of_clubs,2,3,4,5,6,7,8,9,10, jack_of_clubs, queen_of_clubs, king_of_clubs] hearts = [ace_of_hearts,2,3,4,5,6,7,8,9,10, jack_of_hearts, queen_of_hearts, king_of_hearts] diamonds = [ace_of_diamonds,2,3,4,5,6,7,8,9,10, jack_of_diamonds, queen_of_diamonds, king_of_diamonds] list_of_suits.append(spades) list_of_suits.append(clubs) list_of_suits.append(hearts) list_of_suits.append(diamonds) > This is the selector for a random card. It will iterate through the array to > select one of the four cards randomly. Next, it will go into that array and > choose a random card. random_list_of_suits = random.choice(list_of_suits) random_card_number = random.choice(random_list_of_suits) random_list_of_suits.remove(random_card_number) player_card.append(random_card_number) print player_card print list_of_suits > Here's what I'm trying to figure out: How do I create a new random number > each time? > > I'm kind of stuck and I tried putting it through a for loop, but if I put > the random_card_number in a loop, it will select the same random card that > it did initially four times. Answer: import random list2d = [range(0, 5), range(5, 10), range(10, 15), range(15, 20)] for i in range(0, 10): random_suite = random.choice(list2d) random_card = random.choice(random_suite) print random_suite, random_card output: [5, 6, 7, 8, 9] 7 [5, 6, 7, 8, 9] 5 [5, 6, 7, 8, 9] 5 [10, 11, 12, 13, 14] 11 [10, 11, 12, 13, 14] 13 [10, 11, 12, 13, 14] 12 [10, 11, 12, 13, 14] 14 [10, 11, 12, 13, 14] 10 [10, 11, 12, 13, 14] 10 [0, 1, 2, 3, 4] 2
Create a file object from raw binary information in Python Question: ### Question What is a clean way to create a file object from raw binary information in Python? ### More Info The reason I need to do this is because I have the raw binary information comprising a jpeg image stored in ram. I need to put it inside some kind of file object so that I can resize the image using Python's [Pillow](http://pillow.readthedocs.org/en/latest/about.html) library. According to the [pillow documentation](http://pillow.readthedocs.org/en/latest/reference/Image.html), the file object needs to implement the `read()`, `seek()`, and `tell()` methods. The file object must implement read(), seek(), and tell() methods, and be opened in binary mode. Answer: I was able to find a mention of how to handle this situation under the documentation for `PIL.Image.frombytes`: ...If you have an entire image in a string, wrap it in a BytesIO object, and use open() to load it. This is what I ended up with that worked using `BytesIO`: import io import PIL from PIL.Image import Image file_body = <binary image data> t_file = io.BytesIO(file_body) img = PIL.Image.open(t_file) Note: The comments mention `tempfile.SpooledTemporaryFile`. This seems like it should have worked, but it did not for some reason.
Python Snakefood module import generalized failure Question: I want to run [snakefood](http://furius.ca/snakefood/doc/snakefood-doc.html) (an AST-based dependency graph analyser; source code can be found [here](https://bitbucket.org/blais/snakefood/src/e0a74fa6260dcd44716d40b4eb404ca024323eac/lib/python/snakefood/gendeps.py?at=default)). My project has a structureinvolving several levels of Python packages, like this: myproject |code |Utils |AdaptedConfigParser Configs_Parser.py ... ... main.py However, when I start running snakefood on the root directory of my project it claims that it can't find the modules from my Python package being imported: $ sfood --internal --follow --ignore-unused ./PycharmProjects/myproject/ > ~/static_analysis.txt WARNING : Line 9: Could not import module 'myproject.Utils.AdaptedConfigParser.Configs_parser' I tried to get around it by adding a `.pth` file with the project root to the `lib/python2.7/site-packages` Now when I call python with that virtual environment activated from anywhere, I can do the following: $ python Python 2.7.6rc1 (default, Jan 19 2014, 18:57:40) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import myproject.Utils.AdaptedConfigParser.Configs_parser >>> And it works just fine. However, when snakefood is launched with that virtual environement, it still returns the same error. $ sfood --internal --follow --ignore-unused ./PycharmProjects/myproject/ > ~/static_analysis.txt WARNING : Line 9: Could not import module 'myproject.Utils.AdaptedConfigParser.Configs_parser' At this point I don't even understand where the problem with imports could come from. In addition to that, when `--internal` flag is taken away, it fails imports even of the python `builtin` module, which doesn't make any sense to me: WARNING : Line 80: Could not import module 'builtins' WARNING : Line 190: Could not import module 'pyamg' Have anyone encountered such a problem previously? If yes, is there a way of getting around it? Answer: I had similar issues, turns out the warning in my case was generated because of `__all__` declarations. e.g. __all__ = ['abc', 'aaa', ... ] Above code gives out the warnings: WARNING : Line xx: Could not import module 'abc' WARNING : Line xx: Could not import module 'aaa' I modified the warning constant `ERROR_IMPORT` within `snakefood\lib\python\find.py` to add the name of the file where the error occurs along with the line number and module name. That way you can target the specific file and line number pretty much figure out the problem. Hope this helps!
How does the code know when to split into a line? Question: So I was learning on how to download files from the web using python but got a bit thrown by one part of the code. Here is the code: from urllib import request def download_stock_data(csv_url): response = request.urlopen(csv_url) csv = response.read() csv_str = str(csv) lines = csv_str.split("\\n") dest_url = r"stock.csv" fx = open(dest_url, "w") for line in lines: fx.write(line + "\n") fx.close() I don't quite understand the code in the variable lines. How does it know when to split into a new line on a csv file ? Answer: A csv file is essentially just a text file will comma separated data but they also contain new lines (via the newline ascii character). If there a csv file with a long single comma separated line for line in lines: would only see the single line. You can open it up in notepad++ or something to see the raw .csv file. Excel will put data seperated by commas in a cell,and data on a new line into a new row.
Failed to run Python script with Conda Question: I tried to install menpo like in [this tutorial](http://www.menpo.org/installation/windows/index.html). After that I installed menpofit, menpo3d and menpodetect: > conda install -c menpo menpofit > > conda install -c menpo menpo3d > > conda install -c menpo menpodetect Next I ran this python script from CMD(_python testPy.py_): import menpo.io as mio from menpo.visualize import visualize_images images = list(mio.import_images('A:/img/*.png')) visualize_images(images) And got this output: ![enter image description here](http://i.stack.imgur.com/goBBx.png) What am I doing wrong and how I can fix it? Answer: It seems that `visualize_images` is meant to be used from `ipython-notebook`. Calling it in a regular `python` script does not seem to be intended by the authors. See also the example in the [`Visualizing Objects`](http://menpo.readthedocs.org/en/latest/userguide/visualization.html#visualizing- a-list-of-2d-images) section of the docs: %matplotlib inline import menpo.io as mio from menpo.visualize import visualize_images # import_images is a generator, so we must exhaust the generator before # we can visualize the list. This is because the widget allows you to # jump arbitrarily around the list, which cannot be done with generators. images = list(mio.import_images('./path/to/images/*.jpg')) visualize_images(images)
Python won't advance Question: Question: What would be the issue if python continues to ask for the same input over and over again, and won't advance to the end of the program? Where do you want to go? X And how many days will you be staying in X? 1 And how many days will you be staying in X? 2 And how many days will you be staying in X? 164 And how many days will you be staying in X? 59 ... Here's the relevant part of the code: # Import modules import destinations import currency save_itinerary = True main_function = True while (main_function): # Determine length of stay while True: try: length_of_stay = int(input("And how many days will you be staying in " + destinations.destination[0] + "? ")) # Check for non-positive input if (length_of_stay <= 0): print("Please enter a positive number of days.") continue except ValueError: print("The value you entered is invalid. Only numerical values are valid.") break else: break Answer: The reason your code is looping forever is that you have two nested `while` loops, and you never break out of the outer one. You do use `break` statements to exit the inner loop, but the condition for the outer loop is never changed, and you never execute a `break` at the right level to exit it. Here's what I think a better version of your code would be: # get rid of the outer while loop, which was never ending while True: try: length_of_stay = int(input("And how many days will you be staying in " + destinations.destination[0] + "? ")) if (length_of_stay <= 0): print("Please enter a positive number of days.") continue except ValueError: print("The value you entered is invalid. Only numerical values are valid.") # don't break here, you want to stay in the loop! else: break I've used comments to indicate my changes. You could also move the `else: break` block up and indent it so that it is attached to the `if` statement, rather than the `try`/`except` statements (and then get rid of the unnecessary `continue` statement). That's makes the flow a bit more obvious, though there's not really anything wrong with how it is now.
Biopython: ImportError: No module named TreeConstruction Question: Someone knows why I get the following error? >>> from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> import Bio.Phylo.TreeConstruction ImportError: No module named TreeConstruction And also: >>> from Bio.Phylo.Consensus import * Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> from Bio.Phylo.Consensus import * ImportError: No module named Consensus Thanks to all for you time =) Answer: Ok. Fixed! The problem was that in the python IDLE, the version of biopython was 1.63, whereas the code >>>from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor works nice for version 1.65. So, the solution was delete the folder where biopython 1.63 was installed and download and later (re)install the biopython 1.65.
Counting matches / Comparing two text files in python with utf-8 encoding Question: i'm trying to compare two files in utf-8, gold_standard_1.txt with 2553 lines and output_test1.txt with 2476 lines, both disordered, and count if a line in one file matches with another line in the other text file (not necessary same line numbers). I have been trying many alternatives, like zip, intersections etc but does not work. Samples: gold_standard_1.txt: En Prep total Adj , Punt los Det organizadores NC de Prep la Det feria NC esperan V en Prep La_Habana NP a Prep por_lo_menos Adv 150 Num editoriales NC de Prep Europa NP , Punt América NP y Conj Asia NP , Punt donde Pron por Prep primera Adj vez NC concurrirán V representantes NC de Prep Alemania NP y Conj Japón NP , Punt además_de Prep las Det habituales Adj de Prep México NP , Punt Venezuela NP , Punt Argentina NP y Conj España NP , Punt según Prep dijo V el Det presidente NC del Prep Instituto_Cubano_del_Libro NP , Punt Pablo_Pacheco NP . Fin Para Prep la Det comercialización NC la Det feria NC dispondrá V de Prep cerca_de Prep 300.000 Num ejemplares Adj de Prep México NP , Punt Santo_Domingo NP , Punt Ecuador NP , Punt Venezuela NP , Punt Argentina NP , Punt Chile NP , Punt España_e_Inglaterra NP . Fin Durante Prep la Det feria NC se Pron desarrollará V un Det programa NC para Prep la Det lectura NC de Prep textos NC , Punt tertulias NC , Punt encuentros NC de Prep escritores NC y Conj la Det presentación NC de Prep una Det muestra V especializada Adj dedicada Adj al Prep medio_ambiente NC y Conj la Det alimentación NC . Fin Entre Prep los Det invitados NC figuran V el Det director NC general Adj del Prep Centro_Regional_del_Libro_para_América_Latina NP y Conj el Det Caribe NP , Punt José_Salgar NP , Punt la Det presidenta NC de Prep la Det Dirección_del_Libro_de_la_UNESCO NP , Punt Milagros_del_Corral NP y Conj Alfredo_Weisflog NP , Punt quien Pron encabeza V el Det grupo NC interamericano Adj de Prep editores NC . Fin También Adv ha VAux sido V anunciada Adj la Det presencia NC de Prep varios Det autores NC latinoamericanos Adj como Conj los Det argentinos NC Juan_Gelman NP , Punt Adolfo_Colombé NP y Conj Norberto_Galusso NP , Punt la Det salvadoreña NC Claribel_Alegría NP , Punt la Det chilena NC Stela_Díaz_Varín NP y Conj el Det mexicano NC Eraclio_Zepeda NP . Fin Además Adv , Punt en Prep la Det feria NC serán V homenajeados NC los Det escritores NC cubanos Adj Dulce_María_Loynaz NP , Punt ganadora Adj del Prep premio NC " Punt Cervantes NC " Punt de Prep literatura NC en Prep 1992 Num , Punt Eliseo_Diego NP , Punt premiado Adj con Prep el Det galardón NC " Punt Juan_Rulfo NP " Punt 1993 Num , Punt y Conj el Det recién Adv fallecido V Severo_Sarduy NP . Fin La Det feria NC es V convocada Adj cada Det dos Det años NC y Conj en Prep su Det programación NC incluye V la Pron entrega V del Prep Premio_Nacional_de_Literatura NP y Conj el Det de Prep la Det Crítica NP , Punt que Pron proclama NC los Det diez NC mejores Adj títulos NC publicados Adj el Det año NC pasado Adj . Fin Los Det cancilleres NC de Prep Centroamérica NP y Conj la Det Comunidad_Económica_del_Caribe NP ( Fin CARICOM NP ) Fin celebrarán V su Det tercera Adj reunión NC durante Prep la Det primera Adj semana NC de Prep marzo NC , Punt en Prep Costa_Rica NP , Punt para Prep analizar V asuntos NC comunes Adj a Prep ambas Det regiones NC y Conj la Det comercialización NC bananera Adj con Prep la Det Unión_Europea NP ( Fin UE NP ) Fin . Fin El Det canciller NC costarricense Adj , Punt Bernd_Niehaus NP , Punt dijo V que Conj en Prep esta Det reunión NC continuará V el Det análisis NC conjunto NC de Prep diversas Det cuestiones NC , Punt como Conj en Prep las Det dos Det anteriores Adj reuniones NC , Punt celebradas Adj en Prep San_Pedro_Sula NP ( Fin Honduras NC ) Fin , Punt en Prep 1992 Num , Punt y Conj en Prep Kingston NP , Punt la Det capital NC jamaicana Adj , Punt el Det año NC pasado Adj . Fin Niehaus NP consideró V que Conj la Det comercialización NC bananera Adj no Adv estará V ausente Adj de Prep esta Det reunión NC , Punt por Prep la Det importancia NC que Pron reviste V para Prep la Det mayoría NC de Prep naciones NC centroamericanas Adj y Conj caribeñas Adj , Punt muchas Pron de Prep las Det cuales Pron dependen V en_gran_medida Adv de Prep la Det exportación NC de Prep esta Det fruta NC . Fin Las Det restricciones NC impuestas Adj por Prep la Det UE NP a Prep la Det importación NC de Prep esta Det fruta NC desde Prep julio NC pasado Adj y Conj que Pron afectan V a Prep América_Latina NP favorecen V a Prep varios Pron de Prep los Det países NC del Prep CARICOM NP , Punt que Pron fueron V colonias NC europeas Adj . Fin El Det canciller NC dijo V que Conj se Pron debe V buscar V un Det acuerdo NC sobre Prep comercialización NC del Prep banano NC con Prep la Det UE NP que Pron no Adv afecte V a Prep la Det región NC caribeña Adj ni Conj a Prep los Det productores NC de Prep Latinoamérica NP , Punt quienes Pron han VAux visto V reducir V sus Det exportaciones NC de Prep la Det fruta NC de Prep 2,5 Num a Prep 2 Num millones NC de Prep toneladas NC por Prep las Det barreras NC europeas Adj . Fin Los Det países NC productores Adj de Prep café NC suave Adj de Prep América_Latina NP se Pron reunirán V mañana NC viernes NC en Prep Guatemala NP para Prep analizar V los Det primeros Adj resultados NC del Prep plan NC de Prep retención NC y Conj el Det comportamiento NC de Prep las Det exportaciones NC del Prep grano NC en Prep el Det mercado NC internacional Adj . Fin La Det Asociación_Nacional_de_Café NP ( Fin ANACAFE NP ) Fin de Prep Guatemala NP indicó V que Conj la Det reunión NC , Punt a Prep la Det que Pron asistirán V Centroamérica NP y Conj Colombia NP , Punt servirá V también Adv para Prep analizar V el Det Convenio_Internacional_de_Café NP y Conj para Prep revisar V los Det avances NC de Prep la Det creación NC de Prep la Det Asociación_de_Países_Productores_de_Café NP ( Fin APC NP ) Fin . Fin Los Det representantes NC evaluarán V el Det impacto NC que Conj ha VAux tenido V el Det plan NC de Prep retención NC en Prep el Det precio NC del Prep grano NC , Punt que Pron entró V en Prep vigor NC el Det 1_de_octubre Data pasado Adj , Punt y Conj cómo Pron ha VAux afectado V a Prep la Det posición NC de Prep Brasil NP , Punt que Pron aún Adv no Adv lo Pron acepta V completamente Adv . Fin De Prep acuerdo NC con Prep ANACAFE NP , Punt los Det seis Det países NC han VAux retenido V el Det 20 Num por Prep ciento NC de Prep las Det exportaciones NC , Punt lo Det que Pron ha VAux permitido V que Conj el Det quintal NC ( Fin de Prep 50 Num kilos NC ) Fin , Punt puesto NC en Prep Nueva_York NP , Punt aumente V de Prep 60 Num a Prep 75 Num dólares NC . Fin Con_relación_al Prep acuerdo NC de Prep creación NC de Prep la Det asociación NC , Punt suscrito Adj en Prep septiembre NC pasado Adj en Prep Brasilia NP y Conj que Pron representaría V a Prep más Adv del Prep 50 Num por Prep ciento NC de Prep los Det exportadores NC de Prep café NC a_nivel Adv mundial Adj , Punt los Det países NC signatarios Adj informarán V sobre Prep el Det procedimiento NC de Prep ratificación NC . Fin Resultados NC de Prep la Det novena Adj jornada NC y Conj clasificaciones NC de Prep los Det Grupos_A NP y Conj B_de_la_Liga_Europea NP masculina Adj de Prep baloncesto NC : Punt - Punt Resultados NC : Punt -- Punt Grupo_A NP : Punt Barcelona NP ( Fin ESP NP ) Fin 77 Num - Punt Benetton_Treviso NP ( Fin ITA Adj ) Fin 68 Num Bayer_Leverkusen NP ( Fin ALE NC ) Fin 87 Num - Punt Limoges NP ( Fin output_test1.txt tertulias NC Según unknown tenido V Fiscalía_General unknown fuente NC PJ_PG_PP_PF_PC_PTOS NP PJ_PG_PP_PF_PC_PTOS NP magistrado NC magistrado NC invitados NC depositó unknown ciudad NC primer Adj YUG NP pobreza NC celebradas Adj según unknown a_pesar_de Prep viajar V suave Adj vez NC quienes Pron 0 Num masculina Adj encuentros NC solución unknown 665 Num negociación unknown empresario NC feria NC feria NC feria NC feria NC feria NC seis Det cómo unknown alcanzando V estaba V región unknown 718 Num exportadores NC 714 Num 711 Num 710 Num BARCELONISTAS_SALVARON_DIFICIL_ESCOLLO NP ausente Adj tratar V Benetton_Treviso NP francés unknown imputadas Adj ilegales Adj dictó unknown -- Punt -- Punt -- Punt reducir V además_de unknown a_nivel Adv afirmó unknown recabados V meses NC mundial Adj peores Adj suscrito V pueblos NC tenía unknown BEL NC balneario Adj cuentas NC cuentas NC cuentas NC señalaron unknown Pablo_Pacheco NP Grecia NP reviste V abogado V abogado V comprado V importación unknown sentencia NC sentencia NC Latinoamérica unknown Chiapas NP Francia NP Francia NP Francia NP Francia NP Gaspar_Wittgren NP escándalo unknown para_que Conj para_que Conj para_que Conj Butros_Gali NP entrega V sus Det sus Det sus Det sus Det sus Det Caribe Adj capital NC ; Punt EP_Estambul-Panathinaikos_Cibona_Zagreb-Joventut_Benfica_Lisboa-Clear_Cantú_Pau_Orthez-Buckler_Bolonia unknown títulos unknown Grupo_A NP Grupo_A NP reuniones NC 77-68 Num Brasilia NP Chipre NP Asociación_de_Países_Productores_de_Café unknown acuerdo NC acuerdo NC acuerdo NC GRE NP GRE NP GRE NP sucedía unknown mes NC mes NC Thomas_K._Equels NP dedicada Adj norteamericanas Adj viaje NC viaje NC Adolfo_Colombé unknown congelar V 38 Num Clark NP A_través_de unknown 30 Num precio NC Policía_Federal unknown barreras NC 44 Num 44 Num oficial Adj acción unknown 645 Num incremento NC clima NC ING NP julio NC importancia NC apropió unknown ONU_para_Chipre NP Además unknown Stela_Díaz_Varín unknown unos Pron unos Pron semana NC semana NC 2,5 Num otros Det presidenta NC Ecuador NC presidente NC presidente NC presidente NC presidente NC presidente NC presidente NC presidente NC Diez Det internacional Adj internacional Adj internacional Adj Europa NP Europa NP Bayer_Leverkusen NP Bayer_Leverkusen NP Instituto_Cubano_del_Libro NP espectadores NC activades NC conocer V europeas NC europeas NC francesa Adj francesa Adj hacían unknown informarán unknown Iacopini NP 6 Num 6 Num 6 Num 6 Num 6 Num galardón unknown José_Salgar unknown Unión_Europea unknown zona NC Pau_Orthez NP Pau_Orthez NP programación unknown Premio_Nacional_de_Literatura NP asistirá unknown mayoría unknown sublevado V novena Adj novena Adj especialista NC servirá unknown destacable Adj retención unknown Cervantes NC Vianini NP 94 Num tribunal NC tribunal NC 1993 Num 1992 Num 1992 Num 40 Num 40 Num 40 Num autónomo unknown servido V ALE NC mi Det mi Det temas NC editoriales NC Buckler_Bolonia NP Buckler_Bolonia NP del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep del Prep permita V Colombia NP política unknown problemas NC tampoco Adv vigor NC creación unknown 558 Num La NP La NP La NP La NP prisión unknown financieras Adj Comunidad_Económica_del_Caribe unknown propicio Adj mercado NC Collor NP Collor NP Collor NP Collor NP Collor NP proceso NC proceso NC proceso NC proceso NC proceso NC comercialización unknown lograr V Malinas NP fuentes NC fuentes NC impacto NC recién unknown representaría unknown Dirección_de_Recuperación_Patrimonial_de_la_Contraloría_General_de_la_Nación unknown Manuel_Antonio_Noriega NP ene NC Yo NP asistirán unknown 1 Num presunta Adj Alemania NP acordadas Adj años unknown sin Prep Bayer_Leverkusen-Barcelona_Benetton_Treviso-Racing_Malinas_Limoges-Guilford_Kings_Olympiakos-Real_Madrid NP iberoamericana Adj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj y Conj 4.850 Num culpables Adj Gran_Bretaña unknown rechaza V Destacó unknown UE NP UE NP UE NP Pittis NP director NC sometido V hombre NC brasileño unknown especializada Adj las Det las Det las Det las Det las Det las Det las Det las Det las Det las Det las Det las Det las Det las Det las Det las Det a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep a Prep trata V muertos Adj canciller NC canciller NC su Det su Det su Det su Det su Det su Det su Det su Det su Det su Det su Det hasta Prep hasta Prep primera Adj primera Adj primera Adj entró unknown logros NC Incidencias NC 686 Num avances NC 680 Num intercomunitarias Adj 682 Num También unknown sucesor NC Próxima unknown connivencia NC dimitió unknown implantada V producen V Bernd_Niehaus NP España unknown mejores Adj miembros NC Eraclio_Zepeda NP 1_de_octubre Data ronda NC 22 Num la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det la Det sospechosas Adj lo Pron lo Pron lo Pron caribeña unknown fue V fue V fue V fue V fue V , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt , Punt As you can see, every line corresponds to: word+"\t"+tag Here is my code: with open("output_test1.txt", "r") as a, open("gold_standard_1.txt", "r") as b: dataA=a.readlines() dataB=b.readlines() aciertos = 0; for lineaA in dataA: lineaA.decode('latin_1').encode('utf-8') sintagmaA = lineaA.split('\t') for lineaB in dataB: lineaB.decode('latin_1').encode('utf-8') sintagmaB = lineaB.split('\t') print sintagmaB[0] print sintagmaA[0] if(sintagmaA[0] == sintagmaB[0] and sintagmaA[1]== sintagmaB[1]): aciertos+=1; break And if I try to print aciertos, at the end, the value is always 0...but there are matches!!! How can I compare the documents in the right form? Answer: Your current technique is quite inefficient as you iterate over the second file _for each line_ in the first. Try the code below. set_a, set_b = set(), set() with open('a', 'r') as a, open('b', 'r') as b: for line in a: set_a.add(line) for l in b: set_b.add(line) print set_a & set_b What this does is builds two sets, each with lines from file `a` abd `b`. Then it does an intersection `set_a & set_b` to get the lines that are common to both files. Replace `a` and `b` with your file names and do any additional encode / decode on the `line` in each for loop before adding it to the set. If not, the code will do an exact match of the lines (including leading / trailing whitespaces).
Python 3.4.3 subprocess.Popen get output of command without piping? Question: I am trying to assign the output of a command to a variable without the command thinking that it is being piped. The reason for this is that the command in question gives unformatted text as output if it is being piped, but it gives color formatted text if it is being run from the terminal. I need to get this color formatted text. So far I've tried a few things. I've tried Popen like so: output = subprocess.Popen(command, stdout=subprocess.PIPE) output = output.communicate()[0] output = output.decode() print(output) This will let me print the output, but it gives me the unformatted output that I get when the command is piped. That makes sense, as I'm piping it here in the Python code. But I am curious if there is a way to assign the output of this command, directly to a variable, without the command running the piped version of itself. I have also tried the following version that relies on check_output instead: output = subprocess.check_output(command) output = output.decode() print(output) And again I get the same unformatted output that the command returns when the command is piped. Is there a way to get the formatted output, the output the command would normally give from the terminal, when it is not being piped? Answer: Using [pexpect](https://pexpect.readthedocs.org/en/latest/install.html): 2.py: import sys if sys.stdout.isatty(): print('hello') else: print('goodbye') subprocess: import subprocess p = subprocess.Popen( ['python3.4', '2.py'], stdout=subprocess.PIPE ) print(p.stdout.read()) --output:-- goodbye pexpect: import pexpect child = pexpect.spawn('python3.4 2.py') child.expect(pexpect.EOF) print(child.before) #Print all the output before the expectation. --output:-- hello Here it is with `grep --colour=auto`: import subprocess p = subprocess.Popen( ['grep', '--colour=auto', 'hello', 'data.txt'], stdout=subprocess.PIPE ) print(p.stdout.read()) import pexpect child = pexpect.spawn('grep --colour=auto hello data.txt') child.expect(pexpect.EOF) print(child.before) --output:-- b'hello world\n' b'\x1b[01;31mhello\x1b[00m world\r\n'
Using python openpyxl, how to skip first several lines? Question: I am using openpyxl, I tried to read from the fifth line for some files. The files' first four lines are the header. then the main content has a different format than the header. And I tried the method: import openpyxl file_name="xxx.xlsx" wb = openpyxl.load_workbook(filename=file_name, use_iterators = True) first_sheet = workbook.get_sheet_names()[0] ws = workbook.get_sheet_by_name(first_sheet) for index, row in enumerate(ws.iter_rows()): if start < index < stop: for c in row: print c.value It will always have the error: IndexError: list index out of range If I delete the first four lines, the data can be read into python easily. But I have hundreds of such files, each file has a header for four lines. It will take way much time to delete all the headers from the files. How to skip first several lines when reading using openpyxl correctly? Answer: You can pass a range into `ws.iter_rows('A4:Z256')` but you're probably better off using `ws.get_squared_range(1, 5,)`
Caesar Cipher program was working but now isn't(help please) - Python 3 Question: I'm writing a Caesar Cipher code for a part of a controlled assessment. I built a fully functioning program and I thought I had it sussed but after changing a few things around I went to check back and everything has gone wrong! The code's quite untidy but I'm getting a bit sick of coding this now and have taken to the internet to get someone else's view. Code: answer ="C" while answer == "C": lettersList=['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','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'] def menu(): userChoice=input("Would you like to encrypt or decrypt a message? E or D.\n").lower() while userChoice != "e" and userChoice != "d": print("Invalid.") userChoice=input("Would you like to encrypt or decrypt a message? E or D.\n").lower() print("\n") return userChoice def getPlaintext(): plaintext= input("Please enter the message you would like encrypted/decrypted\n").lower() while plaintext.isalpha() == False: print("Invalid") plaintext=input("Please enter the message you would like encrypted/decrypted\n").lower() print("\n") return plaintext def getKey(): key=int(input("Please enter a key. 1-26\n")) while key > 26 or key < 1: print("Invalid.") key=int(input("Please enter a key. 1-26\n")) print("\n") return key def encryptText(plaintext,key): characterNumber = 0 newMessage = "" for characters in plaintext: character = plaintext[characterNumber] characterPosition = lettersList.index(character) newPosition=character+key newLetter = lettersList[newPosition] newMessage = (newMessage+newLetter) characterNumber= characterNumber+1 print(newMessage) def decryptText(plaintext,key): characterNumber = 0 newMessage = "" for characters in plaintext: character = plaintext[characterNumber] characterPosition = lettersList.index(character) print(characterPosition) newPosition=characterPosition-key newLetter = lettersList[newPosition] newMessage = (newMessage+newLetter) characterNumber= characterNumber+1 newMessage = (newMessage.lower()) print(newMessage) userChoice=menu() plaintext=getPlaintext() key=getKey() if userChoice == "e": encryptText(plaintext,key) elif userChoice == "d": decryptText(plaintext,key) print(newMessage) Answer: In decypryptText, newPosition can be negative. You should wrap around the whole alphabet in this case. The best way to do that is to use the % operator: newPosition = (characterPosition - key) % len(lettersList) By the way, using this in encryptText too lets you make lettersList only one copy of the alphabet, instead of the two copies you use. There are other things that can be polished in this code, but they are not as important as this one. Edit: if you want it capitalized for decryptText, you can make decryptText just return newMessage.upper(). In the same way, you can make encryptText return newMessage.lower().
Python Pandas - Main DataFrame, want to drop all columns in smaller DataFrame Question: I have a DataFrame ('main') that has about 300 columns. I created a smaller DataFrame ('public') and have been working on this. I now want to delete the columns contained within 'public' from the larger DataFrame ('main'). I've tried the following instructions: <http://pandas.pydata.org/pandas- docs/dev/generated/pandas.DataFrame.drop.html> [Python Pandas - Deleting multiple series from a data frame in one command](http://stackoverflow.com/questions/14363640/python-pandas-deleting- multiple-series-from-a-data-frame-in-one-command) without any success, along with various other statements that have been unsuccessful. The columns that make up 'public' are not consecutive - i.e. they are taken from various points in the larger DataFrame 'main'. All of the columns have the same Index. [Not sure if this is important, but 'public' was created using the 'join' function]. Yes, I'm being lazy - I don't want to have to type out the names of every column! I'm hoping there's a way to use the DataFrame 'public' in a statement that will allow deletion of these columns en masse. If anyone has any suggestions and/or guidance I'd be most grateful. (Have Python 2.7 and am using Pandas, numpy, math, pylab etc.) Thanks in advance. Answer: Ignore my question - Murphy's Law prevails and I've just solved it. I was using the statement from the stackoverflow question mentioned below: df.drop(df.columns[1:], axis=1) and this was not working. I have instead used df = df.drop(df2, axis=1) and this worked (df = main, df2 = public). Simple really once you don't overthink it.
Headers with Python List Question: Python newbie. I have csv data the looks like the following: Record Name Cur e12mo e24mo e48mo state 3928 Joes 2000 200 400 0 CA,GA 1 Toms 19 1 2 0 AR,KS 1747 Mine 60 5 10 0 AR,CT 5023 Yours 5 12 24 0 FL 7041 Theirs 10 2 4 0 FL Am entering code from tutorial as follows: import numpy as np import csv as csv readdata = csv.reader(open('c:\MyData\BYLCsv.csv')) for row in readdata: print(row) data = [] for row in readdata: data.append(row) for row in data: print(row) Header = data[0] data.pop(0) Code bombs on the "Header = data[0]" statement. Everything runs up to there. Answer: In your first loop, you read the whole file, the file pointer is not reset afterwards: import numpy as np import csv as csv with open('c:\MyData\BYLCsv.csv') as data: readdata = csv.reader(data) header = next(readdata) data = list(readdata) print(header) for row in data: print(row)
US Census API - Get The Population of Every City in a State Using Python Question: I'm having an issue getting the population of every city in a specific state. I do get the population of cities but if I sum the population in every city I don't get the same number as the population of the state. I got my [API Key](http://api.census.gov/data/key_signup.html) used the [P0010001 variable](http://api.census.gov/data/2010/sf1/variables.html) for total population used the FIPS 25 for the state of Massachusetts and requested the population by the [geography level "place"](http://api.census.gov/data/2010/sf1/geography.html) which I understand it to mean city. Here is the Python 3 code I used: import urllib.request import ast class Census: def __init__(self, key): self.key = key def get(self, fields, geo, year=2010, dataset='sf1'): fields = [','.join(fields)] base_url = 'http://api.census.gov/data/%s/%s?key=%s&get=' % (str(year), dataset, self.key) query = fields for item in geo: query.append(item) add_url = '&'.join(query) url = base_url + add_url print(url) req = urllib.request.Request(url) response = urllib.request.urlopen(req) return response.read() c = Census('<mykey>') state = c.get(['P0010001'], ['for=state:25']) # url: http://api.census.gov/data/2010/sf1?key=<mykey>&get=P0010001&for=state:25 county = c.get(['P0010001'], ['in=state:25', 'for=county:*']) # url: http://api.census.gov/data/2010/sf1?key=<mykey>&get=P0010001&in=state:25&for=county:* city = c.get(['P0010001'], ['in=state:25', 'for=place:*']) # url: http://api.census.gov/data/2010/sf1?key=<mykey>&get=P0010001&in=state:25&for=place:* # Cast result to list type state_result = ast.literal_eval(state.decode('utf8')) county_result = ast.literal_eval(county.decode('utf8')) city_result = ast.literal_eval(city.decode('utf8')) def count_pop_county(): count = 0 for item in county_result[1:]: count += int(item[0]) return count def count_pop_city(): count = 0 for item in city_result[1:]: count += int(item[0]) return count **And here are the results:** print(state) # b'[["P0010001","state"],\n["6547629","25"]]' print('Total state population:', state_result[1][0]) # Total state population: 6547629 print('Population in all counties', count_pop_county()) # Population in all counties 6547629 print('Population in all cities', count_pop_city()) # Population in all cities 4615402 I'm reasonable sure that 'place' is the city e.g. # Get population of Boston (FIPS is 07000) boston = c.get(['P0010001'], ['in=state:25', 'for=place:07000']) print(boston) # b'[["P0010001","state","place"],\n["617594","25","07000"]]' What am I doing wrong or misunderstanding? **Why is the sum of populations by place not equal to the population of the state?** [List of example API calls](http://api.census.gov/data/2010/sf1/geo.html) Answer: _if I sum the population in every city I don't get the same number as the population of the state._ That's because not everybody lives **in a city** \-- there are rural "unincorporated areas" in many counties that are not part of any city, and, people do live there. So, this is not a programming problem!-)
Unable to start AMS Acomba Connector on Windows Question: I am trying to get a python service to run under Windows 7 however I am unable to start it. I have started by installing the service using c:\amsconnector>amsconnector.py --username domain\admin --password ************ install Installing service AMS Acomba Connector Service installed After that, I run c:\amsconnector>amsconnector.py start Starting service AMS Acomba Connector When I check the running services list, I notice that the service is not running and when checking the event log, I am presented with this stacktrace Python could not import the service's module Traceback (most recent call last): File "C:\amsconnector\amsconnector.py", line 343, in <module> win32serviceutil.HandleCommandLine(AMSConnectorService) File "C:\Python27\lib\site-packages\win32\lib\win32serviceutil.py", line 521, in HandleCommandLine usage() File "C:\Python27\lib\site-packages\win32\lib\win32serviceutil.py", line 505, in usage sys.exit(1) SystemExit: 1 %2: %3 The line 343 of amsconnector.py looks like this if True or __name__ == '__main__': win32serviceutil.HandleCommandLine(AMSConnectorService) After checking out the source code of win32serviceutil.py, it appears that the service is just printing out the win32service usage dialog instead of actually running the python class. I am completely confused! Answer: Thanks roeland! I was able to fix the issue by simply removing the "True or" part of the last line leaving it like this: if True or __name__ == '__main__': win32serviceutil.HandleCommandLine(AMSConnectorService)
How to convert this json string to dict? Question: After executing the following code: import json a = '{"excludeTypes":"*.exe;~\\$*.*"}' json.loads(a) I get: > Traceback (most recent call last): File "", line 1, in File > "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/**init**.py", > line 338, in loads return _default_decoder.decode(s) File > "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", > line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File > "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", > line 381, in raw_decode obj, end = self.scan_once(s, idx) ValueError: > Expecting property name: line 1 column 2 (char 1) So how can I convert 'a' to dict. Please note that the string is already in 'a' and I cannot add 'r' in front of it. Ideally, the string should have been `{"excludeTypes":"*.exe;~\\\\$*.*"}` Also, the following code doesn't work: import json a = '{"excludeTypes":"*.exe;~\\$*.*"}' b = repr(a) json.loads(b) Answer: import ast d = ast.literal_eval(a)
Why am I getting "UnicodeEncodeError: 'charmap' codec can't encode character" error message Question: I encountered a problem with Python script I wrote while running in a Windows CMD window, and boiled the essence of the problem down to the following [SSCCE](http://sscce.org/): **The Python script (x.py)** import sys in_file = open (sys.argv[1], 'rt') for line in in_file: line = line.rstrip ('\n') print ('line="%s"' % (line)) in_file.close () **The input data file (x.txt)** Line 1 Line 2 “text” Line 3 **The command line invocation** python x.py x.txt **The error output** C:\junk>python x.py x.txt line="Line 1" Traceback (most recent call last): File "x.py", line 7, in <module> print ('line="%s"' % (line)) File "C:\Program Files (x86)\Python34\lib\encodings\cp862.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u201c' in position 13: character maps to <undefined> C:\junk> It seems to be failing on the second input record ("Line 2"). What am I doing wrong? Answer: The answer turned out to be a Windows codepage issue. The second input line uses the ANSI typographical characters 0x93 (147) and 0x94 (148), corresponding to the left and right quotation marks, respectively. Although the input file was meant to be an ASCII file (i.e., characters < 128 decimal), word processors, in contrast to text editors, will often insert these specialized characters. Python read it well enough, but threw an exception when trying to print it to the console window. As the error output shows, the error message emanates from lib\encodings\cp862.py, which corresponds to [code page 862](http://en.wikipedia.org/wiki/Code_page_862), MS_DOS's code page for Hebrew. Windows attempts to convert the ANSI character 0x93 (147) to the Unicode U+201C ("LEFT DOUBLE QUOTATION MARK"), which Python's default encoding cannot support. Executing the [CHCP (Change Codepage) command](https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en- us/chcp.mspx?mfr=true) gives: C:\junk>chcp Active code page: 862 C:\junk> Changing the CMD window's codepage to CP 1252 ("Latin-1") solves the problem: C:\junk>chcp 1252 Active code page: 1252 C:\junk>python x.py x.txt line="Line 1" line="Line 2 “text”" line="Line 3" C:\junk>
Psycopg ppygis select query Question: I'm trying to setup a basic working postgis setup with python ppygis package. >>> import psycopg2 >>> import ppygis >>> connection = psycopg2.connect(database='spre', user='postgres') >>> cursor = connection.cursor() >>> cursor.execute('CREATE TABLE test (geometry GEOMETRY)') >>> cursor.execute('INSERT INTO test VALUES(%s)', (ppygis.Point(1.0, 2.0),)) >>> cursor.execute('SELECT * from test') >>> point = cursor.fetchone()[0] >>> print point 0101000000000000000000F03F0000000000000040 >>> I should have got a python object with separate X and Y coordinate. Something like >>> Point(X: 1.0, Y: 2.0) What am I doing wrong? Answer: You are doing nothing wrong. Following [the same steps as the PPyGIS basic example](http://www.fabianowski.eu/projects/ppygis/usage.html#basic-usage), I get the same [hex-encoded EWKB](https://en.wikipedia.org/wiki/Well- known_binary) as shown in the question (010100...), which is normally expected. Perhaps this worked with an older version of PPyGIS / Psycopg? It doesn't today. The package does not appear to properly register itself as an adapter for PostGIS types, so my advice is to not use the package. Besides, you don't need additional packages to use PostGIS from Psycopg2. * * * Here is the normal approach to read/write points, without any extra packages: # Assuming PostGIS 2.x, use a typmod cursor.execute('CREATE TEMP TABLE test (geom geometry(PointZ,4326));') # Longyearbyen, 78.22°N 15.65°E, altitude 10 m cursor.execute('''\ INSERT INTO test (geom) VALUES(ST_SetSRID(ST_MakePoint(%s, %s, %s), 4326)); ''', (15.65, 78.22, 10.0)) cursor.execute('''\ SELECT ST_Y(geom) AS latitude, ST_X(geom) AS longitude, ST_Z(geom) AS altitude FROM test; ''') print(cursor.fetchone()) # (78.22, 15.65, 10.0) cursor.execute('SELECT ST_AsText(geom) FROM test;') print(cursor.fetchone()[0]) # POINT Z (15.65 78.22 10) cursor.execute('SELECT ST_AsLatLonText(geom) FROM test;') print(cursor.fetchone()[0]) # 78°13'12.000"N 15°39'0.000"E If you want a geometry object on the client-side to do more work with the actual geometry, consider using Shapely, which can be interfaced using WKB data: from shapely.wkb import loads cursor.execute('SELECT geom FROM test;') pt = loads(cursor.fetchone()[0], hex=True) print(pt) # POINT Z (15.65 78.22 10)
Django finds all static files except one - 404 Question: I had my static files working correctly until I tried to add this library <https://github.com/ierror/django-js-reverse> I followed the instructions from the page, but Django still can't find the new resource. from settings.py STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static/'), ) INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_js_reverse', ..., ) in my template <script src="{% static 'django_js_reverse/js/reverse.js' %}"></script> my directory structure looks like this staticfiles/ admin/ dist/ django_js_reverse/ js/ reverse.js After running python manage.py collectstatic python manage.py runserver I also tried to run the following according to the library instructions, but no luck ./manage.py collectstatic_js_reverse Here's the output from runserver when I try to load the page. [08/Mar/2015 19:12:33] "GET /static/custom.css HTTP/1.1" 304 0 [08/Mar/2015 19:12:33] "GET /static/dist/css/bootstrap.min.css HTTP/1.1" 304 0 [08/Mar/2015 19:12:33] "GET /static/django_js_reverse/js/reverse.js HTTP/1.1" 404 1697 [08/Mar/2015 19:12:33] "GET /static/dist/js/bootstrap.min.js HTTP/1.1" 304 0 [08/Mar/2015 19:12:33] "GET /static/csrf.js HTTP/1.1" 304 0 [08/Mar/2015 19:12:33] "GET /static/custom.js HTTP/1.1" 304 0 I can't figure out where the issue is. The static files settings are obviously set up correctly because all the other files are being loaded fine. I must be missing something obvious. Any help would be appreciated\ UPDATE I tried moving the reverse.js file to dist/ but it still returns a 404. The permissions on all the files are the same ls -la staticfiles/dist/js -rw-r--r-- 1 adam staff 67155 Mar 8 15:06 bootstrap.js -rw-r--r-- 1 adam staff 35601 Mar 8 15:06 bootstrap.min.js -rw-r--r-- 1 adam staff 484 Mar 8 15:06 npm.js -rw-r--r-- 1 adam staff 3258 Mar 10 10:31 reverse.js Answer: Got same problem and tried everything. Url to js file seems legit but it isn't (with Django 1.9 at least). I've changed it from <script src="{% static 'django_js_reverse/js/reverse.js' %}"></script> to <script src="{% url 'js_reverse' %}"></script> And you need this url pattern in urls.py for this solution # import view from django_js_reverse.views import urls_js # and add this in url patterns url(r'^jsreverse/$', 'django_js_reverse.views.urls_js', name='js_reverse'), And now it's working without any problem . Hope this will help somebody.
Equivalent Python code for the following Java http get requests Question: I am trying to convert the following Java code to Python. Not sure what I am doing wrong, but I end up with an internal server error 500 with python. Is the "body" in `httplib.httpConnection` method equivalent to Java `httpentity`? Any other thoughts on what could be wrong? The input information I collect is correct for sure. Any help will be really appreciated. I have tried several things, but end up with the same internal server error. Java Code: HttpEntity reqEntitiy = new StringEntity("loginTicket="+ticket); HttpRequestBase request = reMethod.getRequest(uri, reqEntitiy); request.addHeader("ticket", ticket); HttpResponse response = httpclient.execute(request); HttpEntity responseEntity = response.getEntity(); StatusLine responseStatus = response.getStatusLine(); Python code: url = serverURL + "resources/slmservices/templates/"+templateId+"/options" #Create the request ticket = ticket.replace("'",'"') headers = {"ticket":ticket} print "ticket",ticket reqEntity = "loginTicket="+ticket body = "loginTicket="+ticket url2 = urlparse.urlparse(serverURL) h1 = httplib.HTTPConnection(url2.hostname,8580) print "h1",h1 url3 = urlparse.urlparse(url) print "url path",url3.path ubody = {"loginTicket":ticket} data = urllib.urlencode(ubody) conn = h1.request("GET",url3.path,data,headers) #conn = h1.request("GET",url3.path) response = h1.getresponse() lines = response.read() print "response.status",response.status print "response.reason",response.reason Answer: You don't need to go this low level. Using `urllib2` instead: import urllib2 from urllib import urlencode url = "{}resources/slmservices/templates/{}/options".format( serverURL, templateId) headers = {"ticket": ticket} params = {"loginTicket": ticket} url = '{}?{}'.format(url, urlencode(params)) request = urllib2.Request(url, headers=headers) response = urllib2.urlopen(request) print 'Status', response.getcode() print 'Response data', response.read() Note that the parameters are added to the _URL_ to form URL query parameters. You can do this simpler still by installing the [`requests` library](http://docs.python-requests.org/en/latest/): import requests url = "{}resources/slmservices/templates/{}/options".format( serverURL, templateId) headers = {"ticket": ticket} params = {"loginTicket": ticket} response = requests.get(url, params=params, headers=headers) print 'Status', response.status print 'Response data', response.content # or response.text for Unicode Here `requests` takes care of URL-encoding the URL query string parameters and adding it to the URL for you, just like Java does.
Using scrapy to save files on a web page by extension type Question: I am very new to Python and I am trying to use scrapy to download and save the pdf files in this website: <http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#hansard> The following is my code: from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector class legco(BaseSpider): name = "legco" allowed_domains = ["http://www.legco.gov.hk/"] start_urls = ["http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#hansard"] rules =( Rule(SgmlLinkExtractor(allow=r"\.pdf"), callback="save_pdf") ) def parse_listing(self, response): hxs = HtmlXPathSelector(response) pdf_urls=hxs.select("a/@href").extract() for url in pdf_urls: yield Request(url, callback=self.save_pdf) def save_pdf(self, response): path = self.get_path(response.url) with open(path, "wb") as f: f.write(response.body) Basically I tried to restrict the search to just links with ".pdf" and then select by "a/@hfref". From the output, I see this error: > 2015-03-09 11:00:22-0700 [legco] ERROR: Spider error processing > http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#hansard> Can anyone advise how can I fix my code? Thanks a lot! Answer: First of all, _you need to use a`CrawlSpider`_ if you want the `rules` to work. Also, the `rules` should be defined as an iterable, usually it is a tuple (there was a missing comma). Anyway, instead of taking this approach, I would use a normal `BaseSpider`, loop over the links and check the `href` to end with `.pdf`, then, in the callback, save a pdf to a file: import urlparse from scrapy.http import Request from scrapy.spider import BaseSpider class legco(BaseSpider): name = "legco" allowed_domains = ["www.legco.gov.hk"] start_urls = ["http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#hansard"] def parse(self, response): base_url = 'http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/' for a in response.xpath('//a[@href]/@href'): link = a.extract() if link.endswith('.pdf'): link = urlparse.urljoin(base_url, link) yield Request(link, callback=self.save_pdf) def save_pdf(self, response): path = response.url.split('/')[-1] with open(path, 'wb') as f: f.write(response.body) (worked for me)
Creating a 2d colour gradient plot with 3 1D arrays Question: So i have 3 1D arrays, x_vals, y_vals and z_vals. I would like to plot x_vals against y_vals, with z_vals defining the colour at the point. from everything i have looked up it seems i need to use numpy.meshgrid, however when i try this python just times out. Any thoughts? Thank you! Answer: You are looking for the `LineCollection` command. Try this import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection fig,ax = plt.subplots(1) # some data to plot x = np.linspace(0,1,200) y = np.sin(10*x) z = x**2 # creating the segments points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # creating LineCollection object lc = LineCollection(segments, cmap=plt.get_cmap('jet'),norm=plt.Normalize(0, 1)) lc.set_array(z) lc.set_linewidth(2) # add LineCollection to plot ax.add_collection(lc) # set plotting range ax.set_xlim((0,1)) ax.set_ylim((-1,1)) plt.show()
Implementing Matlab's weights and bias on Neurolab (Neural Network) Question: I exported weights and bias from Matlab into python to use with neurolab. My network has 8 inputs, 3 arrays of input weights, 4 arrays of layered weights and 4 output neurons. This is my first time of doing this, I'll really need help to get it done. Below is my implementation and the error I got. import numpy as np import neurolab as nl net = nl.net.newff([[0, 1]], [3, 4]) input_w=[[-24.1874,24.1622,0.0755,-0.2521,4.4625,-10.7961,6.2183,0.2680],...] input_w = np.array(input_w) input_w = np.reshape(input_w, (8,3)) layer_w=[[-3.7940,-0.0336,-14.9024],......] layer_w = [np.array(x) for x in (layer_w)] layer_w = np.reshape(layer_w, (3,4)) input_bias =[0.4747,-1.2475,-1.2470] bias_2=np.array([-10.9982,1.9692,5.0705,-0.1236]) bias_2 = np.reshape(bias_2, (4)) net.layers[0].np['w'][:] = input_w. net.layers[1].np['w'][:] = layer_w. net.layers[1].np['b'][:] = np.array([input_bias]) net.layers[0].np['b'][:] = bias_2 print net.sim([[0.015,0.022,0.0,0.0,0.432,0.647,0.831]]) Traceback (most recent call last): File "C:\Python27\neural13.py", line 206, in <module> net.layers[0].np['w'][:] = input_w ValueError: could not broadcast input array from shape (8,3) into shape (3,1) Thanks for your suggestions, and please feel free to ask if you need more info. Answer: There are several problems here. The first problem is that you want 8 input neurons. For that, you need the first list in newff to have a length of 8 (one min value and one max value for each of 8 inputs). So you are ending up with only one input, not 8 (hence a 3x1 array instead of a 3x8 array). That can be fixed by changing: net = nl.net.newff([[0, 1]], [3, 4]) to: net = nl.net.newff([[0, 1]]*8, [3, 4]) which is a shorter way to write: net = nl.net.newff([[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]], [3, 4]) The next problem is that python uses a different dimension ordering (by default) than matlab. So a 2D array with shape (8,3) would have a shape of (3,8) in numpy. So all of your reshaping is unnecessary. The third problem is that you have the dimensions for input_bias and bias_2 mixed up. I don't know enough about neurlab to say whether you want to change `[3, 4]` at the beginning to `[4, 3]`, or whether you want to switch the biases. I will assume the latter. The final problem is that you need 8 elements in the input to net.sim, but you only have 7. Here is a fixed version of your code, assuming you have the biases mixed up and with some dummy values to fill in what you left out: import numpy as np import neurolab as nl net = nl.net.newff([[0, 1]]*8, [3, 4]) input_w = np.array([[-24.1874,24.1622,0.0755,-0.2521,4.4625,-10.7961,6.2183,0.2680], [-24.1874,24.1622,0.0755,-0.2521,4.4625,-10.7961,6.2183,0.2680], [-24.1874,24.1622,0.0755,-0.2521,4.4625,-10.7961,6.2183,0.2680]]) layer_w = np.array([[-3.7940,-0.0336,-14.9024], [-3.7940,-0.0336,-14.9024], [-3.7940,-0.0336,-14.9024], [-3.7940,-0.0336,-14.9024]]) input_bias = np.array([0.4747,-1.2475,-1.2470]) bias_2 = np.array([-10.9982,1.9692,5.0705,-0.1236]) net.layers[0].np['w'][:] = input_w net.layers[1].np['w'][:] = layer_w net.layers[0].np['b'][:] = input_bias net.layers[1].np['b'][:] = bias_2 print net.sim([[0.015,0.022,0.0,0.0,0.432,0.647,0.831]])
Try block not catching - Am I making inadvertent internet access? Question: I accidentally disconnected my internet connection and received this error below. However, why did this **line** trigger the error? self.content += tuple(subreddit_posts) Or perhaps I should ask, why did the following line **not** lead to a `sys.exit`? It seems it should catch all errors: try: subreddit_posts = self.r.get_content(url, limit=10) except: print '*** Could not connect to Reddit.' sys.exit() Does this mean I am inadvertently hitting reddit's network twice? FYI, praw is a reddit API client. And `get_content()` fetches a subreddit's posts/submissons as a generator object. The error message: Traceback (most recent call last): File "beam.py", line 49, in <module> main() File "beam.py", line 44, in main scan.scanNSFW() File "beam.py", line 37, in scanNSFW map(self.getSub, self.nsfw) File "beam.py", line 26, in getSub self.content += tuple(subreddit_posts) File "/Library/Python/2.7/site-packages/praw/__init__.py", line 504, in get_co page_data = self.request_json(url, params=params) File "/Library/Python/2.7/site-packages/praw/decorators.py", line 163, in wrap return_value = function(reddit_session, *args, **kwargs) File "/Library/Python/2.7/site-packages/praw/__init__.py", line 557, in reques retry_on_error=retry_on_error) File "/Library/Python/2.7/site-packages/praw/__init__.py", line 399, in _reque _raise_response_exceptions(response) File "/Library/Python/2.7/site-packages/praw/internal.py", line 178, in _raise response.raise_for_status() File "/Library/Python/2.7/site-packages/requests/models.py", line 831, in rais raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 503 Server Error: Service Unavailable The script (it's short): import sys, os, pprint, praw class Scanner(object): ''' A scanner object. ''' def __init__(self): self.user_agent = 'debian.22990.myapp' self.r = praw.Reddit(user_agent=self.user_agent) self.nsfw = ('funny', 'nsfw') self.nsfw_posters = set() self.content = () def getSub(self, subreddit): ''' Accepts a subreddit. Connects to subreddit and retrieves content. Unpacks generator object containing content into tuple. ''' url = 'http://www.reddit.com/r/{sub}/'.format(sub=subreddit) print 'Scanning:', subreddit try: subreddit_posts = self.r.get_content(url, limit=10) except: print '*** Could not connect to Reddit.' sys.exit() print 'Constructing list.', self.content += tuple(subreddit_posts) print 'Done.' def addNSFWPoster(self, post): print 'Parsing author and adding to posters.' self.nsfw_posters.add(str(post.author)) def scanNSFW(self): ''' Scans all NSFW subreddits. Makes list of posters.''' # Get content from all nsfw subreddits print 'Executing map function.' map(self.getSub, self.nsfw) # Scan content and get authors print 'Executing list comprehension.' [self.addNSFWPoster(post) for post in self.content] def main(): scan = Scanner() scan.scanNSFW() for i in scan.nsfw_posters: print i print len(scan.content) main() Answer: It looks like `praw` is going to lazily get objects, so when you actually _use_ `subreddit_posts` is when the request gets made, which explains why it's blowing up on that line. See: <https://praw.readthedocs.org/en/v2.1.20/pages/lazy-loading.html>
Get Data from JSON Python? Question: I'm working on doing a live currency converter in Python. I've successfully fetched all the data needed from the URL into Python. However I'm now trying to call a specific string in the url. Here's my current code: import urllib.request import json ##Define JSON API Url with urllib.request.urlopen("http://openexchangerates.org/api/latest.json?app_id=XXX") as url: response = url.read() ##Print Fetched data print (response) As you can see I've printed all the data it's fetched, but it's now printing specific strings from it. My question is, how do i parse specific strings from the url ? I've heard of json.load ,is that something i should use ? Answer: You'll need to load the data as JSON; the [`json` module](https://docs.python.org/3/library/json.html) can do this for you, but you need to decode the data to text first. import urllib.request import json with urllib.request.urlopen("http://openexchangerates.org/api/latest.json?app_id=XXX") as url: response = url.read() charset = url.info(). get_content_charset('utf-8') # UTF-8 is the JSON default data = json.loads(response.decode(charset)) From there on out `data` is a Python object. Judging by the [documenation](https://openexchangerates.org/documentation#preview-api- response) you should be able to access rates as: print('Euro rate', data['rates']['EUR']) for example.
Detect the dates from text in text file. And then list them out using python Question: I have a text file that contains dates in the text. these dates are of format ("march 2016" or "march 2, 2016"). I wish to list them out. Can anybody help me with this? this is my attempt import re regex = '\s(\w+)\s(\d+\,)\s(\d+)' # this will match the form "str int, int" with open('./BACKGROUND OF THE SOLICITATION3.txt', 'r') as f: text = f.read() all_dates = [' '.join(date) for date in re.findall(regex, text)] print all_dates Answer: s = " I want to detect both March 20, 2013 and February 2013 3 and list them" import re print(re.findall(r"([A-Z][a-z\s\d]+, \d+|[A-Z][a-z\s]+\d+)",s)) ['March 20,2013', 'February 2013']
python NameError: name 'memberno' is not defined Question: my code is giving me the error of Destination[index]=inode*dof-dof IndexError: list assignment index out of range I have searched for this error but i cant figure out the problem in this code.Please help me... import numpy as np class memberdata(object): def__init__(self,memberno=None,backnode=None,forenode=None,materialno=None): self.memberno=memberno self.backnode=backnode self.forenode=forenode self.materialno=materialno member=[] member.append(memberdata('10','2','3','1')) print "enter dof" dof=raw_input() dof=int(dof) def get_destination(memberno): inode = member[memberno-1].backnode inode=int(inode) jnode = member[memberno-1].forenode jnode=int(jnode) Destination=[] index=0 Destination[index]=inode*dof-dof for i in range(dof): index=index+1 Destination[index]=Destination[index-1]+1 index=index+1 Destination[index]=jnode*dof-dof for i in range(dof): index=index+1 Destination[index]=Destination[index-1]+1 if __name__ == "__main__": get_destination(memberno) Answer: Destination=[] index=0 Destination[index]=inode*dof-dof Here, you create an empty list with `[]` and then try to assign index 0, where `Destination[0]` doesn't yet exist. The list holds 0 values, hence any index you try to assign will be out of range. If you simply want to add some value to the list, use Destination.append(inode*dof-dof)
Python: Download CSV file, check return code? Question: I am downloading multiple CSV files from a website using Python. I would like to be able to check the response code on each request. I know how to download the file using `wget`, but not how to check the response code: os.system('wget http://example.com/test.csv') I've seen a lot of people suggesting using requests, but I'm not sure that's quite right for my use case of saving CSV files. r = request.get('http://example.com/test.csv') r.status_code # 200 # Pipe response into a CSV file... hm, seems messy? What's the neatest way to do this? Answer: You can use the `stream` argument - along with `iter_content()` it's possible to stream the response contents right into a file ([docs](http://docs.python- requests.org/en/latest/user/advanced/#body-content-workflow)): import requests r = None try: r = requests.get('http://example.com/test.csv', stream=True) with open('test.csv', 'w') as f: for data in r.iter_content(): f.write(data) finally: if r is not None: r.close()
Intellij/Pycharm can't debug Python modules Question: I use **PyCharm** /**IntelliJ** community editions from a wile to write and debug Python scripts, but now I'm trying to debug a **Python module** , and PyCharm does a wrong command line instruction parsing, causing an execution error, or maybe I'm making a bad configuration. This is my run/debug configuration: ![IntelliJ run/debug Python module configuration](http://i.stack.imgur.com/Jrddy.png) And this is executed when I run the module (no problems here): /usr/bin/python3.4 -m histraw But when I debug, this is the output in the IntelliJ console: /usr/bin/python3.4 -m /opt/apps/pycharm/helpers/pydev/pydevd.py --multiproc --client 127.0.0.1 --port 57851 --file histraw /usr/bin/python3.4: Error while finding spec for '/opt/apps/pycharm/helpers/pydev/pydevd.py' (<class 'ImportError'>: No module named '/opt/apps/pycharm/helpers/pydev/pydevd') Process finished with exit code 1 As you can see, the parameters are wrong parsed, and after `-m` option a IntelliJ debug script is passed before the module name. I also tried just put `-m histraw` in the _Script_ field, but doesn't work, that field is only to put Python script paths, not modules. Any ideas? Answer: There is another way to make it work.You can write a python script to run your module.Then just configure PyCharm to run **this script**. import sys import os import runpy path = os.path.dirname(sys.modules[__name__].__file__) path = os.path.join(path, '..') sys.path.insert(0, path) runpy.run_module('<your module name>', run_name="__main__",alter_sys=True) Then the debugger works.
python picamera OSError: dlopen(libmmal.so, 6): image not found Question: I am trying to use picamera to do a video streaming on my Mac(python 2.7). I have installed picamera by this command: **(venv)55-213:video_streaming mreko$ pip install picamera Requirement already satisfied (use --upgrade to upgrade): picamera in ./venv/lib/python2.7/site-packages** Then I wrote a py script trying to test the picamera: **import time import picamera with picamera.PiCamera() as camera: camera.resolution = (1024, 768) camera.start_preview() # Camera warm-up time time.sleep(2) camera.capture('foo.jpg')** However,when I compile this py script,it throws an error: **(venv)55-213:video_streaming mreko$ python test.py Traceback (most recent call last): File "test.py", line 2, in import picamera File "/Users/mreko/python_workstation/video_streaming/venv/lib/python2.7/site- packages/picamera/__init__.py", line 258, in from picamera.exc import ( File "/Users/mreko/python_workstation/video_streaming/venv/lib/python2.7/site- packages/picamera/exc.py", line 41, in import picamera.mmal as mmal File "/Users/mreko/python_workstation/video_streaming/venv/lib/python2.7/site- packages/picamera/mmal.py", line 47, in _lib = ct.CDLL('libmmal.so') File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 365, in __init__ self._handle = _dlopen(self._name, mode) OSError: dlopen(libmmal.so, 6): image not found** I know the extention of lib on mac is 'dylib'.I change 'libmmal.so' into 'libmmal.dylib'.However,still it can't work. Then I search the /usr/lib/,I found there is no dylib name 'libmmal'. So I don't know how to solve this problem.Maybe the picamera can't support Mac? Or is there any way that I can intall libmmal.dylib file to support the picamera? It really makes me upset!! Thanks a lot! Answer: The files that `picamera` is referencing are part of the [raspberry](https://github.com/raspberrypi/firmware/tree/master/hardfp/opt/vc/lib) [firmware](https://github.com/raspberrypi/userland) and you would need to recompile them for your mac. As others asked in the comments, are you sure you have connected the thin flexband of the camera to your apple laptop? If so, how? If not, are you running a raspberry pi and connecting to it via your mac?
SBCL Run Shell Command Question: I've seen [Executing a shell command from Common Lisp](http://stackoverflow.com/q/6065446/1281433) and its answers, but I'm still not sure whether SBCL provides a way execute shell commands from code. The [SBCL Manual](http://www.sbcl.org/manual/#sb_002dposix) does support POSIX, but I was hoping for something a bit more higher level. Specifically, I want to call a Python script and capture the return value. Is there any way to do this? Answer: Given the file `test.py`: import sys sys.exit(42) You can run it with `sb-ext:run-program` and examine the exit code as follows: CL-USER> (sb-ext:run-program "python" '("test.py") :search t :wait t) #<SB-IMPL::PROCESS :EXITED 42> CL-USER> (sb-ext:process-exit-code *) 42
Maya, Python, How do i get the name of an object based on vertex selection? Question: I got the code working like this until i realized that the vertex index changes for geometry with over 100 vertices... I assumed i could just split the string and everything would be dandy import maya.cmds as mc selPoints = mc.ls(sl = True) # list of names of selected vertices objName = (str(selPoints[0]))[:-9] print selPoints print objName Heres what it returned: [u'pCylinder25.vtx[4]', u'pCylinder25.vtx[24]'] pCylinder I'm trying to hack off the portion with '.vtx[integer]' I may be going about this completely wrong, and there may be a dead simple way to do this. Thanks Answer: Wouldn't it be awesome if it were easy to get the object from Maya? From experience, I know it can be frustrating since MEL/maya.cmds doesn't use an object-oriented approach. Anyhow, you should refer to the [documentation](https://docs.python.org/3.1/library/stdtypes.html#string- methods) often for more info on the variety of `string` methods you can use. Really comes in handy _all the time_! To answer your question, you can use `.split` or `.find`, whichever you prefer. print selPoints[0].split('.vtx')[0] print selPoints[0][0:selPoints[0].find('.vtx')] The `split` method returns a list of strings created by the delimiter string `'.vtx'`. Then, taking the first element from that list will always be the object name. The `find` method returns the index of the substring `'.vtx'`, so the second example simply uses slicing syntax to return the correct string.
Compiling Python script to exe Question: I recently created a script using Python 2.7 and pygame. I have tried using `py2exe`, but when I run the file it created, it gives me this error: G:\Downloads2\GAME\dist\ANNECUTE.exe\zipextimporter.py:82: RuntimeWarning: import display: No module named _view (ImportError: No module named _view) G:\Downloads2\GAME\dist\ANNECUTE.exe\zipextimporter.py:82: RuntimeWarning: import draw: No module named _view (ImportError: No module named _view) G:\Downloads2\GAME\dist\ANNECUTE.exe\zipextimporter.py:82: RuntimeWarning: import image: No module named _view (ImportError: No module named _view) G:\Downloads2\GAME\dist\ANNECUTE.exe\zipextimporter.py:82: RuntimeWarning: import pixelcopy: No module named _view (ImportError: No module named _view) G:\Downloads2\GAME\dist\ANNECUTE.exe\zipextimporter.py:82: RuntimeWarning: import transform: No module named _view (ImportError: No module named _view) Traceback (most recent call last): File "ANNECUTE.py", line 45, in <module> File "pygame\__init__.pyc", line 70, in __getattr__ NotImplementedError: display module not available (ImportError: No module named _view) I used this in the `setup.py` file: from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1}}, windows = [{'script': "ANNECUTE.py"}], zipfile = None, ) Answer: Try adding import pygame._view To `zipextimporter.py`. This will import _view and should eliminate your problem.
How to normalise unique dates for graphing Question: I've currently got a data-set from an application, but the problem is the data is listed whenever it changes, not on a regular interval. For example I could have 20 entries in one day and then nothing for two days, then one, then one next month. I want to graph the data I have, but with a consistent time scale - currently it just graphs every entry with every date one after the other. I have thought about the problem and an idea that came to mind would be determining the start and end date of the data, dividing it by the graphing resolution desired, (eg 100 entries), then for each entry working out the closest result in the data-set BEFORE the resolution sample. ie one of the samples for graphing is 10th of january, it finds the first sample before the 10th of january and uses it. Then with 100 samples you can graph with a consistent time scale. Any ideas on how to actually achieve this would be wonderful! I'm looking to normalize in python and then render in a browser with google chart api. Here is an example of the data: 10/03/2015 10:55 7385498415 10/03/2015 9:15 7379639094 10/03/2015 8:55 7376777516 10/03/2015 8:35 7368304217 10/03/2015 8:12 7358015859 8/03/2015 9:22 7358015859 8/03/2015 4:27 7354221274 8/03/2015 4:07 7346810719 7/03/2015 4:25 7339695326 7/03/2015 4:25 7339698276 6/03/2015 13:08 7339701226 6/03/2015 13:04 7317905872 6/03/2015 12:44 7309771372 6/03/2015 12:24 7300851599 6/03/2015 12:04 7292557469 6/03/2015 11:39 7283439433 6/03/2015 11:00 7278056128 6/03/2015 10:41 7267320628 6/03/2015 10:35 7265158228 6/03/2015 10:21 7265158228 6/03/2015 10:01 7255260402 6/03/2015 7:06 7246047762 5/03/2015 15:39 7245760885 5/03/2015 13:41 7170760885 4/03/2015 21:21 5595760885 4/03/2015 18:59 5590496476 4/03/2015 18:59 5585251201 Answer: There’s no need to “normalise” the data, as the Google Charts API has support for dates directly. Not only is adjusting the data more difficult, but it will also give a skewed impression. We can start with the [Dates and Times](https://developers.google.com/chart/interactive/docs/datesandtimes) section of their documentation: > To create a new `Date` object, you call the `Date()` constructor with the > new keyword, with arguments to specify components of the date. These > arguments take the form of several numbers corresponding to the different > properties of your date. > > > new Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds) > A row in a Google Chart is an `[x, y]` list. The first entry will be one of these Date() constructors, and the second will be the value. So we need to take the data you’ve provided, parse the dates and turn them into Date() constructors. (Note that we can omit the second and millisecond arguments.) Here’s a simple script that does this, and then wraps each time in a row that we can supply to a Google Chart: from datetime import datetime # This string is a copy of the example data set. The newlines have been # replaced with '\n' escape codes to save vertical space on Stack Overflow. DATASET = """10/03/2015 10:55 7385498415\n10/03/2015 9:15 7379639094\n10/03/2015 8:55 7376777516\n10/03/2015 8:35 7368304217\n10/03/2015 8:12 7358015859\n8/03/2015 9:22 7358015859\n8/03/2015 4:27 7354221274\n8/03/2015 4:07 7346810719\n7/03/2015 4:25 7339695326\n7/03/2015 4:25 7339698276\n6/03/2015 13:08 7339701226\n6/03/2015 13:04 7317905872\n6/03/2015 12:44 7309771372\n6/03/2015 12:24 7300851599\n6/03/2015 12:04 7292557469\n6/03/2015 11:39 7283439433\n6/03/2015 11:00 7278056128\n6/03/2015 10:41 7267320628\n6/03/2015 10:35 7265158228\n6/03/2015 10:21 7265158228\n6/03/2015 10:01 7255260402\n6/03/2015 7:06 7246047762\n5/03/2015 15:39 7245760885\n5/03/2015 13:41 7170760885\n4/03/2015 21:21 5595760885\n4/03/2015 18:59 5590496476\n4/03/2015 18:59 5585251201""" # For each line in the dataset, print the row which will be added to the # Google Chart. for line in DATASET.splitlines(): date, value = line.split(" ") # First we parse the date string using strptime(), and write it back out # as a Date() constructor to use in JavaScript date_obj = datetime.strptime(date, "%d/%m/%Y %H:%M") js_date = date_obj.strftime("new Date(%Y, %m, %d, %H, %M, %s, %f)") js_value = value.strip() print "[%s, %s]," % (js_date, js_value) Here’s a few rows of the output: [new Date(2015, 03, 10, 10, 55, 1425984900, 000000), 7385498415], [new Date(2015, 03, 10, 09, 15, 1425978900, 000000), 7379639094], [new Date(2015, 03, 10, 08, 55, 1425977700, 000000), 7376777516], [new Date(2015, 03, 10, 08, 35, 1425976500, 000000), 7368304217], Then I took the [scatter plot example](https://developers.google.com/chart/interactive/docs/gallery/scatterchart) from Google’s Chart gallery, dropped in the date values I got from the script above, and changed a few of the options. This is what it looks like: ![enter image description here](http://i.stack.imgur.com/2spPA.png) and here’s the HTML: <head> <!--Load the AJAX API--> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script> google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'Value'], [new Date(2015, 03, 10, 10, 55), 7385498415], [new Date(2015, 03, 10, 09, 15), 7379639094], [new Date(2015, 03, 10, 08, 55), 7376777516], [new Date(2015, 03, 10, 08, 35), 7368304217], [new Date(2015, 03, 10, 08, 12), 7358015859], [new Date(2015, 03, 08, 09, 22), 7358015859], [new Date(2015, 03, 08, 04, 27), 7354221274], [new Date(2015, 03, 08, 04, 07), 7346810719], [new Date(2015, 03, 07, 04, 25), 7339695326], [new Date(2015, 03, 07, 04, 25), 7339698276], [new Date(2015, 03, 06, 13, 08), 7339701226], [new Date(2015, 03, 06, 13, 04), 7317905872], [new Date(2015, 03, 06, 12, 44), 7309771372], [new Date(2015, 03, 06, 12, 24), 7300851599], [new Date(2015, 03, 06, 12, 04), 7292557469], [new Date(2015, 03, 06, 11, 39), 7283439433], [new Date(2015, 03, 06, 11, 00), 7278056128], [new Date(2015, 03, 06, 10, 41), 7267320628], [new Date(2015, 03, 06, 10, 35), 7265158228], [new Date(2015, 03, 06, 10, 21), 7265158228], [new Date(2015, 03, 06, 10, 01), 7255260402], [new Date(2015, 03, 06, 07, 06), 7246047762], [new Date(2015, 03, 05, 15, 39), 7245760885], [new Date(2015, 03, 05, 13, 41), 7170760885], [new Date(2015, 03, 04, 21, 21), 5595760885], [new Date(2015, 03, 04, 18, 59), 5590496476], [new Date(2015, 03, 04, 18, 59), 5585251201] ]); var options = { hAxis: {title: 'Date'}, vAxis: {title: 'Variable'}, legend: 'none', height: 500, width: 1100 }; var chart = new google.visualization.ScatterChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <div id="chart_div"></div> </body>
python with app engine error import ndb Question: I have a problem with app engine, I use it with django. I read a lot of thinks about the problem, but I never find a solution. I use Pycharm for the development, I just use app engine in the models.py For import ndb I make this : from google.appengine.ext import ndb There is my problem: If I use "dev_appserver.py ." I don't have any problems and the application work fine. But when I use "python manage.py test mobile_backend/" I have an error. > from google.appengine.ext import ndb > ImportError: No module named appengine.ext After some hours searching, the solution I have verified few things: -I put "'google.appengine.ext.ndb.django_middleware.NdbDjangoMiddleware', " in the top of my MIDDLEWARE_CLASSES settings -I have the google-cloud-sdk. -I have in my .profile "export PATH=$PATH:/home/david/google-cloud-sdk/platform" -I attempt to change the PYTHONPATH to integrated the PATH of google-cloud-sdk, but without success. Pycharm show me a problemwith the import, he know google, but don't know the end of the import.(appengine.ext) I have search and I have the ndb module with this path : /home/david/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb Somebody can help me? Answer: The problem is you are trying to use App Engine infrastructure but have not properly set up the App Engine environment. This is documented in the App Engine Local Unit Testing page in the [Setting up a testing framework](https://cloud.google.com/appengine/docs/python/tools/localunittesting#Python_Setting_up_a_testing_framework) section: sdk_path = '/home/david/google-cloud-sdk/platform/google_appengine' sys.path.insert(0, sdk_path) import dev_appserver dev_appserver.fix_sys_path()
Unable to process python subprocess stderr on windows Question: I am trying to simple file copy operation using `dd` under Windows. The code is simple. Just open the command using subprocess and read `stderr`. Then process the `stderr` to show the progress of the operation. Here is the sample/simple code which I an trying to accomplish:- import time import signal import subprocess import os def dd_win(): windd = "dd.exe" in_file = os.path.join("E:", "test-in.iso") out_file = os.path.join("E:", "test-out.iso") parameter1 = "if=" + in_file parameter2 = "of=" + out_file parameter3 = "bs=1M" parameter4 = "--progress" command = [windd, parameter1, parameter2, parameter4] print command dd_process = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, bufsize=0) while dd_process.poll() is None: time.sleep(.1) line = dd_process.stderr.readline() if not line: break print ">>>>>", line.strip() if dd_process.poll() is not None: print "Process finished." dd_win() Here is wht I got as an output. I could see the `stderr` but unable to process the transfer bytes to convert in to mega bytes:- C:\Users\user\Documents>python test.py ['dd.exe', 'if=E:test-in.iso', 'of=E:test-out.iso', '--progress'] >>>>> rawwrite dd for windows version 0.6beta3. >>>>> Written by John Newbigin <[email protected]> >>>>> This program is covered by terms of the GPL Version 2. >>>>> 175,882,240 # <--- Problem output line. Unable to assign to other variable for progress calculation Process finished. I actually do not know where the numbers are coming from. Is it from `stderr` or buffer? If it is from `stderr` then ">>>>>" should have be printed before the numbers. I work on Windows 7 and using windows version of dd. Any help is appreciated. Answer: As discussed in chat, the numbers are coming from stderr. By printing the ascii-indexes of each character in line, we discovered that the final line returned by readline() is `\t75,881,728 \r175,882,240 \r\n`. It looks like the `\r` embedded in the middle of this string (which DD outputs) is confusing your code.
python - igraph plot not available (cairo already installed) Question: I've installed py2cairo using brew, but keep getting errors when trying to plot with igraph. I get the following error: >>> import igraph as ig >>> from igraph import * >>> UG = ig.Graph() >>> UG.add_vertex('a') >>> UG.add_vertex('b') >>> UG.add_vertex('c') >>> UG.add_vertex('d') >>> UG.add_edge('a','d') >>> UG.add_edge('a','c') >>> UG.add_edge('b','c') >>> UG.add_edge('b','a') >>> layout = UG.layout_kamada_kawai() >>> plot(UG,layout = layout) Traceback (most recent call last): File "<stdin>", line 1, in <module> File ".../anaconda/lib/python2.7/site-packages/igraph/drawing/__init__.py", line 427, in plot result = Plot(target, bbox, background="white") File ".../anaconda/lib/python2.7/site-packages/igraph/drawing/__init__.py", line 122, in __init__ self._surface_was_created = not isinstance(target, cairo.Surface) File ".../anaconda/lib/python2.7/site-packages/igraph/drawing/utils.py", line 396, in __getattr__ raise TypeError("plotting not available") TypeError: plotting not available Answer: `brew` probably installs `py2cairo` for its own Python, while you are running igraph under Anaconda Python. A module installed for one Python distribution on your machine will not appear magically under the other Python distribution, so you'll either have to get `py2cairo` for Anaconda Python or compile the Python interface of igraph for Homebrew's Python.
Unit Testing JWT token exipiration: Django REST Question: How do I test the case of attempting to refresh an expired token? Or the case of trying to exceed `JWT_REFRESH_EXPIRATION_DELTA`? I'm looking for the most pythonic/djangotacular way to unit test a token refresh endpoint. AFAICT, my endpoint is working fine-it's refreshing the token, and when I test it via python REPL, it does what I expect. But since this is a documented bug I'm fixing, I'd like to end up with the fix under my test harness. Testing the positive case is easy, but I'm unsure of how to proceed from here. I don't want to do some delay loop or something like that, since that would undermine the whole unit test ideology of running quickly and in isolation... my tests are currently using the `response = self.client.post(...)` style. Answer: I can think of two ways to do what you want, and both involve using [mocks](https://docs.python.org/3/library/unittest.mock.html). You must learn to use mocks if you want to do serious isolated unit testing. ;) First, mock the [`validate`](https://github.com/GetBlimp/django-rest- framework-jwt/blob/master/rest_framework_jwt/serializers.py#L141) method of the `RefreshJSONWebTokenSerializer` to raise `serializers.ValidationError`: from rest_framework import serializers @mock.patch('rest_framework_jwt.RefreshJSONWebTokenSerializer.validate') def test_token_expiry_refresh(self, validate_mock): validate_mock.side_effect = serializers.ValidationError('Refresh has expired.') response = self.client.post('/refresh-token-url/') self.assertEquals(response.status, 400) # I believe it's this code what ValidationError should return A second option is a bit more involved and would imply playing with the current datetime: import datetime # http://stackoverflow.com/a/5437199/356729 class FakeDateTime(datetime): "A manipulable datetime replacement" def __new__(cls, *args, **kwargs): return datetime.__new__(datetime, *args, **kwargs) @patch('rest_framework_jwt.RefreshJSONWebTokenSerializer.datetime', FakeDateTime) def test_token_expiry_refresh(self): FakeDateTime.utcnow = classmethod(lambda cls: datetime.utcnow() + timedelta(0, 10)) response = self.client.post('/refresh-token-url/') self.assertEquals(response.status, 400) I prefer the first option since it's easier.
Open SSH connection on exit Python Question: I am writing a little script which picks the best machine out of a few dozen to connect to. It gets a users name and password, and then picks the best machine and gets a hostname. Right now all the script does is print the hostname. What I want is for the script to find a good machine, and open an ssh connection to it with the users provided credentials. So my question is how do I get the script to open the connection when it exits, so that when the user runs the script, it ends with an open ssh connection. I am using sshpass. Answer: You can use the os.exec* function to replace the Python process with the callee: import os os.execl("/usr/bin/ssh", "user@host", ...) <https://docs.python.org/2/library/os.html#os.execl>
Python continue for loop after exception Question: I'm trying to create a new version of a file that excludes NULL bytes. I'm using the code below to attempt this however it's still breaking on the NULL byte. How should I structure the `for` statement and `try-catch` block to keep going after the exception? import csv input_file = "/data/train.txt" outFileName = "/data/train_no_null.txt" ############################ i_f = open( input_file, 'r' ) reader = csv.reader( i_f , delimiter = '|' ) outFile = open(outFileName, 'wb') mywriter = csv.writer(outFile, delimiter = '|') i_f.seek( 0 ) i = 1 for line in reader: try: i += 1 mywriter.writerow(line) except csv.Error: print('csv choked on line %s' % (i + 1)) pass EDIT: Here's the error message: Traceback (most recent call last): File "20150310_rewrite_csv_wo_NULL.py", line 26, in <module> for line in reader: _csv.Error: line contains NULL byte UPDATE: I'm using this code: i_f = open( input_file, 'r' ) reader = csv.reader( i_f , delimiter = '|' ) # reader.next() outFile = open(outFileName, 'wb') mywriter = csv.writer(outFile, delimiter = '|') i_f.seek( 0 ) i = 1 for idx, line in enumerate(reader): try: mywriter.writerow(line) except: print('csv choked on line %s' % idx) and now get this error: Traceback (most recent call last): File "20150310_rewrite_csv_wo_NULL.py", line 26, in <module> for idx, line in enumerate(reader): _csv.Error: line contains NULL byte Answer: You can catch all errors with the following code... for idx, line in enumerate(reader): try: mywriter.writerow(line) except: print('csv choked on line %s' % idx)
how to make a function work in python Question: I wrote the following code in python and it works fine until I try to make it a function, can anyone help? import random def club(): members=int(input("members")) print (random.randint(1, members)) Answer: You have to use 4 spaces ( or tab) per indentation level. And call the function of course. import random def club(): members=int(input("members")) print (random.randint(1, members)) club()
Keeping Score in python code Question: What do I have to do in order to have a score board for my code because I need a score board. I tried a while statement but got lost there. Can you help me? So lost. import random def main_menu(): option = input("Play the game (P) , View the game credits (V), or Quit (Q)") if (option == "Play the game") or (option == "P"): riddles = [ {"riddle": "What walks on four legs in the morning, two legs in the afternoon, and three in the evening?", "answer": ["Monkey", "Humans", "Nothing Silly"], "correct": "2"}, {"riddle": "What has roots as nobady sees?", "answer": ["River", "Famliy Tree", "Mountain"], "correct": "3"}, {"riddle": " I am the ruin of men, and yet they lust for me. \ I have no power, no strength, and yet I am the might of kings and armies. \ I am hard as dragons scales, yet I flow like water. \ Men dream of me, and yet once found I am cast aside. \ I am a dancing rainbow, ever chased, never caught.", "answer": ["Gold", "Sex", "Mountain"], "correct": "1"}] print("Welcome to the Hell of Riddles!!!!") print("Hope you can think") random.shuffle(riddles) for riddle in riddles: print (riddle["riddle"]) for i, choice in enumerate(riddle["answer"]): print(str(i + 1) + ". " + choice) answer = input("Choose the number of the answer:") if answer == riddle["correct"]: print("Congratz! You can think!!!") else: print("Not correct... Pathetic and disappointing.") elif (option == "View the game credits") or (option == "V"): print("This game is brought to you by: Hailey Reisner and Ashleigh Woodard") elif (option == "Quit") or (option == "Q"): print("QUITER") print(main_menu()) Answer: create a counter and add to it for correct answers. You can also create a counter for wrong answer Of course you want to declare these variables first. so the code to increment your counter would be like : rightAnswer += 1 if answer == riddle["correct"]: print("Congratz! You can think!!!") rightAnswer+=1 else: print("Not correct... Pathetic and disappointing.") wrongAnswer+=1 print('Right: %d\tWrong: %d) % (rightAnswer, wrongAnswer)
asking for alternate method apart from eval in python Question: **Problem i am solving:** i am giving liberty to user to make conditions and actions for making rules while inserting data into a database and evaluate these conditions and action, i could not think anything else from using eval , an example of datastructure i created for such purpose is action_var = "" a_hash = {"condition":a_condition, "action":a_hash} a_condition ={"param":"abc", "operator":">", "value":"cde"} a_action = {"param":action_var, "operation":"=", "value":"action So my plan is to take condition id from user and action id from user and then use eval to evaluate the expression . **Help** : Am i going in right direction, is there alternate method to do this ? **P.S:** I can't use triggers on database, I am kind of using orm wrapper for lmdb. So i use write command at base level. Edit: i want to have multiple conditions, with and/or mixed, with brackets. Thanks Answer: You don't need to use `eval`. Map those operators to functions and then apply the functions to the arguments. Consider: >>> import operator >>> operators = {} >>> operators['>'] = operator.gt >>> operators['>'](*[1, 2]) False >>> 1 > 2 False
Websocket connection closed with an error "Received unexpected continuation frame." Question: I were just trying to use WebSockets. i wrote server code in python. The server is running fine but when tried to connect to the socket using browser, I'm getting the error > "WebSocket connection to 'ws://localhost:9876/' failed: Received unexpected > continuation frame" When referring on internet, I understood it is something related to framing of data that sent from the server. I've tried to follow [these](http://tools.ietf.org/html/rfc6455#section-5.6) (rfc6455) standards when sending a data, even I can't achieve a websocket connection. Almost similar question is asked [here](http://stackoverflow.com/questions/10490820/websockets-unresolvable- received-unexpected-continuation-frame-error), but it is an old post also the solution is not clear. This is my pretty simple server code.. import socket def handle(s): print repr(s.recv(4096)) s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) s.bind(('',9876)) s.listen(2) handshakes='\ HTTP/1.1 101 Web Socket Protocol Handshake\r\n\ Upgrade: WebSocket\r\n\ Connection: Upgrade\r\n\ Sec-WebSocket-Origin: null\r\n\ Sec-WebSocket-Location: ws://localhost:9876/\r\n\ ' def handshake(hs): hslist = hs.split('\r\n') body = hs.split('\r\n\r\n')[1] key = '' cc = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' for h in hslist: if h.startswith('Sec-WebSocket-Key:'): key = h[19:] else: continue import hashlib import base64 s = hashlib.sha1() s.update(key+cc)() h = s.digest() return base64.b64encode(h) def sender(data, conn): first_byte = chr(0x00) payload = data.encode('utf-8') pl = first_byte + payload + chr(0xFF) conn.send(pl) while True: c,a = s.accept() msg = c.recv(4096) if(msg): print msg print 'sending handshake ...' handshakes += 'Sec-WebSocket-Accept: '+str(handshake(msg))+'\r\n\r\n' print handshakes c.send(handshakes) sender("Hello", c) break; And the html, index.html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Web Socket Example</title> <meta charset="UTF-8"> <script> window.onload = function() { var s = new WebSocket("ws://localhost:9876/"); s.onopen = function(e) { alert("opened"); } s.onclose = function(e) { alert("closed"); } s.onmessage = function(e) { alert("got: " + e.data); } }; </script> </head> <body> <div id="holder" style="width:600px; height:300px"></div> </body> </html> I'm running this code like this.. ./server.py & python -m SimpleHTTPServer 8888 after running the server, when I hit localhost:8888 using browser, it alerts "opened" (means handshaking is done) at the same time alerts "closed" (connection closed) with the above error on console. Not very clear how to debug this issue. I'm using browser Chrome (version: 41), Python 2.7, Websocket 13. Answer: It works when I changed the sender function like this.. ... def sender(data, conn): length = len(data) if length <= 125: ret = bytearray([129, length]) for byte in text.encode("utf-8"): ret.append(byte) conn.send(ret) ...
Django Sending Email : SMTPServerDisconnected: Connection unexpectedly closed Question: hello i want to sending email activation use django registration redux. this is my setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' ACCOUNT_ACTIVATION_DAYS = 3 EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '[email protected]' EMAIL_HOST_PASSWORD = 'blahpassword' EMAIL_PORT = 465 EMAIL_USE_SSL = True LOGIN_REDIRECT_URL = '/' when i try with > python manage.py shell > > from django.core.mail import send_mail > > send_mail('Test', 'This is a test', '[email protected]', > ['[email protected]']) i am getting error like this: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/apsijogja/djangogirls/myvenv/local/lib/python2.7/site-packages/django/core/mail/__init__.py", line 62, in send_mail return mail.send() File "/home/apsijogja/djangogirls/myvenv/local/lib/python2.7/site-packages/django/core/mail/message.py", line 286, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/apsijogja/djangogirls/myvenv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 92, in send_messages new_conn_created = self.open() File "/home/apsijogja/djangogirls/myvenv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 50, in open self.connection = connection_class(self.host, self.port, **connection_params) 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 310, in connect (code, msg) = self.getreply() File "/usr/lib/python2.7/smtplib.py", line 361, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") SMTPServerDisconnected: Connection unexpectedly closed can you help me solve this problem? Answer: Please look into this Link: <https://code.djangoproject.com/ticket/9575> and try sending via shell, it should work
How to calculate number of downtimes and Total downtime and average downtime in the below xml file using python Question: How to calculate downtime and average downtime and total down time? Answer: The overallAvailability is an attribute of the tag ServiceAvailabiltyReport, so your code needs to look like this. import glob import xml.etree.ElementTree as ET sum = 0; count = 0; avgTime = 0 for fName in glob.glob("*.xml"): tree = ET.parse(fName) root = tree.getroot() for tag in root.iter('ServiceAvailabilityReport'): sum += float(tag.attrib["overallAvailability"]) count += 1 avgTime = sum / count print avgTime Also, just a a side note, the xml file you posted had some issues including missing closing tags etc. I'm not sure if this is true for all your files, or if it is an artefact of the copy paste.
Django: communicate with TCP server (with twisted?) Question: I have a django application, that needs to talk to a remote TCP server. This server will send packages and depending on what the package is, I need add entries to the database and inform other parts of the application. I also need to actively send requests to the TCP server, for instance when the user navigates to a certain page, I want to subscribe to a certain stream on the TCP server. So communication in both directions need to work. So far, I use the following solution: I wrote a custom Django command, that I can start with python manage.py listen This command will start a twisted socket server with `reactor.connectTCP(IP, PORT, factory)` and since it is a django command, I will have access to the database and all the other parts of my application. But since I also want to be able to send something to the TCP server, triggered by a certain django view, I have an additional socket server, that starts within my twisted application by `reactor.listenTCP(PORT, server_factory)`. To this server, I will then connect directly in my django application, within a new thread: class MSocket: def __init__(self): self.stopped = False self.socket = None self.queue = [] self.process = start_new_thread(self.__connect__, ()) atexit.register(self.terminate) def terminate(self): self.stopped = True try: self.socket.close() except: pass def __connect__(self): if self.stopped: return attempts = 0 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True and not self.stopped: try: print "Connecting to Socket Server..." self.socket.connect(("127.0.0.1", settings.SOCKET_PORT)) print "Connection Successful!" for msg in self.queue: self.socket.send(msg) self.queue = [] break except: pause = min(int(round(1.2**attempts)), 30) print "Connection Failed! Try again in " + str(pause) + " seconds." sleep(pause) attempts += 1 self.__loop__() def __loop__(self): if self.stopped: return while True and not self.stopped: try: data = self.socket.recv(1024) except: try: self.socket.close() except: pass break if not data: break self.__connect__() def send(self, msg): try: self.socket.send(msg) return True except: self.queue.append(msg) return False m_socket = MSocket() `m_socket` will then be imported by the main `urls.py` so that it starts with django. So my setup looks kind this: Sending to TCP Server: Django (connect:8001) -------> (listen:8001) Twisted (connect:4444) ------> (listen:4444) TCP-Server Receiving from TCP Server TCP-Server (listen:4444) ------> (connect:4444) Twisted ---(direct access)---> Django It all seems to work that way, but I fear that this is not a really good solution, since I have to open this extra TCP connection. So my question would be now, if the setup can be optimized (and I'm sure it can) and how it can be done. Answer: This is not going to work unless you monkey patch Django (as mentioned by @pss) I had a similar situation so this is what I did. 1. Run a separate twisted deamon. 2. To communicate from Django to Twisted, use Unix sockets. The local twisted server can listen on Unix sockets (AF_UNIX) and Django can simply connect to that socket. This will avoid going through the TCP stack 3. To communicate from Twisted to Django, you have multiple options, a) call Django url with the data b) launch a script (Django management command) c) Use celery to launch the the above Django command d) Use a queue (zeromq or rabbit) and have your Django management command listen in on the queue (preferred) With the last option, you get much better throughput, durability and it scales well.
Color a pixel in python opencv Question: I need to color a pixel in an image. I use opencv and python. I tried `img[x,y]=[255 255 255]` to color a `pixel(x,y)` but it wont work :( Is there is any mistake in this? Can you suggest any method? Thanks in advance. Answer: This works for me, just change it to load your own image: import cv2 img = cv2.imread("C:\calibrate\chess\color001.jpg", cv2.CV_LOAD_IMAGE_COLOR); ## Make pixels row and column 300-400 black img[300:400,300:400] = (0,0,0) cv2.imshow('title',img) cv2.waitKey(0) cv2.destroyAllWindows()
Verifying IP address using regex in Python Question: I am trying to validate an IP address. Following is the code. Can anyone please tell me what is wrong in the code? import re ip = '355.4' m = re.match('^((?:1?\d{0,2}|2[0-4]\d{1}|25[0-5]).){3}(?:1?\d{0,2}|2[0-4]\d{1}|25[0-5])$', ip) if m: print "correct" print m.groups() else: print "wrong" According to the IP given, it should print `wrong` as output but it prints `correct ('4',)` as the output. Answer: If you are allowed to `not to use regex`, you can use python's socket package . `inet_aton("string")` converts the `string` to `ip` address,if this is not valid ip then it will throw exception. Simple example I have tried: import socket def check_valid(address): try: socket.inet_aton(address) return address.count('.') == 3 except socket.error: return False if __name__ == "__main__": print check_valid("192.168.1.255") It will check all valid ip address like `192.168.1.257` is invalid while `192.168.1.255` is valid.
Pipe result from subprocess to unix sort Question: I am calling a perl script on an external txt files from python, and printing the output to an outfile. But instead I want to pipe the output to unix's sort. Right now I am not piping, but are writing the output from the perl program first, then doing by combining my code under, and [this stackoverflow answer](http://stackoverflow.com/a/14409939/2169327). import subprocess import sys import os for file in os.listdir("."): with open(file + ".out", 'w') as outfile: p = subprocess.Popen(["perl", "pydyn.pl", file], stdout=outfile) p.wait() Answer: To emulate the shell pipeline: #!/usr/bin/env python import pipes import subprocess pipeline = "perl pydyn.pl {f} | sort >{f}.out".format(f=pipes.quote(filename)) subprocess.check_call(pipeline, shell=True) without invoking the shell in Python: #!/usr/bin/env python from subprocess import Popen, PIPE perl = Popen(['perl', 'pydyn.pl', filename], stdout=PIPE) with perl.stdout, open(filename+'.out', 'wb', 0) as outfile: sort = Popen(['sort'], stdin=perl.stdout, stdout=outfile) perl.wait() # wait for perl to finish rc = sort.wait() # wait for `sort`, get exit status
Complicated sorting in Python Question: I need to sort a list of strings. However, I do not want to sort it using the first character, so I cannot use `.sort()` I have a list: records = ["Bibble - 1300 / 2000", "Jim Foo - 900 / 2000", "Bibble - 1600 / 2000", "Bibble - 1000 / 2000"] I want to sort by their score out of 2000. I want an output that looks something like this: >>> Jim Foo - 900 / 2000 Bibble - 1000 / 2000 Bibble - 1300 / 2000 Bibble - 1600 / 2000 In the example above, I sorted it by smallest to largest. I also want to know how I would sort this list biggest score to smallest score. I've tried `.sort()`, but It's nothing like what I want. `.sort()` sorts it with the first character which I do not want: >>> records.sort() >>> records ['Bibble - 1000 / 2000', 'Bibble - 1300 / 2000', 'Bibble - 1600 / 2000', 'Jim Foo - 900 / 2000'] >>> Is there anyway of doing this, possibly in regular expression? Is it also possible, so if i were to add more scores into the list I would still be able to sort it this way? Answer: You can use `sorted` function with a proper `key` and use `re.split` : >>> import re >>> sorted(records,key=lambda x:int(re.split(r'[-/]',x)[1].strip())) ['John Smith - 900 / 2000', 'Bob Foo - 1000 / 2000', 'Bob Foo - 1300 / 2000', 'Bob Foo - 1600 / 2000'] The `sorted` function sort your list based on its key function, and your key split your elements with `re.split` with function as following : re.split(r'[-/]',x) the pattern `[-/]` split your string based on `-` or `/`. for example : >>> re.split(r'[-/]',"Bob Foo - 1600 / 2000") ['Bob Foo ', ' 1600 ', ' 2000'] and then you need to `strip()` to remove the leading and trailing spaces. then convert to int and sort your list based on that value!
Ipython notebook 3 disables seaborn settings Question: I just upgraded to IPython Notebook version 3.0 and it's disabling the formatting for seaborn. Here's some sample code that replicates the problem import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline data = np.random.randn(100) fig,ax = plt.subplots(figsize = (11,8.5)) ax.plot(data) This code works just fine in IPython Notebook V2.4.1 (see <http://nbviewer.ipython.org/gist/anonymous/71733c24a68ee464ca40>), but in IPython Notebook v3.0, the axes become invisible (see <http://nbviewer.ipython.org/gist/anonymous/7525146b07709206908c>). Strangely, in V3, when I switch the order of the seaborn import and the matplotlib inline magic, the plot renders normally the first time I run, then if I re-run, the axes and gridlines disappear. So it seems to have something to do with the inline magic disabling seaborn properties. Any workarounds, other than not re-executing my imports after the first time? Answer: In iPython Notebook 3.0, add: seaborn.set_style('darkgrid') to restore Seaborn default color schemes.
Convert CSV to well-structured JSON in Python Question: I have a CSV file that is structured as below : `Store, Region, District, MallName, Location` 1234,90,910,MallA,GMT 4567,87,902,MallB,EST 2468,90,811,MallC,PST 1357,87,902,MallD,CST What I was able to accomplish with my iterative brow-beating was getting a format like so: { "90": { "910": { "1234": { "name": "MallA", "location": "GMT" } }, "811": { "2468": { "name": "MallB", "location": "PST" } } }, "87": { "902": { "4567": { "name": "MallB", "location": "EST" }, "1357": { "name": "MallD", "location": "CST" } } } } The code below is stripped down to match the sample data set I provided but you get the idea as to what is happening. Again, it's very iterative and non- pythonic which I'm trying to also move towards. (If anyone feels the defined procedures would be worthwhile to post I can). #************ # Main() #************ dictHierarchy = {} with open(getFilePath(), 'r') as f: content = [line.strip('\n') for line in f.readlines()] for data in content: data = data.split(",") myRegion = data[1] myDistrict = data[2] myName = data[3] myLocation = data[4] myStore = data[0] if myRegion in dictHierarchy: #check for District if myDistrict in dictHierarchy[myRegion]: #checkforStore dictHierarchy[myRegion][myDistrict].update({myStore:addStoreDetails(data)}) else: #add district dictHierarchy[myRegion].update({myDistrict:addStore(data)}) else: #add region dictHierarchy.update({myRegion:addDistrict(data)}) with open('hierarchy.json', 'w') as outfile: json.dump(dictHierarchy, outfile) Obsessive compulsive me looked at the JSON output above and thought that to someone blindly opening the file it looks like a hodge-podge. What I was hoping to do for plain-text readability is group the data and throw it into JSON format as so: {"Regions":[ {"Region":"90", "Districts":[ {"District":"910", "Stores":[ {"Store":"1234", "name":"MallA", "location":"GMT"}]}, {"District":"811", "Stores":[ {"Store":"2468", "name":"MallC", "location":"PST"}]}]}, {"Region":"87", "Districts":[ {"District":"902", "Stores":[ {"Store":"4567", "name":"MallB", "location":"EST"}, {"Store":"1357", "name":"MallD", "location":"CST"}]}]}]} Long story short I wasted quite some time today trying to sort out how to actually populate the data structure in Python and essentially ended up no where. Is there a clean, pythonic way to achieve this? Is it even worth the effort? Answer: I've added headers to your input like: Store,Region,District,name,location 1234,90,910,MallA,GMT 4567,87,902,MallB,EST 2468,90,811,MallC,PST 1357,87,902,MallD,CST then used python [csv reader](https://docs.python.org/2/library/csv.html) and [group by](https://docs.python.org/2/library/itertools.html#itertools.groupby) like this: import csv from itertools import groupby, ifilter from operator import itemgetter data = [] with open('in.csv') as csvfile: reader = csv.DictReader(csvfile) regions = [] regions_dict = sorted(list(reader), key=itemgetter('Region')) for region_id, region_group in groupby(regions_dict, itemgetter('Region')): districts = [] regions.append({'Region': region_id, 'Districts': districts}) districts_dict = sorted(region_group, key=itemgetter('District')) for district_id, district_group in groupby(districts_dict, itemgetter('District')): districts.append({'District': district_id, 'Stores': list(district_group)}) print regions
check entry inputs in tkinter using a function Question: I trying to create physics calculator using python tkinter but I find it quite difficult. I have done this calculator in Command line interface but I a bit different with tkinter. basically, I have 5 entry boxes and above each one of them a button. the user will insert values in three of them and should press the button on top of each unknown value to make the calculation and get the result. my main issue is how can I create a function that evaluates the inputs in my entry boxes and make the calculation then print the results inside the entry box. I made some coding but unfortunately the operation is not working due to few mistakes. here is my coding part: from Tkinter import * import math class calculator(): def is_positive_number(number): # validation function if number <= 0: return False else : return True def value_of_time(prompt): while True: # loop command for time try: valid = False while not valid: value = float((prompt)) if is_positive_number(value): valid = True return value else : valid = False print ('I donot know what is happening') except ValueError: print("Oops, unfortunately this is a wrong input, please try again.") #better try again... Return to the start of the loop continue else: #value was successfully parsed! #we're ready to exit the loop. break def input_of_box(prompt): while True: # loop for initial velocity try: value = float(input(prompt)) return value except ValueError: print("Oops, we are you not typing a number, please try again.") #better try again... Return to the start of the loop continue else: #value was successfully parsed! #we're ready to exit the loop. break # def minput(numberofinput): if numberofinput == 1: t = value_of_time("Enter the time that takes an object to accelerate in seconds:") return elif numberofinput == 2: u = input_of_box("Enter the initial velocity in m/s:") return elif numberofinput == 2: v = input_of_box("Enter the final velocity in m/s:") return def my_calculation(mvariables): # this function is to operate the calculation if mvariables == 1: a = (v-u) /(t) mentery1 = a return elif mvariables == 2: v = u + a*t mentery2 = v return elif mvariables == 3: u = a*t - v mentery3 = t elif mvariables == 4: t = (v - u)/a mentery3 = t return elif mvariables == 5: s = (v**2-u**2)/2*a mentery4 = s else: print ('there is an error') cal = Tk() cal.configure(background='sky blue') a = StringVar() u = StringVar() v = StringVar() t = StringVar() s = StringVar() cal.geometry('650x420+350+225') cal.title('Main Menu') # here we start greating buttons and entry boxes m_label = Label(text='Calculator',fg = 'Navy', font=("Helvetica", 20,"bold italic"), bg='sky blue') m_label.pack() button1 = Button(cal,text='A',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(1)) button1.place(x=92,y=210) mentery1 = Entry(cal, textvariable = a ,width=10,bd =3) mentery1.place(x=82,y=240) button2 = Button(cal,text='U',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(3)) button2.place(x=192,y=210) mentery2 = Entry(cal, textvariable = u ,width=10,bd =3) mentery2.place(x=182,y=240) button3 = Button(cal,text='V',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(2)) button3.place(x=292,y=210) mentery3 = Entry(cal, textvariable = v ,width=10,bd =3) mentery3.place(x=282,y=240) button4 = Button(cal,text='T',fg='white',bg='dark green',bd =3, width=4,command= lambda : my_calculation(4)) button4.place(x=392,y=210) mentery4 = Entry(cal, textvariable = t ,width=10,bd =3) mentery4.place(x=382,y=240) button5 = Button(cal,text='S',fg='white',bg='dark green',bd =3, width=4,command= lambda : my_calculation(5)) button5.place(x=492,y=210) mentery5 = Entry(cal, textvariable = s , width=10,bd =3) mentery5.place(x=482,y=240) # end of button commands app = calculator() app.mainloop() Answer: For validating the input, do the following: def returnValidatedInput(entry): value = entry.get() # Get the text in the 'entry' widget evaluation = eval(value) # Evaluate 'value' return evaluation And for inserting the answers into the entries (it's not called _printing the answers into the entries_): def insertAnswer(entry, answer): entry.delete(0, 'end') # Be sure the entry is empty, if it is not, clear it entry.insert(END, str(answer)) # Insert the answer into the 'entry' widget.
How to override the .get() method in requests? Question: I would like the `.get()` method in `requests` to do extra operations beside the `GET` itself: * print out "hello world" (in reality this will be logging) * wait 5 seconds before issuing the actual `GET` (in reality this will be a more complex wait-and-retry operation) Right now my simplistic solution is to use a function which actually calls `requests.get()`: def multiple_requests(self, url, retries=5, wait=5): """ retries several times an URL :param url: the url to check retries: how meny times to retry wait: number of seconds to wait between retries :return: the requests response, or None if failed """ for _ in range(retries): try: r = requests.get(url) except Exception as e: self.log.error("cannot connect to {url}: {e}, retrying in {wait} seconds".format(url=url, e=e, wait=wait)) else: if r.ok: return r else: self.log.error( "error connecting to {url}, code {e}, retrying in {wait} seconds".format( url=url, e=r.status_code, wait=wait ) ) finally: time.sleep(wait) # give up after several tries self.log.error("cannot connect to {url} despite retries, giving up".format(url=url)) return None but I have a strong feeling that it would be possible to override the actual `.get()` method in requests. I use object programming in a very basic way and that would be an opportunity to actually learn the override part. There are [various](http://blog.devzero.com/2013/01/28/how-to-override-a-class-method- in-python/) [tutorials](http://lgiordani.com/blog/2014/05/19/method- overriding-in-python/) on how to override and call the parent class methods (which is exactly what I want to do: be able to finally use the original `.get()` method) I therefore tried a basic override: import requests class MyRequest(requests.Request): def get(self, url, **kwargs): print("hello world") # calling the parent .get() method to actually GET something super(MyRequest, self).get(url, **kwargs) r = MyRequest.get('http://google.com') This code fails with Traceback (most recent call last): File "C:/Users/yop/dev/infoscreen/testingrequestsclass.py", line 8, in <module> r = MyRequest.get('http://google.com') TypeError: get() missing 1 required positional argument: 'url' To be honest, I am stuck here. The tutorials all start with a definition of the parent class, while what I have is hidden (there is [documentation](http://docs.python-requests.org/en/latest/api/)) Answer: [`requests.get` is just a function](https://github.com/kennethreitz/requests/blob/master/requests/api.py#L57-L65), you can override it. It is _not_ a method on the `requests.Requests` model: import requests.api def my_get(url, **kwargs): print('Hello World!') kwargs.setdefault('allow_redirects', True) return requests.api.request('get', url, **kwargs) requests.api.get = my_get This then uses a _new session object_ to handle the request. Instead of replacing `requests.get()`, I'd provide a subclass of the `requests.Session()` object instead, overriding the [`Session.request()` method](https://github.com/kennethreitz/requests/blob/master/requests/sessions.py#L382-L463), then use an instance of that session object: from requests import Session class MySession(Session): def request(self, method, url, **kwargs): print('Hello World!') return super().request(method, url, **kwargs) then use that like this: with MySession() as session: response = session.get(url) The advantage here is that you then can also make use of the full feature set that session objects offer, plus your additional code will also work for POST and PUT and DELETE and HEAD, etc. requests.
Django: AttributeError: type object 'MyAppConfig' has no attribute 'rpartition' Question: I am trying to add `view_amodel` permission to my models. I decided to add the permission after migration. So I made following approach. At an_app/**init**.py from an_app.apps import MyAppConfig default_app_config = MyAppConfig At an_app/apps.py from django.apps import AppConfig from django.db.models.signals import post_migrate from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission def add_view_permissions(sender, **kwargs): """ This syncdb hooks takes care of adding a view permission too all our content types. """ # for each of our content types for content_type in ContentType.objects.all(): # build our permission slug codename = "view_%s" % content_type.model # if it doesn't exist.. if not Permission.objects.filter(content_type=content_type, codename=codename): # add it Permission.objects.create(content_type=content_type, codename=codename, name="Can view %s" % content_type.name) print "Added view permission for %s" % content_type.name class MyAppConfig(AppConfig): def ready(self): post_migrate.connect(add_view_permissions, sender=self) When I do `python manage.py migrate`, I get following error, `AttributeError: type object 'MyAppConfig' has no attribute 'rpartition' ` How to solve it. Answer: The reference to the AppConfig in the app's `__init__.py` is supposed to be a string, not the class itself. default_app_config = 'an_app.apps.MyAppConfig' and remove the import. See [the documentation](https://docs.djangoproject.com/en/1.7/ref/applications/#for- application-authors).
Python how to do multiprocessing inside of a class? Question: I have a code structure that looks like this: Class A: def __init__(self): processes = [] for i in range(1000): p = Process(target=self.RunProcess, args=i) processes.append[p] # Start all processes [x.start() for x in processes] def RunProcess(self, i): do something with i... Main script: myA = A() I can't seem to get this to run. I get a runtime error "**An attempt has been made to start a new process before the current process has finished its bootstrapping phase.** " How do I get multiple processing working for this? If I use Threading, it works fine but it is as slow as sequential... And I'm also afraid that multiple processing will also be slow because it takes longer for the the process to be created? Any good tips? Many thanks in advance. Answer: There are a couple of syntax issues that I can see in your code: * `args` in `Process` expects a tuple, you pass an integer, please change line 5 to: `p = Process(target=self.RunProcess, args=(i,))` * `list.append` is a method and arguments passed to it should be enclosed in `()`, not `[]`, please change line 6 to: `processes.append(p)` As @qarma points out, its not good practice to start the processes in the class constructor. I would structure the code as follows (adapting your example): import multiprocessing as mp from time import sleep class A(object): def __init__(self, *args, **kwargs): # do other stuff pass def do_something(self, i): sleep(0.2) print('%s * %s = %s' % (i, i, i*i)) def run(self): processes = [] for i in range(1000): p = mp.Process(target=self.do_something, args=(i,)) processes.append(p) [x.start() for x in processes] if __name__ == '__main__': a = A() a.run()
Issue in reading JSON file in python Question: >>> import json >>> d2 = json.loads(open("t.json").read()) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads return _default_decoder.decode(s) File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode obj, end = self._scanner.iterscan(s, **kw).next() File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan rval, next_pos = action(m, context) File "/usr/lib64/python2.6/json/decoder.py", line 185, in JSONObject raise ValueError(errmsg("Expecting object", s, end)) ValueError: Expecting object: line 1 column 11 (char 11) [ RHEL - ~/testing ]$ cat t.json {"us": u"OFF", "val": u"5"} Here is what I have in my JSON file and when I try to read it using `open` and `json.load` and json.loads it fails. After using json.load >>> import json >>> d2 = json.load(open("t.json")) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/json/__init__.py", line 267, in load parse_constant=parse_constant, **kw) File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads return _default_decoder.decode(s) File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode obj, end = self._scanner.iterscan(s, **kw).next() File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan rval, next_pos = action(m, context) File "/usr/lib64/python2.6/json/decoder.py", line 185, in JSONObject raise ValueError(errmsg("Expecting object", s, end)) ValueError: Expecting object: line 1 column 11 (char 11) >>> Answer: You are using the wrong function. Use `json.load()` (no `s`!) to load data from an open file object: d2 = json.load(open("t.json")) The `json.loads()` function expects you to pass in a _string_ , not a file object. You'd have to read your file in that case, returning the read data: d2 = json.loads(open("t.json").read()) Next, you have invalid JSON in that file: {"us": u"OFF", "val": u"5"} # ^ ^ JSON is not Python; those `u` prefixes are not supported nor needed. You'll need to remove those from the file before it'll load. If you have an API producing that format, it is not giving you JSON. It could be that it is producing a (strange form of) Python syntax instead; Python itself would produce `{'us': u'OFF', 'val': u'5'}` (single quotes). You can have Python interpret that as Python literals with [`ast.literal_eval()`](https://docs.python.org/2/library/ast.html#ast.literal_eval): import ast with open('t.json') as fileobj: d2 = ast.literal_eval(fileobj.read()) but it could be that the format is broken in other ways we cannot determine from a single isolated sample. It could be using `true` and `false` for boolean values, like in JSON, for example. Better to have the _API_ fixed rather that try and work around this broken- ness.
SQLite select query returns string with a preceeding u in python Question: import sqlite3 #connect to the sqlite database conn = sqlite3.connect('database.db') #create a cursor c = conn.cursor() #select query to return a single row c.execute('SELECT NAME FROM T1') #row contains the returned result row = c.fetchone() #print the result print(row) It prints something like --> `(u'John',)`, but I only want `John` Answer: You are printing the whole row, which is _always_ going to be a tuple. If you wanted to print just the first column, use subscription: print(row[0])
In the context of a buildbot master.cfg file, how do I instantiate a class based on a string using native modules Question: In stock python, I can do the following to instantiate a class based on a string containing its name: #!/usr/bin/env python2.7 import sys class Foo(object): pass cls = getattr(sys.modules[__name__], 'Foo') instance = cls() print repr(instance) Which outputs the following: ahammond@af6119›~⁑ ./test.py <__main__.Foo object at 0x1095b0a10> I'd like to do something similar inside a buildbot master.cfg file, however the following (simplified) class BaseBuild(object): pass class BuildStashToSrpmsToRpmsToDepot(BaseBuild): def init(name, build_type): self.name = name def setup(): pass # actually does stuff here, but... for build_name, build_options in config['builds'].iteritems(): cls = getattr(sys.modules[__name__], build_options['build_type']) build = cls(name=build_name, **build_options) build.setup() Produces 2015-03-11 18:39:24-0700 [-] error while parsing config file: Traceback (most recent call last): File "/opt/buildbot_virtualenv/lib/python2.7/site-packages/twisted/internet/defer.py", line 577, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/opt/buildbot_virtualenv/lib/python2.7/site- packages/twisted/internet/defer.py", line 1155, in gotResult _inlineCallbacks(r, g, deferred) File "/opt/buildbot_virtualenv/lib/python2.7/site-packages/twisted/internet/defer.py", line 1099, in _inlineCallbacks result = g.send(result) File "/opt/buildbot_git/master/buildbot/master.py", line 189, in startService self.configFileName) --- <exception caught here> --- File "/opt/buildbot_git/master/buildbot/config.py", line 156, in loadConfig exec f in localDict File "/home/buildbot/master.cfg", line 208, in <module> cls = getattr(sys.modules[__name__], build_options['build_type']) exceptions.AttributeError: 'module' object has no attribute 'BuildStashToSrpmsToRpmsToDepot' 2015-03-11 18:39:24-0700 [-] Configuration Errors: 2015-03-11 18:39:24-0700 [-] error while parsing config file: 'module' object has no attribute 'BuildStashToSrpmsToRpmsToDepot' (traceback in logfile) Phrased another way, I guess what I'm really asking is what is the temporary module used while loading a new `master.cfg` and how can I reference it? I'm currently using a dictionary mapping of { 'class name': class_object } but I'd prefer something a little more native. Answer: Your problem here is: When running buildbot, your dunder name (__ name __ without the spaces...) when buildbot exec your config is buildbot.config, this is why 'module object has no attribute...'. I think you could do what you want making the values of your build_options dictionary to be the class itself, not a string with the class name. Like this: class BaseBuild(object): pass class BuildStashToSrpmsToRpmsToDepot(BaseBuild): def init(name, build_type): self.name = name def setup(): pass # actually does stuff here, but... # here the dict goes with key/class not key/class name build_options = {'build_type': BuildStashToSrpmsToRpmsToDepot} for build_name, build_options in config['builds'].iteritems(): cls = build_options['build_type'] build = cls(name=build_name, **build_options) build.setup() Just in case, this is how buildbot exec master.cfg (module buildbot.config): # ... # execute the config file localDict = { 'basedir': os.path.expanduser(basedir), '__file__': os.path.abspath(filename), } # from here on out we can batch errors together for the user's # convenience global _errors _errors = errors = ConfigErrors() old_sys_path = sys.path[:] sys.path.append(basedir) try: try: exec f in localDict except ConfigErrors, e: for err in e.errors: error(err) raise errors except: log.err(failure.Failure(), 'error while parsing config file:') error("error while parsing config file: %s (traceback in logfile)" % (sys.exc_info()[1],),) raise errors finally: f.close() sys.path[:] = old_sys_path _errors = None # ...
How to implement matlab's ismember(A, b) with A being a numpy ndarray and b being a list Question: What is the most efficient way to implement matlab's [ismember(A, b)](http://www.mathworks.com/help/matlab/ref/ismember.html) in python where in A is any numpy ndarray and b is a list of values. It should return a mask as a boolean ndarray of the same shape as A where in an element is True if the corresponding value in A is in the list of values in b. I want to replace all elements of A with value in list B with something. I expected `A[A in B] = 0` to work but it throws the following error: > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() If an implementation of an equivalent of `ismember` is there then the following would do what I need: A[ismember(A, b)] = 0 Note: I don't want solutions involving looping through all elements of A in python. Based on the answer of [ajcr](http://stackoverflow.com/users/3923281/ajcr), one solution is: import numpy as np def ismember(A, b): return np.in1d(A, b).reshape(A.shape) But this is quite slow and runs out of memory. For my case, A is an image as big as 512 x 512 x 1200. b has about 1000 elements. Answer: You may be looking for [`np.in1d`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html): >>> A = np.arange(9) >>> B = [4, 6, 7] >>> np.in1d(A, B) array([False, False, False, False, True, False, True, True, False]) Note that for multidimensional arrays `A`, the input is flattened so you'll need to reshape the boolean array: >>> A = np.arange(9).reshape(3, 3) >>> np.in1d(A, B).reshape(A.shape) array([[False, False, False], [False, True, False], [ True, True, False]], dtype=bool)
Extracting data from webpage using lxml XPath in Python Question: I am having some unknown trouble when using xpath to retrieve text from an HTML page from lxml library. The page url is www.mangapanda.com/one-piece/1/1 I want to extract the selected chapter name text from the drop down select tag. Now I just want the first option so the XPath to find that is pretty easy. That is :- .//*[@id='chapterMenu']/option[1]/text() I verified the above using Firepath and it gives correct data. but when I am trying to use lxml for the purpose I get not data at all. from lxml import html import requests r = requests.get("http://www.mangapanda.com/one-piece/1/1") page = html.fromstring(r.text) name = page.xpath(".//*[@id='chapterMenu']/option[1]/text()") But in name nothing is stored. I even tried other XPath's like :- //div/select[@id='chapterMenu']/option[1]/text() //select[@id='chapterMenu']/option[1]/text() The above were also verified using FirePath. I am unable to figure out what could be the problem. I would request some assistance regarding this problem. But it is not that all aren't working. An xpath that working with lxml xpath here is :- .//img[@id='img']/@src Thank you. Answer: I've had a look at the html source of that page and the content of the element with the id `chapterMenu` is empty. I think your problem is that it is filled using javascript and javascript will not be automatically evaluated just by reading the html with `lxml.html` You might want to have a look at this: [Evaluate javascript on a local html file (without browser)](http://stackoverflow.com/q/16375251/2677943) Maybe you're able to trick it though... In the end, also javascript needs to fetch the information using a get request. In this case it requests: [http://www.mangapanda.com/actions/selector/?id=103&which=191919](http://www.mangapanda.com/actions/selector/?id=103&which=191919) Which is json and can be easily turned into a python dict/array using the json library. But you have to find out how to get the `id` and the `which` parameter if you want to automate this. The id is part of the html, look for `document['mangaid']` within one of the script tags and `which` ~~can maybe stay 191919~~ has to be 0... ~~although I couldn't find it in any source~~ I found it, when it is 0 you will be redirected to the proper url. So there you go ;)
Pandas HDF5 store unicode error on select query Question: I have unicode data as read from this file: Mdt,Doccompra,OrgC,Cen,NumP,Criadopor,Dtcriacao,Fornecedor,P,Fun 400,8751215432,2581,,1,MIGRAÇÃO,01.10.2004,75852214,,TD 400,5464282154,9874,,1,MIGRAÇÃO,01.10.2004,78995411,,FO I have two problems: 1) When I try to query this unicode data I get the `UnicodeDecodeError`: Traceback (most recent call last): File "<ipython-input-1-4423dceb2b1d>", line 1, in <module> runfile('C:/Users/u5en/Documents/SAP/Programação/Problema HDF.py', wdir='C:/Users/u5en/Documents/SAP/Programação') File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 580, in runfile execfile(filename, namespace) File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 48, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace) File "C:/Users/u5en/Documents/SAP/Programação/Problema HDF.py", line 15, in <module> store.select("EKKA", "columns=['Mdt', 'Fornecedor']") File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 665, in select return it.get_result() File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 1359, in get_result results = self.func(self.start, self.stop, where) File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 658, in func columns=columns, **kwargs) File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 3968, in read if not self.read_axes(where=where, **kwargs): File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 3201, in read_axes a.convert(values, nan_rep=self.nan_rep, encoding=self.encoding) File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 2058, in convert self.data, nan_rep=nan_rep, encoding=encoding) File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 4359, in _unconvert_string_array data = f(data) File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\numpy\lib\function_base.py", line 1700, in __call__ return self._vectorize_call(func=func, args=vargs) File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\numpy\lib\function_base.py", line 1769, in _vectorize_call outputs = ufunc(*inputs) File "C:\Users\u5en\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 4358, in <lambda> f = np.vectorize(lambda x: x.decode(encoding), otypes=[np.object]) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 7: unexpected end of data How can I _store_ and _query_ my unicode data in hdf5? 2) I have many tables with column names I do not know beforehand and which are not propper pytable names (NaturalNameWarning). I would like the user to be able to query on this columns, so I wonder how could I query these when their name prevents me. I see this used to have [no easy fix](http://%20http://stackoverflow.com/questions/19277059/pandas-hdf5-select- with-where-on-non-natural-named-columns), so if that is still the case I will just remove the offending characters from the heading. import csv import pandas as pd dados = pd.read_csv("EKKA - Cópia.csv") print(dados) store= pd.HDFStore('teste.h5' , encoding="utf-8") store.append("EKKA", dados, format="table", data_columns=True) store.select("EKKA", "columns=['Mdt', 'Fornecedor']") store.close() Would I be _better off_ doing this in _sqlite_? Environment: Windows 7 64bit Pandas 15.2 NumPy 1.9.2 Answer: So under Python 2.7 on Windows 7, pandas 0.15.2, everything worked as expected, no encoding necessary. However on Python 3.4, the following worked for me. Apparently some characters are not representable in 'utf-8'; 'latin1' encoding usually solves these issues. Note that I had to read the csv in the first place with this encoding. >>> df = pd.read_csv('../../test.csv',encoding='latin1') >>> df Mdt Doccompra OrgC Cen NumP Criadopor Dtcriacao Fornecedor P Fun 0 400 8751215432 2581 NaN 1 MIGRAÇ\xc3O 01.10.2004 75852214 NaN TD 1 400 5464282154 9874 NaN 1 MIGRAÇ\xc3O 01.10.2004 78995411 NaN FO Further, the encoding must be specified not when opening the store, but on the `append/put` calls >>> df.to_hdf('test.h5','df',format='table',mode='w',data_columns=True,encoding='latin1') >>> pd.read_hdf('test.h5','df') Mdt Doccompra OrgC Cen NumP Criadopor Dtcriacao Fornecedor P Fun 0 400 8751215432 2581 NaN 1 MIGRAÇ\xc3O 01.10.2004 75852214 NaN TD 1 400 5464282154 9874 NaN 1 MIGRAÇ\xc3O 01.10.2004 78995411 NaN FO Once it is written encoded, it is not necessary to specify the encoding when reading.
Python: assert call to a list that contains a variable Question: This question follows python 2.7.3 syntax. In unittest framework, suppose I have the following set up: import mock; my_mock = mock.Mock(); my_patch = mock.patch("my_method", my_mock); Now suppose my_method takes on a list argument as input. How Can I use my_mock.assert_any_call to make sure that a call is made to my_method such that the input list contains a particular value? Answer: You can do that by use both [`mock_calls`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.mock_calls) and call unpacking as documented [here](https://docs.python.org/3/library/unittest.mock.html#call). Now a for cycle can be enough to do the work: >>> import mock >>> m = mock.Mock() >>> m([1,2]) <Mock name='mock()' id='140596484020816'> >>> m([5,6]) <Mock name='mock()' id='140596484020816'> >>> m([8,9]) <Mock name='mock()' id='140596484020816'> >>> for name,args,kwrgs in m.mock_calls: ... if 5 in args[0]: ... print("found") ... found
Selenium Connection Error Question: Has anyone run across this error before? I just started getting this error on monday. Why is it having issues with connecting? Selenium will open the browser but will not plug in the url. C:\Python34\python.exe "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0.5\helpers\pydev\pydevd.py" --multiproc --client 127.0.0.1 --port 49660 --file //HAL1/FTP-Directories/Comal-County/comal.py pydev debugger: process 5564 is connecting Connected to pydev debugger (build 139.1547) Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0.5\helpers\pydev\pydevd.py", line 2217, in <module> globals = debugger.run(setup['file'], None, None) File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0.5\helpers\pydev\pydevd.py", line 1643, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition4.0.5\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "//HAL1/FTP-Directories/Comal-County/comal.py", line 7, in <module> driver = webdriver.Firefox(); File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 59, in __init__ self.binary, timeout), File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\extension_connection.py", line 47, in __init__ self.binary.launch_browser(self.profile) File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 66, in launch_browser self._wait_until_connectable() File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 105, in _wait_until_connectable raise WebDriverException("Can't load the profile. Profile " selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: %s If you specified a log_file in the FirefoxBinary constructor, check it for details. Code: from selenium import webdriver driver = webdriver.Firefox(); driver.get("http://www.google.com") Answer: This is a **compatibility issue** between `selenium` and `Firefox`. Upgrade your `Firefox` to the latest version (36 at the moment). And upgrade `selenium` to the latest version (2.45 at the moment): pip install --upgrade selenium
How to create a combobox that includes checkbox for each item? Question: Fairly new to tkinter and python I was wondering how to achieve a button that would act like this : * Click on button drops down a list (so that's a combobox) * Each line of the list has a checkbox. * Finally if a checkbox is clicked run a function, or (even better) once combobox is no more dropped run a function with items checked as args. **UPDATE** The button/menuButton will have to act like a filter. When menu is dropped down user can uncheck multiple options (without the menu to disappear each time an item is clicked) he don't want. Therefore it's really important to be able to see checkboxes so as the user know which options are currently active. I finally used the idea of Bryan by creating a top level frame. Here is what I have : ![](http://i.stack.imgur.com/HGf8W.png) Answer: I don't think the `OptionMenu` is intended to hold anything but strings. It sounds like you want the functionality of a [Listbox](http://effbot.org/tkinterbook/listbox.htm), which has options to allow for multiple selections, get all selected items, and so on. This gives you an `OptionMenu` with _checkboxes_ in the contained Menu. Check whichever items you like, then right-click in the tkinter window to print the values of the checkboxes to the console. from tkinter import * master = Tk() var = StringVar(master) var.set("Check") w = OptionMenu(master, variable = var, value="options:") w.pack() first = BooleanVar() second = BooleanVar() third = BooleanVar() w['menu'].add_checkbutton(label="First", onvalue=True, offvalue=False, variable=first) w['menu'].add_checkbutton(label="Second", onvalue=True, offvalue=False, variable=second) w['menu'].add_checkbutton(label="Third", onvalue=1, offvalue=False, variable=third) master.bind('<Button-3>', lambda x: print("First:", first.get(), " Second:", second.get(), " - Third:", third.get())) mainloop() See also [this](http://stackoverflow.com/questions/3929355/making-menu- options-with-checkbutton-in-tkinter-python).
Using predict() on statsmodels.formula data with different column names using Python and Pandas Question: I've got some regressions results from running `statsmodels.formula.api.ols`. Here's a toy example: import pandas as pd import numpy as np import statsmodels.formula.api as smf example_df = pd.DataFrame(np.random.randn(10, 3)) example_df.columns = ["a", "b", "c"] fit = smf.ols('a ~ b', example_df).fit() I'd like to apply the model to column `c`, but a naive attempt to do so doesn't work: fit.predict(example_df["c"]) Here's the exception I get: PatsyError: Error evaluating factor: NameError: name 'b' is not defined a ~ b ^ I can do something gross and create a new, temporary `DataFrame` in which I rename the column of interest: example_df2 = pd.DataFrame(example_df["c"]) example_df2.columns = ["b"] fit.predict(example_df2) Is there a cleaner way to do this? (short of switching to `statsmodels.api` instead of `statsmodels.formula.api`) Answer: You can use a dictionary: >>> fit.predict({"b": example_df["c"]}) array([ 0.84770672, -0.35968269, 1.19592387, -0.77487812, -0.98805215, 0.90584753, -0.15258093, 1.53721494, -0.26973941, 1.23996892]) or create a numpy array for the prediction, although that is much more complicated if there are categorical explanatory variables: >>> fit.predict(sm.add_constant(example_df["c"].values), transform=False) array([ 0.84770672, -0.35968269, 1.19592387, -0.77487812, -0.98805215, 0.90584753, -0.15258093, 1.53721494, -0.26973941, 1.23996892])
Running remote command with fabric doesn't separate stdout and stderr streams Question: I have a python file like so in my home directory import sys sys.stdout.write('THIS IS STDOUT\n') sys.stdout.flush() sys.stderr.write('THIS IS STDERR\n') sys.stderr.flush() When I run this python file, I get output to stdout/stderr as expected. Now, I have the following fabfile: from fabric.api import run, task @task def my_task(cmd): run(cmd) When I run the task, both lines get reported as coming from stdout: $ fab --host localhost my_task:'python foo.py' [localhost] Executing task 'my_task' [localhost] run: python foo.py [localhost] out: THIS IS STDOUT [localhost] out: THIS IS STDERR [localhost] out: Done. Disconnecting from localhost... done. Why does fabric pipe stderr into stdout? Looking [here](https://github.com/fabric/fabric/blob/master/fabric/io.py#L44) stderr lines should get `err:` prepended to them, not `out`. Moreover, adding some debugging statements in there I can see that there is an object set up to watch `stderr`; however it's just not getting any data. Is there a way to change this so that the error lines get `err:` in front of them? Answer: Just disable `combine_stderr`: run(cmd, combine_stderr=False)
Is there a way to test correlation between Data X and Binary output Y? Question: I'm trying to find a Python method/library for testing correlation between the independent variables X and the binary output Y.. So for example, lets say I have the following data and output: **X** **Y** 0.65 1 0.11 0 0.13 0 0.35 1 0.21 0 ... Lets say the output Y is 1 if (X > 0.3) and 0 otherwise. If I don't know this correlation (the threshold value 0.3), is there a statistical method/test to find out the degree of correlation between X and Y? So for example, some method that returns x = [0.65, 0.11, 0.13, 0.31, 0.21] y = [1, 0, 0, 1, 0] print some_test(x, y) ==> returns "degree of correlation = 1.0" Thanks Answer: You are looking for a [point biserial correlation](http://en.wikipedia.org/wiki/Point- biserial_correlation_coefficient), which is used when one of your variables is dichotomous. from scipy import stats stats.pointbiserialr(x,y) If you simply want to know whether X is _different_ depending on the value of Y, you should instead use a t-test.
interpreting bytes as ushorts in Python Question: I need to interpret 16 bytes received over a TCP socket as 8 ushorts. This line correctly receives the data (the 16-bit values of 8 a-d converters), and I can access each byte as an index into a byte array: vals = bytearray(s.recv(16)) And I could create 8 variables and decode each: ad1 = (ord(vals[0]) * 256)+ord(vals[1]) But it would be more elegant if I could recast this array as 8 ushorts. I have tried many variations of struct.unpack, with just as many syntax errors. My background is in C, so I would ordinarily use a union or recast a byte pointer, but... can anyone point me in the right direction? thanks, and my apologies if this has been asked before. # here is the full monty: import socket,struct,time import xrlib def readADx(socket,a2dnumber): # a2dnumber 1 - 8 if a2dnumber < 1 or a2dnumber > 8: return 0 a2d = a2dnumber + 0x9D tdata = struct.pack('BB',0xFE,a2d) s.send(tdata) val = ord(s.recv(1)) * 256 val = val + ord(s.recv(1)) return val # # define TCP client socket: # IPADDR = '192.168.99.9' PORTNUM = 2101 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IPADDR,PORTNUM)) tdata = struct.pack('BB',0xFE,0xA7) s.send(tdata) # # the problem: # vals = bytearray(s.recv(16)) adv = struct.unpack('8H',vals) # # get the true values for A/D 7 and 8: # ad8 = readADx(s,8); ad7 = readADx(s,7); s.close() print("%04X %04X %04X %04X %04X %04X %04X %04X"%adv[0],adv[1],adv[2],adv[3],adv[4],adv[5],adv[6],adv[7])) print("AD8: %d"%(ad8)); print("AD7: %d"%(ad7)); print("adv[7]: %d"%(adv[7])); print("adv[6]: %d"%(adv[6])); running this gives this error: struct.error: unpack requires a string argument of length 16 this is the error I would invariably get, with different argument lengths. this code works: adv = struct.unpack('8H',s.recv(16)) but the byte order of each reading (adv[x]) is reversed. I found socket.ntohs() to fix this. Still not sure why the struct.unpack would not work with the bytearray arg... Answer: (transforming a comment to an answer) ad1 = struct.unpack('8H', vals)
How can I monitor a TCP port for packets and timeout if none is received? Question: I'm creating a test client with using python to test my server. It sends TCP data packets to a server, which _should_ send back 1 response to the client in the same TCP connection. If it does not send any response, or sends more than 1 response, then I have a bug in the server code. What I want to do is to monitor the TCP port for response message(s) and print them out. If there is no response, the script should carry on execution after a timeout. Here's the relevant code: import socket import time import multiprocessing def get_response(response_stream, response_buffer_size): response_count = 1 while True: response = response_stream.recv(response_buffer_size).decode() print("[response]", response_count, ":", response) response_count += 1 TCP_IP = '192.168.1.101' TCP_PORT = 12345 BUFFER_SIZE = 1024 MESSAGE = b"Bazinga!" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) s.send(MESSAGE.encode()) print("Message sent.") p = multiprocessing.Process(target = get_response(s,BUFFER_SIZE)) p.start() p.join(3) if p.is_alive(): print("Killing thread ...") p.terminate() p.join() s.close() print("Socket closed.") So it turns out that `p.join(3)` is never reached because the code is stuck inside `get_response` at this line : `response = response_stream.recv(response_buffer_size).decode()`. The script will always wait there to decode the next packet, hence the script never terminates properly. What am I doing wrong ? Answer: First, this line: p = multiprocessing.Process(target = get_response(s,BUFFER_SIZE)) Is actually calling `get_response` _on the main thread_. Since, you're not passing a function name like you should, but calling the function and passing the `target` argument, the result of that call. Instead you want p = multiprocessing.Process(target=get_response, args=(s,BUFFER_SIZE)) **But this won't work!** You can't easily pass a socket to a different process. There are ways around it with pipes, but the implementation is only there for Unix or Python3 on Windows. So consider the different approach I list below. Third, you might want to add something that breaks out of the infinite loop inside your child process function. I added a line to check if `recv` returned an empty string, you could modify it to your liking. Consider: import socket import time import multiprocessing def worker(tcp_ip, tcp_port, response_buffer_size): MESSAGE = b"Bazinga!" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((tcp_ip, tcp_port)) s.send(MESSAGE.encode()) print("Message sent.") response_count = 1 while True: response = s.recv(response_buffer_size).decode() if len(response) == 0: break print("[response]", response_count, ":", response) response_count += 1 # If we got here, the connection was closed s.close() print("Socket closed.") if __name__ == "__main__": TCP_IP = '192.168.1.10' TCP_PORT = 12345 BUFFER_SIZE = 1024 p = multiprocessing.Process(target=worker, args=(TCP_IP, TCP_PORT, BUFFER_SIZE)) p.start() p.join(3) if p.is_alive(): print("Killing thread ...") p.terminate() p.join() print("Thread terminated.") print("Goodbye.") Here, we put _all_ socket activity in the worker thread. It owns and opens the socket, sends the "Bazinga" and handles responses.
Error writing text into a .txt file in python Question: I am making a program that will 1\. Create a text file 2\. Allow a password to be stored 3\. Allow a password to be changed 4\. Add an additional password 5\. Delete a specific password The problem is in `def delete():`. I put in three passwords on three seperate lines: first, second, third. When I choose to delete password "second", it reprints the list from before, and then prints the new list at the end of the last password. Here is my code: import time def create(): file = open("password.txt", "w") passwordOfChoice = input("The password you want to store is: ") file.write(passwordOfChoice) print ("Your password is: ", passwordOfChoice) file.close() time.sleep(2) def view(): file = open("password.txt","r") print ("Your password is: ", "\n", file.read()) file.close() time.sleep(2) def change(): file = open("password.txt", "w") newPassword = input("Please enter the updated password: ") file.write(newPassword) print ("Your new password is: ", newPassword) file.close() time.sleep(2) def add(): file = open("password.txt", "a") extraPassword = input("The password you want to add to storage is: ") file.write("\n") file.write(extraPassword) print ("The password you just stored is: ", extraPassword) file.close() time.sleep(2) def delete(): phrase = input("Enter a password you wish to remove: ") f = open("password.txt", "r+") lines = f.readlines() for line in lines: if line != phrase+"\n": f.write(line) f.close() print("Are you trying to: ", "\n1. Create a password?", "\n2. View a password?", "\n3. Change a previous password?", "\n4. Add a password?", "\n5. Delete a password?", "\n6. Exit?\n") function = input() print("") if (function == '1'): create() elif (function == '2'): view() elif (function == '3'): change() elif (function == '4'): add() elif (function == '5'): delete() elif (function == '6'): print("Understood.", "\nProgram shutting down.") time.sleep(1) else: print("Your answer was not valid.") print("Program shutting down...") time.sleep(1) To show what I meant above, here is my output: Your password is: first second thirdfirst third Can someone please tell me how to fix my `def delete():` function so that it will not rewrite the original data? Thanks a ton! Answer: The problem lies with the 'r+' mode. When you use 'r+' you can read and write, sure, but it's up to you to control _where_ in the file you write. What's happening is you read the file, and the cursor is stuck at the end, so when you write it back, Python dutifully puts your new lines on the end of the file. See [the docs](https://docs.python.org/3.4/tutorial/inputoutput.html#methods-of-file- objects) about file methods; you're looking for something like **seek**.
how do you access rows in tables in html form usibg python mechanize Question: im trying to access the rows in an html form, the html code in the form is as such </script> <form name="calendarForm" method="post" action="/ibook/publicLogin.do" onsubmit="return validateForm(this);"><div><input type="hidden" name="org.apache.struts.taglib.html.TOKEN" value="7a6aa28270cc38601c894a05d01b7264"></div> <input type="hidden" name="apptDetails.apptType" value="PRAP"> <table border="0" cellspacing="1" cellpadding="0" align="center"> <tr> <td nowrap="nowrap" width="20%"><div id=id_div1 style="display:''"><FONT color=#ff0000>*</FONT><label for="apptDetails.identifier1">Sponsor's NRIC /<br />&nbsp;&nbsp;Applicant's FIN</label></div></td> <td nowrap="nowrap" width="5%">:</td> <td nowrap="nowrap" width="75%"><div id=id_div3 style="display:''"><input type="text" name="apptDetails.identifier1" maxlength="9" size="15" value="" onblur="javascript:this.value=this.value.toUpperCase();" id="apptDetails.identifier1" style="text-transform: uppercase;" class="txtFill_singleLine"></div></td> </tr> im tring to add information to row with name `name="apptDetails.identifier1" ` how do i input values to the row? i dont seem to be able to access the html row using conventional python mechanize form options please advise here is my code import cookielib import urllib2 import mechanize # Browser br = mechanize.Browser() # Enable cookie support for urllib2 cookiejar = cookielib.LWPCookieJar() br.set_cookiejar( cookiejar ) # Broser options br.set_handle_equiv( True ) br.set_handle_gzip( True ) br.set_handle_redirect( True ) br.set_handle_referer( True ) br.set_handle_robots( False ) # ?? br.set_handle_refresh( mechanize._http.HTTPRefreshProcessor(), max_time = 1 ) br.addheaders = [ ( 'User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0' ),('Host','eappointment.ica.gov.sg'),('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') ] # authenticate br.open('https://eappointment.ica.gov.sg/ibook/gethome.do') print "forms" br.select_form(name="calendarForm") print "forms" # these two come from the code you posted # where you would normally put in your username and password br.find_control(name="apptDetails.apptType").value = ['PRAP'] res = br.submit() html = br.response().readlines() file = open("html.txt", "w") for i in range(0, len(html)): file.write(html[i]) file.write('\n') file.close() br.close() print "Success!\n" Answer: After calling `br.submit()`, you will have navigated to the next page. There are _two_ forms on that page, _both_ named "calendarForm": >>> for f in br.forms(): ... print f ... print ... <calendarForm POST https://eappointment.ica.gov.sg/ibook/loginSelection.do application/x-www-form-urlencoded <HiddenControl(org.apache.struts.taglib.html.TOKEN=2eb104ffed4bc6ea09b67e556e5dd6e2) (readonly)> <SelectControl(apptDetails.apptType=[CS, CSCA, CSCR, CSIC, CSPC, CSXX, PR, *PRAP, PRCF, PRAR, PRIC, PRNN, PRTR, CSXX, VS, VSEI, VSLA, VSLT, VSSP, VSST, VSVP])>> <calendarForm POST https://eappointment.ica.gov.sg/ibook/publicLogin.do application/x-www-form-urlencoded <HiddenControl(org.apache.struts.taglib.html.TOKEN=2eb104ffed4bc6ea09b67e556e5dd6e2) (readonly)> <HiddenControl(apptDetails.apptType=PRAP) (readonly)> <TextControl(apptDetails.identifier1=)> <TextControl(apptDetails.identifier2=)> <TextControl(apptDetails.identifier3=)> <IgnoreControl(Clear=<None>)>> You need to select the second form (with index 1), so: >>> br.select_form(nr=1) >>> print br.form <calendarForm POST https://eappointment.ica.gov.sg/ibook/publicLogin.do application/x-www-form-urlencoded <HiddenControl(org.apache.struts.taglib.html.TOKEN=2eb104ffed4bc6ea09b67e556e5dd6e2) (readonly)> <HiddenControl(apptDetails.apptType=PRAP) (readonly)> <TextControl(apptDetails.identifier1=)> <TextControl(apptDetails.identifier2=)> <TextControl(apptDetails.identifier3=)> <IgnoreControl(Clear=<None>)>> Now you can fill in the form's fields: >>> br.form['apptDetails.identifier1'] = '12345' >>> br.form['apptDetails.identifier2'] = '99' >>> br.form['apptDetails.identifier3'] = '911' >>> print br.form <calendarForm POST https://eappointment.ica.gov.sg/ibook/publicLogin.do application/x-www-form-urlencoded <HiddenControl(org.apache.struts.taglib.html.TOKEN=2eb104ffed4bc6ea09b67e556e5dd6e2) (readonly)> <HiddenControl(apptDetails.apptType=PRAP) (readonly)> <TextControl(apptDetails.identifier1=12345)> <TextControl(apptDetails.identifier2=99)> <TextControl(apptDetails.identifier3=911)> <IgnoreControl(Clear=<None>)>> and, finally, submit and save the response for inspection: >>> br.submit() >>> open('response.html', 'w').write(br.response().read()) If you entered valid values for the 3 identifiers, you should be at the next page, whatever that is.
Python2: subprocess.Popen() has another output as it runs direct on console Question: When i am running a program in the console, i get some text output. When i am running the same program in Popen(..), with the same parameters, stdout and stderr are empty. I tried everything i could imagine like shell=False and shell=True, set stdout=subprocess.PIPE, did a os.chdir() to change into the directory of this program, try p.wait() and p.communicate(), set the command as a list and as a string, but nothing works. example: p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) out, err = p.communicate() \--> out and err are empty strings, but if i ran this command in console i get a real output. Command is with fullpath, so its regardless where the command will be started. My question is, are there mechanisms for programms to detect they weren't run in a real console? If so, how can i cheat. Or miss i something? (Python 2.7.8. x32 in Win7 x64) Answer: from subprocess import Popen, STDOUT, PIPE p = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, stdin=PIPE) while p.poll() is None: print(p.stdout.read()) p.stdout.close() p.stdin.close() Try this and see if it makes any difference. Also make sure `command` is a string and not a list/touple, `shell=True` for whatever reason works better or only with strings. Also note that `shell=True` will get you hanged because it's insecure etc. Also skipping `.communicate()` you'll need to tap off `stdout` otherwise the buffer will get full and you might hang both yours and the child process. * * * _If this doesn't work, please provide more information. Such as the command used and the expected output (at least first few lines)_
Using GPXPY to parse gpx file results in not well-formed invalid token error Question: I have a few gpx files which I want to parse and then feed into a GIS format. I've downloaded [gpxpy](https://pypi.python.org/pypi/gpxpy/0.9.8) because I need some of its functions rather than just wanting to extract the lat and lon from the files. But when I make a parser import gpxpy p = gpxpy.parse(path_to_gpx_file) it gives me this: ERROR:root:not well-formed (invalid token): line 1, column 2 Traceback (most recent call last): File "C:\Python26\ArcGIS10.0\lib\site-packages\gpxpy\parser.py", line 196, in parse self.xml_parser = XMLParser(self.xml) File "C:\Python26\ArcGIS10.0\lib\site-packages\gpxpy\parser.py", line 43, in __init__ self.dom = mod_minidom.parseString(xml) File "C:\Python26\ArcGIS10.0\lib\xml\dom\minidom.py", line 1928, in parseString return expatbuilder.parseString(string) File "C:\Python26\ArcGIS10.0\lib\xml\dom\expatbuilder.py", line 940, in parseString return builder.parseString(string) File "C:\Python26\ArcGIS10.0\lib\xml\dom\expatbuilder.py", line 223, in parseString parser.Parse(string, True) ExpatError: not well-formed (invalid token): line 1, column 2 Traceback (most recent call last): File "<input>", line 1, in <module> File "C:\Python26\ArcGIS10.0\lib\site-packages\gpxpy\__init__.py", line 32, in parse return parser.parse() File "C:\Python26\ArcGIS10.0\lib\site-packages\gpxpy\parser.py", line 219, in parse raise mod_gpx.GPXXMLSyntaxException('Error parsing XML: %s' % str(e), e) GPXXMLSyntaxException: Error parsing XML: not well-formed (invalid token): line 1, column 2 After spending some time googling, this lead me to suspect that there are errors in the xml structure. However, I can't spot them. I've used <http://www.validome.org/xml/validate/> to validate the files but it says they're valid. This is what my gpx files look like. I've reduced this one to include only 3 trackpoints, but it's still giving me the same error as the full (35k lines)file. <?xml version="1.0" encoding="UTF-8" standalone="no" ?> <gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3" xmlns:wptx1="http://www.garmin.com/xmlschemas/WaypointExtension/v1" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" creator="Dakota 20" version="1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www8.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/WaypointExtension/v1 http://www8.garmin.com/xmlschemas/WaypointExtensionv1.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd"> <metadata> <link href="http://www.garmin.com"> <text>Garmin International</text> </link> <time>2015-03-01T16:59:53Z</time> </metadata> <trk> <name>SKI1</name> <extensions> <gpxx:TrackExtension></gpxx:TrackExtension> </extensions> <trkseg> <trkpt lat="43.3737357836" lon="130.0217922572"> <ele>166.26</ele> <time>2015-03-01T08:34:40Z</time> </trkpt> <trkpt lat="43.3737673834" lon="130.0218102783"> <ele>166.22</ele> <time>2015-03-01T08:34:42Z</time> </trkpt> <trkpt lat="43.3737869971" lon="130.0217925087"> <ele>166.78</ele> <time>2015-03-01T08:35:02Z</time> </trkpt> </trkseg> </trk> </gpx> EDIT maybe should add: using python 2.6, gpxpy 0.9.8, pycharm 3.1.1 Answer: It isn't really documented anywhere (in my opinion), so I'll post it here. Instead of letting the parser try to open the file, generate a file object first, and feed that to the parser, so: import gpxpy f = open(path_to_gpx_file, 'r') p = gpxpy.parse(f) I don't know why I didn't try that before...
Can I use SQL to split contents of a table column stored as CSV (comma seperated values) into individual rows in a new table? Question: I see there are a couple of related questions with answers, but not exactly what I need, so I'll ask a new question. I have this CSV file with thousands of rows of store inventories data which I'd like to import into a MS SQL Server database and use SQL to process them. After importing the CSV file, the SQL table will have three columns that contain CSV data. The problem is that I need to get this CSV data into individual rows in order to analyze it more. I'd like to end up with two tables in the end: the original table created by the import of the CSV file, and a table created by splitting out the CSV. Here is a representation of what the two tables would look like: /Table1 (the original CSV file). First row is column names: StoreID,Date,StoreName,City,State,Category1CSV,Category2CSV,Category3CSV 1051,2/16/2014,Easton,Columbus,OH,"Flour,Yeast,Baking Powder","Milk,Water,Oil","Cinnamon,Sugar" 1425,1/14/2014,Crocker Park,Westlake,OH,"Baking Powder,Yeast,Flour","Oil,Milk,Water","Rosemay,Cinnamon,Sugar" ![Table1](http://i.stack.imgur.com/5X54S.jpg) /Table2 (after splitting the CSV column contents). First row is column names: StoreID,Date,StoreName,City,State,ItemName,ItemRank,ItemCategory 1051,2/16/2014,Easton,Columbus,OH,Flour,1,1 1051,2/16/2014,Easton,Columbus,OH,Yeast,2,1 1051,2/16/2014,Easton,Columbus,OH,Baking Powder,3,1 1051,2/16/2014,Easton,Columbus,OH,Milk,4,2 1051,2/16/2014,Easton,Columbus,OH,Water,5,2 1051,2/16/2014,Easton,Columbus,OH,Oil,6,2 1051,2/16/2014,Easton,Columbus,OH,Cinnamon,7,3 1051,2/16/2014,Easton,Columbus,OH,Sugar,8,3 1425,1/14/2014,Crocker Park,Westlake,OH,Baking Powder,1,1 1425,1/14/2014,Crocker Park,Westlake,OH,Yeast,2,1 1425,1/14/2014,Crocker Park,Westlake,OH,Flour,3,1 1425,1/14/2014,Crocker Park,Westlake,OH,Oil,4,2 1425,1/14/2014,Crocker Park,Westlake,OH,Milk,5,2 1425,1/14/2014,Crocker Park,Westlake,OH,Water,6,2 1425,1/14/2014,Crocker Park,Westlake,OH,Rosemary,7,3 1425,1/14/2014,Crocker Park,Westlake,OH,Cinnamon,8,3 1425,1/14/2014,Crocker Park,Westlake,OH,Sugar,9,3 ![Table2](http://i.stack.imgur.com/5TGjB.jpg) The SQL column data types are: Table 1 StoreID - int Date - date StoreName - nvarchar(50) City- nvarchar(50) State- nvarchar(50) Category1CSV - nvarchar(MAX) Category2CSV - nvarchar(MAX) Category3CSV - nvarchar(MAX) Table2 StoreID - int Date - date StoreName - nvarchar(50) City- nvarchar(50) State - nvarchar(50) ItemName - nvarchar(50) ItemRank - tinyint ItemCategory -tinyint The Table 1 columns labeled Category1CSV, Category2CSV, and Category3CSV contents map to Table 2 columns: ItemName, ItemRank, ItemCategory, where ItemName is the Item (example: Flour), ItemRank is the order of the item in the CSV list, and ItemCategory is either 1,2 or 3, depending on whether the data came from Category1CSV, Category2CSV or Category3CSV. The most important aspect of this (other than splitting out the CSV column) is to maintain the order of items within the CSV columns. for example, StroreID 1051 has Category1CSV contents of "Flour,Yeast,Baking Powder". Those will map to the columns ItemName, ItemRank, and ItemCategory such that ItemName = Flour, it's ItemRank = 1, and the ItemCategory = 1. This would be the first row in Table 2. The second row would be ItemName = Yeast, it's ItemRank = 2, and the ItemCategory = 1, and so on until you end up with what looks like Table 2 above. Also, you'll notice that the ItemRank numbering starts with the contents of the column Category1CSV, then continues to Category2CSV and finally Category3CSV. After that lengthy explanation, is it possible to have some SQL statement that will create Table 2 from Table 1 for me? If so, what would that look like? I'm planning to use MS SQL Server Express 2012. OR... as someone suggest to me, it may be best to have some VBA in Excel or Python script (maybe in conjunction with Notepad++?) to accomplish this, then just import the final data? I don't care either way, I just can't keep manually editing the CSV file, as it's very tedious and time consuming. Thank you! Answer: I would use a Split function in order to split the additional values. The Split function I use uses a Numbers (a table with numbers 1 through 1,000,000) in order to facilitate the split process. Once the Numbers table and Split functions are in place, I would use the CROSS APPLY function to apply the Split to the CSV columns. the code to split the CSV column would look like this (this is just a couple test rows based on your data provided). DECLARE @Table TABLE (val1 VARCHAR(50), val2 VARCHAR(50), val3 VARCHAR(50), csv1 VARCHAR(100), csv2 VARCHAR(100), csv3 VARCHAR(100)) INSERT INTO @Table VALUES ('Easton', 'Columbus', 'OH', 'Flour,Yeast,Baking Powder','Milk,Water,Oil','Cinnamon,Sugar') , ('Crocker Park', 'Westlake', 'OH', 'Baking Powder,Yeast,Flour','Oil,Milk,Water','Rosemary,Cinnamon,Sugar') SELECT tbl.val1, val2, val3, apl.* FROM @Table tbl CROSS APPLY( SELECT val FROM dbo.Split(tbl.csv1, ',') ) apl UNION ALL SELECT tbl.val1, val2, val3, apl.* FROM @Table tbl CROSS APPLY( SELECT val FROM dbo.Split(tbl.csv2, ',') ) apl UNION ALL SELECT tbl.val1, val2, val3, apl.* FROM @Table tbl CROSS APPLY( SELECT val FROM dbo.Split(tbl.csv3, ',') ) apl ORDER BY val1 The output of which will look like this based on the sample date. Crocker Park Westlake OH Baking Powder Crocker Park Westlake OH Cinnamon Crocker Park Westlake OH Flour Crocker Park Westlake OH Milk Crocker Park Westlake OH Oil Crocker Park Westlake OH Rosemary Crocker Park Westlake OH Sugar Crocker Park Westlake OH Water Crocker Park Westlake OH Yeast Easton Columbus OH Baking Powder Easton Columbus OH Cinnamon Easton Columbus OH Flour Easton Columbus OH Milk Easton Columbus OH Oil Easton Columbus OH Sugar Easton Columbus OH Water Easton Columbus OH Yeast Here is the code to create the Numbers table DECLARE @tbl TABLE (n INT) INSERT INTO @tbl (n) VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10) ; WITH Num AS( SELECT one.n FROM @tbl one CROSS JOIN @tbl two CROSS JOIN @tbl three CROSS JOIN @tbl four CROSS JOIN @tbl five CROSS JOIN @tbl six ) SELECT ROW_NUMBER() OVER(ORDER BY n) AS n INTO dbo.Numbers FROM Num ALTER TABLE dbo.Numbers ALTER COLUMN n INT NOT NULL ALTER TABLE dbo.Numbers ADD PRIMARY KEY (n) GO Lastly, here is the code to create the Split function. CREATE FUNCTION dbo.Split ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT val = SUBSTRING(@List, n, CHARINDEX(@Delimiter, @List + @Delimiter, n) - n) FROM dbo.Numbers WHERE n <= CONVERT(INT, LEN(@List)) AND SUBSTRING(@Delimiter + @List, n, LEN(@Delimiter)) = @Delimiter ); GO
Python 3: Finding word which appears the most times without using import or counter or dictionary, only simple tools like .split() and .lower() Question: I am currently learning Python and trying to solve a free tutorial question. Here is the question. A writer is working on their newest poem, Turing and the Machines. They have hired you to determine the word which appears the most times. You can access the lines of the poem by calling input() repeatedly, and the last line contains the three characters ###. All lines consist of words separated by single spaces; there are no digits or punctuation. Convert all the words to lower-case, and print the word that occurs the most times (we guarantee there will not be a tie). For example, if the input is Here is a line like sparkling wine Line up fast or be the last # # # Then the output should be line since it appears twice and no other word appears twice. ..........Below is the closest thing to a solution I can get. It still lacks , among other things, the facility to allow a user to call input() repeatedly. And it only prints out the maximum number of the most used word , not the word itself that the question wants. The poem is supplied by the website shell , at <http://cscircles.cemc.uwaterloo.ca/15b-python-pushups/> Let's assume the user will input the poem one line at a time. Please help. Thanks a million. .......... def poem(P): P_lower = P.lower() P_split = P_lower.split() word_list = [] wordfreq = [] for i in P_split: word_list.append(i) for i in P_split: wordfreq.append(P_split.count(i)) print(max(wordfreq)) poem('Here is a line like line sparkling line wine') Answer: This doesn't use any of the "restricted" tools but only lower(), split() and sort() to return the word with the most occurrences. def main(): done = False P = "" while not done: new_line = input() if new_line != "###": P += new_line + " " else: done = True poem_words = P.lower().split() poem_words.sort() # Initialize variables temp = "" max_count = 0 icount = 1 max_word = "" # Do the loop for i in range(len(poem_words)): if temp == poem_words[i]: icount += 1 else: temp = poem_words[i] icount = 1 if icount > max_count: max_count = icount max_word = temp print(max_word) return if __name__ == "__main__": main()
Copy with Different Memory Address - Python Question: I made a class object I'll call Node. I want to make a copy of an instance of this object. Let's say the original is named "root" and the copy is to be named "start" If I do start = root. When I make any changes to start, it also changes root. This is because they share a memory address. How can I make start = root with different memory address? I tried messing around with copy/deepcopy after some searching but it tells me there is no such attribute. Is there an easy way to do this? Thanks! Answer: I've solved this problem using deepcopy from the lib copy. In my case I had other objects within the object I wanted to duplicate, so I had to use deepcopy otherwise just copy would have solved the problem. Take a look at the lib's documentation (<https://docs.python.org/2/library/copy.html>) Remember: import copy start = copy.deepcopy(root)
Python attribute button error Question: Hey guys im just trying to create a simple button gui (absolute n00b ) but i can seem to figure out whats wrong with my code: ``__author__ = 'Isaac' from Tkinter import * class Application(Frame): """ My smart board application""" def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): #Button1 self.button1 = Button(self, text = "Calandar") self.button1.grid() #button2 self.button2 = Button(self) self.button2.grid() self.button.configure(text = "Weather") root = Tk() root.title("Smartboard") root.geometry("500x400") app = Application(root) root.mainloop() the error im getting is: C:\Python27\python.exe "C:/Users/Isaac/Desktop/Useful python/Clanadar/GUIOOP.py" Traceback (most recent call last): File "C:/Users/Isaac/Desktop/Useful python/Clanadar/GUIOOP.py", line 25, in <module> app = Application(root) File "C:/Users/Isaac/Desktop/Useful python/Clanadar/GUIOOP.py", line 11, in __init__ self.create_widgets() File "C:/Users/Isaac/Desktop/Useful python/Clanadar/GUIOOP.py", line 20, in create_widgets self.button.configure(text = "Weather") AttributeError: Application instance has no attribute 'button' Process finished with exit code 1 thanks for your help Answer: Under your "#button2" comment;3 lines below, you used self.button.configure() However there is no variable called "button". I think you meant to say: self.button2.configure()
Fastest way to pack and unpack binary data into list Question: I am writing a script which will read 32 bytes of data from over thousands of files. The 32 bytes consists of 8 pairs of 16-bit integers and I want to unpack them to Python integers to build a list consisting of average numbers. I would then like to print out a hex string (packed the same way it was unpacked) of the list, along with the list object itself, to the user running the script. My current code looks like this, and it's slower than I'd like it to be (even considering the heavy I/O load): import os import sys import struct import binascii def list_str(list): return str(list) def list_s16be_hex(list): i = 0 bytes = b"" while i < len(list): bytes += struct.pack(">h", list[i]) i += 1 return binascii.hexlify(bytes).decode("ascii") def main(): averages = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] root = os.path.dirname(__file__) for dirpath, dirnames, filenames in os.walk(root): for filename in filenames: with open(os.path.join(dirpath, filename), "rb") as f: f.seek(0x10) tmp = f.read(32) i = 0 while i < 32: averages[i//2] = (averages[i//2] + struct.unpack(">h", tmp[i:i+2])[0]) // 2 i += 2 print("Updated averages (hex): " + list_s16be_hex(averages)) print("Updated averages (list): " + list_str(averages)) return 0 if __name__=="__main__": main() Is there a more efficient way of doing this? Answer: You can unpack all 16 integers at once, using `struct.unpack(">16h", tmp)`, which should be significantly faster for the computational part. Otherwise I'd expect your program runtime to be dominated by the I/O, which you can check by measuring it's runtime without the average computation. There is not so much you can do about the I/O.