text
stringlengths
226
34.5k
Ipython notebook caching issue Question: Within ipython notebook I call a function imported from my own module and run some code. I have noticed that if I change the code in the function (outside of notebook) and execute the notebook the old version of the function runs. Either ipython notebook or firefox seems to be caching the module which I can clear with ctrl-F5, when I remember. Is there an ipython notebook function call to ensure I am running the newest code? Answer: Put in the following two cells at the beggining of your code and it will automatically reload any new version of your code: %load_ext autoreload %autoreload 2 import ...
Run the same IPython notebook code on two different data files, and compare Question: Is there a good way to modularize and re-use code in IPython Notebook (Jupyter) when doing the same analysis on two different sets of data? For example, I have a notebook with a lot of cells doing analysis on a data file. I have another data file of the same format, and I'd like to run the same analysis and compare the output. None of these options looks particularly appealing for this: * **Copy and paste the cells to a second notebook.** The analysis code is now duplicated and harder to update. * **Move the analysis code into a module and run it for both files.** This would lose the cell-by-cell format of the figures that are currently generated and simply jumble them all together in one massive cell. * **Load both files in one notebook and run the analyses side by side**. This also involves a lot of copy-and-pasting, and doesn't generalize well to 3 or 4 different data files. Is there a better way to do this? Answer: You could lace demo directives into the standalone module, as per the [IPython Demo Mode example](https://ipython.org/ipython- doc/dev/api/generated/IPython.lib.demo.html#IPython.lib.demo.Demo). Then when actually executing it in the notebook, you make a call to the demo object wrapper each time you want to step to the next important part. So your cells would mostly consist of calls to that demo wrapper object. Option 2 is clearly the best for code re-use, it is the de facto standard arguably in all of software engineering. I argue that the notebook concept itself doesn't scale well to 3, 4, 5, ... different data files. Notebook presentations are not meant to be batch processing receptacles. If you find yourself needing to do parameter sweeps across different data sets, and wanting to re-run analyses on top of the different data loaded for each parameter group (even when the 'parameters' might be as simple as different file names) it raises a bad code smell. It likely means the level of analysis being performed in an 'interactive' way is wrong. Witnessing analysis 'interactively' and at the same time performing batch processing are two pretty much incompatible goals. A much better idea would be to batch process all of the parameter sets separately, 'offline' from the point of view of any presentation, and then build a set of stand-alone functions that can produce visual results from the computed and stored batch results. Then the notebook will just be a series of function calls, each of which produces summary data (some of which could be examples from a selection of parameter sets during batch processing) across all of the parameter sets at once to invite the necessary comparisons and meaningfully present the result data side-by-side. 'Witnessing' an entire interactive presentation that performs analysis on one parameter set, then changing some global variable / switching to a new notebook / running more cells in the same notebook in order to 'witness' the same presentation on a different parameter set sounds borderline useless to me, in the sense that I cannot imagine a situation where that mode of consuming the presentation is not strictly worse than consuming a targeted summary presentation that first computed results for all parameter sets of interest and assembled important results into a comparison. Perhaps the only case I can think of would be toy pedagogical demos, like some toy frequency data and a series of notebooks that do some simple Fourier analysis or something. But that's exactly the kind of case that begs for the analysis functions to be made into a helper module, and the notebook itself just lets you selectively declare which toy input file you want to run the notebook on top of.
Get data structure of all tests found by Nose Question: How would I get some sort of data structure containing a list of all tests found by Nose? I came across this: [List all Tests Found by Nosetest](http://stackoverflow.com/questions/712020/list-all-tests-found-by- nosetest) I'm looking for a way to get a list of unit test names in a python script of my own (along with the location or dotted location). Answer: There are several ways to achieve that: one is run nose with xunit plugin with `--collect-only` and parse the resulting junit xml file. Alternatively, you can add a basic plugin that captures names of the tests, something like this: import sys from unittest import TestCase import nose from nose.tools import set_trace class CollectPlugin(object): enabled = True name = "test-collector" score = 100 def options(self, parser, env): pass def configure(self, options, conf): self.tests = [] def startTest(self, test): self.tests.append(test) class MyTestCase(TestCase): def test_long_integration(self): pass def test_end_to_end_something(self): pass if __name__ == '__main__': # this code will run just this file, change module_name to something # else to make it work for folder structure, etc module_name = sys.modules[__name__].__file__ plugin = CollectPlugin() result = nose.run(argv=[sys.argv[0], module_name, '--collect-only', ], addplugins=[plugin],) for test in plugin.tests: print test.id() Your test information is all captured in `plugin.test` structure.
Running Python in a command prompt Question: I have some python code that I want to run from the cmd prompt, but it's not working, my partner told me if I had this statement in my code: if __name__ == '__main__': xs, a0, a1, y0, y1, ys = encode(sys.argv[1]) np.set_printoptions(precision=6, suppress=True) then it should be able to be run. I'll post my entire code and my command prompt errors to see if you guys can help ![enter image description here](http://i.stack.imgur.com/33Yhh.jpg) import random import numpy as np import sys import pprint from numpy import linalg as LA #Takes in a n value def encode(n): xA0 = np.zeros((n+3,1)) xA1 = np.zeros((n+3,1)) xStream = np.zeros((n+3,1)) #Creates a random x for i in range(0, n): xStream[i,0] = random.randint(0,1) #Creates A0 and A1 based on size xA0[0,0] = 1 xA0[2,0] = 1 xA0[3,0] = 1 xA1[0,0] = 1 xA1[1,0] = 1 xA1[3,0] = 1 A0 = np.zeros((n+3,n+3)) A1 = np.zeros((n+3,n+3)) y0 = np.zeros((n+3,1)) y1 = np.zeros((n+3,1)) yStream = [] #Creates A0 and A1 using method defined in description for i in range(0,n+3): for k in range (0,i+1): A0[i,k] = xA0[i-k,0] A1[i,k] = xA1[i-k,0] #A0*x and A1*x to get y0 and y1 for i in range(0,n+3): y0[i,0] = np.dot(A0[i,:], xStream) y1[i,0] = np.dot(A1[i,:], xStream) #answers mod 2 to get real answers for i in range(0,n+3): y0[i,0] = y0[i,0]%2 y1[i,0] = y1[i,0]%2 #combined for yStream for i in range(0,n+3): yStream.append([y0[i,0],y1[i,0]]) print("x:") print(xStream) print("\n") print("A0:") print(A0) print("\n") print("A1:") print(A1) print("\n") print("y0:") print(y0) print("\n") print("y1:") print(y1) print("\n") print("yStream:") print(yStream) return xStream, A0, A1, y0, y1, yStream # This is only or when encode is used as a stand-alone module # Read command line argument. Must be exactly one argument. # It outputs on the console if __name__ == '__main__': xs, a0, a1, y0, y1, ys = encode(sys.argv[1]) np.set_printoptions(precision=6, suppress=True) print("x:") print(xs) print("\n") print("A0:") print(a0) print("\n") print("A1:") print(a1) print("\n") print("y0:") print(y0) print("\n") print("y1:") print(y1) print("\n") print("yStream:") print(ys) Answer: Since you have installed into D:\Python, copy the following into an editor and save it as a bat file (say `runpython.bat`) then run it (EDITED with thanks to @eryksun) Assumes Python 2: @SET PATH=%PATH%;D:\Python;D:\Python\Scripts @ASSOC .py=Python.File @ASSOC .pyc=Python.CompiledFile @ASSOC .pyo=Python.CompiledFile @ASSOC .pyw=Python.NoConFile @FTYPE Python.CompiledFile="D:\Python\python.exe" "%%1" %%* @FTYPE Python.File="D:\Python\python.exe" "%%1" %%* @FTYPE Python.NoConFile="D:\Python\pythonw.exe" "%%1" %%* @SET PATHEXT=%PATHEXT%;.py You should now be able to run python programs from the command-line
Print variable in large font in python figure Question: I have borrowed some code from another source and I want to edit the figure produced. Here is the relevant (i think) code from the script. import gtk #the gui toolkit we'll use: from matplotlib.figure import Figure from Tkinter import * from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas #create a window to put the plot in win = gtk.Window() #connect the destroy signal (clicking the x in the corner) win.connect("destroy", quit_app) win.set_default_size(600,500) #create a plot: fig = Figure() ax = fig.add_subplot(111,xlabel='Time Step', ylabel='Temp (deg C)', axisbg='black') ax.set_ylim(0,100) # set limits of y axis. canvas = FigureCanvas(fig) #put the plot onto a canvas win.add(canvas) #put the canvas in the window #show the window win.show_all() win.set_title("ready to receive data"); line, = ax.plot(times,yvals, color='red') while(1): line.set_ydata(yvals) # draw the line fig.canvas.draw() # update the Canvas win.set_title("Temp: "+str(yvals[49])+" deg C") I don't know whether or not all the code above is necessary - but that is all the 'plot' related code I could find. So anyway the code works in my program perfectly. There are TWO tasks I would like to create: (1) What I want is to include that 'str(yvals[49])' variable, which is currently being displayed in the title of the window, to be displayed in large font underneath the plot. So I think I need to make the window size a little bigger to accompany the text but not sure how to print it. (2) I manged to change the background of the plot itself to black that plots a red line. But how can I change the background of the window itself to all black and the x/y axis to red as well. Thanks!! Answer: (1) What you are most probably looking for it the matplotlib text command. Have a look at <http://matplotlib.org/users/pyplot_tutorial.html> section working with text. It might be convenient to create two separate axes, so you can truly put the text below the whole figure. Maybe it is enough to place the text at xlabel position? import matplotlib.pyplot as plt plt.xlabel('yourtext') (2) There are already good answers out there that might help you: e.g. [How to change the pylab window background color?](http://stackoverflow.com/questions/16896341/how-to-change-the-pylab- window-background-color) As for the color of the axis [Changing the color of the axis, ticks and labels for a plot in matplotlib](http://stackoverflow.com/questions/4761623/changing-the-color-of- the-axis-ticks-and-labels-for-a-plot-in-matplotlib) Have also a look at [Matplotlib figure facecolor (background color)](http://stackoverflow.com/questions/4804005/matplotlib-figure- facecolor-background-color) in case you want to save the figure.
How to hide console window using python esky 0.9.8? Question: I currently have an exe that I created using python bundled up with the esky package(<https://pypi.python.org/pypi/esky>). My setup file looks like this setup(name='pythonApp', version = "0.1", scripts=[pythonAppEXE], options = {'bdist_esky':{ 'freezer_module': 'py2exe', },}, ) Now i know that in py2exe you can use windows=[pythonAppEXE] instead of scripts=[pythonAppEXE], but unfortunately I cannot replace scripts=[pythonAppEXE] when using esky. So how can I create an exe that doesn't have a console? Answer: from esky.bdist_esky import Executable executables = [Executable('hi.py', icon='stack.ico', gui_only=True)] setup(name="hellow world", version = '0.1', scripts = executables)
IntegrityError at /accounts/signup/ in django Question: I have just deployed my django site using apache on an ubuntu 14.04 server. The site is being accessed. But when i signup as a user into it, it creates the user but is unable to create the user profile which is in a one to one relationship with myuser. Also, I am using a custom user model. the error it throws on signup is: Cannot add or update a child row: a foreign key constraint fails (`ilog_prod_db`.`myuserprofile_myuserprofile`, CONSTRAINT `myuserprofile_myuserp_myuser_id_6ad6f704425ed359_fk_auth_user_id` FOREIGN KEY (`myuser_id`) REFERENCES `auth_user` (`id`)) The point is that, on my dev machine(windows7), the website is working perfectly fine with the same code. Also, the settings of database is exactly the same, ie in both places i have used InnoDB as the database engine for the database. What can be the problem. Any pointers would be appreciated. Thanks. Traceback: Environment: Request Method: POST Request URL: http://www.industrylogger.com/accounts/signup/ Django Version: 1.7.2 Python Version: 3.4.0 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'enterprise', 'accounts', 'nodes', 'message', 'myuserprofile', 'enterprise_profile', 'activities', 'search', 'imagekit') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback: File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 111. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sp/webapps/ilog_dev/accounts/views.py" in signup 24. password=password,) File "/home/sp/webapps/ilog_dev/accounts/models.py" in create_myuser 93. user.save(using=self._db) File "/home/sp/webapps/ilog_dev/accounts/models.py" in save 152. super(MyUser, self).save(*args, **kwargs) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/models/base.py" in save 589. force_update=force_update, update_fields=update_fields) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/models/base.py" in save_base 626. update_fields=update_fields, raw=raw, using=using) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/dispatch/dispatcher.py" in send 198. response = receiver(signal=self, sender=sender, **named) File "/home/sp/webapps/ilog_dev/myuserprofile/models.py" in create_user_profile 121. MyUserProfile.objects.create(myuser=instance) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/models/manager.py" in manager_method 92. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/models/query.py" in create 372. obj.save(force_insert=True, using=self.db) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/models/base.py" in save 589. force_update=force_update, update_fields=update_fields) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/models/base.py" in save_base 617. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/models/base.py" in _save_table 698. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/models/base.py" in _do_insert 731. using=using, raw=raw) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/models/manager.py" in manager_method 92. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/models/query.py" in _insert 921. return query.get_compiler(using=using).execute_sql(return_id) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in execute_sql 920. cursor.execute(sql, params) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute 81. return super(CursorDebugWrapper, self).execute(sql, params) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute 65. return self.cursor.execute(sql, params) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/mysql/connector/django/base.py" in execute 135. return self._execute_wrapper(self.cursor.execute, query, args) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/mysql/connector/django/base.py" in _execute_wrapper 121. utils.IntegrityError(err.msg), sys.exc_info()[2]) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/django/utils/six.py" in reraise 658. raise value.with_traceback(tb) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/mysql/connector/django/base.py" in _execute_wrapper 115. return method(query, args) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/mysql/connector/cursor.py" in execute 507. self._handle_result(self._connection.cmd_query(stmt)) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/mysql/connector/connection.py" in cmd_query 722. result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "/home/sp/webapps/myenv/lib/python3.4/site-packages/mysql/connector/connection.py" in _handle_result 640. raise errors.get_exception(packet) Exception Type: IntegrityError at /accounts/signup/ Exception Value: Cannot add or update a child row: a foreign key constraint fails (`ilog_prod_db`.`myuserprofile_myuserprofile`, CONSTRAINT `myuserprofile_myuserp_myuser_id_6ad6f704425ed359_fk_auth_user_id` FOREIGN KEY (`myuser_id`) REFERENCES `auth_user` (`id`)) Answer: From the comments on the question, it looks like your django model and database schema are out of sync. If you can, just delete the database and recreate. If you have important data in there... **First make a backup of your production database** Depending on which version of django you're using, database synchronisation behaves differently. ### Django <= 1.6 The `python manage.py syncdb` command can be used to add any missing schema information to your database. If your problem stems from the fact that you've added new tables or fields to your model / that constraints have been deleted, this might fix the schema. It will not remove any old fields or migrate any data, so there's a good chance you'll need to do some manual editing afterwards. ### Django >= 1.7 1.7 introduced the new `python manage.py migrate` ([Docs](https://docs.djangoproject.com/en/1.7/topics/migrations/)) command which is more intelligent. As your model changes, migrations are created. When an old database needs to be brought inline with a new model, the migrations are applied to the database. This is far more flexible and allows database versions to be upgraded/downgraded as required. The downside is that you need to have made migrations as you go (or create them manually afterwards). See the documentation for more information In either case, if the model is too far out of sync or you don't have the appropriate migrations, you're going to need to do some manual work to get the data into the state required by django.
How to merge .csv files to do a matrix Question: I have two different .csv files (a and b), containing several array organized like this : File a : [a, b, c, d] [e, f, g, h] [i, j, k, l] File b : [o, p, q, r] [s, t, u, v] [w, x, y, z] I want to merge these to files to get only on file (c), that would look like : [a, b, c, d, o, p, q, r] [e, f, g, h, s, t, u, v] [i, j, k, l, w, x, y, z] Any ideas how I could do this? I'm running Python 2.7 (matplotlib, openelectrophy). Answer: With python's csv reader and writer, reading from the files `a.csv` and `b.csv`, writing to `c.csv`: # -*- coding: utf-8 -*- import csv with open('a.csv', 'r') as file_a: with open('b.csv', 'r') as file_b: with open('c.csv', 'w') as file_c: reader_a = csv.reader(file_a, delimiter=',') reader_b = csv.reader(file_b, delimiter=',') writer_c = csv.writer(file_c) for cols_a in reader_a: cols_b = reader_b.next() writer_c.writerow(cols_a + cols_b) Creates file `c.csv`: a, b, c, d,o, p, q, r e, f, g, h,s, t, u, v i, j, k, l,w, x, y, z (I assume that those braces and extra linebreaks in your csv code are just here on stackoverflow and not really part of your csv files? I also assume that a.csv and b.csv have the same length in lines.)
How to detect end of picture download in AsyncImage in Kivy? Question: i'm writting a simple appliaction like this one: #!/usr/bin/env python2.7 # -*- coding: utf-8 -*- from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.image import AsyncImage class Application(App): def build(self): box_layout = BoxLayout(orientation='vertical') img = AsyncImage( source='http://pl.python.org/forum/Smileys/default/cheesy.gif') box_layout.add_widget(img) return box_layout def __on_image_loaded(self): print('Very importatn stuff executed afer image has been downloaded by img widget.') app = Application() app.run() How can I detect that AsyncImage widget ended downloading picture from given URL? Alternatively I can write downloading thread by myself and use Image widget but in this case what could I do to load raw bytes from memory to Image widget to display them as a picture? Answer: You can use `img._coreimage.bind(on_load=self.on_image_loaded)`: #!/usr/bin/env python2.7 # -*- coding: utf-8 -*- from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.image import AsyncImage class Application(App): def build(self): box_layout = BoxLayout(orientation='vertical') img = AsyncImage(source='http://pl.python.org/forum/Smileys/default/cheesy.gif') img._coreimage.bind(on_load=self.on_image_loaded) box_layout.add_widget(img) return box_layout def on_image_loaded(self, *args): print('Very importatn stuff executed afer image has been downloaded by img widget.') app = Application() app.run()
How to convert a command output from a string to an integer? Question: I have a script that uses the `time` module in Python to get the current time in hours, minutes and seconds and store them in three different variables: import time while True: A = time.strftime("%H") B = time.strftime("%M") C = time.strftime("%S") I want to be able to do some math with these numbers, but they are always interpreted as strings. A = "07" B = "58" C = "27" How can I convert the string output of the command into a number that I can do math with? Whenever I try to multiply them like they are numbers I get outputs like `"70707070707070707070707"`. Answer: import time while True: A = int(time.strftime("%H")) B = int(time.strftime("%M")) C = int(time.strftime("%S")) # K=A*2+B*3+C*4
python math domain error - sqrt Question: What causes the problem? from math import sqrt print "a : " a = float(raw_input()) print "b : " b = float(raw_input()) print "c : " c = float(raw_input()) d = (a + b + c)/2 s = sqrt(d*(d-a)*(d-b)*(d-c)) print "a+b+c =", a, b, c print "Distr. =", d*2, "Area =", s Error: Traceback (most recent call last): File "C:/Python27/fájlok/háromszög terület2.py", line 11, in <module> s = sqrt(d*(d-a)*(d-b)*(d-c)) ValueError: math domain error Answer: The problem is that the [Heron's formula](http://en.wikipedia.org/wiki/Heron%27s_formula) holds good only when the sum of the two numbers are greater than the third. You need to check that explicitly. A better way as you are using a code to do that is by using _Exception handling_ try: s = sqrt(d*(d-a)*(d-b)*(d-c)) print "a+b+c =", a, b, c print "Distr. =", d*2, "Area =", s except ValueError: print "Please enter 3 valid sides" If you want to do it without `try` block you can do it as delta = (d*(d-a)*(d-b)*(d-c)) if delta>0: s = sqrt(delta) print "a+b+c =", a, b, c print "Distr. =", d*2, "Area =", s else: print "Please enter 3 valid sides"
Lists as values in a dictionary Python Question: ddic = {'a': 10,'b': 23,'c': [0, 1, 2]} n2 = ddic['c'] n2[-2] = 1000. ddic {'a': 10, 'b': 23, 'c': [0, 1000.0, 2]} Why changing the list at which n2 is pointing, changes also the list of dict ddic, which is contained into the hash table that ddic defines? It looks like that when you define a dict, the key-value pairs pops-in the global namespace and is not contained into the namespace defined by the hash- table structure. Someone knows the detailed reason of this? Answer: Few prenotes * Dict keys are immutable whereas values are mutable. * When you use `=`, the new variable just references the old list The value at key `c` is a list. It is pointed to by the key at that place. On copying to a variable, the reference is passed. This can be confirmed by using `id`. >>> id(ddic['c']) 140726603094424 >>> id(n2) 140726603094424 As you see both the variables are pointing to the same element in memory. Hence any changes you make in one are reflected to the original one also. To have a shallow copy of the list you can use `[:]` [as mentioned by Blckknght](http://stackoverflow.com/questions/29376270/lists-as-values-in-a- dictionary-pyython/29376334?noredirect=1#comment46933296_29376334) >>> n2 = ddic['c'][:] In python3, you can use (as mentioned by [Padraic](http://stackoverflow.com/questions/29376270/lists-as-values-in-a- dictionary-pyython/29376334?noredirect=1#comment46933664_29376334)) >>> n2 = ddic['c'].copy() Using `copy` module, you can prevent this from happening as in >>> import copy >>> n2 = copy.copy(ddic['c']) >>> id(ddic['c']) 140726603094424 >>> id(n2) 140726603177640 Reference * [`id`](https://docs.python.org/2/library/functions.html#id) * [`copy`](https://docs.python.org/2/library/copy.html) Also note that as mentioned by [Kasra](http://stackoverflow.com/questions/29376270/lists-as-values-in-a- dictionary-pyython/29376334?noredirect=1#comment46933178_29376334) in the comments, dicts don't have as separate space for them as they are data structures. You can find refernce in [this](http://svn.python.org/view/python/trunk/Objects/dictobject.c?view=markup) document
Index error - Python, Numpy, MatLab Question: I have converted a section of MatLab code to Python using the numpy and scipy libraries. I am however stuck on the following index error; IndexError: index 698 is out of bounds for axis 3 with size 2 698 is the size of the time list. it occurs in the last section of code, on this line; exp_Pes[indx,jndx,j,i]=np.trace(rhotemp[:,:,indx,jndx] * Pe) the rest is included for completeness. the following is the code; import numpy as np import math import time #from scipy.linalg import expm tic = time.clock() dt = 1e-2; # time step t = np.arange(0, 7-dt, dt) # t gam=1 mt=2 nt=2 delta=1 ensemble_size=6 RKflag=0 itype = 'em' #======================================================================== def _min(x): return [np.amin(x), np.argmin(x)] #======================================================================== ############### #Wavepacket envelope #rising exponential sig1 = 1; xi_t = np.zeros(len(t)); [min_dif, array_pos_start] = _min(abs(t -t[0] )); [min_dif, array_pos_stop ] = _min(abs(t -t[-1]/2.0)); step = t[1]-t[0] p_len = np.arange(0, t[array_pos_stop] - t[array_pos_start] + step, step) xi_t[array_pos_start:array_pos_stop+1] = math.sqrt(sig1) * np.exp((sig1/2.0)*p_len); norm = np.trapz(t, xi_t * np.conj(xi_t)); xi = xi_t/np.sqrt(abs(norm)); #Pauli matrices #======================== Pe=np.array([[1,0],[0,0]]) Sm=np.array([[0,0],[1,0]]) Sz=np.array([[1,0],[0,- 1]]) Sy=np.array([[0,- 1j],[1j,0]]) Sx=np.array([[0,1],[1,0]]) #S,L,H coefficients #========================= S=np.eye(2) L=np.sqrt(gam) * Sm H=np.eye(2) #========================= psi=np.array([[0],[1]]) rhoi=psi * psi.T #rho=np.zeros(2,2,2,2) rho=np.zeros((2,2,2,2)) rhotot=np.copy(rho) rhoblank=np.copy(rho) rhos=np.copy(rho) rhotots=np.copy(rho) rhon=np.copy(rho) rhototN=np.copy(rho) rhov=np.copy(rhoi) exp_Pes=np.zeros((2,2,2,2)) exp_Pes2=np.zeros((2,2,2,2)) #initial conditions into rho #================== rho[:,:,0,0]=rhoi #rho[:,:,2,2]=rhoi rhosi=np.copy(rho) num_bad=0 avg_val=0 num_badRK=0 avg_valRK=0 #np.zeros(len(t)); exp_Sz=np.zeros((2,2,len(t))) exp_Sy=np.copy(exp_Sz) exp_Sx=np.copy(exp_Sz) exp_Pe=np.copy(exp_Sz) ##########################3 #functions #======================================================================== #D[X]rho = X*rho* ctranspose(X) -0.5*(ctranspose(X)*X*rho + rho*ctranspose(X)*X) # # To call write curlyD(X,rho) def curlyD(X,rho,nargout=1): y=X * rho * X.conj().T - 0.5 * (X.conj().T * X * rho + rho * X.conj().T * X) return y #======================================================================== def curlyC(A,B,nargout=1): y=A * B - B * A return y #======================================================================== def calc_expect(rhotots,Pe,nargout=1): for indx in (1,2): for jndx in (1,2): exp_Pes[indx,jndx]=np.trace(rhotots[:,:,indx,jndx] * Pe) exp_Pes2[indx,jndx]=np.trace(rhotots[:,:,indx,jndx] * Pe) ** 2 return exp_Pes,exp_Pes2 #======================================================================== #======================================================================== #======================================================================== #======================================================================== #======================================================================== def single_photon_liouvillian(S,L,H,rho,xi,nargout=1): rhotot[:,:,1,1]=curlyD(L,rho[:,:,1,1]) + xi * curlyC(S * rho[:,:,0,1],L.T) + xi.T * curlyC(L,rho[:,:,1,0] * S.T) + xi.T * xi * (S * rho[:,:,0,0] * S.T - rho[:,:,0,0]) rhotot[:,:,1,0]=curlyD(L,rho[:,:,1,0]) + xi * curlyC(S * rho[:,:,0,0],L.T) rhotot[:,:,0,1]=curlyD(L,rho[:,:,0,1]) + xi.T * curlyC(L,rho[:,:,0,0] * S.T) rhotot[:,:,0,0]=curlyD(L,rho[:,:,0,0]) A=np.copy(rhotot) return A #======================================================================== def single_photon_stochastic(S,L,H,rho,xi,nargout=1): K=np.trace((L + L.T) * rho[:,:,1,1]) + np.trace(S * rho[:,:,0,1]) * xi + np.trace(S.T * rho[:,:,1,0]) * xi.T rhotot[:,:,1,1]=(L * rho[:,:,1,1] + rho[:,:,1,1] * L.T + S * rho[:,:,0,1] * xi + rho[:,:,1,0] * S.T * xi.T - K * rho[:,:,1,1]) rhotot[:,:,1,0]=(L * rho[:,:,1,0] + rho[:,:,1,0] * L.T + S * rho[:,:,0,0] * xi - K * rho[:,:,1,0]) rhotot[:,:,0,1]=(L * rho[:,:,0,1] + rho[:,:,0,1] * L.T + rho[:,:,0,0] * S.T * xi.T - K * rho[:,:,0,1]) rhotot[:,:,0,0]=(L * rho[:,:,0,0] + rho[:,:,0,0] * L.T - K * rho[:,:,0,0]) B=np.copy(rhotot) return B #======================================================================== def sde_int_io2_rk(a,b,S,L,H,yn,xi,dt,dW,nargout=1): Gn=yn + a[S,L,H,yn,xi] * dt + b[S,L,H,yn,xi] * dW Gnp=yn + a[S,L,H,yn,xi] * dt + b[S,L,H,yn,xi] * np.sqrt(dt) Gnm=yn + a[S,L,H,yn,xi] * dt - b[S,L,H,yn,xi] * np.sqrt(dt) ynp1=yn + 0.5 * (a[S,L,H,Gn,xi] + a[S,L,H,yn,xi]) * dt + 0.25 * (b[S,L,H,Gnp,xi] + b[S,L,H,Gnm,xi] + 2 * b[S,L,H,yn,xi]) * dW + 0.25 * (b[S,L,H,Gnp,xi] - b[S,L,H,Gnm,xi]) * (dW ** 2 - dt) * (dt) ** (- 0.5) return ynp1 #======================================================================== #======================================================================== def sde_int_photon(itype,rhos,S,L,H,Pe,xi,t,nargout=1): dt=t[1] - t[0] rhoblank=np.zeros(len(rhos)) Ax=single_photon_liouvillian Bx=single_photon_stochastic #if strcmp(itype,'em'): if itype == 'em': for i in (1,(len(t)-1)): if i == 1: exp_Pes[:,:,i],exp_Pes2[:,:,i]=calc_expect(rhos,Pe,nargout=2) continue dW=np.sqrt(dt) * np.randn rhotots=rhos + dt * single_photon_liouvillian(S,L,H,rhos,xi[i]) + dW * single_photon_stochastic(S,L,H,rhos,xi[i]) exp_Pes[:,:,i],exp_Pes2[:,:,i]=calc_expect(rhotots,Pe,nargout=2) rhos=np.copy(rhotots) rhotots=np.copy(rhoblank) if itype == 'rk': for i in (1,(len(t)-1)): if i == 1: exp_Pes[:,:,i],exp_Pes2[:,:,i]=calc_expect(rhos,Pe,nargout=2) continue dW=np.sqrt(dt) * np.randn rhotots=sde_int_io2_rk(Ax,Bx,S,L,H,rhos,xi[i],dt,dW) exp_Pes[:,:,i],exp_Pes2[:,:,i]=calc_expect(rhotots,Pe,nargout=2) rhos=np.copy(rhotots) rhotots=np.copy(rhoblank) return exp_Pes,exp_Pes2 #======================================================================== """ def md_expm(Ain,nargout=1): Aout=np.zeros(len(Ain)) r,c,d1,d2=len(Ain,nargout=4) for indx in (1,d1): for jndx in (1,d2): Aout[:,:,indx,jndx]=expm(Ain[:,:,indx,jndx]) return Aout """ #======================================================================== #======================================================================== Ax=single_photon_liouvillian Bx=single_photon_stochastic toc = time.clock() for indx in (1,range(mt)): for jndx in (1,range(nt)): exp_Sz[indx,jndx,1]=np.trace(rho[:,:,indx,jndx] * Sz) exp_Sy[indx,jndx,1]=np.trace(rho[:,:,indx,jndx] * Sy) exp_Sx[indx,jndx,1]=np.trace(rho[:,:,indx,jndx] * Sx) exp_Pe[indx,jndx,1]=np.trace(rho[:,:,indx,jndx] * Pe) for i in (2,len(t)-1): #Master equation rhotot=rho + dt * single_photon_liouvillian(S,L,H,rho,xi[i - 1]) for indx in (1,range(mt)): for jndx in (1,range(nt)): exp_Sz[indx,jndx,i]=np.trace(rhotot[:,:,indx,jndx] * Sz) exp_Sy[indx,jndx,i]=np.trace(rhotot[:,:,indx,jndx] * Sy) exp_Sx[indx,jndx,i]=np.trace(rhotot[:,:,indx,jndx] * Sx) exp_Pe[indx,jndx,i]=np.trace(rhotot[:,:,indx,jndx] * Pe) rho=np.copy(rhotot) rhotot=np.copy(rhoblank) for j in (1,range(ensemble_size)): psi1=np.array([[0],[1]]) rho1=psi1 * psi1.T rhotemp = np.zeros((2,2,2,2)) rhotemp[:,:,0,0]=rho1 rhotemp[:,:,1,1]=rho1 rhos=np.copy(rhotemp) for indx in (1,range(2)): for jndx in (1,range(2)): exp_Pes[indx,jndx,j,i]=np.trace(rhotemp[:,:,indx,jndx] * Pe) exp_Pes2[indx,jndx,j,i]=np.trace(rhotemp[:,:,indx,jndx] * Pe) ** 2 for i in (2,(len(t)-1)): dW=np.sqrt(dt) * np.random.randn() rhotots=rhos + dt * single_photon_liouvillian(S,L,H,rhos,xi[i - 1]) + dW * single_photon_stochastic(S,L,H,rhos,xi[i - 1]) for indx in (1,range(mt)): for jndx in (1,range(nt)): exp_Pes[indx,jndx,j,i]=np.trace(rhotots[:,:,indx,jndx] * Pe) exp_Pes2[indx,jndx,j,i]=np.trace(rhotots[:,:,indx,jndx] * Pe) ** 2 rhos=np.copy(rhotots) rhotots=np.copy(rhoblank) Irow=np.where(np.squeeze(exp_Pes[2,2,j,:]) > 1) Val=np.squeeze(exp_Pes[2,2,j,Irow]) if Irow: num_bad=num_bad + 1 avg_val=avg_val + max(Val) Any help would be appreciated as I have been stuck on this for a while. Thanks! Answer: The problem is that you are not defining `i` in the loop. `i` is being left over from the last time it was used. Specifically, it is using the last value of `i` from the previous loop. This value is `len(t)-1`, which is much larger than the length of the 3rd dimension of `exp_Pes` which has a length of 2. You need to define a valid value for `i` somewhere. If you don't want to loop over `i`, generally you could just define it once before the loop starts. In your case, however, you would need to set it every time you loop since it is also being defined inside this loop a few lines below the one causing the error. However, it would probably be clearer to just do something like `exp_Pes[indx,jndx,j,0] = ...`, since people reading your code won't need to look back and find what value `i` was set to. A couple more minor points of advice: `np.arange` does not include the last value. So the case where you use `7-dt` at the beginning, you are ending up with the start being `0` and the end being `7-dt-dt`, which is probably not what you want. But anyway, you should never use `np.arange` (or the equivalent in MATLAB) with floats, since it can have floating-point errors. Use `np.linspace` instead. Second, for your `_min` function, you don't need `[]`, you can just do `return np.amin(x), np.argmin(x)`. However, it is usually easier for arrays to use the method version, which is the version attached to the array. This would be `return x.min(), x.argmin()`. Same with `np.copy(rho)`, use `rho.copy()` instead. However, this function could be further simplified to a `lambda` expression, the equivalent of a Matlab anonymous function, like so: `_min = lambda x: [x.min(), x.argmin()]` (you do need the `[]` there). You should use the `numpy` version of functions with `numpy` arrays. They will be faster. So `np.abs(t-t[0])` is faster than `abs(t-t[0])`. Same with using `np.sqrt(sig1)` instead of `math.sqrt(sig1)`. You also don't need the `[] in returned values, so`[min_dif, array_pos_start] = _min(abs(t -t[0] ))`can be`min_dif, array_pos_start = _min(np.abs(t-t[0])). However, since you are never actually using `min_dif`, this could just be `array_pos_start = np.abs(t-t[0]).argmax()`. You don't need to end lines with `;`. You don't need to assign to a variable before returning. So you can just have, for example, `return A*B-B*A`. You seem to unnecessarily use the `nargout` argument. Python doesn't use this, in large part because you can just index the results So say you have a function `foo(x)` that returns the min and max of `x`. You can just want the max, you can do `foo(x)[1]`. Matlab doesn't let you do that, so it relies on `nargout` to work around it.
Executing a script in selenium python Question: I am trying to execute this script in selenium. <div class="vbseo_liked"> <a href="http://www.jamiiforums.com/member.php?u=8355" rel="nofollow">Nyaralego</a> , <a href="http://www.jamiiforums.com/member.php?u=8870" rel="nofollow">Sikonge</a> , <a href="http://www.jamiiforums.com/member.php?u=8979" rel="nofollow">Ab-Titchaz</a> and <a onclick="return vbseoui.others_click(this)" href="http://www.jamiiforums.com/kenyan-news/225589-kenyan-and-tanzanian-surburbs.html#">11 others</a> like this. </div> This is my code to execute it. browser.execute_script("document.getElement(By.xpath(\"//div[@class='vbseo_liked']/a[contains(@onclick, 'return vbseoui.others_click(this)')]\").click()") It didn't work. What am i doing wrong? Answer: Find the element with selenium and pass it to [`execute_script()`](http://selenium- python.readthedocs.org/en/latest/api.html#selenium.webdriver.remote.webdriver.WebDriver.execute_script) to click: link = browser.find_element_by_xpath('//div[@class="vbseo_liked"]/a[contains(@onclick, "return vbseoui.others_click(this)")]') browser.execute_script('arguments[0].click();', link) * * * Since I know the context of the problem, here is the set of things for you to do to solve it: * click on the "11 others" link via javascript relying on the solution provided here: [How to simulate a click with JavaScript?](http://stackoverflow.com/questions/2705583/how-to-simulate-a-click-with-javascript) * make a [custom expected condition](http://stackoverflow.com/a/29377790/771848) to wait for the element text not to ends with "11 others like this." text (this is a solution to the problem you had at [Expected conditions with selenium](http://stackoverflow.com/questions/29361133/expected-conditions-with-selenium/29361478#29361478)): class wait_for_text_not_to_end_with(object): def __init__(self, locator, text): self.locator = locator self.text = text def __call__(self, driver): try : element_text = EC._find_element(driver, self.locator).text.strip() return not element_text.endswith(self.text) except StaleElementReferenceException: return False Implementation: from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class wait_for_text_not_to_end_with(object): def __init__(self, locator, text): self.locator = locator self.text = text def __call__(self, driver): try : element_text = EC._find_element(driver, self.locator).text.strip() return not element_text.endswith(self.text) except StaleElementReferenceException: return False browser = webdriver.PhantomJS() browser.maximize_window() browser.get("http://www.jamiiforums.com/kenyan-news/225589-kenyan-and-tanzanian-surburbs.html") username = browser.find_element_by_id("navbar_username") password = browser.find_element_by_name("vb_login_password_hint") username.send_keys("MarioP") password.send_keys("codeswitching") browser.find_element_by_class_name("loginbutton").click() wait = WebDriverWait(browser, 30) wait.until(EC.visibility_of_element_located((By.XPATH, '//h2[contains(., "Redirecting")]'))) wait.until(EC.title_contains('Kenyan & Tanzanian')) wait.until(EC.visibility_of_element_located((By.ID, 'postlist'))) # click "11 others" link link = browser.find_element_by_xpath('//div[@class="vbseo_liked"]/a[contains(@onclick, "return vbseoui.others_click(this)")]') link.click() browser.execute_script(""" function eventFire(el, etype){ if (el.fireEvent) { el.fireEvent('on' + etype); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); } } eventFire(arguments[0], "click"); """, link) # wait for the "div" not to end with "11 others link this." wait.until(wait_for_text_not_to_end_with((By.CLASS_NAME, 'vbseo_liked'), "11 others like this.")) print 'success!!' browser.close()
How to check for python script requirements on windows Question: I have been developing a python script for a few days now, and wanted to send the final result to a friend of mine. Is there a way to get all software requirements to run my program? The python part is relatively easy, as I can just look at my import list on my script. The problem is external software requirements. For example, one of the python modules I'm using is Rasterio. I could not install this through conda or pip, until I installed Visual Studios C++ Community Version. I imagine there is some specific dll file that is being used. I can't really tell though. I would really like to make a standalone setup.bat file, that installs all requirements and finally allows the user to simply run my program. I'm not 100% sure right now of those requirements though. How can I get these? Answer: You can explicitly check your application dependencies using **Dependency Walker** get it from [here](http://www.dependencywalker.com)
matplotlib show many images in single pdf page Question: Given an image of unknown size as input, the following `python` script shows it 8 times in a single `pdf` page: pdf = PdfPages( './test.pdf' ) gs = gridspec.GridSpec(2, 4) ax1 = plt.subplot(gs[0]) ax1.imshow( _img ) ax2 = plt.subplot(gs[1]) ax2.imshow( _img ) ax3 = plt.subplot(gs[2]) ax3.imshow( _img ) # so on so forth... ax8 = plt.subplot(gs[7]) ax8.imshow( _img ) pdf.savefig() pdf.close() The input image can have different size (unknown a priori). I tried using the function `gs.update(wspace=xxx, hspace=xxx)` to change the spacing between the images, hoping that `matplotlib` would automagically resize and redistribute the images to have least white space possible. However, as you can see below, it didn't work as I expected. > Is there a better way to go to achieve the following? 1. Have images saved with max resolution possible 2. Have less white space possible Ideally I would like the 8 images to completely will the page size of the `pdf` (with minimum amount of margin needed). ![enter image description here](http://i.stack.imgur.com/QtAK0.png) ![enter image description here](http://i.stack.imgur.com/a3GfL.png) Answer: You were on the right path: `hspace` and `wspace` control the spaces between the images. You can also control the margins on the figure with `top`, `bottom`, `left` and `right`: import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import matplotlib.image as mimage from matplotlib.backends.backend_pdf import PdfPages _img = mimage.imread('test.jpg') pdf = PdfPages( 'test.pdf' ) gs = gridspec.GridSpec(2, 4, top=1., bottom=0., right=1., left=0., hspace=0., wspace=0.) for g in gs: ax = plt.subplot(g) ax.imshow(_img) ax.set_xticks([]) ax.set_yticks([]) # ax.set_aspect('auto') pdf.savefig() pdf.close() Result: ![enter image description here](http://i.stack.imgur.com/9YDc1.jpg) If you want your images to really cover all the available space, then you can set the aspect ratio to auto: ax.set_aspect('auto') Result: ![enter image description here](http://i.stack.imgur.com/9lIfr.jpg)
how to replace the characters of the list in python Question: I want to write a code in python that will replace every every small letter character with "a" , every capital letter with "A" and every digit with 0. I write code but it caused an error of **x not in list** , code is below tokens = ["apple","banana","Orange", "pineApple", "10nuts"] for token in tokens: for ch in token: if ch.islower(): loc = tokens.index(ch) tokens.remove(ch) tokens.insert(loc,'a'); elif ch.isupper(): loc = tokens.index(ch) tokens.remove(ch) tokens.insert(loc,'A'); elif ch.isdigit(): loc = tokens.index(ch) tokens.remove(ch) tokens.insert(loc,'0'); for t in tokens: print t Answer: Using [regular expressions](https://docs.python.org/2/library/re.html): from re import sub tokens = ["apple","banana","Orange", "pineApple", "10nuts"] for i, token in enumerate(tokens): token = sub(r'[A-Z]', 'A', token) token = sub(r'[a-z]', 'a', token) token = sub(r'\d', '0', token) tokens[i] = token print tokens ## Output: ['aaaaa', 'aaaaaa', 'Aaaaaa', 'aaaaAaaaa', '00aaaa']
Python lambda with double loops Question: Is it possible to rewrite the following code into a lambda expression? for h in range(height): for w in range(width): if maskImg[h][w] > 0: maskImg[h][w] = srcImg[h][w] Answer: This is not really equivalent to you expression since this is not in-place, but you achieve the same end matrix using something like: lambda_function = lambda height, width, src, mask: [[src[h][w] if mask[h][w] > 0 else mask[h][w] for w in range(width)] for h in range(height)] But I would not recommend using it, ever. If you're after speed you should definitely use [Numpy](http://www.numpy.org/) for these kinds of things. Assuming that your `src` and `mask` are stored in Python-lists, you get the same result much, much faster doing: import numpy as np src_np = np.array(src) mask_np = np.array(mask) mask_np[mask_np > 0] = src_np[mask_np > 0] Which on my computer is ~50 times faster than your solution.
How to compare two imagefile from two different files in python Question: I would like to create a program that compares two images. I need to take images from two different folders and compare that images if they are same or not. Then I want to print out as same or different. For example file 1 will have image1 and image 2 and image 3 , etc then file 2 will have image1,image2 and image3 etc . I need to do this python. How do I do this? Can someone help me? I am new to programming and I am new to python as well. I have tried the solution as below, but it did not work. [Comparing Image Files](http://stackoverflow.com/questions/8978316/comparing-image- files/8978567#8978567) More information. import math, operator from PIL import Image import functools def compare(file1, file2): image1 = Image.open(file1) image2 = Image.open(file2) h1 = image1.histogram() h2 = image2.histogram() rms = math.sqrt( functools.reduce(operator.add, map(lambda a,b: (a-b)**2, h1, h2))/len(h1)) return rms if __name__=='__main__': import sys file1, file2 = sys.argv[1:] print( compare(file1, file2)) Actually I am using this for comparing screen taken by automation and manual testing on mobile devices. The files are *.png. I manage to get this working with below code. the above code you need top provide the image1 and image 2 on command prompt.But I want pyton to take from imagaes form files one in one location and images from other location and compare autamatiucally. If the images are same then it should print as zero as now the above code respons. If they are different then it will be no zero. The issue I am have how I could take from two files and compare one by one form scripts. Eg. File1\Image1.png ==File2\ image1.png Answer: Use ImageMagick, it is available for Python and included on most Linux distros. Get familiar at the commandline first, then work it up into Python. Create two directories mkdir directory{1..2} Create a black square in directory1 convert -size 128x128 xc:black directory1/1.png ![enter image description here](http://i.stack.imgur.com/QnyHe.png) Create a black square with a red 10x10 rectangle in directory2 convert -size 128x128 xc:black -fill red -draw "rectangle 0,0, 9,9" directory2/2.png ![enter image description here](http://i.stack.imgur.com/5g0u0.png) Now ask ImageMagick to tell us how many pixels are different between the two images, `-metric ae` is the Absolute Error. convert directory1/1.png directory2/2.png -metric ae -compare -format "%[distortion]" info: **Output** 100 **Note 1** If you want to allow the images to be nearly the same, you can add `-fuzz 10%` which will allow each pixel to differ by up to 10% from the corresponding pixel in the other image before counting it as different. This may be more useful when comparing JPEG images which may have slightly different quality/quantisation settings, and/or anti-aliasing, both of which cause images to differ slightly. **Note 2** You can _shell out_ from Python and run shell scripts like the above using this... [link](http://stackoverflow.com/questions/89228/calling-an-external- command-in-python) **Note 3** If you create, say a red GIF and a red PNG, and copare them, they will come up identical, like this # Create red GIF convert -size 128x128 xc:red red.gif # Create red PNG convert -size 128x128 xc:red red.png # Compare and find no difference convert red.png red.gif -metric ae -compare -format "%[distortion]" info: 0 despite the fact that the files theselves differ enormously ls -l red* -rw-r--r-- 1 mark staff 196 1 Apr 11:52 red.gif -rw-r--r-- 1 mark staff 290 1 Apr 11:52 red.png
python compare tuples and dictionary Question: I have to compare two sets and find the differences in python: >>> mysql_orders = ((50434L, 5901L), (50733L, 5901L)) >>> opera_orders = [{'orderId': 'WEB050434', 'accountId': '00T001'}, {'orderId': 'WEB050733', 'accountId': '00T001'}, {'orderId': 'DOC075185', 'accountId': '00T001'}, {'orderId': 'WEB081859', 'accountId': '00T001'}] One is a list of tuples and the other a list of dictionaries where the first item in the list could be the `orederId` without the WEB / DOC prefix. What is the correct way to find the missing orderId's that are not in mysql_orders list? Answer: If the letters may or may not be there but the leading 0 is always there you can use a set a strip: from string import ascii_letters st = set(str(a) for a,_ in mysql_orders) missing = [d['orderId'] for d in opera_orders if not d['orderId'].strip(ascii_letters)[1:] in st] print(missing) ['DOC075185', 'WEB081859'] If the prefix is always there just slice: missing = [d['orderId'] for d in opera_orders if not d['orderId'][4:] in st]
Python package callable from the shell? Question: I have a tool written in Python which I would like to turn into a Python package, to make it easier to install dependencies and distribute it. There are two usages: 1. you import the module `mytool.py`, call the wrapper function on it, a summary of some measurements is printed on screen and you obtain a dictionary with the full results. `import mytool; results = mytool.mytool(param1=1, param2=2)` 2. You call `mytool.py` from a shell, with the same parameters as above and a summary of the measurements is printed on screen. `$ python mytool.py --param1 1 --param2 2` Would this be correct? I understand that when you install a package from `pypi`, the main usage is the one in point 1. Once installed, It could be cumbersome to go find the exact path to `mytool.py`, and call it from the shell. Is there an alternative? Answer: I think is fine, just make sure in your setup.py you specify a nice path to store the script playing a bit with the disutils lib from distutils import setup setup( ..., scripts=['path/to/your/script',], ... ) Some nice info can be found here <https://docs.python.org/2/distutils/index.html#distutils-index> <https://docs.python.org/2/distutils/packageindex.html>
Bitnami Django Stack and module "requests": cannot import name 'certs' Question: Very specific stuff. I'm running a Bitnami Django stack cloud VM on Amazon. On two different "regular" machines, I could install `requests` by running `sudo pip install requests`, but it seems that Bitname uses it's own specific structure, and something is going wrong when installing `requests` that way. It can also be related to issue [#2028](https://github.com/kennethreitz/requests/issues/2028), but it was fixed long time ago. I have the following traceback: Environment: Request Method: GET Request URL: http://54.94.226.137/ Django Version: 1.7.7 Python Version: 2.7.6 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'vz_base', 'vz_api', 'vz_admin', 'vz_user') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback: File "/opt/bitnami/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 98. resolver_match = resolver.resolve(request.path_info) File "/opt/bitnami/python/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve 343. for pattern in self.url_patterns: File "/opt/bitnami/python/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns 372. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/opt/bitnami/python/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module 366. self._urlconf_module = import_module(self.urlconf_name) File "/opt/bitnami/python/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/opt/bitnami/apps/django/django_projects/ProjetoVigZul/ProjetoVigZul/urls.py" in <module> 5. from vz_api import urls as api_urls File "/opt/bitnami/apps/django/django_projects/ProjetoVigZul/vz_api/urls.py" in <module> 8. from vz_api import views File "/opt/bitnami/apps/django/django_projects/ProjetoVigZul/vz_api/views.py" in <module> 14. from vz_api.dguard import DGuardManager, DGuardIntegrationException File "/opt/bitnami/apps/django/django_projects/ProjetoVigZul/vz_api/dguard.py" in <module> 5. import requests, json File "/opt/bitnami/python/lib/python2.7/site-packages/requests/__init__.py" in <module> 58. from . import utils File "/opt/bitnami/python/lib/python2.7/site-packages/requests/utils.py" in <module> 25. from . import certs Exception Type: ImportError at / Exception Value: cannot import name certs Website is live at <http://54.94.226.137/>, if anyone is interested. Answer: > sudo pip install --upgrade requests solved that for me
Printing the first value in an array instead of just the first letter? (Python) Question: I have used Python to append data from an SQLite3 database to an array. Now that I have an array, I am trying to print the appended data in a format along the lines of: print "Team: " + new_array[0][0] + " Score: " + new_array[0][1] + " Overall: " + new_array[0][2] The code I have already would be okay for this. However, I am trying to create a loop using a counter that would print all of the data from the array in the above format. The problem is that when I try to create a for loop and print the first value in the array, only the first letter of the value is printed. For example: print new_array[0] ... would print: team_6 team_3 team_5 team_1 team_2 team_4 ... and... print new_array[0][0] ... would print: t t t t t t This is what I have so far: import sqlite3 new_array = [] conn = sqlite3.connect('league.db') c = conn.cursor() game = c.execute("SELECT Team,Score,Overall FROM League ORDER BY Overall DESC") for items in game: new_array.append(items) print new_array[0][0] The code above will print out 'team_6' as it should. However, the problem of printing 't's only occurs when I create a for loop. Your help would be greatly appreciated. Thanks. Answer: Try this to get expected output for items in game.fetchall(): print items[0] # should be `team6` and so on If you want to put in array.Do like this for items in game.fetchall(): new_array.append(items) >>>new_array[0][0] 'team6'
Concatenation of a variant number of keys of a dictionary Python (recursion?) Question: Hello Stackoverlow members, I'm trying to concatenate keys (string) on a hand, and values (list) on the other hand, of a dictionnary. For your better understanding, here is what I have at the beginning: dict = {'bk1': {'k11': ['a1', 'b1', 'c1'], 'k12': ['a2', 'b2', 'c2']}, 'bk2': {'k21': ['d1', 'e1'], 'k22': ['d2', 'e2'], 'k23': ['d3', 'e3']}, 'bk3': {'k31': ['f1', 'g1', 'h1'], 'k32': ['f2', 'g2', 'h2']} } And here is what I would like at the end: newdict = {'k11_k21_k31': ['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1'], 'k11_k21_k32': ['a1', 'b1', 'c1', 'd1', 'e1', 'f2', 'g2', 'h2'], 'k11_k22_k31': ['a1', 'b1', 'c1', 'd2', 'e2', 'f1', 'g1', 'h1'], 'k11_k22_k32': ['a1', 'b1', 'c1', 'd2', 'e2', 'f2', 'g2', 'h2'], 'k11_k23_k31': ['a1', 'b1', 'c1', 'd3', 'e3', 'f1', 'g1', 'h1'], 'k11_k23_k32': ['a1', 'b1', 'c1', 'd3', 'e3', 'f2', 'g2', 'h2'], 'k12_k21_k31': ['a2', 'b2', 'c2', 'd1', 'e1', 'f1', 'g1', 'h1'], 'k12_k21_k32': ['a2', 'b2', 'c2', 'd1', 'e1', 'f2', 'g2', 'h2'], 'k12_k22_k31': ['a2', 'b2', 'c2', 'd2', 'e2', 'f1', 'g1', 'h1'], 'k12_k22_k32': ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2'], 'k12_k23_k31': ['a2', 'b2', 'c2', 'd3', 'e3', 'f1', 'g1', 'h1'], 'k12_k23_k32': ['a2', 'b2', 'c2', 'd3', 'e3', 'f2', 'g2', 'h2']} I wish to do that with: * a **variant** number of "big key" (bki), and for each bki, a **variant** number of key (kij). * "Full combination" between "big keys". For example, I don't expect results like: {'k11_k23': ['a1', 'b1', 'c1', 'd3', 'e3']} where the "bk3" is missed. I tried with imbricated "for" loops but the number of loops is depending on the number of "big keys"... Then, I felt that the problem could be solved with recursion (maybe?), but in spite of my research and my will to implement it, I failed. Any help with "recursive or not" solution would be strongly appreciated. Thank you, Mat * * * Whoaa, what a reactivity! Thanks a lot for all your quick answers, it works **perfect!** Answer: As suggested by @jksnw in the comments, you can use `itertools.product` to do this: import itertools dct = { 'bk1': { 'k11': ['a1', 'b1', 'c1'], 'k12': ['a2', 'b2', 'c2'] }, 'bk2':{ 'k21': ['d1', 'e1'], 'k22': ['d2', 'e2'], 'k23': ['d3', 'e3'] }, 'bk3': { 'k31': ['f1', 'g1', 'h1'], 'k32': ['f2', 'g2', 'h2'] } } big_keys = dct.keys() small_keys = (dct[big_key].keys() for big_key in big_keys) res = {} for keys_from_each in itertools.product(*small_keys): key = "_".join(keys_from_each) value = [] for big_key, small_key in zip(big_keys, keys_from_each): value.extend(dct[big_key][small_key]) res[key] = value So that: >>> res {'k11_k21_k31': ['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1'], 'k11_k21_k32': ['a1', 'b1', 'c1', 'd1', 'e1', 'f2', 'g2', 'h2'], 'k11_k22_k31': ['a1', 'b1', 'c1', 'd2', 'e2', 'f1', 'g1', 'h1'], 'k11_k22_k32': ['a1', 'b1', 'c1', 'd2', 'e2', 'f2', 'g2', 'h2'], 'k11_k23_k31': ['a1', 'b1', 'c1', 'd3', 'e3', 'f1', 'g1', 'h1'], 'k11_k23_k32': ['a1', 'b1', 'c1', 'd3', 'e3', 'f2', 'g2', 'h2'], 'k12_k21_k31': ['a2', 'b2', 'c2', 'd1', 'e1', 'f1', 'g1', 'h1'], 'k12_k21_k32': ['a2', 'b2', 'c2', 'd1', 'e1', 'f2', 'g2', 'h2'], 'k12_k22_k31': ['a2', 'b2', 'c2', 'd2', 'e2', 'f1', 'g1', 'h1'], 'k12_k22_k32': ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2'], 'k12_k23_k31': ['a2', 'b2', 'c2', 'd3', 'e3', 'f1', 'g1', 'h1'], 'k12_k23_k32': ['a2', 'b2', 'c2', 'd3', 'e3', 'f2', 'g2', 'h2']} Here, `itertools.product` is used to get a list of the "small keys" that we take from each block: >>> big_keys = dct.keys() >>> small_keys = (dct[big_key].keys() for big_key in big_keys) >>> list(itertools.product(*small_keys)) [('k12', 'k22', 'k31'), ('k12', 'k22', 'k32'), ('k12', 'k23', 'k31'), ('k12', 'k23', 'k32'), ('k12', 'k21', 'k31'), ('k12', 'k21', 'k32'), ('k11', 'k22', 'k31'), ('k11', 'k22', 'k32'), ('k11', 'k23', 'k31'), ('k11', 'k23', 'k32'), ('k11', 'k21', 'k31'), ('k11', 'k21', 'k32')]
Python: Using a multidimensional multiprocessing.manager.list() Question: This might not be its intended use, but I would like to know how to use a multidimensional manager.list(). I can create on just fine, something like this: from multiprocessing import manager test = manager.list(manager.list()) however when ever I try to access the first element of the test list it returns the element's value and not its proxy object test[0] # returns [] and not the proxy, since I think python is running __getitem__. Is there anyway for me to get around this and use the manager.list() in this way? Answer: The [`multiprocessing` documentation](https://docs.python.org/2.7/library/multiprocessing.html#multiprocessing.managers.SyncManager.list) has a note on this: > **Note** > > Modifications to mutable values or items in dict and list proxies will not > be propagated through the manager, because the proxy has no way of knowing > when its values or items are modified. To modify such an item, you can re- > assign the modified object to the container proxy: > > > # create a list proxy and append a mutable object (a dictionary) > lproxy = manager.list() > lproxy.append({}) > # now mutate the dictionary > d = lproxy[0] > d['a'] = 1 > d['b'] = 2 > # at this point, the changes to d are not yet synced, but by > # reassigning the dictionary, the proxy is notified of the change > lproxy[0] = d > So, the only way to use a multidimensional list is to actually reassign any changes you make to the second dimension of the list back to the top-level list, so instead of: test[0][0] = 1 You do: tmp = test[0] tmp[0] = 1 test[0] = tmp Not the most pleasant way to do things, but you can probably write some helper functions to make it a bit more tolerable. **Edit:** It seems the reason that you get a plain list back when you append a `ListProxy` to another `ListProxy` is because of how pickling Proxies works. `BaseProxy.__reduce__` creates a `RebuildProxy` object, which what actually is used to unpickle the `Proxy`. `RebuildProxy` looks like this: def RebuildProxy(func, token, serializer, kwds): ''' Function used for unpickling proxy objects. If possible the shared object is returned, or otherwise a proxy for it. ''' server = getattr(process.current_process(), '_manager_server', None) if server and server.address == token.address: return server.id_to_obj[token.id][0] else: incref = ( kwds.pop('incref', True) and not getattr(process.current_process(), '_inheriting', False) ) return func(token, serializer, incref=incref, **kwds) As the docstring says, if the unpickling is occuring inside a manager server, the actual shared object is created, rather than the `Proxy` to it. This is probably a bug, and [there is actually one filed](http://bugs.python.org/issue6766) against this behavior already.
Matplotlib: Grouped boxplots using data from numpy array and lists of group/subgroup labels Question: I'm new to Matplotlib / Python, and am trying to make a grouped boxplot very similar to Joe Kington's excellent example shown here: [how to make a grouped boxplot graph in matplotlib](http://stackoverflow.com/questions/20365122/how-to-make-a-grouped- boxplot-graph-in-matplotlib) I'd like to modify Joe's example for my own requirements. For my demo data below, I have 5 individuals who each have 4 attempts ( = "attempts": '1st','2nd','3rd','4th') at each of 3 different tasks (= "tasks": 'A','B','C'). I'd like to be able to: 1) input my data as a series of 2D numpy arrays, one array per task as shown, which are each composed of the scores of the 5 individuals nested within the 4 sequential attempts. 2) label both the tasks and attempts on the shared x-axis of the plot using strings, saved as sequential items in the lists "tasklist" and "attemptlist" respectively. 3) generalise the solution to make the appropriate plots for any number of individuals, and any number of tasks, each requiring any number of repeated attempts. Edit: 2 Apr 2015: The only problem outstanding is the seemingly counter-intuitive way that Python lists assemble themselves into a non-sequential order when using the .keys() method; hence my tasklist keeps coming out as "A,C,B" rather than "A,B,C". The workaround is to import and create an Ordered Dictionary. This is all new to me, but this would seem to require the item names in my tasklist to be declared twice as Joe did in his example - once to associate the tasks with the corresponding data matrices, and once to associate the item names in the Ordered Dictionary with the corresponding sequential numeric keys... Was wondering: is there a method (akin to the .keys() method for regular dictionaries) which would iterate over my data matrices to create an Ordered Dictionary in the order shown ("A,B,C"), without requiring me to enter details of my tasklist twice? Many thanks Dave import matplotlib.pyplot as plt import numpy as np data = {} data ['A'] = np.array([[1,2,3,4,9],[2,3,4,4,4],[3,4,4,5,5],[5,6,6,7,7,7]]) data ['B'] = np.array([[2,3,4,4,5],[3,4,5,6,10],[4,5,6,6,7],[5,6,7,7,8]]) data ['C'] = np.array([[4,5,6,6,10],[6,7,8,8,8],[7,8,9,9,10],[2,10,11,11,12]]) tasklist = data.keys() # list of labels for tasks 'A' to 'C' (each containing 4 attempts labelled '1st' to '4th') attemptlist = ['1st','2nd','3rd','4th'] # list of labels for attempts 1 to 4 within each task fig, axes = plt.subplots(ncols= len(tasklist), sharey=True) fig.subplots_adjust(wspace=0) for ax,task in zip(axes,tasklist): ax.boxplot([data[task][attemptlist.index(attempt)] for attempt in attemptlist],showfliers=False) ax.set(xticklabels=attemptlist, xlabel=task) plt.show() Answer: @cphlewis: Many thanks: on your advice have re-written code with data formatted as list of tuples (task, data), and now have control over order in which tasks are plotted. MWE posted below in case this is helpful for anyone else. import matplotlib.pyplot as plt data = [[('A'),[[1,2,3,4,9],[2,3,4,4,4],[3,4,4,5,5],[5,6,6,7,7,7]]], [('B'),[[2,3,4,4,5],[3,4,5,6,10],[4,5,6,6,7],[5,6,7,7,8]]], [('C'),[[4,5,6,6,10],[6,7,8,8,8],[7,8,9,9,10],[2,10,11,11,12]]] ] attemptlist = ['1st','2nd','3rd','4th'] fig, axes = plt.subplots(ncols= len(data), sharey=True) fig.subplots_adjust(wspace=0) for ax,d in zip(axes,data): ax.boxplot([d[1][attemptlist.index(attempt)] for attempt in attemptlist],showfliers=False) ax.set(xticklabels=attemptlist, xlabel=d[0]) plt.show()
segmentation fault - core dump in python C-extension Question: I am writing a c-extension for python. As you can see below, the aim of the code is to calculate the euclidean-dist of two vectors. the first param n is the dimension of the vectors, the second , the third param is the two list of float. I call the function in python like this: import cutil cutil.c_euclidean_dist(2,[1.0,1,0],[0,0]) and it worked well, return the right result. but if i do it for more than 100 times(the dimension is 1*1000), it will cause segmentation fault - core dump: #!/usr/bin/env python #coding:utf-8 import cutil import science import time a = [] b = [] d = 0.0 for x in range(2500): a.append([float(i+x) for i in range(1000)]) b.append([float(i-x) for i in range(1000)]) t1 = time.time() for x in range(500): d += cutil.c_euclidean_dist(1000,a[x],b[x]) print time.time() - t1 print d the C code is here: #include <python2.7/Python.h> #include <math.h> static PyObject* cutil_euclidean_dist(PyObject* self, PyObject* args) { PyObject *seq_a, *seq_b; int n; float * array_a,* array_b; PyObject *item; PyArg_ParseTuple(args,"iOO", &n , &seq_a, &seq_b); if (!PySequence_Check(seq_a) || !PySequence_Check(seq_b)) { PyErr_SetString(PyExc_TypeError, "expected sequence"); return NULL; } array_a =(float *)malloc(sizeof(float)*n); array_b =(float *)malloc(sizeof(float)*n); if (NULL == array_a || NULL == array_b){ PyErr_SetString(PyExc_TypeError, "malloc failed!"); Py_DECREF(seq_a); Py_DECREF(seq_b); return NULL; } int i; for(i=0;i<n;i++){ item = PySequence_GetItem(seq_a,i); if (!PyFloat_Check(item)) { free(array_a); /* free up the memory before leaving */ free(array_b); Py_DECREF(seq_a); Py_DECREF(seq_b); Py_DECREF(item); PyErr_SetString(PyExc_TypeError, "expected sequence of float"); return NULL; } array_a[i] = PyFloat_AsDouble(item); Py_DECREF(item); item = PySequence_GetItem(seq_b,i); if(!PyFloat_Check(item)) { free(array_a); free(array_b); Py_DECREF(seq_a); Py_DECREF(seq_b); Py_DECREF(item); PyErr_SetString(PyExc_TypeError, "expected sequence of float"); return NULL; } array_b[i] = PyFloat_AsDouble(item); Py_DECREF(item); } double sum = 0; for(i=0;i<n;i++){ double delta = array_a[i] - array_b[i]; sum += delta * delta; } free(array_a); free(array_b); Py_DECREF(seq_a); Py_DECREF(seq_b); return Py_BuildValue("d",sqrt(sum)); } static PyMethodDef cutil_methods[] = { {"c_euclidean_dist",(PyCFunction)cutil_euclidean_dist,METH_VARARGS,NULL}, {NULL,NULL,0,NULL} }; PyMODINIT_FUNC initcutil(void) { Py_InitModule3("cutil", cutil_methods, "liurui's c extension for python"); } the error msg: segmentation fault - core dump: The c-extension is compiled to cutil.so, I do not know how to see the dump. But i looked through my C code for many times,and can not find any problem.. May it be **a memory problem**? It should be a very simple piece of C code, what's wrong with it? I need your help~ thanks a lot ! here is the result of gdb /usr/bin/python2.7 ./core: root@ubuntu:/home/rrg/workspace/opencvTest/test# gdb /usr/bin/python2.7 ./core GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1 Copyright (C) 2014 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from /usr/bin/python2.7...Reading symbols from /usr/lib/debug//usr/bin/python2.7...done. done. warning: core file may not match specified executable file. [New LWP 13787] [New LWP 13789] [New LWP 13790] [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Core was generated by `python py.py'. Program terminated with signal SIGSEGV, Segmentation fault. #0 0x00000000005398b3 in list_dealloc.16846 (op=0x7f688b2faa28) at ../Objects/listobject.c:309 309 ../Objects/listobject.c: no such file or directory #0 0x00000000005398b3 in list_dealloc.16846 (op=0x7f688b2faa28) at ../Objects/listobject.c:309 #1 0x00000000004fdb96 in insertdict_by_entry (value=<optimized out>, ep=0x1777fa8, hash=<optimized out>, key='b', mp=0x7f68a8dbb168) at ../Objects/dictobject.c:519 #2 insertdict (value=<optimized out>, hash=<optimized out>, key='b', mp=0x7f68a8dbb168) at ../Objects/dictobject.c:556 #3 dict_set_item_by_hash_or_entry (value=<optimized out>, ep=0x0, hash=<optimized out>, key='b', op={'a': None, 'x': None, 'c': None, 'b': None, 'd': <float at remote 0x4480b30>, '__builtins__': <module at remote 0x7f68a8de6b08>, 'science': <module at remote 0x7f68a8ce4088>, '__package__': None, 'i': 999, 'cutil': <module at remote 0x7f68a8cdfbb0>, 'time': <module at remote 0x7f68a640ea28>, '__name__': '__main__', 't1': <float at remote 0xd012708>, '__doc__': None}) at ../Objects/dictobject.c:765 #4 PyDict_SetItem ( op=op@entry={'a': None, 'x': None, 'c': None, 'b': None, 'd': <float at remote 0x4480b30>, '__builtins__': <module at remote 0x7f68a8de6b08>, 'science': <module at remote 0x7f68a8ce4088>, '__package__': None, 'i': 999, 'cutil': <module at remote 0x7f68a8cdfbb0>, 'time': <module at remote 0x7f68a640ea28>, '__name__': '__main__', 't1': <float at remote 0xd012708>, '__doc__': None}, key=key@entry='b', value=<optimized out>) at ../Objects/dictobject.c:818 #5 0x000000000055a9e1 in _PyModule_Clear (m=<optimized out>) at ../Objects/moduleobject.c:139 #6 0x00000000004f2ad4 in PyImport_Cleanup () at ../Python/import.c:473 #7 0x000000000042fa89 in Py_Finalize () at ../Python/pythonrun.c:459 #8 0x000000000046ac10 in Py_Main (argc=<optimized out>, argv=0x7fff3958d058) at ../Modules/main.c:665 #9 0x00007f68a8665ec5 in __libc_start_main (main=0x46ac3f <main>, argc=2, argv=0x7fff3958d058, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fff3958d048) at libc-start.c:287 #10 0x000000000057497e in _start () Edit: I comment the last 2 sentences near the last return: Py_DECREF(seq_a); Py_DECREF(seq_b); and then it seems to work well. I feel very very strange... The purpose of the two sentence is to free(or release) the two pyobject, why it works well without the two sentences which I think are necessary? Answer: > The c-extension is compiled to cutil.so, I do not know how to see the dump. To solve this, I'm going to cite [GNU Radio's GDB/Python debugging mini- tutorial](http://gnuradio.org/redmine/projects/gnuradio/wiki/TutorialsGDB): > Luckily, there's a feature called core dumping that allows the state of your > program to be stored in a file, allowing later analysis. Usually, that > feature is disabled; you can enable it by: > > > ulimit -c unlimited > > > Note that this only works for processes spawned from the shell that you used > ulimit in. What happens here is that the maximum size of a core dump is set > to unlimited (the original value is 0 in most cases). > > Now, the core dump file lays in the current execution directory of the > program that crashed. In our case, that's build/python/, but since all core > dumps should have a name like core., we can use a little find magic: > > > marcus> find -type f -cmin 5 -name 'core.[0-9]*' > > > ./build/python/core.22608 > > because that will find all _f_iles, changed/created within the last _5 > min_utes, having a name that matches. > > ## Using GDB with a core dump > > having found build/python/core.22608, we can now launch GDB: > > > gdb programname coredump > > > i.e. > > > gdb /usr/bin/python2 build/python/core.22608 > > > A lot of information might scroll by. > > At the end, you're greeted by the GDB prompt: > > > (gdb) > > > ## Getting a backtrace > > Typically, you'd just get a backtrace (or shorter, bt). A backtrace is > simply the hierarchy of functions that were called. > > > (gdb)bt > [...] skipped, > Frame #2 and following definitely look like they're part of the Python > implementation -- that sounds bad, because GDB doesn't itself know how to > debug python, but luckily, there's an extension to do that. So we can try to > use py-bt: > > > (gdb) py-bt > > > If we get a undefined command error, we must stop here and make sure that > the python development package is installed (python-devel on Redhatoids, > python2.7-dev on Debianoids); for some systems, you should append the > content of /usr/share/doc/{python-devel,python2.7-dev}/gdbinit[.gz] to your > ~/.gdbinit, and re-start gdb. > > The output of py-bt now states clearly which python lines correspond to > which stack frame (skipping those stack frames that are hidden to python, > because they are in external libraries or python-implementation routines) > > ...
How to install numpy and scipy for Ironpython27? Old method doens't work Question: I think this is the most popular way to do it before: <https://pytools.codeplex.com/wikipage?title=NumPy%20and%20SciPy%20for%20.Net> But this link is no longer exist: <https://store.enthought.com/repo/.iron/> * * * **_I recently found a clone for the instruction, and also found a clone of ironpkg-1.0.0.py on github. But<http://www.enthought.com/repo/.iron/eggs/index-depend.txt> is no longer exists in the internet(I googled it, but failed to find it)_** Getting started with SciPy for .NET 1.) IronPython Download and install IronPython 2.7, this will require .NET v4.0. 2.) Modify PATH Add the install location on the path, this is usually: C:\Program File\IronPython 2.7 But on 64-bit Windows systems it is: C:\Program File (x86)\IronPython 2.7 As a check, open a Windows command prompt and go to a directory (which is not the above) and type: > ipy -V PythonContext 2.7.0.40 on .NET 4.0.30319.225 3.) ironpkg Bootstrap ironpkg, which is a package install manager for binary (egg based) Python packages. Download ironpkg-1.0.0.py and type: > ipy ironpkg-1.0.0.py --install > Now the ironpkg command should be available: > > ironpkg -h (some useful help text is displayed here) 4.) scipy Installing scipy is now easy: > ironpkg scipy numpy-2.0.0b2-1.egg ## Question **I think I have done as much as I can do. Any body succeed to install numpy and scipy for Ironpython27?** Answer: For those struggling to get numpy/scipy install for ironpythopn, enthought have moved the download link to <https://store.enthought.com/repo/.iron/> . The link would only allow you in if you are registered. Therefore first up you'd have to register yourself for free, then open the above link, then follow the steps below 1. Download the IronPython-2.7.msi and install it. 2. Download ironpkg-1.0.0.py from the above link. 3. Using command line navigate to the directory where you placed ironpkg-1.0.0.py and run `ipy ironpkg-1.0.0.py --install` Check whether the install worked using `ironpkg -h` 4. The last step is lightly different to the one suggested by enthoughts. Running `ironpkg scipy` won't work as it looks at the old web address for download. Instead download all the eggs and `index-depend.txt` from the above link. For installation to work, you would have to modify the download location in the config file to point to the local drive instead of website. The config file can be found at user directory eg.`C:\Users\Nilster\.ironpkg` . Open it in the textpad and change the location to directory where you downloaded the eggs Eg, mine looks like IndexedRepos = ['file://C:\Work\Python\Enthought_Eggs',] 5. Then run the following to install numpy/scipy `ironpkg scipy` 6. Check whether the install worked using `ipy -X:Frames -c "import scipy"`
Changing data type with pandas on read_excel Question: I'm looking for some help as I'm actually quite new to pandas (and python). I'm facing a data type conversion problem with some datas. As you can see (and try), I'm trying to tell pandas that I want it to read the "DEP" data column as a string (because I want to keep the data unchanged) >>> df = pd.read_excel("http://www2.impots.gouv.fr/documentation/statistiques/ircom2003/dep/060.xls", 0, skiprows=23, na_values="n.d.") >>> df.dtypes Unnamed: 0 float64 DEP float64 Commune float64 ... >>> df["DEP"] = df["DEP"].astype(str) >>> df.dtypes Unnamed: 0 float64 DEP object Commune float64 ..... >>> df["DEP"][5] '60.0' You can download the excel file if you want, but the input data look like this : (I've added the slash between column names) DEP / Commune / Libellé de la commune 060 001 AIGLUN 060 002 AMIRAT In this case, I would like to simply keep the data "060" and "001" as strings. I'm using python 3.4 and pandas 0.16 Thanks a lot for your help. Answer: There is another possibility. I must admit it's a little bit scrapy, but I tested successfully. You need to create a new class: class NewType(): def __init__(self, sValue=""): self.strValue = sValue def __str__(self): return self.strValue then define a convert function: def convert(value): return NewType(value) in your function (where you want to read_excel), do the following, assuming you have 28 columns to read: import pandas as pd converters = dict() for i in range(0,28,1): converters[i] = convert dataframe = pd.read_excel(path_to_file, sheet_name, 0, None, 0, None, 27, False, None, "", None, False, None, converters) dataframe = dataframe.transpose() dataDict = dataframe.to_dict() newDict= OrderedDict() for dataLine in dataDict.values(): for field in dataLine.keys(): dataLine[field] = str(dataLine[field]) #do something with dataLine At the end you have something identical to CSV.DictReader if you had the data formatted in CSV
ImportError No module named 'plotlytools' when importing Cufflinks Question: My system environment: `Windows 8.1, WinPython 3.4.3.1, pandas 0.16, plotly 1.6.14, cufflinks 0.2` I have no idea what's causing the issue. I'm attempting to use the tutorial outlined here [cufflinks nbviewer tutorial](http://nbviewer.ipython.org/gist/santosjorge/cfaaf43b40db19d6127a "cufflinks nbviewer") However when I try to import the cufflinks module I get the following output. ![enter image description here](http://i.stack.imgur.com/IsOyZ.png) That doesn't make sense to me because as far as I can tell the files are all set up correctly within the folder and I don't see any obvious errors within the files themselves. See below image: ![enter image description here](http://i.stack.imgur.com/qyPBY.png) I also looked at the `__init__.py` file and didn't see anything unusual. ![enter image description here](http://i.stack.imgur.com/OD0qX.png) And lastly I looked at the actual `plotlytools.py` file to see if anything looked odd and nothing jumped out at me. ![enter image description here](http://i.stack.imgur.com/dAs1P.png) Any help figuring this one out would be greatly appreciated. Thanks. UPDATE: If this helps here is a print out of my `sys.path` ![enter image description here](http://i.stack.imgur.com/E0F4e.png) Answer: I was able to import the module after implementing the following workarounds: 1. In the `utils.py` file I added `()` to all the `print` statements, example: `print 'string'` became `print('string')`. 2. I copied then deleted the `utils.py` and `colors.py` files and pasted the contents into the `plotlytools.py` file. 3. I updated all the import references in the remaining files. 4. to use the pandastools functionality, specifically the `df.iplot` method, it was also necessary to update the encoding and decoding methods for the `colors.py` file from `str.encode('hex') and str.decode('hex')` to `import codecs; codecs.encode(str,'hex'); codecs.decode(str,'hex')` 5. I also updated the generator methods from `gen_object.next()` to `next(gen_object)` At this point all the functionality of the module seems to be restored.
ImportError: Could not import settings - No module named settings Question: i have what seems to be a basic path problem, but i can't figure this out for the life of me. I have the following directory structure: └── rockitt ├── activities │   ├── migrations │   ├── templates │   │   └── activities │   └── templatetags ├── blog │   ├── settings within `blog/settings` I have: `base.py dev.py __init.py__` `__init.py__` within the directory above contains: `from .dev import *` When running things like manage.py i receive the following error: `ImportError: Could not import settings 'blog.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named settings ` **What I have tried so far:** 1. I've checked what paths are present when manage.py is running and the following path is at the top of the list: ` rockitt lib/python2.7/Django-1.7.7-py2.7.egg lib/python2.7 [other dirs...] ENV/lib/python27.zip ENV/lib/python2.7 ENV/lib/python2.7/plat-linux2 ENV/lib/python2.7/lib-tk ENV/lib/python2.7/lib-old ENV/lib/python2.7/lib-dynload /usr/local/lib/python2.7 /usr/local/lib/python2.7/plat-linux2 /usr/local/lib/python2.7/lib-tk ENV/lib/python2.7/site-packages ` 2. I've tried to manually load the settings file with no luck: from the blog/settings directory i have tried (I'm not sure if this is the right way to test this however based on reading [this](http://stackoverflow.com/questions/11536764/attempted-relative-import-in-non-package-even-with-init-py): >>> import dev Traceback (most recent call last): File "<stdin>", line 1, in <module> File "dev.py", line 1, in <module> from .base import * ValueError: Attempted relative import in non-package I'm kinda stuck on this. I -=think=- it might be also related to my wsgi.py file (below). **Further info:** 1. wsgi.py: import os, sys, site site.addsitedir('/home/thisUserName/webapps/dev_django_rockitt/ENV/lib/python2.7/site-packages') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blog.settings.dev") activate_this = os.path.expanduser("/home/thisUserName/webapps/dev_django_rockitt/ENV/bin/activate_this.py") execfile(activate_this, dict(__file__=activate_this)) #calculate the path based on the location of the WSGI script project = '/home/thisUserName/webapps/dev_django_rockitt/rockitt' workspace = os.path.dirname(project) sys.path.append(workspace) sys.path = ['/home/thisUserName/webapps/dev_django_rockitt/rockitt/blog', '/home/thisUserName/webapps/dev_django_rockitt/rockitt'$ from django.core.wsgi import get_wsgi_application application = get_wsgi_application() 2. Stacktrace: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/thisUserName/webapps/dev_django_rockitt/lib/python2.7/Django-1.7.7-py2.7.egg/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/home/thisUserName/webapps/dev_django_rockitt/lib/python2.7/Django-1.7.7-py2.7.egg/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/home/thisUserName/webapps/dev_django_rockitt/lib/python2.7/Django-1.7.7-py2.7.egg/django/conf/__init__.py", line 46, in __getattr__ self._setup(name) File "/home/thisUserName/webapps/dev_django_rockitt/lib/python2.7/Django-1.7.7-py2.7.egg/django/conf/__init__.py", line 42, in _setup self._wrapped = Settings(settings_module) File "/home/thisUserName/webapps/dev_django_rockitt/lib/python2.7/Django-1.7.7-py2.7.egg/django/conf/__init__.py", line 98, in __init__ % (self.SETTINGS_MODULE, e) ImportError: Could not import settings 'blog.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named settings Answer: it's almost tempting to remove this question due to my own stupidity, however i think the answer might help someone else who is coding and lacks sleep. it's quite simple really - **it was a typo within the`blog/settings` directory**. **I had typed`__init.py__`, but obviously it should have been `__init__.py`** Once this was rectified the error disappeared. I hope this helps someone in the future. Facepalm moment.
Python sending email won't work, and is giving long error messages Question: I'm testing a python script to send e-mail to myself: import smtplib fromaddr = '[email protected]' toaddrs = '[email protected]' msg = 'GRRRRR!!!!!!' username = '[email protected]' password = '----------' server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(username, password) server.sendmail(fromaddr, toaddrs, msg) server.quit() Where "----------" means "private information." This is the error message I get: Traceback (most recent call last): File "ms.py", line 10, in <module> server.login(username, password) File "/usr/lib/python2.7/smtplib.py", line 615, in login raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvXa\n5.7.14 z7t5LRUd-e-nGxiMetNBY2KaLd8EP3SJVhw2EwccDQjlUi0FxHegAH2YrpvKdYIX2lHz9N\n5.7.14 cMZ_w8kPxuXXhBPMbXA26tWu_HM0tt_4IC8aEct5VRz7z1J22epkLWXUx-COwh4rt2K2-_\n5.7.14 1Lw71Ag70CBpsqYpfzScV-_mF7zHl_NFRflAn5sFnPftR_bX6hhGAHxj5rz1bx0U44sByk\n5.7.14 t-arL3mQhKu-nfFzkcIvjlzuUh3w> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 p18sm2343352qkh.10 - gsmtp') What am I doing wrong? Answer: You might need: `server = smtplib.SMTP_SSL('smtp.gmail.com:465')` instead of: server = smtplib.SMTP('smtp.gmail.com:587') and probably don't need the .ehlo () See also <https://support.google.com/accounts/answer/185833>
From a python3 script, how to I pipe a string into a bash program? Question: As an example, here's what I've tried: #!/usr/bin/env python3 from subprocess import Popen message = "Lo! I am up on an ox." Popen('less', shell=True).communicate(input=message) As the last line, I also tried: Popen('less', stdin=message, shell=True) I can do what I want with: Popen('echo "%s" | less' % message, shell=True) Is there a more pythonic way of doing it? Thanks! Answer: @hyades answer above is certainly correct, and depending on what exactly you want might be best, but the reason your second example didn't work is because the `stdin` value must be file-like (just like unix). The following also works for me. with tempfile.TemporaryFile(mode="w") as f: f.write(message) f.seek(0) Popen("less", stdin=f)
Override a "private" method in a python module Question: I want to test a function in python, but it relies on a module-level "private" function, that I don't want called, but I'm having trouble overriding/mocking it. Scenario: module.py _cmd(command, args): # do something nasty function_to_be_tested(): # do cool things _cmd('rm', '-rf /') return 1 test_module.py import module test_function(): assert module.function_to_be_tested() == 1 Ideally, in this test I dont want to call _cmd. I've looked at some other threads, and I've tried the following with no luck: test_function(): def _cmd(command, args): # do nothing pass module._cmd = _cmd although checking module._cmd against _cmd doesn't give the correct reference. Using mock: from mock import patch def _cmd_mock(command, args): # do nothing pass @patch('module._cmd', _cmd_mock) test_function(): ... gives the correct reference when checking module._cmd, although `function_to_be_tested' still uses the original _cmd (as evidenced by it doing nasty things). This is tricky because _cmd is a module-level function, and I dont want to move it into a module Answer: **[Disclaimer]** The synthetic example posted in this question works and the described issue become from specific implementation in production code. Maybe this question should be closed as off topic because the issue is not reproducible. * * * **[Note]** For impatient people _Solution_ is at the end of the answer. * * * Anyway that question given to me a good point to thought: how we can patch a method reference when we cannot access to the _variable_ where the reference is? Lot of times I found some issue like this. There are lot of ways to meet that case and the commons are * Decorators: the instance we would like replace is passed as decorator argument or used in decorator static implementation * What we would like to patch is a default argument of a method In both cases maybe refactor the code is the best way to play with that but what about if we are playing with some legacy code or the decorator is a third part decorator? Ok, we have the back on the wall but we are using python and in python nothing is impossible. What we need is just the reference of the function/method to patch and instead of patching its reference we can patch the `__code__`: yes I'm speaking about patching the bytecode instead the function. Get a real example. I'm using default parameter case that is simple, but it works either in decorator case. def cmd(a): print("ORIG {}".format(a)) def cmd_fake(a): print("NEW {}".format(a)) def do_work(a, c=cmd): c(a) do_work("a") cmd=cmd_fake do_work("b") Output: > > ORIG a > ORIG b > Ok In this case we can test `do_work` by passing `cmd_fake` but there some cases where is impossible do it: for instance what about if we need to call something like that: def what_the_hell(): list(map(lambda a:do_work(a), ["c","d"])) what we can do is patch `cmd.__code__` instead of `_cmd` by cmd.__code__ = cmd_fake.__code__ So follow code do_work("a") what_the_hell() cmd.__code__ = cmd_fake.__code__ do_work("b") what_the_hell() Give follow output: > > ORIG a > ORIG c > ORIG d > NEW b > NEW c > NEW d > Moreover if we want to use a mock we can do it by add follow lines: from unittest.mock import Mock, call cmd_mock = Mock() def cmd_mocker(a): cmd_mock(a) cmd.__code__=cmd_mocker.__code__ what_the_hell() cmd_mock.assert_has_calls([call("c"),call("d")]) print("WORKS") That print out > > WORKS > * * * Maybe I'm done... but OP still wait for a _solution_ of his _issue_ from mock import patch, Mock cmd_mock = Mock() #A closure for grabbing the right function code def cmd_mocker(a): cmd_mock(a) @patch.object(module._cmd,'__code__', new=cmd_mocker.__code__) test_function(): ... Now I should say **never use this trick unless you are with the back on the wall**. Test should be simple to understand and to debug ... try to debug something like this and you will become mad!
Global variable from a library not yet initialized when used Question: ## **The context :** I created a module (I call it Hello) for Python in C++. The interface between C++ and Python is made by Swig. It generates a dynamic library `_Hello.so` and a Python file `Hello.py`. Then, when created, I juste have to call it by this way : python >>> import Hello >>> Hello.say_hello() Hello World ! >>> I want to protect this module with a license, then I want the license is loaded when the module is imported. ## **My implementation :** In order to be sure the license is loaded when I import the module, I created a singleton instanciating a global variable : File `LicenseManager.hpp` : class LicenseManager { private: static LicenseManager licenseManager; // singleton instance public: static LicenseManager& get(); // get the singleton instance public: LicenseManager(); // load the license ~LicenseManager(); // release the license private: LicenseManager(const LicenseManager&); // forbidden (singleton) LicenseManager& operator = (const LicenseManager&); // forbidden (singleton) }; File `LicenseManager.cpp` : LicenseManager LicenseManager::licenseManager; // singleton instance LicenseManager& LicenseManager::get() { return LicenseManager::licenseManager; } LicenseManager::LicenseManager() { /* * Here is the code to check the license */ if(lic_ok) std::cout << "[INFO] License found. Enjoy this tool !" << std::endl; else { std::cerr << "[ERROR] License not found..." << std::endl; throw std::runtime_error("no available licenses"); } } LicenseManager::~LicenseManager() {} This works perfectly ! When I load my module, I obtain : python >>> import Hello [INFO] License found. Enjoy this tool ! >>> Hello.say_hello() Hello World ! >>> ## **My problem :** Actually, the code checking the license in my constructor uses the library _Crypto++_. I have a segmentation fault coming from this library but the same code in the main function works perfectly. Then I think that Crpyto++ also use global variables and these are not yet initialized when the constructor of `LicenseManager` is called. I know there is no control on the initialization order of the global variables in C++. But maybe there is another way to do what I need better ? ## **Bad solutions :** * If the singleton is not initialized as a global variable, the module is not protected when imported. A solution could be add a check in each functionnality of the module, and force the user to call the LicenseManager before usage. It's not a solution for me because I can't rewrite all my module to impose that (the module is quite huge actually). * In the Swig configuration file, I can add Python code called when the module is loaded. Then I have to compile `Hello.py` to prevent the user simply remove the call to the LicenseManager. But then it's a poor security because Python is easy to decompile. Answer: Answering my own question. Actually, it is possible with Swig to add C++ code called during the initialization of the library. Then I just had to add the following code in the Swig file : %init%{ LicenseManager::get(); %}
how to take multiple chracter in argv in python Question: i am new in python3 and currently learning it i have written small code below. i want to know that why argv is taking single character only? for every variable. isn't it supposed to take whole string(multiple characters)? in other words when i input in console it only hold four single characters. every variable have just one character. from sys import argv def main(argv): script, first, second, third = argv print ("The script is called:", script) print ("Your first variable is:", first) print ("Your second variable is:", second) print ("Your third variable is:", third) main(input()) Answer: If you're trying to get arguments from the command line, `main` doesn't need a parameter, and you don't need to call `input`. You're merely overwriting `sys.argv` when you do that. from sys import argv def main(): script, first, second, third = argv print ("The script is called:", script) print ("Your first variable is:", first) print ("Your second variable is:", second) print ("Your third variable is:", third) main() Result: C:\Users\kevin\programs>py -3 test.py hurf durf klurf The script is called: test.py Your first variable is: hurf Your second variable is: durf Your third variable is: klurf * * * Alternatively, if you really _do_ want to get information from `input`, and you just got confused reading about argv, then you can use `split` to get words from the input string rather than letters. Of course, you can't get the script's name this way. def main(data): script, first, second, third = data.split() print ("The script is called:", script) print ("Your first variable is:", first) print ("Your second variable is:", second) print ("Your third variable is:", third) main(input("Enter some data: ")) Result: Enter some data: hello how are you? The script is called: hello Your first variable is: how Your second variable is: are Your third variable is: you?
Python: Difficulties with converting negative strings numbers into floats Question: I have been trying to figure this out for hours now. I have this list that I need converted to a float so I can use it in `numpy.corrceof()` along with another identical list. The list, `r` is as follows: >>> print r [-0.6680161943319838, -0.7236994219653179, -0.7088915956151035, -0.7388949079089924, -0.7149712092130518, -0.6123110151187905, -0.39853300733496333, -0.017366136034732287, -0.1457800511508952, 0.03546099290780142, 0.0319573901464714, 0.3491027732463295, 0.03203342618384407, 0.2081005586592179, 0.014833127317676267, 0.32045779685264664, 0.31069182389937106, -0.06653225806451614, -0.15583075335397314, -0.2147727272727273, 0.03030303030303036, -0.10076530612244898, -0.2888257575757576, 0.1227106227106227, 0.7095238095238093, 2.808510638297873, 3.7588235294117647, 3.4240506329113924, 4.264900662251656, 5.1234567901234565, 6.34090909090909, 5.666666666666667, 4.163265306122449, 3.611764705882353, 5.439024390243903, 1.9197860962566844, 1.1649484536082475, -0.04081632653061228, -0.17874396135265697, -0.20999999999999996, -0.277511961722488, -0.20197044334975356, -0.2189349112426035, 0.2222222222222222, 0.4134615384615384, 0.47826086956521746, 0.23308270676691714, 0.6120689655172415, 0.9795918367346939, 1.0851063829787235, 1.0294117647058822, 0.6666666666666667, 1.1546391752577319, 1.2065217391304346, 0.69, 0.10204081632653071, -0.009523809523809532, -0.16666666666666666, -0.14193548387096772, -0.24675324675324684, -0.16949152542372878, -0.276923076923077, 0.020000000000000018, 0.7142857142857143, -0.5446009389671361, -0.7401129943502825, -0.7858672376873662, -0.8171641791044777, -0.8, -0.7320388349514564, -0.7327586206896552, -0.7555555555555555, -0.8284883720930233, -0.7833333333333333, -0.8144712430426716, -0.8809523809523809, -0.6120218579234973, -0.33831775700934574, -0.2203672787979967, -0.08688245315161836, -0.19230769230769232, 0.030000000000000072, 0.13725490196078435, 0.24752475247524752, 0.4012219959266802, 0.22448979591836726, 0.19777777777777772, 0.3213483146067415, 0.30714285714285716, 0.5735294117647058, 0.8151515151515153, 0.834375, 1.3636363636363635, 0.7301038062283737, 0.5692307692307691, 0.3015463917525773, 0.6098360655737707, 0.4202898550724638, 0.0975609756097562, 0.6360294117647058, 0.9090909090909091, 0.36, 0.5865384615384615, 0.787709497206704, 1.5943396226415094, 1.7264150943396226, 2.25, 2.88, 1.9901960784313724] >>> type(r) <type 'str'> >>> print len(r) 2169 When I try to perform `float(r)`: >>> float(r) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: could not convert string to float: [-0.6680161943319838, -0.7236994219653179, -0.7088915956151035, -0.7388949079089924, -0.7149712092130518, -0.6123110151187905, -0.39853300733496333, -0.017366136034732287, -0.1457800511508952, 0.03546 From previous questions, I have seen that empty values `""` could cause the issue. However I have no idea why there would be an empty value in the list. Even at that, I've tried numerous methods from other questions, like converting the `list` to an `numpy.array`, then using `s = r[r=='']='0'`. However this _still_ does not work. Anyone have any tips? # Bonus: Why is `len(r)` `== 2169?` The code I run to build the list only makes lists of exactly `121` values. If you actually count the list, there are 121 values there... Can anyone explain this? Answer: The string is a JSON string representing a list of floats. import json data = json.loads(r)
Install mysql in dockerfile? Question: I want to write simple python application and put in docker conteiner with dockerfile. My dockerfile is: FROM ubuntu:saucy # Install required packages RUN apt-get update RUN DEBIAN_FRONTEND=noninteractive apt-get -y install python RUN DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server python-mysqldb # Add our python app code to the image RUN mkdir -p /app ADD . /app WORKDIR /app # Set the default command to execute CMD ["python", "main.py"] In my python application I only want to connect to the database. main.py look something like this: import MySQLdb as db connection = db.connect( host='localhost', port=3306, user='root', passwd='password', ) When I built docker image with: docker build -t myapp . and run docker image with: docker run -i myapp I got error: _mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") What is the problem? Answer: The problem is that you've never started the database - you need to explicitly start services in most Docker images. But if you want to run two processes in Docker (the DB and your python program), things get a little more complex. You either have to use a process manager like supervisor, or be a bit cleverer in your start-up script. To see what I mean, create the following script, and call it `cmd.sh`: #!/bin/bash mysqld & python main.py Add it to the Dockerfile: FROM ubuntu:saucy # Install required packages RUN apt-get update RUN DEBIAN_FRONTEND=noninteractive apt-get -y install python RUN DEBIAN_FRONTEND=noninteractive apt-get -y install mysql-server python-mysqldb # Add our python app code to the image RUN mkdir -p /app ADD . /app WORKDIR /app # Set the default command to execute COPY cmd.sh /cmd.sh RUN chmod +x /cmd.sh CMD cmd.sh Now build and try again. (Apologies if this doesn't work, it's off the top of my head and I haven't tested it). Note that this is _not_ a good solution; mysql will not be getting signals proxied to it, so probably won't shutdown properly when the container stops. You could fix this by using a process manager like supervisor, but the easiest and best solution is to use separate containers. You can find stock containers for [mysql](https://registry.hub.docker.com/_/mysql/) and also for [python](https://registry.hub.docker.com/_/python/), which would save you a lot of trouble. To do this: 1. Take the mysql installation stuff out of the Dockerfile 2. Change `localhost` in your python code to `mysql` or whatever you want to call your MySQL container. 3. Start a MySQL container with something like `docker run -d --name mysql mysql` 4. Start your container and link to the mysql container e.g: `docker run myapp --link mysql:mysql`
How to scrape a page with BeautifulSoup and Python? Question: I am trying to extract information from the BBC Good Food website, but I am having some trouble narrowing down the data I'm collecting. Here's what I have so far: from bs4 import BeautifulSoup import requests webpage = requests.get('http://www.bbcgoodfood.com/search/recipes?query=tomato') soup = BeautifulSoup(webpage.content) links = soup.find_all("a") for anchor in links: print(anchor.get('href')), anchor.text This returns all the links from the page in question plus a text description of the link, but I want to extract the links from the 'article' type objects on the page. These are the links to the specific recipes. Through some experimentation I have managed to return the text from the articles, but I can't seem to extract the links. Answer: The only two things I see related to the article tags are the the href and img.src: from bs4 import BeautifulSoup import requests webpage = requests.get('http://www.bbcgoodfood.com/search/recipes?query=tomato') soup = BeautifulSoup(webpage.content) links = soup.find_all("article") for ele in links: print(ele.a["href"]) print(ele.img["src"]) The links are in `"class=node-title"` from bs4 import BeautifulSoup import requests webpage = requests.get('http://www.bbcgoodfood.com/search/recipes?query=tomato') soup = BeautifulSoup(webpage.content) links = soup.find("div",{"class":"main row grid-padding"}).find_all("h2",{"class":"node-title"}) for l in links: print(l.a["href"]) /recipes/681646/tomato-tart /recipes/4468/stuffed-tomatoes /recipes/1641/charred-tomatoes /recipes/tomato-confit /recipes/1575635/roast-tomatoes /recipes/2536638/tomato-passata /recipes/2518/cherry-tomatoes /recipes/681653/stuffed-tomatoes /recipes/2852676/tomato-sauce /recipes/2075/tomato-soup /recipes/339605/tomato-sauce /recipes/2130/essence-of-tomatoes- /recipes/2942/tomato-tarts /recipes/741638/fried-green-tomatoes-with-ripe-tomato-salsa /recipes/3509/honey-and-thyme-tomatoes To access you need to prepend `http://www.bbcgoodfood.com`: for l in links: print(requests.get("http://www.bbcgoodfood.com{}".format(l.a["href"])).status 200 200 200 200 200 200 200 200 200 200
Canonical name for every Unicode character Question: >>> from unicodedata import name, lookup >>> name('a') 'LATIN SMALL LETTER A' >>> name('☃') 'SNOWMAN' >>> name('A') 'LATIN CAPITAL LETTER A' >>> name('`') 'GRAVE ACCENT' >>> name('☹') 'WHITE FROWNING FACE' >>> name('☺') 'WHITE SMILING FACE' I know that Unicode is the correspondence between characters and Integers. UTF-8 is the correspondence between numbers and bytes. Python follows UTF-8 encoding. But, What is the usage of canonical name in programming? Is it specific to python? U+263a WHITE SMILING FACE U+2639 WHITE FROWNING FACE Answer: No, it is not specific to Python. Those are the names given to the code points by the Unicode standard.
"SyntaxError: invalid syntax" in Python Question: I have installed odoo in my server that has Python 2.7.9. When I try to launch the daemon, I get this error: root@des [/opt/odoo/openerp]# /etc/init.d/odoo start Starting Odoo Server Daemon (odoo-server): [ OK ] root@des [/opt/odoo/openerp]# 'import site' failed; use -v for traceback Traceback (most recent call last): File "/opt/odoo/openerp-server", line 2, in ? import openerp File "/opt/odoo/openerp/__init__.py", line 90 from . import models ^ SyntaxError: invalid syntax This is Python information: root@des [/opt/odoo/openerp]# python Python 2.7.9 (default, Apr 2 2015, 20:06:47) [GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> And this is my environment: root@des [/opt/odoo/openerp]# uname -a Linux des.desytec.com 2.6.32-042stab104.1 #1 SMP Thu Jan 29 12:58:41 MSK 2015 x86_64 x86_64 x86_64 GNU/Linux EDIT: Thanks to Tevfik answer, I have solved the error, however, now a syntax error is produced in Python libraries. How is this possible and hot can I solve it? root@des [/usr/local/lib/python2.7]# /etc/init.d/odoo start Starting Odoo Server Daemon (odoo-server): [ OK ] root@des [/usr/local/lib/python2.7]# 'import site' failed; use -v for traceback Traceback (most recent call last): File "/opt/odoo/openerp-server", line 2, in ? import openerp File "/opt/odoo/openerp/__init__.py", line 47, in ? import os File "/usr/local/lib/python2.7/os.py", line 49, in ? import posixpath as path File "/usr/local/lib/python2.7/posixpath.py", line 339 slash, dot = (u'/', u'.') if isinstance(path, _unicode) else ('/', '.') ^ SyntaxError: invalid syntax root@des [/usr/local/lib/python2.7]# Any help will be appreciated Thanks Jaime Answer: try this syntax from «app_name».models import *
Python 2.7 - Find the number of web server hits Question: I am trying to compute the number of hits to a web server per calendar month (Dec, Jan, Feb, ..) by Year. I am very new to Python so I don't even know where to begin. I suppose you have to use some string split or regexp. I am given a log file with the following output: [31/Dec/1994:23:55:08 -0700] "GET 45.html HTTP/1.0" 200 5489 remote - - [31/Dec/1994:23:56:55 -0700] "GET 2195.ps HTTP/1.0" 200 522318 remote - - [31/Dec/1994:23:59:37 -0700] "GET 957.ps HTTP/1.0" 200 122146 remote - - [01/Jan/1995:00:31:54 -0700] "GET index.html HTTP/1.0" 200 2797 remote - - [01/Jan/1995:00:31:58 -0700] "GET 2.gif HTTP/1.0" 200 2555 remote - - [01/Jan/1995:00:32:33 -0700] "GET 3.gif HTTP/1.0" 200 36403 remote - - [01/Jan/1995:01:39:21 -0700] "GET 20.html HTTP/1.0" 200 378 local - - [01/Jan/1995:01:47:41 -0700] "GET index.html HTTP/1.0" 200 2797 local - - [01/Jan/1995:01:47:49 -0700] "GET 39.html HTTP/1.0" 200 669 local - - Answer: Splitting is more easy (IMO) than applying the regular expressions. You can extract these values with the following function by passing in a log line: def year_month(s): try: discard, month, rest = s.split('/', 2) # split twice on '/' except ValueError: return None # for last line without / year = rest.split(':', 1)[0] year = int(year) # optional return year, month You can use the returned tuple from this function as a key to some dictionary: d = {} for line in open('yourfile'): ym = year_month(line) if ym is None: continue x = d.setdefault(ym, [0]) x[0] += 1 for ym in sorted(d): print('Year: {0}, Month: {1}, Hits: {2}'.format(ym[0], ym[1], d[ym][0])) If you want to use regular expressions you can replace the `year_month()` part with: import re # see https://docs.python.org/2/howto/regex.html year_month_pattern = re.compile(r""" .*/ (?P<month>.*) / (?P<year>\d*) :.* """, re.VERBOSE) def year_month(s): res = year_month_pattern.match(s) if res is None: return None try: return int(res.group('year')), res.group('month') except ValueError: pass
Python multiprocessing pool map with multiple arguments Question: I have a function to be called from multiprocessing pool.map with multiple arguments. from multiprocessing import Pool import time def printed(num,num2): print 'here now ' return num class A(object): def __init__(self): self.pool = Pool(8) def callme(self): print self.pool.map(printed,(1,2),(3,4)) if __name__ == '__main__': aa = A() aa.callme() but it gives me following error TypeError: printed() takes exactly 2 arguments (1 given) I have tried solutions from other answers here but they are not working for me. How can i resolve it and what is the reason for this problem (I did not get the pickle POV) Answer: You should be giving args in array from multiprocessing import Pool import time def printed(*args): print 'here now ' return args[0][0] class A(object): def __init__(self): self.pool = Pool(8) def callme(self): print self.pool.map(printed,[(1,2),(3,4)]) if __name__ == '__main__': aa = A() aa.callme()
tempfile is not accessible when using subprocess.Popen Question: When I run the following script, the error"Command line argument error: Argument "query". File is not accessible" occurs. I'm using python 3.4.2. from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord import subprocess import tempfile import sys def main(): # read name file and put all identifications into a list infile_I = open('OTU_name.txt','r') name = infile_I.read().split('>') infile_I.close() # extract sequence segments to a temporary file one at a time for i in name: i = i.replace('\n','') for j in SeqIO.parse("GemSIM_OTU_ids.fa","fasta"): if str(i) == str(j.id): f = tempfile.NamedTemporaryFile() record = j.seq f.write(bytes(str(record),'UTF-8')) f.seek(0) f = f.read().decode() Result = subprocess.Popen(['blastn','-remote','-db','chromosome','-query',f,'-out',str(i)],stdout=subprocess.PIPE) output = Result.communicate()[0] if __name__== '__main__': main() Answer: `f = tempfile.NamedTemporaryFile()` returns a file-like object which you're trying to provide as a command line argument. Instead, you want the _actual filename_ which is available via its `.name` attribute - although I'm somewhat confused why you're creating a tempfile, writing to it, seeking back to position 0, then replacing your tempfile `f` object with the contents of the file? I suspect you don't want to do that replacement and use `f.name` for your query. Result = subprocess.Popen(['blastn','-remote','-db','chromosome','-query',f.name,'-out',str(i)],stdout=subprocess.PIPE) Also, there's some convenient wrapper functions around `subprocess.Popen` such as [subprocess.check_output](https://docs.python.org/3/library/subprocess.html#subprocess.check_output) which are also somewhat more explicit as to your intent which could be used here instead.
Questions about Heroku and Django settings Question: I have tried many, many times to get my apps running on Heroku without success. The fact that they run locally seems to be totally irrelevant. Clearly I don’t understand how this works. So … here are a couple of questions, which I've decided to group to gether in a single question on SO: **1.** Why does Heroku have so many different places that influence the settings (Procfile, wsgi.py, config vars, and settings.py)? **2.** How do they relate to one another? **3.** Which has precedence? **4.** Do they all have to be exactly the same? **5.** What am I supposed to do with / how am I supposed to configure the database settings given in the Heroku Django template? > 78. # Parse database configuration from $DATABASE_URL > 79. DATABASES['default'] = dj_database_url.config() > 80. # this line blank in original. I put text here to make it format > correctly > 81. # Enable Connection Pooling (if desired) > 82. DATABASES['default']['ENGINE'] = 'django_postgrespool' > **a)** Doesn’t DATABASE [‘ENGINE’], coming after DATABASE [default] overwrite DATABASE [default]? **b)** Why aren’t these two in the same format as the default Django settings, which is a simple dictionary, instead of all these extra and confusing brackets? **c)** Are they supposed to be treated as two different settings, so that you have to use database routers if you want both? **d)** Why does the [devcenter article](https://devcenter.heroku.com/articles/python-concurrency-and- database-connections) say to import postgrespool but the [template](https://github.com/heroku/heroku-django-template) says nothing about that? **e)** Why is ‘default’ [optional](https://github.com/kennethreitz/dj- database-url) with dj_database_url but [mandatory](https://docs.djangoproject.com/en/1.7/ref/settings/#databases) with Django? **f)** When I tried commenting out line 82, I got an error about resetting queries, why? **g)** I have the postgres string from my config vars as the argument to dj_database_url, but I get a NAME ERROR, database undefined. Why? Answer: You're making this much much much more difficult than it actually is. All `dj_database_url` does is use an environment variable to create a dictionary suitable for use in the DATABASES setting. It doesn't do anything else. The devcenter article you link to mentions processpool as a way of increasing concurrency. It doesn't say or even hint that you need it when you're starting out. There is no reason for you to even be reading that article at this point. The only article you need to read is the [Getting started with Django](https://devcenter.heroku.com/articles/getting-started-with-django) one, which tells you _exactly_ what to do.
Some readble content, but impossible to JSON dump to file Question: This [text file](http://gget.it/3hgi8uyu/temp.txt) (30 bytes only, the content is `'(Ne pas r\xe9pondre a ce message)'`) can be opened and inserted in a `dict` successfully : import json d = {} with open('temp.txt', 'r') as f: d['blah'] = f.read() with open('test.txt', 'w') as f: data = json.dumps(d) f.write(data) But it is impossible to dump the `dict` into a JSON file (see traceback below). Why? I tried lots of solutions provided by various SO questions. The closest solution I could get was [this answer](http://stackoverflow.com/a/25122834/1422096). When using this, I can dump to file, but then the JSON file looks like this: # test.txt {"blah": "(Ne pas r\u00e9pondre a ce message)"} instead of # test.txt {"blah": "(Ne pas répondre a ce message)"} Traceback: File "C:\Python27\lib\json\encoder.py", line 270, in iterencode return _iterencode(o, 0) UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 9: invalid continuation byte [Finished in 0.1s with exit code 1] Answer: Your file is not UTF-8 encoded. It uses a _Latin_ codec, like ISO-8859-1 or Windows Codepage 1252. Reading the file gives you the _encoded_ text. JSON however requires _Unicode_ text. Python has a separate Unicode type, and byte strings (type `str`) need to be decoded using a suitable codec. The `json.dumps()` function uses UTF-8 by default; UTF-8 is a widely used codec for encoding Unicode text data that can handle all codepoints in the standard, and is also the default codec for JSON strings to use. You need to either decode the string manually or tell `json.dumps()` what codec to use for the byte string: data = json.dumps(d, encoding='latin1') # applies to all bytestrings in d or d['blah'] = d['blah'].decode('latin1') data = json.dumps(d) or using `io.open()` to decode as you read: import io with io.open('test.txt', 'w', encoding='latin1') as f: d['blah'] = f.read() By default, the `json` library produces ASCII-safe JSON output by using the `\uhhhh` escape syntax the JSON standard allows for. _This is entirely normal_ , the output is valid JSON and readable by any compliant JSON decoder. If you _must_ produce UTF-8 encoded output without the `\uhhhh` escape sequences, see [Saving utf-8 texts in json.dumps as UTF8, not as \u escape sequence](https://stackoverflow.com/questions/18337407/saving-utf-8-texts-in- json-dumps-as-utf8-not-as-u-escape-sequence)
How to fix my csv output to make it useable? Question: This might be very easy to fix but I am new to Python, and new to programming. Using BS4 I have managed to, with help, get this code together. It fetches all the information I want it to fetch but the output is not very usable. Here is the code: import requests from bs4 import BeautifulSoup import StringIO import unicodecsv as csv for numb in range(1, 2): urls= "http://www.blocket.se/bostad/uthyres?cg_multi=3020&cg_multi=3100&cg_multi=3120&cg_multi=3060&cg_multi=3070&sort=&ss=&se=&ros=&roe=&bs=&be=&mre=&q=&q=&q=&save_search=1&l=0&md=th&o=" +str(numb) +"&f=p&f=c&f=b&ca=11&w=3" r = requests.get(urls) soup=BeautifulSoup(r.text, 'html.parser') data = soup.find_all("div", {"itemtype": "http://schema.org/Offer"}) data_list = [] for item in data: data_item = {} try: data_item['category'] = item.contents[3].find_all("span", {"class": "subject-param category"})[0].text except: data_item['category']= 'NaN' try: data_item['address'] = item.contents[3].find_all("span", {"class": "subject-param address separator"})[0].text except: data_item['address']= 'NaN' try: data_item['rooms'] = item.contents[3].find_all("span", {"class": "li_detail_params first rooms"})[0].text except: data_item['rooms']= 'NaN' try: data_item['monthly_rent'] = item.contents[3].find_all("span", {"class": "li_detail_params monthly_rent"})[0].text except: data_item['monthly_rent']= 'NaN' try: data_item['size'] = item.contents[3].find_all("span", {"class": "li_detail_params size"})[0].text except: data_item['size']= 'NaN' try: data_item['weekly_rent_offseason'] = item.contents[3].find_all("span", {"class": "li_detail_params first weekly_rent_offseason"})[0].text except: data_item['weekly_rent_offseason']= 'NaN' try: data_item['time'] = item.contents[3].find_all("time", {"class": "jlist_date_image"})[0].text except: data_item['time']= 'NaN' data_list.append(data_item) out = StringIO.StringIO() csv_writer = csv.writer(out) [csv_writer.writerow(data.values()) for data in data_list] print out.getvalue() And here is a sample of what it outputs: lägenhet ",3 800 kr/mån,Idag 13:58,1 rum,NaN," Stockholms stad - Älvsjö, Farsta, Vantör ",NaN " radhus ",4 700 kr/mån,Idag 13:47,1 rum,NaN," Stockholms stad - Kista, Hässelby, Vällingby, Spånga ",NaN " villa ",NaN,Idag 13:46,8 rum,NaN," Vellinge ",250 m² " lägenhet ",6 000 kr/mån,Idag 13:41,1 rum,NaN," Stockholms stad - Kista, Hässelby, Vällingby, Spånga ",25 m² " lägenhet ",3 500 kr/mån,Idag 13:40,1 rum,NaN," Örebro ",NaN Which corresponds to: category ",monthlyrent,time,rooms,weekly_rent_offseason," address ",size I would like it to read something like (the order is not important): category, address, size, monthly_rent, rooms, time, weekly_rent_offseason Is this possible? Here is the content of `data_list` : >>> print data_list [{'category': u'\n\t\t\tl\xe4genhet\n\t\t', 'monthly_rent': u'11 500 kr/m\xe5n', 'time': u'Ig\xe5r 21:32', 'rooms': u'2 rum', 'weekly_rent_offseason': 'NaN', 'address': u'\n\t\t\t\tStockholms stad - H\xe4gersten, Liljeholmen\n\t\t\t\t\n\t\t\t\t', 'size': u'60 m\xb2'}, {'category': u'\n\t\t\tradhus\n\t\t', 'monthly_rent': 'NaN', 'time': u'Ig\xe5r 21:32', 'rooms': u'4 rum', 'weekly_rent_offseason': 'NaN', 'address': u'\n\t\t\t\tBorgholm\n\t\t\t\t\n\t\t\t\t', 'size': u'125 m\xb2'}, ... Answer: You need to strip your strings, and you can use [`csv.DictWriter()`](https://docs.python.org/2/library/csv.html#csv.DictWriter) to write dictionaries in a specific order to an output file. Refactoring your code to use more a more Pythonic approach and all the Schema.org item properties offered: for numb in range(1): params = { 'cg_multi': [3020, 3100, 3120, 3060, 3070], 'save_search': 1, 'l': 0, 'md': 'th', 'ca': 11, 'w': 3, 'f': ['p', 'c', 'b'], 'o': numb + 1, } url = "http://www.blocket.se/bostad/uthyres" r = requests.get(url, params=params) soup = BeautifulSoup(r.content, 'html.parser') # All your entries live in the itemOffered div data = soup.select('div[itemtype=http://schema.org/Offer] div[itemprop=itemOffered]') out = StringIO.StringIO() fields = ('category', 'address', 'size', 'monthly_rent', 'rooms', 'time', 'weekly_rent_offseason') csv_writer = csv.DictWriter(out, fieldnames=fields) for entry in data: row = {} for field in fields: if field == 'time': time_elem = entry.find('time') value = (time_elem or {}).get('datetime', 'NaN') else: span_elem = entry.find(class_=field) value = span_elem.text.strip() if span_elem else 'NaN' row[field] = value csv_writer.writerow(row) print out.getvalue() Note that the `data` variable already selects the `itemprop="itemOffer"` div elements, rather than having to navigate to `.contents[3]` each time. I also opted to extract the `datetime` attribute for the `<time>` elements rather than use the 'human readable' relative time version in the visible text; having the actual date and time is more useful when extracting than _today_. This produces: lägenhet,Sundsvall,170 m²,NaN,7 rum,2015-04-03 14:43:34,NaN radhus,Gotland,66 m²,NaN,2 rum,2015-04-03 14:43:15,NaN lägenhet,Gävle,12 m²,3 200 kr/mån,1 rum,2015-04-03 14:34:46,NaN lägenhet,Sundbyberg,30 m²,4 500 kr/mån,1 rum,2015-04-03 14:29:07,NaN villa,Österåker,9 m²,3 500 kr/mån,1 rum,2015-04-03 14:25:28,NaN villa,Söderköping,75 m²,2 700 kr/mån,3 rum,2015-04-03 14:00:25,NaN lägenhet,"Stockholms stad - Älvsjö, Farsta, Vantör",NaN,3 800 kr/mån,1 rum,2015-04-03 13:58:22,NaN radhus,"Stockholms stad - Kista, Hässelby, Vällingby, Spånga",NaN,4 700 kr/mån,1 rum,2015-04-03 13:47:37,NaN villa,Vellinge,250 m²,NaN,8 rum,2015-04-03 13:46:35,NaN lägenhet,"Stockholms stad - Kista, Hässelby, Vällingby, Spånga",25 m²,6 000 kr/mån,1 rum,2015-04-03 13:41:42,NaN lägenhet,Örebro,NaN,3 500 kr/mån,1 rum,2015-04-03 13:40:02,NaN lägenhet,Helsingborg,10 m²,3 000 kr/mån,1 rum,2015-04-03 13:29:44,NaN villa,Vingåker,140 m²,7 500 kr/mån,4 rum,2015-04-03 13:27:53,NaN villa,Svalöv,200 m²,9 800 kr/mån,5 rum,2015-04-03 13:26:38,NaN lägenhet,Sigtuna,49.5 m²,6 000 kr/mån,1 rum,2015-04-03 13:24:49,NaN lägenhet,Kristianstad,NaN,NaN,1 rum,2015-04-03 13:14:14,NaN villa,Stockholms stad - Bromma,125 m²,25 000 kr/mån,4 rum,2015-04-03 13:13:34,NaN lägenhet,Oskarshamn,18 m²,3 000 kr/mån,1 rum,2015-04-03 13:05:50,NaN villa,Göteborgs stad - Västra Göteborg,10 m²,NaN,1 rum,2015-04-03 13:02:07,NaN gård,Sala,140 m²,NaN,7 rum,2015-04-03 13:00:34,NaN lägenhet,"Stockholms stad - Vasastan, Norrmalm",36 m²,14 900 kr/mån,"1,5 rum",2015-04-03 12:57:55,NaN lägenhet,Solna,60 m²,12 500 kr/mån,2 rum,2015-04-03 12:48:57,NaN lägenhet,Danderyd,50 m²,11 000 kr/mån,1 rum,2015-04-03 12:46:05,NaN lägenhet,Luleå,80 m²,6 500 kr/mån,3 rum,2015-04-03 12:45:03,NaN villa,Söderhamn,172 m²,NaN,6 rum,2015-04-03 12:42:33,NaN lägenhet,"Stockholms stad - Enskede, Årsta, Skarpnäck",51 m²,14 000 kr/mån,2 rum,2015-04-03 12:39:09,NaN lägenhet,Umeå,13 m²,2 400 kr/mån,1 rum,2015-04-03 12:37:43,NaN lägenhet,Linköping,65 m²,6 300 kr/mån,2 rum,2015-04-03 12:36:02,NaN lägenhet,Botkyrka,58.5 m²,NaN,2 rum,2015-04-03 12:34:11,NaN lägenhet,Upplands Väsby,80 m²,5 000 kr/mån,3 rum,2015-04-03 12:32:21,NaN lägenhet,Strömsund,105 m²,4 000 kr/mån,3 rum,2015-04-03 12:32:21,NaN lägenhet,Lund,86 m²,6 500 kr/mån,3 rum,2015-04-03 12:32:18,NaN lägenhet,Uppsala,68 m²,6 000 kr/mån,2 rum,2015-04-03 12:28:13,NaN lägenhet,"Stockholms stad - Maria, Gamla Stan, Högalid",NaN,25 000 kr/mån,2 rum,2015-04-03 12:24:45,NaN lägenhet,Halmstad,21 m²,3 300 kr/mån,1 rum,2015-04-03 12:21:28,NaN lägenhet,Uppsala,40 m²,5 000 kr/mån,2 rum,2015-04-03 12:20:40,NaN lägenhet,Uppsala,92 m²,NaN,3 rum,2015-04-03 12:17:53,NaN lägenhet,Eskilstuna,NaN,NaN,1 rum,2015-04-03 11:48:42,NaN lägenhet,Helsingborg,66 m²,7 350 kr/mån,3 rum,2015-04-03 11:44:17,NaN villa,Göteborgs stad - Hisingen,110 m²,9 500 kr/mån,4 rum,2015-04-03 11:43:30,NaN lägenhet,Göteborgs stad - Västra Göteborg,53 m²,10 000 kr/mån,"2,5 rum",2015-04-03 11:20:36,NaN lägenhet,"Stockholms stad - Kista, Hässelby, Vällingby, Spånga",NaN,4 900 kr/mån,1 rum,2015-04-03 11:17:11,NaN lägenhet,"Stockholms stad - Hägersten, Liljeholmen",55 m²,12 500 kr/mån,2 rum,2015-04-03 11:16:07,NaN lägenhet,Örebro,70 m²,4 000 kr/mån,3 rum,2015-04-03 11:15:02,NaN lägenhet,Linköping,"46,5 m²",NaN,1 rum,2015-04-03 11:13:13,NaN lägenhet,Kristinehamn,34 m²,3 600 kr/mån,"1,5 rum",2015-04-03 11:09:05,NaN lägenhet,Jönköping,NaN,NaN,1 rum,2015-04-03 11:02:07,NaN lägenhet,Göteborgs stad - Innerstaden,42 m²,7 000 kr/mån,1 rum,2015-04-03 10:47:58,NaN lägenhet,Umeå,70 m²,NaN,4 rum,2015-04-03 10:39:31,NaN lägenhet,Göteborgs stad - Västra Centrum,55 m²,7 000 kr/mån,2 rum,2015-04-03 10:16:53,NaN
Having trouble killing linux processes Question: I'm trying to restart celery after code changes by following [How to restart Celery gracefully without delaying tasks](http://stackoverflow.com/questions/9642669/how-to-restart-celery- gracefully-without-delaying-tasks). Based on this I ran: (env1)ubuntu@ip-172-31-22-65:~/projects/tp$ ps aux|grep "celery" ubuntu 2701 0.3 3.7 107788 37904 ? S 12:17 0:00 /home/ubuntu/.virtualenvs/env1/bin/python3.4 /home/ubuntu/.virtualenvs/env1/bin/celery --app=tp.celery:app worker --loglevel=INFO ubuntu 2705 0.0 3.3 107120 34132 ? S 12:17 0:00 /home/ubuntu/.virtualenvs/env1/bin/python3.4 /home/ubuntu/.virtualenvs/env1/bin/celery --app=tp.celery:app worker --loglevel=INFO ubuntu 2716 0.0 0.0 10460 932 pts/0 S+ 12:20 0:00 grep --color=auto celery (env1)ubuntu@ip-172-31-22-65:~/projects/tp$ sudo kill -9 2701 2705 (env1)ubuntu@ip-172-31-22-65:~/projects/tp$ ps aux|grep "celery" ubuntu 2720 16.3 3.7 107796 37908 ? S 12:25 0:00 /home/ubuntu/.virtualenvs/env1/bin/python3.4 /home/ubuntu/.virtualenvs/env1/bin/celery --app=tp.celery:app worker --loglevel=INFO ubuntu 2724 0.0 3.3 107144 34084 ? S 12:25 0:00 /home/ubuntu/.virtualenvs/env1/bin/python3.4 /home/ubuntu/.virtualenvs/env1/bin/celery --app=tp.celery:app worker --loglevel=INFO ubuntu 2726 0.0 0.0 10460 932 pts/0 S+ 12:25 0:00 grep --color=auto celery I don't understand what is going on here. It seems like 2 new celery worker processes appear after I kill the first 2. What am I doing wrong? Answer: I see no evidence you're doing anything wrong. Celery is a collection of processes. The most important is a supervisor that keeps some number of workers ready to answer a request. The worker is disposable, but the supervisor can't tell what a worker is doing. When a worker exits, the supervisor gets a signal and starts up a new one. That's it. If you change the configuration, the supervisor can re-configure itself (IF you have it so configured!), but the workers aren't watching that configuration. They get configured only when they're born. What you're doing with "kill" is killing those workers, and expecting the replacement workers to have the settings you want when they're born. Asking the supervisor to stop itself and workers, and then reload, and start again, can leave several seconds where no requests get answered. That's the benefit, as far as I know, over `supervisorctl`. So, there's nothing obviously wrong with anything you've told us. Of course you should expect the workers to be replaced.
Recompose a table from an SQL with row and colum ID in Python Question: I'm reading from an SQLite table created by a program I have no control on. The idea behind the layout of this SQL table eludes me, but that's the way it is. This table looks like this in SQL: ![SQL Table](http://i.stack.imgur.com/iKpnt.jpg) What it really is, and what I'd like to get in python-pandas dataframe is this: ![Equivalent HTML table](http://i.stack.imgur.com/vaJbh.jpg) So far, this only way I can think of doing this is by getting a list of RowID, looping on them, and reconstructing the table. But I'm wondering if there's an easier and faster way (database is huge), either when doing the SELECT statement or later on the pandas dataframe itself. To load the data I'm using: import pandas as pd import sqlite3 con = sqlite3.connect(sql_path) #Simplified here, to produce the Table I filter on a few things df = pd.read_sql('SELECT * from Table',con=con, index_col='RowID') I've desperately tried and failed to use a bunch of stuff including pd.pivot or pd.groupby but it might just be because I don't know how to use it properly. Version: > Python: 2.7.8 | Pandas: 0.16.0 | sqlite3: 2.6.0 Answer: Just set the index and unstack. You can use 'rowid' instead of 'rowname' or include both in the index if you don't want to leave either one out, but it's redundant as far as the solution. df = pd.DataFrame({ 'rowname':[1,1,2,2], 'colname':[1,2,1,2], 'values':['a11','a12','a21','a22'] }) df colname rowname values 0 1 1 a11 1 2 1 a12 2 1 2 a21 3 2 2 a22 df.set_index(['rowname','colname']).unstack() values colname 1 2 rowname 1 a11 a12 2 a21 a22
Get realtime output from python subprocess Question: I'm trying to invoke a command line utility from Python. The code is as follows import subprocess import sys class Executor : def executeEXE(self,executable ) : CREATE_NO_WINDOW = 0x08000000 process = subprocess.Popen(executable, stdout=subprocess.PIPE, creationflags=CREATE_NO_WINDOW ) while True: line = process.stdout.readline() if line == '' and process.poll() != None: break print line The problem with above code is I want real time output of above process which I'm not getting. What I'm doing wrong here. I've referred 10's of articles but none seems to help. Thanks in advance. Regards, Ganesh. P. S. Command line utility I'm invoking is Star Wind V2V (if some how that matters) Answer: there are 2 problems in your code: 1. first of all, readline() will block untill when a new line is printed out and flushed. That means you should execute the code while True: ... in a new Thread and call a callback function when the output is ready. 2. Since the readline is waiting for a new line, you must use print 'Hello World' sys.stdout.flush() everytime in your executable. You can see some code and example on my git: [pyCommunicator](https://github.com/jstar88/pyCommunicator) Instead, if your external tool is buffered, the only thing you can try is to use stderr as PIPE: <http://stackoverflow.com/a/11902799/2054758>
Issue with docker compose Question: The issue I am having is that after I try and run docker-compose up, after everything is downloaded(python dependencies) docker-compose will just hang on Recreating sensorarray_web_1... Attaching to sensorarray_web_1 My directory structure looks like like this: . ├── docker-compose.yml ├── Dockerfile ├── requirements.txt └── sensoryarray.py Dockerfile: FROM python:2.7 WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code CMD python sensorarray.py docker-compose.yml web: build: . command: python sensorarray.py ports: - "5000:5000" volumes: - .:/code sensoryarray.py: from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello World!' if __name__ == "__main__": app.run(host="0.0.0.0", debug=True) I also ran the docker hello world example and it seems to be working fine. Answer: So I figured I would try updating this evening to the latest docker-composer (1.2.0) and everything just kind of started working. I am still not sure what the problem was. However if someone lands on this page and is still running 1.1.0, I would suggest updating.
Unable to import Python module in Python script Question: I have a Python project having the following hierarchy: - product_recommender_sys - data - dataset.csv - public - __init__.py - startup.py - src - __init__.py - recommender.py I am trying to import the `recommender.py` module in `startup.py`. Following is the code: import sys sys.path.insert(0, '/home/user1/product_recommender_sys/src') print sys.path from product_recommender_sys.src import recommender recommender.recommend() I have included `__init__.py` file and added the respective folders to `sys.path`. Also, the same `import` statement works perfectly fine on the Python interpreter, but fails inside the script. How can I get the import to work inside the script? Answer: I found the issue. The startup.py module was not getting compiled since it was not being imported. First compiling the script solves the problem. python -m compileall product_recommender_sys/public/startup.py
How to split comma delimited data and create a list from the data in python? Question: I am trying to create a function that takes in two dates in YYYY/MM/DD format, reads through the data, and returns a list of lists containing the latitude, longitude, magnitude, and depth for the quakes between the two dates. The data is in this format: Date,TimeUTC,Latitude,Longitude,Magnitude,Depth 2012/02/23,08:09:13.0,-20.984,-178.654,4.6,526 This is my attempt: from tempBetweenDates import dateLessThan import urllib.request def betweenDates(date1, date2, date3): """Determines if the first date is on the second or between the second and third date.""" date_1 = date1.split('/') date_2 = date2.split('/') date_3 = date3.split('/') if int(date_1[0]) >= int(date_2[0]) and int(date_1[1]) >= int(date_2[1]) and int(date_1[2]) >= int(date_2[2]) and dateLessThan(int(date_1[1]), int(date_1[2]), int(date_1[0]), int(date_3[1]), int(date_3[2]), int(date_3[0])) == True: return True else: return False def parseEarthquakeData(date1, date2): page = urllib.request.urlopen("http://www.choongsoo.info/teach/mcs177-sp12/projects/earthquake/earthquakeData-02-23-2012.txt") eqdata = page.readlines() dataList = [] for line in eqdata: lineSplit = line.split(',') date = lineSplit[0] data = lineSplit[2:6] dataList = [[data] for line in eqdata if betweenDates(date, date1, date2) == True] return(dataList) Whenever I try and run the code I get an error: Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> parseEarthquakeData("2012/02/22", "2012/02/19") File "C:\Users\lcooper2\Desktop\Python\PROJECTS\plotEarthquakes.py", line 20, in parseEarthquakeData lineSplit = line.split(',') TypeError: Type str doesn't support the buffer API Any tips on how to avoid this error? Answer: You can actually do something kind of cool with this! If you pipe your response from the `urllib.request.urlopen` call through `csv.DictReader`, you can eliminate a lot of your splitting and assigning. import csv import datetime import urllib.request page = urllib.request.urlopen("http://www.choongsoo.info/teach/mcs177-sp12/projects/earthquake/earthquakeData-02-23-2012.txt") reader = csv.DictReader((line.decode() for line in page), delimiter=',') for line in reader: # each line looks like: # {'Longitude': '-178.654', 'Date': '2012/02/23', # 'Depth': '526', 'Magnitude': '4.6', 'Latitude': '-20.984', # 'TimeUTC': '08:09:13.0'} # so you can use it like a dictionary! date = datetime.datetime.strptime(line['Date'], "%Y/%m/%d") # datetime objects like this aren't naive like numbers, so you can do: # datetime.datetime(year=2012, month=2, day=23) < datetime.datetime(year=2012, month=2, day=24) # and expect it to return True every time. This will massively simplify your # betweenDates function. The cause of the error in your traceback is that `urllib.request.urlopen` gives you an `HTTPResponse` object. That's an iterator that gives you `bytes` objects, not `string` objects. Calling `bytes.decode()` turns them into strings, so you can do stringy things with them like splitting them. If you change to using these `datetime` objects, your `betweenDates` function becomes: def between_dates(date1, date2, date3): return date2 <= date1 < date3
Why is __slots__ behaving differently in Python 2 and 3 when inheriting from an abstract base class Question: I created the following class to store changeable points on a plane in a memory-efficient manner - I need a mutable equivalent of `namedtuple('Point', 'x y')`. Since instance dictionaries are big, I thought I'd go for `__slots__`: from collections import Sequence class Point(Sequence): __slots__ = ('x', 'y') def __init__(self, x=0, y=0): self.x = x self.y = y def __getitem__(self, item): return getattr(self, self.__slots__[item]) def __setitem__(self, item, value): return setattr(self, self.__slots__[item], value) def __repr__(self): return 'Point(x=%r, y=%r)' % (self.x, self.y) def __len__(self): return 2 When testing it on Python 3, everything seemed to be OK: >>> pt = Point(12, 42) >>> pt[0], pt.y (12, 42) >>> pt.x = 5 >>> pt Point(x=5, y=42) >>> pt.z = 6 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Point' object has no attribute 'z' However on Python 2, I can set the attribute `z` even when it is not in slots: >>> pt = Point(12, 42) >>> pt.z = 5 >>> pt.z 5 >>> pt.__slots__ ('x', 'y') >>> pt.__dict__ {'z': 5} Why is that so, and why the difference between Python 2 and Python 3? Answer: The Python 2 data model says the following on [`__slots__`](https://docs.python.org/2/reference/datamodel.html#slots): > * When inheriting from a class without `__slots__`, the `__dict__` > attribute of that class will always be accessible, so a `__slots__` > definition in the subclass is meaningless. > And that is what is happening here. In Python 2 the abstract base classes in the `collections` module did not have the `__slots__` at all: >>> from collections import Sequence >>> Sequence.__slots__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'Sequence' has no attribute '__slots__' This was reported as the [issue 11333](http://bugs.python.org/issue11333) in CPython issue tracker, and was fixed in Python 3.3. In Python 3.3+ the `Sequence` abstract base class now has `__slots__` set to an empty tuple: >>> from collections import Sequence >>> Sequence.__slots__ () * * * Thus in Python 2, you cannot inherit from a `collections` base class and have memory efficient storage with `__slots__` at the same time. * * * Note however that even though the documentation on [`collections` abstract base classes](https://docs.python.org/2/library/collections.html) claims that > These ABCs allow us to ask classes or instances if they provide particular > functionality, for example: > > > size = None > if isinstance(myvar, collections.Sized): > size = len(myvar) > [This is not the case with `Sequence`](http://bugs.python.org/issue23864); simply implementing all the methods required by the `Sequence` does not make instances of your class to pass the `isinstance` check. The reason for that is that the [`Sequence`](https://hg.python.org/cpython/file/dedf481ec2be/Lib/_abcoll.py#l587) class does not have a [`__subclasshook__`](https://docs.python.org/2/library/abc.html#abc.ABCMeta.__subclasshook__); and in its absence, the parent class `__subclasshook__` is consulted instead; in this case [`Sized.__subclasshook__`](https://hg.python.org/cpython/file/dedf481ec2be/Lib/_abcoll.py#l98); and that returns `NotImplemented` if the tested-against class wasn't _exactly_ `Sized`. On the other hand, one couldn't distinguish between a mapping type and a sequence type by the magic methods, as both of them can have the exactly same magic methods - of `collections.OrderedDict` has _all_ the magic methods of a `Sequence`, including the `__reversed__` method, yet it isn't a sequence. However, you still do not need to inherit from `Sequence` to make `isinstance(Point, Sequence)` return `True`. In the following example, the `Point` is the same, except derived from `object` instead of `Sequence`, on Python 2: >>> pt = Point(12, 42) >>> pt.z = 5 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Point' object has no attribute 'z' >>> isinstance(pt, Sequence) False >>> Sequence.register(pt) >>> isinstance(pt, Sequence) True You can register any class as a subclass of the abstract base class for the purpose of `isinstance` checks; and of the extra mix-in methods, you really need to implement only `count` and `index`; the functionality for others will be filled in by Python runtime.
Getting first and last function parameter in Python Question: I have to make a function with more than 2 arguments in python and in the end I have to print the first and the last argument of the function (in a list). I have tried like this, but it doesn't work. What am i doing wrong? import inspect def func(a, b, c): frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) for i in args: return [(i, values[i]) for i=0 and i=n] Answer: You are overthinking this. You already have references to the first and last arguments: def func(a, b, c): print [a, c]
parse xml document (on url) in python Question: I am trying to parse xml document (URL) using requests, facing following error: ValueError: Unicode strings with encoding declaration are not supported here is my code: import requests from lxml import etree from lxml.etree import fromstring req = requests.request('GET', "http://www.nbp.pl/kursy/xml/LastC.xml") a = req.text b = etree.fromstring(a) how can i get this xml parsed. Thanks in advance for help Answer: You are passing in the _Unicode decoded version_. Don't do that, XML parsers require that you pass in the raw bytes instead. Instead of `req.text`, use `req.content` here: a = req.content b = etree.fromstring(a) You can also _stream_ the XML document to the parser: req = requests.get("http://www.nbp.pl/kursy/xml/LastC.xml", stream=True) req.raw.decode_content = True # ensure transfer encoding is honoured b = etree.parse(req.raw)
Simulate a transparent background Question: Since all window managers do not support this feature I have thought copying the background before displaying it. But this poses several problems. \- The background is not always properly backed up. I have no idea why. \- With this method it is impossible to move the window with the mouse. Because with hide() and show() the focus is lost. Do you think there is a solution to these problems? #!/bin/env python3 from PyQt5.QtCore import Qt from PyQt5.QtGui import QColor, QPainter, QPen from PyQt5.QtWidgets import QApplication, QMainWindow class Window(QMainWindow): def __init__(self): super().__init__() self.setWindowFlags(Qt.FramelessWindowHint) self.offset= None self.ps= app.primaryScreen() self.setGeometry(500, 500, 200, 200) self.saveBackground() def keyPressEvent(self, event): if event.key() == Qt.Key_Escape: self.close() elif event.key() in [ Qt.Key_Left, Qt.Key_Right, Qt.Key_Up, Qt.Key_Down ]: point= self.geometry().topLeft() if event.key() == Qt.Key_Left: point.setX(point.x() - 1) elif event.key() == Qt.Key_Right: point.setX(point.x() + 1) elif event.key() == Qt.Key_Up: point.setY(point.y() - 1) elif event.key() == Qt.Key_Down: point.setY(point.y() + 1) self.move(point) self.saveBackground() def mousePressEvent(self, event): self.offset= event.pos() def mouseMoveEvent(self, event): self.move(self.mapToParent(event.pos() - self.offset)) self.saveBackground() def paintEvent(self, event): qp= QPainter() qp.begin(self) qp.drawPixmap(0, 0, self.pix) qp.setPen(QPen(QColor(255, 0, 0), 2, Qt.SolidLine)) qp.drawRect(1, 1, self.width() - 2, self.height() - 2) def saveBackground(self): geo= self.frameGeometry() self.hide() self.pix= self.ps.grabWindow(app.desktop().winId(), geo.x(), geo.y(), geo.width(), geo.height()) self.show() if __name__ == "__main__": app= QApplication([]) ui= Window() ui.show() exit(app.exec_()) Answer: #!/bin/env python3 from PyQt5.QtCore import Qt from PyQt5.QtGui import QColor, QPainter, QPen from PyQt5.QtWidgets import QApplication, QMainWindow from time import time class Window(QMainWindow): def __init__(self): super().__init__() self.setWindowFlags(Qt.FramelessWindowHint) self.offset= None self.ps= app.primaryScreen() self.setGeometry(500, 500, 200, 200) self.saveBackground() self.csec= time() self.moving= False self.ratio= 2 def keyPressEvent(self, event): if event.key() == Qt.Key_Escape: self.close() elif event.key() in [ Qt.Key_Left, Qt.Key_Right, Qt.Key_Up, Qt.Key_Down ]: if time() > self.csec + 1.2: point= self.geometry().topLeft() if event.key() == Qt.Key_Left: point.setX(point.x() - 1) elif event.key() == Qt.Key_Right: point.setX(point.x() + 1) elif event.key() == Qt.Key_Up: point.setY(point.y() - 1) elif event.key() == Qt.Key_Down: point.setY(point.y() + 1) self.move(point) self.csec= time() self.saveBackground() super().keyPressEvent(event) def mousePressEvent(self, event): self.offset= event.pos() self.moving= True self.repaint() def mouseReleaseEvent(self, event): self.saveBackground() self.moving= False self.repaint() def mouseMoveEvent(self, event): self.move(self.mapToParent(event.pos() - self.offset)) def paintEvent(self, event): qp= QPainter() qp.begin(self) if self.moving: qp.setBrush(QColor(220, 220, 220)) qp.drawRect(0, 0, self.width() - 1, self.height() - 1) else: qp.drawPixmap(0, 0, self.pix.scaled(self.size() * self.ratio, Qt.KeepAspectRatio)) qp.setPen(QPen(QColor(255, 0, 0), 1, Qt.SolidLine)) qp.drawRect(0, 0, self.width() - 1, self.height() - 1) def saveBackground(self): self.hide() self.pix= self.ps.grabWindow(app.desktop().winId(), self.x(), self.y(), self.width(), self.height()) self.show() if __name__ == "__main__": app= QApplication([]) ui= Window() ui.show() exit(app.exec_())
AttributeError: 'module' object has no attribute 'subscribe' Python Question: I'm Using `Kubuntu 13.10 64 bit` and `Python 2.7.5+` and `wxPython 2.8.12.1`. I'm trying to use the `wx.lib.pubsub` module to update `wx.Gauge` from different class (thread class). I have in my code such imports: try: from pubsub import pub except ImportError: from wx.lib.pubsub import pub but when I start my application, I'm getting the error: pub.subscribe(self.updateProgress, "update") AttributeError: 'module' object has no attribute 'subscribe' What's wrong and how to fix it? Answer: wxPython 2.8.12 contains an older version of pubsub. In your code it is not clear which version you error on, in other words which import worked? I guess it is the one from wx.lib which with 2.8.12 would be the old version of pubsub. I would suggest to use either a newer version of wxPython, e.g. 3.0.2 or use the stand alone pypubsub, but if you want to stick with 2.8 then the doc shows you what needs to be done. <http://pubsub.sourceforge.net/usage/howtos/upgrade_v1tov3.html#label-upgrade- for-wx>
Problems with a chat program written in Python and PyGTK Question: I am new to python and I am currently working on a chat room program in Python (still in progress...). I have also made a GUI for my program. Initially, I made two py files, one for the GUI and one for the chatting function. They both worked perfectly when separated. After, I combined the two files. I faced the following two problems: 1. One of my threads (`target = loadMsg`) is used to wait for the host's msg and print it out on the screen. The problem is that it delays for one msg every time. For example, I sent a "1" to the host and the host should return a "1" immediately. But, the "1" I received didn't appear on my screen. Then I send a "2" to the host and the host should reply a "2" immediately. Then, my screen shows a "1" but the "2" is still missing until the host reply a "3" to me, after I send a "3" to the host. Where is the problem? 2. This is a technical problem. I was testing the stability of the chat room and I found that about 10% of my msg disappeared during the transmission and this situation occurs randomly. How can I fix such a problem? Sorry for my poor English. I hope someone can help me with it.T_T Here is my code for your reference: \---Client import pygtk,gtk import logging from threading import * import socket DEBUG = 1 HOST = '' PORT = 8018 TIMEOUT = 5 BUF_SIZE = 1024 class Base(): def reload(self): try: buf = self.sock.recv(BUF_SIZE) print buf self.addMsg(buf) except: pass def reload_butt(self,widget): try: self.thread = Thread(target=self.reload) self.thread.start() except: pass def loadMsg(self): try: while True : buf = self.sock.recv(BUF_SIZE) print buf self.addMsg(buf) except: self.sock.close() def sendMsg(self,widget): if DEBUG : print "Send Msg" if self.entry.get_text() : self.sock.send(self.entry.get_text()) self.entry.set_text("") def addMsg(self,string): if DEBUG : print "Try to add Msg" if self.entry.get_text() : iter = self.buffer1.get_iter_at_offset(-1) self.buffer1.insert(iter,("\n Username: "+string)) self.entry.set_text("") self.adj = self.scrolled_window.get_vadjustment() self.adj.set_value( self.adj.upper - self.adj.page_size ) if DEBUG : print "Add msg ok" def destroy(self,widget): if DEBUG : print "Destroy function called" self.sock.close() gtk.main_quit() def __init__(self,sock): if DEBUG : print "Initializing..." self.sock = sock self.win=gtk.Window() self.win.connect("destroy",self.destroy) self.vbox=gtk.VBox() self.win.add(self.vbox) self.view=gtk.TextView() self.view.set_editable(False) self.buffer1=self.view.get_buffer() self.scrolled_window=gtk.ScrolledWindow() self.scrolled_window.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC) self.scrolled_window.add(self.view) self.vbox.add(self.scrolled_window) self.entry=gtk.Entry() self.entry.connect("activate",self.sendMsg) self.enter=gtk.Button("Enter") self.enter.connect("clicked",self.sendMsg) self.reload=gtk.Button("Reload") self.reload.connect("clicked",self.reload_butt) self.hbox=gtk.HBox() self.hbox.add(self.entry) self.hbox.pack_start(self.reload,False,False) self.hbox.pack_start(self.enter,False,False) self.vbox.pack_start(self.hbox,False,False) self.win.show_all() if DEBUG : print "Finish initializing" def main(self): try : gtk.main() except : print "Error!!!" def main() : try : sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT)) print ('Connecting to '+ str(HOST) +' ' + str(PORT)) base=Base(sock) thread1=Thread(target=base.loadMsg) thread2=Thread(target=base.main) thread2.start() thread1.start() except : print "Err0r!!!" sock.close() main() \---host (an echo host) import socket HOST = '' PORT = 8018 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(5) conn, addr = s.accept() print 'Connected by', addr try : print "Start!" while True: data = conn.recv(1024) print data reply = data # echo if not reply : break if reply== "!q" : conn.close() break conn.send(reply) conn.close() except : print "Error!!!!!" conn.close() Answer: I would seriously recommend to use the gio library (part of glib). Using that library, you connect functions to the socket operations such as when data is available, or when data can be written to the socket. The library will call these function when necessary, and you don't need a wait loop. Which is more CPU-friendly. <http://jcoppens.com/soft/howto/gtk/chat_socket.php> contains an example of communications between a C program and Python, using gio, which might be useful to you. This way, you can start monitoring the sockets after the GUI has started, and you do not need threads to attend the communications.
Python - regex relation extraction Question: As a part of schoolwork we have been given this code: >>> IN = re.compile(r'.*\bin\b(?!\b.+ing)') >>> for doc in nltk.corpus.ieer.parsed_docs('NYT_19980315'): ... for rel in nltk.sem.extract_rels('ORG', 'LOC', doc, ... corpus='ieer', pattern = IN): ... print(nltk.sem.rtuple(rel)) We are asked to try it out with some sentences of our own to see the output, so for this i decided to define a function: def extract(sentence): import re import nltk IN = re.compile(r'.*\bin\b(?!\b.+ing)') for rel in nltk.sem.extract_rels('ORG', 'LOC', sentence, corpus='ieer', pattern = IN): print(nltk.sem.rtuple(rel)) When I try and run this code: >>> from extract import extract >>> extract("The Whitehouse in Washington") I get the gollowing error: Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> extract("The Whitehouse in Washington") File "C:/Python34/My Scripts\extract.py", line 6, in extract for rel in nltk.sem.extract_rels('ORG', 'LOC', sentence, corpus='ieer', pattern = IN): File "C:\Python34\lib\site-packages\nltk\sem\relextract.py", line 216, in extract_rels pairs = tree2semi_rel(doc.text) + tree2semi_rel(doc.headline) AttributeError: 'str' object has no attribute 'text' Can anyone help me understand where I am going wrong in my function? The correct output for the test sentence should be: [ORG: 'Whitehouse'] 'in' [LOC: 'Washington'] Answer: If you see the method definition of [extract_rels](http://www.nltk.org/_modules/nltk/sem/relextract.html), it expects the parsed document as third argument. And here you are passing the sentence. To overcome this error, you can do following : tagged_sentences = [ nltk.pos_tag(token) for token in tokens] class doc(): pass IN = re.compile(r'.*\bin\b(?!\b.+ing)') doc.headline=["test headline for sentence"] for i,sent in enumerate(tagged_sentences): doc.text = nltk.ne_chunk(sent) for rel in nltk.sem.relextract.extract_rels('ORG', 'LOC', doc, corpus='ieer', pattern=IN): print(nltk.sem.rtuple(rel) )// you can change it according Try it out..!!!
Parameterized queries using MySQLdb in Python 3 Question: I'm attempting to insert data into a MySQL database through a Python script using parameterized queries rather than formatting the parameters into a string and opening the application up to SQL injection. Here is the Python code: #!/usr/bin/python3 import MySQLdb as mdb conn = mdb.connect("localhost", "fakeuser", "fakepassword", "testdb") c = conn.cursor() c.execute("INSERT INTO test VALUES (%s)", ("Test", )) conn.commit() conn.close() When I run the script, I get the following stack trace: Traceback (most recent call last): File "./load.py", line 7, in <module> c.execute("INSERT INTO test VALUES (%s)", ("Test", )) File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line 184, in execute self.errorhandler(self, exc, value) File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/connections.py", line 37, in defaulterrorhandler raise errorvalue File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line 171, in execute r = self._query(query) File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line 330, in _query rowcount = self._do_query(q) File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line 294, in _do_query db.query(q) _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1") However, every bit of documentation I've read suggests `%s` is the correct placeholder. I've tried to enclose the `%s` in single quotes, but that causes the statement to insert that string literally rather than substitute the given value, which is what I'd expect. Here are the relevant software versions: * Python 3.2.3 * MySQL_python-1.2.3-py3.2 * MySQL 5.5.40-36.1 Note: I'm using a shared host and cannot upgrade the software. Answer: The MySQL-Python project does not support Python 3—see [the project web page](http://sourceforge.net/projects/mysql-python/), which has said "Python 3 support coming soon" for years now, and [the cheese shop entry](https://pypi.python.org/pypi/MySQL-python/1.2.5), which offers only a Python 2.7 version and says: > Python-3.0 will be supported in a future release. There's no "-py3.2" distribution available that I've heard of (or could find by searching); your host may have something silly (like [this](http://stackoverflow.com/a/15859504/2359271), for example) to get the library to install on Python 3, but being able to install a library does not guarantee it will actually work. Here's [an example of someone running into the same problem on a shared host](http://www.gossamer-threads.com/lists/python/python/1046062): > Today i switched to Python v3.2.3 on my remote web server at HostGator. My > cgi-script which it works at python v2.6.6 now produces theses errors: > > > --> --> > Traceback (most recent call last): > File "/opt/python3/lib/python3.2/site- > packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line > 171, in execute > r = self._query(query) > File "/opt/python3/lib/python3.2/site- > packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line > 330, in _query > rowcount = self._do_query(q) > File "/opt/python3/lib/python3.2/site- > packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line > 294, in _do_query > db.query(q) > _mysql_exceptions.ProgrammingError: (1064, "You have an error in your > SQL syntax; check the manual that corresponds to your MySQL server version > for the right syntax to use near '%s' at line 1") > You're right about the `%s` syntax being correct for the library; unfortunately, something about it isn't playing nice with Python 3. You could try using the named parameter style instead, and see if that gets you anywhere, but the best thing would be to stop using an unsupported library altogether. If your host also provides [an old version of Connector/Python](http://dev.mysql.com/doc/connector-python/en/connector- python-versions.html), for example.
Boost - Cannot wrap pass-in vriables Question: I tried to wrap a list to a vector of string using `<boost/python>`, where comes "undefined symbol" error: /* *.cpp */ using namespace std; using namespace boost::python; // convert python list to vector vector<string> list_to_vec_string(list& l) { vector<string> vec; for (int i = 0; i < len(l); ++i) vec.push_back(extract<string>( l[i] )); return vec; }; bool validateKeywords(list& l){ vector<string> keywords = list_to_vec_string(l); // do somethoing }; And I have /* wrapper.cpp */ BOOST_PYTHON_MODULE(testmodule){ // expose just one function def("validateKeywords", validateKeywords); } When import the module, returns the error. Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: /usr/local/lib/python2.7/dist-packages/testmodule.so: undefined symbol: _Z16validateKeywordsSt6vectorISsSaISsEE In my testing, everything works fine if I just convert returned values, i.e. from `vector<string>` to `list`. Just couldn't make it work with pass-in variables. Unless you pass in types that do not need a wrapper (int, char, bool, void), the problem doesn't fade away. * * * **Update** What you can do: /*pass in a variable that do not need a wrapper*/ // testmodule.cpp void sayHello(const std::string& msg) { std::cout << msg << endl; } // wrapper.cpp BOOST_PYTHON_MODULE(testmodule) { def("sayHello", sayHello); } // demo.py import testmodule as tm tm.sayHello('hello!') // output >> hello! /*wrap a returned value from a function*/ // testmodule.cpp vector<int> vecint(int i) { vector<int> v(i); return v; } // wrapper.cpp boost::python::list vecint_wrapper(int i) { boost::python::list l; vector<int> v = vecint(i); for (int j=0; j<v.size(); ++j) l.append(v[j]); return l; // then you have a list } /*cannot change passed in values to more complicate types*/ Answer: You miss get reference in line: def("validateKeywords", validateKeywords); Try to use def("validateKeywords", &validateKeywords );
build a perfect maze recursively in python Question: I have this project to build a perfect maze recursively by using python. I have a MyStack class which creates a stack to track the path that I go through. And a Cell class which represent each square within the maze and store some information. I think I complete the code but IDLE gives me some error that I couldn't figure out. Here is the code. from random import * from graphics import * class MyStack: def __init__(self): self.S = [] def push(self, item): self.S.insert(0, item) def pop(self): return self.S.pop(0) def isEmpty(self): return True if len(self.S) == 0 else False def size(self): return len(self.S) class Maze: def __init__(self, N): self.size = N self.maze = [[i for i in range(N + 2)] for i in range(N + 2)] for r in range(self.size + 2): for c in range(self.size + 2): self.maze[r][c] = Cell() def walk(self, s, x, y): neighboor = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)] if s.size() == self.size**2: return else: new = choice(neighboor) while self.maze[new[0]][new[1]].getVisit(): while new[0] < 1 or new[1] > self.size: new = choice(neighboor) if neighboor != []: new = choice(neighboor.remove(new)) else: temp = s.pop(s) x, y = temp[0], temp[1] self.walk(s, x, y) if new == neighboor[0]: self.maze[x][y].changeNorth() self.maze[new[0]][new[1]].changeSouth() elif new == neighboor[1]: self.maze[x][y].changeSouth() self.maze[new[0]][new[1]].changeNorth() elif new == neighboor[2]: self.maze[x][y].changeEast() self.maze[new[0]][new[1]].changeWest() elif new == neighboor[3]: self.maze[x][y].changeWest() self.maze[new[0]][new[1]].changeEast() s.push(new) self.walk(s, new[0], new[1]) def search(self): startX, startY = randint(1, self.size), randint(1, self.size) s = MyStack() temp = (startX, startY) s.push(temp) self.maze[startX][startY].changeVisit() self.walk(s, startX, startY) def draw(self): win = GraphWin() startXY = Point(27, 27) start = Circle(startXY, 5) start.setOutline('orange') start.setFill('orange') start.draw(win) x, y = 20, 20 for r in range(1, self.size + 1): for c in range(1, self.size + 1): if self.maze[r][c].getNorth(): unit = Line(Point(x, y), Point(x + 15, y)) unit.draw(win) x, y = x + 15, y x, y = 20, y + 15 x, y = 20, 20 for c in range(1, self.size + 1): for r in range(1, self.size + 1): if self.maze[r][c].getWest(): #print(self.maze[r][c].getWest()) unit = Line(Point(x, y), Point(x, y + 15)) unit.draw(win) x, y = x, y + 15 x, y = x + 15, 20 x, y = 20, self.size * 15 + 20 for c in range(1, self.size + 1): if self.maze[self.size][c].getSouth(): unit = Line(Point(x, y), Point(x + 15, y)) unit.draw(win) x, y = x + 15, y x, y = self.size * 15 + 20, 20 for r in range(1, self.size + 1): if self.maze[self.size][c].getEast(): unit = Line(Point(x, y), Point(x, y + 15)) unit.draw(win) x, y = x, y + 15 class Cell: def __init__(self): #self.x = x #self.y = y self.north = True self.south = True self.east = True self.west = True self.visit = False def changeVisit(self): self.visit = True def changeNorth(self): self.north = False def changeSouth(self): self.south = False def changeEast(self): self.east = False def changeWest(self): self.west = False def getVisit(self): return self.visit def getNorth(self): return self.north def getSouth(self): return self.south def getEast(self): return self.east def getWest(self): return self.west Here is the Error I got: >>> a = Maze(5) >>> a.search() Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> a.search() File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 91, in search self.walk(s, startX, startY) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 48, in walk while self.maze[new[0]][new[1]].getVisit(): IndexError: list index out of range I'm new to programming, any help would be appreciate. Thank you~ After fix the previous one, I got an error for the line if len(neighboor) != 0: new = choice(neighboor.remove(new)) The error message is Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> a.search() File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 88, in search self.walk(s, startX, startY) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 73, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 52, in walk if len(neighboor) != 0: new = choice(neighboor.remove(new)) File "C:\Python34\lib\random.py", line 253, in choice i = self._randbelow(len(seq)) TypeError: object of type 'NoneType' has no len() But I define 'neighboor' as a list, it should has a len() Thank you so much for help! plzplz~ Answer: The problem is that you're not ensuring that the steps in your walk are valid. The way you have it currently, `walk` could pick a `neighboor` that is out of the bounds of the maze. For example, if a maze is 5x5, attempting to access `maze[5][?]` or `maze[?][5]` will result in an `IndexError` like you get. To fix this, you could define an `is_valid` method for your maze class, e.g.: def is_valid(self, x, y): return (0 <= x < self.size) and (0 <= y < self.size) Then, you when you pick a `neighboor`, you ensure it's valid: #... else: new = choice(neighboor) while self.is_valid(new[0], new[1]) == False: new = choice(neighboor) while self.maze[new[0]][new[1]].getVisit(): #... This snippet picks a `neighboor`, then, if it's not valid, regenerates `new` until it finds a valid one. But this loop would be better written as: #... else: while True: new = choice(neighboor) if self.is_valid(new[0], new[1]): break while self.maze[new[0]][new[1]].getVisit(): #... There are more problems with your code, however, as you'll eventually see, but this will get you past this specific one.
Why doesn't np.genfromtxt() remove header while importing in Python? Question: I have data of the form: #--------------------- # Data #--------------------- p q r y 1 y 2 y 3 y 4 2 8 14 748 748 748 790 2 9 22 262 245 252 328 1 5 19 512 514 511 569 2 7 19 748 748 748 805 3 11 13 160 168 108 164 2 7 20 788 788 788 848 1 4 15 310 310 310 355 3 12 17 230 210 213 218 And I am trying to generate array B by using np.genfromtxt(), using the code: import numpy as np A = open('data.dat', "r") line = A.readline() while line.startswith('#'): line = A.readline() A_header = line.split("\t") A_header[-1] = A_header[-1].strip() B = np.genfromtxt('data.dat', comments='#', delimiter='\t', names = A_header, dtype = None, unpack = True).transpose() print B print B['y_1'] I have two questions: 1. _Why doesn't np.genfromtxt() remove data header while importing? When data is imported array B still has the header p, q, ... y 3, y 4._ 2. _Why do we have to provide underscore for header names, e.g. y_1, y_2, etc.? Why can't we provide names as it is y 1, y 2 ... y 4?_ Answer: Instead of opening the file twice, what about: import numpy as np with open('input.txt', "r") as data: while True: line = data.readline() if not line.startswith('#'): break header = [e for e in line.strip().split('\t') if e] print(header) B = np.genfromtxt(data, names=header, dtype=None, delimiter='\t') print B print B['y_1'] Output: # header ['p', 'q', 'r', 'y 1', 'y 2', 'y 3', 'y 4'] # B [(2, 8, 14, 748, 748, 748, 790) (2, 9, 22, 262, 245, 252, 328) (1, 5, 19, 512, 514, 511, 569) (2, 7, 19, 748, 748, 748, 805) (3, 11, 13, 160, 168, 108, 164) (2, 7, 20, 788, 788, 788, 848) (1, 4, 15, 310, 310, 310, 355) (3, 12, 17, 230, 210, 213, 218)] # B['y_1'] [748 262 512 748 160 788 310 230] Instead of passing the filename to `np.genfromtxt`, here, you pass `data` the file reader generator. Otherwise, you get into a weird situation where `skip_header` doesn't really work, because it considers comment lines. So you'd have to say `skip_header=4` (3 comment lines + 1 header line) when what makes is `skip_header=1`. So this approach first "throws out" comment lines. Then for the next line it extracts the headers. It passes the remaining lines into the `np.genfromtxt` function with the associated headers. A few notes: * `unpack=True` \+ `transpose()` cancel each other out. So the effect of using both is the same as using neither. So use neither. * And if you really want to access the fields using names with spaces (instead of underscores) you can always rename the fields after you generate the `ndarray`: B.dtype.names = [n.replace('_', ' ') for n in B.dtype.names] print B['y 1'] # [748 262 512 748 160 788 310 230]
How to get diff time from kernel input keyboard events(from key pressed to release)? Question: I'm trying to write a Python code to capture events from /dev/input/event* on linux. With the events I want to filter event type, event value, event code and time(tv_sec and tv_usec). PROBLEM: With EventType=EV_KEY and Event_Code = 0,1,2 (where 0=key_release,1=key_pressed,2=key_repeat), I want to get DiffTime from key_pressed(code 0) and key_released(code 1) (time_pressed - time_released) even if key is repeated (event code 2). Any Idea ? Answer: As a starting point, based on [a solution by Treviño](http://stackoverflow.com/a/16682549/2363712), here is a quick and (mostly) dirty way to capture keyboard events and report the timings: import struct FORMAT = 'llHHI' EVENT_SIZE = struct.calcsize(FORMAT) EV_KEY = 0x01 KEY_DOWN = 1 KEY_AUTO = 2 KEY_UP = 0 devname = "/dev/input/event0" def dt(sec_a, usec_a, sec_b, usec_b): return (sec_a+usec_a/1000000.) - (sec_b+usec_b/1000000) with open(devname, "rb") as infile: kdtime = {} while True: event = infile.read(EVENT_SIZE) (tv_sec, tv_usec, typ, code, value) = struct.unpack(FORMAT, event) if typ == EV_KEY: if value == KEY_DOWN: kdtime[code] = (tv_sec, tv_usec) if value == KEY_UP and code in kdtime: print(code, dt(tv_sec, tv_usec, *kdtime[code])) del kdtime[code] # Not strictly required * * * From [Documentation/input/input.txt](https://www.kernel.org/doc/Documentation/input/input.txt) events are reported by the kernel as: struct input_event { struct timeval time; unsigned short type; unsigned short code; unsigned int value; }; Struct timeval is is its turn defined in [`bits/time.h`](http://www.gnu.org/software/libc/manual/html_node/Elapsed- Time.html#index-struct-timeval) as: struct timeval { __time_t tv_sec; /* Seconds. */ __suseconds_t tv_usec; /* Microseconds. */ }; So the corresponding Python struct format for an event is `llHHI`. Once you have that, you mostly have to loop to read events with type `EV_KEY`, then remember key down time, and calculate the key pressed time when you get back the key up code. Please note that you cannot assume that a key up event match the previous key down event (think about pressing several keys at once). So I keep track of the key code and the corresponding key pressed time in a dictionary. Obviously, you will have to adapt that to your needs. But as I said, this is only a starting point.
python subprocess.call error when pipe to file Question: I am getting an usual error in python 3.4, when I'm calling a command, say `net view` in the form of: `subprocess.call("net view")` returns `error code 0` (i.e. successful) But when I do `subprocess.call("net view > targets.txt")` it returns `error code 1` (unsuccessful). Why does this error appear in python and is there a way to pipe output to file in a similar way? Answer: The easiest way to do what you want is to redirect `stdout` to a file object: from subprocess import check_call with open("targets.txt","w" ) as f: check_call(["net", "view"], stdout=f) `check_call` will raise an error for `any non-zero` exit status.
Scrapy on Ubuntu 14.04 Question: I"m getting these error when i create a scrapy project. I already went through all the google links and it just wont work out for me on ubuntu 14.04 Traceback (most recent call last): File "/usr/local/bin/scrapy", line 11, in <module> sys.exit(execute()) File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 122, in execute cmds = _get_commands_dict(settings, inproject) File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 46, in _get_commands_dict cmds = _get_commands_from_module('scrapy.commands', inproject) File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 29, in _get_commands_from_module for cmd in _iter_command_classes(module): File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 20, in _iter_command_classes for module in walk_modules(module_name): File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/misc.py", line 68, in walk_modules submod = import_module(fullpath) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/lib/python2.7/dist-packages/scrapy/commands/bench.py", line 3, in <module> from scrapy.tests.mockserver import MockServer File "/usr/local/lib/python2.7/dist-packages/scrapy/tests/mockserver.py", line 6, in <module> from twisted.internet import reactor, defer, ssl File "/usr/local/lib/python2.7/dist-packages/twisted/internet/ssl.py", line 59, in <module> from OpenSSL import SSL File "/usr/local/lib/python2.7/dist-packages/OpenSSL/__init__.py", line 8, in <module> from OpenSSL import rand, crypto, SSL File "/usr/local/lib/python2.7/dist-packages/OpenSSL/rand.py", line 11, in <module> from OpenSSL._util import ( File "/usr/local/lib/python2.7/dist-packages/OpenSSL/_util.py", line 3, in <module> from cryptography.hazmat.bindings.openssl.binding import Binding ImportError: No module named cryptography.hazmat.bindings.openssl.binding Some say do pip install pyOpenSSL==0.13 i get the following OpenSSL/crypto/x509.h:17:25: fatal error: openssl/ssl.h: No such file or directory #include <openssl/ssl.h> ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 Answer: You need to install `libssl-dev` package: sudo apt-get install libssl-dev
python: Mac can read all files in a directory but Windows can't? Question: This is probably a naive question since I am absolutely a newbie to python... I was trying to read a bunch of .txt files from a directory using Mac, and it worked perfectly, obtaining all the files without any exceptions. But then I realized I needed to switch to another Window computer to do the computing... and it just wouldn't read all the files. Here is an illustration: import numpy as np import glob import os from __future__ import print_function # read all .txt files in directory names = [] for file in os.listdir("Data/text/film/topy/"): if file.endswith(".txt"): print(file) names.append(file) scripts = [[] for _ in range(len(names)) ] for i in xrange(len(names)): scripts[i] = np.genfromtxt("Data/text/film/topy/"+names[i], delimiter="\t",dtype=character,skip_header=1) names is a list for the .txt file names and scripts is a list comprehension for file contents. There should be 365 files in there, and with Mac I could read all of them, but with Windows, only 357 files could be read... the file names are like these: l_10-Things-I-Hate-About-You.txt l_12.txt l_17-Again.txt l_30-Minutes-or-Less.txt l_48-Hrs..txt l_50-50.txt l_500-Days-of-Summer.txt l_A-Serious-Man.txt l_Adaptation.txt l_Addams-Family,-The.txt l_Adventures-of-Buckaroo-Banzai-Across-the-Eighth-Dimension,-The.txt l_After-School-Special.txt ...... Is there certain files name that prevents Windows from reading? Does anyone know the difference and why is it? Super appreciated!! Answer: Windows has restrictions on the characters that can be contained in a file name. From [Naming Files, Paths, and Namespaces](https://msdn.microsoft.com/en- us/library/windows/desktop/aa365247%28v=vs.85%29.aspx): > Use any character in the current code page for a name, including Unicode > characters and characters in the extended character set (128–255), except > for the following: > > The following reserved characters: > > * `<` (less than) > * `>` (greater than) > * `:` (colon) > * `"` (double quote) > * `/` (forward slash) > * `\` (backslash) > * `|` (vertical bar or pipe) > * `?` (question mark) > * `*` (asterisk) > > * Integer value zero, sometimes referred to as the ASCII NUL character. > > * Characters whose integer representations are in the range from 1 through > 31, except for alternate data streams where these characters are allowed. > For more information about file streams, see File Streams. > If any of your file names contains one of these characters, it will be unreadable on a Windows system.
i = self._randbelow(len(seq)) TypeError: object of type 'NoneType' has no len() Question: I have this error when I'm running my code for building a perfect maze. Here is the code: def walk(self, s, x, y): neighboor = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)] if s.size() == self.size**2: return else: while True: new = choice(neighboor) if self.is_valid(new[0], new[1]): break while self.maze[new[0]][new[1]].getVisit(): if len(neighboor) != 0: new = choice(neighboor.remove(new)) else: temp = s.pop(s) self.walk(s, temp[0], temp[1]) #print(new) self.maze[new[0]][new[1]].changeVisit() if new == neighboor[1]: self.maze[x][y].changeNorth() self.maze[new[0]][new[1]].changeSouth() elif new == neighboor[0]: self.maze[x][y].changeSouth() self.maze[new[0]][new[1]].changeNorth() elif new == neighboor[2]: self.maze[x][y].changeEast() self.maze[new[0]][new[1]].changeWest() elif new == neighboor[3]: self.maze[x][y].changeWest() self.maze[new[0]][new[1]].changeEast() s.push(new) self.walk(s, new[0], new[1]) Here is the Error I got: Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> a.search() File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 93, in search self.walk(s, startX, startY) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 76, in walk self.walk(s, new[0], new[1]) File "C:\Users\Serena\Desktop\XAproject\Stack.py", line 52, in walk if len(neighboor) != 0: new = choice(neighboor.remove(new)) File "C:\Python34\lib\random.py", line 253, in choice i = self._randbelow(len(seq)) TypeError: object of type 'NoneType' has no len() I think 'neighboor' is a list contains four sets of number, it should have len(). I'm new to programming, any help would be appreciate. Answer: Couple of things. First, if you're using something like choice() that's imported from a wildcard import (from random import *), it would be useful to include that, because otherwise we're just guessing where you got that function from. Also, [wildcard imports are considered bad practice anyway](http://stackoverflow.com/questions/3615125/should-wildcard-import-be- avoided). The problem is that the remove() method of a list returns None. You cannot choose something from None, because None is not an iterable. That is to say that the remove() method does not support chaining. Try changing: if len(neighboor) != 0: new = choice(neighboor.remove(new)) # Passes None to choice() which raises an error to if len(neighboor) != 0: neighboor.remove(new) # removes the element from neighboor new = choice(neighboor) # Chooses from the list as you intended You could have other errors, but that's the one that came from the traceback you posted. For the future, I recommend familiarizing yourself with Python's traceback, because it is telling you exactly what is going wrong. [Here's a resource](http://cbio.ufs.ac.za/live_docs/nbn_tut/understanding_errors.html). As an aside, do you mean neighbor instead of neighboor?
In Python, how to enforce an abstract method to be static on the child class? Question: This is the setup I want: A should be an abstract base class with a static & abstract method f(). B should inherit from A. Requirements: 1\. You should not be able to instantiate A 2\. You should not be able to instantiate B, unless it implements a static f() Taking inspiration from [this](http://stackoverflow.com/questions/4474395/staticmethod-and-abc- abstractmethod-will-it-blend) question, I've tried a couple of approaches. With these definitions: class abstractstatic(staticmethod): __slots__ = () def __init__(self, function): super(abstractstatic, self).__init__(function) function.__isabstractmethod__ = True __isabstractmethod__ = True class A: __metaclass__ = abc.ABCMeta @abstractstatic def f(): pass class B(A): def f(self): print 'f' class A2: __metaclass__ = abc.ABCMeta @staticmethod @abc.abstractmethod def f(): pass class B2(A2): def f(self): print 'f' Here A2 and B2 are defined using usual Python conventions and A & B are defined using the way suggested in [this](http://stackoverflow.com/questions/4474395/staticmethod-and-abc- abstractmethod-will-it-blend) answer. Following are some operations I tried and the results that were undesired. With classes A/B: >>> B().f() f #This should have thrown, since B doesn't implement a static f() With classes A2/B2: >>> A2() <__main__.A2 object at 0x105beea90> #This should have thrown since A2 should be an uninstantiable abstract class >>> B2().f() f #This should have thrown, since B2 doesn't implement a static f() Since neither of these approaches give me the output I want, how do I achieve what I want? Answer: You can't do what you want with just `ABCMeta`. ABC enforcement doesn't do _any_ type checking, only the presence of _an attribute_ with the correct name is enforced. Take for example: >>> from abc import ABCMeta, abstractmethod, abstractproperty >>> class Abstract(object): ... __metaclass__ = ABCMeta ... @abstractmethod ... def foo(self): pass ... @abstractproperty ... def bar(self): pass ... >>> class Concrete(Abstract): ... foo = 'bar' ... bar = 'baz' ... >>> Concrete() <__main__.Concrete object at 0x104b4df90> I was able to construct `Concrete()` even though both `foo` and `bar` are simple attributes. The `ABCMeta` metaclass only tracks how many objects are left with the `__isabstractmethod__` attribute being true; when creating a class from the metaclass (`ABCMeta.__new__` is called) the `cls.__abstractmethods__` attribute is then set to a `frozenset` object with all the names that are still abstract. `type.__new__` then tests for that `frozenset` and throws a `TypeError` if you try to create an instance. You'd have to produce your _own_ `__new__` method here; subclass `ABCMeta` and add type checking in a new `__new__` method. That method should look for `__abstractmethods__` sets on the base classes, find the corresponding objects with the `__isabstractmethod__` attribute in the MRO, then does typechecking on the current class attributes. This'd mean that you'd throw the exception when defining the _class_ , not an instance, however. For that to work you'd add a `__call__` method to your `ABCMeta` subclass and have that throw the exception based on information gathered by your own `__new__` method about what types were wrong; a similar two-stage process as what `ABCMeta` and `type.__new__` do at the moment. Alternatively, update the `__abstractmethods__` set on the class to add any names that were implemented but with the wrong type and leave it to `type.__new__` to throw the exception. The following implementation takes that last tack; add names back to `__abstractmethods__` if the implemented type doesn't match (using a mapping): from types import FunctionType class ABCMetaTypeCheck(ABCMeta): _typemap = { # map abstract type to expected implementation type abstractproperty: property, abstractstatic: staticmethod, # abstractmethods return function objects FunctionType: FunctionType, } def __new__(mcls, name, bases, namespace): cls = super(ABCMetaTypeCheck, mcls).__new__(mcls, name, bases, namespace) wrong_type = set() seen = set() abstractmethods = cls.__abstractmethods__ for base in bases: for name in getattr(base, "__abstractmethods__", set()): if name in seen or name in abstractmethods: continue # still abstract or later overridden value = base.__dict__.get(name) # bypass descriptors if getattr(value, "__isabstractmethod__", False): seen.add(name) expected = mcls._typemap[type(value)] if not isinstance(namespace[name], expected): wrong_type.add(name) if wrong_type: cls.__abstractmethods__ = abstractmethods | frozenset(wrong_type) return cls With this metaclass you get your expected output: >>> class Abstract(object): ... __metaclass__ = ABCMetaTypeCheck ... @abstractmethod ... def foo(self): pass ... @abstractproperty ... def bar(self): pass ... @abstractstatic ... def baz(): pass ... >>> class ConcreteWrong(Abstract): ... foo = 'bar' ... bar = 'baz' ... baz = 'spam' ... >>> ConcreteWrong() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class ConcreteWrong with abstract methods bar, baz, foo >>> >>> class ConcreteCorrect(Abstract): ... def foo(self): return 'bar' ... @property ... def bar(self): return 'baz' ... @staticmethod ... def baz(): return 'spam' ... >>> ConcreteCorrect() <__main__.ConcreteCorrect object at 0x104ce1d10>
Python pyodbc Unicode issue Question: I have a string variable res which I have derived from a pyodbc cursor as shown in the bottom. The table `test` has a single row with data `ä` whose unicode codepoint is `u'\xe4'`. The Result I get is >>> res,type(res) ('\xe4', <type 'str'>) Whereas the result I should have got is. >>> res,type(res) (u'\xe4', <type 'unicode'>) I tried adding charset as utf-8 to my pyodbc connect string as shown below. The result was now correctly set as a unicode but the codepoint was for someother string `꓃` which could be due to a possible bug in the pyodbc driver. conn = pyodbc.connect(DSN='datbase;charset=utf8',ansi=True,autocommit=True) >>> res,type(res) (u'\ua4c3', <type 'unicode'>) Actual code import pyodbc pyodbc.pooling=False conn = pyodbc.connect(DSN='datbase',ansi=True,autocommit=True) cursor = conn.cursor() cur = cursor.execute('SELECT col1 from test') res = cur.fetchall()[0][0] print(res) Additional details Database: Teradata pyodbc version: 2.7 So How do I now either 1) cast `('\xe4', <type 'str'>)` to `(u'\xe4', <type 'unicode'>)` (is it possible to do this without unintentional side-effects?) 2) resolve the pyodbc/unixodbc issue Answer: This is something I think is best handled with Python, instead of fiddling with [pyodbc.connect](https://code.google.com/p/pyodbc/wiki/Module) arguments and driver-specific connection string attributes. `'\xe4'` is a [Latin-1](https://en.wikipedia.org/wiki/Latin-1_Supplement_%28Unicode_block%29) encoded string representing the unicode [ä](http://www.codetable.net/decimal/228) character. To explicitly decode the pyodbc result in Python 2.7: >>> res = '\xe4' >>> res.decode('latin1'), type(res.decode('latin1')) (u'\xe4', <type 'unicode'>) >>> print res.decode('latin1') ä Python 3.x does this for you (the [`str` type includes unicode characters](https://docs.python.org/3/howto/unicode.html#the-string-type)): >>> res = '\xe4' >>> res, type(res) ('ä', <class 'str'>) >>> print(res) ä
How can I get the full link from beautifulsoup instead of only the internal link Question: I am new to python. I am building a crawler for the company I work for. Crawling its website, there is a internal link that is not in the link format that it is used to. How can I get the entire link instead of the directory only. If I was not too clear, please run the code that I made bellow: import urllib2 from bs4 import BeautifulSoup web_page_string = [] def get_first_page(seed): response = urllib2.urlopen(seed) web_page = response.read() soup = BeautifulSoup(web_page) for link in soup.find_all('a'): print (link.get('href')) print soup print get_first_page('http://www.fashionroom.com.br') print web_page_string Answer: Tks everyone for the answers I tried to put an if in the script. If anyone sees a potential problem with something I will find in the future, pls let me know import urllib2 from bs4 import BeautifulSoup web_page_string = [] def get_first_page(seed): response = urllib2.urlopen(seed) web_page = response.read() soup = BeautifulSoup(web_page) final_page_string = soup.get_text() for link in soup.find_all('a'): if (link.get('href'))[0:4]=='http': print (link.get('href')) else: print seed+'/'+(link.get('href')) print final_page_string print get_first_page('http://www.fashionroom.com.br') print web_page_string
VideoWriter outputs only a 5.7kB File in OpenCV Python Question: I was trying the following piece of code for storing the captured video into a file. The Live Stream is getting displayed correctly , but for whatever length I record the video, the target file is a 5.7kB file that doesn't contain any video. import numpy as np import cv2 cap = cv2.VideoCapture(0) fourcc= cv2.cv.FOURCC(*'DIVX') ret=cap.set(3,500) ret=cap.set(4,500) out= cv2.VideoWriter('out.avi',fourcc,20,(500,500)) while(cap.isOpened()): ret, frame = cap.read() if ret == True: out.write(frame) cv2.imshow('out.avi',frame) if cv2.waitKey(1) &0xFF ==ord('q'): break else: break cap.release() out.release() cv2.destroyAllWindows() Does anyone have any idea what I might be doing wrong here? Please help to figure it out . Answer: It might be because the encoding of fourcc is not supported/installed on your machine, thus makes it impossible to export the frames to the video. It happens to me all the time. What works for me is the mp4 codec (in opencv: cv2.cv.CV_FOURCC('m', 'p', '4', 'v')). So, try this: import numpy as np import cv2 cap = cv2.VideoCapture(0) fourcc= cv2.cv.CV_FOURCC('m', 'p', '4', 'v') ret=cap.set(3,500) ret=cap.set(4,500) out= cv2.VideoWriter('out.avi',fourcc,20,(500,500)) while(cap.isOpened()): ret, frame = cap.read() if ret == True: out.write(frame) cv2.imshow('out.avi',frame) if cv2.waitKey(1) &0xFF ==ord('q'): break else: break cap.release() out.release() cv2.destroyAllWindows() Otherwise, you can try to install all the codec compatible with ffmpeg (It seems that opencv uses ffmpeg to export the frames to video file) and retry your original code.
Scrapy giving error on start running:AttributeError: 'module' object has no attribute 'Any' Question: Using a tutorial, started "scrapy crawl dmoz" showing an error. I have installed Scrapy but don't know how to check whether it is correctly installed or not. I am using tutorial to use it but got stuck. Trackback is below- Traceback (most recent call last): File "/usr/local/bin/scrapy", line 9, in <module> load_entry_point('Scrapy==0.24.5', 'console_scripts', 'scrapy')() File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 122, in execute cmds = _get_commands_dict(settings, inproject) File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 46, in _get_commands_dict cmds = _get_commands_from_module('scrapy.commands', inproject) File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 29, in _get_commands_from_module for cmd in _iter_command_classes(module): File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 20, in _iter_command_classes for module in walk_modules(module_name): File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/misc.py", line 68, in walk_modules submod = import_module(fullpath) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/lib/python2.7/dist-packages/scrapy/commands/bench.py", line 3, in <module> from scrapy.tests.mockserver import MockServer File "/usr/local/lib/python2.7/dist-packages/scrapy/tests/mockserver.py", line 6, in <module> from twisted.internet import reactor, defer, ssl File "/usr/local/lib/python2.7/dist-packages/twisted/internet/ssl.py", line 223, in <module> from twisted.internet._sslverify import ( File "/usr/local/lib/python2.7/dist-packages/twisted/internet/_sslverify.py", line 192, in <module> verifyHostname, VerificationError = _selectVerifyImplementation(OpenSSL) File "/usr/local/lib/python2.7/dist-packages/twisted/internet/_sslverify.py", line 167, in _selectVerifyImplementation from service_identity import VerificationError File "/usr/local/lib/python2.7/dist-packages/service_identity/__init__.py", line 12, in <module> from . import pyopenssl File "/usr/local/lib/python2.7/dist-packages/service_identity/pyopenssl.py", line 12, in <module> from pyasn1_modules.rfc2459 import GeneralNames File "/usr/local/lib/python2.7/dist-packages/pyasn1_modules/rfc2459.py", line 72, in <module> class AttributeValue(univ.Any): pass AttributeError: 'module' object has no attribute 'Any' Answer: If you are using `virtualenv`.Try pip install -U pyasn1 Otherwise sudo pip install -U pyasn1 For more <https://github.com/scrapy/scrapy/issues/783>
wxpython set max textbox value length Question: how i can set the max length of the textbox in wxpython? this is my code(part of the code) import wx from wx.lib.masked import NumCtrl class MyFrame(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,id,title) self.panelMain = wx.Panel(self, -1) panel = self.panelMain #creating buttons and text boxes. self.guessTxt = wx.lib.masked.NumCtrl(self.panelMain,-1,size=(100,20),pos=(50,102)) self.newGameTxt = wx.TextCtrl(self.panelMain,-1,size=(100,20),pos=(180,73)) Answer: self.newGameTxt.SetMaxLength(200) <http://wxpython.org/Phoenix/docs/html/TextEntry.html?highlight=maxl#TextEntry.SetMaxLength>
Error when trying to run django application Question: Trying to install 'Django-inventory' from <https://github.com/rosarior/django- inventory> After resolving dependency errors im getting this: (inventory)root@ip-172-31-47-17:/home/admin# django-inventory.py runserver Traceback (most recent call last): File "/home/admin/inventory/bin/django-inventory.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/admin/inventory/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/home/admin/inventory/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/admin/inventory/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 261, in fetch_command commands = get_commands() File "/home/admin/inventory/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 107, in get_commands apps = settings.INSTALLED_APPS File "/home/admin/inventory/local/lib/python2.7/site-packages/django/conf/__init__.py", line 54, in __getattr__ self._setup(name) File "/home/admin/inventory/local/lib/python2.7/site-packages/django/conf/__init__.py", line 49, in _setup self._wrapped = Settings(settings_module) File "/home/admin/inventory/local/lib/python2.7/site-packages/django/conf/__init__.py", line 128, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/admin/inventory/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module __import__(name) File "/home/admin/inventory/local/lib/python2.7/site-packages/django_inventory/settings/local.py", line 4 SECRET_KEY = '@PK$vmu_W@=^hYy\<hwYKDX.)eX5-MAlsYJ?Y-v5EbRC7KZ)5CSg:bS2^?RJi/S@$j%L9Tc9^2j&&$<o)xpr.v?uiwvsT%d9sq;\' ^ SyntaxError: EOL while scanning string literal (inventory)root@ip-172-31-47-17:/home/admin# Appreciate any pointers to resolving this. Answer: The final backslash in your SECRET_KEY is escaping the close single quote. Remove it.
Why do I get this IOerror13 ? Using python Question: import sys import os import re import ftplib os.system('dir /S "D:\LifeFrame\*.jpg" > "D:\Python\placestogo.txt"') #this is where to search. dat = open('placestogo.txt','r').read() drives = re.findall(r'.\:\\.+.+',dat) for i in range(len(drives)): path = drives[i] os.system('dir '+ path +'\*.jpg > D:\python\picplace.txt') picplace = open('picplace.txt','r').read() pics = re.findall(r'\w+_\w+.\w+..jpg|IMG.+|\w+.jpg',picplace) for i in range(len(pics)): filename = pics[i] ftp = ftplib.FTP("localhost") print ftp.login("xxxxxxxx","xxxxxxxx") ftp.cwd("/folder") myfile = open(path,"rb") print ftp.storlines('STOR ' + filename, myfile) print ftp.quit() sys.exit() i am trying to copy all of those files to my ftp server but it gives me that error: d:\Python>stealerupload.py 230 Logged on Traceback (most recent call last): File "D:\Python\stealerupload.py", line 22, in <module> myfile = open(path,"rb") IOError: [Errno 22] invalid mode ('rb') or filename: '"D:\\LifeFrame"' any one knows where is the problem ? I am running as administrator and folder should have permissions Answer: In the error message, it shows `'"D:\\LifeFrame"'`, which to me looks like you have extra quotes in `path`. Try adding `print path` to see what its value is. Maybe you want to upload data from `filename` to your server, not from `path`, in which case Python showed in the error message is where the bug is: you should be opening `filename` instead.
Extract parts of log in Python to import to Excel Question: I'm trying to get part of a log (txt file) using regex but I'm needing some help. Basically the log comes like this: Tue Feb 24 17:51:10.835 SRV02 NOTICE Event Loop - noop Tue Feb 24 17:51:10.835 SRV02 NOTICE Exponential histogram: Tue Feb 24 17:51:10.835 SRV02 NOTICE hist[ 0]: < 0.001: 728941854 Tue Feb 24 17:51:10.835 SRV02 NOTICE Event Loop - noop: samples: 728941854; avg: 0.00; min: 0.00; max: 0.00 Tue Feb 24 17:51:10.835 SRV02 NOTICE Data Quality Monitor Thread Processing Time Tue Feb 24 17:51:10.835 SRV02 NOTICE Exponential histogram: Tue Feb 24 17:51:10.835 SRV02 NOTICE hist[ 4]: < 0.016: 3 Tue Feb 24 17:51:10.835 SRV02 NOTICE hist[ 5]: < 0.032: 23 Tue Feb 24 17:51:10.835 SRV02 NOTICE hist[ 6]: < 0.064: 14 Tue Feb 24 17:51:10.835 SRV02 NOTICE hist[ 7]: < 0.128: 4 Tue Feb 24 17:51:10.835 SRV02 NOTICE hist[ 8]: < 0.256: 6 Tue Feb 24 17:51:10.835 SRV02 NOTICE hist[ 9]: < 0.512: 1 Tue Feb 24 17:51:10.835 SRV02 NOTICE hist[10]: < 1.024: 2 Tue Feb 24 17:51:10.835 SRV02 NOTICE Data Quality Monitor Thread Processing Time: samples: 53; avg: 0.08; min: 0.01; max: 0.67 Tue Feb 24 17:51:10.835 SRV02 NOTICE Client Hugepage Memory: 649/4096 MB Tue Feb 24 17:51:10.836 SRV02 NOTICE DQM: Num R: 0 RD: 0 ED: 0 W: 0 WH: 0 Q: 0 D: 0 DF: 0 Tue Feb 24 17:51:10.836 SRV02 NOTICE Num G: 0 M: 0 S: 0 D: 0 U: 0 R: 0 N: 0 Tue Feb 24 17:51:10.836 SRV02 NOTICE num_template_allocs = 4 Tue Feb 24 17:51:10.836 SRV02 NOTICE num_template_frees = 0 Tue Feb 24 17:51:10.836 SRV02 NOTICE num_internal_book_allocs = 24 and I need to get the information about the "Exponential histogram", so, in this example I need to identify the string "Exponential histogram" and get all the "hist[..." to import to a spreadsheet. Also I need this information: samples: XX; avg: X.XX; min: X.XX; max: X.XX So, in the example above, I'll need to extract and rearrange the data like this, where "Event Loop - noop" and "Data Quality Monitor Thread Processing Time" need to be repeated in each line in order to identify the histogram: Event Loop - noop;hist[ 0];0.001;728941854 Event Loop - noop;samples;728941854;avg;0.00;min;0.00;max;0.00 Data Quality Monitor Thread Processing Time;hist[ 4];0.016;3 Data Quality Monitor Thread Processing Time;hist[ 5];0.032;23 Data Quality Monitor Thread Processing Time;hist[ 6];0.064;14 (...) Data Quality Monitor Thread Processing Time;hist[ 10];1.024;2 Data Quality Monitor Thread Processing Time;samples;53;avg;0.08;min;0.01;max;0.67 Somebody can help me how to do this? Thank you! Answer: In your example output, you have data that does not exist in your sample input. Specifically you have more `"Data Quality Monitor Thread Processing Time"` strings then there are in your data. It seems you want to keep the nearest indented header? Anyway, I think it would be easier to just pull the data using a few different regex statements instead of trying to make one all encompassing one: import re hists = re.findall(r'(hist\[\s\d+\]).*?(\d+\.\d+).*?(\d+)',input) sample_avg_etc = re.findall(r'(samples): (\d+); (avg): (\d+\.\d+); (min): (\d+\.\d+); (max): (\d+\.\d+)',input) If you need to keep the local header as you show in your sample output. I don't think you want to use regex. Instead just write a parser which will extract your data. You can start this by stripping each line of its `Tue Feb 24 17:51:10.835 SRV02 NOTICE` and then targeting the data line by line, keeping track of the last header. See the comments, the below returns exactly what you listed above: import re def parse(data): lines = data.split('\n') # get the lines by splitting on the newline char lines = [line[len("Tue Feb 24 17:51:10.835 SRV02 NOTICE "):] for line in lines] # remove the number of characters equal to the logging info out = [] header = '' for line in lines: if line.startswith(' '): if line.strip().startswith('hist'): out.append(header + ";" + extract_hist_data(line)) # outsource the specific extracting to a function for ease of readability else: # header/samples line if all(i in line for i in ("samples", "avg", "min", "max")): # if the line contains all these keywords out.append(header + ";" + extract_stat_data(line)) # outsource the specific extracting to a function for ease of readability else: # Treat as a header header = line return '\n'.join(out) def extract_hist_data(line): data = re.findall(r'(hist\[\s*?\d+\]).*?(\d+\.\d+).*?(\d+)',line) if len(data) > 0: data = data[0] else: return "" return ';'.join(i for i in data) def extract_stat_data(line): data = re.findall(r'(samples).*?(\d+).*?(avg).*?(\d+\.\d+).*?(min).*?(\d+\.\d+).*?(max).*?(\d+\.\d+)',line) if len(data) > 0: data = data[0] else: return "" return ';'.join(i for i in data) def parse_log_file(log_file_path): with open(log_file_path,'r') as f: content = ''.join(i for i in f) return parse(content) print parse_log_file('test.log')
Sorting a text file with strings and digits on each line - Python 3 Question: I have a text file I made with some runners and their race times in which looks like this: Dylan , 3.6 Tom , 4.2 Jack , 1.4 Dave , 8.8 Mick , 5.2 John , 11.3 Matt , 7.6 Ben , 9.7 Joe , 3.9 Chris , 3.3 I have a new line for each new race participant and their race time after a comma. How can I sort this text file so the person with the fastest time is at the top. The code I used to generate the test file looks like this: def runnerData(): thefile = open("race.txt" , "w") names = ["Dylan" , "Tom" , "Jack" , "Dave" , "Mick" , "John" , "Matt" , "Ben" , "Joe" , "Chris"] times = ["3.6" , "4.2" , "1.4" , "8.8" , "5.2" , "11.3" , "7.6" , "9.7" , "3.9" , "3.3"] zipped = zip(names, times) for aname,atime in zipped: thefile.write("%s , %s\n" %(aname,atime)) runnerData() I have only just started using Python and am not familiar with a lot of it - still learning! :) Thanks. EDIT: The code I used to generate the file ok and i'm happy it works - The task I have been set is to write a new file using the text file I have generated to display the winner of the race. Answer: You need to sort your `zipped` list based on second element,you can use [_`sorted()`_](https://docs.python.org/2/library/functions.html#sorted) function with a proper `key` : from operator import itemgetter def runnerData(): thefile = open("race.txt" , "w") names = ["Dylan" , "Tom" , "Jack" , "Dave" , "Mick" , "John" , "Matt" , "Ben" , "Joe" , "Chris"] times = ["3.6" , "4.2" , "1.4" , "8.8" , "5.2" , "11.3" , "7.6" , "9.7" , "3.9" , "3.3"] zipped = zip(names, times) for aname,atime in sorted(zipped,key=float(itemgetter(1)),reverse=True): thefile.write("%s , %s\n" %(aname,atime)) runnerData() And if you read the preceding file you can do : l=[] for line in open('your_file'): l.append(line.split(',')) So the `l` would be : [['Dylan ', ' 3.6'], ['Tom ', ' 4.2'], ['Jack ', ' 1.4'], ['Dave ', ' 8.8'], ['Mick ', ' 5.2'], ['John ', ' 11.3'], ['Matt ', ' 7.6'], ['Ben ', ' 9.7'], ['Joe ', ' 3.9'], ['Chris ', ' 3.3']] then you can use the preceding `sorted()` function to sort your list : sorted(l,key=float(itemgetter(1)),reverse=True)
JSON RPC Client Go Question: I have a python server serving response through JSON-RPC. Here is a sample response from the server. '{"jsonrpc": "2.0", "result": "Peer 1: local 10.10.0.2 remote 10.10.0.1 state CONNECT\\nPeer 2: local 10.10.0.18 remote 10.10.0.17 state ESTABLISHED\\nPeer 3: local 10.10.0.10 remote 10.10.0.9 state ESTABLISHED", "id": "839732f9-cf36-46ff-8b9b-6120250d9ce5"}' Here is the request I need to send to the server: '{"method":"echo","jsonrpc":"2.0","params":["test_params"],"id":"839732f9-cf36-46ff-8b9b-6120250d9ce5"}' Here is my client with go language: package main import ( "fmt" "log" "net" "net/rpc/jsonrpc" ) type Args struct { jsonrpc, id string } func main() { conn, err := net.Dial("tcp", "11.21.22.221:8080") if err != nil { panic(err) } defer conn.Close() args := Args{"2.0", "d87198f0-af92-49f8-9a7d-ab8bed5c4d17"} var reply string c := jsonrpc.NewClient(conn) err = c.Call("echo", args, &reply) if err != nil { log.Fatal("error:", err) } fmt.Printf("Response: %d", reply) } But, when I run this client, it is not sending anything in the params. Instead it is sending empty params like this: '{"method":"echo","params":[{}],"id":0}\n Can somebody help me telling what mistake I am making? I am a newbie to go language. Thanks. Answer: I don't think what you are doing is possible using the client as provided by go because the private `clientRequest` struct is currently defined as: type clientRequest struct { Method string `json:"method"` Params [1]interface{} `json:"params"` Id uint64 `json:"id"` } What you pass into `Call` as `args` is stuck into `Params` and note how there is no "Version `json:"jsonrpc"`" inside of that struct. AFAICT (which may be wrong, this is my first time reading through this code) you would need to implement your own [ClientCodec](http://golang.org/pkg/net/rpc/#ClientCodec). You could probably get away with copying most (all) of the parts out of the stdlib and add the field to the `clientRequest` above. ;-)
Delete extra characters apart from starting and ending in a string in python Question: I have data of the form: "C def geh.#- ijk "<> ""^^xsd:date. Now for the last part of the above string i.e. "C def geh.#- ijk "<> ""^^xsd:date -- i.e the part which begins and ends with quotes. I want to keep just the beginning and ending quotes and delete all the other quotes and <>, etc. except #,-,.,_,(,) which come in between. Can someone please suggest how can i do it. My expected output should appear as: "C def geh.#- ijk "^^xsd:date. Answer: Assuming that there always will be a match: import re def cleanup(str): return ''.join(re.match('(\"[^\"]+\").*?(\^\^xsd\:date\.)', str).groups()) >>> s = """"C def geh.#- ijk "<> ""^^xsd:date.""" >>> cleanup(s) '"C def geh.#- ijk "^^xsd:date.' UPDATE If the dot at the end of the string might or might not appear, use this (and I forgot the dollar sign to mark the end): def cleanup(str): return ''.join(re.match('(\"[^\"]+\").*?(\^\^xsd\:date\.?)$', str).groups()) >>> s = '"1980-"05"-26"^^xsd:date' >>> cleanup(s) '"1980-"^^xsd:date' If you want to handle the situation when there is no match (e.g. return empty string), then it could be done like this: def cleanup(str): try: return ''.join(re.match('(\"[^\"]+\").*?(\^\^xsd\:date\.?)$', str).groups()) except AttributeError: return '' >>> cleanup("asdfadf") '' UPDATE after getting more explanations from OP (need to cleanup the contents between the first and last quotes and return the rest unchanged): def cleanup(str): left_index = s.find('\"') right_index = s.rfind('\"') if left_index==right_index: return str else: cleaned = re.sub('[^0-9a-zA-Z\#\-\.\_\(\)]','',s[left_index+1:right_index]) return str[:left_index+1]+cleaned+str[right_index:] >>> cleanup(s) '"1980-05-26"^^xsd:date'
Python screen is black for a small amount of time then closes Question: The code in this gist (<https://gist.github.com/tobias76/8dc2e1af90f1916a2106>) is completely broken and nothing happens excl. a black screen and closure after seconds, I would be more specific with the code but there is absolutely no error message. As far as the program is concerned, it worked. As requested, here is my code (For some reason stack overflow doesn't like all of the code being formatted); ============================================== import pygame import sys import random from pygame.locals import * pygame.init() FPS = 60 FPSClock = pygame.time.Clock() screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("Graphical Slot Machine") reelgroupone = pygame.sprite.Group() reelgrouptwo = pygame.sprite.Group() reelgroupthree = pygame.sprite.Group() reelone = (reelgroupone, 1) reeltwo = (reelgrouptwo, 2) reelthree = (reelgroupthree, 3) image = "assets/apple.png" image2 = "assets/bar.png" image3 = "assets/cherry.png" image4 = "assets/orange.png" background = "background.jpg" class Reels(pygame.sprite.Sprite): def __init__(self, reelgroup, reelnumbers): self.reelgroup = reelgroup self.reelnumber = reelnumbers self.reellist = [0, 1, 2, 3, 4, 5] self.reelmove = 1 self.reelnudge = 0 self.stoptime = 60 def start(self): self.reelmove = 1 self.stoptime = 60 def stop(self): self.reelmove = 0 def update(self): if self.stoptime > 0: self.stoptime -= 1 self.reelgroup.update() else: self.stop() if self.reelnudge == 1: self.reelmove = 0 def draw(self): self.reelgroup.draw(screen) class Fruit(pygame.sprite.Sprite): def __init__(self, reelgroup, reel, FruitID): pygame.sprite.Sprite.__init__(self) self.reelgroup = reelgroup self.FruitID = FruitID self.machineReel = reel # Depending on Reel ID use a specific image, place the file path in the string if self.FruitID == 1: self.reelImage = "assets/apple.png" if self.FruitID == 2: self.reelImage = "assets/bar.png" if self.FruitID == 3: self.reelImage = "assets/cherry.png" if self.FruitID == 4: self.picture = "assets/orange.png" self.pic = pygame.image.load(self.reelImage).convert_alpha() self.where = ((self.machineReel * 155) - 30, 490) self.rectangle = self.pic.get_rect() self.rectangle.TopLeft = self.where # Make reels faster / slower here. self.reelSpeed = 8 self.reelgroup.add(self) def fruitupdate(self): self.rectangle.y -= self.reelSpeed if self.rectangle.y < 110: self.kill() class main(): def __init__(self): self.money = 10 self.counter = 5 self.fruitlist = [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] self.finished = 0 self.message = "" def splash(self): pass def machine(self): while self.credits > 0: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() self.keys = pygame.key.get_pressed() # Change this key to whatever you want if self.keys[K_p] and reelone.reelmove == reeltwo.reelmove == reelthree.reelmove == 0: self.money -= 1 self.counter = 5 self.finished = 0 reelone.start() reeltwo.start() reelthree.start() self.message = "" if self.keys[K_ESCAPE]: pygame.quit() sys.exit() # Put your image and font blitting here. screen.blit(background,(0,0)) if self.money >= 10: self.counter = 1 if reelone.reelMove == 1 and reelone.stopTime % 10: fruit = Fruit(reelgroupone, 1, random.randint(1,4)) del self.fruitlist[0][0] self.fruitlist[0].append(fruit.ID) if reeltwo.reelMove == 1 and reeltwo.stopTime % 10: fruit = Fruit(reelgrouptwo, 2, random.randint(1,4)) del self.fruitlist[1][0] self.fruitlist[1].append(fruit.ID) if reelthree.reelMove == 1 and reelthree.stopTime % 10: fruit = Fruit(reelgroupthree, 3, random.randint(1,4)) del self.fruitlist[2][0] self.fruitlist[2].append(fruit.ID) else: self.counter += 1 if reelone.reelmove == 1: reelone.update() if reeltwo.reelmove == 1: reeltwo.update() if reelthree.reelmove == 1: reelthree.update() # If all the reels are moving, check if the player has won and add the credits to their # account if so. if reelone.reelmove == reeltwo.reelmove == reelthree.reelmove == 0 and self.finished == 0: if self.fruitlist[0][2] == self.fruitlist[1][2] == self.fruitlist[2][2]: self.message = "Winner, want to play again?" if self.fruitlist[0][2] == 1: self.credits += 10 if self.fruitlist[0][2] == 1: self.credits += 100 if self.fruitlist[0][2] == 3: self.credits += 1000 if self.fruitlist[0][2] == 4: self.credits += 10000 # Now this sets the state to finished self.finished = 1 else: self.message = "Sorry, no win this time!" self.end = 1 reelgroupone.draw(screen) reelgrouptwo.draw(screen) reelgroupthree.draw(screen) FPSClock.tick(FPS) pygame.display.update() fruit = main() Answer: You're not actually running the main() as a function in your code, main is a class instead. Change main to a function, and instead, write this at the bottom of the program: If __name__ == "__main__": main() This way, the code actually runs. Also, get rid of `fruit = main()`. It just makes it more confusing and you're going to be running it anyways with this, hence why it says that the process finished. You may also want to move things previously in the main class in the main function. For example, take functions inside of the class such as the machine() function and put it as a separate function outside of your code, and call it in the main function with machine().
print out list of the relation between variables in python? Question: I'm an absolute beginner with python and my professor is sort of doing a trial of fire approach to teaching us the language. The goal is to list the triples in the relation {(a,b,c) : a, b, and c are integers with 0 < a < b < c < 5}. Use range(5) as the source for values of a, b, and c. I think i understand the general concept of what it is, i set the values of a,b,c fine, but I don't quite get how I can print out variables like that? I was thinking of using some sort of while loop of like while a < b < c print out (a,b,c) or something but I can't get it to work with the syntax. Thanks so much for the help! Answer: So you need to vary each of `a`, `b`, and `c` in the range 0-4 (which is what `range(5)` produces). For this you can use three nested `for` loops. for a in range(5): for b in range(5): for c in range(5): This will ensure that for each possible value of `a`, all possible values of `b` are tried, and similarly, for each possible value of `b`, all possible values of `c` are tried. In other words, the innermost (bottom-most, as they're written) loop `c` will go through 0-4 for each value of `b`, which is also going through 0-4 for each value of `a`, which is _also_ going through 0-4. Now inside these loops, you just need to check to see if the criterion your prof has given is true, and if so, print the numbers. Fortunately, the syntax your prof has given works fine in Python: if 0 < a < b < c < 5: print(a, b, c) Putting it all together, then, we have: for a in range(5): for b in range(5): for c in range(5): if 0 < a < b < c < 5: print(a, b, c) Now, this works fine, and will undoubtedly satisfy your professor, but there are some simple improvements you can make to this program. First, the variables each go from 0-4, but the value 0 is never going to pass the `if` test, because it will never be less than 0! So why even try it? You could save a bit of work by writing each range as `range(1, 5)`. But... there's also the fact that if `a` is 1, `b` can never be 1 (because `a < b` must be true, and if `a` is 2, `b` can likewise never be 2, and so on. And also, from the other end of the range, if `c` is 4, `b` can never be 4 and satisfy the test. We can write the ranges accordingly, so that the range for `b` starts 1 past `a` and leaves off one _before_ `c`, so that those combinations of values need never be tested. Finally, your `if` statement can also be simplified: because of the ranges being used, you don't need to make sure 0 is less than `a`; that will always be true because `a` starts at 1. At the same time, you know that `c` will always be less than 5 because the `range()` makes it that way, so you can remove that test too. So you will get identical results, while doing less work, by writing it like this: for a in range(1, 3): for b in range(a+1, 4): for c in range(b+1, 5): if a < b < c: print(a, b, c) In this case, the extra work is not that important... both versions are so fast you will never notice the extra time the first approach took. But it's always worth thinking about how a problem can be rethought to do less work; sometimes it's the difference between a usable program and an unusable one. In this case, the initial version goes through 125 tests. The second, more efficient version? **Four.** Which happens to be exactly the same as the number of correct results! So we can take out the `if` statement entirely, and just print every combination, because the loops we've written make sure that _only numbers that pass the test are used to begin with._ And we've done less than 1/30th of the work in the process!
i want to set cell using string "," in python excel. but excel is terrible Question: I want to set cell using string "," but it doesn't work. This is my code. import win32com.client xlsfile = "D:\\Temp\\test.xlsx" xl = win32com.client.dynamic.Dispatch("Excel.Application") xl.DisplayAlerts = False wb = xl.Workbooks.open(xlsfile) sh = wb.Sheets[0] sh.Cells(1,1).value = "20342,20343" wb.Save() xl.Quit() I expect the result `20342,20343(string)` but Excel gives the result `2,034,220,343(number)`. Maybe "," is the problem. Excel auto number set is terrible!!!! Answer: Have you tried a leading `'`, e.g. `"'20342,20343"` this informs excel to treat the rest as a string.
Error "unhandled socket.io url" with python as client Question: I am new to Nodejs and using socket.io. But when i connect through python client i am geting error **unhandled socket.io url** **Python code** **client.py** from socketIO_client import SocketIO with SocketIO("192.168.1.191", 8001) as socketIO: socketIO.emit("answer", {"mess":"jdfjdn"}) **Server.js** var ioSocket = require('socket.io').listen(8001, { log: true }); console.log('connect'); ioSocket.sockets.on('connection', function (socket) { socket.on('answer', function (data) { console.log('answer'); }); }); When i run test.py i get the error **"unhandled socket.io url"** Answer: > As your websocket server is running on 192.168.1.191 IP and your client > socket sending request to localhost(127.0.0.1),So you need to change either > 192.168.1.191 to 127.0.0.1 or you need to modify client code to send request > to particular IP Modify client JS code as var io = require('socket.io'); var server = http.createServer(); server.listen(port, ipAddress); var socket = io.listen(server); Enter IP address and port no you want.
Internal Server error: using python script with sqlite + mod_wsgi in apache Question: This is my code example. import sqlite3 def application(environ, start_response): output = "<p> LOG</p>" db = sqlite3.connect('/root/example.db') db.row_factory = sqlite3.Row cursor = db.cursor() cursor.execute('''SELECT id, message,date FROM table''') for row in cursor: print('{0} : {1}, {2}'.format(row['id'], row['message'], row['date'])) db.close() start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')]) return output I get Internal Server Error. How would solve the problem? Answer: Since you webserver (hopefully) doesn't run as the `root`-User, placing your database in the `/root` directory will not work. You habe to put the database in a directory that is writable by your webserver (as it looks to me, that would be `/var/www` for you). And just to prevent further privilege problems, the database file needs to be readable and writable by the webserver as well. On Ubuntu/Debian systems, this can be done with chown www-data:www-data /var/www/example.db
Freeze list copy Question: This might have been asked before, but it's difficult to search for. Basically I am wondering how to make a copy of a list that will not be updated when the list changes. I have been tooling around in Python for a while now--surprised this is the first time I have come across this. var = 10 varcopy = var for i in range(0,5): var = var + i print var print varcopy 10 10 11 10 13 10 16 10 20 list = [] listcopy = list for i in range(0,5): list.append(i) print list print listcopy [0] [0] [0, 1] [0, 1] [0, 1, 2] [0, 1, 2] [0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3, 4] [0, 1, 2, 3, 4] Why is the list copy ALSO being appended to?! How do I freeze it to get: [0] [] [0, 1] [] [0, 1, 2] [] [0, 1, 2, 3] etc... Answer: `list` and `listcopy` both refer to the same object. Here are some ways to make a copy of a list: listcopy = list[:] import copy listcopy = copy.copy(list) # Also make a copy of the objects in the list import copy listcopy = copy.deepcopy(list)
Python csv row count using column name Question: I have a csv file with 'n' columns. I need to get the rowcount of each column using the column name and give out a dictionary of the following format: csv_dict= {col_a:10,col_b:20,col_c:30} where 10,20 and 30 are the row count of col a, b and c respectively. I obtained a list of columns using fieldnames option of Dictreader. Now i need the row count of every column in my list. This is what I tried: for row in csv.DictReader(filename): col_count= sum(1 for row['col_a'] in re)+1 This just gets the row count of column a. How to get the row counts of all the columns in my list and put them in a dictionary in the above mentioned format? Any help appreciated. Thanks and regards. Answer: You can try this: #Save this file with FileName.csv Name,age,DOB abhijeet,17,17/09/1990 raj,17,7/09/1990 ramesh,17,17/09/1990 rani,21,17/09/1990 mohan,21,17/09/1990 nil,25,17/09/1990 #Following is the python code. import csv from collections import defaultdict columns = defaultdict(list) # each value in each column is appended to a list with open('FileName.csv') as f: reader = csv.DictReader(f) # read rows into a dictionary format for row in reader: # read a row as {column1: value1, column2: value2,...} for (k,v) in row.items(): # go over each column name and value if not v=='': columns[k].append(v) # append the value into the appropriate list # based on column name k print len(columns['Name']) #print the length of the specified column print len(columns['age']) #print the length of the specified column print len(columns['DOB']) #print the length of the specified column
how to make a reduced image file in python Question: I'm in a beginning programming class, and our project is to reduce an image to half it's size and then to double it's size. How do I make a new picture that is the same picture as before, but with the reduced height and width? This is the code that I have: def main(): originalPic=makePicture(pickAFile()) show(originalPic) w=getWidth(originalPic) h=getHeight(originalPic) printNow(str(w)+ " \n" + str(h)) if w % 2: reducedW=w/2 else: reducedW=w/2+1 printNow(reducedW) if h % 2: reducedH=h/2 else: reducedH=h/2+1 printNow(reducedH) reducedPic=makePicture(reducedW, reducedH) show(reducedPic) Answer: Here's how I do that in PIL (Pillow): from PIL import Image, ImageTk my_image = Image.open('image.png') # open image my_image = my_image.resize((my_image.size[0] * 2, my_image.size[1] * 2)) # resize my_image.save('new_image.png') # save image tk_image = ImageTk.PhotoImage(my_image) # convert for use in tkinter
Pattern matching in Python regexp Question: How can I use regexp in python to extract the date from an html `<div>` tags. Html is something like this `<div><strong>Date:<\/strong> Monday April 6, 2015 at 4:41PM <div>` I need to get date in "yyyy-dd-mm hh:mm" format. Output for this should be "2015-04-06 16:41" Answer: Instead of approaching the problem with regular expressions (see [RegEx match open tags except XHTML self-contained tags](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except- xhtml-self-contained-tags)), I would use an _HTML Parser_ , [`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/), and [`dateutil`](https://labix.org/python-dateutil) for extracting the date. After extracting the date, use [`strftime()`](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime) to dump it into a string in the desired format: >>> from bs4 import BeautifulSoup >>> from dateutil import parse >>> s = "<div><strong>Date:</strong> Monday April 6, 2015 at 4:41PM <div>" >>> text = soup.find('div').text >>> parse(text, fuzzy=True).strftime("%Y-%d-%m %H:%M") '2015-06-04 16:41'
Installing matplotlib on Codenvy Question: Anyone have experience installing matplotlib on Codenvy(<https://codenvy.com>)? I keep getting following errors trying to run my application: [DOCKER]le "/usr/lib/python3.4/distutils/version.py", line 343, in _cmp [DOCKER] [DOCKER]if self.version < other.version: [DOCKER] [DOCKER]Error: unorderable types: str() < int() [DOCKER] [DOCKER]------------------------------------ [DOCKER] Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-tcimm8pc/matplotlib [DOCKER][ERROR] The command [/bin/sh -c cd /tmp/application && sudo virtualenv /env && sudo /env/bin/pip install -r requirements.txt] returned a non-zero code: 1 [ERROR] We are having trouble starting the runner and deploying application Python. Either necessary files are missing or a fundamental configuration has changed. [ERROR] Unable to retrieve the application logs from the runner.: You tried to detect unknown message. Please, check your message. Your message: The command [/bin/sh -c cd /tmp/application && sudo virtualenv /env && sudo /env/bin/pip install -r requirements.txt] returned a non-zero code: 1 My requirements.txt contains: numpy matplotlib Answer: The output is the following: matplotlib: yes [1.4.3] python: yes [2.7.9 (default, Mar 1 2015, 12:57:24) [GCC 4.9.2]] platform: yes [linux2] REQUIRED DEPENDENCIES AND EXTENSIONS numpy: yes not found. pip may install it below. six: yes six was not found.pip will attempt to install it after matplotlib. dateutil: yes dateutil was not found. It is required for date axis support. pip/easy_install may attempt to install it after matplotlib.] pytz: yes pytz was not found. pip will attempt to install it after matplotlib. tornado: yes tornado was not found. It is required for the WebAgg backend. pip/easy_install may attempt to install it after matplotlib. pyparsing: yes pyparsing was not found. It is required for mathtext support. pip/easy_install may attempt to install it after matplotlib. pycxx: yes Couldn't import. Using local copy. libagg: yes pkg-config information for 'libagg' could not be found. Using local copy. freetype: no The C/C++ header for freetype2 (ft2build.h) could not be found. You may need to install the development package. png: no pkg-config information for 'libpng' could not be found. qhull: yes pkg-config information for 'qhull' could not be found. Using local copy. Some dependencies are missing. Take a look at similar threads: [Matplotlib compilation error: TypeError: unorderable types: str() < int()](http://stackoverflow.com/questions/27024731/matplotlib-compilation- error-typeerror-unorderable-types-str-int) [Installing matplotlib and its dependencies without root privileges](http://stackoverflow.com/questions/20904841/installing-matplotlib- and-its-dependencies-without-root-privileges)
Python Downloading Data File from Web-Scraped URL Question: I'm trying to develop an automated script to download the following data file to a utility server and then ETL related processing. Looking for pythonic suggestions. Not familiar with the current best options for this type of process between urllib, urllib2, beautiful soup, requests, mechanize, selenium, etc. [The Website](http://nppes.viva-it.com/NPI_Files.html) "Full Replacement Monthly NPI File" [The Monthly Data File](http://nppes.viva- it.com/NPPES_Data_Dissemination_March_2015.zip) The file name (and subsequent url) changes monthly. Here is my current approach thus far: from bs4 import BeautifulSoup import urllib import urllib2 soup = BeautifulSoup(urllib2.urlopen('http://nppes.viva-it.com/NPI_Files.html').read()) download_links = [] for link in soup.findAll(href=True): urls = link.get('href', '/') download_links.append(urls) target_url = download_links[2] urllib.urlretrieve(target_url , "NPI.zip") I am not anticipating the content on this clunky govt. site to change, so I though just selecting the 3rd element of the scraped url list would be good enough. Of course, if my entire approach is wrongheaded, I welcome correction (data analytics is the personal forte). Also, if I am using outdated libraries, unpythonic practices, or low performance options, I definitely welcome the newer and better! Answer: In general [requests](http://docs.python-requests.org/en/latest/) is the easiest way to get webpages. If the name of the data files _follows the pattern_ `NPPES_Data_Dissemination_<Month>_<year>.zip`, which seems logical, you can request that directly; import requests url = "http://nppes.viva-it.com/NPPES_Data_Dissemination_{}_{}.zip" r = requests.get(url.format("March", 2015)) The data is then in `r.text`. If the data-file name is less certain, you can get the webpage and use a regular expression to search for links to `zip` files; In [1]: import requests In [2]: r = requests.get('http://nppes.viva-it.com/NPI_Files.html') In [3]: import re In [4]: re.findall('http.*NPPES.*\.zip', r.text) Out[4]: ['http://nppes.viva-it.com/NPPES_Data_Dissemination_March_2015.zip', 'http://nppes.viva-it.com/NPPES_Deactivated_NPI_Report_031015.zip', 'http://nppes.viva-it.com/NPPES_Data_Dissemination_030915_031515_Weekly.zip', 'http://nppes.viva-it.com/NPPES_Data_Dissemination_031615_032215_Weekly.zip', 'http://nppes.viva-it.com/NPPES_Data_Dissemination_032315_032915_Weekly.zip', 'http://nppes.viva-it.com/NPPES_Data_Dissemination_033015_040515_Weekly.zip', 'http://nppes.viva-it.com/NPPES_Data_Dissemination_100614_101214_Weekly.zip'] The regular expression in In[4] basically says to find strings that start with "http", contain "NPPES" and end with ".zip". This isn't speficic enough. Let's change the regular expression as shown below; In [5]: re.findall('http.*NPPES_Data_Dissemination.*\.zip', r.text) Out[5]: ['http://nppes.viva-it.com/NPPES_Data_Dissemination_March_2015.zip', 'http://nppes.viva-it.com/NPPES_Data_Dissemination_030915_031515_Weekly.zip', 'http://nppes.viva-it.com/NPPES_Data_Dissemination_031615_032215_Weekly.zip', 'http://nppes.viva-it.com/NPPES_Data_Dissemination_032315_032915_Weekly.zip', 'http://nppes.viva-it.com/NPPES_Data_Dissemination_033015_040515_Weekly.zip', 'http://nppes.viva-it.com/NPPES_Data_Dissemination_100614_101214_Weekly.zip'] This gives us the URLs of the file we want but also the weekly files. In [6]: fileURLS = re.findall('http.*NPPES_Data_Dissemination.*\.zip', r.text) Let's filter out the weekly files: In [7]: [f for f in fileURLS if 'Weekly' not in f] Out[7]: ['http://nppes.viva-it.com/NPPES_Data_Dissemination_March_2015.zip'] This is the URL you seek. But this whole scheme does depend on how regular the names are. You can add flags to the regular expression searches to discard the case of the letters, that would make it accept more.
Why can shapely/geos parse this 'invalid' Well Known Binary? Question: I am trying to parse [Well Known Binary](https://en.wikipedia.org/wiki/Well- known_text#Well-known_binary) a binary encoding of geometry objects used in Geographic Information Systems (GIS). I am using [this spec from ESRI](http://edndoc.esri.com/arcsde/9.1/general_topics/wkb_representation.htm) (same results [here from esri](http://webhelp.esri.com/arcgisserver/9.3/dotnet/index.htm#geodatabases/the_ogc_103951442.htm)). I have input data from [Osmosis](http://wiki.openstreetmap.org/wiki/Osmosis) a tool to parse OpenStreetMap data, specifically the [pgsimp-dump format](http://wiki.openstreetmap.org/wiki/Osmosis/Detailed_Usage_0.43#--write- pgsimp-dump_.28--wsd.29) which gives the hex represenation of the binary. The ESRI docs say that there should only be 21 bytes for a `Point`, 1 byte for byte order, 4 for uint32 for typeid, and 8 for double x and 8 for double y. An example from osmosis is this (hex) example: `0101000020E6100000DB81DF2B5F7822C0DFBB7262B4744A40`, which is 25 bytes long. [Shapely](http://toblerity.org/shapely/) a python programme to parse WKB (etc), which is based on the popular C library [GEOS](http://trac.osgeo.org/geos/) **is** able to parse this string: >>> import shapely.wkb >>> shapely.wkb.loads("0101000020E6100000DB81DF2B5F7822C0DFBB7262B4744A40", hex=True) <shapely.geometry.point.Point object at 0x7f221f2581d0> When I ask Shapely to parse from then convert to WKB I get a 21 bytes. >>> shapely.wkb.loads("0101000020E6100000DB81DF2B5F7822C0DFBB7262B4744A40", hex=True).wkb.encode("hex").upper() '0101000000DB81DF2B5F7822C0DFBB7262B4744A40' The difference is the 4 bytes in the middle, which appear 3 bytes into the uint32 for the typeif=d 01010000**20E61000**00DB81DF2B5F7822C0DFBB7262B4744A40 Why can shapely/geos parse this WKB when it's invalid WKB? What do these bytes mean? Answer: GEOS / Shapely use an Extended variant of WKT/WKB called EWKT / EWKB, which is [documented](https://github.com/postgis/postgis/blob/2.1.0/doc/ZMSgeoms.txt) by PostGIS. If you have access to PostGIS, you can see what's going on here: SELECT ST_AsEWKT('0101000020E6100000DB81DF2B5F7822C0DFBB7262B4744A40'::geometry); Returns the EWKT `SRID=4326;POINT(-9.2351011 52.9117549)`. So the extra data was the spatial reference identifier, or SRID. Specifically [EPSG:4326](http://epsg.io/4326) for WGS 84. Shapely [does not support SRIDs](https://github.com/Toblerity/Shapely/pull/132), however there are a few hacks, e.g.: from shapely import geos geos.WKBWriter.defaults['include_srid'] = True should now make `wkb` or `wkb_hex` output the EWKB, which includes the SRID. The default is `False`, which would output ISO WKB for 2D geometries (but not for 3D). So it seems your objective is to convert EWKB to ISO WKB, which you can do with GEOS / Shapely for 2D geometries only. If you have 3D (Z or M) or 4D (ZM) geometries, then only PostGIS is able to do this conversion.
Python How to find average of columns using dataframes apply method Question: This is a question on Udacity Data Science Nanodegree and I can't figure it out. The instructions are: Using the dataframe's apply method, create a new Series called `avg_medal_count` that indicates the average number of gold, silver, and bronze medals earned amongst countries who earned at least one medal of any kind at the 2014 Sochi Olympics. The code I have currently is: import numpy from pandas import DataFrame, Series def avg_medal_count(): countries = ['Russian Fed.', 'Norway', 'Canada', 'United States', 'Netherlands', 'Germany', 'Switzerland', 'Belarus', 'Austria', 'France', 'Poland', 'China', 'Korea', 'Sweden', 'Czech Republic', 'Slovenia', 'Japan', 'Finland', 'Great Britain', 'Ukraine', 'Slovakia', 'Italy', 'Latvia', 'Australia', 'Croatia', 'Kazakhstan'] gold = [13, 11, 10, 9, 8, 8, 6, 5, 4, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0] silver = [11, 5, 10, 7, 7, 6, 3, 0, 8, 4, 1, 4, 3, 7, 4, 2, 4, 3, 1, 0, 0, 2, 2, 2, 1, 0] bronze = [9, 10, 5, 12, 9, 5, 2, 1, 5, 7, 1, 2, 2, 6, 2, 4, 3, 1, 2, 1, 0, 6, 2, 1, 0, 1] olympic_medal_counts = {'country_name':countries, 'gold': Series(gold), 'silver': Series(silver), 'bronze': Series(bronze)} df = DataFrame(olympic_medal_counts) # YOUR CODE HERE return avg_medal_count I have tried a couple different things such as: `avg_medal_count = df.apply(numpy.mean)`, but get the error saying it could not convert the first column to numeric which makes sense because the first column is a list of countries. How can I use `df.apply` on only gold, silver and bronze columns? I have tried other variations, but nothing worked. I am pretty sure that I need to use a combination of `df.apply` and `numpy.mean`, because that is what I just learned about. Any thoughts? Thanks! Answer: I would first modify how you import the data to: df = DataFrame(olympic_medal_counts).set_index('country_name') I would then calculate a new column containing the sum of the rows for the toal number of medals per country. df['medal total'] = df.sum(axis=1) Results: bronze gold silver medal total country_name Russian Fed. 9 13 11 33 Norway 10 11 5 26 Canada 5 10 10 25 United States 12 9 7 28 Netherlands 9 8 7 24 Germany 5 8 6 19 Switzerland 2 6 3 11 Belarus 1 5 0 6 Austria 5 4 8 17 France 7 4 4 15 Poland 1 4 1 6 China 2 3 4 9 Korea 2 3 3 8 Sweden 6 2 7 15 Czech Republic 2 2 4 8 Slovenia 4 2 2 8 Japan 3 1 4 8 Finland 1 1 3 5 Great Britain 2 1 1 4 Ukraine 1 1 0 2 Slovakia 0 1 0 1 Italy 6 0 2 8 Latvia 2 0 2 4 Australia 1 0 2 3 Croatia 0 0 1 1 Kazakhstan 1 0 0 1 Finally, subset the the DataFrame for rows with medal totals greater than or equal to 1 and find the average of the columns. df[df['medal total'] >= 1].apply(np.mean) Results: bronze 3.807692 gold 3.807692 silver 3.730769 medal total 11.346154 This could also be accomplished in one line using: df[ df.sum(axis=1) >= 1 ].apply(np.mean)
Changing line in file based on previous lines - Python Question: Relatively new to python, trying to figure out the most general and readable way to attack this problem. Execution speed wouldn't be bad either, but its a secondary concern. I have an input file for another program that I need to edit automatically. The format is similar to the following: ---Thousands of lines that can be ignored--- &Brand: Ford &Define Class &Model: Sedan &Parameter: Cost &Dollars &25000 &Parameter: Stock &Quantity &14 &Brand: Honda &Define Class &Model: Sedan &Parameter: Cost &Dollars &22000 &Parameter: Stock &Quantity &17 &Model: SUV &Parameter: Cost &Dollars &35000 &Parameter: Stock &Quantity &7 ---Thousands of lines that can be ignored--- My code needs to automatically change the numerical parameters. The trouble I'm having is that I'm not just matching a single condition and changing a line, I'm matching unique combinations of non-unique lines (Parameter: Cost appears three times, twice under Model: Sedan and twice under Brand: Honda, but only once under both of those conditions). Right I'm storing the new parameters in a nested dictionary, like: params = {'Ford': {'Sedan': {'Cost': 17000, 'Stock': 43}}, 'Honda':{'Sedan': {'Cost': 19000, 'Stock': 12}, {'Truck': {'Cost': 33000, 'Stock': 5}}} In this way I can do `for brand in params.keys()` and then `for model in params[brand].keys()` and so on. I have the basics of opening, closing, and modifying files down, it is identifying the correct lines to be modified that I'm having trouble with. Thanks for any help. Ex: For the above sample dictionary, the ideal output would be: ---Thousands of lines that can be ignored--- &Brand: Ford &Define Class &Model: Sedan &Parameter: Cost &Dollars &17000 &Parameter: Stock &Quantity &43 &Brand: Honda &Define Class &Model: Sedan &Parameter: Cost &Dollars &19000 &Parameter: Stock &Quantity &12 &Model: SUV &Parameter: Cost &Dollars &33000 &Parameter: Stock &Quantity &5 ---Thousands of lines that can be ignored--- Answer: Have to looked at Python's regular expressions? Take a look at the 're' package. You can use that to search for numerical entries. You can identify the lines of interest like this (from the top of my head and not checked): import re ... m = re.match(r'&(\d+)', the_line) if m: print 'found ', m.group(1) # modify it... The expression matches any number of digits (the \d+ part). Not sure if & is special, but if it is you can put in in square brackets. Granted, You'll need similar regular expressions to capture that the line before is cost, and then capture the value. You can do that with a simple flag to signal net line is cost. See <https://docs.python.org/2/library/re.html>
Merge semicolon delimited txt file looping in directory Question: Suppose I have many different text files from the same directory with the content structure as shown below: File a.txt: HEADER_X;HEADER_Y;HEADER_Z a_value;a_value;a_value a_value;a_value;a_value File b.txt: HEADER_X;HEADER_Y;HEADER_Z b_value;b_value;b_value b_value;b_value;b_value File c.txt: HEADER_X;HEADER_Y;HEADER_Z c_value;c_value;c_value c_value;c_value;c_value File d.txt: ... I'd like to merge all of the txt files into one, by appending the content of each file to the final row of the each previous file. See below: File combined.txt: HEADER_X;HEADER_Y;HEADER_Z a_value;a_value;a_value a_value;a_value;a_value b_value;b_value;b_value b_value;b_value;b_value c_value;c_value;c_value c_value;c_value;c_value ... How can I do this in Python? Assumptions: \- all txt files are located in the same folder \- all txt files have same headers \- all txt files have same number of columns \- all txt files have different number of rows Answer: Use the [CSV Module](https://docs.python.org/2/library/csv.html). Something like this: import csv with ('output.csv', 'ab') as output: writer = csv.writer(output, delimiter=";") with open('a.txt', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=";") reader.readline() // this is to skip the header for row in spamreader: writer.writerow(row) If you didn't want to harcode in every file (Say you have many more than three) you could do: from os import listdir from os.path import isfile, join onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ] for aFile in onlyfiles: with open(aFile, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=";") reader.readline() // this is to skip the header for row in spamreader: writer.writerow(row)
convert image to byte literal in python Question: I'm trying to store an image as text, so that I can do something like this example of a transparent icon for a Tk gui: import tempfile # byte literal code for a transparent icon, I think ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00' b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00' b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x01\x00\x00\x00\x01') + b'\x00'*1282 + b'\xff'*64 # makes a temp file for the transparent icon and saves it _, ICON_PATH = tempfile.mkstemp() with open(ICON_PATH, 'wb') as icon_file: icon_file.write(ICON) I've tried base 64 encoding, decoding with utf8, converting to bytes and bytearray, and some answers from another post: ([Python Script to convert Image into Byte array](http://stackoverflow.com/questions/22351254/python- script-to-convert-image-into-byte-array)) import tempfile, base64, io # byte literal code for a transparent icon, I think ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00' b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00' b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x01\x00\x00\x00\x01') + b'\x00'*1282 + b'\xff'*64 # makes a temp file for the transparent icon and saves it _, ICON_PATH = tempfile.mkstemp() with open(ICON_PATH, 'wb') as icon_file: icon_file.write(ICON) a = open(ICON_PATH, 'rb').read() b = base64.b64encode(a) print b # output does not match what ICON equals above #b = bytes(a).decode('utf-8') # doesn't work -- gives error UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 1342: invalid start byte c = bytearray(a) print c # prints garbled junk # gives error AttributeError: __exit__ on Image.open(ICON_PATH) line with io.BytesIO() as output: from PIL import Image with Image.open(ICON_PATH) as img: img.convert('RGB').save(output, 'BMP') data = output.getvalue()[14:] print data It also doesn't work for b.decode('utf-8') or b.encode('utf-8') Answer: I think you're just not printing out the data properly -- there doesn't seem to be any need to mess around with `base64` doing this. Here's proof: from itertools import izip import tempfile # byte literal code for a transparent icon, I think ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00' b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00' b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x01\x00\x00\x00\x01') + b'\x00'*1282 + b'\xff'*64 # make a temp file from ICON data for testing _, ICON_PATH = tempfile.mkstemp() with open(ICON_PATH, 'wb') as icon_file: icon_file.write(ICON) # Convert raw data in the file into a valid Python string literal. # helper function def grouper(n, seq): "s -> (s0,s1,...sn-1), (sn,sn+1,...s2n-1), (s2n,s2n+1,...s3n-1), ..." for i in xrange(0, len(seq), n): yield seq[i:i+n] # read data file in binary mode a = open(ICON_PATH, 'rb').read() # create Python code to define string literal code = '\n'.join(['ICON2 = ('] + [' '+repr(group) for group in grouper(16, a)] + [')']) print 'len(ICON): {}'.format(len(ICON)) print 'len(a): {}'.format(len(a)) print code exec(code) print print 'len(ICON2): {}'.format(len(ICON2)) print 'ICON2 == ICON: {}'.format(ICON2 == ICON) Output: len(ICON): 1406 len(a): 1406 ICON2 = ( '\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05' '\x00\x00\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00' '\x00\x00\x01\x00\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' ... '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff' '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' ) len(ICON2): 1406 ICON2 == ICON: True
Trying to figure out longest path algorithm python Question: I'm trying to make a python script, that gets me the longest repeated character in a given matrix (horizontally and vertically). **Example:** I have this matrix: afaaf rbaca rlaff Giving this matrix for input, it should result: **a 3** You can see that that the 3rd column of the matrix, is full of a's and also, it's the most repeated character in the matrix. **What I have:** #!/bin/python2.7 #Longest string in matrix #Given a matrix filled with letters. Find the longest string, containing only the same letter, which can be obtained by starting #with any position and then moving horizontally and vertically (each cell can be visited no more than 1 time). # Settings here # ------------- string_matrix = """ afaaf rbaca rlaff """ pos = (0,0) # ------------- import pdb import time import collections from collections import defaultdict import re rows = 0 columns = 0 matrix = [] matrix2 = [] counter = 0 res_l = [] i = 0 c = '' # if matrix2 is full of 1's, stop def stop(): for i in range(0, rows): for j in range(0, columns): if matrix2[i][j] == 0: return False return True # checks the points, and returns the most repeated char and length def check_points(points1, points2): r = [] r.append(-1) r.append('') # create strings from matrix s1 = '' s2 = '' for point in points1: s1 += matrix[point[0]][point[1]] for point in points2: s2 += matrix[point[0]][point[1]] rr = {} for c in s1: rr[c] = 0 for c in s2: rr[c] = 0 for i in range(0, len(s1)): k = 1 for j in range(i+1, len(s1)): if s1[i] == s1[j]: k += 1 else: break if k > rr[s1[i]]: rr[s1[i]] = k for i in range(0, len(s2)): k = 1 for j in range(i+1, len(s2)): if s2[i] == s2[j]: k += 1 else: break if k > rr[s2[i]]: rr[s2[i]] = k m = -1 c = '' for key,value in rr.iteritems(): if value > m: m = value c = key return m, c # Depth-first search, recursive def search(pos): global res_l global matrix2 global c counter = 0 x = pos[0] y = pos[1] c = matrix[x][y] # base clause # when matrix2 is all checked if stop(): return counter, c points1 = [] points2 = [] allpoints = [] for i in range(0, columns): if matrix2[x][i] != 1: points1.append([x, i]) allpoints.append([x, i]) for i in range(0, rows): if matrix2[i][x] != 1: points2.append([i, x]) allpoints.append([i, x]) r = check_points(points1, points2) if r[0] > counter: counter = r[0] c = r[1] matrix2[x][y] = 1 for point in allpoints: rr = search(point) if rr[0] > counter: counter = int(rr[0]) c = rr[1] #print 'c: ' + str(c) + ' - k: ' + str(counter) return counter, c def main(): # create the matrix from string string_matrix_l = string_matrix.strip() splited = string_matrix_l.split('\n') global rows global columns global matrix global matrix2 rows = len(splited) columns = len(splited[1]) # initialize matrixes with 0 matrix = [[0 for x in range(columns)] for x in range(rows)] matrix2 = [[0 for x in range(columns)] for x in range(rows)] # string to matrix i = 0 for s in splited: s = s.strip() if s == '': continue j = 0 for c in s: try:## Heading ## matrix[i][j] = c #print 'ok: ' + str(i) + ' ' + str(j) + ' ' + c except: print 'fail: index out of range matrix[' + str(i) + '][' + str(j)+'] ' + c j = j + 1 i = i + 1 # print some info print 'Given matrix: ' + str(matrix) + '\n' print 'Start position: ' + str(pos) print 'Start character: ' + str(matrix[pos[0]][pos[1]]) # get the result res = search(pos) print '-------------------------------------' print '\nChar: ' + str(res[1]) + '\nLength: ' + str(res[0]) if __name__ == "__main__": main() This is my source code. The example given above, is also used in the source code. The result given is: **r 2** which is wrong ... again, should be **a 3** It has 4 functions: main, search, stop and check_points. * main is initializing things up, * search is my recursive function that takes one parameter (the start point), and should recursively check for the longest string. I have another matrix, same length as original, which is just 1 and 0. 1 means the position was visited, 0, not. The search function is setting 1 on the right position after a certain position was processed by the search function. * stop is checking if matrix2 is full of 1's, in this case, the matrix was all parsed * check_points takes 2 parameters, 2 list of points, and returns the most repeated character and it's length for those points **What doesn't work:** Most of the time is giving me the wrong character as result, even thought the count might be right sometimes. Sometimes it's working on horizontally, sometimes it doesn't. I am sure that I'm doing something wrong, but ... it's over 1 week now since I'm trying to figure out how to do this. Asked another question here on stackoverflow, got bit further but ... still stuck. Any suggestion is appreciated. Answer: You can use `itertools.groupby` to quickly find the count of repetitions of some character, and `izip_longest(*matrix)` to transpose the matrix (swap its rows and columns). from itertools import groupby, izip_longest matrix_string = """ afaaf rbaca rlaff """ def longest_repetition(row): return max((sum(1 for item in group), letter) for letter, group in groupby(row) if letter is not None) def main(): matrix = [[letter for letter in row.strip()] for row in matrix_string.strip().split('\n')] count, letter = max( max(longest_repetition(row) for row in matrix), max(longest_repetition(col) for col in izip_longest(*matrix)) ) print letter, count if __name__ == '__main__': main() Since you've updated the requirement here is a recursive version of the code with some explanations. If it were not an assignment and this task came up in some real life problem, you should really have used the first version. matrix_string = """ afaaf rbaca rlaff """ def find_longest_repetition(matrix): rows = len(matrix) cols = len(matrix[0]) # row, col - row and column of the current character. # direction - 'h' if we are searching for repetitions in horizontal direction (i.e., in a row). # 'v' if we are searching in vertical direction. # result - (count, letter) of the longest repetition we have seen by now. # This order allows to compare results directly and use `max` to get the better one # current - (count, letter) of the repetition we have seen just before the current character. def recurse(row, col, direction, result, current=(0, None)): # Check if we need to start a new row, new column, # new direction, or finish the recursion. if direction == 'h': # If we are moving horizontally if row >= rows: # ... and finished all rows return recurse( # restart from the (0, 0) position in vertical direction. 0, 0, 'v', result ) if col >= cols: # ... and finished all columns in the current row return recurse( # start the next row. row + 1, 0, direction, result ) else: # If we are moving vertically if col >= cols: # ... and finished all columns return result # then we have analysed all possible repetitions. if row >= rows: # ... and finished all rows in the current column return recurse( # start the next column. 0, col + 1, direction, result ) # Figure out where to go next in the current direction d_row, d_col = (0, 1) if direction == 'h' else (1, 0) # Try to add current character to the current repetition count, letter = current if matrix[row][col] == letter: updated_current = count + 1, letter else: updated_current = 1, matrix[row][col] # Go on with the next character in the current direction return recurse( row + d_row, col + d_col, direction, max(updated_current, result), # Update the result, if necessary updated_current ) return recurse(0, 0, 'h', (0, None)) def main(): matrix = [[letter for letter in row.strip()] for row in matrix_string.strip().split('\n')] count, letter = find_longest_repetition(matrix) print letter, count if __name__ == '__main__': main()
Python 2.7 encoding Question: I am trying to write a xml file from python (2.7) using xml.append function. I have a string "Frédéric" that needs to be written to xml file as one of the values. I am trying to use unicode function on this string and then encode function to write to the file. a ="Frédéric" unicode(a, 'utf8') By I get error message as _'ascii' codec can't decode byte 0xe9 in position 9'_ I have gone through other stackoverflow posts for this scenario, the suggestion was to add unicode-literal before the string. a = u'Frédéric' a.encode('utf8') Since, my 'a' variable is going to be dynamic (it can take any value from a list) I need to use unicode function. Any suggestions please? Thanks Answer: Maybe following helps. You can use codecs to save the XML string while using utf-8. import codecs def save_xml_string(path, xml_string): """ Writes the given string to the file associated with the given path. :param path: Path to the file to write to. :param xml_string: The string to be written :return: nothing """ output_file = codecs.open(path, "w", "utf-8") output_file.write(xml_string) output_file.close()
Authentication in pyramid Question: I am trying to set up a basic navigation in pyramid (1.4a1). According to the tutorial given at [tutorial](http://sluggo.scrapping.cc/python/Akhet/auth.html) _groupfinder_ is called once we remember after login is successful. This works on my local but when I try the same on a server it doesn't call groupfinder at all and keeps looping between the two routes. Here's my code snippet: from pyramid.security import remember, forget, authenticated_userid from pyramid.httpexceptions import HTTPFound, HTTPForbidden from pyramid.threadlocal import get_current_registry from pyramid.url import route_url from pyramid.view import view_config, forbidden_view_config @view_config(route_name='index', renderer='templates:templates/index.pt', permission='Authenticated') def index_view(request): try: full_name = (request.user.first_name + ' ' + request.user.last_name) except: full_name = "Anonymous" return {"label": label, "user_name": full_name} @forbidden_view_config() def forbidden(request): if authenticated_userid(request): return HTTPForbidden() loc = request.route_url('login.view', _query=(('next', request.path),)) return HTTPFound(location=loc) @view_config(route_name='login.view') def login_view(request): came_from = request.route_url('index') #perform some authentication username = 'xyz' if authenticate(username): headers = remember(request, username) #user was authenticated. Must call groupfinder internally and set principal as authenticated. return HTTPFound(location=came_from, headers=headers) else: return HTTPForbidden('Could not authenticate.') return HTTPForbidden('Could not authenticate.') Also, my ACL looks like: `__acl__ = [(Allow, Authenticated, 'Authenticated'), DENY_ALL]`. Can someone tell my why groupfinder is not being called? Is the request routing happening properly? Also, the same code works on my local setup fine. So there is no problem in groupfinder or ACL authorization settings. Thanks much! Answer: After lot of debugging and digging up I found out that the issue was very simple. Don't know the reason for the behavior but I had added `secure = True` attribute when calling `AuthTktAuthenticationPolicy()`. When I removed this attribute, it started working.