text
stringlengths
226
34.5k
Explain time and space complexity of two python codes. Which one is the best? (Non- subjective) Question: These codes gives the sum of even integers in a list without using loop statement. I would like to know the time complexity and space complexity of both codes. which is best? CODE 1: class EvenSum: #Initialize the class def __init__(self): self.res = 0 def sumEvenIntegers(self, integerlist): if integerlist: if not integerlist[0] % 2: self.res += integerlist[0] del integerlist[0] self.sumEvenIntegers(integerlist) else: del integerlist[0] self.sumEvenIntegers(integerlist) return self.res #main method if __name__ == "__main__": l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even = EvenSum() print even.sumEvenIntegers(l) CODE 2: import numpy as np def sum_of_all_even_integers(list): list_sum = sum(list) bin_arr = map(lambda x:x%2, list) return list_sum - sum(list*bin_arr) if __name__ == "__main__": list = np.array([1,2,3,4,5,6,7,8,9,10]) print sum_of_all_even_integers(list) Answer: According to the [Python wiki](https://wiki.python.org/moin/TimeComplexity), deleting an item from a list takes linear time proportional to the number of elements in the list. Since you delete every item in the list, and each deletion takes linear time, the overall runtime is proportional to the square of number of items in the list. In your second code snippet, both `sum` as well as `map` take linear time. So the overall complexity is linear proportional to the number of elements in the list. Interestingly, `sum_of_elements` isn't used at all (but it doesn't sum all even elements either).
PySide and Python - How to browse a folder and write the file name? Question: I would like to press a button and than open a file browser and write down selected file in a label. I have this function which I call when the button is pressed: @Slot() def browse_folder(self): self.fname = QtGui.QFileDialog.getOpenFileName() self.statusLabel.setText(self.fname) However, I get an error: TypeError: 'PySide.QtGui.QLabel.setText' called with wrong argument types: PySide.QtGui.QLabel.setText(unicode, unicode) Supported signatures: PySide.QtGui.QLabel.setText(unicode) How do I convert `self.fname`, which holds selected file name, as unicode? Answer: The PySide docs are not brilliant on this. But the easiest way to answer this sort of question is to build a little test harness. Something like: from PySide import QtCore,QtGui def do_file(): fname = QtGui.QFileDialog.getOpenFileName() print fname app = QtGui.QApplication([]) button = QtGui.QPushButton("Test File") button.clicked.connect(do_file) button.show() app.exec_() Running this a little bit will show you that the static `getOpenFileName` method returns a tuple consisting of the filename first and the chosen filter second. For example, by default, on my system this returns `('C:/Users/Myname/Documents/filename', 'All Files (*.*)')`. So you then need to extract the first element of the tuple before calling `setText`.
python requests ssl handshake failure Question: Every time I try to do: requests.get('https://url') I got this message: import requests >>> requests.get('https://reviews.gethuman.com/companies') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/requests/api.py", line 55, in get return request('get', url, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/api.py", line 44, in request return session.request(method=method, url=url, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 455, in request resp = self.send(prep, **send_kwargs) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 558, in send r = adapter.send(request, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 385, in send raise SSLError(e) requests.exceptions.SSLError: [Errno 1] _ssl.c:510: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure I tried everything: * update my requests * update my ssl but nothing changes. I am using Python 2.7.6, can't change this. Answer: I resolve the problem in the end i updated my ubuntu from 14.04 to 14.10 and the problem was solved but in the older version of ubuntu and python I install those lib and it seems to fix all my problems sudo apt-get install python-dev libssl-dev libffi-dev sudo pip2.7 install -U pyopenssl==0.13.1 pyasn1 ndg-httpsclient if you don`t have pip2.7 installed you can use pip instead
Automating powerpoint using python. How to access format axis objects Question: Currently I'm working on Python to automate a powerpoint file. I'm using win32com.client to access the various objects needed. However I haven't been able to find any documentation on chart objects. can someone point me in the right direction. import win32com.client PPTApplication = win32com.client.Dispatch("PowerPoint.Application") PPTApplication.Visible = True PPTFile = PPTApplication.Presentations.Open("D:\test.pptx") x=PPTFile.Slides(1).Shapes("Chart1").Chart.ChartData.Workbook.Sheets(1).Range("A1","C13").Value The code above allows me to access the data for chart1. How do I access the format axis options???? Or where can I find the documentation for the same. Answer: The PowerPoint Chart object API is documented here: <https://msdn.microsoft.com/EN-US/library/office/ff746468.aspx> The direction you'll want to head is `Chart.Axes()`, perhaps `Chart.Axes(xlValue)`. Once you have the axis you want, you have the properties and methods listed here available to you: <https://msdn.microsoft.com/EN- US/library/office/ff745187.aspx> In my experience, it sometimes takes some digging to come up with the path to the right attribute, but that's the general procedure. Usually when I don't find what I'm looking for I search on 'vba powerpoint chart font color' or whatever specific call I'm looking for and the example VBA code shows the "path" through the object hierarchy to the property I need.
gdata autentication trouble python Question: I ran for awhile a python script to post articles on my blogspot blog. everything ran smoothly until I started to get this auth error RequestError: {'status': 401, 'body': 'User does not have permission to create new post', 'reason': 'Unauthorized'} I really can't understand how to fix it reading gdata documentation. Could you please suggest me how to do? Thank you Here the part of my code that doesn't work anymore: from gdata import service import gdata import atom blogger_service = service.GDataService('xxxxxx','xxxxxx') blogger_service.service = 'blogger' blogger_service.account_type = 'GOOGLE' blogger_service.server = 'www.blogger.com' blogger_service.ProgrammaticLogin() def CreatePublicPost(blogger_service, blog_id, title, content,tags): entry = gdata.GDataEntry() entry.title = atom.Title('xhtml', title) entry.content = atom.Content(content_type='html', text=content) for tag in tags : category = atom.Category(term=tag, scheme="http://www.blogger.com/atom/ns#") entry.category.append(category) return blogger_service.Post(entry, '/feeds/%s/posts/default' % blog_id) Answer: Now there is a API version 3.0... This old version is obsolete and no longer works, apparently... You can find more about it here: <https://developers.google.com/blogger/> <https://developers.google.com/blogger/docs/3.0/using/> And if you have questions about authentication, maybe those links help: [Having trouble trying to use gdata and oauth2 in python](http://stackoverflow.com/questions/30519537/having-trouble-trying-to- use-gdata-and-oauth2-in-python/) [Authentication with the Google Docs List API, Python and OAuth 2](http://stackoverflow.com/questions/10907087/authentication-with-the-google- docs-list-api-python-and-oauth-2?rq=1/)
Comparing tuple elements against integers with Python Question: I am having a hard time converting data. I select the data from my database, which is returned in tuple format. I try to convert them using `list()`, but all I get is a list of tuples. I am trying to compare them to integers which i receive from parsing my JSON. What would be the easiest way to convert and compare these two? from DBConnection import db import pymssql from data import JsonParse db.execute('select id from party where partyid = 1') parse = JsonParse.Parse() for row in cursor: curList = list(cursor) i = 0 for testData in parse: print curList[i], testData['data'] i += 1 Output: (6042,) 6042 (6043,) 6043 (6044,) 6044 (6045,) 6045 Answer: Quick and dirty: `print curList[i][0], testData['data']` Or how about: for db_tuple, json_int in zip(cursor, parse): print db_tuple[0], json_int
django render the same page after post Question: I am trying to create a form that gets JSON inputs through a textarea(textarea1) and then processes it and prints the response back in another text area(textarea2) while still showing the original json input from textarea1. I have the code that takes the input computes the result and puts the value back. But the values are not shown in the new form. My server does not use any models. Here is the code from views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect import simplejson import read_json from .forms import JsonTestForm import sys import traceback def index(request): form = JsonTestForm() return render(request, 'ellora/index.html', {'form': form}) def get_json_text(request): print "Enter method get_json_text" if request.method == 'POST': print "request method is post" form = JsonTestForm(request.POST) if form.is_valid(): print "form is valid" #call the read_json.py and pass the json script in the appropriate format # capture the result of it in some way and then redirect it to the results page try: data_string=form.cleaned_data['jsonText'] data = simplejson.loads(data_string) #do some processing of the data here f = open("temp/test7777777.py", "r") form.cleaned_data['pythonScript'] = f.read() return render(request, "ellora/index.html", {"form": form}) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) print ''.join('! ' + line for line in lines) mystr = ''.join('! ' + line for line in lines) form.cleaned_data['pythonScript'] = mystr print "cleanded_data=", form.cleaned_data['pythonScript'] return render(request, "ellora/index.html", {"form": form}) else: print "request type was not POST" code from my forms.py from django import forms class JsonTestForm(forms.Form): jsonText = forms.CharField(label="", widget=forms.Textarea(attrs={"class": "txtarea", "placeholder": "Enter your json script here"}), initial="[]") pythonScript = forms.CharField(label="", widget=forms.Textarea(attrs={ "class": "txtarea", "readonly": "readonly", "rows": "1", "cols": ""}), initial="python script here") testLog = forms.CharField(label="", widget=forms.Textarea(attrs={ "class": "txtarea", "readonly": "readonly", "rows": "1", "cols": ""}), initial="logs here") Thanks for your help Answer: You need to use AJAX. [This](http://stackoverflow.com/questions/20306981/how- do-i-integrate-ajax-with-django-applications) should give you an idea of how to go about this. AngularJS would also allow you to easily do this, depending on the logic required.
Why is PyCharm unable to find the correct verion of pip to install a Python module? Question: OSX: 10.9.5 PyCharm: 4.5 I am working on project in PyCharm IDE, using the 2.7.3 Python interpreter and need to import the`psycopg2` module. I tried to install the module with PyCharm, but it failed and asked me to do it manually: [Image of error message](http://i.stack.imgur.com/2tLL8.png) So I typed that command in the bash shell, the module installed and now it shows up in the project interpreter 2.7.2 but not in 2.7.3 !!!!! Maybe the `pip` version is too old? I upgraded pip from the bash shell: `pip install --upgrade pip` * python 2.7.2 shows version 7.1.0 * [python 2.7.3](http://i.imgur.com/8gIw9VZ.png) shows version 1.5.6 Answer: You didn't specify what pip version you have. My guess is that the pip version is too old and PyCharm passing some flag which returns deprecation warning which cause it to fail. Try updating pip: `pip install --upgrade pip`
How to retreive values from list: python Question: **Summary:** I have a list list = [ { 'id': '1', 'elements': 'A', 'table': 'maps/partials/a.html', 'chart': 'maps/partials/charts/a.html', }, { 'id': '2', 'elements': 'B', 'table': 'maps/partials/census/b.html', 'chart': 'maps/partials/charts/b.html', }, { 'id': '3', 'elements': ('C','D','E','F'), //i believe it is wrong 'table': 'maps/partials/census/common.html', 'chart': 'maps/partials/charts/common.html', },] some_arr = ['E','2011','English','Total'] I want to compare `elements` with items in `some_arr`. and i am doing this to get list and compare it with some_arr. for data in list: for i in range(len(some_arr)): if data['elements'] == some_arr[i]: print(data['id']) As you can see in `'id':3` section_title has 4 values. How do i compare elements here with some_arr. Answer: If you want to find any matches: lst = [ { 'id': '1', 'elements': 'A', 'table': 'maps/partials/a.html', 'chart': 'maps/partials/charts/a.html', }, { 'id': '2', 'elements': 'B', 'table': 'maps/partials/census/b.html', 'chart': 'maps/partials/charts/b.html', }, { 'id': '3', 'elements': ('C','D','E','F'), 'table': 'maps/partials/census/common.html', 'chart': 'maps/partials/charts/common.html', }] some_arr = ['E','2011','English','Total'] st = set(some_arr) from collections import Iterable for d in lst: val = d["elements"] if isinstance(val, Iterable) and not isinstance(val, str): if any(ele in st for ele in val): print(d["id"]) else: if val in st: print(d["id"]) Making a set of all the elements in `some_arr` will give you `O(1)` lookups, using `isinstance(val, Iterable) and not isinstance(val, str)` will catch any iterable value like a list, tuple etc.. and avoid iterating over a string which could give you false positives as `"F"` is in `"Foo"`. [any](https://docs.python.org/3.4/library/functions.html#any) will _short circuit_ on the first match so if you actually want to print id for every match then use a for loop. Lastly if you are using python2 use `basestring` instead of `str`.
Error reading csv file using rpy2 in python Question: I cannot seem to be able to run the following code and get the error: rpy2.rinterface.RRuntimeError: Error in paste(r.base_dir, r.inp_file, ".csv", sep = "") : object 'r.base_dir' not found I get the same error even if I replace r.base_dir by base_dir. The code is essentially reading in a csv file using rpy2 from rpy2.robjects.packages import importr from rpy2.robjects import r import rpy2.robjects.numpy2ri as rpyn r.base_dir = '/Users/r/Documents/Projects/GLM/Visualize/' r.inp_file = 'Cns' r.out_file = 'Main.png' r.inp_mat = r("read.table(paste(r.base_dir,r.inp_file,'.csv',sep=''), header=T, row.names=1, sep=',')") Answer: The Python symbols are not magically visible in the R namespace. While at it you may consider calling R functions with Python arguments. For example here: from rpy2.robjects.packages import importr from rpy2.robjects import r import rpy2.robjects.numpy2ri as rpyn import os utils = importr('utils') base_dir = '/Users/r/Documents/Projects/GLM/Visualize/' inp_file = 'Cns' out_file = 'Main.png' inp_mat = utils.read_csv(os.path.join(r.base_dir, r.inp_file +'.csv'), header=True, row_names=1, sep=',')
Replace object in json with another json file using python Question: I currently have two json files that I need to combine using python. Essentially I want to replace the choices array in file 1 with the array in file 2 using python. How do I go about doing this? File 1 is: { "choice_list": { "name": "Boston Street Names", "choices":[ {"value": "127906", "label": "DAVIS STREET"}, {"value": "129909", "label": "NORTH QUINCY STREET" }, { "value": "134194", "label": "ADAMS STREET" }] } } File 2 is: [{"value": "134484", "label": "PRISCILLA ALDEN ROAD"}, {"value": "134487", "label": "VAN BUREN DRIVE"}] Answer: Use the native python JSON library: import json json1 = '{\ "choice_list": {\ "name": "Boston Street Names",\ "choices":[ {"value": "127906", "label": "DAVIS STREET"},\ {"value": "129909", "label": "NORTH QUINCY STREET" },\ { "value": "134194", "label": "ADAMS STREET" }]\ } \ }' json2 = '[{"value": "134484", "label": "PRISCILLA ALDEN ROAD"},\ {"value": "134487", "label": "VAN BUREN DRIVE"}]' res = json.loads(json1) res['choice_list']['choices'] = json.loads(json2) print json.dumps(res) Results in: {"choice_list": {"name": "Boston Street Names", "choices": [{"value": "134484","label": "PRISCILLA ALDEN ROAD"}, {"value": "134487", "label": "VAN BUREN DRIVE"}] } } The loads method takes in a JSON string and converts it to a python dictionary object (with all keys as unicode). You can then load the other JSON object, reference to the key you want to replace, and assign it. Then you just convert back to a JSON string.
Is using the args syntax in Python multiprocessing always necessary? Question: I am learning up on methods of multiprocessing in Python and have found myself with a question. Consider the following example: import multiprocessing as mp def worker(n): print('worker %d' % n) return if __name__ == '__main__': jobs = [] for i in range(5): p = mp.Process(target = worker, args = (i,)) jobs.append(p) p.start() This is how the documentation that I am following uses `Process`. Is it necessary to user `args = (i,)`? I have never seen this syntax in Python before and it seems strange. I tested, and this works exactly the same: `p = mp.Process(target = worker(i))` Is there any reason that I should avoid that? Thanks for any help. Answer: Here's a quick way for you to prove that it isn't the same thing. Change your `worker(i)` function to this: import time def worker(n): print('worker %d' % n) time.sleep(1) return When you call this the first way, you'll notice that you still get all 5 prints at the same time right at the beginning. When you do it your second way, you'll see that you get all 5 prints staggered, with a second between each one. Think about what you're trying to set up: 5 independent processes are each being started up at about the same time, each print at about the same time, and then each wait about a second, but the total time elapsed is only a little more than a second. This is what you want to have happen. Here's the key point: `target = worker` sets `target` to be the `worker` function, and `args = (i,)` sets `args` to be a single element tuple containing `i`. On the other hand, `target = worker(i)` calls `worker(i)` and sets `target` to be the value that the function returns, in this case `None`. You're not really using `multiprocessing` at all when you do it the second way. If you have a really time consuming task that you want to split across multiple processes, then you'll see no improvement when it's done the second way. Basically, anytime you have `func(args)`, you're going to be _calling_ the function and getting its return value, whereas when you pass `func` and `args` separately, you allow the `multiprocessing` package to work its magic and make those function calls on independent processes. Setting the target to be `func(args)` will just call the function in the main process, losing you any benefits from multiprocessing in the first place.
How can I load an image using Python Pillow? Question: I load an image this way: from PIL import Image im = Image.open('test.png') gives me the following error: IOError: [Errno 2] No such file or directory: 'test.png' I have saved the image 'test.png' on the desktop. So where should I save the image? Answer: You need to give the directory where the file is located. So if you put in desktop it should go something like this: Image.open('C:\Users\$(your_user_name)\Desktop\test.png') or move the file "test.png" to folder where your script is.
Python analog of mvrnorm's empirical setting when generating a multivariate distribution? Question: So in `R`'s `MASS` package there is a function called `mvrnorm` for generating multivariate distributions. It has an argument called `empirical` which, when set to to TRUE, mu (means) and sigma (covariance matrix) specifiy the emperical, not the population mean and covariance matrix. In short, when you pull out samples the means and variances are very similar to what was prescribed. Is there anything similar in python? I have been unable to find anything like this in numpy, for example. Answer: Solution: import numpy as np import rpy2 import rpy2.robjects as robjects from rpy2.robjects.packages import importr MASS = importr('MASS') # Must use R: install.packages('MASS') r = robjects.r np.matrix(MASS.mvrnorm(n = 10, mu = r.c(0,0), Sigma = r.diag(2), empirical = True)) [This helped.](http://stackoverflow.com/questions/11163472/fitdistr-in-rpy2)
Max Distance between 2 points in a data set and identifying the points Question: I have a matrix consisting of x,y,z coordinates of several points. I would like to find the extremum points i.e. the two points that are farthest apart. I could figure out a way in matlab, but i need it in Python Here is the code in matlab A = randint(500,3,[-5 5]); D=pdist(A); D=squareform(D); [N,I]=max(D(:)); [I_row, I_col] = ind2sub(size(D),I); pdist gives the distance between pairs of points(i,j). squareform gives the matrix output In last two steps I attempt to find the indices of the matrix I_row, I_col.. Points I_row and I_col have the max distance.. Could anybody suggest me an efficient way in python as all my other codes are in Python. Answer: If you have `scipy`, you have exact equivalent for most of matlab core functions : from numpy import random, nanmax, argmax, unravel_index from scipy.spatial.distance import pdist, squareform A = random.randint(-5,5, (500,3)) D = pdist(A) D = squareform(D); N, [I_row, I_col] = nanmax(D), unravel_index( argmax(D), D.shape ) You can also get it in pure python using `itertools` : from itertools import combinations from random import randint A = [[randint(-5,5) for coord in range(3)] for point in range(500)] def square_distance(x,y): return sum([(xi-yi)**2 for xi, yi in zip(x,y)]) max_square_distance = 0 for pair in combinations(A,2): if square_distance(*pair) > max_square_distance: max_square_distance = square_distance(*pair) max_pair = pair
How to speed up web scraping with nested urllib2.urlopen() in Python? Question: I have the following code to gather the number of words there are in each chapter of a book. In a nutshell, it opens the url of each book, then the urls of each chapter associated with the book. import urllib2 from bs4 import BeautifulSoup import re def scrapeBook(bookId): url = 'http://www.qidian.com/BookReader/'+str(bookId)+'.aspx' try: words = [] html = urllib2.urlopen(url,'html').read() soup = BeautifulSoup(html) try: chapters = soup.find_all('a', rel='nofollow') # find all relevant chapters for chapter in chapters: # loop through chapters if 'title' in chapter.attrs: link = chapter['href'] # go to chapter to find words htmlTemp = urllib2.urlopen(link,'html').read() soupTemp = BeautifulSoup(htmlTemp) # find out how many words there are in each chapter spans = soupTemp.find_all('span') for span in spans: content = span.string if not content == None: if u'\u5b57\u6570' in content: word = re.sub("[^0-9]", "", content) words.append(word) except: pass return words except: print 'Book'+ str(bookId) + 'does not exist' Below is a sample run words = scrapeBook(3501537) print words >> [u'2532', u'2486', u'2510', u'2223', u'2349', u'2169', u'2259', u'2194', u'2151', u'2422', u'2159', u'2217', u'2158', u'2134', u'2098', u'2139', u'2216', u'2282', u'2298', u'2124', u'2242', u'2224', u'178', u'2168', u'2334', u'2132', u'2176', u'2271', u'2237'] Without doubt the code is very slow. One major reason is that I need to open the url for each book, and for each book I need to open the url of each chapter. Is there a way to make the process faster? Here is another bookId without empty return 3052409. It has hundreds of chapters, and the code runs forever. Answer: The fact that you need to open each book and each chapter is dictated by the views exposed on the server. What you could do, it to implement parallel clients. Create a thread pool where you offload HTTP requests as jobs to the workers, or do something similar with coroutines. Then there's the choice of the HTTP client library. I found `libcurl` and `geventhttpclient` more CPU efficient than `urllib` or any other of the python standard libs.
appending a class to list results in appending str error python Question: So I my program has a class with a persons name. I am trying to have the program read it off from a input file and then read it and arrange it into classes. While I am trying to appened the class to a list. It gives me this error: AttributeError: 'str' object has no attribute 'append' I have used this code before to do the same similar thing, but without reading from a file. I was wondering what was happening to cause this error. Here is my code: class person: def __init__(self, FName, FLast,age ): self.FName=FName self.FLast=FLast self.age=age from sys import argv script = argv filename = raw_input('enter filename: ') txt = open(filename, 'r+') count = 0 i = 2 lines = txt.readlines() z=lines[0] a=lines[1] r=lines[2] hi=person(z,a,r) a=[hi] while i != -1: try: z=lines[i] a=lines[i+1] r=lines[i+2] i = i + 3 hi=person(z,a,r) a.append[hi] except IndexError: i = -1 Answer: Few issues in your code - 1. `a.append[hi]` \- This is not how you append, append is a function, you have to call it passing it the value to append as parameter. 2. You are defining `a` as a string in the line - `a=lines[i+1]` \- Then you are trying to append to it. You may want to create a new list outside the `while` , and then keep appending to it. Example - classlist = [] while i != -1: try: z=lines[i] a=lines[i+1] r=lines[i+2] i = i + 3 hi=person(z,a,r) classlist.append(hi) except IndexError: i = -1
Permission Denied when load Firefox Extension in WebDriver Question: I'm creating a python script with selenium webdriver. I need to use an extension in firefox, but when I test with a little script, the script produces an error like this: Traceback (most recent call last): File "C:\Users\User\Desktop\Bot\Mania.py", line 8, in <module> firefoxProfile.add_extension(elem) File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\firefox_profile.py", line 93, in add_extension self._install_extension(extension) File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\firefox_profile.py", line 264, in _install_extension with open(os.path.join(tmpdir, name), 'wb') as f: PermissionError: [Errno 13] Permission denied: 'C:\\Users\\User\\AppData\\Local\\Temp\\tmpzq3rmztk.firebug-2.0.11-fx.xpi\\content/firebug/' [Finished in 0.4s with exit code 1] The sample code is it: from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import FirefoxProfile import os firefoxProfile = FirefoxProfile() elem = "quickjava-2.0.6-fx.xpi" firefoxProfile.add_extension(elem) firefoxProfile.set_preference("thatoneguydotnet.QuickJava.startupStatus.CSS", 2) driver = webdriver.Firefox(firefoxProfile) driver.get('http://www.google.cl') PS: The add-on is in the same folder that the script. I tested with full path but it doesn't work too. Answer: You need to provide an absolute path to the extension: firefoxProfile.add_extension("/absolute/path/to/the/extension")
Softmax choice probabilities with Categorical in PyMC3 Question: I am trying to perform a parameter estimation for a single parameter of a softmax choice function in the following scenario: In each trial, three option values are given (e.g., [1,2,3]), and a subject makes a choice between the options (0, 1 or 2). The softmax function transforms option values into choice probabilities (vector of 3 probabilities, summing to 1), depending on a temperature parameter (here bound between 0 and 10). The choice in each trial is supposed to be modelled as a Categorical distribution with trial choice probabilities calculated from the softmax. Note that the choice probabilities of the Categorical depend on the option values and are therefore different in each trial. Here's what I came up with: # Generate data nTrials = 60 # number of trials (value triplets and choices) np.random.seed(42) # generate nTrials triplets of values values = np.random.choice([1,2,3,4,5], size=(nTrials, 3)) choices = values.argmax(axis=1) # choose highest value option # add some random variation, so that *not* always the highest value option is chosen errors = np.random.rand(nTrials)>0.8 # determine trials with non-optimal choice # randomly determine new choices for these trials choices[errors] = np.random.choice([0,1,2], size=sum(errors==True)) # Model specification & estimation import pymc3 as pm from theano import tensor as t with pm.Model(): # prior over theta theta = pm.Uniform('theta', lower=0, upper=10) # softmax implementation enumerator = pm.exp(theta*values) denominator = t.reshape(pm.sum(pm.exp(theta*values), axis=1), (nTrials, 1)) ps = enumerator/denominator # Likelihood (sampling model for the data) for trial in range(nTrials): yobs = pm.Categorical('yobs{}'.format(trial), p=ps[trial], observed=choices[trial]) # draw 500 samples from posterior trace = pm.sample(500, pm.Metropolis()) This code fails for nTrials bigger than something like 50 with an extremely long warning / error message: Warning: INFO (theano.gof.compilelock): Refreshing lock /Users/felixmolter/.theano/compiledir_Darwin-14.4.0-x86_64-i386-64bit-i386-2.7.8-64/lock_dir/lock INFO:theano.gof.compilelock:Refreshing lock /Users/felixmolter/.theano/compiledir_Darwin-14.4.0-x86_64-i386-64bit-i386-2.7.8-64/lock_dir/lock 00001 #include <Python.h> 00002 #include <iostream> 00003 #include <math.h> 00004 #include <numpy/arrayobject.h> 00005 #include <numpy/arrayscalars.h> 00006 #include <vector> 00007 #include <algorithm> 00008 ////////////////////// 00009 //// Support Code 00010 ////////////////////// 00011 00012 00013 namespace { 00014 struct __struct_compiled_op_65734e56ae54d89bdcf84e36893358e6 { 00015 PyObject* __ERROR; 00016 00017 PyObject* storage_V3; 00018 PyObject* storage_V5; 00019 PyObject* storage_V7; 00020 PyObject* storage_V9; 00021 PyObject* storage_V11; 00022 PyObject* storage_V13; [...] Error: Exception: ('The following error happened while compiling the node', Elemwise{Composite{((Switch(LE(Abs((i0 + i1)), i2), log(i3), i4) + Switch(LE(Abs((i0 + i5)), i2), log(i6), i4) + Switch(LE(Abs((i0 + i7)), i2), log(i8), i4) + Switch(LE(Abs((i0 + i9)), i2), log(i10), i4) + Switch(LE(Abs((i0 + i11)), [...] I am rather new to PyMC (and Theano) and I feel my implementation is really clunky and suboptimal. Any help and advice is strongly appreciated! Felix Edit: I've uploaded the code as a notebook, showing the warnings and error messages in full: <http://nbviewer.ipython.org/github/moltaire/softmaxPyMC/blob/master/softmax_stackoverflow.ipynb> Answer: I found again this case. Just as a follow up, now not able able to reproduce it now. So I think it got fixed. We fixed related problem that could hve caused in some case this error. It work with g++ 4.5.1. If you have this problem update Theano to the development version. If that don't fix it, try to use a g++ more recent, this could be related to older g++ version.
Python: Iterative subdirectory line count Question: I'm attempting to count the number of lines in two separate directories that are formatted differently and compare the results. The text files needed are all within a single directory in the the first dir, but the second one has subdirectories that I need to iterate through, save the name of, and then pull and count all txt files that begin with the name. At the moment, I'm having trouble comparing the subdirectory name with the txt files that begin with it. My traceback is as follows: be29X1(149)% ./SeriesCount.py Traceback (most recent call last): File "./SeriesCount.py", line 23, in <module> for fn in files('subdir_name*.txt'): TypeError: 'list' object is not callable I don't need to permanently save the subdirectory name, since all I care about is storing the txt file names and their counts to a dict. For example, if the directory name is "regprices", I want to pull out the line counts for all text files within the directory that begin with "regprices". Code is below: #!/usr/bin/env python import csv import copy import os import sys import glob import dircmp #set dicts dict1 = {} dict2 = {} final_dict = {} #parses through directory 1, counts lines, saves to a dict for fn in glob.glob('/data/*.txt'): with open(fn) as f: dict1[fn] = [1 for line in f if line.strip() and not line.startswith('#')] #parses through subdirectories in directory 2, counts lines, saves to a dict for subdir, dirs, files in os.walk('/docs/prod/count/'): subdir_name = os.getcwd() for fn in files('subdir_name*.txt'): dict2[fn] = [1 for line in f if line.strip() and not line.startswith('#')] #compare dicts, overwrite counts from dict1 with dict2, save to final dict save final dictionary with key/val pairs to a csv with open('seriescount.csv', 'w') as f: w = csv.DictWriter(f, final_dict) w.writeheader() w.writerow({k:sum(v) for k, v in final_dict.items()}) Bonus points if you can help with syntax comparing the two dictionaries, overwriting the counts from dir2 to dir1, and saving them to final_dict Answer: Example is all over the place with differently named variables. Definitely not a working example. It's hard to work out what you're trying to achieve. Not sure how you're trying to compare the dictionary keys based on filename. Here's an attempt at guessing what you're trying to achieve. import glob import os def count_lines(filename): with open(filename,'r') as f: count = sum(1 for line in f if line.strip() and line[0] != '#') return count def directory1_count(path='/data/*.txt'): counts = {} for filepath in glob.glob(path): directory, filename = os.path.split(filepath) name, extension = os.path.splitext(filename) counts[name] = count_lines(filepath) return counts def directory2_count(path='/docs/prod/count/'): counts = {} for directory, dirs, files in os.walk(path): _, subdir = os.path.split(directory) for filename in [x for x in files if x.startswith(subdir) and x.endswith('.txt')]: name, extension = os.path.splitext(filename) filepath = os.path.join(directory,filename) counts[name] = count_lines(filepath) return counts counts = directory1_count() counts.update(directory2_count())
sphinx back up one directory Question: I have followed this [guide](http://www.marinamele.com/2014/03/document-your- django-projects.html) to set up Sphinx. My directories are as follows: /cms-service /documentation /modules models.rst The guide tells to place the path to the python files in `models.rst`. What should this path be? Clearly `.. automodule:: cms-service.apps.models` isn't working, I keep getting two errors when I run `make html`. **I think I need to go up one directory but I don't know how to do this.** The errors: > cms-service/documentation/modules/models.rst:3: WARNING: invalid signature > for automodule (u'cms-service.apps.models') > > cms-service/documentation/modules/models.rst:3: WARNING: don't know which > module to import for autodocumenting u'cms-service.apps.models' (try placing > a "module" or "currentmodule" directive in the document, or giving an > explicit module name) Any other guides on how to setup Sphinx are welcome too. I've been trying for days... Answer: Cyber, I have searched the same blog to carry on the autodoc process with Sphinx and Django. I think there is an error in the tutorial. In the module/models.rst file, in the tutorial it uses **project.app.models** , in this way Sphinx cannot find the module to process on. However, if you change it to **app.models** it can find your module. I don't think we need to add project name because it is already specified in the **conf.py**.
matplotlib: generate a new graph in a new window for subsequent program runs Question: I have a Python program that generates graphs using matplotlib. I am trying to get the program to generate a bunch of plots in one program run (the user is asked if they want to generate another graph) all in separate windows. Any way I can do this? Answer: To generate a new figure, you can add plt.figure() before any plotting that your program does. import matplotlib.pyplot as plt import numpy as np def make_plot(slope): x = np.arange(1,10) y = slope*x+3 plt.figure() plt.plot(x,y) make_plot(2) make_plot(3)
Convert datetime.datetime object to days since epoch in Python Question: I've got a `pandas.Series` object that might look like this: import pandas as pd myVar = pd.Series(["VLADIVOSTOK 690090", "MAHE", NaN, NaN, "VLADIVOSTOK 690090", "2000-07-01 00:00:00"]) `myVar[5]` is parsed as a `datetime.datetime` object when the data is read into Python via `pandas`. I'm assuming that converting this value to the number of days since epoch (36708) isn't difficult at all. I'm just new to Python and don't know how to do it. Thanks in advance! Answer: I'm not sure where you're getting 36,708 days since the epoch (it's only been 16,644 days since January 1, 1970), but `datetime.timedelta` objects (used in date arithmetic) have a `days` attribute: >>> import datetime >>> (datetime.datetime.utcnow() - datetime.datetime(1970,1,1)).days 16644
python decorator function with arguments Question: I've read and understood this article about function decorators: <https://www.artima.com/weblogs/viewpost.jsp?thread=240845> Specifically I'm talking about the section "Decorator Functions with Decorator Arguments" I'm running into a problem, though. I'm trying to write a decorator function with arguments to modify arguments into a class constructor. I have two ways to write this. First some imports: import scipy.stats as stats import numpy as np Way 1 (similar to the aforementioned article's example): def arg_checker1(these_first_args): def check_args(func): def wrapped(*args): for arg in args[:these_first_args]: assert isinstance(arg, np.ndarray) and arg.ndim == 2 return func(*args) return wrapped return check_args or way 2: def arg_checker2(these_first_args, func): def wrapped(*args): for arg in args[:these_first_args]: assert isinstance(arg, np.ndarray) and arg.ndim == 2 return func(*args) return wrapped I just want an error to be thrown when the first 'these_first_args' to the function aren't 2-d np arrays. But take a look what happens when I try to use it (not with a @ but using it directly as a function) class PropDens1: def __init__(self, samp_fun): self.samp = arg_checker1(samp_fun, 2) #right here class PropDens2: def __init__(self, samp_fun): self.samp = arg_checker2(2, samp_fun) #right here q_samp = lambda xnm1, yn, prts : stats.norm.rvs(.9*xnm1,1.,prts) q1 = PropDens1(q_samp) #TypeError: arg_checker1() takes exactly 1 argument (2 given) q2 = PropDens2(q_samp) #no error The second one seems to work with a few examples. Is there a better way to do this, though? If not, why does this work? I think this is why I don't get it. Here's the example in that linked paper: def decoratorFunctionWithArguments(arg1, arg2, arg3): def wrap(f): print "Inside wrap()" def wrapped_f(*args): print "Inside wrapped_f()" print "Decorator arguments:", arg1, arg2, arg3 f(*args) print "After f(*args)" return wrapped_f return wrap Why doesn't he actually have to pass the function-to-be-wrapped (f in this case) as an argument into the decoratorFunctionWithArguments()? Answer: The exception is telling you exactly what is wrong. You call `arg_checker1` with 2 args but you defined it with only one. You should write: self.samp = arg_checker1(2)(samp_fun) Which is somewhat equivalent to: @arg_checker1(2) def q_samp(...): ... Anyway, you way 1 is the way to go, since it will work fine with the `@` syntax.
Prevent cherrypy from logging access Question: I'm trying to set up a logger to only catch my ERROR level messages, but my logger always seems to write `INFO:cherrypy.access` messages to my log file, which I dont want. I tried setting the `log.error_file` global, and using the standard python logging module `logging.basicConfig(filename='error.log', filemode='w', level=logging.ERROR)`, but even though I specify the threshold to be ERROR level messages, I still get those INFO level messages written to my log file. Is there any way to prevent this? Answer: Seems like the `INFO` level logs are coming for `cherrypy.access` . According to [documentation](https://cherrypy.readthedocs.org/en/3.3.0/refman/_cplogging.html) - > You should set these at either the global level or per application (see > next), but generally not both. > > **log.screen** : Set this to True to have both “error” and “access” messages > printed to stdout. **log.access_file** : Set this to an absolute filename > where you want “access” messages written. **log.error_file** : Set this to > an absolute filename where you want “error” messages written. You should also try setting the `log.access_file` (similar to `log.error_file`) . Or you can add an handler for that, example - from logging import handlers fname = getattr(log, "rot_access_file", "access.log") #The log for access messsages. h = handlers.TimedRotatingFileHandler(fname, when='midnight') h.setLevel(logging.DEBUG) h.setFormatter(_cplogging.logfmt) log.access_file = "" log.access_log.addHandler(h)
Wlst how to assign output of listAppStripes() to grantAppRole() Question: I'm new to Python and WLST. I'm trying to write a Python script that retrieves the the Application Stripes for a deployed application and assigned it to appStripes values in the grantAppRole. For example: 1. Connect to Admin Server 2. Deploy the new application 3. Determine the new application stripes for the deployed application listAppStripes() Example: wls:/myapp_domain/serverRuntime> listAppStripes() MyApp#V14.1.0.0.17-b585_APP_75.111.73 wls:/myapp_domain/serverRuntime> 4. GrantAppRole permission. I need to be able to pass the Application Stripe output from Step #3 to this next command: grantAppRole(appStripe="MyApp#V14.1.0.0.17-b585_APP_75.111.73",appRoleName="ROLE_USER",principalClass="weblogic.security.principal.WLSGroupImpl",principalName="LDAP_ROLE_PROD",forceValidate="false") Any feedback will be greatly appreciated! Answer: Try storing the value in a variable and then using that variable in the `grantAppRole()` function call - app_stripes = listAppStripes() I think this might be returning an array , so try using `app_stripes[0]` , to get the first element. You can test it out, what is the exact value returned and use that accordingly. grantAppRole(appStripe=app_stripes[0],appRoleName="ROLE_USER",principalClass="weblogic.security.principal.WLSGroupImpl",principalName="LDAP_ROLE_PROD",forceValidate="false") * * * Seems like `listAppStripes()` is just printing the values and not returning the value. You can do one thing, which is to redirect the `stdout` to a string buffer just before running the`listAppStripes()` , and then correctly redirect it back. and then get your value from the string buffer. Example - from cStringIO import StringIO import sys oldstdout = sys.stdout sys.stdout = mystdout = StringIO() listAppStripes() sys.stdout = oldstdout app_stripes=mystdout.getvalue() app_stripes = app_stripes.replace('wls:/myapp_domain/domainRuntime> ','').strip().split() After this, `app_stripes` would be a list of all the stripes , and you can use the method given in the start to call `grantAppRole()` .
Executing ansible playbook AttributeError: 'str' object has no attribute 'set_playbook_basedir' Question: **Hello,** **_I have a two part question._** **First Part:** I'm trying to execute a playbook from a python script that downloads a playbook and executes it. I know the playbook works because i've tested it. However, when i try to execute the playbook with python code I get a _no attribute error 'set_playbook_basedir'_ not quite sure where this is coming from. Here is the full error output. [ec2-user@ip-172-30-199-190 scripts]$ sudo python /var/lib/cloud/instance/scripts/part-001 /usr/lib64/python2.7/dist-packages/Crypto/Util/number.py:57: PowmInsecureWarning: Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability. _warn("Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.", PowmInsecureWarning) /bin/bash: line 0: export: `=': not a valid identifier /bin/bash: line 0: export: `3': not a valid identifier ~/vision_provis/storm.yml Traceback (most recent call last): File "/var/lib/cloud/instance/scripts/part-001", line 71, in <module> fatal: destination path 'vision_provis' already exists and is not an empty directory. check=True) File "/usr/local/lib/python2.7/site-packages/ansible/playbook/__init__.py", line 169, in __init__ self.inventory.set_playbook_basedir(self.basedir) AttributeError: 'str' object has no attribute 'set_playbook_basedir' #!/usr/bin/python import ansible.runner from ansible.playbook import PlayBook from ansible import inventory from ansible import callbacks import json import subprocess import os from ansible import utils import time def shell_command_execute(cmd): try: subprocess.Popen(['/bin/bash', '-c', cmd]) except: print 'There seems to be an error' repo = "https://github.com/zukeru/vision_provis.git" playbook = "storm.yml" echo_bash_profile = "export CLOUD_ENVIRONMENT=integration|export CLOUD_MONITOR_BUCKET=0|export CLOUD_APP=ES-test-storm-deploy-DEV--_yV_cyE-|export CLOUD_STACK=infra|export CLOUD_CLUSTER=0|export CLOUD_AUTO_SCALE_GROUP=0|export CLOUD_LAUNCH_CONFIG=0|export EC2_REGION=us-west-2|export CLOUD_DEV_PHASE=0|export CLOUD_REVISION=0|export CLOUD_DOMAIN=0|export SG_GROUP=ES-test-storm-deploy-DEV--qtv6a_Uj" for commands in echo_bash_profile.split('|'): command_to_send = 'echo "' + commands + '" >> /home/ec2-user/.bash_profile' shell_command_execute(commands) shell_command_execute(command_to_send) var_user_data = "export SHARDS = 3" for commands in var_user_data.split('|'): echo_bash_profile_passed = 'echo "' + commands + '" >> /home/ec2-user/.bash_profile' shell_command_execute(commands) shell_command_execute(echo_bash_profile_passed) command_remove = 'rm -rf /home/ec2-user/'+repo shell_command_execute(command_remove) command = 'cd /home/ec2-user/; git clone ' + repo shell_command_execute(command) folder = repo.split('/')[4].replace('.git','') full_path = '/home/ec2-user/' + folder + '/' + playbook time.sleep(6) # setting callbacks stats = callbacks.AggregateStats() playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) print full_path # creating the playbook instance to run, based on "test.yml" file pb = PlayBook(playbook = full_path, stats = stats, callbacks = playbook_cb, runner_callbacks = runner_cb, inventory = "localhost", check=True) # running the playbook pr = pb.run() # print the summary of results for each host #print json.dumps(pr, sort_keys=True, indent=4, separators=(',', ': ')) **_The Second Problem is:_** This script is actually being passed as base64 encoded aws user-data and its executing but it doesn't seem to recognize that it is python. Here is the cloud-init-output.log Complete! Cloud-init v. 0.7.6 running 'modules:final' at Wed, 29 Jul 2015 00:17:16 +0000. Up 103.79 seconds. /var/lib/cloud/instance/scripts/part-001: line 3: import: command not found /var/lib/cloud/instance/scripts/part-001: line 4: import: command not found /var/lib/cloud/instance/scripts/part-001: line 5: import: command not found /var/lib/cloud/instance/scripts/part-001: line 6: import: command not found /var/lib/cloud/instance/scripts/part-001: line 7: import: command not found /var/lib/cloud/instance/scripts/part-001: line 8: import: command not found /var/lib/cloud/instance/scripts/part-001: line 10: syntax error near unexpected token `(' /var/lib/cloud/instance/scripts/part-001: line 10: `def shell_command_execute(cmd):' Jul 29 00:17:16 cloud-init[1958]: util.py[WARNING]: Failed running /var/lib/cloud/instance/scripts/part-001 [2] Jul 29 00:17:16 cloud-init[1958]: cc_scripts_user.py[WARNING]: Failed to run module scripts-user (scripts in /var/lib/cloud/instance/scripts) Jul 29 00:17:16 cloud-init[1958]: util.py[WARNING]: Running module scripts-user (<module 'cloudinit.config.cc_scripts_user' from '/usr/lib/python2.7/dist-packages/cloudinit/config/cc_scripts_user.pyc'>) failed Jul 29 00:17:16 cloud-init[1958]: templater.py[WARNING]: Cheetah not available as the default renderer for unknown template, reverting to the basic renderer. Cloud-init v. 0.7.6 finished at Wed, 29 Jul 2015 00:17:16 +0000. Datasource DataSourceEc2. Up 103.97 seconds Answer: I can't reproduce your issues, but my best guess is that: 1) You need to initialize your playbook with an Inventory object instead of a string: from ansible.inventory import Inventory pb = PlayBook(playbook = full_path, stats = stats, callbacks = playbook_cb, runner_callbacks = runner_cb, inventory = Inventory(["localhost"]), check=True) 2) Your python script needs to be prefixed with an indication to bash that it should be executed by python. Just put the following [shebang](https://en.wikipedia.org/wiki/Shebang_%28Unix%29) at the top of your python script: #! /usr/bin/env python Alternatively, you may run your script with: python /var/lib/cloud/instance/scripts/part-001 instead of just: /var/lib/cloud/instance/scripts/part-001
Using user defined variables/functions in eval [Python 3.4.2]? Question: I have a calculator (python 3.4.2) that can do normal operations using eval. def calculator(user_input): if any(c not in config.valid_cal_chars for c in user_input): print("- Invalid Equation | Bad characters") return elif not any(c in user_input for c in "0123456789"): print("- Invalid Equation | No numbers found") return sys.stdout.write("calculating " + "-".join(gfx.load_sequence)) time.sleep(0.1) print (" | 100%") try: current_ans = eval(user_input) except (SyntaxError, ZeroDivisionError, NameError, TypeError, ValueError): print ("- Invalid Equation | Error") return config.ans = current_ans print (current_ans) Here is the config.py that config.ans, config.valid_cal_char is refering to: ans = ("0.0") valid_cal_chars = ("0123456789-+/*ansqrt() \n") And if you are wondering what the user_choice variable is referring to, it is referring to a input function that I have before this function. That part works, so no need to worry there. However, I am wondering if it is possible to do something like this: input equation here: 4*4 #this would be saved as the user_input variable > 16 #the output of the equation input equation here: sqrt(ans) #this would use the previous answer saved in config.ans (ans) and the sqrt() to find the square root of the previous printed value, so: > 4 So typing ans would result in: input equation here: 1+1 > 2 input equation here: ans > 2 And using sqrt() would result in: input equation here: 2+2 > 4 input equation here: sqrt(4) > 2 So if you still don't get it, sqrt() find the square root of the value inputted. ans uses the previous returned value. So combining the two "sqrt(ans)" would give the square root of the previous returned value. With the back ground info out of the way, what I want to do is to allow a user to use these when calculating. While the "eval" may not work, I am happy to use "exec" too (knowing the dangers). However, here is a multitool.py (the main file) that imports the this file (functions.py) to use all the functions that I have in there, including this one. import os, sys, glob, math, random, login, gfx, config, functions, time path = "******" #creates path to folder (can be changed by commenting this line out and creating new one) dirs = os.listdir( path ) #not used currently functions.load_sequence_complete() functions.username_login() time.sleep(0.05) functions.password_login() print ("\n[credentials have been verified! proceeding to main program " + "-".join(gfx.load_sequence) + "]\n") time.sleep(0.1) program = True while (program == True): user_choice = functions.choice_selecter() functions.validate_choice(user_choice) If there are any other info that you need, please put that in the comments or answers below so I can edit this to help you help me :) Answer: You can do it in the first method , you can define `ans` as a global in the start of the function, and then the result of `eval(user_input)` , and use `ans` instead of `current_ans` everywhere. How your function would look like , assuming everything works - def calculator(user_input): global ans if any(c not in config.valid_cal_chars for c in user_input): print("- Invalid Equation | Bad characters") return sys.stdout.write("calculating " + "-".join(gfx.load_sequence)) time.sleep(0.1) print (" | 100%") try: ans = eval(user_input, {'ans':ans,'sqrt':sqrt},{}) except (SyntaxError, ZeroDivisionError, NameError, TypeError, ValueError): print ("- Invalid Equation | Error") return config.ans = ans print (ans) Please note I got rid of the `elif` part in the function, as otherwise, it would not let an input like - `ans` \- go through - you may rethink how to rewrite that. Example/Demo - >>> def calculator(user_input): ... global ans ... if any(c not in "0123456789-+/*ansqrt() \n" for c in user_input): ... print("- Invalid Equation | Bad characters") ... return ... time.sleep(0.1) ... print (" | 100%") ... try: ... ans = eval(user_input, {'ans':ans,'sqrt':sqrt},{}) ... except (SyntaxError, ZeroDivisionError, NameError, TypeError, ValueError): ... print ("- Invalid Equation | Error") ... return ... print (ans) ... >>> >>> calculator('1+2') | 100% 3 >>> calculator('ans') | 100% 3 >>> from math import sqrt >>> calculator('sqrt(ans)') | 100% 1.7320508075688772 * * * Though you can also use [`eval`](https://docs.python.org/2/library/functions.html#eval) as - ans = eval(user_input, {'ans':ans,'sqrt':sqrt},{}) This would restrict eval to only take `ans` and `sqrt` as that names. But still you should reconsider using `eval()` , as even after restricting the globals and locals in it, users can still cause harm. Why? [Check here.](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html)
Global Variables with threading in python Question: By threading a process as in this code: import threading import time def loop(): global bbcount bbcount = 0 while True: bbcount += 1 print "This is a Loop" time.sleep(1) if __name__ == '__main__': t = threading.Thread(target=loop) t.start() while True: user_input = raw_input("Please enter a value:") print "User input: " + user_input print "Current count: " + str(bbcount) t.join() Do I run the risk of bbcount being corrupted by trying to print a partially updated/incremented memory space while being incremented the loop? I thought about this after reading: Since all threads of a process share the same global variables, a problem arises with synchronization of access to global variables. For example, let's assume you have a global variable X and two threads A and B. Let's say threads A and B will merely increment the value of X. When thread A begins execution, it copies the value of X into the registers and increments it. Before it gets a chance to write the value back to memory, this thread is suspended. The next thread starts, reads the same value of X that the first thread read, increments it and writes it back to memory. Then, the first thread finishes execution and writes its value from the register back to memory. After these two threads finish, the value of X is incremented by 1 instead of 2 as you would expect. from: <http://www.linuxjournal.com/article/3138> Answer: Because of GIL, this program would run expectedly. More about GIL: <https://en.wikipedia.org/wiki/Global_Interpreter_Lock> So the global variables will be thread-safe editing in a short time.
choosing random directories in PC using Python Question: I'm using python 3.x and I don't know how to make my script randomly choose directories in the same PC to copy files. I want it to copy the files in the random directories. What should I do to make it happen? from sys import argv import os import random script=argv name=str(script[0]) count = 0 i = 10 while (count < i) : os.system('start omnomnom.txt') count+=1 os.mkdir('tembilaland') os.system(r"copy omnomnom.txt tembilaland") os.system(r"copy acme.py tembilaland") Answer: I don't know what you are doing that for... honestly :^) Well, if you don't have a pre-determined list of target directories, you could use [`os.walk`](https://docs.python.org/2/library/os.html#os.walk) then [`random.choice`](https://docs.python.org/2/library/random.html#random.choice) to pick one. Like: # all subdirectories in the user's home directories = [row[0] for row in os.walk(os.path.expanduser('~/subdir'))] # or if you want to limit to an arbitrary number directories = [] for i, row in enumerate(os.walk(os.path.expanduser('~'))): if i > 100: break directories+= [row[0]] print random.choice(directories)
How to use sign-in quota (plus.login scope) for Google Plus Question: I wrote a scraper to get some of the users' public contents. This scraper fetches the comments, plusoners, resharers, and the user's post. The free quota is 10,000 requests/day if you use API key: service = apiclient.discovery.build(service_name, service_version, developerKey=api_key) I'd like to use Sign-in quota to fetch plusoners and resharers (people.list API call). But I couldn't use oauth for this purpose. That is, I don't have any users. I'd like to use the scope (<https://www.googleapis.com/auth/plus.login>) for fetching plusoners and resharers. In Java, I think the procedure is this: <https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.Builder>. How can I do it for Python? Answer: There is really lots of documents how to authenticate it with Oauth2.0 but there isn't so much information about how a server side script can authenticate itself without any human presence. I think I found the most convenient way of doing it with JWT. from apiclient.discovery import build from httplib2 import Http from oauth2client.client import SignedJwtAssertionCredentials private_key = open("MyProject.p12").read() client_email = 'EMAIL' http_auth = credentials.authorize(Http()) credentials = SignedJwtAssertionCredentials(client_email, private_key, 'https://www.googleapis.com/auth/plus.login') service.people().list(userId='me', collection='connected').execute() _Note for people who are not careful like me_ : Moreover, this authentication method doesn't useful for me because it's for people().list API calls. However, I'd like to use people().listByActivity.
Optimize Python Script to parse xml Question: I'm parsing the US Patent XML files (downloaded from [Google patent dumps](https://www.google.com/googlebooks/uspto-patents-redbook.html)) using Python and Beautifulsoup; parsed data is exported to MYSQL database. Each year's data contains close to 200-300K patents - which means parsing 200-300K xml files. The server on which I'm running the python script is pretty powerful - 16 cores, 160 gigs of RAM, etc. but still it is taking close to 3 days to parse one year's worth of data. [![enter image description here](http://i.stack.imgur.com/Rve8M.png)](http://i.stack.imgur.com/Rve8M.png) [![enter image description here](http://i.stack.imgur.com/dEmQB.png)](http://i.stack.imgur.com/dEmQB.png) I've been learning and using python since 2 years - so I can get stuff done but do not know how to get it done in the most efficient manner. I'm reading on it. How can I optimize the below script to make it efficient? Any guidance would be greatly appreciated. Below is the code: from bs4 import BeautifulSoup import pandas as pd from pandas.core.frame import DataFrame import MySQLdb as db import os cnxn = db.connect('xx.xx.xx.xx','xxxxx','xxxxx','xxxx',charset='utf8',use_unicode=True) def separated_xml(infile): file = open(infile, "r") buffer = [file.readline()] for line in file: if line.startswith("<?xml "): yield "".join(buffer) buffer = [] buffer.append(line) yield "".join(buffer) file.close() def get_data(soup): df = pd.DataFrame(columns = ['doc_id','patcit_num','patcit_document_id_country', 'patcit_document_id_doc_number','patcit_document_id_kind','patcit_document_id_name','patcit_document_id_date','category']) if soup.findAll('us-citation'): cit = soup.findAll('us-citation') else: cit = soup.findAll('citation') doc_id = soup.findAll('publication-reference')[0].find('doc-number').text for x in cit: try: patcit_num = x.find('patcit')['num'] except: patcit_num = None try: patcit_document_id_country = x.find('country').text except: patcit_document_id_country = None try: patcit_document_id_doc_number = x.find('doc-number').text except: patcit_document_id_doc_number = None try: patcit_document_id_kind = x.find('kind').text except: patcit_document_id_kind = None try: patcit_document_id_name = x.find('name').text except: patcit_document_id_name = None try: patcit_document_id_date = x.find('date').text except: patcit_document_id_date = None try: category = x.find('category').text except: category = None print doc_id val = {'doc_id':doc_id,'patcit_num':patcit_num, 'patcit_document_id_country':patcit_document_id_country,'patcit_document_id_doc_number':patcit_document_id_doc_number, 'patcit_document_id_kind':patcit_document_id_kind,'patcit_document_id_name':patcit_document_id_name,'patcit_document_id_date':patcit_document_id_date,'category':category} df = df.append(val, ignore_index=True) df.to_sql(name = 'table_name', con = cnxn, flavor='mysql', if_exists='append') print '1 doc exported' i=0 l = os.listdir('/path/') for item in l: f = '/path/'+item print 'Currently parsing - ',item for xml_string in separated_xml(f): soup = BeautifulSoup(xml_string,'xml') if soup.find('us-patent-grant'): print item, i, xml_string[177:204] get_data(soup) else: print item, i, xml_string[177:204],'***********************************soup not found********************************************' i+=1 print 'DONE!!!' Answer: Here is a [tutorial on multi- threading](http://www.tutorialspoint.com/python/python_multithreading.htm), because currently that code will run on 1 thread, 1 core. Remove all try/except statements and handle the code properly. Exceptions are expensive. Run a [profiler](http://docs.python.org/2/library/profile.html) to find the chokepoints, and multi-thread those or find a way to do them less times.
Decoding Hex char string in python Question: I'm trying to interface a software with python via a TCP connection. The software is AGWPE (in fact, it's soundmodem, but they share the same API). When I ask the software for "normal" packets, everything fine, but when I ask for "raw" packets, the hex bytes the tcp connection gives me won't decode as nothing at all. Not ASCII, not unicode, not latin-1. This is the API of AGWPE already to the packet I'm having trouble with: <http://uz7.ho.ua/includes/agwpeapi.htm#_Toc500723814> This is my code: import socket #import aprslib raw=1 TCP_IP = '127.0.0.1' TCP_PORT = 8000 BUFFER_SIZE = 1024 MESSAGE = '000000006D00000000000000000000000000000000000000000000000000000000000000' message2 = '000000006B00000000000000000000000000000000000000000000000000000000000000' MESSAGE = bytearray.fromhex(MESSAGE) message2 = bytearray.fromhex(message2) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) s.send(MESSAGE) if raw: s.send(message2) data = s.recv(BUFFER_SIZE) dataf=data.decode("ascii", 'ignore') #not putting the second argument raises an exception #aprs=aprslib.parse(dataf) print(dataf) s.close() And this is my result: (I would paste it but seems that notepad and the browser don't like some characters) Raw on: <http://i.gyazo.com/2e6eecf99c6e79c7cdbcf868a734694b.png> I would be expecting something like on the example: ....K...LU7DID..8.LU7DID-4..B...,.E....n......n...i8...[LU7DID@LU7DID-4] B,C,D,E,X,I,M,?,N,P,U,J,R: .. with the char 0x00 instead of . of course. At least something readable. Thanks a lot for your time. Answer: I assume you're using python 3. Try something like: bytearray.fromhex(data).decode() From [python docs](https://docs.python.org/3/library/stdtypes.html#bytearray.fromhex)
Don't know where is error. Code returns False with no reason Question: can you tell me, why this code returns False? I've just started learning python and have no clue why this doesn't work. #!/usr/bin/python from math import * lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] } def average(numbers): total = sum(numbers) total = float(total) total = total / len(numbers) return total def get_average(students): homework = average(students["homework"]) quizzes = average(students["quizzes"]) tests = average(students["tests"]) homework = homework * 0.1 quizzes = quizzes * 0.3 tests = tests * 0.6 score = tests + quizzes + homework score = float(score) return score def get_letter_grade(score): score = float(score) if score == int or score == float: if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" elif score >= 60: return "D" else: return "F" else: return False print get_letter_grade(get_average(lloyd)) Thank you in advance ;) Answer: The problem is in: if score == int or score == float: What you want is: if isinstance(score, (int, float)): Your variable `score` will never be equal to class `int` or class `float`. But it can be an instance of `int` or `float`. Another valid variant is: if type(score) is int or type(score) is float: or: if type(score) in (int, float):
Android drawables are not recognized by AndroidStudio if I use dpi subfolders Question: I have just started the [Treehouse](http://www.teamtreehouse.com) Android development course, I have also asked this question on their forums without any luck. **DATA** * AndroidStudio v 1.2.2, the course is based on v0.86 I think * OS / DE: Manjaro Linux, KDE I have copied the image files inside the drawable folder, each into their specific dpi folder. I have created the ImageView for a mail_title.png, and added the src as the full path to the png. When I do that, the image loads into the preview screen, and I can work with it, but If I try to build the app it just says the value of src cannot be a string. So then I tried to point to it as a resource. On many forums and the android documentation I only found that I should reference it through a "pointer" @drawable/main_title , when I downloaded the projectfiles from the course I saw thats how they did it too. If I try to rebuild now it gives the following error: Error:(14, 22) No resource found that matches the given name (at 'src' with value '@drawable/main_title'). Then I tried to create a resource inside strings.xml, I found some autocomplete function that pointed me in "the right direction", of course it did not work!, same error as before. I have tried using absolute paths as well without luck. Right now It shows R as "cannot resolve symbol R" in the MAinActivity file. I figured out by reading online that this is due to my drawable not existing problem. Then I created a refs.xml in values and added main_title.png I actually tried with and without the extension (png) After that I clicked on the IDE suggestion to create a drawable folder and it just created a @drawable folder inside of layout.... Basically it says it cannot resolve directory @drawable from activity_main.xml and also Error:(3, 33) String types not allowed (at 'main_title' with value 'main_title.png'). on the refs.xml file (this happens whether I use the extension (png) or not. The only solution I have found is to just copy one version fo the images to the main drawables folder, and deleting all of the subfolders, if I don't delte them then it also doesn't work... So, as you can see I'm kinda lost... Any help would be appreciated. I'm a python backend developer and I'm pretty comfortable usiong Pycharm (IntelliJ for python), but somehow I feel Android Studio has me totally lost! Answer: I use eclipse but i think its pretty much the same, you should have you various drawable folders, then you have to include the R (res folder) import com.example.project.R; and then call them by reference R.drawables.main_title Note you dont need to specify which drawable folder , adroid does that for you. Also if you are getting unresolved errors with R then you may need to have the appcompatv7 library inlcuded in your project.
Opening raw images on Python resulting in a different image compared to ImageJ Question: I wrote this script to open a raw image and do some processing. import numpy as np import matplotlib.pyplot as plt PATH = "C:\Users\Documents\script_testing_folder\\" IMAGE_PATH = PATH +"simulation01\\15x15_output_det_00001_raw_df_00000.bin" raw_image = np.fromfile(IMAGE_PATH, dtype=np.uint64) raw_image.shape = (15,15) plt.imshow(raw_image,cmap = 'gray') total_intensity = ndimage.sum(raw_image) print total_intensity plt.show() Using this script I get an Image such as this: [![enter image description here](http://i.stack.imgur.com/DqJP3.jpg)](http://i.stack.imgur.com/DqJP3.jpg) In contrast... when I open the same image on ImageJ(file>import>raw (64bit real, 15x15 length and width)) I have this: [![enter image description here](http://i.stack.imgur.com/JUprq.jpg)](http://i.stack.imgur.com/JUprq.jpg) I have tried looking around, but I am not sure where I am going wrong when trying to reproduce the same image on python. Any help would be greatly appreciated. Additionally when I sum the intensity in the image using: total_intensity = ndimage.sum(raw_image) print total_intensity y I get 4200794456581938015, whereas, on ImageJ I get 0.585. I am not sure where I am going wrong on these steps... Thanks ! Edit: The original file if anyone wants to reproduce the results I got <https://www.dropbox.com/s/po82z4uf2ku7k0e/15x15_output_det_00001_raw_df_00000.bin?dl=0> Answer: The problem is the [endianness](https://en.wikipedia.org/wiki/Endianness) of your data (the order of the single bytes of a 64bit float). Fortunately, numpy has the [functionality](http://docs.scipy.org/doc/numpy/user/basics.byteswapping.html) to solve this issue: import numpy as np import matplotlib.pyplot as plt # load the image raw_image = np.fromfile('15x15_output_det_00001_raw_df_00000.bin') raw_image = np.reshape(raw_image, (15, 15)) # swap the byte order raw_image = raw_image.byteswap() # output the sum of the intensities to check total_intensity = np.sum(raw_image) print "total intensity:", total_intensity # plot the image plt.imshow(raw_image,cmap = 'gray', interpolation='nearest') plt.show() Output: > total intensity: 0.585123878711 Result: [![enter image description here](http://i.stack.imgur.com/yqVvL.png)](http://i.stack.imgur.com/yqVvL.png)
"Failed building wheel for py-bcrypt" when pip installing flask-user Question: I'm trying to pip install the various extensions for Flask. So far they've all succeeded, and I've had no problems installing flask, flask-bcrypt, etc. with the exception of flask-user. When I try to pip install flask-user, the first error I get is "Failed building wheel for py-bcrypt". And then the following appears. Failed to build py-bcrypt Installing collected packages: py-bcrypt, pycrypto, flask-user Running setup.py install for py-bcrypt Complete output from command C:\Python27\Scripts\venv_flask\Scripts\python.e xe -c "import setuptools, tokenize;__file__='c:\\users\\brandon\\appdata\\local\ \temp\\pip-build-czloyh\\py-bcrypt\\setup.py';exec(compile(getattr(tokenize, 'op en', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install - -record c:\users\brandon\appdata\local\temp\pip-nk4rxx-record\install-record.txt --single-version-externally-managed --compile --install-headers C:\Python27\Scr ipts\venv_flask\include\site\python2.7\py-bcrypt: running install running build running build_py running build_ext building 'bcrypt._bcrypt' extension C:\Users\Brandon\AppData\Local\Programs\Common\Microsoft\Visual C++ for Pyth on\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\Scripts\venv_flask\PC /Tcbcrypt/bcrypt.c /Fobuild\temp.win32-2.7\R elease\bcrypt/bcrypt.obj bcrypt.c bcrypt/bcrypt.c(139) : warning C4996: '_snprintf': This function or variable may be unsafe. Consider using _snprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. C:\Users\Brandon\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Include\stdio.h(358) : see declaration of '_snprintf' bcrypt/bcrypt.c(249) : warning C4996: '_snprintf': This function or variable may be unsafe. Consider using _snprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. C:\Users\Brandon\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Include\stdio.h(358) : see declaration of '_snprintf' C:\Users\Brandon\AppData\Local\Programs\Common\Microsoft\Visual C++ for Pyth on\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\Scripts\venv_flask\PC /Tcbcrypt/bcrypt_pbkdf.c /Fobuild\temp.win32 -2.7\Release\bcrypt/bcrypt_pbkdf.obj bcrypt_pbkdf.c C:\Users\Brandon\AppData\Local\Programs\Common\Microsoft\Visual C++ for Pyth on\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\Scripts\venv_flask\PC /Tcbcrypt/bcrypt_python.c /Fobuild\temp.win3 2-2.7\Release\bcrypt/bcrypt_python.obj bcrypt_python.c bcrypt/bcrypt_python.c(63) : warning C4244: 'function' : conversion from 'lo ng' to 'u_int8_t', possible loss of data C:\Users\Brandon\AppData\Local\Programs\Common\Microsoft\Visual C++ for Pyth on\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\Scripts\venv_flask\PC /Tcbcrypt/blowfish.c /Fobuild\temp.win32-2.7 \Release\bcrypt/blowfish.obj blowfish.c c:\users\brandon\appdata\local\temp\pip-build-czloyh\py-bcrypt\bcrypt\pybc_b lf.h(86) : error C2146: syntax error : missing ')' before identifier 'passlen' c:\users\brandon\appdata\local\temp\pip-build-czloyh\py-bcrypt\bcrypt\pybc_b lf.h(86) : error C2081: 'size_t' : name in formal parameter list illegal c:\users\brandon\appdata\local\temp\pip-build-czloyh\py-bcrypt\bcrypt\pybc_b lf.h(86) : error C2061: syntax error : identifier 'passlen' c:\users\brandon\appdata\local\temp\pip-build-czloyh\py-bcrypt\bcrypt\pybc_b lf.h(86) : error C2059: syntax error : ';' c:\users\brandon\appdata\local\temp\pip-build-czloyh\py-bcrypt\bcrypt\pybc_b lf.h(86) : error C2059: syntax error : ',' c:\users\brandon\appdata\local\temp\pip-build-czloyh\py-bcrypt\bcrypt\pybc_b lf.h(88) : error C2059: syntax error : ')' c:\users\brandon\appdata\local\temp\pip-build-czloyh\py-bcrypt\bcrypt\pybc_b lf.h(91) : error C2146: syntax error : missing ')' before identifier 'n' c:\users\brandon\appdata\local\temp\pip-build-czloyh\py-bcrypt\bcrypt\pybc_b lf.h(91) : error C2081: 'size_t' : name in formal parameter list illegal c:\users\brandon\appdata\local\temp\pip-build-czloyh\py-bcrypt\bcrypt\pybc_b lf.h(91) : error C2061: syntax error : identifier 'n' c:\users\brandon\appdata\local\temp\pip-build-czloyh\py-bcrypt\bcrypt\pybc_b lf.h(91) : error C2059: syntax error : ';' c:\users\brandon\appdata\local\temp\pip-build-czloyh\py-bcrypt\bcrypt\pybc_b lf.h(91) : error C2059: syntax error : ')' error: command 'C:\\Users\\Brandon\\AppData\\Local\\Programs\\Common\\Micros oft\\Visual C++ for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2 I didn't want to risk leaving anything out. However, I BELIEVE the key part of this error message is this part: bcrypt/bcrypt.c(139) : warning C4996: '_snprintf': This function or variable may be unsafe. Consider using _snprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. I believe that there is something with Microsoft Visual Basic that's the problem. However, I haven't gotten any good answers online when I looked it up. I'm using Microsoft Visual Basic C++ 's compiler for Python 2.7 I haven't seen any other problems online that seem to address my problem. Some come close, but they seem to offer solutions that don't have anything to do with my problem (references to files that I don't use/have, etc.) Answer: This was an issue with Microsoft Visual Studio which seems to be patched now. See [here](https://code.google.com/p/py-bcrypt/issues/detail?id=15) the patch.
many-to-many relationship in sqlalchemy Question: I just switched from MySQL to SQLalchemy and I have to say that it is more difficult to get my head around sqlalchemy than I thought. Currently I have some trouble with a many-to-many relationship. I have users and queries in my model. A user can have many queries and a query offers a new article to read every day. I want to store which user read which query on what date. My models.py looks like this class User(db.Model): id = db.Column(db.Integer, primary_key=True) read_dates = db.relationship("ReadIndex", backref="user") def __repr__(self): return '<User %r>' % (self.id) class Queries(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Queries %r>' % (self.id) class ReadIndex(db.Model): user_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) query_id = db.Column(db.Integer, db.ForeignKey('queries.id'), primary_key=True) read_datetime = db.Column(db.DateTime) read_query = db.relationship("Queries", backref="user_assocs") def __repr__(self): return '<ReadIndex>' so I have users and queries. To store which user read which query on what date I have the class ReadIndex, which has an extra field called read_datetime, where I store the date of a user-query association. I than want to add such an association like user = models.User.query.filter_by(id=user_id).first() query = models.Queries.query.filter_by(id=query_id).first() a = models.ReadIndex(read_datetime=dt.utcnow()) a.read_query = query user.read_dates.append(a) db.session.commit() where query_id and user_id are the corresponding ids to select my objects. If I run this I get an error sqlalchemy.exc.IntegrityError IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: read_index.query_id [SQL: u'INSERT INTO read_index (user_id, read_datetime) VALUES (?, ?)'] [parameters: (1, '2015-07-29 20:55:50.898366')] I am not sure what the problem is? I don't seem to violate any NOT NULL edit: I noticed that I assigned query=None to a.read_query. Correcting this slightly changed the error IntegrityError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely) (sqlite3.IntegrityError) NOT NULL constraint failed: read_index.user_id [SQL: u'INSERT INTO read_index (query_id, read_datetime) VALUES (?, ?)'] [parameters: (1, '2015-07-29 23:11:11.934038')] here is exactly what happens: >>> from app import app, db, models >>> user = models.User.query.filter_by(id=1).first() >>> user <User u'Florian Beutler'> >>> query = models.Queries.query.filter_by(id=1).first() >>> query <Queries 1> >>> import datetime >>> a = models.ReadIndex(read_datetime=datetime.datetime.utcnow()) >>> a.read_query = query >>> user.read_dates.append(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site- packages/sqlalchemy/orm/attributes.py", line 237, in __get__ return self.impl.get(instance_state(instance), dict_) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 578, in get value = self.callable_(state, passive) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/strategies.py", line 529, in _load_for_state return self._emit_lazyload(session, state, ident_key, passive) File "<string>", line 1, in <lambda> File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/strategies.py", line 599, in _emit_lazyload result = q.all() File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2399, in all return list(self) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2515, in __iter__ self.session._autoflush() File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1292, in _autoflush util.raise_from_cause(e) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause reraise(type(exception), exception, tb=exc_tb) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1282, in _autoflush self.flush() File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2004, in flush self._flush(objects) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2122, in _flush transaction.rollback(_capture_exception=True) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2086, in _flush flush_context.execute() File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 373, in execute rec.execute(self) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 532, in execute uow File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 174, in save_obj mapper, table, insert) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 781, in _emit_insert_statements execute(statement, params) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 914, in execute return meth(self, multiparams, params) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 323, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1010, in _execute_clauseelement compiled_sql, distilled_params File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1146, in _execute_context context) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1341, in _handle_dbapi_exception exc_info File "/usr/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause reraise(type(exception), exception, tb=exc_tb) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1139, in _execute_context context) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 450, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.IntegrityError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely) (sqlite3.IntegrityError) NOT NULL constraint failed: read_index.user_id [SQL: u'INSERT INTO read_index (query_id, read_datetime) VALUES (?, ?)'] [parameters: (1, '2015-07-29 23:17:06.013485')] constraint? thanks carl Answer: The `.first()` method either returns the first result or `None` if there isn't one, are you sure you're not assigning `a.read_query` to `None`?
Need some help on how to implement an restfull api app based on golang Question: My coding skills are a bit low :) Recently i started learning golang and how to handle an Api communication app. Have been having a great time learning it by myself, golang is revealing itself as a challenging language with great rewards in the end (code sense ^^). Have been trying to create a cryptsy api lib for golang based on their API V2 (BETA) which is a restfull api. They have a python lib on their api website <https://github.com/ScriptProdigy/CryptsyPythonV2/blob/master/Cryptsy.py>. So far have been able to get the public access working but am having a really hard time at the private access because of the authentication part.. I find that the info they give on their website on how to implement it is a bit confusing :( > Authorization is performed by sending the following variables into the > request header Key > > * Public API key. > * All query data (nonce=blahblah&limit=blahblah) signed by a secret key > according to HMAC-SHA512 method. Your secret key and public keys can be > generated from your account settings page. Every request requires a unique > nonce. (Suggested to use unix timestamp with microseconds) > For this authentication part the python code goes as: def _query(self, method, id=None, action=None, query=[], get_method="GET"): query.append(('nonce', time.time())) queryStr = urllib.urlencode(query) link = 'https://' + self.domain + route sign = hmac.new(self.PrivateKey.encode('utf-8'), queryStr, hashlib.sha512).hexdigest() headers = {'Sign': sign, 'Key': self.PublicKey.encode('utf-8')} Got this far in golang: package main import( "crypto/hmac" "crypto/sha512" "encoding/hex" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "strings" "time" ) const ( API_BASE_CRY = "https://api.cryptsy.com/api/" API_VERSION_CRY = "v2" API_KEY_CRY = "xxxxx" API_SECRET_CRY = "xxxxxxxxxxxx" DEFAULT_HTTPCLIENT_TIMEOUT = 30 // HTTP client timeout ) type clientCry struct { apiKey string apiSecret string httpClient *http.Client } type Cryptsy struct { clientCry *clientCry } type CryptsyApiRsp struct { Success bool `json:"success"` Data json.RawMessage `json:"data"` } func NewCry(apiKey, apiSecret string) *Cryptsy { clientCry := NewClientCry(apiKey, apiSecret) return &Cryptsy{clientCry} } func NewClientCry(apiKey, apiSecret string) (c *clientCry) { return &clientCry{apiKey, apiSecret, &http.Client{}} } func ComputeHmac512Hex(secret, payload string) string { h := hmac.New(sha512.New, []byte(secret)) h.Write([]byte(payload)) return hex.EncodeToString(h.Sum(nil)) } func (c *clientCry) doTimeoutRequestCry(timer *time.Timer, req *http.Request) (*http.Response, error) { type data struct { resp *http.Response err error } done := make(chan data, 1) go func() { resp, err := c.httpClient.Do(req) done <- data{resp, err} }() select { case r := <-done: return r.resp, r.err case <-timer.C: return nil, errors.New("timeout on reading data from Bittrex API") } } func (c *clientCry) doCry(method string, ressource string, payload string, authNeeded bool) (response []byte, err error) { connectTimer := time.NewTimer(DEFAULT_HTTPCLIENT_TIMEOUT * time.Second) var rawurl string nonce := time.Now().UnixNano() result := fmt.Sprintf("nonce=%d", nonce) rawurl = fmt.Sprintf("%s%s/%s?%s", API_BASE_CRY ,API_VERSION_CRY , ressource, result ) req, err := http.NewRequest(method, rawurl, strings.NewReader(payload)) sig := ComputeHmac512Hex(API_SECRET_CRY, result) req.Header.Add("Sign", sig) req.Header.Add("Key", API_KEY_CRY ) resp, err := c.doTimeoutRequestCry(connectTimer, req) defer resp.Body.Close() response, err = ioutil.ReadAll(resp.Body) fmt.Println(fmt.Sprintf("reponse %s", response), err) return response, err } func main() { crypsy := NewCry(API_KEY_CRY, API_SECRET_CRY) r, _ := crypsy.clientCry.doCry("GET", "info", "", true) fmt.Println(r) } and my output is : `response {"success":false,"error":["Must be authenticated"]} <nil>` not getting why :( im passing the public key and the signature in the header, the signature.. i think im doing it right in the hmac-sha512. I'm quering the user info url <https://www.cryptsy.com/pages/apiv2/user>, which as stated in the api site doesn't have any extra query variables so the nonce is the only one needed.. Have googled about restfull api's but haven't been able to find any answer :( starting to not let me sleep at night since i think that what im doing is kinda right.. really cant spot the error.. Anyone out there that could try and help me with this? Thxs a lot :) Answer: I see the issue with `result := fmt.Sprintf("%d", nonce)`. The code that corresponds to the Python code should be something like result := fmt.Sprintf("nonce=%d", nonce) Could you please check it with this fix? I also can observe a major difference in how the request is sending. The Python version is ([link](https://github.com/ScriptProdigy/CryptsyPythonV2/blob/master/Cryptsy.py)): ret = requests.get(link, params=query, headers=headers, verify=False) but your code is does not send `params` with added nonce, etc. I think it should be something like rawurl = fmt.Sprintf("%s%s/%s?%s", API_BASE_CRY ,API_VERSION_CRY , ressource, queryStr) where queryStr should contain nonce, etc.
parsing with expression including a newline in python Question: I was trying to parsing some html files, in which I want to extract some value called "Total Cash", but these html come in two different forms: 1. `...Total Cash (mrq):</td> <td class="yfnc_tabledata1">8.71B</td>...` 2. `...Total Cash (mrq):</td> <td class="yfnc_tabledata1">8.71B</td>...` It is easy to parsing the first one, and the following code gives me the number 8.71B source.split('Total Cash (mrq):</td> <td class="yfnc_tabledata1">')[1].split('</td>')[0] However, I don't know how to parse the second form, in which the value and the string 'Total Cash (mrq)' are in two different lines. Any suggestions? Also, there are about 9000 htmls, and each file contains about 1000 rows of code. Answer: You can try something like this as you mentioned `beautifulsoup` from bs4 import BeautifulSoup html_doc = """ <td>Total Cash (mrq):</td> <td class="yfnc_tabledata1">8.71B</td> """ soup = BeautifulSoup(html_doc, 'html.parser') td_head = soup.find(text="Total Cash (mrq):").parent td_desired = td_head.find_next('td') print td_desired.contents[0] If you need to get all the elements you can try `find_all` , by using something like this : td_heads_content = soup.find_all(text="Total Cash (mrq):") for elem in td_heads_content: td_head = elem.parent
Suppressing logger messages below a certain level in Python Question: I worked on one system with a repo that imported lots of libraries. These used the Python logger facility. I would only receive messages for events logger.error and higher. I moved to a different system and cloned the same repos (and libraries). Now, I get logger.info() and higher. I've done a bit of searching and I've been unable to track down where a central configuration for logger for a user is kept. I'm not sure what changed from the first system to the second, but I wish to have the functionality of the first back. To clarify: the logger 'filter' applied to messages generated by not only the software, but also the libraries it used. Any ideas? Answer: For Python's standard `logging` module, there's no system-wide central config for logging, IIRC; you have to set it programmatically — and you can trigger that from your own config file, the arguments in `sys.argv`, from Consul, etc., if you want; sky's the limit here. Depending on exactly what program you're using, and how it works, it may have a particular config file or method for setting the logging level. If this is just your own codebase, then read on. To set the logging level, you need a logger; once you have a logger, you just need to call [`setLevel`](https://docs.python.org/2/library/logging.html#logging.Logger.setLevel) on it. You can do this for the root logger, which will likely affect all logging: root_logger = logging.getLogger() root_logger.setLevel(logging.WARNING) # I'd recommend not removing WARNINGs. Applying a log level to the root logger is a bit of a sledgehammer solution; some well-behaved libraries (and your own code can do this, too) create their own loggers, with something like, MY_LIBRARYS_LOGGER = logging.getLogger('my_library') def some_public_function(…): MY_LIBRARYS_LOGGER.info('Hi there logs.') You can then silence _just those messages_ with, logging.getLogger('my_library').setLevel(logging.WARNING) (or, if they export their logger as a constant, as my example does, `MY_LIBRARYS_LOGGER.setLevel(…)`) I find it very useful to redirect entire subsystems through a logger, so that you can raise/lower the levels as needed when hunting bugs. As an example of a library that does this, [this answer](http://stackoverflow.com/a/26460395/101999) shows how to apply this to the [requests library](http://docs.python-requests.org/en/latest/). One last note: the loggers form a hierarchy: `foo.bar` is a child logger to `foo`. See [the logging module's documentation](https://docs.python.org/2/library/logging.html), of course. One _last_ opinion: if this _is_ your code-base, and you're seeing too many log lines, consider moving some of them to `debug`; I find `info` a good place to log things that are indicative of the health of the system, such as "this request to this other server took n seconds" (a real metrics system is of course a better choice, if you have one, but sometimes what you have are logs); this makes for an easy grep to see if that request is slow, and still allows you to grep them _out_ mostly reliably if it is too noisy (by grepping out info lines); `debug` is more "I did this thing that I always would do."
How to test Pl/Python PostgreSQL procedures with Travis CI? Question: I'm trying to set up CI for some PL/Python PostgreSQL procedures in Travis CI. I've tried several ways: 1) With the legacy infrastructure I've tried to just assume, that PL/Python is already installed, but it had not succeed: The command "psql -U postgres -c 'CREATE EXTENSION plpythonu;'" exited with 1. 0.01s$ psql -U postgres -d test -c 'CREATE LANGUAGE plpythonu;' ERROR: could not access file "$libdir/plpython2": No such file or directory 2) Have tried to add `sudo apt-get update && sudo apt-get -y install postgresql-plpython-9.4` commands in the beginning. And it was also failed, because this command initiated replacement of PostgresSQL 9.4, that comes already installed in the Travis environment. [Travis build.](https://travis-ci.org/AndrewPashkin/python- tempo/builds/74546906) 3) Also tried to use container-based infrastructure with this lines in the config: addons: postgresql: "9.4" apt: packages: - postgresql-plpython-9.4 No success too. What is the good way to test PL/Python procedure in Travis CI? Answer: I was able to get the [python-tempo build working](https://travis- ci.org/heenenee/python-tempo/builds/74848089) with the following [.travis.yml](https://github.com/heenenee/python- tempo/blob/pg_test/.travis.yml): sudo: required language: python before_install: - sudo apt-get -qq update - sudo /etc/init.d/postgresql stop - sudo apt-get install -y postgresql-9.4 - sudo apt-get install -y postgresql-contrib-9.4 postgresql-plpython-9.4 - sudo -u postgres createdb test - sudo -u postgres createlang plpython2u test - sudo pip install jinja2 script: - > sudo -u postgres psql -d test -c 'CREATE OR REPLACE FUNCTION py_test() RETURNS void LANGUAGE plpython2u AS $$ import jinja2 $$;' - sudo -u postgres psql -d test -c 'SELECT py_test();' Your legacy configuration attempts had a variety of issues including not stopping the existing PostgreSQL 9.1 instance before installing 9.4 and not specifying the plpython language properly. I believe some commands were also not being run as the correct user. All of the issues are resolved by the above configuration. There may be ways in which this configuration can be improved, but I stopped once I got it working. The container-based configuration won't work because `postgresql-plpython-9.4` is not currently in the [whitelist of pre-approved packages](https://github.com/travis-ci/apt-package- whitelist/blob/master/ubuntu-precise). However, `postgresql-plpython-9.5` is, so if you want to migrate to a container-based configuration, you can either try [following the package approval process](https://github.com/travis-ci/apt- package-whitelist) for `postgresql-plpython-9.4` or wait for the [GA release of PostgreSQL 9.5](http://www.postgresql.org/developer/roadmap/) and try migrating then.
Set timeout for Python socket when sending data out Question: I would like to set timeout for Python socket client. That means, socket client connects to server then sends data within 1 second. If it takes more than 1 second, the method would raise some kind of exception or error. Here is my source code: def sendDataTelnet(ipTmp, strTmp): # try to send data to <ipTmp> try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) writeLog("connecting to %s" % (ipTmp)) s.settimeout(1.0) s.connect((ipTmp, 4242)) writeLog("connected to %s, start to send data" % (ipTmp)) s.sendall(strTmp) s.close() s = None writeLog("done writing to %s" % (ipTmp)) return True except socket.timeout: writeLog("timed out when connecting to %s" % (ipTmp)) s.close() s = None return False except socket.error: writeLog("error when communicating with %s" % (ipTmp)) s.close() s = None return False This doesn't work for me. It works only when "connect" action takes longer than 1 second. However, if it connects fine but it sends large amount of data that takes more than 1 second, no exception raised. Answer: You could set an alarm timeout prior to the socket call and clear when done. eg. import os, signal class TimeoutError(Exception): pass def handle_timeout(signum, frame): import errno raise TimeoutError(os.strerror(errno.ETIME)) TIMEOUT=1 signal.signal(signal.SIGALRM, handle_timeout) signal.alarm(TIMEOUT) try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # your code .... except TimeoutError: print "Timeout reached" finally: signal.alarm(0)
Method of Runge-Kutta in Python Question: I wrote a code about runge-kutta method in python, but every time when the program realizes any calculus the program require the differential equation. this is my code: from math import * import numpy as np #Initial Values n=input("Enter the number of equations n:") n=int(n) x=np.array([]) for i in range(0,n): x0=input("Enter the initial value of x{}:".format(i)) x=np.append(x,[x0]) t=input("Enter the initial value of t:") tf=input("Enter the final value of t:") h=input("Enter the time interval h:") m=int((tf-t)/float(h)) #Definition of differential equations def f(t,x): f=np.array([]) for i in range(0,n): f0=input("Enter the equation f{}:".format(i)) f=np.append(f,[f0]) return f a=1.0/6 for i in range(0,m): k1=f(t,x) k2=f(t+0.5*h,x+0.5*h*k1) k3=f(t+0.5*h,x+0.5*h*k2) k4=f(t+h,x+h*k3) x=x+a*h*(k1+2*(k2+k3)+k4) t=t+h print t, x Example using the equation dx/dt=x, x(0)=1, xf=1, h=0.1: Enter the number of equations n:1 Enter the initial value of x0:1 Enter the initial value of t:0 Enter the final value of t:1 Enter the time interval h:0.1 Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] Enter the equation f0:x[0] 1.0 [ 2.71827974] What should i do to enter only once the differential equation to program calculate all? Answer: You have to move the the equation input code out of your function `f(x,y)` Ask for the equations to be input in the same block as you are asking for all the other input. As it stands your code calls the function at every time interval so will ask for input at every time interval.
Django project not working with Apache and mod-wsgi Question: I created a droplet(cloud server) on DigitalOcean and with no-ip.com I gave it the hostname - project.ddns.net.By ssh(ing) into the droplet I installed pip and virtualenv. Inside /var/www/ I created a virtualenv and cloned the repository from github of my project.The directory struture is - project_revamped (root of the project) ->requirements ->base.txt ->dev.txt ->project (django project) ->static ->media ->apps (folder which contains apps) ->manage.py ->project ->urls.py ->settings ->base.py ->dev.py I installed apache2 and mod_wsgi using - sudo apt-get install apache2 sudo apt-get install libapache2-mod-wsgi I then installed mysql,created a database and installed all requirements pip install -r base.txt I created a virtualhost project.conf on the path - /etc/apache2/sites-available/project.conf the content of file is this - <VirtualHost *:80> ServerAdmin [email protected] ServerName project.ddns.net ServerName www.project.ddns.net WSGIScriptAlias / /var/www/project_revamped/project/project/wsgi.py <Directory /var/www/project_revamped/project/project> Order deny,allow Allow from all </Directory> </VirtualHost> Then I gave this command to activate this conf file - a2ensite project.conf The content of my wsgi.py in my django project is - import os import sys import site #Add the site-packages of the chosen virtualenv to work with site.addsitedir('/var/www/.virtualenvs/projectenv/local/lib/python2.7/site-packages') #Add the app's directory to the python path sys.path.append('/var/www/project_revamped/project') sys.path.append('/var/www/project_revamped/project/project') os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings.dev' #Activate your virtualenv activate_env = os.path.expanduser('/var/www/.virtualenvs/projectenv/bin/activate_this.py' ) execfile(activate_env, dict(__file__=activate_env)) from django.core.wsgi import get_wsgi_application application = get_wsgi_application() After changing the files I finally gave the commands - service apache2 reload service apache2 restart However after doing these things right the corresponding ip says there is some problem the server and sends 500 error.I guess the problem is somewhere in my configuration because apache server was responding working fine.After I include django project with it the problem starts. Can anybody please help me here in the configuration? I am stuck in this for past 2 days and every different article on the internet tells the different story. Answer: Have a look at [the official documentation](https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/modwsgi/). I think you're missing the `WSGIPythonPath`-directive. As @BurhanKhalid stated, this linked tutorial is complete and tested and should nearly exactly match your setup.
scikit learn - converting features stored as strings into numbers Question: I'm currently dipping my toes into machine learning using the scikit-learn python library and am trying to use some .CSV data in the format Date Name Average_Price_SA 1995-01-01 Barking And Dagenham 70885.331285935 1995-01-01 Barnet 99567.4268042005 1995-01-01 Barnsley 49608.33494746 .... .... .... 2005-01-01 Barking And Dagenham 13294.12321312 I have read them in using panda using the line data = pd.read_csv('data.csv') From what I have learned so far, I think I'm supposed to convert those 'Name' category strings into floats so that they can be accepted into a model. I'm not sure how to go about this. Any help would be greatly appreciated. Thanks Answer: You can use scikit's `LabelBinarizer` to convert the strings to one hot vectors. These have N zeros (where N is the number of unique strings) with a one at a single component. from __future__ import print_function from sklearn import preprocessing names = ["Barking And Dagenham", "Barnet", "Barnsley"] lb = preprocessing.LabelBinarizer() vectors = lb.fit_transform(names) for name, vector in zip(names, vectors): print("%s => %s" % (name, str(vector))) Output: Barking And Dagenham => [1 0 0] Barnet => [0 1 0] Barnsley => [0 0 1]
Reading from text file with HTML and Javascript Question: We currently have a python script that uses the Twitter API to generate a text file with a user's latest tweets. We now need to somehow display them in a webpage, so we attempted to use an XMLHttpRequest to read the local text file and display it. Formatting is not important at the moment, we are just trying to read directly from the file. The code we have so far, which is mostly from what we found online, is as follows: <!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { document.write("Test. "); document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } xmlhttp.open("GET","twitterFeed.txt",false); xmlhttp.send(); } </script> </head> <body> <h2>Using the XMLHttpRequest object</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html> Thanks in advance. EDIT: The issue we have is that it is not outputting anything, regardless of what is written in the text file. It does print out the "Test. " string that we were using to ensure that the function was being called. As far as we can tell, there aren't any js or net errors showing up. Answer: If you call `document.write` on a document in the closed state (which the document will be in as the DOM will have been completely parsed) it will implicitly call `document.open` which will _wipe out the existing document_. You then write out _Test._ , which you can see. Among the things that will have been deleted will be `<div id="myDiv"></div>` so `document.getElementById("myDiv").innerHTML=xmlhttp.responseText;` will fail. **Don't use`document.write`**.
Working interactively in Python Question: Is there any way to switch to 'interactive' mode within a Python script, similar to the "keyboard" function in Matlab? I am aware of iPython, but I don't think it would allow me to 'pause' at some point in a script, e.g., within a for-loop, switch to interactive mode based on an if-statement. In Matlab this would simply be something like: for i = 1:100 % do stuff if i == 55 keyboard end % do more stuff end Answer: I think you want the debugger. import pdb; pdb.set_trace() This will dump you into a debug session where you can inspect and edit variables, and call functions.
Understanding syntax in Python Question: I am trying to use PodSixNet library in Python to implement a multiplayer game. As I have seen a few tutorials online, the server file is as follows: import PodSixNet.Channel import PodSixNet.Server from time import sleep class ClientChannel(PodSixNet.Channel.Channel): def Network(self, data): print data class BoxesServer(PodSixNet.Server.Server): channelClass = ClientChannel def __init__(self, *args, **kwargs): PodSixNet.Server.Server.__init__(self, *args, **kwargs) What does the line `channelClass = ClientChannel`mean? `channelClass` is definitely not an instance of the `ClientChannel` class because the instance declaration is not correct. So what is it then? Answer: All this does is create the `BoxesServer.channelClass` class attribute. It is just a reference to another class. Why would you do that? Well, the `PodSixNet.Server.Server` is flexible, it doesn't hardcode the class it'll use to create channels for new connections. Instead, it'll look for the `self.channelClass` attribute, and use that to create new channel instances. See the [`Server.handle_accept()` method source](https://github.com/chr15m/PodSixNet/blob/master/PodSixNet/Server.py#L22-L35): self.channels.append(self.channelClass(conn, addr, self, self._map)) Calling `self.channelClass()` then creates an instance of whatever class is assigned to that attribute. This lets you swap out the channel class easily when defining new subclasses. Note that the `PodSixNet.Server.Server()` class can also take the channel class as an argument when creating an instance. That'll then override the class attribute you set.
TypeError: an integer is required (got type str) Question: I am new to Python and Flask. I am working my way throught this tutorials: <http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web- forms> Right now i am getting an error for which i can't find a fix for. I have reinstalled Python 3.4.3 and reinstalled the virtual environment, I have copyed the code directly from the tutorial to make sure i did not make a mistake while typing, still nothing works. **init**.py from flask import Flask app = Flask(__name__) app.config.from_object('config') from app import views views.py from flask import render_template, flash, redirect from app import app from .forms import LoginForm @app.route('/') @app.route('/index') def index(): user = {'nickname': 'Miguel'} posts = [ { 'author': {'nickname': 'John'}, 'body': 'Beautiful day in Portland!' }, { 'author': {'nickname': 'Susan'}, 'body': 'The Avengers movie was so cool!' } ] return render_template("index.html", title='Home', user=user, posts=posts) @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() return render_template('login.html', title='Sign In', form=form) forms.py from flask.ext.wtf import Form from wtforms import StringField, BooleanField from wtforms.validators import DataRequired class LoginForm(Form): openid = StringField('openid', validators=[DataRequired()]) remember_me = BooleanField('remember_me', default=False) run.py from app import app app.run(debug=True) The error: (flask) G:\microblog>python run.py Traceback (most recent call last): File "run.py", line 1, in <module> from app import app File "G:\microblog\app\__init__.py", line 6, in <module> from app import views File "G:\microblog\app\views.py", line 3, in <module> from .forms import LoginForm File "G:\microblog\app\forms.py", line 1, in <module> from flask.ext.wtf import Form File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1191, in _load_unlocked File "<frozen importlib._bootstrap>", line 1161, in _load_backward_compatible File "G:\microblog\flask\lib\site-packages\flask\exthook.py", line 62, in load_module __import__(realname) File "G:\microblog\flask\lib\site-packages\flask_wtf\__init__.py", line 15, in <module> from .form import Form File "G:\microblog\flask\lib\site-packages\flask_wtf\form.py", line 15, in <module> from .i18n import translations File "G:\microblog\flask\lib\site-packages\flask_wtf\i18n.py", line 12, in <module> from flask_babel import get_locale File "G:\microblog\flask\lib\site-packages\flask_babel\__init__.py", line 21, in <module> from babel import dates, numbers, support, Locale File "G:\microblog\flask\lib\site-packages\babel\dates.py", line 28, in <module> from babel.util import UTC, LOCALTZ File "G:\microblog\flask\lib\site-packages\babel\util.py", line 278, in <module> from babel import localtime File "G:\microblog\flask\lib\site-packages\babel\localtime\__init__.py", line 21, in <module> from babel.localtime._win32 import _get_localzone File "G:\microblog\flask\lib\site-packages\babel\localtime\_win32.py", line 18, in <module> tz_names = get_global('windows_zone_mapping') File "G:\microblog\flask\lib\site-packages\babel\core.py", line 58, in get_global _global_data = pickle.load(fileobj) TypeError: an integer is required (got type str) I am frustrated that i can't continue the tutorial, so any help is welcome. Answer: The old version of babel doesn't work with 3.4. Install this update instead: pip3.4.exe install git+<https://github.com/mitsuhiko/[email protected]> It works with Python3.4 so you no longer need to downgrade your Python.
Python Internal Server Error Question: I'm new to Python Web Development and I have written the following code and uploaded into the root of my server (`public_html`) folder: import web urls = ('/','index') app = web.application(urls, globals()) class index: def GET(self): greeting = "Hello World" return greeting app.run() My `.htaccess` file is: AddType text/html py AddHandler cgi-script .py .cgi When I open my site, I get the following error: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, [email protected] and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request. My cPanel Error Log shows: [Thu Jul 30 10:44:42 2015] [error] [client 1.1.1.1] client denied by server configuration: /home/user/public_html/.htaccess [Thu Jul 30 10:36:53 2015] [error] [client 1.1.1.1] attempt to invoke directory as script: /home/user/public_html/cgi-bin/, referer: http://example.com/ Most of the places I searched for said that the `.py` file should be given permission 755. I did the same and in addition, even gave 755 permission to `.htaccess` file. What may be the probable solution? Answer: I believe its neither issue with py or .htaccess file permissions, its all about provide access to the files under .htaccess in the configuration section... check that out!!!!
Python Poplib Error Question: This is the code import poplib from email import parser pop_conn = poplib.POP3_SSL('pop.gmail.com') pop_conn.user('[email protected]') pop_conn.pass_('password') messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] messages = ["\n".join(mssg[1]) for mssg in messages] messages = [parser.Parser().parsestr(mssg) for mssg in messages] for message in messages: print(message) When it gets to the 8th line (`messages = ["\n".join(mssg[1]) for mssg in messages]`) It says this: TypeError: sequence item 0: expected str instance, bytes found Does anyone know what i'm doing wrong? Answer: Convert the bytes objects into string using [`bytes.decode`](https://docs.python.org/3/library/stdtypes.html#bytes.decode): messages = ["\n".join(m.decode() for m in mssg[1]) for mssg in messages]
saving a structure of a list with the data in a text file using Python Question: I have a list of lists of tuples which I want to save in a text file as a string and later read it from another Python script and use ast.literal_eval to transform it from string to list. My question is if its possible to write in a text file not only the data in the list but the whole structure my list of lists of tuples has. For example to have a text file like this: [[(365325.342877, 4385460.998374), (365193.884409, 4385307.899807), (365433.717878, 4385148.9983749995)]] Does this makes sense? Answer: This sounds like a situation better suited to `pickle` than writing to a text file and using `ast.literal_eval`. >>> import pickle >>> l = [(1,2),(3,4)] >>> with open('new_pickle.txt', 'wb') as f: pickle.dump(l, f) >>> ================================ RESTART ================================ >>> import pickle >>> with open('new_pickle.txt' ,'rb') as f: l = pickle.load(f) >>> l [(1, 2), (3, 4)] >>>
Error on creating cassandra cluster with ccm (Cassandra Cluster Manager ) Question: I am trying to follow tutorials on Cassandra academy and this is what I get when trying to run ccm to create a Cassandra cluster. ~/cassandra$ ccm create demo_1node -v 2.2.0 -n 1 -s -d Downloading http://archive.apache.org/dist/cassandra/2.2.0/apache-cassandra-2.2.0-src.tar.gz to /tmp/ccm-RlxXjd.tar.gz (21.283MB) 22316682 [100.00%] Extracting /tmp/ccm-RlxXjd.tar.gz as version 2.2.0 ... Compiling Cassandra 2.2.0 ... Deleted /home/adelin/.ccm/repository/2.2.0 due to error Traceback (most recent call last): File "/usr/local/bin/ccm", line 4, in <module> __import__('pkg_resources').run_script('ccm==2.0.4.1', 'ccm') File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 534, in run_script self.require(requires)[0].run_script(script_name, ns) File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 1445, in run_script exec(script_code, namespace, namespace) File "/usr/local/lib/python2.7/dist-packages/ccm-2.0.4.1-py2.7.egg/EGG-INFO/scripts/ccm", line 72, in <module> File "build/bdist.linux-x86_64/egg/ccmlib/cmds/cluster_cmds.py", line 130, in run File "build/bdist.linux-x86_64/egg/ccmlib/cluster.py", line 56, in __init__ File "build/bdist.linux-x86_64/egg/ccmlib/cluster.py", line 69, in load_from_repository File "build/bdist.linux-x86_64/egg/ccmlib/repository.py", line 44, in setup File "build/bdist.linux-x86_64/egg/ccmlib/repository.py", line 231, in download_version ccmlib.common.CCMError: Error compiling Cassandra. See /home/adelin/.ccm/repository/last.log for details adelin@sofiaag:~/cassandra$ java -version java version "1.7.0_60" Java(TM) SE Runtime Environment (build 1.7.0_60-b19) Java HotSpot(TM) 64-Bit Server VM (build 24.60-b09, mixed mode) adelin@sofiaag:~/cassandra$ ant -version Apache Ant(TM) version 1.9.5 compiled on May 31 2015 Operating System PRETTY_NAME="Debian GNU/Linux 8 (jessie)" NAME="Debian GNU/Linux" VERSION_ID="8" VERSION="8 (jessie)" ID=debian HOME_URL="http://www.debian.org/" SUPPORT_URL="http://www.debian.org/support/" BUG_REPORT_URL="https://bugs.debian.org/" here is the error file last.log <https://gist.github.com/AdelinGhanaem/a30e29e1fec9f520d747> Answer: Cassandra 2.2 requires Java 8. Update your path and try to launch the command again.
python lxml get parent element when you know child text with xpath Question: I have the following xml file: _test.xml_ <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <SubmitTransaction xmlns="http://www.someaddress.com/someendpoint"> <objTransaction> <DataFields> <TxnField> <FieldName>Pickup.Address.CountryCode</FieldName> <FieldValue>DE</FieldValue> <FieldIndex>0</FieldIndex> </TxnField> <TxnField> <FieldName>Pickup.Address.PostalCode</FieldName> <FieldValue>10827</FieldValue> <FieldIndex>0</FieldIndex> </TxnField> <TxnField> <FieldName>Pickup.DateTime</FieldName> <FieldValue>2016-05-28T03:26:05</FieldValue> <FieldIndex>0</FieldIndex> </TxnField> <TxnField> <FieldName>Pickup.LocationTypeCode</FieldName> <FieldValue>O</FieldValue> <FieldIndex>0</FieldIndex> </TxnField> <TxnField> <FieldName>Pickup.Address.City</FieldName> <FieldValue>Berlin</FieldValue> <FieldIndex>0</FieldIndex> </TxnField> </DataFields> </objTransaction> </SubmitTransaction> </soap:Body> </soap:Envelope> What I want to do is to get an element with tag `TxnField` that has a child `FieldName` with text `Pickup.DateTime`. It is important to get the parent element, so I need to get this: <TxnField> <FieldName>Pickup.DateTime</FieldName> <FieldValue>2016-05-28T03:26:05</FieldValue> <FieldIndex>0</FieldIndex> </TxnField> What I have so far is the following: from lxml import etree xml_parser = etree.XMLParser(remove_blank_text=True) xml_tree = etree.parse('test.xml', xml_parser) p_time = xml_tree.xpath("//*[local-name()='TxnField']/*[text()='Pickup.DateTime']") print(p_time[0].tag) # {http://http://www.someaddress.com/someendpoint}FieldName But this gives me the actual element with text `Pickup.DateTime` and I am interested in getting its parent as shown above. **As a side note** : it took me almost an hour even to get this far because I find the lxml documentation to be very cumbersome. If anyone has a link with a good tutorial please post it at least as a comment. Thanks! Answer: I have found how to get it: p_time = xml_tree.xpath("//*[local-name()='TxnField']/*[text()='Pickup.DateTime']/./..")
Python and tile based game: limiting player movement speed Question: I've been putting together an isometric tile-based RPG using Python and the Pyglet library. I've run into the following problem, however: My player movement is based on positions on the three-dimensional array that consists of tiles. To limit movement speed, I use a global variable: TILE_TO_TILE_DELAY = 200. TILE_TO_TILE_DELAY is supposed to be the amount of time in milliseconds it takes for the player to move from one tile to another. During this time, they should not be able to make a new movement. The system I've been using is that I have a timer class, like this: import time def GetSystemTimeInMS(): #Return system time in milliseconds systime = round((time.clock()*1000), 0) return systime class Timer: def __init__(self,time): #time = time for which the timer runs self.time = time self.start_time = 0 self.stop_time = 0 def StartTimer(self): #start_time = time at which the timer was started self.start_time = GetSystemTimeInMS() self.stop_time = self.start_time + self.time def TimerIsStopped(self): if GetSystemTimeInMS() >= self.stop_time: return True else: return False The player class has a Timer object: self.MoveTimer = Timer(TILE_TO_TILE_DELAY) When the player presses the W-key, a function is called that checks for player.MoveTimer.TimerIsStopped(). If it returns True, it calls player.MoveTimer.StartTimer() and starts a new movement to the next position. In the even loop, the update(dt) function is set to happen 30 times a second: def update(dt): if player.MoveTimer.TimerIsStopped() player.UpdatePosition() pyglet.clock.schedule_interval(update, 1/30) Now, by my logic, update(dt) should check 30 times a second whether or not enough time has passed to warrant the player a new movement event. However, for some reason the player moves much faster at lower FPS. When my FPS is around 30, the player moves much faster than in areas where there are less tile sprites, pumping the framerate to 60. In areas where FPS is high, the player indeed by my measurements moves almost twice as slowly. I just cannot figure it out, nor did I find anything off the internet after a day of searching. Some help would be much appreciated. Edit: The code that starts the MoveTimer: def StartMovement(self, new_next_pos): self.RequestedMovement = False if self.GetCanMoveAgain(): self.SetNextPos(new_next_pos) self.SetMoveDirection(self.GetDirection()) #Start the timer for the movement self.MoveTimer.StartTimer() self.SetIsMoving(True) self.SetStartedMoving(True) self.SetWalking(True) self.SetNeedUpdate(True) self.MOVE_EVENT_HANDLER.CreateMoveEvent() GetCanMoveAgain() returns the value of player.can_move_again, which is set back to True by the UpdatePosition() in update(dt) Answer: Alright, I fixed the problem, how ever I'm still unsure about what caused it. Maybe it was some sort of a rounding error with milliseconds, having to do with more checks being made to the clock when the FPS is higher. Anyways, the solution: Instead of using the system clock, I decided to use Pyglet's own "dt" argument in their update functions: > The dt parameter gives the number of seconds (due to latency, load and timer > inprecision, this might be slightly more or less than the requested > interval). The new timer looks like this: class dtTimer: #A timer based on the dt-paremeter of the pyglet event loop def __init__(self,time): self.time = time self.time_passed = 0 def StartTimer(self): self.time_passed = 0 def UpdateTimer(self, dt): self.time_passed += dt*1000 def GetTime(self): return self.time def GetTimePassed(self): if not self.TimerIsStopped(): return self.time_passed else: return 0 def TimerIsStopped(self): if self.time_passed > self.time: return True else: return False When the loop attempts to update the player's position, if the TimerIsStopped returns false, dt is simply added to the Timer's self.time_passed. This has fixed the issue: the time it takes for the player to move is now constant. Thanks for looking at my issue.
NameError: name 'value_from_name' is not defined Question: I'm trying to use beautiful soup 4 to parse html for a login page and get tokens from that page. import requests from bs4 import BeautifulSoup session = requests.Session() login_page_html = BeautifulSoup(session.get('https://url.com', verify=False).text) lsd = value_from_name('something', login_page_html) def value_from_name(name, soup): return soup.find(name=name)['value'] I got this to work in another program, but I'm not sure why it's not working here. I'm new to python, guessing it's because I'm not passing the paramaters correctly? Answer: You are using the function before defining it. Define the function first, before using it. Example - import requests from bs4 import BeautifulSoup def value_from_name(name, soup): return soup.find(name=name)['value'] session = requests.Session() page_html = BeautifulSoup(session.get('https://url.com', verify=False).text) lsd = value_from_name('something', login_page_html)
python code to control GPIO at specific times Question: I want to build an irrigation automation system based on a Raspberry Pi. I have a script that generates a .CSV file based on the input parameters of the sprinkeling schedule (station no, time/station, use/not use rain sensor, etc.). The .CSV file looks like this: 1 00:00:00 00:29:59 110000 2 00:30:00 00:44:59 101000 3 00:45:00 01:14:59 100100 . . . . , where each line represent a time interval and the six digits binary number represent the GPIO pins state (1=valve on, 0=valve off). What is the best way to scan this .CSV file and trigger the valves based on the binary code? For now I have two options, but I'm sure there must be a better one: * Continuously loop a code at 1 second interval, read each line of the .CSV file until the interval mathes the current time and then trigger the correspondent ports * Read a .CSV file and generate a cron job for each line Either way, the solution has to be very simple and very reliable, the program is supposed to run during the entire summer season without mistake or error. Thanks! Answer: This program should do what you want it to. When it starts, your file is read into a schedule. The schedule is sorted, and the for loop runs through your schedule as needed. Once the schedule has been completed, your program will need to be run again. import operator import time def main(): schedule = [] with open('example.csv') as file: for line in file: _, start, _, state = line.split() data = time.strptime(start, '%H:%M:%S') schedule.append((time_to_seconds(data), int(state, 2))) schedule.sort(key=operator.itemgetter(0)) for start, state in schedule: current_time = time_to_seconds(time.localtime()) difference = start - current_time if difference >= 0: time.sleep(difference) set_gpio_pins(state) def time_to_seconds(data): return (data.tm_hour * 60 + data.tm_min) * 60 + data.tm_sec def set_gpio_pins(state): raise NotImplementedError() if __name__ == '__main__': main()
cx_freeze fails to include Cython .pyx module Question: I have a Python application to which I recently added a Cython module. Running it from script with pyximport works fine, but I also need an executable version which I build with cx_freeze. Trouble is, trying to build it gives me an executable that raises ImportError trying to import the .pyx module. I modified my setup.py like so to see if I could get it to compile the .pyx first so that cx_freeze could successfully pack it: from cx_Freeze import setup, Executable from Cython.Build import cythonize setup(name='projectname', version='0.0', description=' ', options={"build_exe": {"packages":["pygame","fx"]},'build_ext': {'compiler': 'mingw32'}}, ext_modules=cythonize("fx.pyx"), executables=[Executable('main.py',targetName="myproject.exe",base = "Win32GUI")], requires=['pygcurse','pyperclip','rsa','dill','numpy'] ) ... but then all that gives me is `No module named fx` within cx_freeze at build-time instead. How do I make this work? Answer: The solution was to have two separate calls to `setup()`; one to build `fx.pyx` with Cython, then one to pack the EXE with cx_freeze. Here's the modified setup.py: from cx_Freeze import Executable from cx_Freeze import setup as cx_setup from distutils.core import setup from Cython.Build import cythonize setup(options={'build_ext': {'compiler': 'mingw32'}}, ext_modules=cythonize("fx.pyx")) cx_setup(name='myproject', version='0.0', description='', options={"build_exe": {"packages":["pygame","fx"]}}, executables=[Executable('main.py',targetName="myproject.exe",base = "Win32GUI")], requires=['pygcurse','pyperclip','rsa','dill','numpy'] )
How to specify number of characters in each line in python? Question: I have fasta file that contains two gene sequences and what i want to is to remove the fasta header (line starting with ">"), concatenate the rest of the lines and output that sequence in length of 50 characters per line. I made some progress but got struck at the end. Here is my fasta sequence: >Potrs164783 AGGAAGTGTGAGATTGAAAAAACATTACTATTGAGGAATTTTTGACCAGATCAGAATTGAACCAACATGATGAAGGGGAT TGTTTGCCATCAGAATATGGCATGAAATTTCTCCCCTAGATCGGTTCAAGCTCCTGTAGGTTTGGAGTCCTTAGTGAGAA CTTTCTTAAGAGAATCTAATCTGGTCTGTTCCTCGTCATAAGTTAAAGAAAAACTTGAAACAAATAACAAGCATGCATAA >Potrs164784 TTACCCTCTACCAGCACCAATGCCTATGATCTTACAAAAATCCTTAATAAAAAGAAATCCAAAACCATTGTTACCATTCC GGAATTACATTCTGAGATAAAAACCCTCAAATCTGAATTACAATCCCTTAAACAAGCCCAACAAAAAGACTCTGCCATAC And the output that i want is something like this >conc AGGAAGTGTGAGATTGAAAAAACATTACTATTGAGGAATTTTTGACCAGA TCAGAATTGAACCAACATGATGAAGGGGATTGTTTGCCATCAGAATATGG CATGAAATTTCTCCCCTAGATCGGTTCAAGCTCCTGTAGGTTTGGAGTCC TTAGTGAGAACTTTCTTAAGAGAATCTAATCTGGTCTGTTCCTCGTCATA AGTTAAAGAAAAACTTGAAACAAATAACAAGCATGCATAAACCATATGGC ATTTTGCATCCATTTGTGCATTTCATTTAGTTTACTTGCATTCATTCAGG My script so far is final = list() with open("test.fa", 'r') as fh_in: for line in fh_in: line = line.strip() if not line.startswith(">"): final.append(line) final2 = "".join(final) with open("testconcat.fa", 'w') as fh_out: fh_out.write(">con") fh_out.write("\n") fh_out.write(final2) How can i make sure that i only write 50 characters in each line? Answer: You can use the inbuilt [textwrap](https://docs.python.org/2/library/textwrap.html) library import textwrap final2 = "".join(final) print '\n'.join(textwrap.wrap(final2, 50)
Python neural network accuracy - correct implementation? Question: I wrote a simple neural net/MLP and I'm getting some strange accuracy values and wanted to double check things. This is my intended setup: features matrix with 913 samples and 192 features (913,192). I'm classifying 2 outcomes, so my labels are binary and have shape (913,1). 1 hidden layer with 100 units (for now). All activations will use tanh and all losses use l2 regularization, optimized with SGD The code is below. It was writtin in python with the Keras framework (<http://keras.io/>) but my question isn't specific to Keras input_size = 192 hidden_size = 100 output_size = 1 lambda_reg = 0.01 learning_rate = 0.01 num_epochs = 100 batch_size = 10 model = Sequential() model.add(Dense(input_size, hidden_size, W_regularizer=l2(lambda_reg), init='uniform')) model.add(Activation('tanh')) model.add(Dropout(0.5)) model.add(Dense(hidden_size, output_size, W_regularizer=l2(lambda_reg), init='uniform')) model.add(Activation('tanh')) sgd = SGD(lr=learning_rate, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='mean_squared_error', optimizer=sgd, class_mode="binary") history = History() model.fit(features_all, labels_all, batch_size=batch_size, nb_epoch=num_epochs, show_accuracy=True, verbose=2, validation_split=0.2, callbacks=[history]) score = model.evaluate(features_all, labels_all, show_accuracy=True, verbose=1) I have 2 questions: This is my first time using Keras, so I want to double check that the code I wrote is actually correct for what I want it to do in terms of my choice of parameters and their values etc. Using the code above, I get training and test set accuracy hovering around 50-60%. Maybe I'm just using bad features, but I wanted to test to see what might be wrong, so I manually set all the labels and features to something that should be predictable: labels_all[:500] = 1 labels_all[500:] = 0 features_all[:500] = np.ones(192)*500 features_all[500:] = np.ones(192) So I set the first 500 samples to have a label of 1, everything else is labelled 0. I set all the features manually to 500 for each of the first 500 samples, and all other features (for the rest of the samples) get a 1 When I run this, I get training accuracy of around 65%, and validation accuracy around 0%. I was expecting both accuracies to be extremely high/almost perfect - is this incorrect? My thinking was that the features with extremely high values all have the same label (1), while the features with low values get a 0 label Mostly I'm just wondering if my code/model is incorrect or whether my logic is wrong thanks! Answer: I don't know that library, so I can't tell you if this is correctly implemented, but it looks legit. I think your problem lies with activation function - tanh(500)=1 and tanh(1)=0.76. This difference seem too small for me. Try using -1 instead of 500 for testing purposes and normalize your real data to something about [-2, 2]. If you need full real numbers range, try using linear activation function. If you only care about positive half on real numbers, I propose softplus or ReLU. I've checked and all those functions are provided with Keras. You can try thresholding your output too - answer 0.75 when expecting 1 and 0.25 when expecting 0 are valid, but may impact you accuracy. Also, try tweaking your parameters. I can propose (basing on my own experience) that you'd use: * learning rate = 0.1 * lambda in L2 = 0.2 * number of epochs = 250 and bigger * batch size around 20-30 * momentum = 0.1 * learning rate decay about 10e-2 or 10e-3 I'd say that learning rate, number of epochs, momentum and lambda are the most important factors here - in order from most to least important. PS. I've just spotted that you're initializing your weights uniformly (is that even a word? I'm not a native speaker...). I can't tell you why, but my intuition tells me that this is a bad idea. I'd go with random initial weights.
ValueError: negative number cannot be raised to a fractional power in iterable list - Python Question: We have a list of 10 points of coord. x and y as follow: NOTE: Here we iterate through the lists of x,y and br without using numpy.array because in the far future, I will replicate this into Fortran77. x = [7., -6., 7., -7., 8., 9., 5., 4., -5., 0.] for i, x[i] in enumerate(x): print 'The values of x =', x[i] y = [3., 6., 3., 9., 1., 9., -2., 0., 3., 7.] for i, y[i] in enumerate(y): print 'The values of y =', y[i] br = [1., 2., 8., 0., 7., 9., 6., 9., 7., 4.] for i, br[i] in enumerate(br): print 'brightness = ',br[i] NOTE: rad_cut is the radius of the circle (r^2 = x^2 + y^2) rad_cut = input("Please provide a value of rad_cut: ") br_total = 0 for i in xrange(0,10): if x[i]**0.5 + y[i]**0.5 < rad_cut: br_total += br[i] print 'The total brightness = ', br_total The issue I have having is as follows: in <module> if x[i]**0.5 + y[i]**0.5 < rad_cut: ValueError: negative number cannot be raised to a fractional power I would appreciate if anyone can lend me a hand to resolve this issue. I have tried to use complex numbers because of the negative number in the iterable lists `x[i+0j]**0.5 + y[i+0j]**0.5 < rad_cut:` but it didn't work. Answer: As noted in the comments you need to square those x & y values, rather than taking their square roots. Here's a more Pythonic way to write your program. This code will work on Python 2.6 and up, it will also work properly on Python 3. The main change is that it uses a [generator expression](https://docs.python.org/2/tutorial/classes.html#generator- expressions) inside the `sum()` function to add the appropriate `br` values. #!/usr/bin/env python from __future__ import print_function x = [7., -6., 7., -7., 8., 9., 5., 4., -5., 0.] y = [3., 6., 3., 9., 1., 9., -2., 0., 3., 7.] br = [1., 2., 8., 0., 7., 9., 6., 9., 7., 4.] print(' x y br') for i, (xi, yi, bri) in enumerate(zip(x, y, br)): print('{0}: {1:4.1f} {2:4.1f} {3:4.1f}'.format(i, xi, yi, bri)) rad_cut = input("Please provide a value of rad_cut: ") rad_cut = float(rad_cut) rad_sq = rad_cut ** 2 br_total = sum(bri for xi, yi, bri in zip(x, y, br) if xi**2 + yi**2 < rad_sq) print('The total brightness = {0:.1f}'.format(br_total)) **typical output** x y br 0: 7.0 3.0 1.0 1: -6.0 6.0 2.0 2: 7.0 3.0 8.0 3: -7.0 9.0 0.0 4: 8.0 1.0 7.0 5: 9.0 9.0 9.0 6: 5.0 -2.0 6.0 7: 4.0 0.0 9.0 8: -5.0 3.0 7.0 9: 0.0 7.0 4.0 Please provide a value of rad_cut: 10 The total brightness = 44.0 Note: It's better in Python 2 to use `raw_input()` rather than `input()`, since the Python 2 version of `input()` uses the potentially [dangerous `eval()` function](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) on the entered data; the Python 3 version of `input()` is identical to Python 2's `raw_input()`.
Python's SimpleHTTPServer started in a thread won't close the port Question: I have the following code: import os from ghost import Ghost import urlparse, urllib import SimpleHTTPServer import SocketServer import sys, traceback from threading import Thread, Event from time import sleep please_die = Event() # this is my enemy httpd = None PORT = 8001 address = 'http://localhost:'+str(PORT)+'/' search_dir = './category' def main(): """ basic run script routine, FIXME: is supossed to exits gracefully """ thread = Thread(target = simpleServe) try: thread.start() run() except KeyboardInterrupt: print "Shutdown requested" except Exception: traceback.print_exc(file=sys.stdout) shutdown() sys.exit(0) def shutdown(): global httpd global please_die print "Shutting down" # A try - except for the shutdown routine try: please_die.wait() # how do you do? httpd.shutdown() # Please! I whant to run you multiple times. print "Have you died?" except Exception: traceback.print_exc(file=sys.stdout) def path2url(path): """ constructs an url from a relative path / concatenates the global address variable with the path given """ global address return urlparse.urljoin(address, urllib.pathname2url(path)) def simpleServe(): global httpd, PORT please_die.set() # Attaching the event to this thread # Start the service Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), Handler) print "serving at port", PORT # And loop infinetly in the hope that I can stop you later httpd.serve_forever() def run(): global search_dir; ghost = Ghost() # the webkit facade with ghost.start() as session: session.set_viewport_size(2560, 1600) # "retina" size for directory, subdirectories, files in os.walk(search_dir): for file in files: path = os.path.join(directory, file) urlPath = path2url(path) process(session, urlPath); def process(session, urlPath): page, resources = session.open(urlPath) assert page.http_status == 200 # ... other asserts here if __name__ == '__main__': main() The idea is to make a script that starts a "simple http server", do some requests on it and then exit. First time it runs without any problems: ... 127.0.0.1 - - [31/Jul/2015 13:16:17] "GET /category/52003.html HTTP/1.1" 200 - 127.0.0.1 - - [31/Jul/2015 13:16:17] "GET /category/52003.html HTTP/1.1" 200 - 127.0.0.1 - - [31/Jul/2015 13:16:17] "GET /category/52003.html HTTP/1.1" 200 - 127.0.0.1 - - [31/Jul/2015 13:16:17] "GET /static/img/glyphicons-halflings.png HTTP/1.1" 200 - Shutting down Have you died? Launching it the second time crashes saying that the: > Address already in use Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 763, in run self.__target(*self.__args, **self.__kwargs) File "download-images.py", line 51, in simpleServe httpd = SocketServer.TCPServer(("", PORT), Handler) File "/usr/lib/python2.7/SocketServer.py", line 420, in __init__ self.server_bind() File "/usr/lib/python2.7/SocketServer.py", line 434, in server_bind self.socket.bind(self.server_address) File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) error: [Errno 98] Address already in use If I kill all python processes than the script runs again, and because of that I'm assuming that I used the thread wrong, but I cannot find where. ## Update Forgot to mention that, my OS is : $ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 15.04 Release: 15.04 Codename: vivid The python that I'm using is : $ python --version Python 2.7.9 $ netstat -putelan | grep 8001 prints : $ netstat -putelan | grep 8001 (Not all processes could be identified, non-owned process info cp 0 0 127.0.0.1:34691 127.0.0.1:8001 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:8001 127.0.0.1:34866 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:34798 127.0.0.1:8001 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:8001 127.0.0.1:34588 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:34647 127.0.0.1:8001 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:34915 127.0.0.1:8001 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:34674 127.0.0.1:8001 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:34451 127.0.0.1:8001 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:8001 127.0.0.1:34930 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:8001 127.0.0.1:34606 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:34505 127.0.0.1:8001 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:34717 127.0.0.1:8001 TIME_WAIT 0 0 - tcp 0 0 127.0.0.1:8001 127.0.0.1:34670 0 0 127.0.0.1:8001 127.0.0.1:34626 ... I can't post the whole sequence (due to the post limits of stackoverflow). The rest is the same with 34*** port mixed with 8001 port in an uniform sequence. Answer: As @LFJ say, this is probably due to the `allow_reuse_address` attribute of the `TCPServer`. httpd = SocketServer.TCPServer(("", PORT), Handler, bind_and_activate=False) httpd.allow_reuse_address = True try: httpd.server_bind() httpd.server_activate() except: httpd.server_close() raise Equivalent code : SocketServer.TCPServer.allow_reuse_address = True https = SocketServer.TCPServer(("", PORT), Handler) Let's explain a bit why. When you enable `TCPServer.allow_reuse_address`, it adds an option on the socket : class TCPServer: [...] def server_bind(self): if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) [...] What is `socket.SO_REUSEADDR` ? > > This socket option tells the kernel that even if this port is busy (in > the TIME_WAIT state), go ahead and reuse it anyway. If it is busy, > but with another state, you will still get an address already in use > error. It is useful if your server has been shut down, and then > restarted right away while sockets are still active on its port. You > should be aware that if any unexpected data comes in, it may confuse > your server, but while this is possible, it is not likely. > In fact, it allows the reuse of your socket socket binding address. If another process try to bind while the socket is not listening, the process will be allowed to use this socket binding address. The reason you need to enable that is because you don't shutdown properly your `TCPServer`. In order to close it properly, you must run `shutdown` method, which will close the thread launched by `server_forever` and then close the socket properly by calling the `server_close` method. def shutdown(): global httpd global please_die print "Shutting down" try: please_die.wait() # how do you do? httpd.shutdown() # Stop the serve_forever httpd.server_close() # Close also the socket. except Exception: traceback.print_exc(file=sys.stdout)
Using import our script with Python Question: I don't know how explain what I want do so I think with code example you can understand. y.py y = 0 import printy printy.py import y print y NameError: name 'y' is not defined When I call scripts with import works perfect but I want to know how I can share variables. y.py import printy printy.py y = 0 print y result = 0 Answer: I don't know which is which file, (assuming each code block is a different file) it should work, and share `variables` if `import`ing them works. Also, I would write it like this: file y.py: from printy import * y = 0 file printy.py: from y import * print y Also, both files have to already exist at time of running, and they have to saved into the same folder. EDIT: If `result = 0` is the output, then everything is working fine. Also, if this doesn't work, I'd do `printy.print(y)`
Numpy array mean function did not exclude masked element in mean computation Question: I am new in python programming, please forgive me if my question is too basic. But I am trying to use masked_array to calculate the mean of three arrays to produce a third array without using the elements with values less than zero. Using these steps: import numpy as np from numpy.ma import masked_array d=[] a = np.array([[-2,-3,-4,-6],[5,2,6,1],[9,3,2,4],[3,1,1,2]]) b = np.array([[3,4,2,4],[5,2,6,1],[9,3,2,4],[0.3,12,1,3]]) c = np.array([[2,3,4,5],[7,0,1,5],[10,9,2,3],[1.5,2.01,2,0.2]]) mask = (a <= 0).astype(int) a = masked_array(a,mask) d.append(a) d.append(b) d.append(c) result = np.array(d).mean(axis=0) print result [[ 1. 1.33333333 0.66666667 1. ] [ 5.66666667 1.33333333 4.33333333 2.33333333] [ 9.33333333 5. 2. 3.66666667] [ 1.6 5.00333333 1.33333333 1.73333333]] I thought that (from documentation that) if one uses the numpy array mean function on arrays with masked values, that it will not consider them (the masked values) in computing the mean. I expected the result to be [[ 2.5 3.5 3. 4.5 ] [ 5.66666667 1.33333333 4.33333333 2.33333333] [ 9.33333333 5. 2. 3.66666667] [ 1.6 5.00333333 1.33333333 1.73333333]] Please, does anyone have some tips on how I can use the numpy.ma.masked_array to archive this? Answer: The problem is that `np.array(d)` does not create a masked array. The mask in `a` is lost when the arrays in the list `d` are assembled into a bigger (nonmasked) array. One way to fix it is to replace this: result = np.array(d).mean(axis=0) with result = masked_array(d).mean(axis=0) E.g.: In [27]: result = masked_array(d).mean(axis=0) In [28]: result Out[28]: masked_array(data = [[2.5 3.5 3.0 4.5] [5.666666666666667 1.3333333333333333 4.333333333333333 2.3333333333333335] [9.333333333333334 5.0 2.0 3.6666666666666665] [1.5999999999999999 5.003333333333333 1.3333333333333333 1.7333333333333334]], mask = [[False False False False] [False False False False] [False False False False] [False False False False]], fill_value = 1e+20)
Python - How to read previous lines while reading csv file? Question: I want to read rows in excel table but when I want, during reading process, I would like to stop reading forward and I want to read previous lines (backward reading)? How can I go previous rows again? import csv file = open('ff.csv2', 'rb') reader = csv.reader(file) for row in reader: print row Answer: You could always store the lines in a list and then access each line using the index. import csv file = open('ff.csv2', 'r') def somereason(line): # some logic to decide if stop reading by returning True return False # keep on reading for row in csv.reader(file): if somereason(line): break lines.append(line) # visit the stored lines in reverse for row in reversed(lines): print(row)
python.net import clr throws invalid pointer error Question: When i am trying to import clr in my python code i get the following error: *** Error in `python': free(): invalid pointer: 0xb0f1a120 *** Stacktrace: at <unknown> <0xffffffff> at (wrapper managed-to-native) Python.Runtime.Runtime.Py_Initialize () <0xffffffff> at Python.Runtime.Runtime.Initialize () <0x00023> at Python.Runtime.PythonEngine.Initialize () <0x00047> at Python.Runtime.PythonEngine.InitExt () <0x0000b> at (wrapper runtime-invoke) object.runtime_invoke_void (object,intptr,intptr,intptr) <0xffffffff> Native stacktrace: /usr/lib/libmonoboehm-2.0.so.1(+0xcb5f4) [0xb1b5e5f4] [0xb7745d14] [0xb7745d1e] /lib/i386-linux-gnu/libc.so.6(gsignal+0x47) [0xb7592607] /lib/i386-linux-gnu/libc.so.6(abort+0x143) [0xb7595a33] /lib/i386-linux-gnu/libc.so.6(+0x68e53) [0xb75cce53] /lib/i386-linux-gnu/libc.so.6(+0x7333a) [0xb75d733a] /lib/i386-linux-gnu/libc.so.6(+0x73fad) [0xb75d7fad] /usr/lib/i386-linux-gnu/libpython2.7.so(PyString_InternInPlace+0x97) [0xb0b3a157] /usr/lib/i386-linux-gnu/libpython2.7.so(PyString_InternFromString+0x2f) [0xb0ad78ef] /usr/lib/i386-linux-gnu/libpython2.7.so(PyType_Ready+0xb50) [0xb0b356e0] /usr/lib/i386-linux-gnu/libpython2.7.so(_Py_ReadyTypes+0xcd) [0xb0b3d47d] /usr/lib/i386-linux-gnu/libpython2.7.so(Py_InitializeEx+0x6d) [0xb0b5d5dd] /usr/lib/i386-linux-gnu/libpython2.7.so(Py_Initialize+0x1b) [0xb0b5df7b] [0xb481553c] [0xb4814f2c] [0xb480af98] [0xb480ae84] [0xb480af0d] /usr/lib/libmonoboehm-2.0.so.1(+0x29723) [0xb1abc723] Debug info from gdb: Could not attach to process. If your uid matches the uid of the target process, check the setting of /proc/sys/kernel/yama/ptrace_scope, or try again as the root user. For more details, see /etc/sysctl.d/10-ptrace.conf ptrace: Operation not permitted. No threads. ================================================================= Got a SIGABRT while executing native code. This usually indicates a fatal error in the mono runtime or one of the native libraries used by your application. ================================================================= I found a reference to a similar problem (<https://mail.python.org/pipermail/pythondotnet/2014-October/001598.html>) but i can not figure out how to use the npython binary for example and i do not wish to rebuild python with shared-library enabled. Any hints or help will be greatly appreciated. Answer: After some painful trials i achieved using `import clr` successfully in my code. First i needed somehow to use the right binaries and in order to achieve that i used the latest development source from git of the pythonnet/pythonnet package. You can try: `$ sudo pip install --pre pythonnet` that downloads and installs the latest development source. But keep in mind there are some perquisites so i am attaching the travis build details system_info Build language: python Operating System: Ubuntu 12.04 LTS $ python --version Python 2.7.9 $ pip --version pip 6.0.7 from /home/travis/virtualenv/python2.7.9/lib/python2.7/site-packages (python 2.7) $ sudo apt-get install software-properties-common $ sudo add-apt-repository -y "deb http://archive.ubuntu.com/ubuntu/ trusty main universe" $ sudo apt-get -qq install mono-devel mono-gmcs mono-xbuild nunit-console $ sudo mozroots --import --machine --sync $ yes | sudo certmgr -ssl -m https://go.microsoft.com $ yes | sudo certmgr -ssl -m https://nugetgallery.blob.core.windows.net $ yes | sudo certmgr -ssl -m https://nuget.org $ pip install six Now normally installing pythonnet with pip should execute successfully and you can try calling import clr in your python code. In my case personally it failed even in this scenario although it was installing without errors. The reason was that although my python was compiled without --enable-shared, running $ python -c 'import sys; from distutils.sysconfig import get_config_var; print(get_config_var("Py_ENABLE_SHARED"))' returned 1 although it should return 0. So i downloaded the latest dev-source from git <https://github.com/pythonnet/pythonnet> and after putting it in the right folder i edited setup.py setting the variable that was checking for the shared libraries to 0, after that executing $ sudo python setup.py install the script installed successfully without error and i could use import clr in my python scripts. To make sure everything runs correctly you can run: $ python src/tests/runtests.py
How to count elapsed time on Python Question: I have the following code: def base(nomor) day = localtime.tm_wday time = localtime.tm_hour no = str(nomor) dosen = cek_dosen(no) if dosen == 'null': no_dosen() elif dosen != 'null': ada_dosen() matkul = cek_jadwal(day,time,dosen) if matkul == 'null': no_jadwal() elif matkul != 'null': ada_jadwal() pertemuan = cek_pertemuan(matkul) print pertemuan if pertemuan > 1: cek_before(pertemuan) filename = ''.join([dosen, matkul, str(pertemuan), ".pptx"]) else: filename = ''.join([dosen, matkul, str(pertemuan), ".pptx"]) grabfile(filename) os.system(''.join(["loimpress ",filename])) pertemuan = pertemuan + 1 update_pertemuan(pertemuan,matkul) mulai() if __name__ == '__main__': mulai() while True: data = port.read() count += 1 if count == 1: if str(data) != start: nomor = '' count = 0 elif 2 <= count <= 13: nomor = nomor + str(data) elif count == 16 and str(data) == stop: base(nomor) nomor = '' count = 0 I want to count time elapse from after `data = port.read()` until after `grabfile(filename)`. I've used `start = time.time()` after `data = port.read` and `end = time.time()` after `grabfile`, `time = end - start`, but it stuck after `data = port.read()` so I use Ctrl + C to stop that. If I put `start = time.time()` after `no = str(nomor)`, I get `Attribute Error : 'int' object has no attribute 'time'`. How do I count the elapsed time? Answer: from time import clock start = clock() ... print "Time taken = %.5f" % (clock() - start)
Python vs perl sort performance Question: **_Solution_** This solved all issues with my Perl code (plus extra implementation code.... :-) ) In conlusion both Perl and Python are equally awesome. use WWW::Curl::Easy; Thanks to ALL who responded, very much appreciated. **_Edit_** It appears that the Perl code I am using is spending the majority of its time performing the http get, for example: my $start_time = gettimeofday; $request = HTTP::Request->new('GET', 'http://localhost:8080/data.json'); $response = $ua->request($request); $page = $response->content; my $end_time = gettimeofday; print "Time taken @{[ $end_time - $start_time ]} seconds.\n"; The result is: Time taken 74.2324419021606 seconds. My python code in comparison: start = time.time() r = requests.get('http://localhost:8080/data.json', timeout=120, stream=False) maxsize = 100000000 content = '' for chunk in r.iter_content(2048): content += chunk if len(content) > maxsize: r.close() raise ValueError('Response too large') end = time.time() timetaken = end-start print timetaken The result is: 20.3471381664 In both cases the sort times are sub second. So first of all I apologise for the misleading question, and it is another lesson for me to never ever make assumptions.... :-) I'm not sure what is the best thing to do with this question now. Perhaps someone can propose a better way of performing the request in perl? **_End of edit_** This is just a quick question regarding sort performance differences in Perl vs Python. This is not a question about which language is better/faster etc, for the record, I first wrote this in perl, noticed the time the sort was taking, and then tried to write the same thing in python to see how fast it would be. I simply want to know, **how can I make the perl code perform as fast as the python code?** Lets say we have the following json: ["3434343424335": { "key1": 2322, "key2": 88232, "key3": 83844, "key4": 444454, "key5": 34343543, "key6": 2323232 }, "78237236343434": { "key1": 23676722, "key2": 856568232, "key3": 838723244, "key4": 4434544454, "key5": 3432323543, "key6": 2323232 } ] Lets say we have a list of around 30k-40k records which we want to sort by one of the sub keys. We then want to build a new array of records ordered by the sub key. Perl - Takes around 27 seconds my @list; $decoded = decode_json($page); foreach my $id (sort {$decoded->{$b}->{key5} <=> $decoded->{$a}->{key5}} keys %{$decoded}) { push(@list,{"key"=>$id,"key1"=>$decoded->{$id}{key1}...etc)); } Python - Takes around 6 seconds list = [] data = json.loads(content) data2 = sorted(data, key = lambda x: data[x]['key5'], reverse=True) for key in data2: tmp= {'id':key,'key1':data[key]['key1'],etc.....} list.append(tmp) For the perl code, I have tried using the following tweaks: use sort '_quicksort'; # use a quicksort algorithm use sort '_mergesort'; # use a mergesort algorithm Answer: Your benchmark is flawed, you're benchmarking multiple variables, not one. It is not just sorting data, but it is also doing JSON decoding, and creating strings, and appending to an array. You can't know how much time is spent sorting and how much is spent doing everything else. The matter is made worse in that there are several different JSON implementations in Perl each with their own different performance characteristics. Change the underlying JSON library and the benchmark will change again. If you want to benchmark sort, you'll have to change your benchmark code to eliminate the cost of loading your test data from the benchmark, JSON or not. Perl and Python have their own internal benchmarking libraries that can benchmark individual functions, but their instrumentation can make them perform far less well than they would in the real world. The performance drag from each benchmarking implementation will be different and might introduce a false bias. These benchmarking libraries are more useful for comparing two functions in the same program. For comparing between languages, keep it simple. Simplest thing to do to get an accurate benchmark is to time them within the program using the wall clock. # The current time to the microsecond. use Time::HiRes qw(gettimeofday); my @list; my $decoded = decode_json($page); my $start_time = gettimeofday; foreach my $id (sort {$decoded->{$b}->{key5} <=> $decoded->{$a}->{key5}} keys %{$decoded}) { push(@list,{"key"=>$id,"key1"=>$decoded->{$id}{key1}...etc)); } my $end_time = gettimeofday; print "sort and append took @{[ $end_time - $start_time ]} seconds\n"; (I leave the Python version as an exercise) From here you can improve your technique. You can use CPU seconds instead of wall clock. The array append and cost of creating the string are still involved in the benchmark, they can be eliminated so you're just benchmarking sort. And so on. Additionally, you can use [a profiler](https://metacpan.org/pod/Devel::NYTProf) to find out where your programs are spending their time. These have the same raw performance caveats as benchmarking libraries, the results are only useful to find out what percentage of its time a program is using where, but it will prove useful to quickly see if your benchmark has unexpected drag. The important thing is to benchmark what you think you're benchmarking.
Locating max value in a list Question: I'm very new to Python programming and I've been tasked by an online friend to write code to solve the following problem: 'imagine a board game and you have to roll 2 dices.Write a program to roll the dices 100 times and find out which value (of both dices) appears most' My attempt below kind of works in the sense that I'm able to ascertain the max frequency of two dice faces added together but not the actual dice thrown.(e.g. the total '9' was the most frequently thrown). I'm sure there are plenty of ways of accomplishing the above so do excuse my very first attempt at coding! import random results = [] freq_2 = 0 freq_3 = 0 freq_4 = 0 freq_5 = 0 freq_6 = 0 freq_7 = 0 freq_8 = 0 freq_9 = 0 freq_10 = 0 freq_11 = 0 freq_12 = 0 for i in range(100): face1 = random.randrange(1,7) face2 = random.randrange(1,7) value = face1 + face2 if value == 2: freq_2 += 1 if value == 3: freq_3 += 1 if value == 4: freq_4 += 1 if value == 5: freq_5 += 1 if value == 6: freq_6 += 1 if value == 7: freq_7 += 1 if value == 8: freq_8 += 1 if value == 9: freq_9 += 1 if value == 10: freq_10 += 1 if value == 11: freq_11 += 1 if value == 12: freq_12 += 1 results.append(freq_2) results.append(freq_3) results.append(freq_4) results.append(freq_5) results.append(freq_6) results.append(freq_7) results.append(freq_8) results.append(freq_9) results.append(freq_10) results.append(freq_11) results.append(freq_12) print max(results) print freq_2, freq_3, freq_4, freq_5, freq_6, freq_7, freq_8, freq_9, freq_10, freq_11, freq_12 Answer: [`collections`](https://docs.python.org/2/library/collections.html#collections.Counter) provides `Counter` which makes this task easy: from random import choice from collections import Counter dice = range(1,7) freq = Counter([choice(dice) + choice(dice) for i in range(100)]) print freq print freq.most_common(1)
save the user input to existing text file everytime running the script python? Question: I'm trying to save the user input into one text file(I want to keep the record for a month). But I'm not sure how to keep the old user input because every time I re-run the script new user input is automatically written on old-user input. Is there any way to keep all the records regardless of running the script? This is a simple example. When I run the script once, I get the following result in output textile, 2.5 2015-07-30 7 2015-07-30 1 2015-07-30 4 2015-07-30 5 2015-07-30 8.9 2015-07-30 but when I re-run the script, the above data is all being written by new user input. How can I make it so that my output text file maintains all the record regardless of running the script? This is my desired look of my output text file 2.5 2015-07-30 7 2015-07-30 1 2015-07-30 4 2015-07-30 5 2015-07-30 8.9 2015-07-30 4 2015-07-31 7 2015-07-31 2.4 2015-07-31 5 2015-07-31 1 2015-07-31 and this is the code that I've tried so far. import datetime with open("output.txt", 'w') as textfile: while True: input = raw_input("Enter: ") if input == 'done': break textfile.write(input+'\t'+ datetime.datetime.now().strftime("20%y-%m-%d")+'\n') Answer: You need to [open the file in append mode](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing- files) to preserve the data already in the file. `'a'` opens the file for appending. `'a+'` opens the file for appending and creates the file if it does not exist. import datetime with open("output.txt", 'a+') as textfile: while True: input = raw_input("Enter: ") if input == 'done': break textfile.write(input+'\t'+ datetime.datetime.now().strftime("20%y-%m-%d")+'\n')
Python-Pygame Level Select Pages Question: I'm trying to create a typing game. You know that point in many apps,where there is a level select, and there are several pages. Yeah, I'm trying to do that. Every time I select the button to move to the next page of level selections, it heads to the last page, and then starts to do some sort of recursion. Help! Here is the code, feel free to paste it in to your computer, and see whats wrong. (I am aware that it's messy right now the main problem is within the section that will be within the lines) Thanks in advance! import pygame pygame.init() display_width = 800 display_height = 600 white = (255,255,255) black = (0,0,0) red = (175,0,0) green = (34,177,76) yellow = (175,175,0) blue = (30,144,255) light_green = (0,255,0) light_red = (255,0,0) light_yellow = (255,255,0) light_blue = (0,191,255) smallFont = pygame.font.SysFont("Comicsansms", 20) medFont = pygame.font.SysFont("Comicsansms", 45) largeFont = pygame.font.SysFont("Comicsansms", 55) gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption("Typing Game") def text_objects(text, color, size): if size == "small": textSurf = smallFont.render(text, True, color) elif size == "medium": textSurf = medFont.render(text, True, color) elif size == "large": textSurf = largeFont.render(text, True, color) return textSurf, textSurf.get_rect() def messageToScreen(msg, color, y_displace = 0, size = "small"): textSurface, textRect = text_objects(msg, color, size) textRect.center = (display_width/2), (display_height/2) + y_displace gameDisplay.blit(textSurface, textRect) def text_to_button(msg, color, buttonX, buttonY, buttonWidth, buttonHeight, size = "small"): textSurface, textRect = text_objects(msg, color, size) textRect.center = ((buttonX + (buttonWidth/2), buttonY + (buttonHeight/2))) gameDisplay.blit(textSurface, textRect) -------------------------------------------------------------------------------------------------------------------- def button(text, x, y, width, height, inactiveColor , activeColor,textColor = black, action = None): cur = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x+ width > cur[0] > x and y + height > cur[1] > y: pygame.draw.rect(gameDisplay, activeColor, (x,y,width,height)) if click[0] == 1 and action != None: if action == "quit": pygame.quit() quit() if action == "directions": gameDisplay.fill(white) pygame.display.update() directions() if action == "lvl": gameDisplay.fill(white) pygame.display.update() levelScreen() if action == "clear": gameDisplay.fill(white) pygame.display.update() clearData() if action == "main": gameDisplay.fill(white) pygame.display.update() startScreen() if action == "page2": gameDisplay.fill(white) pygame.display.update() page2() if action == "page3": gameDisplay.fill(white) pygame.display.update() page3() else: pygame.draw.rect(gameDisplay, inactiveColor, (x,y,width,height)) text_to_button(text,textColor,x,y,width,height) def clearData(): pass def levelScreen(): level = True while level: global levelnumber levelnumber = 1 gameDisplay.fill(white) messageToScreen("Level Select", green, -200, size = "large") button("Back",150, 500,150,50, light_yellow, yellow, action = "main") button("Quit",350,500,150,50,light_red,red,action = "quit") button("Next",550,500,150,50,light_yellow,yellow,action = "page2") pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: level = False pygame.quit() quit() def page2(): level = True print("page2") while level: gameDisplay.fill(white) messageToScreen("Level Select", green, -200, size = "large") button("Previous",150, 500,150,50, light_yellow, yellow, action = "lvl") button("Quit",350,500,150,50,light_red,red,action = "quit") button("Next",550,500,150,50,light_yellow,yellow,action = "page3") pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: level = False pygame.quit() quit() def page3(): level = True print("page3") while level: gameDisplay.fill(white) messageToScreen("Level Select 2", green, -200, size = "large") button("Previous",150, 500,150,50, light_yellow, yellow, action = "lvl") button("Quit",350,500,150,50,light_red,red,action = "quit") button("Next",550,500,150,50,light_yellow,yellow,action = "main") pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: level = False pygame.quit() quit() ---------------------------------------------------------------------------------------------------------------------------- def directions(): directions = True while directions: gameDisplay.fill(white) messageToScreen("Directions", green, -200, size = "large") messageToScreen("Click The Buttons To Navigate",black,-100) messageToScreen("Select Level Buttons To Start The Level",black,-60) messageToScreen("Complete A Level By Typing All The Words In The Level",black,-20) messageToScreen("Each Level Is Timed And Gets Harder And Harder",black,20) messageToScreen("Have Fun!!!",blue,80, size = "medium") button("Back",150, 500,150,50, light_yellow, yellow, action = "main") button("Quit",550,500,150,50,light_red,red,action = "quit") pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: directions = False pygame.quit() quit() def startScreen(): game = True while game: gameDisplay.fill(white) messageToScreen("Welcome To The Typing Game", green, -100, size = "large") button("Lvl Select",150, 300,150,50, light_green, green, action = "lvl") button("Directions",350, 300,150,50, light_yellow, yellow, action = "directions") button("Quit Game",550, 300,150,50, light_red, red, action = "quit") button("Clear Data", 350, 400,150,50, light_blue, blue, action = "clear") pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: game = False pygame.quit() quit() startScreen() Answer: This seems to be a common issue that is going around. I answered a similar question [here](http://stackoverflow.com/a/31718675/5168325). Is the button code your own? It might be good for someone to let the original code owner know about these questions so they can change their code or show some other usage examples. On your level select screen you are drawing a next button. When I click that button it is generating a click event and Pygame starts to draw the next screen. The new screen has a next button in the exact same position. There is code in the button creation that checks if a button is being clicked. I am talking about these 2 lines in the button function: click = pygame.mouse.get_pressed() ... if click[0] == 1 and action != None: Since that is being checked while the button is being created it assumes that you have clicked the new button and it goes to the next screen. That is the answer to the question to that you asked. Here are my suggestions for the next step: * Move the checking of a button being clicked to the main loop and not in the button creation code. The main loop of your code starts on 180 * Add some code (like I suggested in the answer of the link provided) that will make sure a user releases their click before that code fires. I hope this helps.
PL/Python with Anaconda Question: I've got Anaconda installed on a Ubuntu and would like to use some of it's modules in PL/Python. However, every time I call scipy, it errors with _ImportError: No module_ named scipy.stats. How do I get the Anaconda to work with PL/Python? UPDATED: Below is the code & the error CREATE OR REPLACE FUNCTION hdi_bars( numerator integer, denominator integer) RETURNS SETOF double precision[] AS $BODY$ from scipy.stats import beta import numpy as np from scipy.stats import beta import numpy as np $BODY$ LANGUAGE plpythonu VOLATILE COST 100 ROWS 1000; ALTER FUNCTION hdi_bars(integer, integer) OWNER TO postgres; ERROR: ERROR: ImportError: No module named scipy.stats CONTEXT: Traceback (most recent call last): PL/Python function "hdi_bars", line 5, in from scipy.stats import beta PL/Python function "hdi_bars" ********** Error ********** ERROR: ImportError: No module named scipy.stats SQL state: XX000 Context: Traceback (most recent call last): PL/Python function "hdi_bars", line 5, in from scipy.stats import beta PL/Python function "hdi_bars" Answer: Based on the [Postgres installation/configuration docs](http://www.postgresql.org/docs/9.0/static/install-procedure.html), there is an environment variable `PYTHON` which can be set to the full path of the executable for Python that you want. Otherwise, the default `--with-python` behavior will look for the system Python, most likely at `/usr/bin/python` or similar standard location for other operating systems. [This question and answer](http://stackoverflow.com/questions/5921664/how-to- change-python-version-used-by-plpython-on-mac-osx) seems to confirm that to alter it, you need to rebuild Postgres from source.
YAML with Python using PyYAML Question: I am trying to follow these two examples: [Parsing a YAML file in Python, and accessing the data?](http://stackoverflow.com/questions/8127686/parsing-a-yaml-file-in- python-and-accessing-the-data) [YAML parsing and Python?](http://stackoverflow.com/questions/6866600/yaml- parsing-and-python) but for some reason I keep getting the following error message: Traceback (most recent call last): File "test.py", line 3, in <module> doc = yaml.load(f) File "/usr/local/lib/python2.7/dist-packages/yaml/__init__.py", line 71, in load return loader.get_single_data() File "/usr/local/lib/python2.7/dist-packages/yaml/constructor.py", line 37, in get_single_data node = self.get_single_node() File "/usr/local/lib/python2.7/dist-packages/yaml/composer.py", line 36, in get_single_node document = self.compose_document() File "/usr/local/lib/python2.7/dist-packages/yaml/composer.py", line 55, in compose_document node = self.compose_node(None, None) File "/usr/local/lib/python2.7/dist-packages/yaml/composer.py", line 84, in compose_node node = self.compose_mapping_node(anchor) File "/usr/local/lib/python2.7/dist-packages/yaml/composer.py", line 133, in compose_mapping_node item_value = self.compose_node(node, item_key) File "/usr/local/lib/python2.7/dist-packages/yaml/composer.py", line 64, in compose_node if self.check_event(AliasEvent): File "/usr/local/lib/python2.7/dist-packages/yaml/parser.py", line 98, in check_event self.current_event = self.state() File "/usr/local/lib/python2.7/dist-packages/yaml/parser.py", line 449, in parse_block_mapping_value if not self.check_token(KeyToken, ValueToken, BlockEndToken): File "/usr/local/lib/python2.7/dist-packages/yaml/scanner.py", line 116, in check_token self.fetch_more_tokens() File "/usr/local/lib/python2.7/dist-packages/yaml/scanner.py", line 257, in fetch_more_tokens % ch.encode('utf-8'), self.get_mark()) yaml.scanner.ScannerError: while scanning for the next token found character '\t' that cannot start any token in "tree.yaml", line 2, column 1 I have installed PyYAML by doing the following: python setup.py install I also tested it with: python setup.py test and it seemed to be ok. Now granted I am a little new to Python and YAML, but I have followed those two links to the letter. I have a file named tree.yaml and a file named test.py each containing the following: **_test.py_** import yaml with open('tree.yaml', 'r') as f: doc = yaml.load(f) txt = doc["treeroot"]["branch1"] print txt **_tree.yaml_** treeroot: branch1: branch1 text branch2: branch2 text and before you ask, yes I verified my tab space and I ran the YAML file through a validator. Any idea why this isnt working? Seems like its not able to communicate with PyYAML. Again I am very new to all of this, so I don't understand yet how it works and how everything integrates. Thanks for the help! I'm heading home for the day so will be away from computer for a little bit. Will check back in soon or will try to reply/answer any questions via phone. Thanks Answer: Yaml file uses spaces , not tabs as an indentation. In the error you provided it is clearly says that the first character in the second line is **tab**. Please replace it with 2 or 4 spaces and it should work. Tabs are not permited in yaml since they are treated differently by different editors and tools. And to avoid this confusion you should be using spaces.
Python 3.x's dictionary view objects and matplotlib Question: In python 3.x `keys()`, `values()` and `items()` return [views](https://docs.python.org/3/library/stdtypes.html#dict-views). Now while views certainly have [advantages](http://stackoverflow.com/a/8960727/1622937), they also seem to cause some compatibility issues. For example with `matplotlib` (ultimately it's with `numpy`). As an example [this](http://stackoverflow.com/a/16014873/1622937) and [this](http://stackoverflow.com/a/21832451/1622937) answers on stackexchange questions work just fine with python 2.x but raise an Exception when executing them in python 3.4. A minimal example would be: import matplotlib.pyplot as plt d = {1: 2, 2: 10} plt.scatter(d.keys(), d.values()) Which raises `TypeError: float() argument must be a string or a number, not 'dict_values'` with python 3.4. While for the minimal example the Exception is quite clear, [this](http://stackoverflow.com/questions/31753621/stackplot-using-list-of- dictionary-values-python-3-x) question arises because of the same problem and here the Exception is a lot less clear: `TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''` What is the best practice to deal with this issue? Can we hope that in a new release of `matplotlib` (or ultimately `numpy`) this issue will be dealt with or should we just start to write things like `list(dict.values())` when using `matplotlib` just to be sure not to run into trouble with python 3.x? Answer: More of that error: --> 512 return array(a, dtype, copy=False, order=order, subok=True) 513 514 def ascontiguousarray(a, dtype=None): TypeError: float() argument must be a string or a number, not 'dict_values' So the minimal example is: np.array(d.keys(),dtype=float) Without the dtype specification In [16]: np.array(d.keys()) Out[16]: array(dict_keys([1, 3]), dtype=object) The `dict_keys` is treated as an `object`. Usually you have to work at keeping `np.array` from treating an object as a list of numbers. In [17]: np.fromiter(d.keys(),dtype=float) Out[17]: array([ 1., 3.]) `np.fromiter` can handle `d.keys()`, treating it as a iterable. So there's some detail in how `fromiter` handles an iterable that is different from `np.array`. A generator expression works the same way, e.g. `(i for i in range(4))`. `fromiter` can iterate through it, `array` either treats it as an object or raises an error. If all the errors that the SO mentioned boiled down to `np.array(...)` handling a generator, then it might be possible to fix the behavior with one `numpy` change. Developers certainly wouldn't want to tweak every function and method that might accept a list. But it feels like a fundamental change that would have to be thoroughly tested. And even then it's likely to produce backward compatibility issues. The accepted fix, for some time now, has been to pass your code through `2to3`. <https://docs.python.org/2/library/2to3.html> for dictionaries: > Fixes dictionary iteration methods. dict.iteritems() is converted to > dict.items(), dict.iterkeys() to dict.keys(), and dict.itervalues() to > dict.values(). Similarly, dict.viewitems(), dict.viewkeys() and > dict.viewvalues() are converted respectively to dict.items(), dict.keys() > and dict.values(). It also wraps existing usages of dict.items(), > dict.keys(), and dict.values() in a call to list.
Initiate a Python Script via a Website (Click of a Button) Question: I have a small web panel on which I would like to control a python script that continuously collects data from a sensor (while loop). I would like to be able to start and stop this script by simply clicking a button. I know of a method of enabling the script to stop, but starting it seems to be a bit of a hassle. I have tried several solutions that included jQuery.ajax requests, but that sadly did not start the script. What should be noted is that I only want to start the script, I do not want any output/return values from it, so the script needs to run asynchronously in the background (which is what Ajax is for after all). Here are a few solutions that could potentially work: 1) Install Flask. The thing is I actually really want to avoid that and instead find a direct way to do this. After all, I just want to make a request to the script so it gets executed. 2) Execute it by installing PHP on the server and use exec(). But this again goes back to the point that I actually prefer to use Python directly or do it through a jQuery/Ajax call that actually works. Any suggestions on how to set this up? If there is really no other way, I suppose that installing PHP and using it to execute the files is the only way. If that is true, is it actually possible to have both Python scripts run asynchronously through the PHP exec() call? Answer: just wanted to answer my own question as, after extensive research, I found a solution to my initial problem. Here is a description: **The Button:** Here we simply have the onclick event for our Javascript function. <div class="col-md-4"><button id="script_run" type="button" class="btn btn-primary" onclick="runscript()">Test</button></div> **The Javascript Code:** On the Javascript side, I have created 2 functions. One that is there to update the color of the button (so the user will know if the script is currently running or not) and one script which actually makes an HTTP request via Ajax to our Python script. What you will notice here is that for the button, we are checking whether a local file (RUNNING.txt) exists. This is because RUNNING.txt is a temporary file that is created when our Python script is executed, here we store the ID's of our simultaneously running processes so that we can later terminate them. function changebutton() { $.ajax({ url: "RUNNING.txt", error: function() { document.getElementById('script_run').className = "btn btn-danger"; document.getElementById('script_run').innerHTML = "OFFLINE"; }, success: function() { document.getElementById('script_run').className = "btn btn-success"; document.getElementById('script_run').innerHTML = "ONLINE"; } }); } changebutton(); function runscript() { if (document.getElementById('script_run').innerHTML == "ONLINE") { $.ajax({ type: "POST", url: 'main.py', data: {offline: "True"} }) .done(setTimeout(function(){ changebutton(); }, 50000)); } else { $.ajax({ url: 'main.py' }) .done(setTimeout(function(){ changebutton(); }, 50000)); } }; **The Python Code:** What we are doing here is that when the script is called, we are creating the file RUNNING.txt. Then we actually get to the core part: which is the asynchronous processing of our functions. This is achieved through the _multiprocessing_ library. After that we save the process ID's in RUNNING.txt and wait for an event. If the script is called again (this leads us to the else statement), we execute the abort() function, which simply uses the os.kill() function to kill our processes. That's it :) import multiprocessing import cgi import os import os.path import signal import YOURFUNCTION1 import YOURFUNCTION2 def abort(): f = open('RUNNING.txt', 'r') process = f.readline() process = filter(None, process.split(",")) for p in process: os.kill(int(p), signal.SIGQUIT) f.close() os.remove('RUNNING.txt') def main(): if not os.path.isfile("RUNNING.txt"): f = open('RUNNING.txt', 'w+') for func in [YOURFUNCTION1, YOURFUNCTION2]: processes.append(multiprocessing.Process(target=func)) processes[-1].start() for p in processes: f.write(str(p.pid)) f.write(",") f.close() choice = raw_input("Press X to abort all processes: ") if choice == "X": abort() else: print "Processes already operational." if form.getvalue('offline') == "True": abort() Hope that I could help someone with this :)
How to test django session in django unittest? Question: I have created view: def forgot_password(request): """ Actions when user forgot password. :param request: object :return: redirect to views.home() or 'loginsys/forgot.html' with form, message """ message = None if request.method == 'POST': form = ForgotPasswordForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] user = User.objects.filter(email=email) salt = random_salt(len(user[0].username)) code = signing.dumps([user[0].id, user[0].email, user[0].username], key=settings.SECRET_KEY, salt=salt) url = settings.SITE_URL + reverse('loginsys:reset', args=[code]) send_email.apply_async(('Welcome', '<p>Hello</p><p><a href="{0}">Go to this link</a></p>'. format(url), [email])) store = ForgotPasswordLink() store.random_salt = salt store.user_link_id = user[0].id store.code_value = code store.save() forgot_password_salt_life.apply_async((user[0].id, salt), countdown=180) request.session["message"] = 'Instruction have sent on your mail - {0}'.format(email) return redirect(reverse('home')) else: form = ForgotPasswordForm() return render(request, 'loginsys/forgot.html', {'form': form, 'message': message}) I have write message in session: request.session["message"] = 'Instruction have sent on your mail - {0}'.format(email) Then I have tested view: def test_forgot_password(self): response = self.client.post(reverse('loginsys:forgot'), {'email': '[email protected]'}) self.assertRedirects(response, reverse('home'), 302, 200) session = self.client.session self.assertEqual(session['message'], 'Instruction have sent on your mail - [email protected]') And I have got error: Error Traceback (most recent call last): File "/home/maxim/PycharmProjects/SSHKeyStore/loginsys/tests.py", line 105, in test_forgot_password self.assertEqual(session['message'], 'Instruction have sent on your mail - [email protected]') File "/home/maxim/SSHKeyStoreVE/lib/python3.4/site-packages/django/contrib/sessions/backends/base.py", line 48, in __getitem__ return self._session[key] KeyError: 'message' So I don't know what is the problem. I find some examples and make like there, but it doesn't help: [Django testing stored session data in tests](http://stackoverflow.com/questions/13128443/django-testing-stored- session-data-in-tests), [How do I modify the session in the Django test framework](http://stackoverflow.com/questions/4453764/how-do-i-modify-the- session-in-the-django-test-framework), http://stackoverflow.com/questions/25132621/setting-a-session-variable-in- django-tests error: Error Traceback (most recent call last): File "/home/maxim/PycharmProjects/SSHKeyStore/loginsys/tests.py", line 22, in setUp self.client.session = self.session AttributeError: can't set attribute I have got message: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9. return f(*args, **kwds) This is bad. Please help me to fined solution and understand the problem ( may be solution is here [Using session object in Django unit test](http://stackoverflow.com/questions/14714585/using-session-object-in- django-unit-test) but I didn't understand). Thanks. Answer: Define a mixin for this purpose like this from django.test import Client from django.utils.importlib import import_module class ModifySessionMixin(object): client = Client() def create_session(self): session_engine = import_module(settings.SESSION_ENGINE) store = session_engine.SessionStore() store.save() self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key Now extend your test class from this mixin and call create_session in your setUp method to initialize session. class TestMobileResumeUpload(ModifySessionMixin, TestCase): def setUp(self): .... self.create_session() .... You can set any parameters to self.client.session now which can be accessed in your view as session variable. Also session changes done in view will be available in self.client.seesion for testing.
OSError: [WinError 10022] An invalid argument was supplied Question: Im making a port scanner it through's this message here is my code but it checks one port 21 i have pasted output below import socket import os host = input("Enter the host name or ip : ") s = socket.socket() s.settimeout(5) p = 0; s.close port = [21,22,23,25,53,80,110,115,135,139,143,194,443,445,1433,3306,3389,5632,5900,6112] while(p<=19): try: s.connect(('host', port[p])) except ConnectionRefusedError: print("Port %d is close" %(port[p])) except socket.timeout: print("Port %d is close" %(port[p])) else: print("Port %d is open" %(port[p])) p=p+1; s.close * * * On command line : PS E:\Codes by me\Selenium py> python .\practice.py Enter the host name or ip : 89.86.98.76 Port 21 is close # it checks one port Traceback (most recent call last): File ".\practice.py", line 11, in <module> s.connect((host, port[p])) OSError: [WinError 10022] An invalid argument was supplied Answer: You are passing the literal string `'host'` as the host. You should be passing the variable `host`: s.connect((host, port[p])) You are also not actually closing the socket each time, since you left off the parentheses in `s.close()`. But if you did close the socket each time, you would have to create a new socket each time, instead of trying to reuse the same socket. You can't reuse a closed socket.
Python datetime.datetime from time.structtime difference Question: I use feedparser to grab the entries from some RSS feeds. The entries have a published_parsed field which are parsed by feedparser into time.structtime. I use this function to convert the time.structtime into a datetime.datetime: def publishParsedToDatetime(structTime): return datetime.datetime.fromtimestamp(time.mktime(structTime)) Input (structtime): time.struct_time(tm_year=2015, tm_mon=8, tm_mday=1, tm_hour=20, tm_min=28, tm_sec=33, tm_wday=5, tm_yday=213, tm_isdst=0) Output (datetime): 2015-08-01 21:28:33 I see a problem which could be timezone related, there is **1 hour difference** between the structtime and the datetime values. The structtime value is UTC. But the datetime.datetime value is neither UTC, nor my current timezone (CET, Central European Time, we observe Summertime, so we have UTC + 2hrs at the moment). How can this be explained? Answer: Actually, as explained in the [documentation for `datetime.fromtimestamp`](https://docs.python.org/2/library/datetime.html#datetime.datetime.fromtimestamp), it converts to local time by default: > Return the local date and time corresponding to the POSIX timestamp, such as > is returned by time.time(). If optional argument tz is None or not > specified, the timestamp is converted to the platform’s local date and time, > and the returned datetime object is naive The 1 hour difference can then be explained by the [field `tm_isdst=0`](https://docs.python.org/2/library/time.html#time.struct_time) tells it to not use daylight savings (despite your local time zone using it). To see this more clearly, we construct two test cases import time, datetime # this is how your time object was constructed before tm_isdst = 0 t = time.mktime((2015, 8, 1, 20, 28, 33, 5, 213, tm_isdst)) print("Old conversion: {0}".format(datetime.datetime.fromtimestamp(t))) # this is what happens if you let mktime "divine" a time zone tm_isdst = -1 t = time.mktime((2015, 8, 1, 20, 28, 33, 5, 213, tm_isdst)) print("New conversion: {0}".format(datetime.datetime.fromtimestamp(t))) The output of this is as follows: Old conversion: 2015-08-01 21:28:33 New conversion: 2015-08-01 20:28:33 The problem then, you see, is that the `structTime` object being passed to your `publishParsedToDatetime` has `tm_isdst=0` but the time stamp you wanted to parse was for a DST time zone. As you have already noted in another comment, the proper solution to this is probably to always use UTC in your back-end code, and only do time zone handling when showing the time to the user, or when reading user input.
Missing needed parameter state Python social auth Email Validation Question: I am using python social auth with django app. In email validation, the link received on the mail works fine in the same browser from which authentication was initiated but it show `Missing needed parameter state` in different browser.Did anybody fix this issue ? The issue is discussed here [Issue #577](https://github.com/omab/python- social-auth/issues/577) Answer: **This is because there's no partial pipeline data in other browser!** Christopher Keefer has worked on [monkey- patch](https://gist.github.com/SaneMethod/b30156a3705ce9e944cd) for this by fetching the session_key for Django session table. There's also a blog article [here](http://artandlogic.com/2015/07/email-validation-with-django-and-python- social-auth/) on this , refer Step 3 of this article. # Monkey patching - an occasionally necessary evil. from social import utils from social.exceptions import InvalidEmail from django.core import signing from django.core.signing import BadSignature from django.contrib.sessions.models import Session from django.conf import settings def partial_pipeline_data(backend, user=None, *args, **kwargs): """ Monkey-patch utils.partial_pipeline_data to enable us to retrieve session data by signature key in request. This is necessary to allow users to follow a link in an email to validate their account from a different browser than the one they were using to sign up for the account, or after they've closed/re-opened said browser and potentially flushed their cookies. By adding the session key to a signed base64 encoded signature on the email request, we can retrieve the necessary details from our Django session table. We fetch only the needed details to complete the pipeline authorization process from the session, to prevent nefarious use. """ data = backend.strategy.request_data() if 'signature' in data: try: signed_details = signing.loads(data['signature'], key=settings.EMAIL_SECRET_KEY) session = Session.objects.get(pk=signed_details['session_key']) except BadSignature, Session.DoesNotExist: raise InvalidEmail(backend) session_details = session.get_decoded() backend.strategy.session_set('email_validation_address', session_details['email_validation_address']) backend.strategy.session_set('next', session_details.get('next')) backend.strategy.session_set('partial_pipeline', session_details['partial_pipeline']) backend.strategy.session_set(backend.name + '_state', session_details.get(backend.name + '_state')) backend.strategy.session_set(backend.name + 'unauthorized_token_name', session_details.get(backend.name + 'unauthorized_token_name')) partial = backend.strategy.session_get('partial_pipeline', None) if partial: idx, backend_name, xargs, xkwargs = \ backend.strategy.partial_from_session(partial) if backend_name == backend.name: kwargs.setdefault('pipeline_index', idx) if user: # don't update user if it's None kwargs.setdefault('user', user) kwargs.setdefault('request', backend.strategy.request_data()) xkwargs.update(kwargs) return xargs, xkwargs else: backend.strategy.clean_partial_pipeline() utils.partial_pipeline_data = partial_pipeline_data This fixes the problem to much extent, still its not perfect. It will fail if session_key gets deleted/changed in the database. Django updates session_key each time the session data changes. So in case any other user logs in the same browser the session_key gets changed and user can't verify with the email link. Omab has mentioned in the comment on [issue](https://github.com/omab/python- social-auth/issues/577), > I see the problem now, and even if I think that this could be solved with a > re-write of the email validation pipeline, this affects all the pipeline > functions that use the partial mechanism, so, I'm already working on a > restructure of the pipeline serialization functionality that will improve > this behavior. Basically the pipeline data will be dumped to a DB table and > a hash code will be used to identify the processes which can be stopped and > continue later, removing the dependency of the session. Looking for update on this.
RabbitMQ consumer connection dies after 90 seconds idle Question: I have a RabbitMQ task queue and a Pika consumer to consume these tasks (with acks). The problem is that the connection dies after 90 seconds Idle but my tasks will often take longer than that. That means that while tasks are still being computed they are returned to the task queue and never acked. Using RabbitMQ 3.5.3 and Pika 0.9.14 with the _channel.basic_consume()_ method. The connection has a _heartbeat_interval_ of 30 seconds. Consume code: import pika from time import sleep RABBITMQ_URL = "amqp://user:[email protected]/my_virtual_host?heartbeat_interval=30" QUEUE_NAME = "my_queue" def callback(ch, method, properties, body): print body sleep(91) # if sleep value < 90 this code works (even 89) ch.basic_ack(delivery_tag=method.delivery_tag) parameters = pika.URLParameters(RABBITMQ_URL) connection = pika.BlockingConnection(parameters) channel = connection.channel() channel.queue_declare(queue=QUEUE_NAME, durable=True) channel.basic_qos(prefetch_count=1) channel.basic_consume(callback, queue=QUEUE_NAME) channel.start_consuming() Traceback: Traceback (most recent call last): File "main.py", line 19, in <module> channel.basic_consume(callback, queue=QUEUE_NAME) File "/usr/local/lib/python2.7/site-packages/pika/channel.py", line 221, in basic_consume {'consumer_tag': consumer_tag})]) File "/usr/local/lib/python2.7/site-packages/pika/adapters/blocking_connection.py", line 1143, in _rpc self.connection.process_data_events() File "/usr/local/lib/python2.7/site-packages/pika/adapters/blocking_connection.py", line 240, in process_data_events if self._handle_read(): File "/usr/local/lib/python2.7/site-packages/pika/adapters/blocking_connection.py", line 347, in _handle_read if self._read_poller.ready(): File "/usr/local/lib/python2.7/site-packages/pika/adapters/blocking_connection.py", line 43, in inner return f(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/pika/adapters/blocking_connection.py", line 89, in ready self.poll_timeout) select.error: (9, 'Bad file descriptor') Answer: The problem here is that because you are sleeping for so long, pika cannot respond to heartbeat requests from RabbitMQ, and when this happens, RabbitMQ will close the connection. The only way around this is to either disable heartbeats or sleep in smaller intervals and run `process_data_events()` continuously so that pika can handle the heartbeats. **e.g. something like this** def amqp_sleep(connection, time_to_sleep=20): remaining = time_to_sleep while remaining > 0: connection.process_data_events() time.sleep(5) remaining -= 5 Personally though I would go for a library that automatically handles the heartbeats in the background so you don't have to deal with them, e.g. [rabbitpy](https://github.com/gmr/rabbitpy) or my own [amqp- storm](https://github.com/eandersson/amqp-storm).
uploading image to server php to python Question: I am converting my code from php to python and want to find the equivalent in python. My android application sends a base64 encrypted image and folder name. The script should decode it and save it to my server. The php is <?php // Get image string posted from Android App $base=$_REQUEST['image']; // Get file name posted from Android App $filename = $_REQUEST['filename']; // Decode Image $binary=base64_decode($base); header('Content-Type: bitmap; charset=utf-8'); // Images will be saved under 'www/img/uplodedimages' folder $file = fopen('/home1/test/public_html/img/'.$filename.'.jpg', 'wb'); if($file != true) { echo'Error uploading image'; } else{ // Create File fwrite($file, $binary); fclose($file); echo 'Image upload successful'; } ?> My attempt to convert to python is bellow #! /usr/bin/python import cgi import base64 import json print "Content-type: text/html\r\n\r\n" d = {} arguments = cgi.FieldStorage() base = arguments.getvalue('image') filename = arguments.getvalue('filename') binary = base.b64decode('base64') file = open('/home1/test/public_html/img/%s.jpg', 'wb') % filename if file != True: d['success'] = 0 d['message'] = 'Error uploading image' print json.dumps(d) else: file.write(file, binary) file.close() d['success'] = 1 d['message'] = 'Upload Successful' print json.dumps(d) I have never used I/O With python so I am new with it. When running the output is blank. Answer: This should work #! /usr/bin/python import cgi import base64 import simplejson print "Content-type: text/html\r\n\r\n" d = {} arguments = cgi.FieldStorage() data = arguments.getvalue('image') filename = arguments.getvalue('filename') binary = base64.b64decode(data) file = open('/home1/test/public_html/img/%s.jpg' % filename, 'wb') if file != True: d['success'] = 0 d['message'] = 'Error uploading image' print simplejson.dumps(d) else: file.write(file, binary) file.close() d['success'] = 1 d['message'] = 'Upload Successful' print simplejson.dumps(d)
Q: wx MouseEvent doing nothing Question: So im been working a little while with wx on python. For my problem I made a little code in order to show you what i need. import wx while True: if wx.MouseEvent().LeftIsDown() == True: print True I have been trying several variations with no results. Hope u can help me. Answer: The event objects are not meant to be created by user. It is created by the wx framework, when there is a relevant event, like when user clicked the mouse, keyboard, button clicked, .... You need to set up event binding. See [Events and Event Handling - wxPython documentation](http://wxpython.org/Phoenix/docs/html/events_overview.html).
Automatically strip the number in front of python codes when pasting Question: When I am reading an ebook or website, instead of inefficiently writing all the codes, I can obviously copy and paste the python codes. But about sometimes the format of the python code has a **number, a period, and a space** in front of the actual python code lines, I wonder if there is any technique/tools to remove them automatically? For example, from... 68. # File name: floatlayout.py 69. 70. from kivy.app import App 71. from kivy.uix.floatlayout import FloatLayout to ... # File name: floatlayout.py from kivy.app import App from kivy.uix.floatlayout import FloatLayout Answer: def remove_spaces(file_path): with open(file_path) as myfile, open('newfile.py', mode='w+') as newfile: for line in myfile: idx = line.find(' ') if idx < 0 or idx + 1 >= len(line) or is_int(line.strip()[:-1]): newfile.write('\n') continue newfile.write(line[idx+1:] + '\n') def is_int(str): try: int(str) except: return False return True
Python time.sleep syntax error Question: I'm writing a short program that makes it look like the computer is being hacked. I'm going to run it and leave the computer lying around and see how people react. However, I am getting this syntax error when I try to use `time.sleep.` can someone please help? import time print("Connecting to Server...") print("Connected!") response = input("Proceed with Hack? Y/N: ") if response == "Y": { print("Uploading File: 10%") time.sleep(2) print("Uploading File: 20%") time.sleep(2) print("Uploading File: 30%") time.sleep(2) print("Uploading File: 40%") time.sleep(2) print("Uploading File: 50%") time.sleep(2) print("Uploading File: 60%") time.sleep(2) print("Uploading File: 70%") time.sleep(2) print("Uploading File: 80%") time.sleep(2) print("Uploading File: 90%") time.sleep(2) print("Uploading File: 99%") time.sleep(1) print("File Uploaded!") print("Virus Injection Started...") time.sleep(6) print("Virus Injection Complete!") } Answer: You are using curly braces and they are not python's syntax for `if` statements, nor for loops (`for, while`). The curly braces are used in other programming languages. For example C and Java use curly braces to define the lines of code that belong to an `if` statement, but it is not like that in Python. In Python just remember that each line starting with an indentation of 4 spaces will belong to the code executed when entering the `if`. This Python's syntax also extends to loops, functions definitions, classes definitions... keep that in mind as well. For your code remove the curly braces and keep the indentation. As a simple example: a = 0 if a == 0: a = 1 # This line is inside the if statement b = 1 # This line is also inside the if statement a = 2 # Outside the if statement
Parsing html page with lxml in python Question: i want to parse this Xpath query with lxml in python. .//*[@id='content_top']/article/div/table/tbody/tr[5]/td/p/text() I checked the xpath query in Firepath (the firebug extension for xpath),and it works,but my python code show me nothing. Here's the source. from lxml import html import requests page = requests.get("http://www.scienzeetecnologie.uniparthenope.it/avvisi.html") tree = html.fromstring(page.text) avvisi = tree.xpath(".//*[@id='content_top']/article/div/table/tbody/tr[5]/td/p/text()") print(avvisi) The output is a `"[]"`. Answer: There is no actual `<tbody>` element in the source html, its just an element in the DOM added by the HTML parser. The firebug actually displays the DOM (and I am guessing firepath , which is a firebug extension works on this DOM (rather than the source html)). For a more detailed explanation on `<tbody>` and why firebug displays it , check the answers to the SO question - [Why does firebug add <tbody> to <table>?](http://stackoverflow.com/questions/1678494/why-does-firebug-add- tbody-to-table) or this question - [Why do browsers insert tbody element into table elements?](http://stackoverflow.com/questions/938083/why-do-browsers- insert-tbody-element-into-table-elements) * * * In your case, removing the `<tbody>` from the xpath, would make it work , Example - avvisi = tree.xpath(".//*[@id='content_top']/article/div/table/tr[5]/td/p/text()")
python daemon signal does not work Question: I wrote a python daemon script and registered some signal handlers , but when i use `kill -1 pid` , i found that signal handler does not work. Any body know why? Here is the script: test.py: #!/usr/bin/env python import sys, time from daemon import Daemon import threading import signal class MyDaemon(Daemon): def run(self): time.sleep(1) threading.Thread(target=mythread).start() threading.Thread(target=mythread2).start() def mythread(): while 1: raise Exception,"shit" def mythread2(): while 1: time.sleep(1) print "22222222222" if __name__ == "__main__": daemon = MyDaemon('/tmp/daemon-example.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() else: print "Unknown command" sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart" % sys.argv[0] sys.exit(2) daemon.py: #!/usr/bin/env python import sys, os, time, atexit from signal import SIGTERM import signal import logging import logging.handlers LOG_FILENAME = "/tmp/myservice.log" LOG_LEVEL = logging.INFO # Could be e.g. "DEBUG" or "WARNING" # Configure logging to log to a file, making a new file at midnight and keeping the last 3 day's data # Give the logger a unique name (good practice) logger = logging.getLogger(__name__) # Set the log level to LOG_LEVEL logger.setLevel(LOG_LEVEL) # Make a handler that writes to a file, making a new file at midnight and keeping 3 backups handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when="midnight", backupCount=3) # Format each log message like this formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s') # Attach the formatter to the handler handler.setFormatter(formatter) # Attach the handler to the logger logger.addHandler(handler) # Make a class we can use to capture stdout and sterr in the log class MyLogger(object): def __init__(self, logger, level): """Needs a logger and a logger level.""" self.logger = logger self.level = level def write(self, message): # Only log if there is a message (not just a new line) if message.rstrip() != "": self.logger.log(self.level, message.rstrip()) # Replace stdout with logging to file at INFO level sys.stdout = MyLogger(logger, logging.INFO) # Replace stderr with logging to file at ERROR level sys.stderr = MyLogger(logger, logging.ERROR) def signal_handler(signum,stack): print "signal:%s" % signum signal.signal(signal.SIGHUP,signal_handler) signal.signal(signal.SIGINT,signal_handler) signal.signal(signal.SIGTERM,signal_handler) class Daemon: """ A generic daemon class. Usage: subclass the Daemon class and override the run() method """ def __init__(self, pidfile, stdin='/dev/null', stdout='/tmp/out.txt', stderr='/tmp/err.txt'): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.pidfile = pidfile def daemonize(self): """ do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e: sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: # exit from second parent sys.exit(0) except OSError, e: sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors # sys.stdout.flush() # sys.stderr.flush() # si = file(self.stdin, 'r') # so = file(self.stdout, 'a+', 0) # se = file(self.stderr, 'a+', 0) # os.dup2(si.fileno(), sys.stdin.fileno()) # os.dup2(so.fileno(), sys.stdout.fileno()) # os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write("%s\n" % pid) def delpid(self): os.remove(self.pidfile) def start(self): """ Start the daemon """ # Check for a pidfile to see if the daemon already runs try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if pid: message = "pidfile %s already exist. Daemon already running?\n" sys.stderr.write(message % self.pidfile) sys.exit(1) # Start the daemon self.daemonize() self.run() def stop(self): """ Stop the daemon """ # Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message = "pidfile %s does not exist. Daemon not running?\n" sys.stderr.write(message % self.pidfile) return # not an error in a restart # Try killing the daemon process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err: err = str(err) if err.find("No such process") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) else: print str(err) sys.exit(1) def restart(self): """ Restart the daemon """ self.stop() self.start() def run(self): """ You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart(). """ As you can see, when i use kill command to the test.py , there is nothing print in the log files. Answer: Signals are only delivered to a single thread. If delivered to your first thread `mythread()` since it has stopped due to an exception, nothing will happen. Try reversing the order of dispatch of threads to see.
What does the first argument of the imp.load_source method do? Question: I'm reading [this](http://stackoverflow.com/questions/67631/how-to-import-a- module-given-the-full-path) SO question about importing modules from absolute path. An answer suggest to use following code: import imp foo = imp.load_source('module.name', '/path/to/file.py') foo.MyClass() I want to import file from dir which has following structure (it is package): __int__.py model_params.py I've done this: import01 = imp.load_source('module.name', '/home/wakatana/experiments/model_params/model_params.py') Now I can access variables within `model_params.py` via `import01.VARIABLE_NAME`. It seems like equivalent to `import numpy as np`. Where `model_params.py` is like `numpy` and `import01` is like `np`. I would like to ask what does the first argument of `load_source` method do? `help(imp)` says practically nothing about `load_source` method, e.g. following `help(imp.load_source)` returns `load_source(...)` Thanks **EDIT based on behzad.nouri comment** On documentation page of [load_source](https://docs.python.org/2/library/imp.html#imp.load_source) is said: > The name argument is used to create or access a module object. But when I try to access `module.name` I get an error about not defined module. Also why there is not documentation that can be accessed by `help`, can I install it somehow? I was hoping that documentation is part of the code itself in python, or is it common practice to not have it built-in but rather have it on-line? Answer: [From documentation ](https://docs.python.org/2/library/imp.html) > imp.load_source(name, pathname[, file]): > > Load and initialize a module implemented as a Python source file and return > its module object. If the module was already initialized, it will be > initialized again. **The name argument is used to create or access a module > object**. The pathname argument points to the source file. The file argument > is the source file, open for reading as text, from the beginning. It must > currently be a real file object, not a user-defined class emulating a file. > Note that if a properly matching byte-compiled file (with suffix .pyc or > .pyo) exists, it will be used instead of parsing the given source file
Passing PHP variable into a Python script not working Question: I am trying to call a simple python script from a php script. The result I am getting is just a single word while my actual input is a long text/sentence. The php script should return the entire sentence; it currently outputs only "The" Python script import sys print sys.argv[1] Php script $var1 = "The extra sleep will help your body wash out stress hormones."; $output = exec("C:\Python27\python.exe example.py $var1"); echo $output; Answer: Because command line parameters are space-delimited, you have to add some quotes: $output = exec("C:\Python27\python.exe example.py \"$var1\"");
cProfile with imports Question: I'm currently in the process of learn how to use cProfile and I have a few doubts. I'm currently trying to profile the following script: import time def fast(): print("Fast!") def slow(): time.sleep(3) print("Slow!") def medium(): time.sleep(0.5) print("Medium!") fast() slow() medium() I execute the command `python -m cProfile test_cprofile.py` and I have the following result: Fast! Slow! Medium! 7 function calls in 3.504 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 3.504 3.504 test_cprofile.py:1(<module>) 1 0.000 0.000 0.501 0.501 test_cprofile.py:10(medium) 1 0.000 0.000 0.000 0.000 test_cprofile.py:3(fast) 1 0.000 0.000 3.003 3.003 test_cprofile.py:6(slow) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 2 3.504 1.752 3.504 1.752 {time.sleep} However, when I edit the script with a pylab import for example (`import pylab`) on the top, the output of cProfile is very large. I tried to limit the number of lines using `python -m cProfile test_cprofile.py | head -n 10` however I receive the following error: Traceback (most recent call last): File "/home/user/anaconda/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/home/user/anaconda/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/home/user/anaconda/lib/python2.7/cProfile.py", line 199, in <module> main() File "/home/user/anaconda/lib/python2.7/cProfile.py", line 192, in main runctx(code, globs, None, options.outfile, options.sort) File "/home/user/anaconda/lib/python2.7/cProfile.py", line 56, in runctx result = prof.print_stats(sort) File "/home/user/anaconda/lib/python2.7/cProfile.py", line 81, in print_stats pstats.Stats(self).strip_dirs().sort_stats(sort).print_stats() File "/home/user/anaconda/lib/python2.7/pstats.py", line 360, in print_stats self.print_line(func) File "/home/user/anaconda/lib/python2.7/pstats.py", line 438, in print_line print >> self.stream, c.rjust(9), IOError: [Errno 32] Broken pipe Can someone help what is the correct procedure to situations similar with this one, where we have a import pylab or another module that generates such high output information on cProfile? Answer: I don't know of a way to do selective profiling like you want by running the `cProfile` module directly from the command line like that. However you can do it by modifying the your code to explicitly import the module, but you have to do everything yourself. Here's how that might be done to your example code: from cProfile import Profile from pstats import Stats prof = Profile() prof.disable() # i.e. don't time imports import time prof.enable() # profiling back on def fast(): print("Fast!") def slow(): time.sleep(3) print("Slow!") def medium(): time.sleep(0.5) print("Medium!") fast() slow() medium() prof.disable() # don't profile the generation of stats prof.dump_stats('mystats.stats') with open('mystats_output.txt', 'wt') as output: stats = Stats('mystats.stats', stream=output) stats.sort_stats('cumulative', 'time') stats.print_stats() Contents of `mystats_output.txt` after running: Sun Aug 02 16:55:38 2015 mystats.stats 6 function calls in 3.522 seconds Ordered by: cumulative time, internal time ncalls tottime percall cumtime percall filename:lineno(function) 2 3.522 1.761 3.522 1.761 {time.sleep} 1 0.000 0.000 3.007 3.007 cprofile-with-imports.py:15(slow) 1 0.000 0.000 0.515 0.515 cprofile-with-imports.py:19(medium) 1 0.000 0.000 0.000 0.000 cprofile-with-imports.py:12(fast) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
How can I efficiently compute the md5 sum of an iterable of bits in Python? Question: Consider the code below. It converts an image to line art and then computes the md5sum of the bits. I don't know a better to do this than with a generator expression producing individual bits. But then how can I feed the result to md5 in an efficient way? The code below does it with a [bitarray](https://pypi.python.org/pypi/bitarray/) object, but I get non- deterministic results handing `bitarray` instances (which seem to use fancy C stuff under the hood) to md5. So what is the "right" way to do this? import os, hashlib from PIL import Image from bitarray import bitarray def image_pixel_hash_code(image): pixels = list(image.getdata()) avg = sum(pixels) / len(pixels) bits = bitarray(pixel < avg for pixel in pixels) return hashlib.md5(bits).hexdigest() im = Image.open(os.path.expanduser("~/Downloads/test.jpg")).convert("L") print image_pixel_hash_code(im) P.S. I can reproduce the bitarray non-determinism but I assumes it's just a function of using two things together that aren't supposed to work together. Answer: The hash is including random bits at the end of `bits` if the length of `bits` is not a multiple of 8. You can see this by looking at `memoryview(bits)` You could fix this by padding `bits` with `0`s bits = bitarray(1 if pixel < avg else 0 for pixel in pixels) bits.fill() return hashlib.md5(bits).hexdigest()
How can I make a Post Request on Python with urllib3? Question: I've been trying to make a request to an API, I have to pass the following body: { "description":"Tenaris", "ticker":"TS.BA", "industry":"Metalúrgica", "currency":"ARS" } Altough the code seems to be right and it finished with "Process finished with exit code 0", it's not working well. I have no idea of what I'm missing but this is my code: http = urllib3.PoolManager() http.urlopen('POST', 'http://localhost:8080/assets', headers={'Content-Type':'application/json'}, data={ "description":"Tenaris", "ticker":"TS.BA", "industry":"Metalúrgica", "currency":"ARS" }) By the way, this the first day working with Python so excuse me if I'm not specific enough. Answer: Since you're trying to pass in a JSON request, you'll need to encode the body as JSON and pass it in with the `body` field. For your example, you want to do something like: import json encoded_body = json.dumps({ "description": "Tenaris", "ticker": "TS.BA", "industry": "Metalúrgica", "currency": "ARS", }) http = urllib3.PoolManager() r = http.request('POST', 'http://localhost:8080/assets', headers={'Content-Type': 'application/json'}, body=encoded_body) print r.read() # Do something with the response? _Edit: My original answer was wrong. Updated it to encode the JSON. Also, related question:[How do I pass raw POST data into urllib3?](https://stackoverflow.com/questions/19233001/how-do-i-pass-raw-post- data-into-urllib3)_
How to share variables among python scripts Question: I am having trouble making variables accessible among different python scripts. I have three scripts: shared.py test1.py test2.py In `shared.py`, I define a dictionary `devices` and initialize it. devices = {} In `test1.py`, I import `shared.py` and add some value into `devices` import shared shared.devices['item1': 'item1'] In `test2.py`, I import `shared.py` and try to print the updated `devices` in `shared.py` import shared print shared.devices Instead of printing the updated value, it gives me an empty dictionary. My understanding is that when I imported `shared` in `test2.py`, codes in `shared.py` are executed again, so it leads to the re-initialization of `devices` Is there a way that I can access the updated `devices` in `test2.py`? Thanks in advance. **UPDATE1:** I changed my shared.py test1.py and test2.py according to a similar solution from [link](http://stackoverflow.com/questions/13034496/using-global-variables- between-files-in-python) and then added test3.py # shared.py def init(): global devices devices = {} # test1.py import shared def add(key, value): shared.devices[key] = value # test2.py import shared import test1.py shared.init() test1.add('key1', 'value1') print shared.devices # test3.py import shared print shared.devices I executed the scripts in the following order: python test1.py (fine) python test2.py (fine) python test3.py (which gives me an error:"AttributeError: 'module' object has no attribute 'devices'") **UPDATE2:** To make my question more realistic. I have a `login.py` which takes a few arguments and tries to connect to a switch. For example: python login.py --ip 10.1.1.1 --username admin --password admin # login.py - pseudocode switch = Switch() #create an object of Router class switch.connect(ip, username, password) #take the arguments from the command line and try to connect to a router switch_dict[admin] = switch #add switch instance to a shared dictionary switch_dict, which will be used by over scripts as well. After connecting to a switch, I then need to execute another script `vlan.py` to create a vlan on that switch # vlan.py - pseudocode # first I need to get the switch that was created by admin, not other users my_switch = switch_dict['admin'] # Then I can perform some configuration on vlan my_switch.createvlan() The problem is how can I create and store a dictionary `switch_dict` that can be shared and accessed by other scripts?? Answer: You need some form of shared storage. You can use (depending on what you are doing): 1. A queue or a pipe ([documentation](https://docs.python.org/2/library/multiprocessing.html#exchanging-objects-between-processes)). 2. Shared memory ([documentation](https://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes)). 3. A third, independent store like a file (you can use json or pickle to serialize the object), memcache, redis, sqlite or a database. The point being that this is not trivial and you need to decide (based on the application) which option works for you.
Python mutliprocessing: Timestamp of a process Question: I am using python multiprocessing module. I need to see the timestamp at which a process starts and the timestamp at which a process ends. If I do this: ... processes = [Process(target=topo.func1, args=(host,servers,q)) for x in range(1,i)] for p in processes: p.start() print p <Process(Process-1, started)> p.join() print p <Process(Process-1, stopped)> It only prints process number and status. How can I print the timestamp? Answer: **import datetime** module first and then you can print the timestamp
Loop over multiple .csv files python/pandas Question: I have two folders that contain +50 .csv files, I want to process al those files in my python code with pandas. At the beginning of my code I load two different .csv files: Location1 = path\tasks_01.csv' Location2 = path\resource_01.csv' dftask = pd.read_csv(Location1) dfresource = pd.read_csv(Location2) In the middle I do all kind of different operations to structure the data etc. At the end I save both .csv files to a new .csv file: dftask.to_csv(path\tasks_new.csv') dfresource.to_csv(path\resource_new.csv') Since I have two folders, one containts the task.csv files and the other the resource.csv files how can I edit my code in such a way I can loop over all those files? And save them under their original name? Hope you can help me out! Answer: Create a list of files in each folder and then zip through both of them. import os files_in_folder_1 = [os.path.join(path1, f) for f in os.listdir(path1) if os.path.isfile(os.path.join(path1, f))] files_in_folder_2 = [os.path.join(path2, f) for f in os.listdir(path2) if os.path.isfile(os.path.join(path2, f))] for file1, file2 in zip(files_in_folder_1, files_in_folder_2): with open(file1) as f1, open(file2) as f2: ...
Define imports and Python project structure to allow running locally and when installed Question: I am working on a Python project and started using a setup.py file to install it. I followed some guides on how to structure the project and everything is working great after installing it. My problem is that I "lost" the ability to run my application from inside the project's directory, locally so to speak without installing it, for testing purposes. Here's how the directory layout looks like: project_dir/ ├── bin │   └── app.py ├── data │ └── data.conf ├── app_module │   └── __init__.py ├── LICENSE ├── README.md └── setup.py The problem has to do with the imports. In `app.py` I have `import app_module` and it works as intended after it gets installed to the proper directory by running `python setup.py install`. If I want to run it by doing `python bin/app.py` it obviously doesn't work. What am I doing wrong and how could I get this to work? Ideally I want to be able to run it from inside the directory and it should still work when installed with the `setup.py` script. Answer: if your `bin/app.py` is only doing: import app_module app_module.run() # or whatever you called the main() function you could (should!) use an [`entry_points` (search for `console_scripts`)](https://pythonhosted.org/setuptools/setuptools.html#dynamic- discovery-of-services-and-plugins). And while running your uninstalled code, you would do either: `python -m app_module` or `python app_module/__init__.py` (assuming you have a `__main__` section inside this file, otherwise look at how [`json.tool`](https://hg.python.org/cpython/file/62235755609f/Lib/json/tool.py) is doing. ## Edit Here is a basic example, assuming your library is named "app_module". ### setup.py import imp import os import setuptools module_name = 'app_module' module = imp.load_module( module_name, *imp.find_module(module_name, [os.path.dirname(__file__)]) ) base = 'data' data_files = [ ( '/usr/local/share/appdata/' + module_name + root[len(base):], [os.path.join(root, f) for f in files] ) for root, dirs, files in os.walk(base) ] setuptools.setup( name=module_name, version=module.__version__, classifiers=( 'Environment :: Console', 'Operating System :: POSIX :: Linux', ), packages=( module_name, ), entry_points={ # the executable will be called 'app' (not 'app.py') 'console_scripts': ['app = ' + module_name + ':main'], # it does not seems unnecessarily complicated to me, it's just three lines }, data_files=data_files, ) ### app_module/__init__.py import optparse import sys __version__ = '1.2.3' def main(): parser = optparse.OptionParser(version=__version__) parser.add_option('-m', '--man', action='store_true') opt, args = parser.parse_args() if opt.man: help(__name__) sys.exit() print opt, args if __name__ == '__main__': main() ### And now... To run it: python /full-or-replative/path/to/app_module/__init__.py # or export PYTHONPATH=/full-or-replative/path/to/app_module/ python -m app_module To install and run it: # test in a virtualenv workon test python setup.py install app -h
Error when serve Django 1.8 Applications with Apache2 and mod_wsgi on Ubuntu 14.04 Question: I am trying to serve my django project with Apache2 and mod_wsgi and I am stuck. Everything works fine until I try to integrate mod_wsgi. I am using python 3. The relevant coding are as below: * * * ## Apache2.conf <VirtualHost *:80> ServerAdmin [email protected] ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/mysite Alias /static/ /var/www/mysite/static/ <Directory /var/www/mysite/static> Require all granted </Directory> WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py <Directory /var/www/mysite/mysite/wsgi.py> <Files wsgi.py> Require all granted </Files> </Directory> # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # after it has been globally disabled with "a2disconf". #Include conf-available/serve-cgi-bin.conf </VirtualHost> * * * ## wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() * * * ## Error log [Mon Aug 03 18:45:42.192589 2015] [:error] [pid 2638:tid 140604829079296] [client 130.102.158.21:49084] File "<frozen importlib._bootstrap>", line 2254, in _gcd_import [Mon Aug 03 18:45:42.192606 2015] [:error] [pid 2638:tid 140604829079296] [client 130.102.158.21:49084] File "<frozen importlib._bootstrap>", line 2237, in _find_and_load [Mon Aug 03 18:45:42.192623 2015] [:error] [pid 2638:tid 140604829079296] [client 130.102.158.21:49084] File "<frozen importlib._bootstrap>", line 2224, in _find_and_load_unlocked [Mon Aug 03 18:45:42.192649 2015] [:error] [pid 2638:tid 140604829079296] [client 130.102.158.21:49084] ImportError: No module named 'mysite' * * * I know it has something to do with how wsgi was configured in apache2.conf file, but have no idea how to fix it. Any help would be appreciated. Thanks Answer: You need to add this: WSGIPythonPath /var/www/mysite From the [doc](https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/modwsgi/), _"The WSGIPythonPath line ensures that your project package is available for import on the Python path; in other words, that import mysite works."_
Is there a pythonic way to check whether OS is a 64bit Ubuntu? Question: Is there a pythonic way to check whether OS is a 64bit Ubuntu? Currently, I've been doing it as such: import os def check_is_linux(distro, architecture, err_msg): try: this_os = os.popen('lsb_release -d').read() this_arch = os.popen('uname -a').read() assert distro in this_os and architecture in this_arch, err_msg except: print(err_msg) def check_is_64bit_ubuntu(err_msg): check_is_linux('Ubuntu', 'x86_64', err_msg) Answer: You can use the [`platform` module](https://docs.python.org/2/library/platform.html) to get distribution and processor information: import platform def is_linux(distro, architecture): if not platform.system() == 'Linux': return False if platform.linux_distribution()[0].lower() != distro: return False return platform.processor() == architecture def is_64bit_ubuntu(): return is_linux('ubuntu', 'x86_64') if not is_64bit_ubuntu(): print(err_msg)
Split path in Python Question: How I could split this: C:\my_dir\repo\branch to: ['C:\my_dir', rest_part_of_string] where `rest_part_of_string` can be one string or could be splitted every `\`. I don't care about rest, i just want first two elements together. Answer: Using [regular expression](https://docs.python.org/2/howto/regex.html) ([`re` module documentation](https://docs.python.org/2/library/re.html)): >>> import re >>> print(re.match(r'[^\\]+\\[^\\]+', r'C:\my_dir\repo\branch').group()) C:\my_dir >>> re.findall(r'[^\\]+\\[^\\]+|.+', r'C:\my_dir\repo\branch') ['C:\\my_dir', '\\repo\\branch']
Search and return lines in a file with matching keyword in python Question: I have used regex to isolate a particular keyword in a line taken from a file. I want to search the entire file and return groups of lines which have the same keyword. I am a little confused about this, and I was wondering if there is a direct regex way to do this in Python ? e.g. - > My file may look like this 1 0001 1 UG science,ee;YEAR=onefour;standard->2;district->9 2 0002 1 UG science,cs;YEAR=onefive;standard->1;district->9 3 0012 2 UG science,eng;YEAR=onefour;standard->3;district->4 4 0021 2 UG science,ee;YEAR=onetwo;standard->2;district->9 5 0056 4 UG science,cs;YEAR=onefive;standard->1;district->8 6 0145 3 UG science,eng;YEAR=onetwo;standard->4;district->2 I used regex to extract "YEAR=****" and want to group the lines according to the value of "****" The output should look like this - 1 0001 1 UG science,ee;YEAR=onefour;standard->2;district->9 3 0012 2 UG science,eng;YEAR=onefour;standard->3;district->4 2 0002 1 UG science,cs;YEAR=onefive;standard->1;district->9 5 0056 4 UG science,cs;YEAR=onefive;standard->1;district->8 4 0021 2 UG science,ee;YEAR=onetwo;standard->2;district->9 6 0145 3 UG science,eng;YEAR=onetwo;standard->4;district->2 I believe I can do it the long way of opening file, storing in dictionaries and matching, etc, etc. But would like to know if there is short concise way of doing this. as requested - a bit of code I tried to write and run - #!/usr/bin/python import re ##open file and read each line of file dfile = open("datafile.txt","r") ##regex to find YEAR in entry and return YEAR regex_unique = re.compile(r'(?<=\bYEAR=)[^;]+') list_Name =[] for line in dfile: match1 = re.search(regex_unique,line) if match1: if match1.group(0) not in list_Name: list_Name.append(match1.group(0)) ## print (list_Name) for item in list_Name: for line in dfile: match2 = re.search(item,line) if match2: print (match2) the last bit does not seem to work - I am assuming if I give item to re.search it should search for that word in the entire file - Now I think I might have to add some wildcard entries before and after the actual word to make it work. Answer: I think I'm right in saying that regex only deals with matches on lines, not with how to aggregate matches -- so you'll need to do that yourself. You can keep things simple by writing your own utility function and keeping it separate from you application code. Grouping operations in general must pass over all of the items to assemble the groups. Your problem can't be solved without making a pass over all of the data to collect the groups, and then another pass to output the groups. A dictionary of lists is the natural datastructure to collect a each line by by a key (as you note). Doing this yourself set is a little kludgey, since you frequently need to test whether a key exists to know whether you should add to an existing list or create a new one. Fortunately, python provides defaultdict, that lets you: from collections import defaultdict >>> d = defaultdict(list) >>> d[key].append(line) So, you can do the following: def groupLinesByMatch(filename,regex): import re from collections import defaultdict regex = re.compile(regex) result = defaultdict(list) for line in open(filename).readlines(): matches = regex.match(line) if matches: result[matches.group(1)].append( line ) return result.values() for lines in groupLinesByMatch(filename, regex): for line in lines: print line, print