text
stringlengths
226
34.5k
NSUserNotificationCenter.defaultUserNotificationCenter() returns None in python Question: I am trying to connect to the Mountain Lion notification center via python. I've installed pyobjc and am following the instructions [here](https://github.com/maranas/pyNotificationCenter) and [here](https://gist.github.com/baliw/4020619). Also see: [Working with Mountain Lion's Notification Center using PyObjC](http://stackoverflow.com/questions/12202983/working-with-mountain- lions-notification-center-using-pyobjc) Here's my code: import Foundation, objc import AppKit import sys NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') def notify(title, subtitle, info_text, delay=0, sound=False, userInfo={}): """ Python method to show a desktop notification on Mountain Lion. Where: title: Title of notification subtitle: Subtitle of notification info_text: Informative text of notification delay: Delay (in seconds) before showing the notification sound: Play the default notification sound userInfo: a dictionary that can be used to handle clicks in your app's applicationDidFinishLaunching:aNotification method """ notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(info_text) notification.setUserInfo_(userInfo) if sound: notification.setSoundName_("NSUserNotificationDefaultSoundName") notification.setDeliveryDate_(Foundation.NSDate.dateWithTimeInterval_sinceDate_(delay, Foundation.NSDate.date())) NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification) When I call the notify function with arguments I get an attribute error: `AttributeError: 'NoneType' object has no attribute 'scheduleNotification_'` I don't understand why `NSUserNotificationCenter.defaultUserNotificationCenter()` is returning a NoneType object. I've not been able to query anything on this matter on the internet or SO. Answer: So, this works fine using Ned's advice of using default python. It also worked when I installed pyobjc on the 32-bit enthought distribution. It seems to me that pyobjc works only on 32 bit python distributions (I cannot confirm this, but so far this seems to be the case). (Note: When I posted the question I had installed pyobjc on the 64 bit enthought distribution).
Plotting mathematica data with python Question: This question is related to my previous question on ["publication quality plots in python"](http://stackoverflow.com/q/15988413/957560). I am trying to write a post processor (a bash script/python combo) that would comb through the thousands (literally!) of data files I have and plot data. The trouble is, my data files are from mathematica. I have interpolating function polynomials in Mathematica (mma) as a result of an NDSolve operation on a non-linear partial differential equation. I was able to deconstruct/extract discrete data out of my mma polynomials. The data when plotted in mma results in 3D profile plots such as this: ![3D plot from mathematica using <code>ListPlot3D</code>](http://i.stack.imgur.com/jDCHn.png) Now this is a profile plot at a certain time step that I am interested in. It is constituted of X and Y coordinate values (data included at the end of this post) which I extracted and when plotted look like this: ![X data](http://i.stack.imgur.com/7Yg41.png) ![Y data](http://i.stack.imgur.com/IFEGe.png) How do I plot this X, Y data with python? In other words, what is the best way of going about it? I have tried the following python code for surface plots and wireframe plots but they all **need a Z coordinate which I don't have**. ## Edit My full data for this particular 3D profile plot is [here](http://dl.dropboxusercontent.com/u/13223318/data3d.dat). I am trying to figure out how to arrange this in rows and columns now... ## Example wireframe plot: from numpy import * from numpy.random import rand from pylab import pcolor, show, colorbar, xticks, yticks from pylab import * from mpl_toolkits.mplot3d import axes3d from matplotlib import * #from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X, Y, Z = axes3d.get_test_data(0.05) ax.plot_wireframe(X, Y,Z, rstride=10, cstride=10, cmap="binary") plt.show() ![Python wireframe plot](http://i.stack.imgur.com/xesVc.jpg) ## Surface plot from numpy import * from numpy.random import rand from pylab import pcolor, show, colorbar, xticks, yticks from pylab import * from mpl_toolkits.mplot3d import Axes3D from matplotlib import * #from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) surf = ax.plot_surface(X,Y,Z, rstride=1, cstride=1, cmap="binary", linewidth=0, antialiased=False) #ax.set_zlim(-1.01, 1.01) #ax.zaxis.set_major_locator(LinearLocator(10)) #ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() ![Python surface plot](http://i.stack.imgur.com/bIByR.png) ## X, Y data: X: {0.132737, 0.13191, 0.129746, 0.127106, 0.125117, 0.12483, 0.126976, \ 0.131958, 0.140068, 0.151781, 0.167899, 0.189295, 0.216319, 0.248189, \ 0.282795, 0.317034, 0.347415, 0.370662, 0.384156, 0.386236, 0.376402, \ 0.355467, 0.325648, 0.290526, 0.254685, 0.222845, 0.198549, 0.183281, \ 0.177335, 0.182392, 0.203451, 0.246983, 0.315549, 0.405471, 0.509765, \ 0.621364, 0.73459, 0.845401, 0.951138, 1.05018, 1.14164, 1.22514, \ 1.30063, 1.3683, 1.42847, 1.48156, 1.52802, 1.56836, 1.60306, \ 1.63263, 1.65754, 1.67825, 1.69521, 1.70884, 1.71951, 1.72761, \ 1.73347, 1.7374, 1.73971, 1.74066, 1.74049, 1.73944, 1.7377, 1.73545, \ 1.73286, 1.73009, 1.72724, 1.72445, 1.7218, 1.71938, 1.71726, 1.7155, \ 1.71414, 1.71322, 1.71275, 1.71275, 1.71322, 1.71415, 1.71551, \ 1.71727, 1.71939, 1.72181, 1.72446, 1.72726, 1.7301, 1.73288, \ 1.73547, 1.73772, 1.73947, 1.74052, 1.74069, 1.73974, 1.73744, \ 1.7335, 1.72765, 1.71955, 1.70888, 1.69525, 1.67829, 1.65757, \ 1.63266, 1.60309, 1.56838, 1.52803, 1.48156, 1.42846, 1.36828, \ 1.30059, 1.22507, 1.14155, 1.05005, 0.950968, 0.845186, 0.734326, \ 0.621052, 0.509426, 0.405163, 0.31538, 0.247033, 0.203632, 0.18257, \ 0.177457, 0.183338, 0.198563, 0.222852, 0.254712, 0.290571, 0.325696, \ 0.355504, 0.376422, 0.386237, 0.38414, 0.370635, 0.347385, 0.317008, \ 0.282778, 0.24818, 0.216314, 0.189287, 0.167886, 0.151767, 0.140056, \ 0.131952, 0.126973, 0.124829, 0.125116, 0.127103, 0.129743, 0.131907, \ 0.132737} Y: {0.132737, 0.160814, 0.248665, 0.386715, 0.554857, 0.736199, \ 0.919228, 1.09676, 1.26441, 1.41958, 1.56072, 1.68695, 1.79781, \ 1.89307, 1.97268, 2.03665, 2.08504, 2.11789, 2.13527, 2.1372, \ 2.12369, 2.0947, 2.05018, 1.99008, 1.91432, 1.82288, 1.71579, 1.5932, \ 1.45551, 1.30345, 1.13838, 0.962571, 0.779892, 0.596757, 0.423678, \ 0.276942, 0.177388, 0.136833, 0.13817, 0.160097, 0.190941, 0.222093, \ 0.247023, 0.261917, 0.265986, 0.261225, 0.251781, 0.243058, 0.240757, \ 0.250172, 0.275704, 0.320022, 0.382994, 0.461711, 0.551722, 0.648374, \ 0.747602, 0.846211, 0.941863, 1.03295, 1.11842, 1.19768, 1.27043, \ 1.33662, 1.39633, 1.4498, 1.49731, 1.53921, 1.57586, 1.60765, \ 1.63497, 1.65821, 1.67774, 1.69392, 1.70711, 1.71765, 1.72583, \ 1.73197, 1.73635, 1.73922, 1.74084, 1.74142, 1.74119, 1.74032, 1.739, \ 1.73739, 1.73562, 1.73382, 1.73211, 1.73057, 1.72928, 1.72831, \ 1.72768, 1.72744, 1.72759, 1.72812, 1.72901, 1.73023, 1.73172, \ 1.7334, 1.73518, 1.73697, 1.73864, 1.74005, 1.74105, 1.74146, \ 1.74111, 1.73977, 1.73724, 1.73326, 1.72759, 1.71994, 1.71003, \ 1.69753, 1.68213, 1.66347, 1.64119, 1.61492, 1.58428, 1.54888, \ 1.50832, 1.46224, 1.41028, 1.35213, 1.28756, 1.21644, 1.13877, \ 1.05479, 0.965005, 0.870346, 0.772266, 0.672914, 0.575269, 0.483202, \ 0.401281, 0.334109, 0.285083, 0.255065, 0.242016, 0.241877, 0.249537, \ 0.25934, 0.265716, 0.264102, 0.251884, 0.229106, 0.198813, 0.166855, \ 0.141209, 0.132737} Answer: Use the `plot` or `scatter` method to plot x, y data. In your case, x is time and y is either one of X or Y. To generate your time coordinates use the [range](http://docs.python.org/2.7/library/functions.html?highlight=range#range) function: range(5) -> [0, 1, 2, 3, 4] Here is an example. #!python2 import matplotlib.pyplot as plt X = [0.132737, 0.13191, 0.129746, 0.127106, 0.125117, 0.12483, 0.126976, 0.131958, 0.140068, 0.151781, 0.167899, 0.189295, 0.216319, 0.248189, 0.282795, 0.317034, 0.347415, 0.370662, 0.384156, 0.386236, 0.376402, 0.355467, 0.325648, 0.290526, 0.254685, 0.222845, 0.198549, 0.183281, 0.177335, 0.182392, 0.203451, 0.246983, 0.315549, 0.405471, 0.509765, 0.621364, 0.73459, 0.845401, 0.951138, 1.05018, 1.14164, 1.22514, 1.30063, 1.3683, 1.42847, 1.48156, 1.52802, 1.56836, 1.60306, 1.63263, 1.65754, 1.67825, 1.69521, 1.70884, 1.71951, 1.72761, 1.73347, 1.7374, 1.73971, 1.74066, 1.74049, 1.73944, 1.7377, 1.73545, 1.73286, 1.73009, 1.72724, 1.72445, 1.7218, 1.71938, 1.71726, 1.7155, 1.71414, 1.71322, 1.71275, 1.71275, 1.71322, 1.71415, 1.71551, 1.71727, 1.71939, 1.72181, 1.72446, 1.72726, 1.7301, 1.73288, 1.73547, 1.73772, 1.73947, 1.74052, 1.74069, 1.73974, 1.73744, 1.7335, 1.72765, 1.71955, 1.70888, 1.69525, 1.67829, 1.65757, 1.63266, 1.60309, 1.56838, 1.52803, 1.48156, 1.42846, 1.36828, 1.30059, 1.22507, 1.14155, 1.05005, 0.950968, 0.845186, 0.734326, 0.621052, 0.509426, 0.405163, 0.31538, 0.247033, 0.203632, 0.18257, 0.177457, 0.183338, 0.198563, 0.222852, 0.254712, 0.290571, 0.325696, 0.355504, 0.376422, 0.386237, 0.38414, 0.370635, 0.347385, 0.317008, 0.282778, 0.24818, 0.216314, 0.189287, 0.167886, 0.151767, 0.140056, 0.131952, 0.126973, 0.124829, 0.125116, 0.127103, 0.129743, 0.131907, 0.132737] ax = plt.subplot(111) ax.plot(range(len(X)), X) #ax.scatter(range(len(X)), X) plt.show() ## Edit in answer to the comment #!python2 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np DATA = 'test0005.dat' def get_data(fname=DATA): '''Read 2d array of z coordinates from file. Convert to float values and wrap in a numpy array.''' with open(fname) as f: data = [map(float, line.split()) for line in f] return np.array(data) def plot(x, y, z): '''Surface plot of 3d data.''' fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_surface(x, y, z, rstride=4, cstride=4) plt.show() if __name__ == '__main__': z = get_data() x = range(z.shape[0]) y = range(z.shape[1]) x, y = np.meshgrid(x, y) plot(x, y, z)
Pythonic method to sum all the odd-numbered lines in a file Question: I'm learning Python for a programming placement test I have to take for grad school, and this is literally the first little script I threw together to get a feel for it. My background is mainly C# and PHP, but I can't use either language on the test. My test script reads in the below text file (test_file1.txt). The even lines contain a sample size, and the odd lines contain "results" for each test in the sample. EOF is marked with a 0. I wanted to read in the file, output the sample size, and sum the results of each test. How would you perform this task with Python? I feel like I was trying to force python to be like PHP or C#, and from my research I guess there are very "Python" ways of doing thigs. test_file1.txt: 3 13 15 18 5 19 52 87 55 1 4 11 8 63 4 2 99 3 0 My simple script: file = open("test_file1.txt", "r") i=0 for line in file: if i % 2 == 0: #num is even if line == '0': #EOF print 'End of experiment' else: #num is odd numList = line.split( ) numList = [int(x) for x in numList] print 'Sample size: ' + str(len(numList)) + ' Results: ' + str(sum(numList)) i += 1 file.close() My results: Sample size: 3 Results: 46 Sample size: 5 Results: 214 Sample size: 4 Results: 86 Sample size: 2 Results: 102 End of experiment Thanks! Answer: Use the file as an iterator, then use [`iterators.islice()`](http://docs.python.org/2/library/itertools.html#itertools.islice) to get every second line: from itertools import islice with open("test_file1.txt", "r") as f: for line in islice(f, 1, None, 2): nums = [int(n) for n in line.split()] print 'Sample size: {} Results: {}'.format(len(nums), sum(nums)) `islice(f, 1, None, 2)` skips the first line (`start=1`), then iterates over all lines (`stop=None`) returning every second line (`step=2`). This'll work with whatever filesize you throw at it; it won't need any more memory than required by the internal iterator buffer. Output for your test file: Sample size: 3 Results: 46 Sample size: 5 Results: 214 Sample size: 4 Results: 86 Sample size: 2 Results: 102
Finding All Neighbours within Range using KD-tree Question: I am trying to implement a [KD-tree](http://en.wikipedia.org/wiki/K-d_tree) for use with [DBSCAN](http://en.wikipedia.org/wiki/DBSCAN). The problem is that I need to find all the neighbours of all points that meet a distance criteria. The problem is I don't get the same output when using the naive search (which is the desired output) as when I use the `nearestNeighbours` method in my implementation. My implementation is adapted from a [python implementation](https://code.google.com/p/python-kdtree/). Here's what I've got so far: //Point.java package dbscan_gui; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; public class Point { final HashSet<Point> neighbours = new HashSet<Point>(); int[] points; boolean visited = false; public Point(int... is) { this.points = is; } public String toString() { return Arrays.toString(points); } public double squareDistance(Point p) { double sum = 0; for (int i = 0;i < points.length;i++) { sum += Math.pow(points[i] - p.points[i],2); } return sum; } public double distance(Point p) { return Math.sqrt(squareDistance(p)); } public void addNeighbours(ArrayList<Point> ps) { neighbours.addAll(ps); } public void addNeighbour(Point p) { if (p != this) neighbours.add(p); } } //KDTree.java package dbscan_gui; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.TreeSet; public class KDTree { KDTreeNode root; PointComparator[] comps; public KDTree(ArrayList<Point> list) { int axes = list.get(0).points.length; comps = new PointComparator[axes]; for (int i = 0; i < axes; i++) { comps[i] = new PointComparator(i); } root = new KDTreeNode(list,0); } private class PointComparator implements Comparator<Point> { private int axis; public PointComparator(int axis) { this.axis = axis; } @Override public int compare(Point p1, Point p2) { return p1.points[axis] - p2.points[axis]; } } /** * Adapted from https://code.google.com/p/python-kdtree/ * Stores points in a tree, sorted by axis */ public class KDTreeNode { KDTreeNode leftChild = null; KDTreeNode rightChild = null; Point location; public KDTreeNode(ArrayList<Point> list, int depth) { if(list.isEmpty()) return; final int axis = depth % (list.get(0).points.length); Collections.sort(list, comps[axis] ); int median = list.size()/2; location = list.get(median); List<Point> leftPoints = list.subList(0, median); List<Point> rightPoints = list.subList(median+1, list.size()); if(!leftPoints.isEmpty()) leftChild = new KDTreeNode(new ArrayList<Point>(leftPoints), depth+1); if(!rightPoints.isEmpty()) rightChild = new KDTreeNode(new ArrayList<Point>(rightPoints),depth+1); } /** * @return true if this node has no children */ public boolean isLeaf() { return leftChild == null && rightChild == null; } } /** * Finds the nearest neighbours of a point that fall within a given distance * @param queryPoint the point to find the neighbours of * @param epsilon the distance threshold * @return the list of points */ public ArrayList<Point> nearestNeighbours(Point queryPoint, int epsilon) { KDNeighbours neighbours = new KDNeighbours(queryPoint); nearestNeighbours_(root, queryPoint, 0, neighbours); return neighbours.getBest(epsilon); } /** * @param node * @param queryPoint * @param depth * @param bestNeighbours */ private void nearestNeighbours_(KDTreeNode node, Point queryPoint, int depth, KDNeighbours bestNeighbours) { if(node == null) return; if(node.isLeaf()) { bestNeighbours.add(node.location); return; } int axis = depth % (queryPoint.points.length); KDTreeNode nearSubtree = node.rightChild; KDTreeNode farSubtree = node.leftChild; if(queryPoint.points[axis] < node.location.points[axis]) { nearSubtree = node.leftChild; farSubtree = node.rightChild; } nearestNeighbours_(nearSubtree, queryPoint, depth+1, bestNeighbours); if(node.location != queryPoint) bestNeighbours.add(node.location); if(Math.pow(node.location.points[axis] - queryPoint.points[axis],2) <= bestNeighbours.largestDistance) nearestNeighbours_(farSubtree, queryPoint, depth+1,bestNeighbours); return; } /** * Private datastructure for holding the neighbours of a point */ private class KDNeighbours { Point queryPoint; double largetsDistance = 0; TreeSet<Tuple> currentBest = new TreeSet<Tuple>(new Comparator<Tuple>() { @Override public int compare(Tuple o1, Tuple o2) { return (int) (o1.y-o2.y); } }); KDNeighbours(Point queryPoint) { this.queryPoint = queryPoint; } public ArrayList<Point> getBest(int epsilon) { ArrayList<Point> best = new ArrayList<Point>(); Iterator<Tuple> it = currentBest.iterator(); while(it.hasNext()) { Tuple t =it.next(); if(t.y > epsilon*epsilon) break; else if(t.x != queryPoint) best.add(t.x); } return best; } public void add(Point p) { currentBest.add(new Tuple(p, p.squareDistance(queryPoint))); largestDistance = currentBest.last().y; } private class Tuple { Point x; double y; Tuple(Point x, double y) { this.x = x; this.y = y; } } } public static void main(String[] args) { int epsilon = 3; System.out.println("Epsilon: "+epsilon); ArrayList<Point> points = new ArrayList<Point>(); Random r = new Random(); for (int i = 0; i < 10; i++) { points.add(new Point(r.nextInt(10), r.nextInt(10))); } System.out.println("Points "+points ); System.out.println("----------------"); System.out.println("Neighbouring Kd"); KDTree tree = new KDTree(points); for (Point p : points) { ArrayList<Point> neighbours = tree.nearestNeighbours(p, epsilon); for (Point q : neighbours) { q.addNeighbour(p); } p.addNeighbours(neighbours); p.printNeighbours(); p.neighbours.clear(); } System.out.println("------------------"); System.out.println("Neighbouring O(n^2)"); for (int i = 0; i < points.size(); i++) { for (int j = i + 1; j < points.size(); j++) { Point p = points.get(i), q = points.get(j); if (p.distance(q) <= epsilon) { p.addNeighbour(q); q.addNeighbour(p); } } } for (Point point : points) { point.printNeighbours(); } } } When I run this I get the following output (the latter part being the model output): Epsilon: 3 Points [[9, 5], [4, 7], [3, 1], [0, 0], [5, 7], [0, 1], [5, 5], [1, 2], [9, 2], [9, 9]] ---------------- Neighbouring Kd Neighbours of [0, 0] are: [[0, 1]] Neighbours of [0, 1] are: [[1, 2], [0, 0], [3, 1]] Neighbours of [1, 2] are: [[0, 1], [3, 1]] Neighbours of [3, 1] are: [[0, 1], [1, 2]] Neighbours of [4, 7] are: [[5, 7]] Neighbours of [5, 7] are: [[4, 7]] Neighbours of [5, 5] are: [[4, 7], [5, 7]] Neighbours of [9, 5] are: [[9, 2]] Neighbours of [9, 2] are: [[9, 5]] Neighbours of [9, 9] are: [] ------------------ Neighbouring O(n^2) Neighbours of [0, 0] are: [[0, 1], [1, 2]] Neighbours of [0, 1] are: [[1, 2], [0, 0], [3, 1]] Neighbours of [1, 2] are: [[0, 1], [0, 0], [3, 1]] Neighbours of [3, 1] are: [[0, 1], [1, 2]] Neighbours of [4, 7] are: [[5, 5], [5, 7]] Neighbours of [5, 7] are: [[4, 7], [5, 5]] Neighbours of [5, 5] are: [[4, 7], [5, 7]] Neighbours of [9, 5] are: [[9, 2]] Neighbours of [9, 2] are: [[9, 5]] Neighbours of [9, 9] are: [] I can't figure out why the neighbours aren't the same, it seems that it can find that a->b is a neighbouring, but not that b->a is also a neighbouring. Answer: You may want to use [ELKI](http://elki.dbs.ifi.lmu.de/) which includes DBSCAN and index structures such as the R*-tree for nearest neighbors search. When parameterized right, it's really really fast. I saw in the trac that the next version will also have a KD-tree. From a quick look at your code, I have to agree with @ThomasJungblut - you do not backtrace and then try the other branch as necessary, which is why you miss a lot of neighbors.
tkinter attribute error Question: I have the class BankAccount that I am using to create a GUI that allows the user to make a deposit, make a withdrawal, and see their balance. This is the BankAccount class code: class BankAccount(object): """ creates a bank account with the owner's name and a balance """ def __init__(self, name, balance = 0): self.__name = name self.__balance = balance def getName(self): """ returns the owner's name """ return self.__name def getBalance(self): """ returns the current balance """ return round(self.__balance, 2) def deposit(self, amount): """ deposits amount into the account """ self.__balance += amount def withdraw(self, amount): """ withdraws amount from the account returns 'overdrawn' if balance is too low """ if self.__balance >= amount: self.__balance -= amount else: return 'overdrawn' def __str__(self): """ return a string representation of the account """ return self.__name + ' has a balance of $' + str(round(self.__balance, 2)) And this is the GUI code: from tkinter import * from bankAccountClass import BankAccount class bankAccountGUI(Frame): def __init__(self): """Set up the GUI""" self.__balance= 0 Frame.__init__(self) self.master.title('Bank Account') self.grid() depositLabel = Label(self, text= "Make Deposit") depositLabel.grid(row = 0, column = 0) self.depositVar= DoubleVar() depositEntry = Entry(self, textvariable= self.depositVar) depositEntry.grid(row = 0, column = 1) withdrawLabel= Label(self, text= "Make Withdrawal") withdrawLabel.grid(row = 1, column = 0) self.withdrawVar = DoubleVar() withdrawEntry= Entry(self, textvariable= self.withdrawVar) withdrawEntry.grid(row = 1, column = 1) button_1= Button(self, text = "Enter", command = self.deposit) button_1.grid(row = 0, column = 2) button_2= Button(self, text = "Enter", command = self.withdrawal) button_2.grid(row = 1, column = 2) def deposit(self): """event handler for button_1""" try: amount= self.depositVar.get() balance= BankAccount.getBalance(self) if amount <= 0: messagebox.showerror(message= 'Deposit must be greater than 0') else: balance= BankAccount.deposit(self, amount) messagebox.showinfo(title= "Current Balance", message= "$" + self.balance, parent= self) except ValueError: messagebox.showerror(message= "Invalid deposit amount") def withdrawal(self): """event handler for button_2""" try: amount= self.withdrawVar.get() balance= BankAccount.getBalance(self) if amount > self.balance: messagebox.showerror(message= "Insufficient funds") else: balance= BankAccount.withdraw(self, amount) messagebox.showinfo(title= "Current Balance", message= "$" + self.balance, parent= self) except ValueError: messagebox.showerror(message= "Invalid withdrawal amount") def main(): """instantiate and pop up the window""" bankAccountGUI().mainloop() I'm getting an error that I don't really know what it means or how to fix it. Exception in Tkinter callback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/tkinter/__init__.py", line 1442, in __call__ return self.func(*args) File "/Users/tinydancer9454/Documents/python/bankAccountGUI.py", line 49, in deposit balance= BankAccount.getBalance(self) File "/Users/tinydancer9454/Documents/python/bankAccountClass.py", line 24, in getBalance return round(self.__balance, 2) AttributeError: 'bankAccountGUI' object has no attribute '_BankAccount__balance' Answer: When you call `balance= BankAccount.getBalance(self)` in your `deposit` function, what you're actually doing is accessing the `getBalance()` method of the `BankAccount` class, using it uninitialized, and trying to pass in a different object as `self`. When you call a method by accessing the class instead of an instance, you do have to give it a `self` object for it to actually work. BankAccount methods expect their `self` objects to be a BankAccount object. You're passing it a BankAccountGUI object instead, which does not contain the `__balance` attribute. That's why its throwing that error. What you should be doing is creating an instance of BankAccount, then using its method: account = BankAccount() balance = account.getBalance() Something like that.
Webpage with Javascript executing Python script with arguments Question: I have three files in the same directory. One is a python script, which takes argumenet. One is a html page with javascript. And the last one is a source .wav file. ./myfolder/sound_manipulation.py ./myfolder/volume_slider.html ./myfolder/the_song.wav The sound_manipulation.py file can be executed like: python sound_manipulation.py -v 50 and it generates a new wav file, new_song.wav, based on the_song.wav, but only has 50% of the original volume level. On the other hand, the volume_slider.html contains a slider goes from 0 to 100%, and a button calling an onclick javascript function, update_vol(); So far, the update_vol() alerts the value of the slider, and that's all. function update_vol() { var vol = document.getElementById('vol_slider').value; alert(vol); } But I want the update_vol() to actually execute the python script using the vol. How can I make that happen? Also, when the "python sound_manipulation.py -v 50" is executed, how can I return the location of the new_song.wav back to volume_slider.html? Please help. Thanks! Answer: the simplest and crudest one-time cgi script might solve your problem. set up a cgi script/environment to just get `volume` value from user / then use `subprocess` module to process the .wav file and send it back to user. if you need anything more than that, build your own web app. import cgi import subprocess import sys form = cgi.FieldStorage() volume = form.getfirst('volume') #read from form 'volume' subprocess.call(['python', 'sound_manipulation.py', '-v', volume]) with open('new_song.wav', 'rb') as wav_file: print("Content-Type: audio/wav\n") sys.stdout.write(wav_file.read())
How to look up the entries added to a table in last 5 seconds using Pymongo in python for mongodb Question: I require to look up the entries added to my mongodb collection which were created or added in the past 10 seconds . At present I do not have timestamp as part of the documents i have inserted into the collection. By reading stuff off google I understood that I can do this somehow using hte object id but I did not understand exactly how can I do it . Answer: You could try: from datetime import datetime from bson.objectid import ObjectId newdate = datetime.utcnow() + timedelta(seconds=-10) dummy_id = ObjectId.from_datetime(newdate) result = collection.find( { "_id": { "$gt": dummy_id } } )
Can't get past a Django ImportError after running manage.py sync.db Question: Very new to coding. I've been trying to install this tablestacker: <http://datadesk.github.io/latimes-table-stacker/> And I'm running into problems with manage.py syncdb, and I can't get past this particular error. My hunch is: I have both Python 2.6 and 2.7 on my computer, and I'm not sure how to make sure everything's running with 2.7. I have a feeling things are being installed for 2.6. Any advice is much appreciated! Thanks in advance. Here is my error: Traceback (most recent call last): File "manage.py", line 14, in <module> execute_manager(settings) File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4.5-py2.7.egg/django/core/management/__init__.py", line 459, in execute_manager utility.execute() File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4.5-py2.7.egg/django/core/management/__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4.5-py2.7.egg/django/core/management/__init__.py", line 261, in fetch_command klass = load_command_class(app_name, subcommand) File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4.5-py2.7.egg/django/core/management/__init__.py", line 69, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4.5-py2.7.egg/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/South-0.7.6-py2.7.egg/south/management/commands/__init__.py", line 10, in <module> import django.template.loaders.app_directories File "/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.4.5-py2.7.egg/django/template/loaders/app_directories.py", line 23, in <module> raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0])) django.core.exceptions.ImproperlyConfigured: ImportError bakery: No module named bakery Answer: Thanks, I did import south, used python manage.py migrate, and created aliases for all python2.7 commands like pip and easy_install so to be sure I'm not using 2.6.
How to call numpy/scipy C functions from Cython directly, without Python call overhead? Question: I am trying to make calculations in Cython that rely heavily on some numpy/scipy mathematical functions like `numpy.log`. I noticed that if I call numpy/scipy functions repeatedly in a loop in Cython, there are huge overhead costs, e.g.: import numpy as np cimport numpy as np np.import_array() cimport cython def myloop(int num_elts): cdef double value = 0 for n in xrange(num_elts): # call numpy function value = np.log(2) This is very expensive, presumably because `np.log` goes through Python rather than calling the numpy C function directly. If I replace that line with: from libc.math cimport log ... # calling libc function 'log' value = log(2) then it's much faster. However, when I try to pass a numpy array to libc.math.log: cdef np.ndarray[long, ndim=1] foo = np.array([1, 2, 3]) log(foo) it gives this error: TypeError: only length-1 arrays can be converted to Python scalars My questions are: 1. Is it possible to call the C function and pass it a numpy array? Or can it only be used on scalar values, which would require me to write a loop (eg if I wanted to apply it to the `foo` array above.) 2. Is there an analogous way to call scipy functions from C directly without a Python overhead? Which how can I import scipy's C function library? Concrete example: say you want to call many of scipy's or numpy's useful statistics functions (e.g. `scipy.stats.*`) on scalar values inside a `for` loop in Cython? It's crazy to reimplement all those functions in Cython, so their C versions have to be called. For example, all the functions related to pdf/cdf and sampling from various statistical distributions (e.g. see <http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.pdf.html#scipy.stats.rv_continuous.pdf> and <http://www.johndcook.com/distributions_scipy.html>) If you call these functions with Python overhead in a loop, it'll be prohibitively slow. thanks. Answer: You cannot apply C functions such as log on numpy arrays, and numpy does not have a C function library that you can call from cython. Numpy functions are already optimized to be called on numpy arrays. Unless you have a very unique use case, you're not going to see much benefit from reimplementing numpy functions as C functions. (It's possible that some functions in numpy are not implemented well, in chich case consider submitting your importations as patches.) However you do bring up a good point. # A from libc.math cimport log for i in range(N): r[i] = log(foo[i]) # B r = np.log(foo) # C for i in range(n): r[i] = np.log(foo[i]) In general, A and B should have similar run times, but C should be avoided and will be much slower. Update Here is the code for scipy.stats.norm.pdf, as you can see it's written in python with numpy and scipy calls. There is no C version of this code, you have to call it "through python". If this is what is holding you back, you'll need to re-implant it in C/Cython, but first I would spend some time very carefully profiling the code to see if there are any lower hanging fruit to go after first. def pdf(self,x,*args,**kwds): loc,scale=map(kwds.get,['loc','scale']) args, loc, scale = self._fix_loc_scale(args, loc, scale) x,loc,scale = map(asarray,(x,loc,scale)) args = tuple(map(asarray,args)) x = asarray((x-loc)*1.0/scale) cond0 = self._argcheck(*args) & (scale > 0) cond1 = (scale > 0) & (x >= self.a) & (x <= self.b) cond = cond0 & cond1 output = zeros(shape(cond),'d') putmask(output,(1-cond0)+np.isnan(x),self.badvalue) if any(cond): goodargs = argsreduce(cond, *((x,)+args+(scale,))) scale, goodargs = goodargs[-1], goodargs[:-1] place(output,cond,self._pdf(*goodargs) / scale) if output.ndim == 0: return output[()] return output
python3 datetime.datetime.strftime failed to accept utf-8 string format Question: python3 `datetime.datetime.strftime` failed to accept utf-8 string format what I did is:: # encoding: utf-8 import datetime f = "%Y年%m月%d日" now = datetime.datetime.now() print( now.strftime(f) ) and what I get is: D:\pytools>python a.py Traceback (most recent call last): File "a.py", line 6, in <module> print( now.strftime(f) ) UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2 : Illegal byte sequence Why and how can I fix this? Answer: ~~The problem is not in`datetime`, it's in `print`. See [PrintFails](http://wiki.python.org/moin/PrintFails)~~ Ah, it's not exactly that - although it has the same cause, and you're likely to have that problem writing Unicode to stdout. (Using an IDE with a Python shell eg an up-to-date IDLE, avoids this.) The `strftime()` function which is what `datetime.strftime()` ends up calling, is part of the C standard library, which under Windows/MSVCRT can't deal with Unicode strings. (Although in theory you could work around it by setting code page to 65001 and using UTF-8, there are serious long-standing bugs in the C runtime for that code page.) Workaround in Python could be to replace out the non-ASCII characters until after the call: strftime('%Y{0}%m{1}%d{2}').format(*'年月日') Or to eschew `strftime` and do it yourself. This should probably be considered a bug in `time.strftime()` and fixed there, by either of these means. It would make sense to add a Python-native implementation of `strftime` \- they have already had to do the same for `strptime` due to other platform bugs in that function.
Reading files and regex with PYTHON Question: i'm beginner in python and in programming in general, I'd like to create a script in python that can tell if the message was sent or not. after reading log files I've noticed that each message has a **mid** so i got an idea but i'm not sure... if i save all the mid in a list or dictionary i'll be able to compare it with the line that has the mid+**\s** +"**OK** " or "**Error** " here's a part of my log file ( the mid's are incremented by one each time. ) can someone help me out to start ? because i have no idea how to start this.. Thanks in advance 01:09:25.258 mta Messages I Doc O:NVS:SMTP/[email protected] R:NVS:SMS.0/+01542xx **mid:6261** 01:09:41.965 mta Messages I Rep O:NVS:SMTP/[email protected] R:NVS:SMS.0/+01542xx **mid:6261** 01:09:41.965 mta Messages I Rep **6261** OK, Accepted (ID: 26) Answer: I would suggest the following: Let's assume that the log file isn't too big to fit in memory. import re with open("myfile.log") as infile: data = infile.read() First, find all the message IDs in your file: messages = set(m.group(1) for m in re.finditer(r"\*\*mid:(\d+)\*\*", data)) Now, find all the message IDs for which there exists an `OK` line successes = set(m.group(1) for m in re.finditer(r"\*\*(\d+)\*\*\s*OK", data)) The difference between the two is the set of IDs that have no `OK` message: failures = messages - successes
what's the type of read() function's return value in python? Question: I write a program in python here. I wanna read a binary file, read first 188 Bytes, and check whether the first character is 0x47. Code below: import os fp=open("try.ts","rb") for i in range(100): buf=fp.read(188) if buf[0]=="\x47" print "OK" fp.close() But it goes wrong as follows: if buf[0]=="\x47" ^ SyntaxError: invalid syntax What I wanna ask are: 1. What's the type of a return value in read() function? 2. How can I get the first character in a string or array? * * * Thanks, I miss the colon. But when I add it,it shows that: if buf[0]=="\x47": IndexError: string index out of range Still wrong ? Answer: 1. `str` 2. You forgot the colon: `if buf[0] == "\x47":` * * * if buf[0]=="\x47": IndexError: string index out of range That means your `buf` is empty. You overwrote it 100 times in your loop. The file probably doesn't have 18800 bytes in it. At the end of a file `read` just returns an empty string. Did you mean to put your `if` inside the `for`? If so, indent it accordingly.
Python - find average for columns with unique matching value in nested list Question: This is very similar to this question: [Finding minimum, maximum and average values for nested lists?](http://stackoverflow.com/questions/9858739/finding- minimum-maximum-and-average-values-for-nested-lists) The important difference and root of the question being I would like to find min, max, average within a list (nested within a list) for each unique column name (person's name). For example: Each line is basically (with similar fictitious names)- epochtime, name, score, level, extralives e.g. 1234455, suzy, 120, 3, 0 1234457, billy, 123, 1, 2 1234459, billy, 124, 2, 4 1234459, suzy, 224, 5, 4 1234460, suzy, 301, 7, 1 1234461, billy, 201, 3, 1 And these are placed in a list by time: if epochtime < 1234500 and epochtime > 1234400: timechunk1.append(line) There's a list of lists with each of the time chunks: listoflists = [timechunk1, timechunk2....] _This may or may not be overkill / extraneous for this question._ How do I find min, max, average values for each field (score, level, extralives) for each unique name (billy or suzy - _there are many more than just billy or suzy, so it'd be much better not to list them individually_) in each list (timechunk1, timechunk2)? Answer: [pandas](http://pandas.pydata.org) example: >>> import pandas as pd >>> df = pd.read_csv("grouped.csv", sep="[,\s]*") >>> df epochtime name score level extralives 0 1234455 suzy 120 3 0 1 1234457 billy 123 1 2 2 1234459 billy 124 2 4 3 1234459 suzy 224 5 4 4 1234460 suzy 301 7 1 5 1234461 billy 201 3 1 >>> g = df.groupby("name").describe() >>> g epochtime score level extralives name billy count 3.000000 3.000000 3.0 3.000000 mean 1234459.000000 149.333333 2.0 2.333333 std 2.000000 44.747439 1.0 1.527525 min 1234457.000000 123.000000 1.0 1.000000 25% 1234458.000000 123.500000 1.5 1.500000 50% 1234459.000000 124.000000 2.0 2.000000 75% 1234460.000000 162.500000 2.5 3.000000 max 1234461.000000 201.000000 3.0 4.000000 suzy count 3.000000 3.000000 3.0 3.000000 mean 1234458.000000 215.000000 5.0 1.666667 std 2.645751 90.835015 2.0 2.081666 min 1234455.000000 120.000000 3.0 0.000000 25% 1234457.000000 172.000000 4.0 0.500000 50% 1234459.000000 224.000000 5.0 1.000000 75% 1234459.500000 262.500000 6.0 2.500000 max 1234460.000000 301.000000 7.0 4.000000 Or simply: >>> df.groupby("name").mean() epochtime score level extralives name billy 1234459 149.333333 2 2.333333 suzy 1234458 215.000000 5 1.666667 And then: >>> g.ix[("billy","mean")] epochtime 1234459.000000 score 149.333333 level 2.000000 extralives 2.333333 Name: (billy, mean), dtype: float64 >>> g.ix[("billy","mean")]["score"] 149.33333333333334 >>> g["score"] name billy count 3.000000 mean 149.333333 std 44.747439 min 123.000000 25% 123.500000 50% 124.000000 75% 162.500000 max 201.000000 suzy count 3.000000 mean 215.000000 std 90.835015 min 120.000000 25% 172.000000 50% 224.000000 75% 262.500000 max 301.000000 Name: score, dtype: float64 Et cetera. If you're thinking in R/SQL ways, but want to use Python, then definitely give pandas a try. Note that you can also do multi-column groupbys: >>> df.groupby(["epochtime", "name"]).mean() score level extralives epochtime name 1234455 suzy 120 3 0 1234457 billy 123 1 2 1234459 billy 124 2 4 suzy 224 5 4 1234460 suzy 301 7 1 1234461 billy 201 3 1
Python Game of inbetween - can't get if-elif to work Question: trying to make a game in Python.. although I can't seem to get a certain bit of code working?! It's driving me nuts! Any help is greatly appreciated! import random die1 = random.randint(1,10) die2 = random.randint(1,10) die3 = random.randint(1,10) if die1 > die2: print ('Die 1:', die2,' Die 2:', die1,) else: print ('Die 1:', die1,' Die 2:', die2,) if die1 == die2 or die2 == die1: print('\nEven-steven!') else: print('\nNot the same, let\'s play!') print ('\nDie 3:', die3,) if die3 > die1 and die3 < die2 or die3 < die1 and die3 > die2: print ('\n*** You win! ***') elif die1 > die2: if die3 < die2 or die3 > die1: print('\n*** Sorry - You lose! ***') elif die2 > die1: if die3 < die1 or die3 > die2: print('\n*** Sorry - You lose! ***') **elif die3 == die1 or die3 == die2: print ('\n*** You hit the post - You lose double your bet! ***')** print ('\nThanks for playing!') It's in the second if statement structure, and for whatever reason if die1 or die2 are the same as die3, it just won't print 'You hit the post...' it just ends! Thanks! Answer: Your diagnosis is incorrect. The last statement _will_ match if `die3` is equal to either `die1` or `die2`: >>> die1, die2 = 1, 2 >>> die3 = die1 >>> die3 == die1 or die3 == die2 True >>> die3 = die2 >>> die3 == die1 or die3 == die2 True However, if `die1` is greater than `die2` your _first_ `elif` matches, but your comparison to `die3` is flawed: >>> die1, die2 = 2, 1 >>> die3 = die1 >>> die3 < die2 or die3 > die1 False and _nothing_ is ever printed. You need to clean up the logic for that case. Since you only have 3 different outcomes; winning, losing and hitting the post, you can really simplify the whole thing down to: if die1 < die3 < die2: print('\n*** You win! ***') elif die3 == die1 or die3 == die2: print('\n*** You hit the post - You lose double your bet! ***') else: print('\n*** Sorry - You lose! ***') Note that I used [chained comparisons](http://docs.python.org/2/reference/expressions.html#not-in) to simplify the first `if` expression some more. You also made sure that `die1` is lower than `die2`, so testing for `die2 < die3 < die1` is _always_ going to be `False`. Another note: `==` should be transitive, so `die1 == die2 or die2 == die1` is redundant. You can simplify that to just `die1 == die2`. Simplifying your whole program: import random die1 = random.randint(1,10) die2 = random.randint(1,10) if die1 > die2: die1, die2 = die2, die1 print ('Die 1:', die1,' Die 2:', die2,) if die1 == die2: print('Even-steven!') else: print("Not the same, let's play!") die3 = random.randint(1,10) print ('Die 3:', die3) if die1 < die3 < die2: print('\n*** You win! ***') elif die3 == die1 or die3 == die2: print('\n*** You hit the post - You lose double your bet! ***') else: print('\n*** Sorry - You lose! ***') print ('Thanks for playing!')
class PCA matplotlib for face recognition Question: I am trying to make face recognition by Principal Component Analysis (PCA) using python. I am using class `pca` found in `matplotlib`. Here is it's documentation: > class matplotlib.mlab.PCA(a) compute the SVD of a and store data for PCA. > Use project to project the data onto a reduced set of dimensions > > > Inputs: > a: a numobservations x numdims array > Attrs: > a a centered unit sigma version of input a > numrows, numcols: the dimensions of a > mu : a numdims array of means of a > sigma : a numdims array of atandard deviation of a > fracs : the proportion of variance of each of the principal components > Wt : the weight vector for projecting a numdims point or array into PCA > space > Y : a projected into PCA space > The factor loadings are in the Wt factor, ie the factor loadings for the 1st principal component are given by Wt[0] And here is my code: import os from PIL import Image import numpy as np import glob import numpy.linalg as linalg from matplotlib.mlab import PCA #Step 1: put database images into a 2D array filenames = glob.glob('C:\\Users\\Karim\\Downloads\\att_faces\\New folder/*.pgm') filenames.sort() img = [Image.open(fn).convert('L').resize((90, 90)) for fn in filenames] images = np.asarray([np.array(im).flatten() for im in img]) #Step 2: database PCA results = PCA(images.T) w = results.Wt #Step 3: input image input_image = Image.open('C:\\Users\\Karim\\Downloads\\att_faces\\1.pgm').convert('L') input_image = np.asarray(input_image) #Step 4: input image PCA results_in = PCA(input_image) w_in = results_in.Wt #Step 5: Euclidean distance d = np.sqrt(np.sum(np.asarray(w - w_in)**2, axis=1)) But I am getting an error: Traceback (most recent call last): File "C:/Users/Karim/Desktop/Bachelor 2/New folder/matplotlib_pca.py", line 32, in <module> d = np.sqrt(np.sum(np.asarray(w - w_in)**2, axis=1)) ValueError: operands could not be broadcast together with shapes (30,30) (92,92) 1. Can anyone help me to correct the error? 2. Is that the correct way for face recognition? Answer: The error is telling you that the two arrays (`w` and `w_in`) are not the same size and `numpy` can not figure out how to broadcast the values to take the difference. I am not familiar with this function, but I would guess that the source of the issue is your input images are different sizes.
Matplotlib cmap values must be between 0-1 Question: I am having trouble with the code below: import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np from pylab import * import sys s = (('408b2e00', '24.21'), ('408b2e0c', '22.51'), ('4089e04a', '23.44'), ('4089e04d', '24.10')) temp = [x[1] for x in s] print temp figure(figsize=(15, 8)) pts = [(886.38864047695108, 349.78744809964849), (1271.1506973277974, 187.65500904929195), (1237.272277227723, 860.38363675077176), (910.58751197700428, 816.82566805067597)] x = map(lambda x: x[0],pts) # Extract the values from pts y = map(lambda x: x[1],pts) t = temp result = zip(x,y,t) img = mpimg.imread('floor.png') imgplot = plt.imshow(img, cmap=cm.hot) scatter(x, y, marker='h', c=t, s=150, vmin=-20, vmax=40) print t # Add cmap colorbar() show() Given the temperature in s - I am trying to set the values of the cmap so I can use temperatures between -10 and 30 instead of having to used values between 1 and 0. I have set the vmin and vmax values but it still gives me the error below: ValueError: to_rgba: Invalid rgba arg "23.44" to_rgb: Invalid rgb arg "23.44" gray (string) must be in range 0-1 I have use earlier code to simplify the problem and have been successful. This example below works and shows what I am trying to (hopefully) do: import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np from pylab import * figure(figsize=(15, 8)) # use ginput to select markers for the sensors matplotlib.pyplot.hot() markers = [(269, 792, -5), (1661, 800, 20), (1017, 457, 30)] x,y,t = zip(*markers) img = mpimg.imread('floor.png') imgplot = plt.imshow(img, cmap=cm.hot) scatter(x, y, marker='h', c=t, s=150, vmin=-10, vmax=30) colorbar() show() Any ideas why only the second solution works? I am working with dynamic values i.e inputs from mysql and user selected points and so the first solution would be much easier to get working later on (the rest of that code is in this question: [Full program code](http://stackoverflow.com/questions/15888693/python-matplotlib-and-mysql- and-ginput) ) Any help would be great. Thanks! Answer: You are handing in strings instead of floats, change this line: temp = [float(x[1]) for x in s] `matplotlib` tries to be good about guessing what you mean and lets you define gray as a string of a float between [0, 1] which is what it is trying to do with your string values (and complaining because it is not in than range).
plotting orbital trajectories in python Question: How can I setup the three body problem in python? How to I define the function to solve the ODEs? The three equations are `x'' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * x`, `y'' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * y`, and `z'' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * z`. Written as 6 first order we have `x' = x2`, `y' = y2`, `z' = z2`, `x2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * x`, `y2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * y`, and `z2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * z` I also want to add in the path Plot o Earth's orbit and Mars which we can assume to be circular. Earth is `149.6 * 10 ** 6` km from the sun and Mars `227.9 * 10 ** 6` km. #!/usr/bin/env python # This program solves the 3 Body Problem numerically and plots the trajectories import pylab import numpy as np import scipy.integrate as integrate import matplotlib.pyplot as plt from numpy import linspace mu = 132712000000 #gravitational parameter r0 = [-149.6 * 10 ** 6, 0.0, 0.0] v0 = [29.0, -5.0, 0.0] dt = np.linspace(0.0, 86400 * 700, 5000) # time is seconds Answer: As you've shown, you can write this as a system of six first-order ode's: x' = x2 y' = y2 z' = z2 x2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * x y2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * y z2' = -mu / np.sqrt(x ** 2 + y ** 2 + z ** 2) * z You can save this as a vector: u = (x, y, z, x2, y2, z2) and thus create a function that returns its derivative: def deriv(u, t): n = -mu / np.sqrt(u[0]**2 + u[1]**2 + u[2]**2) return [u[3], # u[0]' = u[3] u[4], # u[1]' = u[4] u[5], # u[2]' = u[5] u[0] * n, # u[3]' = u[0] * n u[1] * n, # u[4]' = u[1] * n u[2] * n] # u[5]' = u[2] * n Given an initial state `u0 = (x0, y0, z0, x20, y20, z20)`, and a variable for the times `t`, this can be fed into `scipy.integrate.odeint` as such: u = odeint(deriv, u0, t) where `u` will be the list as above. Or you can unpack `u` from the start, and ignore the values for `x2`, `y2`, and `z2` (you must transpose the output first with `.T`) x, y, z, _, _, _ = odeint(deriv, u0, t).T
libxml2.so.2: cannot open shared object file: No such file or directory Question: I am using Centos in which i had removed libxml2 accidentally now it was showing the folling error as follows There was a problem importing one of the Python modules required to run yum. The error leading to this problem was: libxml2.so.2: cannot open shared object file: No such file or directory Please install a package which provides this module, or verify that the module is installed correctly. It's possible that the above module doesn't match the current version of Python, which is: 2.4.3 (#1, Jun 18 2012, 08:55:31) [GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] If you cannot solve this problem yourself, please go to the yum faq at: <http://wiki.linux.duke.edu/YumFaq> Answer: You need to reinstall the libxml2 package. Since yum is currently broken on your system, you will need to obtain the libxml2 package by another means, such as using `yumdownloader` on another (working) system or by visiting your repositories website or from one of the CentOS mirrors. For example here is a link to [the CentOS5.9 libxml2 rpm for i386](http://mirrors.usc.edu/pub/linux/distributions/centos/5.9/updates/i386/RPMS/libxml2-2.6.26-2.1.21.el5_9.2.i386.rpm) .
Runge–Kutta RK4 not better than Verlet? Question: I'm just testing several integration schemes for orbital dynamics in game. I took RK4 with constant and adaptive step here <http://www.physics.buffalo.edu/phy410-505/2011/topic2/app1/index.html> and I compared it to simple verlet integration (and euler, but it has very very poor performance). It doesnt seem that RK4 with constant step is better than verlet. RK4 with adaptive step is better, but not so much. I wonder if I'm doing something wrong? Or in which sense it is said that RK4 is much superior to verlet? The think is that Force is evaluated 4x per RK4 step, but only 1x per verlet step. So to get same performance I can set time_step 4x smaller for verlet. With 4x smaller time step verlet is more precise than RK4 with constant step and almost comparable with RK4 with addaptive step. See the image: <https://lh4.googleusercontent.com/-I4wWQYV6o4g/UW5pK93WPVI/AAAAAAAAA7I/PHSsp2nEjx0/s800/kepler.png> 10T means 10 orbital periods, the following number 48968,7920,48966 is number of force evaluations needed the python code (using pylab) is following: from pylab import * import math G_m1_plus_m2 = 4 * math.pi**2 ForceEvals = 0 def getForce(x,y): global ForceEvals ForceEvals += 1 r = math.sqrt( x**2 + y**2 ) A = - G_m1_plus_m2 / r**3 return x*A,y*A def equations(trv): x = trv[0]; y = trv[1]; vx = trv[2]; vy = trv[3]; ax,ay = getForce(x,y) flow = array([ vx, vy, ax, ay ]) return flow def SimpleStep( x, dt, flow ): x += dt*flow(x) def verletStep1( x, dt, flow ): ax,ay = getForce(x[0],x[1]) vx = x[2] + dt*ax; vy = x[3] + dt*ay; x[0]+= vx*dt; x[1]+= vy*dt; x[2] = vx; x[3] = vy; def RK4_step(x, dt, flow): # replaces x(t) by x(t + dt) k1 = dt * flow(x); x_temp = x + k1 / 2; k2 = dt * flow(x_temp) x_temp = x + k2 / 2; k3 = dt * flow(x_temp) x_temp = x + k3 ; k4 = dt * flow(x_temp) x += (k1 + 2*k2 + 2*k3 + k4) / 6 def RK4_adaptive_step(x, dt, flow, accuracy=1e-6): # from Numerical Recipes SAFETY = 0.9; PGROW = -0.2; PSHRINK = -0.25; ERRCON = 1.89E-4; TINY = 1.0E-30 scale = flow(x) scale = abs(x) + abs(scale * dt) + TINY while True: x_half = x.copy(); RK4_step(x_half, dt/2, flow); RK4_step(x_half, dt/2, flow) x_full = x.copy(); RK4_step(x_full, dt , flow) Delta = (x_half - x_full) error = max( abs(Delta[:] / scale[:]) ) / accuracy if error <= 1: break; dt_temp = SAFETY * dt * error**PSHRINK if dt >= 0: dt = max(dt_temp, 0.1 * dt) else: dt = min(dt_temp, 0.1 * dt) if abs(dt) == 0.0: raise OverflowError("step size underflow") if error > ERRCON: dt *= SAFETY * error**PGROW else: dt *= 5 x[:] = x_half[:] + Delta[:] / 15 return dt def integrate( trv0, dt, F, t_max, method='RK4', accuracy=1e-6 ): global ForceEvals ForceEvals = 0 trv = trv0.copy() step = 0 t = 0 print "integrating with method: ",method," ... " while True: if method=='RK4adaptive': dt = RK4_adaptive_step(trv, dt, equations, accuracy) elif method=='RK4': RK4_step(trv, dt, equations) elif method=='Euler': SimpleStep(trv, dt, equations) elif method=='Verlet': verletStep1(trv, dt, equations) step += 1 t+=dt F[:,step] = trv[:] if t > t_max: break print " step = ", step # ============ MAIN PROGRAM BODY ========================= r_aphelion = 1 eccentricity = 0.95 a = r_aphelion / (1 + eccentricity) T = a**1.5 vy0 = math.sqrt(G_m1_plus_m2 * (2 / r_aphelion - 1 / a)) print " Semimajor axis a = ", a, " AU" print " Period T = ", T, " yr" print " v_y(0) = ", vy0, " AU/yr" dt = 0.0003 accuracy = 0.0001 # x y vx vy trv0 = array([ r_aphelion, 0, 0, vy0 ]) def testMethod( trv0, dt, fT, n, method, style ): print " " F = zeros((4,n)); integrate(trv0, dt, F, T*fT, method, accuracy); print "Periods ",fT," ForceEvals ", ForceEvals plot(F[0],F[1], style ,label=method+" "+str(fT)+"T "+str( ForceEvals ) ); testMethod( trv0, dt, 10, 20000 , 'RK4', '-' ) testMethod( trv0, dt, 10, 10000 , 'RK4adaptive', 'o-' ) testMethod( trv0, dt/4, 10, 100000, 'Verlet', '-' ) #testMethod( trv0, dt/160, 2, 1000000, 'Euler', '-' ) legend(); axis("equal") savefig("kepler.png") show(); Answer: I know this question is quite old by now, but this really has nothing to do with the "superiority" of one of these methods over the other, or with your programming of them - they're just good at different things. (So no, this answer won't really be about code. Or even about programming. It's more about math, really...) The Runge-Kutta family of solvers are pretty good at attacking almost any problem with quite good precision and, in case of the adaptive methods, performance. However, they are not [symplectic](http://en.wikipedia.org/wiki/Symplectic_integrator), which shortly means that they do not conserve energy in the problem. The Verlet method on the other hand, may require a much smaller step size than the RK methods in order to minimize oscillations in the solution, but the method is symplectic. Your problem is energy-conserving; after an arbitrary number of revolutions, the planetary body's total energy (kinetic + potential) should be the same as it was with the initial conditions. This will be true with a Verlet integrator (at least as a time-windowed average), but it will not with an integrator from the RK family - over time, the RK solvers will build up an error that is not reduced, due to energy lost in the numerical integration. To verify this, try saving the total energy in the system at each time step, and plot it (you might have to do much more than ten revolutions to notice the difference). The RK method will have steadily decreasing energy, while the Verlet method will give an oscillation around a constant energy. If this is the exact problem you need to solve, I also recommend the Kepler equations, which solve this problem analytically. Even for rather complex systems with many planets, moons etc, the interplanetary interactions are so insignificant that you can use the Kepler equations for each body and it's rotational center individually without much loss of precision. However, if you're writing a game you might really be interested in some other problem, and this was just an example to learn - in that case, read up on the properties of the various solver families, and choose one that is appropriate for your problems.
ImportError: The _imaging C module is not installed? PIL Python3 Question: root@syscomp1:~# cd Pillow-master root@syscomp1:~/Pillow-master# python3 selftest.py Traceback (most recent call last): File "selftest.py", line 8, in <module> from PIL import Image File "./PIL/Image.py", line 155, in <module> if hasattr(core, 'DEFAULT_STRATEGY'): File "./PIL/Image.py", line 39, in __getattr__ raise ImportError("The _imaging C module is not installed") ImportError: The _imaging C module is not installed root@syscomp1:~/Pillow-master# ## this is the step before i install PIL sudo apt-get install python-pip python-dev build-essential sudo pip install --upgrade pip sudo pip install --upgrade virtualenv sudo aptitude install python3-setuptools sudo easy_install3 pip sudo apt-get install python3-dev download the Pillow-master.zip wget https://github.com/python-imaging/Pillow/archive/master.zip go to downloaded directory and, sudo unzip master.zip sudo apt-get install libjpeg62-dev //must install this sudo apt-get install zlib1g-dev sudo apt-get install libfreetype6-dev sudo apt-get install liblcms1-dev python3 setup.py build_ext -i but error with `The _imaging C module is not installed` why? Answer: Looks like a Python 2 print statement in setup.py: Downloading from URL http://effbot.org/media/downloads/PIL-1.1.7.tar.gz (from http://effbot.org/downloads/) Running setup.py egg_info for package pil Traceback (most recent call last): File "<string>", line 16, in <module> File "<pyenv>/build/pil/setup.py", line 182 print "--- using Tcl/Tk libraries at", TCL_ROOT
smart way to read multiple variables from textfile in python Question: I'm trying to load multiple vectors and matrices (for numpy) that are stored in a single text file. The file looks like this: %VectorA 1 2 3 4 %MatrixA 1 2 3 4 5 6 %VectorB 3 4 5 6 7 The ideal solution would be to have a dictionary object like: {'VectorB': [3, 4, 5, 6, 7], 'VectorA': [1, 2, 3, 4], 'MatrixA':[[1, 2, 3],[4, 5, 6]]} The order of the variables can be assumed as fixed. So, a list of the numpy arrays in the order of appearance in the text file would also be okay. Answer: from StringIO import StringIO mytext='''%VectorA 1 2 3 4 %MatrixA 1 2 3 4 5 6 %VectorB 3 4 5 6 7''' myfile=StringIO(mytext) mydict={} for x in myfile.readlines(): if x.startswith('%'): mydict.setdefault(x.strip('%').strip(),[]) lastkey=x.strip('%').strip() else: mydict[lastkey].append([int(x1) for x1 in x.split(' ')]) above gives `mydict` as: {'MatrixA': [[1, 2, 3], [4, 5, 6]], 'VectorA': [[1, 2, 3, 4]], 'VectorB': [[3, 4, 5, 6, 7]]}
2d matrix composed from 1d matrices in python Question: A newbie question and possible duplicate: How can one compose a matrix in numpy using arrays or 1d matrices? In matlab, I would use following syntax for the matrix consisting of three arrays treated as rows: A=[1; 1; 1]; B=[2; 2; 2]; C=[3; 3; 3]; D=[A B C] The result is: D = 1 2 3 1 2 3 1 2 3 Thank you Answer: You should do import numpy as np A = np.array([1, 1, 1]) B = np.array([2, 2, 2]) C = np.array([3, 3, 3]) D = np.vstack((A, B, C)) See [NumPy for MATLAB users](http://mathesaurus.sourceforge.net/matlab- numpy.html) (official link seems to be down)
Having problems with making an .exe with cx_freeze with python and pygame, including additional files Question: I'm having trouble creating an .exe file with cx_Freeze. I'm trying to use [this](http://pastebin.com/kRFX0QEf "this") Pygame game which needs some .png's, .gif's and .ogg's to run. I have tried to compile a simple Python only (no pygame or additional files) using the commmand line and a setup.py, but neither worked and I'm a bit out of my death. I have installed cx_Freeze and checked it worked with ''import cx_freeze' in the IDLE not throwing an error. I'm using Python 3.3 on Windows 7 with the correct versions of pygame and cx_freeze for my python version. Can anyone assist me in creating this .exe? Answer: To include files in your `.exe` you should write a `setup.py` file that is similar to this: from cx_Freeze import setup, Executable exe=Executable( script="file.py", base="Win32Gui", icon="Icon.ico" ) includefiles=["file.ogg","file.png",etc] includes=[] excludes=[] packages=[] setup( version = "0.0", description = "No Description", author = "Name", name = "App name", options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}}, executables = [exe] )
Using re.findall in python outputting one set of parameters rather than a set of parameters for each line Question: I've used `readlines` to split all of the sentences in a file up and I want to use `re.findall` to go through and find the capitals within them. However, the only output I can get is one set of capitals for all the sentences but I want a set of capitals for each sentence in the file. I'm using a for loop to attempt this at the moment, but I'm not sure whether this is the best course of action with this task. Input: Line 01: HE went to the SHOP Line 02: THE SHOP HE went This is what I'm getting as an output: [HE, SHOP, THE] and I want to get the output: [HE, SHOP], [THE, SHOP, HE] Is there a way of doing this? I've put my coding at the minute below. Thanks! import re, sys f = open('findallEX.txt', 'r') lines = f.readlines() ii=0 for l in lines: sys.stdout.write('line %s: %s' %(ii, l)) ii = ii + 1 for x in l re.findall('[A-Z]+', l) print x Answer: I think the way to do that is as follows: txt = """HE went to the SHOP THE SHOP HE went""" result = [] for s in txt.split('\n'): result += [re.findall(r'[A-Z]+', s)] print(result) # prints [['HE', 'SHOP'], ['THE', 'SHOP', 'HE']] Or using list comprehensions (a bit less readable): txt = """HE went to the SHOP THE SHOP HE went""" print([re.findall(r'[A-Z]+', s) for s in txt.split('\n')])
Trying to read information in a file into two lists in Python Question: I think this is a relatively simple question but i'm a beginner and having trouble. I have to read in information from a text file into two lists in python. This is an example of what the text file looks like, it is called 'ratings.txt' and the three colums are movieId|numberofRatings|averageRatings. 1|452|3.9 2|131|3.2 3|90|3 4|209|3.6 ... ... 1321|2|2.5 ... ... 1685|0|-nan 1686|0|-nan I need to read in the second and third columns of numbers into two separate arrays. the second column of numbers needs to be read into a list numRatings. and the third column needs to be read into a list avgRatings. the text file goes from movies 1 to 1686 so `numRatings` needs to be `[452,131,90,....0,0]` and `avgRating` needs to be `[3.9,3.2,3,....-nan,-nan]` I think I have to create the lists, and then create loops to read through the text file and store these numbers in the array. here is my code so far f = open("ratings.txt") #opens the text file line = f.readline() #reads in one line of the file a = line.split("|") #splits the line of the file, for example line 1 looks like [1, 452, 3.9] in the above code if I print `a[0]`, `a[1]` and `a[2]` I get `1`, `452`, and `3.9` respectively. How do I do this over and over again and store my results into the arrays? Answer: You really have a CSV-style file, so use the [`csv` module](http://docs.python.org/2/library/csv.html): import csv results = [] with open('ratings.txt', 'rb') as f: reader = csv.reader(f, delimiter='|') for row in reader: results.append(row) You could augment this as needed; append the second and third columns to separate lists, converting them to `int`s and `float()`s, for example: numRatings = [] avgRating = [] with open('ratings.txt', 'rb') as f: reader = csv.reader(f, delimiter='|') for row in reader: numRatings.append(int(row[1])) avgRating.append(float(row[2])) If this _were not_ a CSV-style file, you'd still use a loop; you'd loop directly over the file object: with open('ratings.txt', 'rb') as f: for line in f: a = line.strip().split("|")
Is it possible to replace a string (zipped) code from apk dalvik Question: I would like to replace a single string from the hex/dalvik apk code. I realize this would entail finding how the string gets encoded when it is converted from an Android class project into a signed apk file. Is this possible? Well, I know in code, anythings possible.. but does anyone here know how to do it? I have learned that it's possible to delete and add to .apk files on a windows platform with a simple zip archive (such as replacing icons for the SystemUI.apk), without breaking the apk.. but how would one do it programmatically? Specifically in python? Does anyone have any ideas on how to do this? I have tried: import zipfile zf=zipfile.ZipFile('APK.apk') # my zip file for filename in ['classes.dex']: # zipped file content file data=zf.read(filename) data=data.replace('mystring','newstring') #replace string within the content file file=open('classes.dex','wb') file.write(data) # write NEW content file to local disk file.close() zin=zipfile.ZipFile('APK.apk','r') # create zip in and zip out zout=zipfile.ZipFile('APK.apk','w') # iterate through zipped contents and for item in zin.infolist(): # copy all EXCEPT 'classes.dex' content file buffer=zin.read(item.filename) if (item.filename!='classes.dex'): zout.writestr(item,buffer) zout.close() zin.close() zf=zipfile.ZipFile('APK.apk',mode='a') # finally, add new content file from my local disk zf.write('classes.dex',arcname='classes.dex') zf.close() This takes the original APK.apk file, and rewrites a string within one of the zipped content files, then repacking it back to APK.apk. Problem is: ORIGINAL APK.apk = 170 kb NEW APK.apk = 399 kb and NOT INSTALLABLE, the apk was "broken", and the Android system won't install the apk. Answer: You can't add a string with higher bytes than the original.. you have to replace a string of particular size with the same size of string. Try lucky patcher. It replaces string in your Android only.. no need to bring it to your pc. :-)
Bug or meant to be: numpy raises "ValueError: too many boolean indices" for repeated boolean indices Question: I am doing some simulations in experimental cosmology, and encountered this problem while working with numpy arrays. I'm new to numpy, so I am not sure if I'm doing this wrong or if it's a bug. I run: Enthought Python Distribution -- www.enthought.com Version: 7.3-1 (32-bit) Python 2.7.3 |EPD 7.3-1 (32-bit)| (default, Apr 12 2012, 11:28:34) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "credits", "demo" or "enthought" for more information. >>> import numpy as np >>> t = np.arange(10) >>> t[t < 8][t < 5] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many boolean indices >>> I expected it to return: array([0, 1, 2, 3, 4]) since t[t < 8] should presumably be treated as just another ndarray? The numpy documentation (<http://docs.scipy.org/doc/numpy/user/basics.indexing.html>) says about boolean arrays as indices: > As with index arrays, what is returned is a copy of the data, not a view as > one gets with slices. running `type(t[t < 8])` also gives `ndarray`, which I guess should have all the properties of a numpy array. Should I perhaps do this better with list expressions? I have not done a timed comparison yet, but I would imagine this to be a problem for large 2D arrays. Answer: `t[ t < 8 ]` does indeed give you an array, however, it doesn't give you an array of the same size that you started with. `t < 8` will give a boolean array with the same shape as `t`. When you use that to index `t`, you pull out only the elements where the boolean array is `True` leaving you with a shorter array. When you do that again: result = t[t<8] result[t<5] Then the boolean index array is the same shape as `t` once again, but you're using it to index a smaller array which is what causes the error. The documentation is completely correct. Your new array isn't a `view` into the original ... It is a copy of the data, but that doesn't imply that the new array is the same shape or size as the original.
Python - How to transform counts in to m/s using the obspy module Question: I have a miniseed file with a singlechannel trace and I assume the data is in counts (how can i check the units of the trace?). I need to transform this in to m/s. I already checked the obspy tutorial and my main problem is that i dont know how to access the poles and zeros and amplification factor from the miniseed file. Also, do I need the calibration file for this? Here is my code: from obspy.core import * st=read('/Users/guilhermew/Documents/Projecto/Dados sismicos 1 dia/2012_130_DOC01.mseed') st.plot() Thanks in advance, Guilherme EDIT: I finally understood how to convert the data. Obspy has different ways to achieve this, but it all comes down to removing the instrument response from the waveform data. Like @Robert Barsch said, I needed another file to get the instrument response metadata. So I came up with the following code: parser=Parser("dir/parser/file") for tr in stream_aux: stream_id=tr.stats.network+'.'+tr.stats.station+ '..' + tr.stats.channel paz=parser.getPAZ(stream_id, tr.stats.starttime) df = tr.stats.sampling_rate tr.data = seisSim(tr.data, df, paz_remove=paz) Im using the seisSim function to convert the data. My problem now is that the output dosen't look right (but i cant seem to post the image) Answer: This is clearly a question which should be asked to the seismology community and not at StackOverflow! How about you write to the [ObsPy user mailinglist](http://lists.obspy.org/cgi-bin/mailman/listinfo/obspy-users)? **Update:** I still feel the answer is that he/she should ask directly at the ObsPy mailing list. However, in order to give a proper answer for the actual question: MiniSEED is a data only format which does not contain any meta information such as poles and zeros or the used unit. So yes you will need another file such as RESP, SAC PAZ, Dataless SEED, Full SEED etc in order to get the station specific meta data. To apply your seismometer correction read <http://docs.obspy.org/tutorial/code_snippets/seismometer_correction_simulation.html>
Correct way to install scikit-learn on OS-X using port Question: I'm tying to install scikit-learn using port on OS-X. Any idea what I'm missing here. port version Version: 2.1.3 OS-X 10.8.2 Build 12C60 Xcode Version 3.2.5 (1760) Python Python 2.7.2 (default, Jun 20 2012, 16:23:33) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> command to install scikit-learn sudo port install py27-scikit-learn ---> Computing dependencies for py27-scikit-learn ---> Cleaning py27-scikit-learn ---> Scanning binaries for linking errors: 100.0% ---> No broken files found. However, looks like it's not installed or configured properly. What am I missing here ? >>> import sklearn Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named sklearn >>> from sklearn import cluster, covariance, manifold Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named sklearn >>> Answer: I moved to Homebrew and everything after that was easy.
Change Windows password using Python Question: I am developing a little password manager tool using Python. It allows central password manager and single use passwords, therefor nobody will ever know the password of the server and we won't need to change all the passwords when an employee goes to an other employer. Anyway, the design of the software was for it to Phone-Home (and thus elimiate a lot of Firewall/Natting issues) and run as a service. We can now sync the users of the system, verify if the passwords we got are correct. But the resetting of the password after the logging in is something we are struggling with at the moment. win32.net NetUserchangePassword seemd to have what we want. As (I thought) it called "net user *". After testing I figured out it really called the netUserchangePassword feature of the msvc libs. The issue is that it doesnt work when I enter the old-password to be None. The process runs as full-admin. And should be able to change user passwords without knowing the old (DISCLAIMER: I am from an unix background, thus root (superadmin) can do everything, ciorrect me if I am wrong with the Windows OS). So, how can I as a super-admin change the password for localusers without knowing the old password using the Python Scripting Language? Thanks! Update: def set_password(username, password): from win32com import adsi ads_obj = adsi.ADsGetObject("WinNT://localhost/%s,user" % username) ads_obj.Getinfo() ads_obj.Put('Password', password) ads_obj.SetInfo() def verify_success(username, password): from win32security import LogonUser from win32con import LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT try: LogonUser(username, None, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT) except: return False return True u = "test_usr" p = "TheNewStrongP@S$w0rd!" set_password(u, p) if verify_success(u, p): print "W00t it workz" else: print "Continue Googling" Guess what, doesn't work. Answer: In the example. Change: ads_obj.Put('Password', password) ads_obj.SetInfo() With: ads_obj.SetPassword(password) Issue solved :)
Pass complex object to a python script in command line Question: I am beginner in Python programing, I want to pass a complex object (Python dictionary or class object) as an argument to a python script using command line (cmd). I see that **sys.argv** gets only string parameters. Here is an example of what I want: class point(object): def __init__(self,x,y): self.__x=x self.__y=y p=point(4,8) import os os.system('""xxxxxx.exe" "-s" "../create_scenario.py" "'+ p +'""') The xxxxxx.exe is a program which accept to run a python script with the -s option. Thanks for all!!! Answer: You could try serialize\deserialize to\from a string using a pickle module. Look for [dumps](http://docs.python.org/2/library/pickle.html#pickle.dumps) and [loads](http://docs.python.org/2/library/pickle.html#pickle.loads)
Connecting to dropbox via python over a proxy Question: i am trying to connect to a Dropbox Account with python 2.7.4 (x64 win7) and their guide [here](https://www.dropbox.com/developers/core/authentication#python) helped me a lot. However when i am behind a proxy and this code just won't do it. (From home the code works great, where i am not behind the proxy) I tried to fiddle with the urllib2 and httplib which are used in the **dropbox/rest.py** but had no luck. I know i have to change the Connection Code but i am not sure how to do this for a Socket. **dropbox/rest.py** [line:99] def create_connection(address): host, port = address err = None for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) sock.connect(sa) return sock except socket.error, _: err = _ if sock is not None: sock.close() if err is not None: raise err else: raise socket.error("getaddrinfo returns an empty list") i always get the error: [Errno 10060] SocketError. I don't really know a lot about networks and ports but i know i can connect to the proxy on port 3128 and dropbox waits on 433. For that matter i had trouble connecting to any **https://** -adress. So i found this code: proxyHost = 'www.myProxy.adress.com' proxyPort = 3128 conn = httplib.HTTPConnection(proxyHost, proxyPort) conn.request("POST", "https://www.google.com") Which works but i lack the skills to adapt this to the socket connection. Especially confusing is that i give the proxyAdress to the connection and have to write the Request in the header or somewhere, compared to the usually way, where i can give the final-Adress to the connection. This was when i read about [SOCKS](http://sourceforge.net/projects/pysocks/) for python and tried them but i could not easily replace the socket code with the new "_socksocket_ " for which a proxy can be set with: import socks socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,"www.myProxy.adress.com") socket.socket = socks.socksocket urllib.urlopen("https://www.google.com/") Any help, how to change the create_connection func of the rest.py to work with a proxy is highly appreciated. Answer: I just ran into this issue myself and in searching for a solution came across this post. I've managed to resolve this with a minor modification to the dropbox/rest.py code. In the RESTClientObject class's **init** method change: self.pool_manager = urllib3.PoolManager( num_pools=4, # only a handful of hosts. api.dropbox.com, api-content.dropbox.com maxsize=max_reusable_connections, block=False, timeout=60.0, # long enough so datastores await doesn't get interrupted cert_reqs=ssl.CERT_REQUIRED, ca_certs=TRUSTED_CERT_FILE, ssl_version=ssl.PROTOCOL_TLSv1, ) to: self.pool_manager = urllib3.ProxyManager( num_pools=4, # only a handful of hosts. api.dropbox.com, api-content.dropbox.com maxsize=max_reusable_connections, block=False, timeout=60.0, # long enough so datastores await doesn't get interrupted cert_reqs=ssl.CERT_REQUIRED, ca_certs=TRUSTED_CERT_FILE, ssl_version=ssl.PROTOCOL_TLSv1, proxy_url ='http://yourproxy.com:proxyport/', ) Note the change to use ProxyManager rather than PoolManager and the addition of the proxy_url. There are ways to authenticate against the proxy, but I haven't explored those. So this will only work if you've already authenticated via Internet Explorer or similar. Hope this helps someone.
Sys.path.append("") Dosen't work on Debian.. :/ "no module named guess_language" Question: Just transferred my python project by ftp to my linux server and the project can't import files some what.. :/ sys.path.append("Functions\guess_language") import check_language sys.path.append("Functions\SL4A") import android It's doesn't let me to import any module, but In windows, It does work.. why? I'm using Python 2.7 btw. Thanks. Answer: backslashes are escape characters in strings. so you have a few choices to deal with that in your example... 1. use raw strings: sys.path.append(r"Functions\guess_language") 2. escape the backslash with another backslash: sys.path.append("Functions\\\guess_language") 3. use forward slashes: sys.path.append("Functions/guess_language") 4. use os.path.join: sys.path.append(os.path.join("Functions", "guess_language")) 5. string formatting with os.sep: sys.path.append('Functions%sguess_language' % os.sep)
Error in installing mlabwrap in Windows Question: I tried to install mlabwrap in Windows by following the steps in [this article](http://obasic.net/how-to-install-mlabwrap-on-windows). After I completed all steps, when I typed `from mlabwrap import mlab` in Python, I got the following error: >>> from mlabwrap import mlab Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> from mlabwrap import mlab File "C:\Python27\lib\site-packages\mlabwrap.py", line 188, in <module> import mlabraw ImportError: DLL load failed: The specified module could not be found. I set all my path and environment variables according to the above link. So why do I get this error? The last step I performed is from mlabwrap directory, I typed python setup.py install Is there any other step after this? I saw it generates `mlabwrap.py` in `C:\Python27\lib\site-packages`. Answer: I was able to fix this error by putting c:/Program Files (x86)/MATLAB/R2009b/bin/win32 on the PATH so mlabraw could find the Matlab DLLs. I assume this error means mlabraw could not be loaded because it depends on a DLL that could not be found.
Read only lines that contain certain specific string and apply regex on them Question: Here's my code: I have a script that reads a file but in my file not all the lines are similar and I'd like to extract informations only from lines that have `I DOC O:`. I've tried with an if condition but it still doesn't work when there are lines where regex aren't matching: #!/usr/bin/env python # -*- coding: utf-8 -*- import re def extraire(data): ms = re.match(r'(\S+).*?(O:\S+).*(R:\S+).*mid:(\d+)', data) # heure & mid return {'Heure':ms.group(1), 'mid':ms.group(2),"Origine":ms.group(3),"Destination":ms.group(4)} tableau = [] fichier = open("/home/TEST/file.log") f = fichier.readlines() for line in f: if (re.findall(".*I Doc O:.*",line)): tableau = [extraire(line) for line in f ] print tableau fichier.close() And here's an example of some lines of my file here i want first and fourth lines..: 01:09:25.258 mta Messages I Doc O:NVS:SMTP/[email protected] R:NVS:SMS/+654811 mid:6261 01:09:41.965 mta Messages I Rep O:NVS:SMTP/[email protected] R:NVS:SMS/+455451 mid:6261 01:09:41.965 mta Messages I Rep 6261 OK, Accepted (ID: 26) 08:14:14.469 mta Messages I Doc O:NVS:SMTP/[email protected] R:NVS:SMS/+654646 mid:6262 08:14:30.630 mta Messages I Rep O:NVS:SMTP/[email protected] R:NVS:SMS/+33688704859 mid:6262 08:14:30.630 mta Messages I Rep 6262 OK, Accepted (ID: 28) Answer: From: <http://docs.python.org/2/library/re.html> _?, +?, ?? The '_ ', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against ... Also, findall is best used w/ your entire buffer, and returns a list, hence looping over matches saves you from having to do a conditional against each line of your file. buff = fichier.read() matches = re.findall(".*?I Doc ):.*", buff) for match in matches: tableau = ... -Here is my test code, could you tell me what it's doing, that you didn't want? >>> import re >>> a = """ ... 01:09:25.258 mta Messages I Doc O:NVS:SMTP/[email protected] R:NVS:SMS/+654811 mid:6261 ... 01:09:41.965 mta Messages I Rep O:NVS:SMTP/[email protected] R:NVS:SMS/+455451 mid:6261 ... 01:09:41.965 mta Messages I Rep 6261 OK, Accepted (ID: 26) ... 08:14:14.469 mta Messages I Doc O:NVS:SMTP/[email protected] R:NVS:SMS/+654646 mid:6262 ... 08:14:30.630 mta Messages I Rep O:NVS:SMTP/[email protected] R:NVS:SMS/+33688704859 mid:6262 ... 08:14:30.630 mta Messages I Rep 6262 OK, Accepted (ID: 28)""" >>> m = re.findall(".*?I Doc O:.*",a) ['01:09:25.258 mta Messages I Doc O:NVS:SMTP/[email protected] R:NVS:SMS/+654811 mid:6261', '08:14:14.469 mta Messages I Doc O:NVS:SMTP/[email protected] R:NVS:SMS/+654646 mid:6262'] >>> tableau = [] >>> for line in m: ... tableau.append( extraire(line) ) ... >>> tableau [{'Origine': 'R:NVS:SMS/+654811', 'Destination': '6261', 'Heure': '01:09:25.258', 'mid': 'O:NVS:SMTP/[email protected]'}, {'Origine': 'R:NVS:SMS/+654646', 'Destination': '6262', 'Heure': '08:14:14.469', 'mid': 'O:NVS:SMTP/[email protected]'}] you could also do this in a single line as >>> tableau = [ extraire(line) for line in re.findall( ".*?I Doc ):.*", fichier.read() ) ]
Python TypeError: range() integer end argument expected, got float Question: I apologize in advance, I saw the answers already given for a similar kind of error but I couldn't make out anything out of it for my case. My python is quite basic and I am trying run that little piece of code: mybox = (17.0, -13.0, 489.0644700903291, 566.0) # this 'box' is my input so these values will vary xMin, yMin, xMax, yMax = mybox yValue = range(yMin, yMax, 30) running it, I get an error: TypeError: range() integer end argument expected, got float. Is there a way to use a float in a range like that? Thanks, Answer: You're looking for arange, which can be found in numpy (or pylab). import numpy ... yValue = numpy.arange(yMin, yMax, 30.0)
Building python packages Question: I am bitbaking a couple of python libraries and got this warning while adding second one of them: WARNING: The recipe is trying to install files into a shared area when those files already exist. Those files are: /home/ilya/beaglebone-dany/build/tmp/sysroots/beaglebone/usr/lib/python2.7/site-packages/site.py /home/ilya/beaglebone-dany/build/tmp/sysroots/beaglebone/usr/lib/python2.7/site-packages/site.pyo The libraries both use `inherit distutils`. So this is okay as far as bitbake goes, but when I tried to install the second package via opkg, I got this error: # opkg install http://yocto.local:8080/python-requests_1.2.0-r0_armv7a-vfp-neon.ipk Downloading http://yocto.local:8080/python-requests_1.2.0-r0_armv7a-vfp-neon.ipk. Installing python-requests (1.2.0-r0) to root... Configuring python-requests. # opkg install http://yocto.local:8000/python-mylib_0.0.1-r0_armv7a-vfp-neon.ipk Downloading http://yocto.local:8080/python-mylib_0.0.1-r0_armv7a-vfp-neon.ipk. Installing python-mylib (0.0.1-r0) to root... Collected errors: * check_data_file_clashes: Package mylib-python wants to install file /usr/lib/python2.7/site-packages/site.py But that file is already provided by package * python-requests * check_data_file_clashes: Package mylib-python wants to install file /usr/lib/python2.7/site-packages/site.pyo But that file is already provided by package * python-requests * opkg_install_cmd: Cannot install package mylib-python. Both recipes look just like so: DESCRIPTION = "Requests: HTTP for Humans" HOMEPAGE = "http://docs.python-requests.org/en/latest/" SECTION = "devel/python" LICENSE = "Apache-2.0" DEPENDS = "python" RDEPENDS_${PN} = "python-core" PR = "r0" SRC_URI = "git://github.com/kennethreitz/requests;protocol=git" S = "${WORKDIR}/git/" inherit distutils #NOTE: I'm not 100% sure whether I still need to export these? export BUILD_SYS export HOST_SYS export STAGING_INCDIR export STAGING_LIBDIR BBCLASSEXTEND = "native" I have copied this from [pycurl recipe](http://git.yoctoproject.org/cgit/cgit.cgi/poky/plain/meta/recipes- devtools/python/python-pycurl_7.19.0.bb?id=danny-8.0.1), which also have had these lines that I removed: do_install_append() { rm -rf ${D}${datadir}/share } Answer: To get rid of the conflicting `/usr/lib/python2.7/site-packages/site.py`, one needs to avoid shipping this file by doing this: do_install_append() { rm -f ${D}${libdir}/python*/site-packages/site.py* } There had been another issue with the original version of recipe, the files it installed contained just `.egg` directory. I wasn't able to `import` the resulting package. It turns out that using `inherit setuptools` instead of `inherit distutils` works. I'm not a Python expert, but all [setuptools class](http://git.yoctoproject.org/cgit/cgit.cgi/poky/plain/meta/classes/setuptools.bbclass?id=danny-8.0.1) does is just this: inherit distutils DEPENDS += "python-setuptools-native" DISTUTILS_INSTALL_ARGS = "--root=${D} \ --single-version-externally-managed \ --prefix=${prefix} \ --install-lib=${PYTHON_SITEPACKAGES_DIR} \ --install-data=${datadir}" It turns out that some modules (e.g. [PyBBIO](https://github.com/alexanderhiam/PyBBIO)) do not recognise `--single- version-externally-managed`, so then you have to use `inherit distutils` and you do get a working package. Below is full recipe for the _python-requests_ package which should soon be available upstream, in case you are intending to use it. DESCRIPTION = "Requests: HTTP for Humans" HOMEPAGE = "http://docs.python-requests.org/en/latest/" SECTION = "devel/python" LICENSE = "Apache-2.0" #DEPENDS = "python-core" RDEPENDS_${PN} = "python" PR = "r0" SRC_URI = "git://github.com/kennethreitz/requests;protocol=git" S = "${WORKDIR}/git/" inherit setuptools # need to export these variables for python-config to work export BUILD_SYS export HOST_SYS export STAGING_INCDIR export STAGING_LIBDIR BBCLASSEXTEND = "native" do_install_append() { rm -f ${D}${libdir}/python*/site-packages/site.py* }
Django: ImportError: No module named pocdebug_toolbar Question: I'm getting this error when starting Django from uWSGI and can't figure out what's wrong: ... File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 160, in _fetch app = import_module(appname) File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module __import__(name) ImportError: No module named pocdebug_toolbar Python 2.7.3; Django==1.4.3; Ubuntu 12.04.2 LTS Here is the full traceback: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 241, in __call__ response = self.get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 179, in get_response response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 221, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/local/lib/python2.7/dist-packages/django/views/debug.py", line 66, in technical_500_response html = reporter.get_traceback_html() File "/usr/local/lib/python2.7/dist-packages/django/views/debug.py", line 287, in get_traceback_html return t.render(c) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 140, in render return self._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 134, in _render return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 823, in render bit = self.render_node(node, context) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py", line 74, in render_node return node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py", line 84, in render output = self.filter_expression.resolve(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 599, in resolve new_obj = func(obj, *arg_vals) File "/usr/local/lib/python2.7/dist-packages/django/template/defaultfilters.py", line 718, in date return format(value, arg) File "/usr/local/lib/python2.7/dist-packages/django/utils/dateformat.py", line 310, in format return df.format(format_string) File "/usr/local/lib/python2.7/dist-packages/django/utils/dateformat.py", line 33, in format pieces.append(force_unicode(getattr(self, piece)())) File "/usr/local/lib/python2.7/dist-packages/django/utils/dateformat.py", line 214, in r return self.format('D, j M Y H:i:s O') File "/usr/local/lib/python2.7/dist-packages/django/utils/dateformat.py", line 33, in format pieces.append(force_unicode(getattr(self, piece)())) File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py", line 71, in force_unicode s = unicode(s) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 121, in __unicode_cast return func(*self.__args, **self.__kw) File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/__init__.py", line 86, in ugettext return _trans.ugettext(message) File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 278, in ugettext return do_translate(message, 'ugettext') File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 268, in do_translate _default = translation(settings.LANGUAGE_CODE) File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 183, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 160, in _fetch app = import_module(appname) File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module __import__(name) ImportError: No module named pocdebug_toolbar Answer: Solved. I forgot a comma between my apps in the `settings.py` `INSTALLED_APPS` tuple, so it was concatenating the two strings 'poc' and 'debug_toolbar' into 'pocdebug_toolbar'. > > INSTALLED_APPS = ( > ... > 'poc' # <== missing comma here > 'debug_toolbar' > ) >
Running test script scenarios in python Question: I'm developing a script to test another program. Basically I replicated a class with all the functions that the program I am testing have. To make things simple, assume I have only 2 functions: set(value) and add(value). set(value) sets an accumulator value and add(value) adds value to it; and I'm testing a program that should do the same thing. I also have a check() function that verifies that the accumulator value in which set(value) and add(value) operates have the same value as the value retrieved by the program I'm testing; so, after EACH operation, I want to run this check() function and make sure they match. To try to make this clear, here's a (non-tested) example: def set(self, value): self.acc = value sendCommandToMyProgram('set', value) def add(self, value): self.acc += value sendCommandToMyProgram('add', value) def check(self): return self.acc == sendCommandToMyProgram('check', value) and I want to do "test scenarios" like: set(1) check() add(2) check() add(-2) check() add(3) and many others What would be the best way to make this "test scenario" script? It would be nice if it could work with functions that takes different parameters (in this example, both set() and add() received just one parameter - value -, but this isn't always the case). thanks Answer: Assuming that you're not wanting to check the value _all_ the time during normal operation, the thing that pops to mind first would be the built-in [unit test module](http://docs.python.org/2/library/unittest.html). If you are needing to do more complex things that you cannot cleanly isolate the test as shown below, check out a some of [my issues](http://stackoverflow.com/q/5834872/157744) I had to work around. It's worth noting that I ended up rolling my own test runner that behaves very similar to unit-test, but with greater control. I'll be pushing it up to py-pi in the next month or so. **Working Unit Test Examples** import unittest class RealAccumlator(object): def __init__(self): self.acc = 0 def add(self, val): self.acc += val def set(self, val): self.acc = val def get(self): return self.acc # Using a global variable as I dont know how "sendCommandToMyProgram" # is used real_acc = RealAccumlator() # Test Script class MyAccumlator(object): def __init__(self): self.acc = 0 def add(self, val): self.acc += val real_acc.add(val) def set(self, val): self.acc = val real_acc.set(val) def check(self): return self.acc == real_acc.get() class MockedAccumlatorTests(unittest.TestCase): def setUp(self): self.acc = MyAccumlator() def test_SetFunction(self): test_values = range(-10,10) # Test the set commands for val in test_values: self.acc.set(val) self.assertTrue(self.acc.check()) def test_AddFunction(self): test_values = range(-10,10) # Set the acc to a known value and to a quick test self.acc.set(0) self.assertTrue(self.acc.check()) # Test the add commands for val in test_values: self.acc.add(val) self.assertTrue(self.acc.check()) class RealAccumlatorTests(unittest.TestCase): def test_SetFunction(self): test_values = range(-10,10) # Test the set commands for val in test_values: real_acc.set(val) self.assertEqual(val, real_acc.get()) def test_AddFunction(self): test_values = range(-10,10) # Set the acc to a known value and to a quick test real_acc.set(0) self.assertEqual(0, real_acc.get()) # Test the add commands expected_value = 0 for val in test_values: expected_value += val real_acc.add(val) self.assertEqual(expected_value, real_acc.get()) if __name__ == '__main__': unittest.main() **Update based on accepted answer** If this is only going to be a test script and your mock accumulator isn't used out side this tests consider the following mod. _I still believe writing the unittests will serve you better in the long run_ class MyAccumlator(object): def __init__(self): self.acc = 0 def add(self, val): self.acc += val real_acc.add(val) assert(self.check()) return self.check() def set(self, val): self.acc = val real_acc.set(val) assert(self.check()) return self.check() def check(self): return self.acc == real_acc.get() This would allow you to iterate over whatever lists you want without having to think about calling the check function. There are two methods provided that you could check. 1. Leaving the `assert` call would throw an exception if they ever didn't match (only suggesting under the assumption this will live as a test script). 2. Removing the `assert` and checking the return status from your calling script (rather than an explicit call to `check()` might clean things up as well.
Can't get AndroidViewClient example code to run Question: [AndroidViewClient](https://github.com/dtmilano/AndroidViewClient) is a github repo that allows you to call on views directly, without specifying exact coordinates with monkeyrunner. I'm having trouble actually using it though. _Note: I'm using Windows_ In cmdline if I type: monkeyrunner test.py and test.py consists of: # Imports the monkeyrunner modules used by this program from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice # Connects to the current device, returning a MonkeyDevice object device = MonkeyRunner.waitForConnection() # Presses the Menu button device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP) Then the actionBar overflow button get's clicked. If I edit test.py to any of the AndroidViewClient examples it will doesn't do anything. Any ideas? I'm not sure if I'm implementing AndroidViewClient correctly. **EDIT:** The only thing I did to setup AndroidViewClient is download the .zip from github and then I added it to my environment variables like this: ![enter image description here](http://i.stack.imgur.com/Flbt2.png) When I try to run `monkeyrunner dump.py`: 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] Scri pt terminated due to an exception 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions]Trace back (most recent call last): File "C:\Users\EgamerHDK\android-sdk\tools\dump.py", line 29, in <module> from com.dtmilano.android.viewclient import ViewClient ImportError: No module named dtmilano 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.Py.ImportError(Py.java:264) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.imp.import_logic(imp.java:692) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.imp.import_name(imp.java:746) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.imp.importName(imp.java:791) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.ImportFunction.__call__(__builtin__.java:1236) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyObject.__call__(PyObject.java:367) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.__builtin__.__import__(__builtin__.java:1207) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.imp.importFromAs(imp.java:869) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.imp.importFrom(imp.java:845) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.pycode._pyx0.f$0(C:\Users\EgamerHDK\android-sdk\tools\dump.py:78) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.pycode._pyx0.call_function(C:\Users\EgamerHDK\android-sdk\tools\dump. py) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyTableCode.call(PyTableCode.java:165) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.PyCode.call(PyCode.java:18) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.Py.runCode(Py.java:1197) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.core.__builtin__.execfile_flags(__builtin__.java:538) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:156) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.android.monkeyrunner.ScriptRunner.run(ScriptRunner.java:116) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.android.monkeyrunner.MonkeyRunnerStarter.run(MonkeyRunnerStarter.java:77) 130419 02:46:57.869:S [main] [com.android.monkeyrunner.MonkeyRunnerOptions] at com.android.monkeyrunner.MonkeyRunnerStarter.main(MonkeyRunnerStarter.java:18 9) **Typing in the full path:** C:\Users\EGamerHDK\android-sdk\tools>monkeyrunner C:\AndroidViewClient-master\Andro idViewClient-master\AndroidViewClient\examples\dump.py Can't open specified script file Usage: monkeyrunner [options] SCRIPT_FILE -s MonkeyServer IP Address. -p MonkeyServer TCP Port. -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF) Answer: From [AndroidViewClient wiki](https://github.com/dtmilano/AndroidViewClient/wiki): > Installation AndroidViewClient does not require installation to be used. You > only need to download the source distribution and set the environment > variable ANDROID_VIEW_CLIENT_HOME or PYTHONPATH to allow the monkeyrunner > interpreter to find the required modules. Expand the downloaded ZIP file and set the environment variable accordingly. Then if you are intending to run, for example `dump.py` the next step is: monkeyrunner dump.py
Tweepy App Engine example raises 401 exception Question: I'm using the tweepy google app engine example here as the basis for my application: <https://github.com/tweepy/examples/tree/master/appengine> The get_authorization_url() method triggers the 401 unauthorized exception. template.render('oauth_example/main.html', { "authurl": auth.get_authorization_url(), "request_token": auth.request_token }) In console I get: TweepError: HTTP Error 401: Unauthorized Using the library from the python interpreter works fine: > > > import tweepy >>> >>> auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) >>> >>> print auth.get_authorization_url() prints out a valid authentication url. But the same code at the start of the MainPage handler in the example fails. class MainPage(RequestHandler): def get(self): # Build a new oauth handler and display authorization url to user. auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) print auth.get_authorization_url() # EXCEPTION 401 Unauthorized Any help would be appreciated. Answer: Found the solution Other than updating the callback in tweepy with the callback URL, also update in app section in dev.twitter.com also. so, you have to give the correct callback URL while auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET, CALLBACK) and also in the twitter app section.
Parse content from select menu, Python+BeautifulSoup Question: I am trying to parse data from a page using python which can be pretty straightforward but all the data is hidden under jquery elements and such which makes it harder to grab the data. Please forgive me as i am a newbie to Python and programming as a whole so still getting familiar with it.The website i am getting it from is <http://www.asusparts.eu/partfinder/Asus/All> In One/E Series so i just need all the data from the E This is the code i have so far: import string, urllib2, csv, urlparse, sys from bs4 import BeautifulSoup changable_url = 'http://www.asusparts.eu/partfinder/Asus/All%20In%20One/E%20Series' page = urllib2.urlopen(changable_url) base_url = 'http://www.asusparts.eu' soup = BeautifulSoup(page) redirects = [] model_info = [] select = soup.find(id='myselectListModel') print select.get_text() options = select.findAll('option') for option in options: if(option.has_attr('redirectvalue')): redirects.append(option['redirectvalue']) for r in redirects: rpage = urllib2.urlopen(base_url + r.replace(' ', '%20')) s = BeautifulSoup(rpage) print s sys.exit() However the only problem is, it just prints out the data for the first model which is Asus->All In One->E Series->ET10B->AC Adapter. The actual HTML page prints out like the [following...](http://codepad.org/3f4GEdJb) (output was too long - just pasted the main output needed) I am unsure on how i would grab the data for all the E Series parts as i assumed this would grab everything? Also i would appreciate if any answers you show relate to the current method i am using as this is the way the person in charge would like it done, Thanks. **[EDIT]** This is how i am trying to parse the HTML: for r in redirects: rpage = urllib2.urlopen(urljoin(base_url, quote(r))) s = BeautifulSoup(rpage) print s data = soup.find(id='accordion') selection = data.findAll('td') for s in selections: if(selection.has_attr('class', 'ProduktLista')): redirects.append(td['class', 'ProduktLista']) This is the error i come up with: Traceback (most recent call last): File "C:\asus.py", line 31, in <module> selection = data.findAll('td') AttributeError: 'NoneType' object has no attribute 'findAll' Answer: You need to remove the `sys.exit()` call you have in your loop: for r in redirects: rpage = urllib2.urlopen(base_url + r.replace(' ', '%20')) s = BeautifulSoup(rpage) print s # sys.exit() # remove this line, no need to exit your program You also may want to use `urllib.quote` to properly quote the URLs you get from the option dropdown; this removes the need to manually replace spaces with `'%20'`. Use `urlparse.urljoin()` to construct the final URL: from urllib import quote from urlparse import for r in redirects: rpage = urllib2.urlopen(urljoin(base_url, quote(r))) s = BeautifulSoup(rpage) print s
django unit test class based view error No JSON object could be decoded Question: I want to test my class based view. Here is the models.py file: class TodoList(models.Model): todoitem = models.CharField(max_length=200) description = models.TextField() pub_date = models.DateField(auto_now_add=True) Here is my views.py file class ListTodoView(ListView): model = TodoList template_name = 'todolist_listview.html' Here is my unit test: class TestToDoListView(TestCase): def test_list_view(self): url = reverse('notes-list') resp = self.client.get(url) self.assertEquals(resp.status_code, 200) data = json.loads(resp.content) # getting error here No JSON object could be decoded self.assertEquals(len(data), 1) What is the mistake that I am doing? I have made sure, I have placed all the imports at place. Here is the stacktrace: ====================================================================== ERROR: test_list_view ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/.../tests/test_views.py", line 21, in test_list_view data = json.loads(resp.content) File "/usr/lib/python2.7/json/__init__.py", line 326, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded Answer: Why do you test like this? What is the code in your html template? If there is a html code, it wrong to test like json data. If you need return json data, it is wrong way to do.
Formatting Text in a Table in Python Question: I'm having issues creating a table that is dynamic to adjust to various results. I've written a screen scraper to pull stocks from <http://finance.yahoo.com> and print the company name, it's symbol, and it's current stock price. However the output looks like this: Microsoft Corporation MSFT 29.76 Apple Inc. AAPL 396.77 SPDR S&P 500 SPY 155.25 Google Inc. GOOG 787.76 I want it to look like Microsoft Corporation MSFT 29.76 Apple Inc. AAPL 396.77 SPDR S&P 500 SPY 155.25 Google Inc. GOOG 787.76 I just started wokring with Python yesterday and am using 3.3.1 My current code is as follows: import re import urllib.request import cgi from bs4 import BeautifulSoup price = [0,0,0,0] namesList = ["string1", "string2", "string3", "string4"] stocksList = ["msft","aapl","spy","goog"] def HTML(): i = 0 while i < len(stocksList): htmlPull = urllib.request.urlopen("http://finance.yahoo.com/q?s="+stocksList[i]+"&ql=1") htmlPull = htmlPull.read().decode('utf-8') regex = '<span id="yfs_l84_'+stocksList[i]+'">(.+?)</span>' pattern = re.compile(regex) price[i] = re.findall(pattern,htmlPull) htmlParse = BeautifulSoup(htmlPull) title = htmlParse.title.contents namesList[i] = title i+=1 formatPrice(price) formatStock(namesList) formatOutput(namesList, stocksList, price) def formatPrice(price): k=0 while k < len(price): cleaner = str(price[k]) cleaner = cleaner.replace("[","") cleaner = cleaner.replace("]","") cleaner = cleaner.replace("'","") price[k] = float(cleaner) k+=1 def formatStock(namesList): k = 0 while k <len(namesList): capital = stocksList[k] capital = capital.upper() cleaner = str(namesList[k]) cleaner = cleaner.replace("Summary for ", "") cleaner = cleaner.replace(":"," ") cleaner = cleaner.replace("- Yahoo! Finance'","") cleaner = cleaner.replace("['","") cleaner = cleaner.replace("]","") cleaner = cleaner.replace(";","") cleaner = cleaner.replace(capital, "") namesList[k] = cleaner; k+=1 def formatOutput(namesList, stocksList, price): i = 0 while i < len(price): capital = stocksList[i] capital = capital.upper() print(namesList[i],capital, price[i]) print("") i+=1 HTML() Have tried print ({0},{1},{2}.format (namesList, capital, price[i])), various types of {:<16} variations, etc. It seems to only affect one line and I'm trying to get it to think in terms of columns, or a table, or maybe a certain amount of space that the text and whitespace should fill. I'm not sure what exactly the solution is here, so I'm asking you all :) As you can tell by my code, I'm pretty new to programming, so if there is a better way to do anything in this code, I'd be happy to listen to correction, advice, and suggestions. Thanks! Answer: You want to set the width based on the longest item in the column. In Python, you use `max` to find the largest of some group of things. So, outside the loop, you can do: names_width = max(len(name) for name in namesList) stock_width = max(len(stock) for stock in stockList) Then, format each line like you said you tried: print({0:{3}} {1:{4}} {2}.format(namesList[i], capital, price[i], names_width, stock_width))
Explicitly linking a local shared object library Question: I'm working on setting up a `Makefile` for compiling Python wrappers for a C library. The contents of the file are below (with library names altered for infosec reasons). The line numbers are for reference and are not included in the file data itself. 1 CC = gcc 2 CFLAGS = -Wall -fPIC -shared 3 EXAMPLE_LIB = example 4 PYTHON = /usr/include/python2.6 5 LIBS = -L./$(EXAMPLE_LIB) -lexample 6 INCLUDE = -I./$(EXAMPLE_LIB)/include -I$(PYTHON) 7 DEPS = test.h 8 OBJ = test.o 9 SHARED = test.so 10 11 .PHONY : build 12 13 all: build $(SHARED) 14 15 build: 16 ./$(EXAMPLE_LIB)/config shared 17 $(MAKE) -C $(EXAMPLE_LIB) 18 19 %.o: %.c $(DEPS) 20 $(CC) $(CFLAGS) $(INCLUDE) -c -o $@ $< 21 22 $(SHARED): $(OBJ) 23 $(CC) $(CFLAGS) $(LIBS) -o $@ $+ 24 25 clean: 26 $(MAKE) clean -C $(EXAMPLE_LIB) 27 rm $(OBJ) 28 rm $(SHARED) The `EXAMPLE_LIB` shared object file `example.so` is compiling properly and exists at `<project-directory>/example/example.so` and the proper header files for the 3rd party library exist at `<project-directory>/example/include`. The problem I'm having is that a different version (with less features) of the `example.so` shared object library is installed on the global system and is being linked in my library (`test.so`) instead of the local (self-compiled) copy. This causes an `undefined symbol` error when attempting to import the library in Python. When I check the `test.so` shared object library using `ldd` I see that `/usr/lib64/example.so.1` is being loaded instead of `<project- directory>/example/example.so`. Or to demonstrate: [mike@tester myproject]$ ldd test.so linux-vdso.so.1 => (0x00007fff803ff000) example.so.1 => /usr/lib64/example.so.1 (0x00007f98700e8000) libc.so.6 => /lib64/libc.so.6 (0x00007f986fd55000) libdl.so.2 => /lib64/libdl.so.2 (0x00007f986fb50000) libz.so.1 => /lib64/libz.so.1 (0x00007f986f93a000) /lib64/ld-linux-x86-64.so.2 (0x0000003afda00000) **Is there an option I can pass to GCC to tell it to explicitly link the local version of the shared object library?** Answer: The problem is that `-L` just adds a directory to the search path, and `-l` just finds the library anywhere on the search path. So: LIBS = -L./$(EXAMPLE_LIB) -lexample … might look for `libexample.so` (or `libexample.a`!) in `/usr/lib`, `/usr/local/lib`, `/usr/lib64`, etc., before looking in `./example`. See [Link Options](http://gcc.gnu.org/onlinedocs/gcc-4.8.0/gcc/Link- Options.html#Link-Options) and [Options for Directory Search](http://gcc.gnu.org/onlinedocs/gcc-4.8.0/gcc/Directory- Options.html#Directory-Options) in the GCC docs for details. If you want to specify a library explicitly, just pass its path to the linker: LIBS = ./$(EXAMPLE_LIB)/libexample.so As the docs explicitly say: > The only difference between using an -l option and specifying a file name is > that -l surrounds library with ‘lib’ and ‘.a’ and searches several > directories. So, if you don't want it to search several directories, don't use `-l`.
Python Module identifies as dict Question: Lets say I have a lot of key-pair data. I would like to have this data in a package so that it can be imported. Is there a way to make modules work like dicts, for performance and extendibility reasons? Example: common/pairs/ ├── BUILDINGS.py └── __init__.py import BUILDINGS BUILDINGS["foo"] == "bar" Note: The desired result can be archived by putting declaring `BUILDINGS` in `__init__.py` but they will all be compiled every time, its not drag and undroppable, and it seems ugly. Is there a way to achieve this well? Is there a way to achieve it at all? Answer: Not that I recommend it, but you can assign the `dict` into `sys.modules`. Python doesn't care that what's there is actually a module object. # BUILDINGS.py from sys import modules if __name__ != "__main__": modules[__name__] = {'a': 1, 'b': 2, ...}
Python Comparing Lists Question: I want to compare two lists and want to know if a element corresponds to another element. example: 'a' should correspond to 'b' here, it will return True. list1 = [a,b,c,d] list2 = [b,a,d,c] 'a' and 'b' correspond to each-other (they share the same spot on lists). how do I make a function to return True if they correspond? list1 = [a,b,c,d] list2 = [c,d,a,b] This would return False. Answer: I would do it like this: >>> from operator import eq >>> list1 = ['a','b','c','d'] >>> list2 = ['c','d','a','b'] >>> any(map(eq, list1, list2)) False Of course, if you want the full boolean 'correspondence' list you can simply omit the `any` function: >>> map(eq, list1, list2) [False, False, False, False]
How do mixed definitions work in enum? Question: I am trying to use a C program (via dynamic libraries) with Python and the ctypes module. Several constants defined in a header file will be important for me, but I am unsure of how `enum` is being used to set their values. The obvious ones, I think I understand like: `enum{THING1, THING2, THING3};` `THING1=0, THING2=1, THING3=3` But, what about this? `enum{THING1=-1, THING2, THING3};` Is the result: `THING1=-1, THING2=1, THING3=2`? What about this one? `enum{THING1=1, THING2, THING3, THING4=-1}`? I don't have an easy way to test this, so hoping someone can explain the way `enum` works in this context. C books I looked in seemed to cover either the first case or the case where each value is explicitly defined, but not this mixed case. Many thanks in advance! Answer: The value of the first `enum` constant is 0, unless specified otherwise. The value of any other `enum` constant is one more than the value of the previous, unless it is explicitly specified. So enum{THING1=-1, THING2, THING3}; sets `THING2 = 0, THING3 = 1`, and enum{THING1=1, THING2, THING3, THING4=-1} sets `THING2 = 2, THING3 = 3` (and `THING4 = -1` is explicitly given).
calling dot products and linear algebra operations in Cython? Question: I'm trying to use dot products, matrix inversion and other basic linear algebra operations that are available in numpy from Cython. Functions like `numpy.linalg.inv` (inversion), `numpy.dot` (dot product), `X.t` (transpose of matrix/array). There's a large overhead to calling `numpy.*` from Cython functions and the rest of the function is written in Cython, so I'd like to avoid this. If I assume users have `numpy` installed, is there a way to do something like: #include "numpy/npy_math.h" as an `extern`, and call these functions? Or alternatively call BLAS directly (or whatever it is that numpy calls for these core operations)? To give an example, imagine you have a function in Cython that does many things and in the end needs to make a computation involving dot products and matrix inverses: cdef myfunc(...): # ... do many things faster than Python could # ... # compute one value using dot products and inv # without using # import numpy as np # np.* val = gammaln(sum(v)) - sum(gammaln(v)) + dot((v - 1).T, log(x).T) how can this be done? If there's a library that implements these in Cython already, I can also use that, but have not found anything. Even if those procedures are less optimized than BLAS directly, not having the overhead of calling `numpy` Python module from Cython will still make things overall faster. Example functions I'd like to call: * dot product (`np.dot`) * matrix inversion (`np.linalg.inv`) * matrix multiplication * taking transpose (equivalent of `x.T` in numpy) * gammaln function (like `scipy.gammaln` equivalent, which should be available in C) I realize as it says on numpy mailing list (<https://groups.google.com/forum/?fromgroups=#!topic/cython- users/XZjMVSIQnTE>) that if you call these functions on large matrices, there is no point in doing it from Cython, since calling it from numpy will just result in the majority of the time spent in the optimized C code that numpy calls. However, in my case, I have _many calls to these linear algebra operations on small matrices_ \-- in that case, the overhead introduced by repeatedly going from Cython back to numpy and back to Cython will far outweigh the time spent actually computing the operation from BLAS. Therefore, I'd like to keep everything at the C/Cython level for these simple operations and not go through python. I'd prefer not to go through GSL, since that adds another dependency and since it's unclear if GSL is actively maintained. Since I'm assuming users of the code already have scipy/numpy installed, I can safely assume that they have all the associated C code that goes along with these libraries, so I just want to be able to tap into that code and call it from Cython. **edit** : I found a library that wraps BLAS in Cython (<https://github.com/tokyo/tokyo>) which is close but not what I'm looking for. I'd like to call the numpy/scipy C functions directly (I'm assuming the user has these installed.) Answer: Calling BLAS bundled with Scipy is "fairly" straightforward, here's one example for calling DGEMM to compute matrix multiplication: <https://gist.github.com/pv/5437087> Note that BLAS and LAPACK expect all arrays to be Fortran-contiguous (modulo the lda/b/c parameters), hence `order="F"` and `double[::1,:]` which are required for correct functioning. Computing inverses can be similarly done by applying the LAPACK function `dgesv` on the identity matrix. For the signature, see [here](http://www.netlib.org/lapack/double/dgesv.f). All this requires dropping down to rather low-level coding, you need to allocate temporary work arrays yourself etc etc. --- however these can be encapsulated into your own convenience functions, or just reuse the code from `tokyo` by replacing the `lib_*` functions with function pointers obtained from Scipy in the above way. If you use Cython's memoryview syntax (`double[::1,:]`) you transpose is the same `x.T` as usual. Alternatively, you can compute the transpose by writing a function of your own that swaps elements of the array across the diagonal. Numpy doesn't actually contain this operation, `x.T` only changes the strides of the array and doesn't move the data around. It would probably be possible to rewrite the `tokyo` module to use the BLAS/LAPACK exported by Scipy and bundle it in `scipy.linalg`, so that you could just do `from scipy.linalg.blas cimport dgemm`. [Pull requests](https://github.com/scipy/scipy/blob/master/HACKING.rst.txt) are accepted if someone wants to get down to it. * * * As you can see, it all boils down to passing function pointers around. As alluded to above, Cython does in fact provide its own protocol for exchanging function pointers. For an example, consider `from scipy.spatial import qhull; print(qhull.__pyx_capi__)` \--- those functions could be accessed via `from scipy.spatial.qhull cimport XXXX` in Cython (they're private though, so don't do that). However, at the present, `scipy.special` does not offer this C-API. It would however in fact be quite simple to provide it, given that the interface module in scipy.special is written in Cython. I don't think there is at the moment any sane and portable way to access the function doing the heavy lifting for `gamln`, (although you could snoop around the UFunc object, but that's not a sane solution :), so at the moment it's probably best to just grab the relevant part of source code from scipy.special and bundle it with your project, or use e.g. GSL.
Python Relative import does not work from command line gives ValueError Question: My Directory structure is as follows microblog/__init__.py urls.py views.py wsgi.py settings/__init__.py testing.py base.py local.py In testing.py I have a relative import from .base import * ... ...more code When I try to run the testing.py from the command line in the directory microblog/settings using python testing.py from .base import * ValueError: Attempted relative import in non-package Why does this not work. The settings directory is a valid package with a **init**.py . I do not get the ValueError from the command line only If I change the from .base import * to from base import * I am trying to understand why the relative local import fails and gives a ValueError when I run the "testing.py" package with a relative import in it from the command line. Answer: The answer from icyrock in [this post](http://stackoverflow.com/questions/9123062/python-relative-import- example-code-does-not-work?lq=1) clarifies exactly what I didnt understand about the python "repl". In the Directory microblog/settings when I run python testing.py It actually puts testing in the package "main" and it does not know that testing is part of the package "settings". Instead running "testing.py" as a module as part of its normal package hierarchy using this python -m microblog.settings.testing Runs it without any ValueError since now python knows that "testing" is part of package "settings" where the relative local import "from .base import *" makes perfect sense.
Python: C for loop with two variables Question: I'm new to python. Is there a similar way to write this C for loop with 2 variables in python? for (i = 0, j = 20; i != j; i++, j--) { ... } Answer: Python 2.x from itertools import izip, count for i, j in izip(count(0, 1), count(20, -1)): if i == j: break # do stuff Python 3.x: from itertools import count for i, j in zip(count(0, 1), count(20, -1)): if i == j: break # do stuff This uses `itertools.count()`, an iterator that iterates from a certain starting point indefinitely: > `itertools.count(start=0, step=1)` > > Make an iterator that returns evenly spaced values starting with `n`. Often > used as an argument to `imap()` to generate consecutive data points. Also, > used with `izip()` to add sequence numbers. In Python 2.x you have to use `izip` because Py2K `zip` tries to create a list of all the results, as opposed to `izip` which returns an `iterator` over the results as they are obtained. Unfortunately we are dealing with infinite iterators here so `zip` won't work... this is probably a good point as to why `zip` has been changed to perform the role of `izip` in Py3K (`izip` no longer exists there). If you are crazy about being _functional_ you could even do this (but it looks ugly in my opinion since I have grown to hate `lambda`s): from itertools import takewhile, izip, count for i, j in takewhile(lambda x: x[0] != x[1], izip(count(0, 1), count(20, -1))): # do stuff
Python for loop using Threading or multiprocessing Question: All, I am rather new and am looking for assistance. I need to perform a string search on a data set that compressed is about 20 GB of data. I have an eight core ubuntu box with 32 GB of RAM that I can use to crunch through this but am not able to implement nor determine the best possible code for such a task. Would Threading or multiprocessing be best for such a task? Please provide code samples. Thank you. Please see my current code; #!/usr/bin/python import sys logs = [] iplist = [] logs = open(sys.argv[1], 'r').readlines() iplist = open(sys.argv[2], 'r').readlines() print "+Loaded {0} entries for {1}".format(len(logs), sys.argv[1]) print "+Loaded {0} entries for {1}".format(len(iplist), sys.argv[2]) for a in logs: for b in iplist: if a.lower().strip() in b.lower().strip() print "Match! --> {0}".format(a.lower().strip()) Answer: I'm not sure if multithreading can help you, but your code has a problem that is bad for performance: Reading the logs in one go consumes incredible amounts of RAM and thrashes your cache. Instead, open it and read it sequentially, after all you are making a sequential scan, don't you? Then, don't repeat any operations on the same data. In particular, the iplist doesn't change, but for every log entry, you are repeatedly calling `b.lower().strip()`. Do that once, after reading the file with the IP addresses. In short, this looks like this: with open(..) as f: iplist = [l.lower().strip() for l in f] with open(..) as f: for l in f: l = l.lower().strip() if l in iplist: print('match!') You can improve performance even more by using a set for iplist, because looking things up there will be faster when there are many elements. That said, I'm assuming that the second file is huge, while iplist will remain relatively small. BTW: You could improve performance with multiple CPUs by using one to read the file and the other to scan for matches, but I guess the above will already give you a sufficient performance boost.
Error while downloading images from Wikipedia via python script Question: I am trying to download all images of a particular wikipedia page. Here is the code snippet from bs4 import BeautifulSoup as bs import urllib2 import urlparse from urllib import urlretrieve site="http://en.wikipedia.org/wiki/Pune" hdr= {'User-Agent': 'Mozilla/5.0'} outpath="" req = urllib2.Request(site,headers=hdr) page = urllib2.urlopen(req) soup =bs(page) tag_image=soup.findAll("img") for image in tag_image: print "Image: %(src)s" % image urlretrieve(image["src"], "/home/mayank/Desktop/test") While after running the program I see error with following stack Image: //upload.wikimedia.org/wikipedia/commons/thumb/0/04/Pune_Montage.JPG/250px-Pune_Montage.JPG Traceback (most recent call last): File "download_images.py", line 15, in <module> urlretrieve(image["src"], "/home/mayank/Desktop/test") File "/usr/lib/python2.7/urllib.py", line 93, in urlretrieve return _urlopener.retrieve(url, filename, reporthook, data) File "/usr/lib/python2.7/urllib.py", line 239, in retrieve fp = self.open(url, data) File "/usr/lib/python2.7/urllib.py", line 207, in open return getattr(self, name)(url) File "/usr/lib/python2.7/urllib.py", line 460, in open_file return self.open_ftp(url) File "/usr/lib/python2.7/urllib.py", line 543, in open_ftp ftpwrapper(user, passwd, host, port, dirs) File "/usr/lib/python2.7/urllib.py", line 864, in __init__ self.init() File "/usr/lib/python2.7/urllib.py", line 870, in init self.ftp.connect(self.host, self.port, self.timeout) File "/usr/lib/python2.7/ftplib.py", line 132, in connect self.sock = socket.create_connection((self.host, self.port), self.timeout) File "/usr/lib/python2.7/socket.py", line 571, in create_connection raise err IOError: [Errno ftp error] [Errno 111] Connection refused please help on what is causing this error? Answer: `//` is shorthand for the current protocol. It seems like Wikipedia is using the shorthand, so you have to explicitly specify HTTP instead of FTP (which Python is assuming for some reason): for image in tag_image: src = 'http:' + image
multiprocessing.pool context and load balancing Question: I've encountered some unexpected behaviour of the python multiprocessing Pool class. Here are my questions: 1) When does Pool creates its context, which is later used for serialization? _The example below runs fine as long as the Pool object is created after the Container definition. If you swap the Pool initializations, serialization error occurs. In my production code I would like to initialize Pool way before defining the container class. Is it possible to refresh Pool "context" or to achieve this in another way._ 2) Does Pool have its own load balancing mechanism and if so how does it work? _If I run a similar example on my i7 machine with the pool of 8 processes I get the following results: \- For a light evaluation function Pool favours using only one process for computation. It creates 8 processes as requested but for most of the time only one is used (I printed the pid from inside and also see this in htop). \- For a heavy evaluation function the behaviour is as expected. It uses all 8 processes equally._ 3) When using Pool I always see 4 more processes that I requested (i.e. for Pool(processes=2) I see 6 new processes). What is their role? I use Linux with Python 2.7.2 from multiprocessing import Pool from datetime import datetime POWER = 10 def eval_power(container): for power in xrange(2, POWER): container.val **= power return container #processes = Pool(processes=2) class Container(object): def __init__(self, value): self.val = value processes = Pool(processes=2) if __name__ == "__main__": cont = [Container(foo) for foo in xrange(20)] then = datetime.now() processes.map(eval_power, cont) now = datetime.now() print "Eval time:", now - then **EDIT - TO BAKURIU** 1) I was afraid that that's the case. 2) I don't understand what the linux scheduler has to do with python assigning computations to processes. My situation can be ilustrated by the example below: from multiprocessing import Pool from os import getpid from collections import Counter def light_func(ind): return getpid() def heavy_func(ind): for foo in xrange(1000000): ind += foo return getpid() if __name__ == "__main__": list_ = range(100) pool = Pool(4) l_func = pool.map(light_func, list_) h_func = pool.map(heavy_func, list_) print "light func:", Counter(l_func) print "heavy func:", Counter(h_func) On my i5 machine (4 threads) I get the following results: _light func: Counter({2967: 100}) heavy func: Counter({2969: 28, 2967: 28, 2968: 23, 2970: 21})_ It seems that the situation is as I've described it. However I still don't understand why python does it this way. My guess would be that it tries to minimise communication expenses, but still the mechanism which it uses for load balancing is unknown. The documentation isn't very helpful either, the multiprocessing module is very poorly documented. 3) If I run the above code I get 4 more processes as described before. The screen comes from htop: <http://i.stack.imgur.com/PldmM.png> Answer: 1. The `Pool` object creates the subprocesses during the call to `__init__` hence you **must** define `Container` before. By the way, I wouldn't include all the code in a single file but use a module to implement the `Container` and other utilities and write a small file that launches the main program. 2. The `Pool` does exactly what is described in the [documentation](http://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool). In particular it has no control over the scheduling of the processes hence what you see is what Linux's scheduler thinks it is right. For small computations they take so little time that the scheduler doesn't bother parallelizing them(this probably have better performances due to core affinity etc.) 3. Could you show this with an example and what you see in the task manager? I think they may be the processes that handle the queue inside the `Pool`, but I'm not sure. On my machine I can see only the main process plus the two subprocesses. * * * Update on point 2: The `Pool` object simply puts the tasks into a queue, and the child processes get the arguments from this queue. If a process takes almost no time to execute an object, than Linux scheduler let the process execute more time(hence consuming more items from the queue). If the execution takes much time then this scheduler will change processes and thus the other child processes are also executed. In your case a single process is consuming all items because the computation take so little time that before the other child processes are ready it has already finished all items. As I said, `Pool` doesn't do anything about balancing the work of the subprocesses. It's simply a queue and a bunch of workers, the pool puts items in the queue and the processes get the items and compute the results. AFAIK the only thing that it does to control the queue is putting a certain number of tasks in a single item in the queue(see [the documentation](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map)) but there is no guarantee about which process will grab which task. Everything else is left to the OS. On my machine the results are less extreme. Two processes get about twice the number of calls than the other two for the light computation, while for the heavy one all have more or less the same number of items processed. Probably on different OSes and/or hardware we would obtain even different results.
Different type while calling an instance Question: I have following code: # def macierz(self, R, alfa, beta): # '''Definiuje macierz przeksztalcenia.''' # alfa=float(self.rad(alfa)) # beta=float(self.rad(beta)) # R=float(R) # B=self.array([[-self.cos(alfa), -self.sin(alfa), 0, -R*self.cos(alfa)], [self.sin(alfa)*self.cos(beta), -self.cos(alfa)*self.cos(beta), -self.sin(beta), R*self.sin(alfa)*self.cos(beta)], [self.sin(alfa)*self.sin(beta), -self.cos(alfa)*self.sin(beta), self.cos(beta), R*self.sin(alfa)*self.cos(beta)], [0, 0, 0, 1]]) def konwersja(self): '''Ta funkcja przeprowadza konwersje listy wsp wewnetrznych na wspolrzedne kartezjanskie.''' listaB=[] R=2 alfa=1 beta=1 B=self.array([[-self.cos(alfa), -self.sin(alfa), 0, -R*self.cos(alfa)], [self.sin(alfa)*self.cos(beta), -self.cos(alfa)*self.cos(beta), -self.sin(beta), R*self.sin(alfa)*self.cos(beta)], [self.sin(alfa)*self.sin(beta), -self.cos(alfa)*self.sin(beta), self.cos(beta), R*self.sin(alfa)*self.cos(beta)], [0, 0, 0, 1]]) lista_xyz=[] #matrix=self.macierz j=0 q=self.array((0., 0., 0., 1.)).reshape(4,1) while j<len(self.lista): # B=matrix(self.lista[j+1], self.lista[j+3], self.lista[j+5]) q=self.dot(B, q) print self.lista[j], q[0,0], q[1,0], q[2,0] break , which works fine, but when I change it to: def macierz(self, R, alfa, beta): '''Definiuje macierz przeksztalcenia.''' alfa=float(self.rad(alfa)) beta=float(self.rad(beta)) R=float(R) B=self.array([[-self.cos(alfa), -self.sin(alfa), 0, -R*self.cos(alfa)], [self.sin(alfa)*self.cos(beta), -self.cos(alfa)*self.cos(beta), -self.sin(beta), R*self.sin(alfa)*self.cos(beta)], [self.sin(alfa)*self.sin(beta), -self.cos(alfa)*self.sin(beta), self.cos(beta), R*self.sin(alfa)*self.cos(beta)], [0, 0, 0, 1]]) def konwersja(self): '''Ta funkcja przeprowadza konwersje listy wsp wewnetrznych na wspolrzedne kartezjanskie.''' listaB=[] R=2 alfa=1 beta=1 lista_xyz=[] matrix=self.macierz j=0 q=self.array((0., 0., 0., 1.)).reshape(4,1) while j<len(self.lista): B=matrix(self.lista[j+1], self.lista[j+3], self.lista[j+5]) q=self.dot(B, q) print self.lista[j], q[0,0], q[1,0], q[2,0] break I get: File "./zmat_xyz.py", line 37, in konwersja q=self.dot(B, q) TypeError: unsupported operand type(s) for *: 'NoneType' and 'float' Why, when I call the `macierz` function type is not recognised? Okay, I think that what I wrote above is quite confusing. Here is a full code: #!/usr/bin/python class Internal: from numpy import sin, cos, radians, array, pi, dot, zeros, reshape rad=radians lista=[] i=0 def dane(self, plik_zmat): '''Ta funkcja przygotowuje plik zmat, typu MOPAC do odczytu przez funkcje konwersja.''' plik=open(plik_zmat, 'r+') for linijka in plik: for slowo in linijka.split(): try: slowo=float(slowo) except ValueError: pass self.lista.append(slowo) while self.i<6: self.lista.pop(0) self.i+=1 # def macierz(self, R, alfa, beta): # '''Definiuje macierz przeksztalcenia.''' # alfa=float(self.rad(alfa)) # beta=float(self.rad(beta)) # R=float(R) # B=self.array([[-self.cos(alfa), -self.sin(alfa), 0, -R*self.cos(alfa)], [self.sin(alfa)*self.cos(beta), -self.cos(alfa)*self.cos(beta), -self.sin(beta), R*self.sin(alfa)*self.cos(beta)], [self.sin(alfa)*self.sin(beta), -self.cos(alfa)*self.sin(beta), self.cos(beta), R*self.sin(alfa)*self.cos(beta)], [0, 0, 0, 1]]) def konwersja(self): '''Ta funkcja przeprowadza konwersje listy wsp wewnetrznych na wspolrzedne kartezjanskie.''' listaB=[] R=2 alfa=1 beta=1 B=self.array([[-self.cos(alfa), -self.sin(alfa), 0, -R*self.cos(alfa)], [self.sin(alfa)*self.cos(beta), -self.cos(alfa)*self.cos(beta), -self.sin(beta), R*self.sin(alfa)*self.cos(beta)], [self.sin(alfa)*self.sin(beta), -self.cos(alfa)*self.sin(beta), self.cos(beta), R*self.sin(alfa)*self.cos(beta)], [0, 0, 0, 1]]) lista_xyz=[] #matrix=self.macierz j=0 q=self.array((0., 0., 0., 1.)).reshape(4,1) while j<len(self.lista): # B=matrix(self.lista[j+1], self.lista[j+3], self.lista[j+5]) q=self.dot(B, q) print self.lista[j], q[0,0], q[1,0], q[2,0] break Internal().dane('formaldehyd.zmat') print Internal().lista Internal().konwersja() Answer: You don't have any `return` statements in your `macierz` function. This causes Python to return an implicit `None`. Which you notice in the error. Change the following line: `B=self.array([[-self.cos(alfa), -self.sin(alfa), 0, -R*self.cos(alfa)], [self.sin(alfa)*self.cos(beta), -self.cos(alfa)*self.cos(beta), -self.sin(beta), R*self.sin(alfa)*self.cos(beta)], [self.sin(alfa)*self.sin(beta), -self.cos(alfa)*self.sin(beta), self.cos(beta), R*self.sin(alfa)*self.cos(beta)], [0, 0, 0, 1]])` to: `return self.array([[-self.cos(alfa), -self.sin(alfa), 0, -R*self.cos(alfa)], [self.sin(alfa)*self.cos(beta), -self.cos(alfa)*self.cos(beta), -self.sin(beta), R*self.sin(alfa)*self.cos(beta)], [self.sin(alfa)*self.sin(beta), -self.cos(alfa)*self.sin(beta), self.cos(beta), R*self.sin(alfa)*self.cos(beta)], [0, 0, 0, 1]])` This will return the array created and be assigned to your `B` name in `konwersja`.
How to connect a webpage with python to mod_wsgi? Question: I am a total newbie when it comes to Python and incorporating it within html. I have spent many hours researching with no luck, so all I ask is a little help or an area where I can find the information required. I'm using AMPPS to develop a website as this has mod_wsgi pre-installed. I am creating a function where the user can input a Python script within a text area E.G. > print 'Hello World' The user pushes an execute button and then the results is displayed in a page. This I assume is sent using a html and a Python script and passed server side so mod_wsgi can decode python and pass it back. Hello World The question is what commands or python commands are required to send a script that includes 'print hello world' and then connects with mod_wsgi server side? And once connected how is the resonse displayed? Does AMPPS need any configuration to allow mod_wsgi to work correctly (read a thread about configuring the httpd.conf file)? I'm sorry for all the questions, Im just totally stumped atm and my Python book is going way over my head. Kind regards Andy Answer: The easiest wsgi work I've ever done was using [web.py](http://webpy.org/). [Here](http://webpy.org/cookbook/mod_wsgi-apache) are the apache mod_wsgi setup docs. You'll need a class with a GET method that renders html with an input form which will take the script then POST it back to a POST method (on the same class, if you wish). The response from your post method will be whatever result you get from calling eval on the python script. Note: this is a very dangerous application as the user can now run unvalidated python scripts on your server as whatever user the server process runs as. Example code: import web class Echo: def GET(self): return """<html><form name="script-input-form" action="/" method="post"> Script: <input type="text" name="script-body"> <input type="submit" value="Submit"> </form><html>""" def POST(self): data = web.input() obj = compile(data['script-body'], '', 'exec') result = eval(obj, globals(), locals()) web.seeother('/') urls = ( '/.*', Echo, ) if __name__ == "__main__": app = web.application(urls, globals()) app.run() else: app = web.application(urls, globals()).wsgifunc() I must also comment, if you are just learning programming, just learning python, and have not done any apache configuration, you're biting off a lot at the same time. You may want to learn these items in more digestible portions.
py2app error: in find_needed_modules TypeError: 'NoneType' object has no attribute '__getitem__' Question: I have some troubles with py2app; for some reason I have always the same error for all scripts that I developed. At the moment I am using last MacPorts version and after two days of testing I cannot figure out what is wrong. One of the setup.py file for py2app is: from setuptools import setup APP = ['main.py'] OPTIONS = {'argv_emulation': True, 'includes': ['sip', 'PyQt4._qt', 'PyQt4.QtCore', 'PyQt4.QtGui'], 'excludes': ['PyQt4.QtDesigner', 'PyQt4.QtNetwork', 'PyQt4.QtOpenGL', 'PyQt4.QtScript', 'PyQt4.QtSql', 'PyQt4.QtTest', 'PyQt4.QtWebKit', 'PyQt4.QtXml', 'PyQt4.phonon']} setup( app=APP, options={'py2app': OPTIONS}, setup_requires=['py2app'], ) And this is the log: python setup.py py2app running py2app creating /Users/opensw/SkyDrive/SISSA/Kymograph/build/bdist.macosx-10.6-intel/python2.7-standalone/app creating /Users/opensw/SkyDrive/SISSA/Kymograph/build/bdist.macosx-10.6-intel/python2.7-standalone/app/collect creating /Users/opensw/SkyDrive/SISSA/Kymograph/build/bdist.macosx-10.6-intel/python2.7-standalone/app/temp creating build/bdist.macosx-10.6-intel/python2.7-standalone/app/lib-dynload creating build/bdist.macosx-10.6-intel/python2.7-standalone/app/Frameworks *** using recipe: virtualenv *** WARNING: ImportError in sip recipe ignored: No module named matplotlib-1 WARNING: ImportError in sip recipe ignored: No module named scipy-0 *** using recipe: sip *** *** using recipe: matplotlib *** *** using recipe: scipy *** Traceback (most recent call last): File "setup.py", line 10, in <module> setup_requires=['py2app'], File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 152, in setup dist.run_commands() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 953, in run_commands self.run_command(cmd) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/Users/opensw/SkyDrive/SISSA/Kymograph/py2app-0.7.3-py2.7.egg/py2app/build_app.py", line 553, in run self._run() File "/Users/opensw/SkyDrive/SISSA/Kymograph/py2app-0.7.3-py2.7.egg/py2app/build_app.py", line 741, in _run self.run_normal() File "/Users/opensw/SkyDrive/SISSA/Kymograph/py2app-0.7.3-py2.7.egg/py2app/build_app.py", line 816, in run_normal self.process_recipes(mf, filters, flatpackages, loader_files) File "/Users/opensw/SkyDrive/SISSA/Kymograph/py2app-0.7.3-py2.7.egg/py2app/build_app.py", line 710, in process_recipes find_needed_modules(mf, packages=rval['packages']) File "build/bdist.macosx-10.6-intel/egg/modulegraph/find_modules.py", line 199, in find_needed_modules TypeError: 'NoneType' object has no attribute '__getitem__' Thanks for any help. Answer: The problem is that some bad input has been passed to the algorithm which attempts to detect dependancies in order to package them into your app - one of the places where I have had trouble with this has been in use of github flavoured markdown in package README.md files. This is a general guide to debugging setup.py issues, or actually python issues in general. 1. Run it again in interactive mode, i.e. `python -i setup.py py2app`. Once `setup.py` exits you will find yourself in a python prompt. 2. Run `from pdb import pm; pm()`. You should now find yourself at a debug prompt. 3. Type `up` and hit enter - you are now a frame higher in the stack - you can type `list` to see where in the source code the current frame is positioned, and `args` to see the arguments passed to the current frame (usually a function or method). You can also run python commands to inspect the current state, and run `pp var` to pretty-print that variable. 4. Once you have repeated the above step a few times you will find where the error is encountered - in the case I encountered where it was a README file I found a variable called `lineno` which gave the line of my README file which caused the error. If your problem is a module import, it'll probably be something different, but my instinct is that you'll find yourself looping over the `packages` argument seen in your stack trace, and the current list item will be the key to your problem.
Python - I'm trying to get the output of pwd and instead i get the exit status Question: I'm trying to get the output of `pwd`: #!python import os pwd = os.system("pwd") print (pwd) it prints 0 which is the successful exit status instead the path. How can i get the path instead? Answer: Running system commands is better done with [`subprocess`](http://docs.python.org/3/library/subprocess.html), but if you are using `os` already, why not just do pwd = os.getcwd() [`os.getcwd()`](http://docs.python.org/3/library/os.html#os.getcwd) is available on Windows and Unix.
Python - Summing a list of dictionaries with a condition Question: Let say I have a list: l = [{"num1":3, "num2":8, "num3":5, "type":"A"}, {"num1":2, "num2":5, "num3":5, "type":"B"}, {"num1":5, "num2":2, "num3":1, "type":"A"}, {"num1":4, "num2":4, "num3":9, "type":"B"} and I want to create 2 dictionaries: sumA: {"num1":8, "num2":10, "num3":6} sumB: {"num1":6, "num2":9, "num3":14} I want to make it simple and readable as much as possible. I managed to do it in a horrible way using too many variables... Thanks! Answer: This can be done reasonably easily using some [list and dict comprehensions](http://www.youtube.com/watch?v=pShL9DCSIUw). from operator import itemgetter from itertools import groupby l = [{"num1": 3, "num2": 8, "num3": 5, "type": "A"}, {"num1": 2, "num2": 5, "num3": 5, "type": "B"}, {"num1": 5, "num2": 2, "num3": 1, "type": "A"}, {"num1": 4, "num2": 4, "num3": 9, "type": "B"}] wanted_values = {"num1", "num2", "num3"} type_getter = itemgetter("type") groups = [(group, list(items)) for group, items in groupby(sorted(l, key=type_getter), type_getter)] print({group: {k: sum(map(itemgetter(k), items)) for k in wanted_values} for group, items in groups}) Which gives us: {'B': {'num2': 9, 'num3': 14, 'num1': 6}, 'A': {'num2': 10, 'num3': 6, 'num1': 8}} We sort the values by type, then split them into groups with [`itertools.groupby()`](http://docs.python.org/3.3/library/itertools.html#itertools.groupby) (making the items lists instead of generators, as we need to iterate over them multiple times). We then use a nested dict comprehension to create the data we need, summing the values from the items and assigning them to a group. This is a flexible solution that would scale to having more than just two types.
Correct way to generate random numbers in Cython? Question: What is the most efficient and portable way to generate a random random in `[0,1]` in Cython? One approach is to use `INT_MAX` and `rand()` from the C library: from libc.stdlib cimport rand cdef extern from "limits.h": int INT_MAX cdef float randnum = rand() / float(INT_MAX) Is it OK to use `INT_MAX` in this way? I noticed that it's quite different from the constant you get from Python's max int: import sys print INT_MAX print sys.maxint yields: 2147483647 (C max int) 9223372036854775807 (python max int) Which is the right "normalization" number for `rand()`? **EDIT** additionally, how can the random seed be set (e.g. seeded based on current time) if one uses the C approach of calling `rand()` from libc? Answer: The C standard says `rand` returns an `int` in the range 0 to RAND_MAX inclusive, so dividing it by RAND_MAX (from `stdlib.h`) is the proper way to normalise it. In practice, RAND_MAX will almost always be equal to MAX_INT, but don't rely on that. Because `rand` has been part of ISO C since C89, it's guaranteed to be available everywhere, but no guarantees are made regarding the quality of its random numbers. If portability is your main concern, though, it's your best option, unless you're willing to use Python's `random` module. Python's [`sys.maxint`](http://docs.python.org/2/library/sys.html#sys.maxint) is a different concept entirely; it's just the largest positive number Python can represent in _its own_ int type; larger ones will have to be longs. Python's ints and longs aren't particularly related to C's.
Get data for specific date range from yahoo finance api via python Question: I'm trying to fetch data from the Yahoo finance API via Joe C's method described here: [Download history stock prices automatically from yahoo finance in python](http://stackoverflow.com/questions/12433076/download- history-stock-prices-automatically-from-yahoo-finance-in- python/12510334#12510334) However, when I try to pass additional parameters about the date, Yahoo finance seems to ignore these parameters and returns a list of prices from the beginning of the stock's existence. Is there an easy way to get the data for a certain date range or should I just process the results manually? Thanks for your help. Answer: To get data for a particular date range, you need to modify the make_url as shown below, def make_url(ticker_symbol,start_date, end_date): print ticker_symbol a = start_date b = end_date dt_url = '%s&a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&g=d&ignore=.csv'% (ticker_symbol, a.month-1, a.day, a.year, b.month-1, b.day,b.year) return base_url + dt_url To use this function, you need to do the following, import datetime s = datetime.date(2012,1,1) e = datetime.date(2013,1,1) u = make_url('csco',s,e)
Iterating based on list of strings in Python Question: With a list of YouTube videoIDs in a text file, the code below aims to loop through these while getting the comment feeds from all these videos. Could anyone spot the looping error(s) I must have made, but cannot find? # Set the videoID list f = open('video_ids.txt', 'r') videoID_list = f.read().splitlines() f.close() # Cycle through videoID list getting comments via the YouTube API for video_id in videoID_list: #Define the comments generator def comments_generator(yt_service, video_id): comment_feed = yt_service.GetYouTubeVideoCommentFeed(video_id=video_id) while comment_feed is not None: for comment in comment_feed.entry: yield comment next_link = comment_feed.GetNextLink() if next_link is None: comment_feed = None else: comment_feed = yt_service.GetYouTubeVideoCommentFeed(next_link.href) for comment in comments_generator(yt_service, video_id): # About the video video_title = entry.media.title.text video_date = entry.published.text # About comments author_name = comment.author[0].name.text raw_text = comment.content.text comment_date = comment.published.text # Keep only alphanumeric characters and spaces in the comment text text = re.sub(r'\W+', ' ', raw_text) # Write to a file ('a' means append) - Comment text is set to lowercase [.lower()] f = open('video_comments.tsv', 'a') f.write("{}\t{}\t{}\t{}\t{}\t{}\t\r".format(video_title, video_date[:10], comment_date[:10], comment_date[11:19], author_name, text.lower())) # Also print results on screen - Comment text is set to lowercase [.lower()] print("{}\t{}\t{}\t{}\t{}\t{}\t\r".format(video_title, video_date[:10], comment_date[:10], comment_date[11:19], author_name, text.lower())) Answer: After fix some bugs in your code: import gdata.youtube import gdata.youtube.service import re yt_service = gdata.youtube.service.YouTubeService() # Set the videoID list f = open('video_ids.txt', 'r') videoID_list = f.read().splitlines() f.close() #Define the comments generator def comments_generator(yt_service, video_id): comment_feed = yt_service.GetYouTubeVideoCommentFeed(video_id=video_id) while comment_feed is not None: for comment in comment_feed.entry: yield comment next_link = comment_feed.GetNextLink() if next_link is None: comment_feed = None else: comment_feed = yt_service.GetYouTubeVideoCommentFeed(next_link.href) f = open('video_comments.tsv', 'a') # Cycle through videoID list getting comments via the YouTube API for video_id in videoID_list: for comment in comments_generator(yt_service, video_id): video_entry = yt_service.GetYouTubeVideoEntry(video_id=video_id) # About the video video_title = video_entry.title.text video_date = video_entry.published.text # About comments author_name = comment.author[0].name.text raw_text = comment.content.text comment_date = comment.published.text # Keep only alphanumeric characters and spaces in the comment text text = re.sub(r'\W+', ' ', raw_text) # Write to a file ('a' means append) - Comment text is set to lowercase [.lower()] f.write("{}\t{}\t{}\t{}\t{}\t{}\t\r".format(video_title, video_date[:10], comment_date[:10], comment_date[11:19], author_name, text.lower())) # Also print results on screen - Comment text is set to lowercase [.lower()] f.close() print("{}\t{}\t{}\t{}\t{}\t{}\t\r".format(video_title, video_date[:10], comment_date[:10], comment_date[11:19], author_name, text.lower()))
issue with vtk python wrapping: can't import vtk in interpreter but can import in console Question: I compiled vtk with python wrapping and I can us it on the command line. However, I am using eclipse IDE and want to use vtk but no matter what I do with my PYTHONPATH variable, I still get the errors below: from filtering import * File "C:\Development\third-party\vtk-5.6.1\build\Wrapping\Python\vtk\filtering.py", line 9, in <module> from vtkFilteringPython import * ImportError: DLL load failed: The specified procedure could not be found. My PATH and PYTHONPATH contain: "C:\Development\third-party\vtk-5.6.1\Wrapping\Python" "C:\Development\third-party\vtk-5.6.1\build\bin\Release" which has the *.lib, *.pyd, *.dll In the DOS console, that is all I need and I can "import vtk" with no errors. However, in eclipse I set the "External Libraries" of my project to contain the same directories above and I get an error. The error happens at in the file "C:\Development\third- party\vtk-5.6.1\Wrapping\Python\vtk__init__.py" : just after loading vtk "common" library. ... # Load all required kits. from common import * from filtering import * ... The funny thing is that both vtkcommon and vtkfiltering python (.dll, .lib and .pyd) are all in the same folder here: "C:\Development\third- party\vtk-5.6.1\build\bin\Release" Can someone please help ? Why would import vtk work on console and not in eclipse IDE ? I am using Version: Juno Service Release 2 Build id: 20130225-0426 for eclipse, vtk-5.6, python 2.6.5 and pydev 2.7.3 Can anyone with pydev + vtk experience help me? Answer: I was having problems with VTK on PyDev and I just found [this article](http://www.switchcase.org/), to do with PyCUDA on PyDev. It helped me get things working on Linux. I followed the instructions there: Go to Run->Run Configurations and add a new environment variable LD_LIBRARY_PATH I also found [this forum](http://www.coderanch.com/t/105391/vc/Configuring- eclipse-dll-files-runtime), which deals with a similar problem on Windows. They suggest adding -Djava.library.path="{dll path}" to your runtime args in eclipse. See [this page](http://wiki.eclipse.org/Eclipse.ini) on the eclipse wiki.
IPython Notebook Sympy Math Rendering Question: I have just started with using IPython Notebook and have been fascinated by its power. I have been using a few examples available on the net to get started with. I was following this tutorial: <http://nbviewer.ipython.org/url/finiterank.com/cuadernos/suavesylocas.ipynb> but the maths output is not getting rendered as expected. Below is the my code and the output: In [30]: %load_ext sympyprinting %pylab inline from __future__ import division import sympy as sym from sympy import * init_printing() x,y,z=symbols("x y z") k,m,n=symbols("k m n", integer=True) The sympyprinting extension is already loaded. To reload it, use: %reload_ext sympyprinting Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.kernel.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'. In [31]: t = sin(2*pi*x*(k**2))/ (4*(pi**2)*(k**5)) + (x**2) / (2*k) t Out[31]: 2 ⎛ 2 ⎞ x sin⎝2⋅π⋅k ⋅x⎠ ─── + ───────────── 2⋅k 2 5 4⋅π ⋅k I have tried other examples also, and they are also not getting rendered properly. Where am I going wrong? Answer: I had the same problem. Try from sympy.interactive import printing printing.init_printing(use_latex=True) instead of %load_ext sympyprinting I am using sympy 0.7.2
no newlines for python interactive console over socket Question: In a C program embedding the python interpreter, I spawn a python interactive console over a TCP socket. import socket import code import sys s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('0.0.0.0', 2000)) s.listen(1) c = s.accept()[0] # client socket def sread(s, len): return s.recv(len) def swrite(s, str): return s.sendall(str) def sreadline(s): return sread(s, 256) # lazy implementation for quick testing socket.socket.read = sread socket.socket.write = swrite socket.socket.readline = sreadline sys.stdin = c sys.stdout = c sys.stderr = c code.interact() # runs the interactive console This basically works. But, the interactive console never ever issues any end- of-line character when returning the result of some user input statement. In other words we get things like this: nc localhost 2000 Python 2.7.3 (default, Sep 26 2012, 21:53:55) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> 1+1 2>>> We see no CR-LF after the result '2' send by the interpreter in response to the user input '1+1', and before the next prompt '>>>'. The absence of any end-of-line character (CR and/or LF) is confirmed by examining the output of the user end of the socket in hexadecimal, or examining the string that is about to be written to the socket in function swrite(). Now why are no end-of-line characters issued by the interactive console? Can it be fixed and how? Answer: The question about the 'why' is still open, but as to how to fix it, here is solution. Instead of adding read/write/readline methods to the socket.socket class, make a wrapper of the socket.socket class: import socket import code import sys s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('0.0.0.0', 2000)) s.listen(1) c = s.accept()[0] # client socket class sw: # socket wrapper def __init__(self, s): self.s = s def read(self, len): return self.s.recv(len) def write(self, str): return self.s.send(str) def readline(self): return self.read(256) # lazy implementation for quick testing c = sw(c) sys.stdin = c sys.stdout = c sys.stderr = c code.interact() # runs the interactive console Now this works as expected, but for an unknown reason. nc localhost 2000 Python 2.7.3 (default, Sep 26 2012, 21:51:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> 1+1 2 >>>
SQLAlchemy __init__ not running Question: I have the following code: session = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=engine)) Base = declarative_base() Base.query = session.query_property() class CommonBase(object): created_at = Column(DateTime, default=datetime.datetime.now) updated_at = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now) class Look(Base, CommonBase): __tablename__ = "looks" id = Column(Integer, primary_key=True) def __init__(self): print "__init__ is run" Base.__init__(self) self.feedback = None def set_feedback(self, feedback): """Status can either be 1 for liked, 0 no response, or -1 disliked. """ assert feedback in [1, 0, -1] self.feedback = feedback def get_feedback(self): return self.feedback And I am getting the following error: Traceback (most recent call last): File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__ return self.wsgi_app(environ, start_response) File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app response = self.full_dispatch_request() File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request rv = self.handle_user_exception(e) File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request rv = self.dispatch_request() File "/Volumes/Data2/Dropbox/projects/Giordano/venv/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/web/backend.py", line 94, in wrapped ret = f(*args, **kwargs) File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/web/backend.py", line 81, in decorated return f(*args, **kwargs) File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/web/backend.py", line 187, in next json_ret = ge.encode(results) # automatically pulls the tags File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 201, in encode chunks = self.iterencode(o, _one_shot=True) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 264, in iterencode return _iterencode(o, 0) File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/__init__.py", line 54, in default jsonable = self.convert_to_jsonable(obj) File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/__init__.py", line 40, in convert_to_jsonable image_url=obj.image_url, feedback=obj.get_feedback()) File "/Volumes/Data2/Dropbox/projects/Giordano/src/giordano/models.py", line 100, in get_feedback return self.feedback AttributeError: 'Look' object has no attribute 'feedback' It seems to me that my `__init__` method is not run as I can't see any print statements in my log. Can someone explain why my `__init__` is not run and what can I do for this? Answer: Check out the [SQLAlchemy documentation on reconstruction](http://docs.sqlalchemy.org/en/latest/orm/constructors.html): > The SQLAlchemy ORM does not call `__init__` when recreating objects from > database rows. The ORM’s process is somewhat akin to the Python standard > library’s pickle module, invoking the low level `__new__` method and then > quietly restoring attributes directly on the instance rather than calling > `__init__`. > > If you need to do some setup on database-loaded instances before they’re > ready to use, you can use the @reconstructor decorator to tag a method as > the ORM counterpart to `__init__`. SQLAlchemy will call this method with no > arguments every time it loads or reconstructs one of your instances. This is > useful for recreating transient properties that are normally assigned in > your `__init__`: from sqlalchemy import orm class MyMappedClass(object): def __init__(self, data): self.data = data # we need stuff on all instances, but not in the database. self.stuff = [] @orm.reconstructor def init_on_load(self): self.stuff = [] > When obj = MyMappedClass() is executed, Python calls the `__init__` method > as normal and the data argument is required. When instances are loaded > during a Query operation as in query(MyMappedClass).one(), `init_on_load` is > called.
creating JSON in python from string not working Question: i am trying to create and display arrays from a string value. First i try to create a JSON value from the string, then i try to display key/values from it. I get the error: Invalid syntax on last rule... busy whole evening, but can't find dit out:( Python3 code: import urllib.request import urllib.parse import json user = 'user' pw = 'password' login_url = 'http://www.xxxxxxx.nl/test/index.php' data = urllib.parse.urlencode({'user': user, 'pw': pw}) data = data.encode('utf-8') # adding charset parameter to the Content-Type header. request = urllib.request.Request(login_url) request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8") f = urllib.request.urlopen(request, data) ## returning content from webpage: {"A":"aap","B":"noot","C":"mies"} #json.JSONDecoder().decode(f) #json.JSONDecoder.raw_decode(f) #test = print(f.read().decode('utf-8')) test = f.read().decode('utf-8') #print (test) #test2 = json.JSONDecoder().decode(test) test = '{"A":"aap","B":"noot","C":"mies"}' dest = json.loads(test) print dest['A'] ## <<< invalid syntax ?? #json.loads(test2) Answer: In Python 3.x - `print` is a function (ie: no longer a statement as in Python 2.x) - you need to use: print(dest['A']) instead of: print dest['A']
minimum distance from an array Question: I followed this method from my other post [distance between a point and a curve[([find the distance between a point and a curve python](http://stackoverflow.com/questions/16158402/find-the-distance-between- a-point-and-a-curve-python/16158876#16158876)) but something is wrong. The values aren't accurate. I plotted this same trajectory in Mathematica and checked a few distances and I have found distances as low as `18000` where python is returning a minimum of `209000`. What is going wrong in the code at the bottom? **EDIT** There was an error in this code everything checks out now. Thanks. import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D me = 5.974 * 10 ** (24) # mass of the earth mm = 7.348 * 10 ** (22) # mass of the moon G = 6.67259 * 10 ** (-20) # gravitational parameter re = 6378.0 # radius of the earth in km rm = 1737.0 # radius of the moon in km r12 = 384400.0 # distance between the CoM of the earth and moon M = me + mm pi1 = me / M pi2 = mm / M mue = 398600.0 # gravitational parameter of earth km^3/sec^2 mum = G * mm # grav param of the moon mu = mue + mum omega = np.sqrt(mu / r12 ** 3) nu = -129.21 * np.pi / 180 # true anomaly angle in radian x = 327156.0 - 4671 # x location where the moon's SOI effects the spacecraft with the offset of the # Earth not being at (0,0) in the Earth-Moon system y = 33050.0 # y location vbo = 10.85 # velocity at burnout gamma = 0 * np.pi / 180 # angle in radians of the flight path vx = vbo * (np.sin(gamma) * np.cos(nu) - np.cos(gamma) * np.sin(nu)) # velocity of the bo in the x direction vy = vbo * (np.sin(gamma) * np.sin(nu) + np.cos(gamma) * np.cos(nu)) # velocity of the bo in the y direction xrel = (re + 300.0) * np.cos(nu) - pi2 * r12 # spacecraft x location relative to the earth yrel = (re + 300.0) * np.sin(nu) # r0 = [xrel, yrel, 0] # v0 = [vx, vy, 0] u0 = [xrel, yrel, 0, vx, vy, 0] def deriv(u, dt): n1 = -((mue * (u[0] + pi2 * r12) / np.sqrt((u[0] + pi2 * r12) ** 2 + u[1] ** 2) ** 3) - (mum * (u[0] - pi1 * r12) / np.sqrt((u[0] - pi1 * r12) ** 2 + u[1] ** 2) ** 3)) n2 = -((mue * u[1] / np.sqrt((u[0] + pi2 * r12) ** 2 + u[1] ** 2) ** 3) - (mum * u[1] / np.sqrt((u[0] - pi1 * r12) ** 2 + u[1] ** 2) ** 3)) return [u[3], # dotu[0] = u[3] u[4], # dotu[1] = u[4] u[5], # dotu[2] = u[5] 2 * omega * u[5] + omega ** 2 * u[0] + n1, # dotu[3] = that omega ** 2 * u[1] - 2 * omega * u[4] + n2, # dotu[4] = that 0] # dotu[5] = 0 dt = np.arange(0.0, 320000.0, 1) # 200000 secs to run the simulation u = odeint(deriv, u0, dt) x, y, z, x2, y2, z2 = u.T fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot(x, y, z) plt.show() my_x, my_y, my_z = (384400,0,0) delta_x = x - my_x delta_y = y - my_y delta_z = z - my_z distance = np.array([np.sqrt(delta_x ** 2 + delta_y ** 2 + delta_z ** 2)]) print(distance.min()) Answer: Corrected code import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D me = 5.974 * 10 ** (24) # mass of the earth mm = 7.348 * 10 ** (22) # mass of the moon G = 6.67259 * 10 ** (-20) # gravitational parameter re = 6378.0 # radius of the earth in km rm = 1737.0 # radius of the moon in km r12 = 384400.0 # distance between the CoM of the earth and moon M = me + mm pi1 = me / M pi2 = mm / M mue = 398600.0 # gravitational parameter of earth km^3/sec^2 mum = G * mm # grav param of the moon mu = mue + mum omega = np.sqrt(mu / r12 ** 3) nu = -129.21 * np.pi / 180 # true anomaly angle in radian x = 327156.0 - 4671 # x location where the moon's SOI effects the spacecraft with the offset of the # Earth not being at (0,0) in the Earth-Moon system y = 33050.0 # y location vbo = 10.85 # velocity at burnout gamma = 0 * np.pi / 180 # angle in radians of the flight path vx = vbo * (np.sin(gamma) * np.cos(nu) - np.cos(gamma) * np.sin(nu)) # velocity of the bo in the x direction vy = vbo * (np.sin(gamma) * np.sin(nu) + np.cos(gamma) * np.cos(nu)) # velocity of the bo in the y direction xrel = (re + 300.0) * np.cos(nu) - pi2 * r12 # spacecraft x location relative to the earth yrel = (re + 300.0) * np.sin(nu) # r0 = [xrel, yrel, 0] # v0 = [vx, vy, 0] u0 = [xrel, yrel, 0, vx, vy, 0] def deriv(u, dt): n1 = -((mue * (u[0] + pi2 * r12) / np.sqrt((u[0] + pi2 * r12) ** 2 + u[1] ** 2) ** 3) - (mum * (u[0] - pi1 * r12) / np.sqrt((u[0] - pi1 * r12) ** 2 + u[1] ** 2) ** 3)) n2 = -((mue * u[1] / np.sqrt((u[0] + pi2 * r12) ** 2 + u[1] ** 2) ** 3) - (mum * u[1] / np.sqrt((u[0] - pi1 * r12) ** 2 + u[1] ** 2) ** 3)) return [u[3], # dotu[0] = u[3] u[4], # dotu[1] = u[4] u[5], # dotu[2] = u[5] 2 * omega * u[4] + omega ** 2 * u[0] + n1, # dotu[3] = that omega ** 2 * u[1] - 2 * omega * u[3] + n2, # dotu[4] = that 0] # dotu[5] = 0 dt = np.arange(0.0, 320000.0, 1) # 200000 secs to run the simulation u = odeint(deriv, u0, dt) x, y, z, x2, y2, z2 = u.T fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot(x, y, z) plt.show() my_x, my_y, my_z = (384400,0,0) delta_x = x - my_x delta_y = y - my_y delta_z = z - my_z distance = np.array([np.sqrt(delta_x ** 2 + delta_y ** 2 + delta_z ** 2)]) print(distance.min())
Get an error message from a SQL query back into Python Question: I need to be able to tell if SQL queries kicked off by Python have failed. So far I have: import subprocess p = subprocess.Popen(['sqlcmd', '-E -m-1 -S 1070854A\AISP -i NewStructures.sql >>process.log'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() print out print err But it is not liking the SQLCMD parameters. Output says Sqlcmd: '-E -S 1070854A\AISP -i NewStructures.sql': Unknown Option. Enter '-?' for help. These parameters work when typing them into the command line. Thanks. Answer: `'-E -m-1 -S 1070854A\AISP -i NewStructures.sql >>process.log'` is interpreted as one single argument, that's why you get this error. You need to split the arguments to make this work. Seen as you're trying to use a redirection in your shell command, you could use something like this: import subprocess with open('process.log', 'ab') as logfile: logfile.seek(0, 2) p = subprocess.Popen(['sqlcmd', '-E', '-m-1', '-S', '1070854A\AISP', '-i', 'NewStructures.sql'], stdout=logfile, stderr=subprocess.PIPE) out, err = p.communicate() `out` will be emty anyway, as stdout is redirected to a file. Redirection using `>` or `>>` only works with `shell=True`.
How to use easy_install to install locally? Question: I try to install [PyTables package](http://www.pytables.org) using easy_install. My problem is that I am not root on the system and am not allowed to write to `/usr/local/lib/python2.7/dist-packages/` directory. To solve this problem I decided to install locally. For that I have created a new directory: `/home/myname/mylibs`. Then I executed `easy_install -d /home/myname/mylibs tables`. As a result `easy_install` complained about the PYTHONPATH environment variable. To resolve this problem I added my new directory to the PYTHONPATH and repeated the previous command. As a result I get `syte.py` and `syte.pyc` file in my `/home/myname/mylibs` directory. However, when I try `import tables` from Python it still does not work. What also worries me is that the new files do not have "table" in their names as well in their content. Can anybody, please, explain me what is going on? Answer: I had a similar problem recently trying to use `easy_install` to put packages in a location I had write-access to. Like you, I had to add the location to my `PYTHONPATH` variable to get it to install. It was then necessary to set `PYTHONPATH` every time I wanted to run a command using the installed package(s). For example, to install and use the `flask` package I needed to do this: $ PYTHONPATH=/tmp easy_install -d /tmp flask $ PYTHONPATH=/tmp python -c 'import flask; print(flask.__version__)' 0.10.1 Without the `PYTHONPATH` variable set you'd get an error: $ python -c 'import flask; print(flask.__version__)' Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named flask You can of course set the variable permanently by running: $ export PYTHONPATH=/tmp Or putting `export PYTHONPATH=/tmp` in your `~/.bashrc` file.
Python Tkinter Grid issue - user error? Question: I am trying to create a basic layout for a Python gui using Tkinter. #!/usr/bin/env python from Tkinter import * #create root root = Tk() banner = Frame(root, width=500) body = Frame(root, width=500) banner.grid() body.grid() bannercontent = Label(banner, bg="Green", text="Green").grid(row=0, column=0) bannerbuttons = Label(banner, bg="Red", text="Red").grid(row=0, column=1) bodycontent = Label(body, bg="Blue", text="Blue").grid(row=1, column=0, columnspan=2, sticky=E+W) root.mainloop() However with the above, the blue label is not expanding to fill the 2 columns as I'd wish, i.e. fill the space under Green and Red. What am I doing wrong please? Example here <http://imgur.com/nGWQX9y> ![example](http://i.stack.imgur.com/UPjQ5.png) Thank you in advance Answer: You have a few things wrong with your code. First, you aren't specifying a `sticky` option, so widgets won't "stick" (ie: grow or shrink) to the edges of the cell. Your `bodycontent` label is in fact occupying two columns, but the frame itself isn't expanding to the full width of the main window. The second problem is that you seem to be assuming that columns span the entire app. They do not. You have two columns in `banner` because you put a widget in column 0 and column 1. However, `bodycontent` only has one column (or, you could say it has two, but the second column is of zero width). The column sizes in the first frame have no relationship to the columns in the second frame. Thus, the bottom frame contents won't line up with the top frame. A third problem that your code has is that you aren't giving your rows or columns "weight". The `weight` attribute tells Tkinter how to allocate any extra space. Since you haven't done that, your GUI does not resize in a pleasant way when you grow or shrink the window. A good rule of thumb is that for any given container, at least one row and one column should be given a non-zero weight.
nginx with websocket and https content on same url Question: My server provides on a root url, in https: * files, rest resources * websocket I would like my configuration to support websocket but it does not work. I use nginx 1.3.16 which supports websocket proxy. Here is part of my nginx configuration: map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 443 default ssl; server_name localhost; ssl on; ssl_certificate ssl/server.crt; ssl_certificate_key ssl/server.key; ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers RC4:HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; keepalive_timeout 60; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ### We want full access to SSL via backend ### location / { proxy_pass http://localhost:8080; ### force timeouts if one of backend is died ## proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; ### Set headers #### proxy_set_header Accept-Encoding ""; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; ### Most PHP, Python, Rails, Java App can use this header ### #proxy_set_header X-Forwarded-Proto https;## #This is better## proxy_set_header X-Forwarded-Proto $scheme; add_header Front-End-Https on; ### By default we don't want to redirect it #### proxy_redirect off; } location /writever/chat { proxy_pass http://localhost:8080/writever/chat; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } Here is the error I see in nginx: 2013/04/23 22:41:52 [error] 17011#0: *2093 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET /writever/chat?X-Atmosphere-tracking-id=0&X-Atmosphere-Framework=1.0.12&X-Atmosphere-Transport=websocket&X-Cache-Date=0&Content-Type=application/json&X-atmo-protocol=true HTTP/1.1", upstream: "http://127.0.0.1:8080/writever/chat?X-Atmosphere-tracking-id=0&X-Atmosphere-Framework=1.0.12&X-Atmosphere-Transport=websocket&X-Cache-Date=0&Content-Type=application/json&X-atmo-protocol=true", host: "localhost" I am not sure if the two locations can work together, if the order is important, as '/' contains /writever/chat. Any help would be greatly appreciated. * * * **update:** I had remains of a previous nginx version. After cleanning, everything seems to work fine. So I'll keep this config until I find an issue or something better. I will let you know. Answer: As indicated above, my problem was with an incorrect installation of nginx. Uninstall toroughly any version < 1.3.13- (do a sudo updatedb;locate nginx to make sure) and then install the new version. For the moment you have to do it manually (no apt-get yet): sudo apt-get install build-essential libssl-dev zlib1g-dev **pcre** cd ~/src #make this if it doesn't exist wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.30.tar.gz tar -xzvf pcre-8.30.tar.gz cd pcre-8.3X/ ./configure # /usr/local is the default so no need to prefix make sudo make install sudo ldconfig # this is important otherwise nginx will compile but fail to load **nginx** wget http://nginx.org/download/nginx-1.4.0.tar.gz -> check for latest version on nginx website tar -xvzf nginx-1.4.0.tar.gz cd nginx-1.4.0 ./configure --with-http_flv_module \ --with-http_ssl_module \ --with-http_gzip_static_module make sudo make install (uninstall previous version if nginx before) [source](https://jamiecurle.co.uk/blog/compiling-nginx-ubuntu/)
Python - reading data from file with variable attributes and line lengths Question: I'm trying to find the best way to parse through a file in Python and create a list of namedtuples, with each tuple representing a single data entity and its attributes. The data looks something like this: UI: T020 STY: Acquired Abnormality ABR: acab STN: A1.2.2.2 DEF: An abnormal structure, or one that is abnormal in size or location, found in or deriving from a previously normal structure. Acquired abnormalities are distinguished from diseases even though they may result in pathological functioning (e.g., "hernias incarcerate"). HL: {isa} Anatomical Abnormality UI: T145 RL: exhibits ABR: EX RIN: exhibited_by RTN: R3.3.2 DEF: Shows or demonstrates. HL: {isa} performs STL: [Animal|Behavior]; [Group|Behavior] UI: etc... While several attributes are shared (eg UI), some are not (eg STY). However, I could hardcode an exhaustive list of necessary. Since each grouping is separated by an empty line, I used split so I can process each chunk of data individually: input = file.read().split("\n\n") for chunk in input: process(chunk) I've seen some approaches use string find/splice, itertools.groupby, and even regexes. I was thinking of doing a regex of '[A-Z]*:' to find where the headers are, but I'm not sure how to approach pulling out multiple lines afterwards until another header is reached (such as the multilined data following DEF in the first example entity). I appreciate any suggestions. Answer: source = """ UI: T020 STY: Acquired Abnormality ABR: acab STN: A1.2.2.2 DEF: An abnormal structure, or one that is abnormal in size or location, found in or deriving from a previously normal structure. Acquired abnormalities are distinguished from diseases even though they may result in pathological functioning (e.g., "hernias incarcerate"). HL: {isa} Anatomical Abnormality """ inpt = source.split("\n") #just emulating file import re reg = re.compile(r"^([A-Z]{2,3}):(.*)$") output = dict() current_key = None current = "" for line in inpt: line_match = reg.match(line) #check if we hit the CODE: Content line if line_match is not None: if current_key is not None: output[current_key] = current #if so - update the current_key with contents current_key = line_match.group(1) current = line_match.group(2) else: current = current + line #if it's not - it should be the continuation of previous key line output[current_key] = current #don't forget the last guy print(output)
solaris python setuptools install Question: I have a solaris host: SunOS blah 5.10 Generic_147441-27 i86pc i386 i86pc and I have python at `/usr/bin/python` $ /usr/bin/python Python 2.6.4 (r264:75706, Jun 26 2012, 21:27:36) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> the problem is that I do not appear to have setuptools installed, so I download the tarball and try: setuptools-0.6c12dev-r88846$ /usr/bin/python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from distutils.util import convert_path ImportError: No module named distutils.util and of course, because I don't have distutils, I can't install... well anything. I'm not familiar with solaris at all; some googling indicated that I need python-dev installed. how do I do that? any other suggestions? Answer: You can use Python from OpenCSW. There you'll get a Python package and many modules, including setuptools. Available Python versions are Python 2.6 (`CSWpython`), 2.7 (`CSWpython27`) and 3.3 (`CSWpython33`). Most module packages are available for Python 2.6 and 2.7. Assuming you've [got started with OpenCSW](http://www.opencsw.org/manual/for-administrators/getting- started.html) and added `/opt/csw/bin` to `PATH`, you can: sudo pkgutil -y -i python py_django To get modules for Python 3.3, can use virtualenv and pip as a regular user. For example: sudo pkgutil -y -i python33 virtualenv virtualenv -p /opt/csw/bin/python3.3 py3env source py3env/bin/activate pip install django
Using any other values in pyaudio for rate / format / chunk give me the error: [Errno Input overflowed] -9981 Question: OS: Mac OSX 10.7.5 Python: Python 2.7.3 (homebrew) pyaudio: 0.2.7 portaudio: 19.20111121 (homebrew - portaudio) **The following script outputs the following and displays the issues I am having:** #!/usr/bin/env python import pyaudio from pprint import pprint p = pyaudio.PyAudio() # SUCCEEDS pprint(p.is_format_supported(input_format=pyaudio.paInt8,input_channels=1,rate=44100,input_device=0)) # => True try: stream = p.open(format=pyaudio.paInt8,channels=1,rate=44100,input=True,frames_per_buffer=1024) data = stream.read(1024) except IOError as e: print 'This never happens: '+str(e) # FAILS pprint(p.is_format_supported(input_format=pyaudio.paInt8,input_channels=1,rate=22050,input_device=0)) # => True try: stream = p.open(format=pyaudio.paInt8,channels=1,rate=22050,input=True,frames_per_buffer=1024) data = stream.read(1024) except IOError as e: print 'This fails: '+str(e) # FAILS pprint(p.is_format_supported(input_format=pyaudio.paInt8,input_channels=1,rate=22050,input_device=0)) # => True try: stream = p.open(format=pyaudio.paInt8,channels=1,rate=22050,input=True,frames_per_buffer=512) data = stream.read(1024) except IOError as e: print 'This also fails: '+str(e) # FAILS pprint(p.is_format_supported(input_format=pyaudio.paInt8,input_channels=1,rate=11025,input_device=0)) # => True try: stream = p.open(format=pyaudio.paInt8,channels=1,rate=11025,input=True,frames_per_buffer=512) data = stream.read(1024) except IOError as e: print 'This also fails as well: '+str(e) stream.stop_stream() stream.close() p.terminate() **The above outputs the following:** True True This fails: [Errno Input overflowed] -9981 True This also fails: [Errno Input overflowed] -9981 True This also fails as well: [Errno Input overflowed] -9981 Answer: If you want to check whether the desired settings of format, channels, rate, etc. are supported by your OS and hardware, do the following: import pyaudio soundObj = pyaudio.PyAudio() # Learn what your OS+Hardware can do defaultCapability = soundObj.get_default_host_api_info() print defaultCapability # See if you can make it do what you want isSupported = soundObj.is_format_supported(input_format=pyaudio.paInt8, input_channels=1, rate=22050, input_device=0) print isSupported `isSupported` will be `True` incase your system can deal with your settings. The memory overflow errors might be due to some OS+Hardware issues. You must check what your default host API can actually do. You don't need to "open" and "close" the `soundObj` via the "stream class" for querying it. Have a look at this SO question: [PyAudio Input overflowed](http://stackoverflow.com/questions/10733903/pyaudio-input- overflowed) For additional pyaudio documentation and help visit: <http://people.csail.mit.edu/hubert/pyaudio/docs/> ### Edit: It turns out that "Errno Input overflowed - 9981" is not a trivial issue: <http://trac.macports.org/ticket/39150> I see that you have the latest portaudio version (19.20111121) but 19.20111121_4 claims to have fixed the bug. See if upgrading portaudio works.
Reference to value of the function Question: At beginning i wanna say i'm newbie in use Python and everything I learned it came from tutorials. My problem concerning reference to the value. I'm writing some script which is scrapping some information from web sites. I defined some function: def MatchPattern(count): sock = urllib.urlopen(Link+str(count)) htmlSource = sock.read() sock.close() root = etree.HTML(htmlSource) root = etree.HTML(htmlSource) result = etree.tostring(root, pretty_print=True, method="html") expr1 = check_reg(root) expr2 = check_practice(root) D_expr1 = no_ks(root) D_expr2 = Registred_by(root) D_expr3 = Name_doctor(root) D_expr4 = Registration_no(root) D_expr5 = PWZL(root) D_expr6 = NIP(root) D_expr7 = Spec(root) D_expr8 = Start_date(root) #-----Reg_practice----- R_expr1 = Name_of_practise(root) R_expr2 = TERYT(root) R_expr3 = Street(root) R_expr4 = House_no(root) R_expr5 = Flat_no(root) R_expr6 = Post_code(root) R_expr7 = City(root) R_expr8 = Practice_no(root) R_expr9 = Kind_of_practice(root) #------Serv_practice ----- S_expr1 = TERYT2(root) S_expr2 = Street2(root) S_expr3 = House_no2(root) S_expr4 = Flat_no2(root) S_expr5 = Post_code2(root) S_expr6 = City2(root) S_expr7 = Phone_no(root) return expr1 return expr2 return D_expr1 return D_expr2 return D_expr3 return D_expr4 return D_expr5 return D_expr6 return D_expr7 return D_expr8 #-----Reg_practice----- return R_expr1 return R_expr2 return R_expr3 return R_expr4 return R_expr5 return R_expr6 return R_expr7 return R_expr8 return R_expr9 #------Serv_practice ----- return S_expr1 return S_expr2 return S_expr3 return S_expr4 return S_expr5 return S_expr6 return S_expr7 So now inside the script I wanna check value of the expr1 returned by my fynction. I don't know how to do that. Can u guys help me ? Is my function written correct ? EDIT: I can't add answer so I edit my current post This is my all script. Some comments are in my native language but i add some in english #! /usr/bin/env python #encoding:UTF-8- # ----------------------------- importujemy potrzebne biblioteki i skrypty ----------------------- # ------------------------------------------------------------------------------------------------ import urllib from lxml import etree, html import sys import re import MySQLdb as mdb from TOR_connections import * from XPathSelection import * import os # ------------------------------ Definiuje xPathSelectors ------------------------------------------ # -------------------------------------------------------------------------------------------------- # -------Doctors ----- check_reg = etree.XPath("string(//html/body/div/table[1]/tr[3]/td[2]/text())") #warunek Lekarz check_practice = etree.XPath("string(//html/body/div/table[3]/tr[4]/td[2]/text())") #warunek praktyka no_ks = etree.XPath("string(//html/body/div/table[1]/tr[1]/td[2]/text())") Registred_by = etree.XPath("string(//html/body/div/table[1]/tr[4]/td[2]/text())") Name_doctor = etree.XPath("string(//html/body/div/table[2]/tr[2]/td[2]/text())") Registration_no = etree.XPath("string(//html/body/div/table[2]/tr[3]/td[2]/text())") PWZL = etree.XPath("string(//html/body/div/table[2]/tr[4]/td[2]/text())") NIP = etree.XPath("string(//html/body/div/table[2]/tr[5]/td[2]/text())") Spec = etree.XPath("string(//html/body/div/table[2]/tr[18]/td[2]/text())") Start_date = etree.XPath("string(//html/body/div/table[2]/tr[20]/td[2]/text())") #-----Reg_practice----- Name_of_practise = etree.XPath("string(//html/body/div/table[2]/tr[1]/td[2]/text())") TERYT = etree.XPath("string(//html/body/div/table[2]/tr[7]/td[2]/*/text())") Street = etree.XPath("string(//html/body/div/table[2]/tr[8]/td[2]/text())") House_no = etree.XPath("string(//html/body/div/table[2]/tr[9]/td[2]/*/text())") Flat_no = etree.XPath("string(//html/body/div/table[2]/tr[10]/td[2]/*/text())") Post_code = etree.XPath("string(//html/body/div/table[2]/tr[11]/td[2]/*/text())") City = etree.XPath("string(//html/body/div/table[2]/tr[12]/td[2]/*/text())") Practice_no = etree.XPath("string(//html/body/div/table[3]/tr[4]/td[2]/text())") Kind_of_practice = etree.XPath("string(//html/body/div/table[3]/tr[5]/td[2]/text())") #------Serv_practice ----- TERYT2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[2]/td[2]/*/text())") Street2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[3]/td[2]/text())") House_no2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[4]/td[2]/*/text())") Flat_no2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[5]/td[2]/i/text())") Post_code2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[6]/td[2]/*/text())") City2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[7]/td[2]/*/text())") Phone_no = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[8]/td[2]/text())") # --------------------------- deklaracje zmiennych globalnych ---------------------------------- # ---------------------------------------------------------------------------------------------- decrease = 9 No = 1 Link = "http://rpwdl.csioz.gov.pl/rpz/druk/wyswietlKsiegaServletPub?idKsiega=" # --------------------------- funkcje zdefiniowane ---------------------------------- # ---------------------------------------------------------------------------------------------- def MatchPattern(count): sock = urllib.urlopen(Link+str(count)) htmlSource = sock.read() sock.close() root = etree.HTML(htmlSource) root = etree.HTML(htmlSource) result = etree.tostring(root, pretty_print=True, method="html") expr1 = check_reg(root) expr2 = check_practice(root) D_expr1 = no_ks(root) D_expr2 = Registred_by(root) D_expr3 = Name_doctor(root) D_expr4 = Registration_no(root) D_expr5 = PWZL(root) D_expr6 = NIP(root) D_expr7 = Spec(root) D_expr8 = Start_date(root) #-----Reg_practice----- R_expr1 = Name_of_practise(root) R_expr2 = TERYT(root) R_expr3 = Street(root) R_expr4 = House_no(root) R_expr5 = Flat_no(root) R_expr6 = Post_code(root) R_expr7 = City(root) R_expr8 = Practice_no(root) R_expr9 = Kind_of_practice(root) #------Serv_practice ----- S_expr1 = TERYT2(root) S_expr2 = Street2(root) S_expr3 = House_no2(root) S_expr4 = Flat_no2(root) S_expr5 = Post_code2(root) S_expr6 = City2(root) S_expr7 = Phone_no(root) return expr1 return expr2 return D_expr1 return D_expr2 return D_expr3 return D_expr4 return D_expr5 return D_expr6 return D_expr7 return D_expr8 #-----Reg_practice----- return R_expr1 return R_expr2 return R_expr3 return R_expr4 return R_expr5 return R_expr6 return R_expr7 return R_expr8 return R_expr9 #------Serv_practice ----- return S_expr1 return S_expr2 return S_expr3 return S_expr4 return S_expr5 return S_expr6 return S_expr7 # --------------------------- ustanawiamy polaczenie z baza danych ----------------------------- # ---------------------------------------------------------------------------------------------- con = mdb.connect('localhost', 'root', '******', 'SANBROKER', charset='utf8'); # ---------------------------- początek programu ----------------------------------------------- # ---------------------------------------------------------------------------------------------- with con: cur = con.cursor() cur.execute("SELECT Old_num FROM SANBROKER.Number_of_records;") Old_num = cur.fetchone() count = Old_num[0] counter = input("Input number of rows: ") # ----------------------- pierwsze połączenie z TORem ------------------------------------ # ---------------------------------------------------------------------------------------- #connectTor() #conn = httplib.HTTPConnection("my-ip.heroku.com") #conn.request("GET", "/") #response = conn.getresponse() #print(response.read()) while count <= counter: # co dziesiata liczba # --------------- pierwsze wpisanie do bazy danych do Archive -------------------- with con: cur = con.cursor() cur.execute("UPDATE SANBROKER.Number_of_records SET Archive_num=%s",(count)) # --------------------------------------------------------------------------------- if decrease == 0: MatchPattern(count) # Now I wanna check some expresions (2 or 3) # After that i wanna write all the values into my database #------- ostatnie czynności: percentage = count / 100 print "rekordów: " + str(count) + " z: " + str(counter) + " procent dodanych: " + str(percentage) + "%" with con: cur = con.cursor() cur.execute("UPDATE SANBROKER.Number_of_records SET Old_num=%s",(count)) decrease = 10-1 count +=1 else: MatchPattern(count) # Now I wanna check some expresions (2 or 3) # After that i wanna write all the values into my database # ------ ostatnie czynności: percentage = count / 100 print "rekordów: " + str(count) + " z: " + str(counter) + " procent dodanych: " + str(percentage) + "%" with con: cur = con.cursor() cur.execute("UPDATE SANBROKER.Number_of_records SET Old_num=%s",(count)) decrease -=1 count +=1 Answer: Well, I'm assuming check_reg is a function that returns a boolean (either True or False). If that's the case, to check the return: if expr1: print "True." else: print "False" There's more than one way to do it, but basically, `if expr1:` is all you need to do the checking.
Sort CSV File Python/Linux Command Question: I need to sort the CSV File by the Temp5 column which contain Following format.In my specific case,Temp5 column contain failed value. In other words, it does not contain any value and present only Failed. So, I need to perform sort operation on value in Temp5 and ignore Failed value. I can write new csv File or modify exist one. I have looked into `csv` in python and `sort` command in linunx But I could not Find any solution. So In `new/Existing CSV File`,I have temp5 sorted value than after Failed value(i.e without loosing any row and Failed value any be any order) Effort: I have tried into python code also which suggest me to make dictionary and store column as key(which you want to sort) and value make complete line than sort the keys and retrives data based on the keys.But I faced the problem,it did not included the Failed value.Please Find the Function Which I wrote into python csv_s_mt0 = csv.reader(open("data.csv","rb")) s_mt0_map = {} s_mt1_map = {} line_escape = 0 for line in csv_s_mt0: if(line_escape > 3): print line print line[4] s_mt0_map[line[4]] = line else: line_escape = line_escape + 1 s_mt0_map_key = s_mt0_map.keys() s_mt0_map_key.sort() for key in s_mt0_map_key: print s_mt0_map_key[key] print len(s_mt0_map_key) $Header Information $Tool info=3 .TITLE '*****************************************************' Temp1,Temp2,Temp3,Temp4,Temp5,Temp6,Temp6,Temp7,Temp8,Temp9 0., failed, failed,-2.700e-10, 9.803e-11,-2.725e-11, 2.725e-11,-1.645e-06, -40.0000,1 1.000e-12, failed, failed,-2.689e-10, 9.805e-11,-2.731e-11, 2.731e-11, 6.571e-08, -40.0000,1 2.000e-12, failed, failed,-2.679e-10, 9.806e-11,-2.731e-11, 2.731e-11, 6.835e-08, -40.0000,1 3.000e-12, failed, failed,-2.669e-10, 9.805e-11,-2.729e-11, 2.729e-11, 1.376e-07, -40.0000,1 4.000e-12, failed, failed,-2.660e-10, 9.803e-11,-2.731e-11, 2.731e-11, 3.583e-08, -40.0000,1 5.000e-12, failed, failed,-2.649e-10, 9.807e-11,-2.725e-11, 2.725e-11,-1.646e-06, -40.0000,1 6.000e-12, failed, failed,-2.640e-10, 9.803e-11,-2.731e-11, 2.731e-11, 3.579e-08, -40.0000,1 7.000e-12, failed, failed,-2.630e-10, 9.801e-11,-2.728e-11, 2.728e-11, 1.828e-07, -40.0000,1 8.000e-12, failed, failed,-2.620e-10, 9.805e-11,-2.729e-11, 2.729e-11, 1.353e-07, -40.0000,1 4.940e-10, failed, failed, 2.241e-10, failed, failed, failed, 0.8100, -40.0000,1 4.950e-10, failed, failed, 2.251e-10, failed, failed, failed, 0.8100, -40.0000,1 4.960e-10, failed, failed, 2.261e-10, failed, failed, failed, 0.8100, -40.0000,1 4.970e-10, failed, failed, 2.271e-10, failed, failed, failed, 0.8100, -40.0000,1 4.980e-10, failed, failed, 2.280e-10, failed, failed, failed, 0.8100, -40.0000,1 4.990e-10, failed, failed, 2.291e-10, failed, failed, failed, 0.8100, -40.0000,1 5.000e-10, failed, failed, 2.301e-10, failed, failed, failed, 0.8100, -40.0000,1 Answer: The `key` function is used for sorting, which returns `float('inf')` for all `failed` so they all get put at the bottom of the list. Similarly you could use `float('-inf')` if you want them all at the top. >>> import csv >>> import sys # to print to sys.stdout for this example >>> from itertools import islice >>> def key(n): return float(n) if n != 'failed' else float('inf') >>> with open('data.csv') as f: info = list(islice(f, 0, 3)) # first 3 lines r = csv.DictReader(f) w = csv.DictWriter(sys.stdout, r.fieldnames) rows = sorted(r, key=lambda row: key(row['Temp5'])) sys.stdout.writelines(info) w.writeheader() w.writerows(rows) $HeaderInformation $Toolinfo=3 .TITLE'*****************************************************' Temp1,Temp2,Temp3,Temp4,Temp5,Temp6,Temp6,Temp7,Temp8,Temp9 7.000e-12,failed,failed,-2.630e-10,9.801e-11,2.728e-11,2.728e-11,1.828e-07,-40.0000,1 0.,failed,failed,-2.700e-10,9.803e-11,2.725e-11,2.725e-11,-1.645e-06,-40.0000,1 4.000e-12,failed,failed,-2.660e-10,9.803e-11,2.731e-11,2.731e-11,3.583e-08,-40.0000,1 6.000e-12,failed,failed,-2.640e-10,9.803e-11,2.731e-11,2.731e-11,3.579e-08,-40.0000,1 1.000e-12,failed,failed,-2.689e-10,9.805e-11,2.731e-11,2.731e-11,6.571e-08,-40.0000,1 3.000e-12,failed,failed,-2.669e-10,9.805e-11,2.729e-11,2.729e-11,1.376e-07,-40.0000,1 8.000e-12,failed,failed,-2.620e-10,9.805e-11,2.729e-11,2.729e-11,1.353e-07,-40.0000,1 2.000e-12,failed,failed,-2.679e-10,9.806e-11,2.731e-11,2.731e-11,6.835e-08,-40.0000,1 5.000e-12,failed,failed,-2.649e-10,9.807e-11,2.725e-11,2.725e-11,-1.646e-06,-40.0000,1 4.940e-10,failed,failed,2.241e-10,failed,failed,failed,0.8100,-40.0000,1 4.950e-10,failed,failed,2.251e-10,failed,failed,failed,0.8100,-40.0000,1 4.960e-10,failed,failed,2.261e-10,failed,failed,failed,0.8100,-40.0000,1 4.970e-10,failed,failed,2.271e-10,failed,failed,failed,0.8100,-40.0000,1 4.980e-10,failed,failed,2.280e-10,failed,failed,failed,0.8100,-40.0000,1 4.990e-10,failed,failed,2.291e-10,failed,failed,failed,0.8100,-40.0000,1 5.000e-10,failed,failed,2.301e-10,failed,failed,failed,0.8100,-40.0000,1
how to read data from clipboard and pass it as value to a variable in python? Question: how to read data from clipboard and pass it as value to a variable in python? For example: I will copy some data {eg: 200} by pressing ctrl+c or through rightclick. and pass it to a variable. c = 200 ..can any1 tel me how to do this? Answer: To read from clipboard in your script with tkinter is this easy: try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk root = tk.Tk() # keep the window from showing root.withdraw() # read the clipboard c = root.clipboard_get()
Python Tkinter scrollbar for frame Question: My objective is to add a vertical scroll bar to a frame which has several labels in it. The scroll bar should automatically enabled as soon as the labels inside the frame exceed the height of the frame. After searching through, I found [this](http://stackoverflow.com/questions/3085696/adding-a- scrollbar-to-a-grid-of-widgets-in-tkinter) useful post. Based on that post I understand that in order to achieve what i want, (correct me if I am wrong, I am a beginner) I have to create a Frame first, then create a Canvas inside that frame and stick the scroll bar to that frame as well. After that, create another frame and put it inside the canvas as a window object. So, i finally come up with this from Tkinter import * def data(): for i in range(50): Label(frame,text=i).grid(row=i,column=0) Label(frame,text="my text"+str(i)).grid(row=i,column=1) Label(frame,text="..........").grid(row=i,column=2) def myfunction(event): canvas.configure(scrollregion=canvas.bbox("all"),width=200,height=200) root=Tk() sizex = 800 sizey = 600 posx = 100 posy = 100 root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy)) myframe=Frame(root,relief=GROOVE,width=50,height=100,bd=1) myframe.place(x=10,y=10) canvas=Canvas(myframe) frame=Frame(canvas) myscrollbar=Scrollbar(myframe,orient="vertical",command=canvas.yview) canvas.configure(yscrollcommand=myscrollbar.set) myscrollbar.pack(side="right",fill="y") canvas.pack(side="left") canvas.create_window((0,0),window=frame,anchor='nw') frame.bind("<Configure>",myfunction) data() root.mainloop() 1. Am I doing it right? Is there better/smarter way to achieve the output this code gave me? 2. Why must I use grid method? (I tried place method, but none of the labels appear on the canvas.) 3. What so special about using anchor='nw' when creating window on canvas? Please keep your answer simple as I am a beginner. Thanks for your help. Answer: Here is an example: from Tkinter import * # from x import * is bad practice from ttk import * # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame class VerticalScrolledFrame(Frame): """A pure Tkinter scrollable frame that actually works! * Use the 'interior' attribute to place widgets inside the scrollable frame * Construct and pack/place/grid normally * This frame only allows vertical scrolling """ def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) # create a canvas object and a vertical scrollbar for scrolling it vscrollbar = Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=canvas.yview) # reset the view canvas.xview_moveto(0) canvas.yview_moveto(0) # create a frame inside the canvas which will be scrolled with it self.interior = interior = Frame(canvas) interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to the canvas and frame width and sync them, # also updating the scrollbar def _configure_interior(event): # update the scrollbars to match the size of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != canvas.winfo_width(): # update the canvas's width to fit the inner frame canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != canvas.winfo_width(): # update the inner frame's width to fill the canvas canvas.itemconfigure(interior_id, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas) if __name__ == "__main__": class SampleApp(Tk): def __init__(self, *args, **kwargs): root = Tk.__init__(self, *args, **kwargs) self.frame = VerticalScrolledFrame(root) self.frame.pack() self.label = Label(text="Shrink the window to activate the scrollbar.") self.label.pack() buttons = [] for i in range(10): buttons.append(Button(self.frame.interior, text="Button " + str(i))) buttons[-1].pack() app = SampleApp() app.mainloop() It does not yet have the mouse wheel bound to the scrollbar but it is possible. Scrolling with the wheel can get a bit bumpy, though. edit: to 1) IMHO scrolling frames is somewhat tricky in Tkinter and does not seem to be done a lot. It seems there is no elegant way to do it. One problem with your code is that you have to set the canvas size manually - that's what the example code I posted solves. to 2) You are talking about the data function? Place works for me, too. (In general I prefer grid). to 3) Well, it positions the window on the canvas. One thing I noticed is that your example handles mouse wheel scrolling by default while the one I posted does not. Will have to look at that some time.
"error: NSInternalInconsistencyException - Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType" Question: Sometimes, mostly on heavy load, I am getting these errors: 2013-04-23 23:53:13.595 MusicPlayer[74705:6303] unrecognized type is -2 2013-04-23 23:53:14.686 MusicPlayer[74705:6303] *** Assertion failure in -[NSEvent _initWithCGSEvent:eventRef:], /SourceCache/AppKit/AppKit-1187.37/AppKit.subproj/NSEvent.m:1348 2013-04-24 00:40:47.358 MusicPlayer[74705:6303] unrecognized type is -2 2013-04-24 00:40:47.561 MusicPlayer[74705:6303] *** Assertion failure in -[NSEvent _initWithCGSEvent:eventRef:], /SourceCache/AppKit/AppKit-1187.37/AppKit.subproj/NSEvent.m:1348 2013-04-24 00:42:49.016 MusicPlayer[74705:6303] unrecognized type is -2 2013-04-24 00:42:49.017 MusicPlayer[74705:6303] *** Assertion failure in -[NSEvent _initWithCGSEvent:eventRef:], /SourceCache/AppKit/AppKit-1187.37/AppKit.subproj/NSEvent.m:1348 2013-04-24 00:42:53.689 MusicPlayer[74705:6303] unrecognized type is -2 2013-04-24 00:42:53.689 MusicPlayer[74705:6303] *** Assertion failure in -[NSEvent _initWithCGSEvent:eventRef:], /SourceCache/AppKit/AppKit-1187.37/AppKit.subproj/NSEvent.m:1348 2013-04-24 00:43:01.091 MusicPlayer[74705:6303] unrecognized type is -2 2013-04-24 00:43:01.091 MusicPlayer[74705:6303] *** Assertion failure in -[NSEvent _initWithCGSEvent:eventRef:], /SourceCache/AppKit/AppKit-1187.37/AppKit.subproj/NSEvent.m:1348 2013-04-24 00:43:06.840 MusicPlayer[74705:6303] unrecognized type is -2 2013-04-24 00:43:06.840 MusicPlayer[74705:6303] *** Assertion failure in -[NSEvent _initWithCGSEvent:eventRef:], /SourceCache/AppKit/AppKit-1187.37/AppKit.subproj/NSEvent.m:1348 EXCEPTION Traceback (most recent call last): File "/Users/az/Programmierung/music-player/mac/build/Release/MusicPlayer.app/Contents/Resources/Python/mediakeys.py", line 71, in runEventsCapture line: Quartz.CFRunLoopRun() locals: Quartz = <local> <module 'Quartz' from '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC/Quartz/__init__.py'> Quartz.CFRunLoopRun = <local> <objc.function 'CFRunLoopRun' at 0x1027dfb30> error: NSInternalInconsistencyException - Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType EXCEPTION Traceback (most recent call last): File "/Users/az/Programmierung/music-player/mac/build/Release/MusicPlayer.app/Contents/Resources/Python/mediakeys.py", line 71, in runEventsCapture line: Quartz.CFRunLoopRun() locals: Quartz = <local> <module 'Quartz' from '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC/Quartz/__init__.py'> Quartz.CFRunLoopRun = <local> <objc.function 'CFRunLoopRun' at 0x1027dfb30> error: NSInternalInconsistencyException - Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType EXCEPTION Traceback (most recent call last): File "/Users/az/Programmierung/music-player/mac/build/Release/MusicPlayer.app/Contents/Resources/Python/mediakeys.py", line 71, in runEventsCapture line: Quartz.CFRunLoopRun() locals: Quartz = <local> <module 'Quartz' from '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC/Quartz/__init__.py'> Quartz.CFRunLoopRun = <local> <objc.function 'CFRunLoopRun' at 0x1027dfb30> error: NSInternalInconsistencyException - Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType new song: Tiestö - Reepublic, 00:15, mp3, 125 kbit/s, 233 KB EXCEPTION Traceback (most recent call last): File "/Users/az/Programmierung/music-player/mac/build/Release/MusicPlayer.app/Contents/Resources/Python/mediakeys.py", line 71, in runEventsCapture line: Quartz.CFRunLoopRun() locals: Quartz = <local> <module 'Quartz' from '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC/Quartz/__init__.py'> Quartz.CFRunLoopRun = <local> <objc.function 'CFRunLoopRun' at 0x1027dfb30> error: NSInternalInconsistencyException - Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType EXCEPTION Traceback (most recent call last): File "/Users/az/Programmierung/music-player/mac/build/Release/MusicPlayer.app/Contents/Resources/Python/mediakeys.py", line 71, in runEventsCapture line: Quartz.CFRunLoopRun() locals: Quartz = <local> <module 'Quartz' from '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC/Quartz/__init__.py'> Quartz.CFRunLoopRun = <local> <objc.function 'CFRunLoopRun' at 0x1027dfb30> error: NSInternalInconsistencyException - Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType EXCEPTION Traceback (most recent call last): File "/Users/az/Programmierung/music-player/mac/build/Release/MusicPlayer.app/Contents/Resources/Python/mediakeys.py", line 71, in runEventsCapture line: Quartz.CFRunLoopRun() locals: Quartz = <local> <module 'Quartz' from '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC/Quartz/__init__.py'> Quartz.CFRunLoopRun = <local> <objc.function 'CFRunLoopRun' at 0x1027dfb30> error: NSInternalInconsistencyException - Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType The related code: import AppKit, Quartz from AppKit import NSSystemDefined pool = AppKit.NSAutoreleasePool.alloc().init() self.runLoopRef = Quartz.CFRunLoopGetCurrent() while True: # https://developer.apple.com/library/mac/#documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, # Quartz.kCGSessionEventTap or kCGHIDEventTap Quartz.kCGHeadInsertEventTap, # Insert wherever, we do not filter Quartz.kCGEventTapOptionDefault, #Quartz.kCGEventTapOptionListenOnly, Quartz.CGEventMaskBit(NSSystemDefined), # NSSystemDefined for media keys self.eventTap, None ) assert tap # Create a runloop source and add it to the current loop runLoopSource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) Quartz.CFRunLoopAddSource( self.runLoopRef, runLoopSource, Quartz.kCFRunLoopDefaultMode ) # Enable the tap Quartz.CGEventTapEnable(tap, True) try: # and run! This won't return until we exit or are terminated. Quartz.CFRunLoopRun() except Exception: # I got this one here once: # error: NSInternalInconsistencyException - Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType sys.excepthook(*sys.exc_info()) continue # rerun # this is a regular quit break del pool The exception mostly comes along with a hang of the GUI thread (which is the main reason why I don't just want to ignore it - because it can be very notable). Answer: From [here](http://forums.macrumors.com/showthread.php?t=1145465), I got the helpful information bit that says: > Actually an event type CGEventType is defined in CGEventType.h as unsigned > 32-bit integer. So your -2 is actually 0xFFFFFFFE. In CGEventType.h that's > defined as kCGEventTapDisabledByTimeout. There's a comment just about this > that says: > > > /* Out of band event types. These are delivered to the event tap > callback > to notify it of unusual conditions that disable the event tap. */ > kCGEventTapDisabledByTimeout = 0xFFFFFFFE, > kCGEventTapDisabledByUserInput = 0xFFFFFFFF > > > So it looks like your event tap is timing out. That's why your not getting > anymore events after this. In Python, in your event tap, you can check for this case like this: def eventTap(self, proxy, type_, event, refcon): if type_ < 0 or type_ > 0x7fffffff: # handle it ... Note that the event tap is disabled after you got such an event type. So you might want to restart your event loop.
How to execute one program's output in some different terminal Question: My last question was also same thing, but did not get proper suggestion, so I am asking again. I have a GUI which will connect to ssh. After it connects to ssh I am not able to do anything , so I have to open new terminal through script do rest of the operation (display respective outputs ) in that 'new terminal'. Now I am able to open new window using subprocess but its not taking any action from GUI may be code issue. Please help me solve my problem. I am using python and shell script for the backend and wxpython for GUI. Note: I'm looking for solutions using Python and shell script. My code is: import time import sys import pexpect c = pexpect.spawn("ssh -Y -L xxxx:localhost:xxxx user @ host.com") time.sleep(0.1) c.expect("[pP]aasword") c.sendline("xxxxxx") sub = subprocess.call("xfce4-terminal") if sub: subprocess.call("svn update",shell=True) time.sleep(0.2) c.interact() c.pexpect([[email protected]~]$) # here after its connects to ssh then command wont be executed c.sendline("xfce4-terminal") In GUI I have a button "APPLY" and 5 radio button . I can select 1 radio button at a time and have to click button "APPLY". then it have connect to ssh tunnel and do the requested operation . Right now it is not allowing to do any of operation after it gets connect to ssh_tunnel. Answer: The actual problem that you are seeing is how to avoid blocking the GUI event loop while you are running `ssh`. There are two major approaches that allow to solve it: * run `ssh` in a background thread and use [an appropriate for your GUI framework method of communicating with the main GUI thread](http://wiki.wxpython.org/LongRunningTasks) to report results. * run `ssh` asynchronously and subscribe to its I/O events. Here's [an example for gtk framework](https://gist.github.com/zed/8a255e81eb87431c0e63). To run commands via `ssh`, you could try to use [`fabric`](http://fabfile.org) as a [library](http://docs.fabfile.org/en/1.6/usage/library.html) (it is higher level than `paramiko`).
Read an SQLite 2 database using Python 3 Question: I have an old SQLite 2 database that I would like to read using Python 3 (on Windows). Unfortunately, it seems that Python's sqlite3 library does not support SQLite 2 databases. Is there any other convenient way to read this type of database in Python 3? Should I perhaps compile an older version of pysqlite? Will such a version be compatible with Python 3? Answer: As the pysqlite author I am pretty sure nobody has ported pysqlite 1.x to Python 3 yet. The only solution that makes sense effort-wise is the one theomega suggested. If all you need is access the data from Python for importing them elsewhere, but doing the sqlite2 dump/sqlite3 restore dance is not possible, there is an option, but it is not convenient: Use the builtin ctypes module to access the necessary functions from the SQLite 2 DLL. You would then implement a minimal version of pysqlite yourself that only wraps what you really need.
Python Memory leak when accessing GetCurrentImage() from DirectShow comtype Question: I have to debug someone elses code that has a memory leak. It uses up all the RAM and then eventually crashes (at a rate of 4Mb/s). I isolated it down to a call that grabs a screen shot of a video filter and saves it to a object named **lbDib**. But then Python does not free it afterward it is used. I have tried to Del it, then call gc.collect(). I have assigned it to zero or None etc. But the memory is not freed. After some googling I came across this: <http://msdn.microsoft.com/en- us/library/windows/desktop/dd390556%28v=vs.85%29.aspx> Which states: > The VMR allocates the memory for the image and returns a pointer to it in > the lpDib variable. The caller must free the memory by calling > CoTaskMemFree. When I research memory management I just keep coming across the python garbage collector is the best thing since sliced pie, and you doing something wrong if you trying to clear up memory. This is the line that creates memory that does not get released: lpDib = vmr_windowless_control.GetCurrentImage() Where **vmr_windowless_control** comes from: vmr_windowless_control = vmr_config.QueryInterface(IVMRWindowlessControl) Where **vmr_config** comes from: vmr_config = self.filter.QueryInterface(IVMRFilterConfig) vmr_config.SetRenderingMode(Renderer.VMRMode[vmrmode] Where **IVMRFilterConfig** comes from COMtype DirectShowLib import: try: from comtypes.gen.DirectShowLib import (ICreateDevEnum, IBaseFilter, IBindCtx, IMoniker, IFilterGraph, IVMRFilterConfig, IVMRWindowlessControl, IAMCrossbar, IAMTVTuner, IAMStreamConfig, IAMVideoProcAmp, IFilterMapper2) except ImportError: GetModule("DirectShow.tlb") # Create gen.DirectShowLib if it doesn't exist from comtypes.gen.DirectShowLib import (ICreateDevEnum, IBaseFilter, IBindCtx, IMoniker, IFilterGraph, IVMRFilterConfig, IVMRWindowlessControl, IAMCrossbar, IAMTVTuner, IAMStreamConfig, IAMVideoProcAmp, IFilterMapper2) No idea how to attack this, brain is fried. Thanks in advance for any help or leads. Answer: Just needed to add the following: from ctypes import windll windll.ole32.CoTaskMemFree(lpDib) Thank guys
Python & CV2: How do i draw a line on an image with mouse then return line coordinates? Question: I'm looking to draw a line on a video which I'm stepping through frame by frame so I can calculate the angle of the line. I've made a very simple script which steps through the video and tries to collect the points clicked in each image in an array, however not even this seems to work... Here's the code: import cv2, cv cap = cv2.VideoCapture('video.avi') box = [] def on_mouse(event, x, y, flags): if event == cv.CV_EVENT_LBUTTONDOWN: print 'Mouse Position: '+x+', '+y box.append(x, y) #cv2.rectangle(img, pt1, pt2, color) #cv2.line(img, pt1, pt2, color) drawing_box = False cv.SetMouseCallback('real image', on_mouse, 0) count = 0 while(1): _,img = cap.read() img = cv2.blur(img, (3,3)) cv2.namedWindow('real image') cv2.imshow('real image', img) if cv2.waitKey(0) == 27: cv2.destroyAllWindows() break print box Any help is appreciated! Many Thanks John Answer: Here is the fix that I found: def on_mouse(event, x, y, flags, params): if event == cv.CV_EVENT_LBUTTONDOWN: print 'Start Mouse Position: '+str(x)+', '+str(y) sbox = [x, y] boxes.append(sbox) elif event == cv.CV_EVENT_LBUTTONUP: print 'End Mouse Position: '+str(x)+', '+str(y) ebox = [x, y] boxes.append(ebox) count = 0 while(1): count += 1 _,img = cap.read() img = cv2.blur(img, (3,3)) cv2.namedWindow('real image') cv.SetMouseCallback('real image', on_mouse, 0) cv2.imshow('real image', img) if count < 50: if cv2.waitKey(33) == 27: cv2.destroyAllWindows() break elif count >= 50: if cv2.waitKey(0) == 27: cv2.destroyAllWindows() break count = 0
Python counter key value Question: My question is similar to my previous question: [Python list help (incrementing count, appending)](http://stackoverflow.com/questions/16172268/python-list-help- incrementing-count-appending). My accepted answer works well. However, this time I have a different question. I'm parsing a string from a json file, do some clean up then append it a new string. I need to get a counter of each word (which makes it a unique list, the counter for occurrence gets updated), sort it by high to low (I believe I need to use most_common here) then limit the list to 20. I can do all of this in JavaScript but not in python. In detail, I'm again running through a for loop to get each string from strings(json strings file) like this. # Counter for each word. words = Counter(); for e in strings: # I am cleaning up the string here for unwanted chars, make it lower case # and append it to a new string variable. # if I were to print the new string variable it will look like this: # hello test another test append hi hai hello hello # i know I need to call words.update # should I run a for loop in my new string variable for each word? Also how I can limit it to 20? What I would like to generate is something like this: word, count hello 3 test 2 another 1 append 1 hai 1 hi 1 Any suggestions would be great thanks. Answer: If you have a _list_ of words, you'd use the `.update()` method: words.update(some_list_of_words) You can pass in a generator expression too: words.update(word.lower() for word in e.split()) would split the string `e` into separate words on whitespace, then lowercase each word and count these. `.most_common()` takes a parameter, the maximum number of items to return: words.most_common(20) Demo with a smaller set of words, limiting it to the top 3 most common words: >>> from collections import Counter >>> words = Counter('spam ham eggs baz foo bar baz spam ham eggs spam spam bacon eggs ham spam spam spam eggs ham'.split()) >>> words.most_common(3) [('spam', 7), ('ham', 4), ('eggs', 4)]
How can I retrieve environment variables from remote system in Python? Question: I'm trying to retrieve environment variables of a remote Linux server in Python. Alternatively, if I could use the variable name in the command I'm executing, that'd be great as well. The calls I'm making should work, as far as I can tell, but I'm getting back garbage. I have set up public-key authentication, so no password required. Effort 1: devdir = subprocess.check_output(["ssh", connectstring, "echo $DEVDIR"]) Effort 2: ret = subprocess.check_output(["ssh", connectstring, "$DEVDIR/{0}".format(testpath)]) `connectstring` is user@ip and works fine. `$DEVDIR` is the remote variable I want to use and contains a path. `testpath` is the path to the script I'm trying to execute, rooted at `$DEVDIR`. Effort 1 returns "\n", Effort 2 fails to resolve $DEVDIR remotely. * * * Effort 3: import paramiko ... ssh = paramiko.SSHClient() ssh.connect(ip, user) # succeeds stdin, stdout, stderr = ssh.exec_command("echo $DEVDIR") result: stdout.readlines() = "\n" Answer: If the environment variable is set in `.bashrc`, you can force the remote command to run under a login shell with the `-l` option. The following... devdir = subprocess.check_output(["ssh", connectstring, "sh -l -c 'echo $DEVDIR'"]) ...works for me.
Python Requests library returns wrong status code Question: The Python code below returns '403': import requests url = 'http://bedstardirect.co.uk/star-collection-braemar-double-bedstead.html' r = requests.get(url) print r.status_code But this page is valid and the script should return '200', as does the perl script below: use WWW::Mechanize; my $mech = WWW::Mechanize->new(); my $url = 'http://bedstardirect.co.uk/star-collection-braemar-double-bedstead.html'; $mech->get($url); print $mech->status,"\n"; I have also checked with Firebug in Firefox and all requests have a '200' status code. I use Python Requests v1.2.0. Answer: Seems your particular server requires a User-Agent header. Try: `r = requests.get('http://bedstardirect.co.uk/star-collection-braemar-double- bedstead.html', headers={'User-Agent': 'a user agent'})` Edit: The default User-Agent on requests for my machine comes out as: `python- requests/1.2.0 CPython/2.7.4 Darwin/12.3.0` After some testing I found that any User-Agent that contains the word `python` will fail on this server.
Best way to distinguish between scalar, list and dict arguments in Python? Question: I want a function that normally takes in an argument of type X where X is either a scalar, a list, or a dict, and returns a list of X's with the same key values, based on other information. def foo(info, k): return [bar(item,k) for item in processInfo(info)] def bar(item, keydata): # pseudocode follows. # What we want to do is return an output of parallel type to the input key k, # using the key data to lookup information from the input item. if keydata is a scalar: return item[keydata] elif keydata is a list: return [item[k] for k in keydata] elif keydata is a dict: return dict((k,item[v]) for (k,v) in keydata.iteritems()) else: raise ValueError('bar expects a scalar, list, or dict') My question is, how can I dispatch between the three types? * * * edit: A string is to be interpreted as a scalar, not a list/iterable. Tuples are to be interpreted as iterable. edit 2: I want duck typing, not strict typing. Answer: You need to do things in the proper order since `str` and `dict` types are iterable. from collections import Iterable, Mapping # in Python 3 use from collections.abc def bar(item, keydata): if isinstance(keydata, Mapping): return {k: item[v] for (k,v) in keydata.iteritems()} elif isinstance(keydata, Iterable) and not isinstance(keydata, str): return [item[k] for k in keydata] return item[keydata]
python subprocess issue with Nmap Question: Im trying to get a linux binary to send its standard output to a variable by using subprocess. But just keep getting tracebacks. >>> import subprocess >>>nmap -sn -Pn todd.ns.cloudflare.com --script dns-check-zone --script-args='dns-check-zone.domain=www.macmonster.com Any Ideas (oh and Im using Python2.7). Ideally I would like to avoid using Shell=true to avoid any security concerns. Thanks, Answer: ## shlex to the rescue! The module shlex will take a string containing the whole shell command and split it up exactly how Popen and check_output expect it. Like this: import shlex, subprocess cmd = "/usr/bin/nmap -sn -Pn todd.ns.cloudflare.com --script dns-check-zone --script-args='dns-check-zone.domain=www.macmonster.com'" args = shlex.split(cmd) output = subprocess.check_output(args) When you look at contents of args you'll see: >>> print args ['/usr/bin/nmap', '-sn', '-Pn', 'todd.ns.cloudflare.com', '--script', 'dns-check-zone', '--script-args=dns-check-zone.domain=www.macmonster.com'] Note that shlex split up the option "--script dns-check-zone" into two tokens. On the other hand it kept "--script-args='dns-check- zone.domain=www.macmonster.com'", but removed the single-quotes.
Get array of Map's keys Question: I am trying to learn Java with a Python basis, so please bear with me. I am implementing a Sieve of Eratosthenes method (I have one in Python; trying to convert it to Java): def prevPrimes(n): """Generates a list of primes up to 'n'""" primes_dict = {i : True for i in range(3, n + 1, 2)} for i in primes_dict: if primes_dict[i]: num = i while (num * i <= n): primes_dict[num*i] = False num += 2 primes_dict[2] = True return [num for num in primes_dict if primes_dict[num]] This is my attempt to convert it to Java: import java.util.*; public class Sieve { public static void sieve(int n){ System.out.println(n); Map primes = new HashMap(); for(int x = 0; x < n+1; x++){ primes.put(x, true); } Set primeKeys = primes.keySet(); int[] keys = toArray(primeKeys); // attempt to convert the set to an array System.out.println(primesKeys); // the conversion does not work for(int x: keys){ System.out.println(x); } // still have more to add System.out.println(primes); } } The error I get is that it cannot find the method `toArray(java.util.Set)`. How can I fix this? Answer: First of all, use generics: Map<Integer, Boolean> map = new HashMap<Integer, Boolean>(); Set<Integer> keys = map.keySet(); Second, to convert the set to an array, you can use `toArray(T[] a)`: Integer[] array = keys.toArray(new Integer[keys.size()]); and if you want `int` instead of `Integer`, then iterate over each element: int[] array = new int[keys.size()]; int index = 0; for(Integer element : keys) array[index++] = element.intValue();
Python/BeautifulSoup - how to remove all tags from an element? Question: How can I simply strip all tags from an element I find in BeautifulSoup? Answer: With `BeautifulStoneSoup` gone in `bs4`, it's even simpler in Python3 from bs4 import BeautifulSoup soup = BeautifulSoup(html) text = soup.get_text() print(text)
Python: 'NoneType' object has no attribute 'get_username' Question: I'm working on a hangman program that also has user accounts objects. The player can log in, create a new account, or view account details, all of which work fine before playing the game. After the game has completed, the user's wins and losses are updated. Before exiting the program, if I try to view the account (the viewAcc function) I get the error: 'NoneType' object has no attribute 'get_username'. When I run the the program again, I can log in to the account, but when I view the account info the wins and losses haven't been updated. Any help would be appreciated, I have to turn this in for class in about 8 hours. Heres the class code: class Account: def __init__(self, username, password, name, email, win, loss): self.__username = username self.__password = password self.__name = name self.__email = email self.__win = int(win) self.__loss = int(loss) def set_username (self, username): self.__username = username def set_password (self, password): self.__password = password def set_name (self, name): self.__name = name def set_email (self, email): self.__email = email def set_win (self, win): self.__win = win def set_loss (self, loss): self.__loss = loss def get_username (self): return self.__username def get_password (self): return self.__password def get_name (self): return self.__name def get_email (self): return self.__email def get_win (self): return self.__win def get_loss (self): return self.__loss And here's my program's code: import random import os import Account import pickle import sys #List of images for different for different stages of being hanged STAGES = [ ''' ___________ |/ | | | | | | | | | | _____|______ ''' , ''' ___________ |/ | | | | (o_o) | | | | | | _____|______ ''' , ''' ___________ |/ | | | | (o_o) | | | | | | | | _____|______ ''' , ''' ___________ |/ | | | | (o_o) | |/ | | | | | | _____|______ ''' , ''' ___________ |/ | | | | (o_o) | \|/ | | | | | | _____|______ ''' , ''' ___________ |/ | | | | (o_o) | \|/ | | | / | | | _____|______ ''' , ''' YOU DEAD!!! ___________ |/ | | | | (X_X) | \|/ | | | / \ | | | _____|______ ''' ] #used to validate user input ALPHABET = ['abcdefghijklmnopqrstuvwxyz'] #Declares lists of different sized words fourWords = ['ties', 'shoe', 'wall', 'dime', 'pens', 'lips', 'toys', 'from', 'your', 'will', 'have', 'long', 'clam', 'crow', 'duck', 'dove', 'fish', 'gull', 'fowl', 'frog', 'hare', 'hair', 'hawk', 'deer', 'bull', 'bird', 'bear', 'bass', 'foal', 'moth', 'back', 'baby'] fiveWords = ['jazzy', 'faker', 'alien', 'aline', 'allot', 'alias', 'alert', 'intro', 'inlet', 'erase', 'error', 'onion', 'least', 'liner', 'linen', 'lions', 'loose', 'loner', 'lists', 'nasal', 'lunar', 'louse', 'oasis', 'nurse', 'notes', 'noose', 'otter', 'reset', 'rerun', 'ratio', 'resin', 'reuse', 'retro', 'rinse', 'roast', 'roots', 'saint', 'salad', 'ruins'] sixwords = ['baboon', 'python',] def main(): #Gets menu choice from user choice = menu() #Initializes dictionary of user accounts from file accDct = loadAcc() #initializes user's account user = Account.Account("", "", "", "", 0, 0) while choice != 0: if choice == 1: user = play(user) if choice == 2: createAcc(accDct) if choice == 3: user = logIn(accDct) if choice == 4: viewAcc(user) choice = menu() saveAcc(accDct) #Plays the game def play(user): os.system("cls") #Clears screen hangman = 0 #Used as index for stage view done = False #Used to signal when game is finished guessed = [''] #Holds letters already guessed #Gets the game word lenght from the user difficulty = int(input("Chose Difficulty/Word Length:\n"\ "1. Easy: Four Letter Word\n"\ "2. Medium: Five Letter Word\n"\ "3. Hard: Six Letter Word\n"\ "Choice: ")) #Validates input while difficulty < 1 or difficulty > 3: difficulty = int(input("Invalid menu choice.\n"\ "Reenter Choice(1-3): ")) #Gets a random word from a different list depending on difficulty if difficulty == 1: word = random.choice(fourWords) if difficulty == 2: word = random.choice(fiveWords) if difficulty == 3: word = random.choice(sixWords) viewWord = list('_'*len(word)) letters = list(word) while done == False: os.system("cls") print(STAGES[hangman]) for i in range(len(word)): sys.stdout.write(viewWord[i]) sys.stdout.write(" ") print() print("Guessed Letters: ") for i in range(len(guessed)): sys.stdout.write(guessed[i]) print() guess = str(input("Enter guess: ")) guess = guess.lower() while guess in guessed: guess = str(input("Already guessed that letter.\n"\ "Enter another guess: ")) while len(guess) != 1: guess = str(input("Guess must be ONE letter.\n"\ "Enter another guess: ")) while guess not in ALPHABET[0]: guess = str(input("Guess must be a letter.\n"\ "Enter another guess: ")) if guess not in letters: hangman+=1 for i in range(len(word)): if guess in letters[i]: viewWord[i] = guess guessed += guess if '_' not in viewWord: print ("Congratulations! You correctly guessed",word) done = True win = user.get_win() win += 1 username = user.get_username() password = user.get_password() name = user.get_name() email = user.get_email() loss = user.get_loss() user = Account.Account(username, password, name, email, win, loss) if hangman == 6: os.system("cls") print() print(STAGES[hangman]) print("You couldn't guess the word",word.upper(),"before being hanged.") print("Sorry, you lose.") done = True loss = user.get_loss() loss += 1 username = user.get_username() password = user.get_password() name = user.get_name() email = user.get_email() win = user.get_win() user = Account.Account(username, password, name, email, win, loss) #Loads user accounts from file def loadAcc(): try: iFile = open('userAccounts.txt', 'rb') accDct = pickle.load(iFile) iFile.close except IOError: accDct = {} return accDct #Displays the menu def menu(): os.system('cls') print("Welcome to Karl-Heinz's Hangman") choice = int(input("1. Play Hangman\n"\ "2. Create Account\n"\ "3. Log In\n"\ "4. View Account Details\n"\ "0. Quit Program\n"\ "Choice: ")) while choice < 0 or choice > 4: choice = int(input("Invalid Menu Choice.\n"\ "Reenter Choice: ")) return choice #Logs user in to existing account def logIn(accDct): os.system('cls') user = Account.Account("","","","",0,0) username = str(input("Enter Username(case sensitive): ")) if username not in accDct: print("Account does not exist") os.system("pause") return user temp = Account.Account("","","","",0,0) temp = accDct[username] password = str(input("Enter Password(case sensitive): ")) if password != temp.get_password(): print("Incorrect password.") os.system("pause") return user user = accDct[username] return user #Creates a new account and a new account file if one doesn't exist def createAcc(accDct): os.system('cls') print("Enter account info:") username = str(input("UserName: ")) if username in accDct: print("Account already exists.") os.system("pause") return password = str(input("Password: ")) name = str(input("Name: ")) email = str(input("Email: ")) wins = 0 loss = 0 tempuser = Account.Account(username, password, name, email, wins, loss) accDct[username] = tempuser print("Account created.") os.system("pause") def viewAcc(user): os.system('cls') print("Account Details: ") print("Username: ",user.get_username()) print("Name: ",user.get_name()) print("Email: ",user.get_email()) print("Wins: ",user.get_win()) print("Losses: ",user.get_loss()) os.system("pause") #Saves accounts dictionary to file def saveAcc(accDct): oFile = open("userAccounts.txt", "wb") pickle.dump(accDct, oFile) oFile.close() main() Any help is greatly appreciated. Answer: Your play() function doesn't have a `return` statement, which means it's returning `None` as its return value. That's how you're getting `None` into your `user` variable in main(). Add a `return` statement to your play() function and you should be fine.
SNMP Agent in Python Question: I required a SNMP agent in python, which listen on a particular port and and responds to basic SNMP command (like GTE, SET, GETNEXT ...etc) If any one have code please reply on this post. Answer: There's a collection of SNMP Command Responder scripts at [pysnmp web- site](http://pysnmp.sourceforge.net/examples/current/v3arch/agent/cmdrsp/v2c-custom- scalar-mib-objects.html). Here's a simple PySNMP-based Command Responder that uses text files in /tmp as a MIB data store. from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asynsock.dgram import udp from pysnmp.smi import instrum, error from pysnmp.proto.api import v2c snmpEngine = engine.SnmpEngine() config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 1161)) ) config.addV1System(snmpEngine, 'my-area', 'public', contextName='my-context') config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1,3,6), (1,3,6)) snmpContext = context.SnmpContext(snmpEngine) class FileInstrumController(instrum.AbstractMibInstrumController): def readVars(self, vars, acInfo=(None, None)): try: return [ (o,v2c.OctetString(open('/tmp/%s.txt' % o, 'r').read())) for o,v in vars ] except IOError: raise error.SmiError def writeVars(self, vars, acInfo=(None, None)): try: for o,v in vars: open('/tmp/%s.txt' % o, 'w').write(str(v)) return vars except IOError: raise error.SmiError snmpContext.registerContextName( v2c.OctetString('my-context'), # Context Name FileInstrumController() # Management Instrumentation ) cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) snmpEngine.transportDispatcher.jobStarted(1) try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise Keep in mind that this script is just a starter for you, it does not handle some corner cases.
Python/Django 1.5 DatabaseWrapper thread error Question: Throwing the following DatabaseError in Django 1.5.1 (and 1.5.0) and mysql when I runserver and attempt to load a local version of the web app: > DatabaseError at / > > DatabaseWrapper objects created in a thread can only be used in that same > thread. The object with alias 'default' was created in thread id 4365488128 > and this is thread id 140735183980896. The exception location is as follows: > /Users/USERNAME/.envs/PROJECT_NAME/lib/python2.7/site- > packages/django/db/backends/**init**.py in validate_thread_sharing, line 154 This happens only on the first page load. When I hit refresh the the web app loads as expected. The error returns when I alter Django/python code and the local server needs to re-validate. When that happens the first load once again throws the DatabaseError and subsequent loads once again do not. This issue is only happening on my Django 1.5 projects. I've uninstalled mysql and cleared the mysql binary files located in /usr/local/var/mysql. A fresh install of mysql has not solved this issue. A similar DatabaseError is discussed here but I'm not able to follow their solution: <https://code.djangoproject.com/ticket/17998> I'm at a loss here, any ideas or expertise would be appreciated. Thank you. Answer: I solved the issue by monkey patching before imports of django.*: import eventlet eventlet.monkey_patch() You understood than I use threads here.
how to use a variable with a GUI in python 3 Question: I'm trying to get this so when you press 'HELLO' five time the text turn red just its not adding any thing on when i add anything to the viable.this is the code. from tkinter import * class application(Frame): global t t=1 def info(self): print ("test") global t t=t+5 def createWidgets(self): global t t=t self.exet= Button(self) self.exet["text"] = "QUIT" self.exet["fg"] = "red" self.exet["command"] = self.quit self.exet.pack({"side": "left"}) self.hi = Button(self) self.hi["text"] = "HELLO", if t == 5: self.hi["fg"] = "red" self.hi["command"] = self.info self.hi.pack({"side": "left"}) def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() Thanks to anyone helps! Answer: You have a couple of problems here: First, you use a global variable and then you include it within the scope of your functions. Instead of this, you should use an instance variable (`self.t`, or even `self.counter` for better readability). Secondly, you are checking the value of the counter in `createWidgets`, which is only called once by the `__init__` method. You should increase and check its value in the event handler function on the button. class application(Frame): def info(self): self.counter += 1 print(self.counter) if self.counter == 5: self.hi["fg"] = "red" def createWidgets(self): self.counter = 0 self.exet= Button(self) self.exet["text"] = "QUIT" self.exet["fg"] = "red" self.exet["command"] = self.quit self.exet.pack({"side": "left"}) self.hi = Button(self) self.hi["text"] = "HELLO", self.hi["command"] = self.info self.hi.pack({"side": "left"}) def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets()
Problems in connecting to MusicBrainz database using psycopg2 Question: I am trying to connect to the MusicBrainz database using the psycopg2 python's module. I have followed the instructions presented on <http://musicbrainz.org/doc/MusicBrainz_Server/Setup>, but I cannot succeed in connecting. In particular I am using the following little script: import psycopg2 conn = psycopg2.connect( database = 'musicbrainz_db', user= 'musicbrainz', password = 'musicbrainz', port = 5000, host='10.16.65.250') print "Connection Estabilished" The problem is that when I launch it, it never reaches the print statement, and the console (I'm on linux) is block indefinitely. It does not even catches the ctrl-c kill, so I have to kill python itself in another console. What can cause this? Answer: You seem to be mistaking MusicBrainz-Server to be only the database. What's running on port 5000 is the Web Server. You can access `http://10.16.65.250:5000` in the browser. Postgres is also running, but listens on `localhost:5432`. This works: import psycopg2 conn = psycopg2.connect(database="musicbrainz_db", user="musicbrainz", password="musicbrainz", port="5432", host="localhost") print("Connection established") In order to make postgres listen to more than localhost you need to change `listen_addresses` in `/etc/postgresql/9.1/main/postgres.conf` and make an entry for your (client) host or network in `/etc/postgresql/9.1/main/pg_hba.conf`. My VM is running in a 192.168.1.0/24 network so I set `listen_addresses='*'` in postgres.conf and in pg_hab.conf: host all all 192.168.1.0/24 trust I can now connect from my local network to the DB in the VM. * * * Depending on what you actually need, you might not want to connect to the MusicBrainz Server via postgres. There is a [MusicBrainz web service](http://musicbrainz.org/doc/Development/XML_Web_Service/Version_2) you can access in the VM. Example: `http://10.16.65.250:5000/ws/2/artist/c5c2ea1c-4bde-4f4d-bd0b-47b200bf99d6`. In that case you might be interested in a library to process the data: [python-musicbrainzngs](http://python-musicbrainzngs.readthedocs.org/). EDIT: You need to set `musicbrainzngs.set_hostname("10.16.65.250:5000")` for musicbrainzngs to connect to your local VM.
Calling upon data in just 1 cell from sqlite in python Question: My question is essentially twofold. Firstly, I have a database using SQlite, which I'm running with Python. My database is: CREATE TABLE cards (id integer primary key autoincrement not null, ref text unique check(ref!=''), name text, description text, quantity integer default 0, cat1 text, cat2 text); INSERT INTO "cards" VALUES(1,'lx247','green door',NULL,20,'abstract',''); INSERT INTO "cards" VALUES(2,'lxx247','green door',NULL,20,'abstract',''); INSERT INTO "cards" VALUES(3,'lxx2f47','green door',NULL,20,'abstract',''); And I'm running the following python code: import sqlite3 as lite import sys con = lite.connect('cards.db') idn = raw_input("Enter your ID number") with con: cur=con.cursor() cur.execute("SELECT quantity FROM cards WHERE ref=?", idn) print "Quantity" + str(cur.fetchone()) Firstly, when I execute this script, and enter 'lx247' into the prompt, I get the following error message: Enter your ID numberlx247 Traceback (most recent call last): File "test1.py", line 7, in <module> cur.execute("SELECT quantity FROM cards WHERE ref=?", idn) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 5 supplied. I've identified that the 5 it refers to are the number of characters in what I enter into the idn input (lx247). If I change the line: cur.execute("SELECT quantity FROM cards WHERE ref=?", idn) to cur.execute("SELECT quantity FROM cards WHERE id=?", idn) and enter '2' at the prompt, it returns: Enter your ID number2 Quantity(20,) So this has told me there is something wrong with the way it is handling the idn parameter to look up the ref column. So my first question is **how do I get it to look up the value I enter in idn in column ref**? The second question is how do I then get it to output the value as a number, rather than in the form (20,), because I then want to later direct python to add or subtract another number, x, to it and update the entry in the database to 20+x, so I'm looking to create a variable in python that is the value of the quantity column for a certain ref entry. Answer: You need to pass in a _sequence_ of parameters, make it a tuple with one element: cur.execute("SELECT quantity FROM cards WHERE ref=?", (idn,)) Python strings are sequences too, so if `idn` is a 5-character string, python sees a sequence of length 5. The database always returns _rows_ of columns, even for results with only one column. A row is essentially a Python tuple, a sequence. It's the same problem as your `idn` parameter, but in reverse. Take the one column out of the result row by indexing: print "Quantity " + str(cur.fetchone()[0]) A quick demo with your sample database: >>> import sqlite3 >>> con = sqlite3.connect(':memory:') >>> con.executescript('''\ ... CREATE TABLE cards (id integer primary key autoincrement not null, ref text unique ... check(ref!=''), name text, description text, quantity integer default 0, cat1 text, ... cat2 text); ... ... INSERT INTO "cards" VALUES(1,'lx247','green door',NULL,20,'abstract',''); ... INSERT INTO "cards" VALUES(2,'lxx247','green door',NULL,20,'abstract',''); ... INSERT INTO "cards" VALUES(3,'lxx2f47','green door',NULL,20,'abstract',''); ... ''') <sqlite3.Cursor object at 0x10ad66ab0> >>> idn = 'lx247' >>> cur=con.cursor() >>> cur.execute("SELECT quantity FROM cards WHERE ref=?", (idn,)) <sqlite3.Cursor object at 0x10ad66b20> >>> print "Quantity " + str(cur.fetchone()[0]) Quantity 20
Python unpacking binary stream from tcp socket Question: ok, So I thought it would be a good idea to get familiar with Python. (I have had experience with Java, php, perl, VB, etc. not a master of any, but intermediate knowledge) so I am attempting to write a script that will take a the data from a socket, and translate it to the screen. rough beginning code to follow: my code seems to correctly read the binary info from the socket, but I can't unpack it since I don't have access to the original structure. I have the output for this stream with a different program, (which is terribly written which is why I am tackling this) when I do print out the recv, it's like this... b'L\x00k\x07vQ\n\x01\xffh\x00\x04NGIN\x04MAIN6Product XX finished reprocessing cdc XXXXX at jesadr 0c\x00k\x07vQ\n\x01\xffF\x00\x06CSSPRD\x0cliab_checkerCCheckpointed to XXXXXXXXXXXXXXXX:XXXXXXX.XXX at jesadr 0 (serial 0)[\x00l\x07vQ\n\x00\xff\x01\x00\x05MLIFE\x06dayendBdayend 1 Copyright XXXX XXXXXXX XXXXXXX XXXXX XXX XXXXXX XXXXXXXX. from looking at this, and comparing it to the output of the other program, I would surmise that it should be broken up like.. b'L\x00k\x07vQ\n\x01\xffh\x00\x04NGIN\x04MAIN6Product XX finished reprocessing cdc XXXXX at jesadr 0' with corresponding info 04-23 00:00:43 10 1 NGIN MAIN 255 104 Product XX finished reprocessing cdc XXXXX at jesadr 0 Now, based on my research, it looks like I need to use the "struct" and unpack it, however I have no idea of the original structure of this, I only know what info is available from it, and to be honest, I'm having a hell of a time figuring this out. I have used the python interpreter to attempt to unpack bits and pieces of the line, however it is an exercise in frustration. If anyone can at least help me get started, I would very much appreciate it. Thanks Answer: Okay. I think I've managed to decode it, although I'm not sure about the intermediate 16-bit value. This Python 2.7 code... from cStringIO import StringIO import struct import time def decode(f): def read_le16(f): return struct.unpack('<h', f.read(2))[0] def read_timestamp(f): ts = struct.unpack('<l', f.read(4))[0] return time.ctime(ts) def read_byte(f): return ord(f.read(1)) def read_pascal(f): l = ord(f.read(1)) return f.read(l) result = [] # Read total length result.append('Total message length is %d bytes' % read_le16(f)) # Read timestamp result.append(read_timestamp(f)) # Read 3 x byte result.append(read_byte(f)) result.append(read_byte(f)) result.append(read_byte(f)) # Read 1 x LE16 result.append(read_le16(f)) # Read 3 x pascal string result.append(read_pascal(f)) result.append(read_pascal(f)) result.append(read_pascal(f)) return result s = 'L\x00k\x07vQ\n\x01\xffh\x00\x04NGIN\x04MAIN6Product XX finished reprocessing cdc XXXXX at jesadr 0c\x00k\x07vQ\n\x01\xffF\x00\x06CSSPRD\x0cliab_checkerCCheckpointed to XXXXXXXXXXXXXXXX:XXXXXXX.XXX at jesadr 0 (serial 0)[\x00l\x07vQ\n\x00\xff\x01\x00\x05MLIFE\x06dayendBdayend 1 Copyright XXXX XXXXXXX XXXXXXX XXXXX XXX XXXXXX XXXXXXXX.' f = StringIO(s) print decode(f) print decode(f) print decode(f) ...yields... ['Total message length is 76 bytes', 'Tue Apr 23 05:00:43 2013', 10, 1, 255, 104, 'NGIN', 'MAIN', 'Product XX finished reprocessing cdc XXXXX at jesadr 0'] ['Total message length is 99 bytes', 'Tue Apr 23 05:00:43 2013', 10, 1, 255, 70, 'CSSPRD', 'liab_checker', 'Checkpointed to XXXXXXXXXXXXXXXX:XXXXXXX.XXX at jesadr 0 (serial 0)'] ['Total message length is 91 bytes', 'Tue Apr 23 05:00:44 2013', 10, 0, 255, 1, 'MLIFE', 'dayend', 'dayend 1 Copyright XXXX XXXXXXX XXXXXXX XXXXX XXX XXXXXX XXXXXXXX.'] The timestamps are out by 5 hours, so I'm assuming it's a timezone thing.
Python - Import module based on string then pass arguments Question: Ive searched the web and this site and cant find an answer to this problem. Im sure its right in front of me somewhere but cant find it. I need to be able to import a module based on a string. Then execute a function within that module while passing arguments. I can import based on the string and then execute using eval() but I know this is not the best way to handle this. I also cant seem to pass arguments that way. My current module that would be set based on a string is named TestAction.py and lives in a folder called Tasks. This is the content of TestAction.py: def doSomething(var): print var This is the code I am executing to import TestAction and execute. module = "Tasks.TestAction" import Tasks mymod = __import__(module) eval(module + ".doSomething()") How can I make this code #1 not use `eval()` and #2 pass the var argument to `doSomething()`? Thanks in advance! Answer: Is the function name also variable? If not, just use your imported module: mymod.doSomething('the var argument') if it is, use `getattr`: fun = 'doSomething' getattr(mymod, fun)('the var argument')
How to combine python lists, with shared items, into new lists Question: I am new to python and I hit a roadblock. I have a python list that contains a single list on each line. Basically, I would like to combine lists that share values among lists. For example, below is what my python list looks at the moment and what I would like the data to look like after the additional commands are executed. I know this sort of problem is ideal for sets and intersections, but I just haven't been able to get them to work correctly. I have also seen a post using indexes and that hasn't worked for me either. What the list looks like: [ ['mary', 'home'], ['mary', 'school'], ['mary', 'work'], ['bob', 'home'], ['bob', 'school'], ['bob', 'work'], ['tom', 'work'], ['tom', 'school'], ['tom', 'home'], ['bill', 'vacation'], ] What I want it to look like: [ ['mary', 'bob', 'tom', 'home', 'school', 'work'], ['bill', 'vacation'], ] Answer: Your example data suggests that order is important in your input data, which would complicate the situation. Assuming that it's actually just an example and order _isn't_ important, sets are indeed an ideal way to solve the problem: data = [ ['mary', 'home'], ['mary', 'school'], ['mary', 'work'], ['bob', 'home'], ['bob', 'school'], ['bob', 'work'], ['tom', 'work'], ['tom', 'school'], ['tom', 'home'], ['bill', 'vacation'], ] combined = [] for subset in [set(d) for d in data]: for candidate in combined: if not candidate.isdisjoint(subset): candidate.update(subset) break else: combined.append(subset) This uses Python's [`for`-`else`](http://docs.python.org/2/tutorial/controlflow.html#break-and- continue-statements-and-else-clauses-on-loops) construct, which not everyone is familiar with. `combined` will contain a list of sets, so you might want to convert them to lists depending on your use case.