instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
Difference between variable_scope and name_scope in TensorFlow
What is the difference between variable_scope and name_scope? The variable scope tutorial talks about variable_scope implicitly opening name_scope. I also noticed that creating a variable in a name_scope automatically expands its name with the scope name as well. So what is the difference?
When you create a variable with tf.get_variable instead of tf.Variable, Tensorflow will start checking the names of the vars created with the same method to see if they collide. If they do, an exception will be raised. If you created a var with tf.get_variable and you try to change the prefix of your variable names by using the tf.name_scope context manager, this won't prevent the Tensorflow of raising an exception. Only tf.variable_scope context manager will effectively change the name of your var in this case. Or if you want to reuse the variable you should call scope.reuse_variables() before creating the var the second time. In summary, tf.name_scope just add a prefix to all tensor created in that scope (except the vars created with tf.get_variable), and tf.variable_scope add a prefix to the variables created with tf.get_variable.
Flask-restful API Authorization. Access current_identity inside decorator
I use flask-restful to create my APIs. I have used flask-jwt for enabling authentication based on JWT. Now I need to do authorization. I have tried putting my authorization decorator. test.py (/test api) from flask_restful import Resource from flask_jwt import jwt_required from authorization_helper import authorized_api_user_type class Test(Resource): decorators = [jwt_required(), authorized_api_user_type()] def get(self): return 'GET OK' def post(self): return 'POST OK' Basically to handle the basic authorization, I need to access current_identity and check it's type. Then based on it's type I am gonna decided whether the user is authorized to access the api / resources. But current_identity appears to be empty in that decorator. So to acquire it indirectly, I had to see the code of jwt_handler and do the thing done there. authorization_helper.py from functools import wraps from flask_jwt import _jwt, JWTError import jwt from models import Teacher, Student def authorized_api_user_type(realm=None, user_type='teacher'): def wrapper(fn): @wraps(fn) def decorator(*args, **kwargs): token = _jwt.request_callback() if token is None: raise JWTError('Authorization Required', 'Request does not contain an access token', headers={'WWW-Authenticate': 'JWT realm="%s"' % realm}) try: payload = _jwt.jwt_decode_callback(token) except jwt.InvalidTokenError as e: raise JWTError('Invalid token', str(e)) identity = _jwt.identity_callback(payload) if user_type == 'student' and isinstance(identity, Student): return fn(*args, **kwargs) elif user_type == 'teacher' and isinstance(identity, Teacher): return fn(*args, **kwargs) # NOTE - By default JWTError throws 401. We needed 404. Hence status_code=404 raise JWTError('Unauthorized', 'You are unauthorized to request the api or access the resource', status_code=404) return decorator return wrapper Why can't I just access current_identity in my authorized_api_user_type decorator? What is the RIGHT way of doing authorization in flask-restful?
Here is the combination of quickstarts of both Flask-JWT and Flask-Restful. from flask import Flask from flask_restful import Resource, Api, abort from functools import wraps app = Flask(__name__) api = Api(app) from flask_jwt import JWT, jwt_required, current_identity from werkzeug.security import safe_str_cmp class User(object): def __init__(self, id, username, password): self.id = id self.username = username self.password = password def __str__(self): return "User(id='%s')" % self.id users = [ User(1, 'user1', 'abcxyz'), User(2, 'user2', 'abcxyz'), ] username_table = {u.username: u for u in users} userid_table = {u.id: u for u in users} def authenticate(username, password): user = username_table.get(username, None) if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')): return user def identity(payload): user_id = payload['identity'] return userid_table.get(user_id, None) app.config['SECRET_KEY'] = 'super-secret' jwt = JWT(app, authenticate, identity) def checkuser(func): @wraps(func) def wrapper(*args, **kwargs): if current_identity.username == 'user1': return func(*args, **kwargs) return abort(401) return wrapper class HelloWorld(Resource): decorators = [checkuser, jwt_required()] def get(self): return {'hello': current_identity.username} api.add_resource(HelloWorld, '/') if __name__ == '__main__': app.run(debug=True) POST { "username": "user1", "password": "abcxyz" } To localhost:5000/auth and get the access_token in response. Then GET localhost:5000/ with header Authorization: JWT `the access_token value above` You would get { "hello": "user1" } if you try to access localhost:5000/ with the JWT token of user2, you would get 401. The decorators are wrapped in this way: for decorator in self.decorators: resource_func = decorator(resource_func) https://github.com/flask-restful/flask-restful/blob/master/flask_restful/init.py#L445 So the later one in the decorators array gets to run earlier. For more reference: https://github.com/rchampa/timetable/blob/master/restful/users.py https://github.com/mattupstate/flask-jwt/issues/37
Installing custom builds heroku and issue with Library paths
I'm attempting to install a custom build on heroku, so I'm using a variety of ways to attempt a third part installing using the buildpacks. In my .buildpacks file I have: https://github.com/ddollar/heroku-buildpack-apt https://github.com/heroku/heroku-buildpack-python.git and in my Aptfile I have the following: libgeoip-dev which is a pre-requisite for geoip which is installed with the requirements.txt (GeoIP==1.3.2) Here are my environment variables: remote: C_INCLUDE_PATH is /app/.heroku/vendor/include:/app/.heroku/vendor/include:/app/.heroku/python/include remote: CPATH is /tmp/build_xxxxx/.apt/usr/include: remote: LD_LIBRARY_PATH is /app/.heroku/vendor/lib:/app/.heroku/vendor/lib:/app/.heroku/python/lib The error message I am getting is: remote: building 'GeoIP' extension remote: creating build remote: creating build/temp.linux-x86_64-2.7 remote: gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/app/.heroku/python/include/python2.7 -c py_GeoIP.c -o build/temp.linux-x86_64-2.7/py_GeoIP.o -fno-strict-aliasing remote: creating build/lib.linux-x86_64-2.7 remote: gcc -pthread -shared build/temp.linux-x86_64-2.7/py_GeoIP.o -lGeoIP -o build/lib.linux-x86_64-2.7/GeoIP.so remote: /usr/bin/ld: cannot find -lGeoIP remote: collect2: error: ld returned 1 exit status remote: error: command 'gcc' failed with exit status 1 What is the smartest way to fix this? I.e. I guess I cannot change where the package manager installs. Is there a way around this?
https://github.com/heroku/heroku-buildpack-python/blob/master/bin/compile#L99-L107 # Prepend proper path buildpack use. export PATH=$BUILD_DIR/.heroku/python/bin:$BUILD_DIR/.heroku/vendor/bin:$PATH export PYTHONUNBUFFERED=1 export LANG=en_US.UTF-8 export C_INCLUDE_PATH=/app/.heroku/vendor/include:$BUILD_DIR/.heroku/vendor/include:/app/.heroku/python/include export CPLUS_INCLUDE_PATH=/app/.heroku/vendor/include:$BUILD_DIR/.heroku/vendor/include:/app/.heroku/python/include export LIBRARY_PATH=/app/.heroku/vendor/lib:$BUILD_DIR/.heroku/vendor/lib:/app/.heroku/python/lib export LD_LIBRARY_PATH=/app/.heroku/vendor/lib:$BUILD_DIR/.hero ku/vendor/lib:/app/.heroku/python/lib export PKG_CONFIG_PATH=/app/.heroku/vendor/lib/pkg-config:$BUILD_DIR/.heroku/vendor/lib/pkg-config:/app/.heroku/python/lib/pkg-config vs. https://github.com/ddollar/heroku-buildpack-apt/blob/master/bin/compile#L75-L81 export PATH="$BUILD_DIR/.apt/usr/bin:$PATH" export LD_LIBRARY_PATH="$BUILD_DIR/.apt/usr/lib/x86_64-linux-gnu:$BUILD_DIR/.apt/usr/lib/i386-linux-gnu:$BUILD_DIR/.apt/usr/lib:$LD_LIBRARY_PATH" export LIBRARY_PATH="$BUILD_DIR/.apt/usr/lib/x86_64-linux-gnu:$BUILD_DIR/.apt/usr/lib/i386-linux-gnu:$BUILD_DIR/.apt/usr/lib:$LIBRARY_PATH" export INCLUDE_PATH="$BUILD_DIR/.apt/usr/include:$INCLUDE_PATH" export CPATH="$INCLUDE_PATH" export CPPPATH="$INCLUDE_PATH" export PKG_CONFIG_PATH="$BUILD_DIR/.apt/usr/lib/x86_64-linux-gnu/pkgconfig:$BUILD_DIR/.apt/usr/lib/i386-linux-gnu/pkgconfig:$BUILD_DIR/.apt/usr/lib/pkgconfig:$PKG_CONFIG_PATH" The heroku-buildpack-python buildpack is not playing nice with heroku-buildpack-apt buildpack as it is clobbering important variables for gcc to link your python extension with the geoip lib. File a bug on the issue tracker. Issue tracker: https://github.com/heroku/heroku-buildpack-python/issues
How to assign value to a tensorflow variable?
I am trying to assign a new value to a tensorflow variable in python. import tensorflow as tf import numpy as np x = tf.Variable(0) init = tf.initialize_all_variables() sess = tf.InteractiveSession() sess.run(init) print(x.eval()) x.assign(1) print(x.eval()) But the output I get is 0 0 So the value has not changed. What am I missing?
The statement x.assign(1) does not actually assign the value 1 to x, but rather creates a tf.Operation that you have to explicitly run to update the variable.* A call to Operation.run() or Session.run() can be used to run the operation: assign_op = x.assign(1) sess.run(assign_op) # or `assign_op.op.run()` print(x.eval()) # ==> 1 (* In fact, it returns a tf.Tensor, corresponding to the updated value of the variable, to make it easier to chain assignments.)
Difference between np.mean and tf.reduce_mean (numpy | tensorflow)?
In the following tutorial: https://www.tensorflow.org/versions/master/tutorials/mnist/beginners/index.html There is accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) tf.cast basically changes the type of tensor the object is...but what is the difference between tf.reduce_mean and np.mean? Here is the doc on tf.reduce_mean reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None) input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the defaut), reduces all dimensions. # 'x' is [[1., 1. ]] # [2., 2.]] tf.reduce_mean(x) ==> 1.5 tf.reduce_mean(x, 0) ==> [1.5, 1.5] tf.reduce_mean(x, 1) ==> [1., 2.] For a 1D vector, it looks like np.mean == tf.reduce_mean but I don't understand what's happening in tf.reduce_mean(x, 1) ==> [1., 2.]. tf.reduce_mean(x, 0) ==> [1.5, 1.5] kind of makes sense, since mean of [1,2] and [1,2] are [1.5,1.5] but what's going on with tf.reduce_mean(x,1) ?
The functionality of numpy.mean and tensorflow.reduce_mean are the same. They do the same thing. From the documentation, for numpy and tensorflow, you can see that. Lets look at an example, c = np.array([[3.,4], [5.,6], [6.,7]]) print(np.mean(c,1)) Mean = tf.reduce_mean(c,1) with tf.Session() as sess: result = sess.run(Mean) print(result) Output [ 3.5 5.5 6.5] [ 3.5 5.5 6.5] Here you can see that when axis(numpy) or reduction_indices(tensorflow) is 1, it computes mean across (3,4) and (5,6) and (6,7), so 1 defines across which axis the mean is computed. When it is 0, the mean is computed across(3,5,6) and (4,6,7), and so on. I hope you get the idea. Now what are the differences between them? You can compute the numpy operation anywhere on python. But in order to do a tensorflow operation, it must be done inside a tensorflow Session. You can read more about it here. So when you need to perform any computation for your tensorflow graph(or structure if you will), it must be done inside a tensorflow Session. Lets look at another example. npMean = np.mean(c) print(npMean+1) tfMean = tf.reduce_mean(c) Add = tfMean + 1 with tf.Session() as sess: result = sess.run(Add) print(result) We could increase mean by 1 in numpy as you would naturally, but in order to do it in tensorflow, you need to perform that in Session, without using Session you can't do that. In other words, when you are computing tfMean = tf.reduce_mean(c), tensorflow doesn't compute it then. It only computes that in a Session. But numpy computes that instantly, when you write np.mean(). I hope it makes sense.
difference between tensorflow tf.nn.softmax and tf.nn.softmax_cross_entropy_with_logits
I was going through the tensorflow api docs here. In tensorflow docs they used a keyword called logits. What is it? In a lot of methods in the api docs it is written like, tf.nn.softmax(logits, name=None) Now what it is written is that logits are only Tensors. Well why keep a different name like logits? I almost thought that it was logics. :D. Another thing is that there are two methods i could not differentiate. They were tf.nn.softmax(logits, name=None) tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None) What are the differences between them? The docs are not clear to me. I know what tf.nn.softmax does. But not the other. An example will be really helpful.
Logits simply means that the function operates on the unscaled output of earlier layers and that the relative scale to understand the units is linear. It means, in particular, the sum of the inputs may not equal 1, that the values are not probabilities (you might have an input of 5). tf.nn.softmax produces just the result of applying the softmax function to an input tensor. The softmax "squishes" the inputs so that sum(input) = 1; it's a way of normalizing. The shape of output of a softmax is the same as the input - it just normalizes the values. The outputs of softmax can be interpreted as probabilities. a = tf.constant(np.array([[.1, .3, .5, .9]])) print s.run(tf.nn.softmax(a)) [[ 0.16838508 0.205666 0.25120102 0.37474789]] In contrast, tf.nn.softmax_cross_entropy_with_logits computes the cross entropy of the result after applying the softmax function (but it does it all together in a more mathematically careful way). It's similar to the result of: sm = tf.nn.softmax(x) ce = cross_entropy(sm) The cross entropy is a summary metric - it sums across the elements. The output of tf.nn.softmax_cross_entropy_with_logits on a shape [2,5] tensor is of shape [2,1] (the first dimension is treated as the batch). If you want to do optimization to minimize the cross entropy, AND you're softmaxing after your last layer, you should use tf.nn.softmax_cross_entropy_with_logits instead of doing it yourself, because it covers numerically unstable corner cases in the mathematically right way. Otherwise, you'll end up hacking it by adding little epsilons here and there. (Edited 2016-02-07: If you have single-class labels, where an object can only belong to one class, you might now consider using tf.nn.sparse_softmax_cross_entropy_with_logits so that you don't have to convert your labels to a dense one-hot array. This function was added after release 0.6.0.)
Acessing POST field data without a form (REST api) using Django
In the django documentation, it says: HttpRequest.POST A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead. However, the server does not respond to a browser (such as using JS frameworks or a form) but instead a REST api sent by an Anroid/iOS application. If the client sends fields directly in a POST request, how can I read the data? For example, this (Java + Unirest): Unirest.post("/path/to/server") .field("field1", "value2") .field("field2", "value2"); EDIT: Can I simply read the data usingresponse.POST["field1"], or will I have to do something with request.body? EDIT 2: So I can simply use request.body as a dictionary-like object similar to request.POST?
As far as I understand the field method from Unirest just uses normal application/x-www-form-urlencoded data like a HTML form. So you should be able to just use response.POST["field1"] like you suggested.
Patch __call__ of a function
I need to patch current datetime in tests. I am using this solution: def _utcnow(): return datetime.datetime.utcnow() def utcnow(): """A proxy which can be patched in tests. """ # another level of indirection, because some modules import utcnow return _utcnow() Then in my tests I do something like: with mock.patch('***.utils._utcnow', return_value=***): ... But today an idea came to me, that I could make the implementation simpler by patching __call__ of function utcnow instead of having an additional _utcnow. This does not work for me: from ***.utils import utcnow with mock.patch.object(utcnow, '__call__', return_value=***): ... How to do this elegantly?
[EDIT] Maybe the most interesting part of this question is Why I cannot patch somefunction.__call__? Because the function don't use __call__'s code but __call__ (a method-wrapper object) use function's code. I don't find any well sourced documentation about that, but I can prove it (Python2.7): >>> def f(): ... return "f" ... >>> def g(): ... return "g" ... >>> f <function f at 0x7f1576381848> >>> f.__call__ <method-wrapper '__call__' of function object at 0x7f1576381848> >>> g <function g at 0x7f15763817d0> >>> g.__call__ <method-wrapper '__call__' of function object at 0x7f15763817d0> Replace f's code by g's code: >>> f.func_code = g.func_code >>> f() 'g' >>> f.__call__() 'g' Of course f and f.__call__ references are not changed: >>> f <function f at 0x7f1576381848> >>> f.__call__ <method-wrapper '__call__' of function object at 0x7f1576381848> Recover original implementation and copy __call__ references instead: >>> def f(): ... return "f" ... >>> f() 'f' >>> f.__call__ = g.__call__ >>> f() 'f' >>> f.__call__() 'g' This don't have any effect on f function. Note: In Python 3 you should use __code__ instead of func_code. I Hope that somebody can point me to the documentation that explain this behavior. You have a way to work around that: in utils you can define class Utcnow(object): def __call__(self): return datetime.datetime.utcnow() utcnow = Utcnow() And now your patch can work like a charm. Follow the original answer that I consider even the best way to implement your tests. I've my own gold rule: never patch protected methods. In this case the things are little bit smoother because protected method was introduced just for testing but I cannot see why. The real problem here is that you cannot to patch datetime.datetime.utcnow directly (is C extension as you wrote in the comment above). What you can do is to patch datetime by wrap the standard behavior and override utcnow function: >>> with mock.patch("datetime.datetime", mock.Mock(wraps=datetime.datetime, utcnow=mock.Mock(return_value=3))): ... print(datetime.datetime.utcnow()) ... 3 Ok that is not really clear and neat but you can introduce your own function like def mock_utcnow(return_value): return mock.Mock(wraps=datetime.datetime, utcnow=mock.Mock(return_value=return_value)): and now mock.patch("datetime.datetime", mock_utcnow(***)) do exactly what you need without any other layer and for every kind of import. Another solution can be import datetime in utils and to patch ***.utils.datetime; that can give you some freedom to change datetime reference implementation without change your tests (in this case take care to change mock_utcnow() wraps argument too).
Find "one letter that appears twice" in a string
I'm trying to catch if one letter that appears twice in a string using RegEx (or maybe there's some better ways?), for example my string is: ugknbfddgicrmopn The output would be: dd However, I've tried something like: re.findall('[a-z]{2}', 'ugknbfddgicrmopn') but in this case, it returns: ['ug', 'kn', 'bf', 'dd', 'gi', 'cr', 'mo', 'pn'] # the except output is `['dd']` I also have a way to get the expect output: >>> l = [] >>> tmp = None >>> for i in 'ugknbfddgicrmopn': ... if tmp != i: ... tmp = i ... continue ... l.append(i*2) ... ... >>> l ['dd'] >>> But that's too complex... If it's 'abbbcppq', then only catch: abbbcppq ^^ ^^ So the output is: ['bb', 'pp'] Then, if it's 'abbbbcppq', catch bb twice: abbbbcppq ^^^^ ^^ So the output is: ['bb', 'bb', 'pp']
You need use capturing group based regex and define your regex as raw string. >>> re.search(r'([a-z])\1', 'ugknbfddgicrmopn').group() 'dd' >>> [i+i for i in re.findall(r'([a-z])\1', 'abbbbcppq')] ['bb', 'bb', 'pp'] or >>> [i[0] for i in re.findall(r'(([a-z])\2)', 'abbbbcppq')] ['bb', 'bb', 'pp'] Note that , re.findall here should return the list of tuples with the characters which are matched by the first group as first element and the second group as second element. For our case chars within first group would be enough so I mentioned i[0].
Adding lambda functions with the same operator in python
I have a rather lengthy equation that I need to integrate over using scipy.integrate.quad and was wondering if there is a way to add lambda functions to each other. What I have in mind is something like this y = lambda u: u**(-2) + 8 x = lambda u: numpy.exp(-u) f = y + x int = scipy.integrate.quad(f, 0, numpy.inf) The equations that I am really using are far more complicated than I am hinting at here, so for readability it would be useful to break up the equation into smaller, more manageable parts. Is there a way to do with with lambda functions? Or perhaps another way which does not even require lambda functions but will give the same output?
In Python, you'll normally only use a lambda for very short, simple functions that easily fit inside the line that's creating them. (Some languages have other opinions.) As @DSM hinted in their comment, lambdas are essentially a shortcut to creating functions when it's not worth giving them a name. If you're doing more complex things, or if you need to give the code a name for later reference, a lambda expression won't be much of a shortcut for you -- instead, you might as well define a plain old function. So instead of assigning the lambda expression to a variable: y = lambda u: u**(-2) + 8 You can define that variable to be a function: def y(u): return u**(-2) + 8 Which gives you room to explain a bit, or be more complex, or whatever you need to do: def y(u): """ Bloopinate the input u should be a positive integer for fastest results. """ offset = 8 bloop = u ** (-2) return bloop + offset Functions and lambdas are both "callable", which means they're essentially interchangable as far as scipy.integrate.quad() is concerned. To combine callables, you can use several different techniques. def triple(x): return x * 3 def square(x): return x * x def triple_square(x): return triple(square(x)) def triple_plus_square(x): return triple(x) + square(x) def triple_plus_square_with_explaining_variables(x): tripled = triple(x) squared = square(x) return tripled + squared There are more advanced options that I would only consider if it makes your code clearer (which it probably won't). For example, you can put the callables in a list: all_the_things_i_want_to_do = [triple, square] Once they're in a list, you can use list-based operations to work on them (including applying them in turn to reduce the list down to a single value). But if your code is like most code, regular functions that just call each other by name will be the simplest to write and easiest to read.
Error in function to return 3 largest values from a list of numbers
I have this data file and I have to find the 3 largest numbers it contains 24.7 25.7 30.6 47.5 62.9 68.5 73.7 67.9 61.1 48.5 39.6 20.0 16.1 19.1 24.2 45.4 61.3 66.5 72.1 68.4 60.2 50.9 37.4 31.1 10.4 21.6 37.4 44.7 53.2 68.0 73.7 68.2 60.7 50.2 37.2 24.6 21.5 14.7 35.0 48.3 54.0 68.2 69.6 65.7 60.8 49.1 33.2 26.0 19.1 20.6 40.2 50.0 55.3 67.7 70.7 70.3 60.6 50.7 35.8 20.7 14.0 24.1 29.4 46.6 58.6 62.2 72.1 71.7 61.9 47.6 34.2 20.4 8.4 19.0 31.4 48.7 61.6 68.1 72.2 70.6 62.5 52.7 36.7 23.8 11.2 20.0 29.6 47.7 55.8 73.2 68.0 67.1 64.9 57.1 37.6 27.7 13.4 17.2 30.8 43.7 62.3 66.4 70.2 71.6 62.1 46.0 32.7 17.3 22.5 25.7 42.3 45.2 55.5 68.9 72.3 72.3 62.5 55.6 38.0 20.4 17.6 20.5 34.2 49.2 54.8 63.8 74.0 67.1 57.7 50.8 36.8 25.5 20.4 19.6 24.6 41.3 61.8 68.5 72.0 71.1 57.3 52.5 40.6 26.2 Therefore I have written the following code, but it only searches the first row of numbers instead of the entire list. Can anyone help to find the error? def three_highest_temps(f): file = open(f, "r") largest = 0 second_largest = 0 third_largest = 0 temp = [] for line in file: temps = line.split() for i in temps: if i > largest: largest = i elif largest > i > second_largest: second_largest = i elif second_largest > i > third_largest: third_largest = i return largest, second_largest, third_largest print(three_highest_temps("data5.txt"))
Your data contains float numbers not integer. You can use sorted: >>> data = '''24.7 25.7 30.6 47.5 62.9 68.5 73.7 67.9 61.1 48.5 39.6 20.0 ... 16.1 19.1 24.2 45.4 61.3 66.5 72.1 68.4 60.2 50.9 37.4 31.1 ... 10.4 21.6 37.4 44.7 53.2 68.0 73.7 68.2 60.7 50.2 37.2 24.6 ... 21.5 14.7 35.0 48.3 54.0 68.2 69.6 65.7 60.8 49.1 33.2 26.0 ... 19.1 20.6 40.2 50.0 55.3 67.7 70.7 70.3 60.6 50.7 35.8 20.7 ... 14.0 24.1 29.4 46.6 58.6 62.2 72.1 71.7 61.9 47.6 34.2 20.4 ... 8.4 19.0 31.4 48.7 61.6 68.1 72.2 70.6 62.5 52.7 36.7 23.8 ... 11.2 20.0 29.6 47.7 55.8 73.2 68.0 67.1 64.9 57.1 37.6 27.7 ... 13.4 17.2 30.8 43.7 62.3 66.4 70.2 71.6 62.1 46.0 32.7 17.3 ... 22.5 25.7 42.3 45.2 55.5 68.9 72.3 72.3 62.5 55.6 38.0 20.4 ... 17.6 20.5 34.2 49.2 54.8 63.8 74.0 67.1 57.7 50.8 36.8 25.5 ... 20.4 19.6 24.6 41.3 61.8 68.5 72.0 71.1 57.3 52.5 40.6 26.2 ... ''' >>> sorted(map(float, data.split()), reverse=True)[:3] [74.0, 73.7, 73.7] If you want to integer results >>> temps = sorted(map(float, data.split()), reverse=True)[:3] >>> map(int, temps) [74, 73, 73]
Install python3-venv module on linux mint
I was able to move to Linux mint 17.3 64 bit version from my Linux mint 16. This was long awaited migration. After moving to Linux Mint 17.3, I am not able to the install python3-venv module, which is said to be the replacement for virtualenv in python 3.x. In my linux mint 16 I had access to pyvenv-3.4 tool. I dont know when I installed that module in Linux mint 16. Anybody faced this issue ? python -m venv test The virtual environment was not created successfully because ensurepip is not available. On Debian/Ubuntu systems, you need to install the python3-venv package using the following command. apt-get install python3-venv You may need to use sudo with that command. After installing the python3-venv package, recreate your virtual environment. izero@Ganesha ~/devel $ sudo apt-get install python3-venv [sudo] password for izero: Reading package lists... Done Building dependency tree Reading state information... Done E: Unable to locate package python3-venv
Try running this command: sudo apt-get install python3.4-venv Then use this: python3 -m venv test the package name is python3.4-venv and not python3-venv.
Why is str.translate faster in Python 3.5 compared to Python 3.4?
I was trying to remove unwanted characters from a given string using text.translate() in Python 3.4. The minimal code is: import sys s = 'abcde12345@#@$#%$' mapper = dict.fromkeys(i for i in range(sys.maxunicode) if chr(i) in '@#$') print(s.translate(mapper)) It works as expected. However the same program when executed in Python 3.4 and Python 3.5 gives a large difference. The code to calculate timings is python3 -m timeit -s "import sys;s = 'abcde12345@#@$#%$'*1000 ; mapper = dict.fromkeys(i for i in range(sys.maxunicode) if chr(i) in '@#$'); " "s.translate(mapper)" The Python 3.4 program takes 1.3ms whereas the same program in Python 3.5 takes only 26.4μs. What has improved in Python 3.5 that makes it faster compared to Python 3.4?
TL;DR - ISSUE 21118 The long Story Josh Rosenberg found out that the str.translate() function is very slow compared to the bytes.translate, he raised an issue, stating that: In Python 3, str.translate() is usually a performance pessimization, not optimization. Why was str.translate() slow? The main reason for str.translate() to be very slow was that the lookup used to be in a Python dictionary. The usage of maketrans made this problem worse. The similar approach using bytes builds a C array of 256 items to fast table lookup. Hence the usage of higher level Python dict makes the str.translate() in Python 3.4 very slow. What happened now? The first approach was to add a small patch, translate_writer, However the speed increase was not that pleasing. Soon another patch fast_translate was tested and it yielded very nice results of up to 55% speedup. The main change as can be seen from the file is that the Python dictionary lookup is changed into a C level lookup. The speeds now are almost the same as bytes unpatched patched str.translate 4.55125927699919 0.7898181750006188 str.translate from bytes trans 1.8910855210015143 0.779950579000797 A small note here is that the performance enhancement is only prominent in ASCII strings. As J.F.Sebastian mentions in a comment below, Before 3.5, translate used to work in the same way for both ASCII and non-ASCII cases. However from 3.5 ASCII case is much faster. Earlier ASCII vs non-ascii used to be almost same, however now we can see a great change in the performance. It can be an improvement from 71.6μs to 2.33μs as seen in this answer. The following code demonstrates this python3.5 -m timeit -s "text = 'mJssissippi'*100; d=dict(J='i')" "text.translate(d)" 100000 loops, best of 3: 2.3 usec per loop python3.5 -m timeit -s "text = 'm\U0001F602ssissippi'*100; d={'\U0001F602': 'i'}" "text.translate(d)" 10000 loops, best of 3: 117 usec per loop python3 -m timeit -s "text = 'm\U0001F602ssissippi'*100; d={'\U0001F602': 'i'}" "text.translate(d)" 10000 loops, best of 3: 91.2 usec per loop python3 -m timeit -s "text = 'mJssissippi'*100; d=dict(J='i')" "text.translate(d)" 10000 loops, best of 3: 101 usec per loop Tabulation of the results: Python 3.4 Python 3.5 Ascii 91.2 2.3 Unicode 101 117
standard deviation and errors bars in seaborn tsplot function in Python
How does Seaborn compute its error bars? example: import numpy as np; np.random.seed(22) import seaborn as sns; sns.set(color_codes=True) x = np.linspace(0, 15, 31) data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1) ax = sns.tsplot(data=data, err_style="ci_bars") plt.show() how are the ci_bars (or ci_bands) calculated? also, is it possible to make tsplot plot in ci_bars style where the error bars or bands correspond to the standard deviation of the values at each time point? (and not standard error of mean, or bootstraps)
Another workaround for plotting standard deviation could be to use matplotlib errorbar on top of seaborn tsplot: import numpy as np; import seaborn as sns; import pandas as pd # create a group of time series num_samples = 90 group_size = 10 x = np.linspace(0, 10, num_samples) group = np.sin(x) + np.linspace(0, 2, num_samples) + np.random.rand(group_size, num_samples) + np.random.randn(group_size, 1) df = pd.DataFrame(group.T, index=range(0,num_samples)) # plot time series with seaborn ax = sns.tsplot(data=df.T.values) #, err_style="unit_traces") # Add std deviation bars to the previous plot mean = df.mean(axis=1) std = df.std(axis=1) ax.errorbar(df.index, mean, yerr=std, fmt='-o') #fmt=None to plot bars only plt.show()
Disable special "class" attribute handling
The Story: When you parse HTML with BeautifulSoup, class attribute is considered a multi-valued attribute and is handled in a special manner: Remember that a single tag can have multiple values for its “class” attribute. When you search for a tag that matches a certain CSS class, you’re matching against any of its CSS classes. Also, a quote from a built-in HTMLTreeBuilder used by BeautifulSoup as a base for other tree builder classes, like, for instance, HTMLParserTreeBuilder: # The HTML standard defines these attributes as containing a # space-separated list of values, not a single value. That is, # class="foo bar" means that the 'class' attribute has two values, # 'foo' and 'bar', not the single value 'foo bar'. When we # encounter one of these attributes, we will parse its value into # a list of values if possible. Upon output, the list will be # converted back into a string. The Question: How can I configure BeautifulSoup to handle class as a usual single-valued attribute? In other words, I don't want it to handle class specially and consider it a regular attribute. FYI, here is one of the use-cases when it can be helpful: BeautifulSoup returns empty list when searching by compound class names What I've tried: I've actually made it work by making a custom tree builder class and removing class from the list of specially-handled attributes: from bs4.builder._htmlparser import HTMLParserTreeBuilder class MyBuilder(HTMLParserTreeBuilder): def __init__(self): super(MyBuilder, self).__init__() # BeautifulSoup, please don't treat "class" specially self.cdata_list_attributes["*"].remove("class") soup = BeautifulSoup(data, "html.parser", builder=MyBuilder()) What I don't like in this approach is that it is quite "unnatural" and "magical" involving importing "private" internal _htmlparser. I hope there is a simpler way. NOTE: I want to save all other HTML parsing related features, meaning I don't want to parse HTML with "xml"-only features (which could've been another workaround).
What I don't like in this approach is that it is quite "unnatural" and "magical" involving importing "private" internal _htmlparser. I hope there is a simpler way. Yes, you can import it from bs4.builder instead: from bs4 import BeautifulSoup from bs4.builder import HTMLParserTreeBuilder class MyBuilder(HTMLParserTreeBuilder): def __init__(self): super(MyBuilder, self).__init__() # BeautifulSoup, please don't treat "class" as a list self.cdata_list_attributes["*"].remove("class") soup = BeautifulSoup(data, "html.parser", builder=MyBuilder()) And if it's important enough that you don't want to repeat yourself, put the builder in its own module, and register it with register_treebuilders_from() so that it takes precedence.
How to cache reads?
I am using python/pysam to do analyze sequencing data. In its tutorial (pysam - An interface for reading and writing SAM files) for the command mate it says: 'This method is too slow for high-throughput processing. If a read needs to be processed with its mate, work from a read name sorted file or, better, cache reads.' How would you 'cache reads'?
Caching is a typical approach to speed up long running operations. It sacrifices memory for the sake of computational speed. Let's suppose you have a function which given a set of parameters always returns the same result. Unfortunately this function is very slow and you need to call it a considerable amount of times slowing down your program. What you could do, is storing a limited amount of {parameters: result} combinations and skip its logic any time the function is called with the same parameters. It's a dirty trick but quite effective especially if the parameters combination is low compared to the function speed. In Python 3 there's a decorator for this purpose. In Python 2 a library can help but you need a bit more work.
"Failed building wheel for psycopg2" - MacOSX using virtualenv and pip
I'm attempting to make a website with a few others for the first time, and have run into a weird error when trying to use Django/Python/VirtualEnv. I've found solutions to this problem for other operating systems, such as Ubuntu, but can't find any good solutions for Mac. This is the relevant code being run: virtualenv -p python3 venv source venv/bin/activate pip install -r requirements.txt After running that block, I get the following errors: AssertionError Failed building wheel for django-toolbelt Running setup.py bdist_wheel for psycopg2 ... AssertionError Failed building wheel for psycopg2 Failed to build django-toolbelt psycopg2 I believe I've installed the "django-toolbelt" and "psycopg2", so I'm not sure why it would be failing. The only difference I can think of is that I did not use the command sudo apt-get install libpq-dev as was instructed for Ubuntu usage as I believe that installing postgresql with brew took care of the header. Thanks for any help or insight!
I had the same problem on Arch linux. I think that it's not an OS dependant problem. Anyway, I fixed this by finding the outdated packages and updating then. pip uninstall psycopg2 pip list --outdated pip install --upgrade wheel pip install --upgrade setuptools pip install psycopg2 hope this helps...
Why values of an OrderedDict are not equal?
With Python 3: >>> from collections import OrderedDict >>> d1 = OrderedDict([('foo', 'bar')]) >>> d2 = OrderedDict([('foo', 'bar')]) I want to check equality: >>> d1 == d2 True >>> d1.keys() == d2.keys() True But: >>> d1.values() == d2.values() False Do you know why values are not equal? Tested with Python 3.4 and 3.5 Following this question, I posted on the Python-Ideas mailing list to have additional details: https://mail.python.org/pipermail/python-ideas/2015-December/037472.html
In Python 3, dict.keys() and dict.values() return special iterable classes - respectively a collections.abc.KeysView and a collections.abc.ValuesView. The first one inherit it's __eq__ method from set, the second uses the default object.__eq__ which tests on object identity.
Indexing a list with an unique index
I have a list say l = [10,10,20,15,10,20]. I want to assign each unique value a certain "index" to get [1,1,2,3,1,2]. This is my code: a = list(set(l)) res = [a.index(x) for x in l] Which turns out to be very slow. l has 1M elements, and 100K unique elements. I have also tried map with lambda and sorting, which did not help. What is the ideal way to do this?
You can do this in O(N) time using a defaultdict and a list comprehension: >>> from itertools import count >>> from collections import defaultdict >>> lst = [10, 10, 20, 15, 10, 20] >>> d = defaultdict(count(1).next) >>> [d[k] for k in lst] [1, 1, 2, 3, 1, 2] In Python 3 use __next__ instead of next. If you're wondering how it works? The default_factory(i.e count(1).next in this case) passed to defaultdict is called only when Python encounters a missing key, so for 10 the value is going to be 1, then for the next ten it is not a missing key anymore hence the previously calculated 1 is used, now 20 is again a missing key and Python will call the default_factory again to get its value and so on. d at the end will look like this: >>> d defaultdict(<method-wrapper 'next' of itertools.count object at 0x1057c83b0>, {10: 1, 20: 2, 15: 3})
Haystack says “Model could not be found for SearchResult”
After updating my Django from 1.7 to 1.9, search engine, which is based on Haystack and Solr, stopped working. This is what I get: ./manage.py shell Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from haystack.query import SearchQuerySet >>> sqs = SearchQuerySet().all() >>>sqs[0].pk u'1' >>> sqs[0].text u'\u06a9\u0627\u0645\u0631\u0627\u0646 \u0647\u0645\u062a\u200c\u067e\u0648\u0631 \u0648 \u0641\u0631\u0647\u0627\u062f \u0628\u0627\u062f\u067e\u0627\nKamran Hematpour &amp; Farhad Badpa' >>> sqs[0].model_name u'artist' >>> sqs[0].id u'mediainfo.artist.1' >>> sqs[0].object Model could not be found for SearchResult '<SearchResult: mediainfo.artist (pk=u'1')>'. I have to say my database is not empy and my configuration is as follow: HAYSTACK_CONNECTIONS ={ 'default': { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://ahangsolr:8983/solr', }, } And this is my search_indexes.py: import datetime from haystack import indexes from mediainfo.models import Album from mediainfo.models import Artist from mediainfo.models import PlayList from mediainfo.models import Track from mediainfo.models import Lyric class AlbumIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) artist = indexes.CharField(model_attr='artist', indexed=True) publish_date = indexes.DateTimeField(model_attr='publish_date') def get_model(self): return Album def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.filter(publish_date__lte=datetime.datetime.now()) class ArtistIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Artist class PlaylistIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return PlayList class TrackIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Track class LyricIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Lyric
I was able to fix the issue by including a missing commit to the 2.4.1 release. The commit that fixed this issue was https://github.com/django-haystack/django-haystack/commit/f1ed18313777005dd77ed724ecbfb27c0b03cad8 so you can do pip install git+ssh://git@github.com/django-haystack/django-haystack.git@f1ed18313777005dd77ed724ecbfb27c0b03cad8 to install until that specific commit.
Setting group permissions with python
That is my setup: I have a VirtualMachine (Ubuntu 14.04. LTS), where there is running a PostgreSQL/PostGIS database. With Windows 7 in QGIS I connect to this database and load feature layer into my GIS project. With some python code I create a file with a tile ID and some information. import os import io import time layer=None for lyr in QgsMapLayerRegistry.instance().mapLayers().values(): if lyr.name() == "fishnet_final": layer = lyr for f in layer.selectedFeatures(): pth = os.path.join(os.path.dirname(r'H:\path_to_file\'), str(f['name']) + "_" + str(time.strftime("%Y-%m-%d")) + "_" + str(f['country']) + ".txt") fle = open(pth,'wb') fle.writelines(str(f['name'])) fle.write('\n') fle.write(str(time.strftime("%Y-%d-%m"))) fle.write('\n') fle.write(str(f['country'])) fle.write('\n') fle.close() os.rename(pth, pth.replace(' ', '')) The file has the permissions: -rwx------ I want to set also the same permissions for my group and other. -rwxrwxrwx I tried: import shlex command=shlex.split("chmod 777 r'H:\path_to_file\file.txt'") subprocess.call(command) No success. What was working is: command=shlex.split("touch r'H:\path_to_file\file.txt'") OR command=shlex.split("rm r'H:\path_to_file\file.txt'") Why doesn't work the chmod command? Under UNIX I can chmod this file and I'am the same user like in Windows. I also tried the os.chmod method. But no success. import os, stat st = os.stat(r'H:\path_to_file\file.txt') os.chmod(r'H:\path_to_file\file.txt', st.st_mode | 0o111 ) UPDATE When I do a "chmod 777 file" under UNIX (Solaris) the permissions are -rwxrwxrwx What I can do now is to downgrade/remove permissions under Windows in the GIS project: subprocess.call(r'chmod 400 "H:\path_to_file\file.txt"', shell=True) 0 -r-xr-xr-x With this command I get a 0 feedback in the python console output I also get a 0 feedback when I do a chmod 777 on the new file but nothing happens. The Problem is that I can only downgrade permissions. I can't set new permissions!
From the os module documentation: Note: Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored. For Windows permissions, you manage the ACLs. Adapting from another answer, you need the pywin32 library: import win32security import ntsecuritycon as con FILENAME = r"H:\path_to_file\file.txt" user, domain, type = win32security.LookupAccountName ("", "Your Username") sd = win32security.GetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION) dacl = sd.GetSecurityDescriptorDacl() # instead of dacl = win32security.ACL() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, user) sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary win32security.SetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd) Change the con.FILE_ALL_ACCESS flag to the ones you need.
Tensorflow read images with labels
I am building a standard image classification model with Tensorflow. For this I have input images, each assigned with a label (number in {0,1}). The Data can hence be stored in a list using the following format: /path/to/image_0 label_0 /path/to/image_1 label_1 /path/to/image_2 label_2 ... I want to use TensorFlow's queuing system to read my data and feed it to my model. Ignoring the labels, one can easily achieve this by using string_input_producer and wholeFileReader. Here the code: def read_my_file_format(filename_queue): reader = tf.WholeFileReader() key, value = reader.read(filename_queue) example = tf.image.decode_png(value) return example #removing label, obtaining list containing /path/to/image_x image_list = [line[:-2] for line in image_label_list] input_queue = tf.train.string_input_producer(image_list) input_images = read_my_file_format(input_queue) However, the labels are lost in that process as the image data is purposely shuffled as part of the input pipeline. What is the easiest way of pushing the labels together with the image data through the input queues?
There are three main steps to solving this problem: Populate the tf.train.string_input_producer() with a list of strings containing the original, space-delimited string containing the filename and the label. Use tf.read_file(filename) rather than tf.WholeFileReader() to read your image files. tf.read_file() is a stateless op that consumes a single filename and produces a single string containing the contents of the file. It has the advantage that it's a pure function, so it's easy to associate data with the input and the output. For example, your read_my_file_format function would become: def read_my_file_format(filename_and_label_tensor): """Consumes a single filename and label as a ' '-delimited string. Args: filename_and_label_tensor: A scalar string tensor. Returns: Two tensors: the decoded image, and the string label. """ filename, label = tf.decode_csv(filename_and_label_tensor, [[""], [""]], " ") file_contents = tf.read_file(filename) example = tf.image.decode_png(file_contents) return example, label Invoke the new version of read_my_file_format by passing a single dequeued element from the input_queue: image, label = read_my_file_format(input_queue.dequeue()) You can then use the image and label tensors in the remainder of your model.
Sending JSON data over WebSocket from Matlab using Python Twisted and Autobahn
I'm trying to create a connection from Matlab to stream JSON frames over a WebSocket. I've tested my python installation of autobahn and twisted using the following. Working Example Matlab Code Sample driver code that uses the JSONlab toolbox to convert Matlab data to JSON form and then I compress and Base64 encode the data. Since I haven't gotten RPC to work I'm using the command-line where I need compression and Base64 encoding to avoid line-length and shell escaping issues. clear all close all python = '/usr/local/bin/python' bc = '/Users/palmerc/broadcast_client.py' i = uint32(1) encoder = org.apache.commons.codec.binary.Base64 while true tic; packet = rand(100, 100); json_packet = uint8(savejson('', packet)); compressed = CompressLib.compress(json_packet); b64 = char(encoder.encode(compressed)); message = sprintf('%s %s %s', python, bc, b64); status = system(message); i = i + 1; toc; end Broadcast Client Code The client code has two ways of being called. You can pass your message through the command-line or create an instance of BroadcastClient and call sendMessage. #!/usr/bin/env python import sys from twisted.internet import reactor from txjsonrpc.web.jsonrpc import Proxy class BroadcastClient(): def __init__(self, server=None): self.proxy = Proxy(server) def errorMessage(self, value): print 'Error ', value def sendMessage(self, message): rc = self.proxy.callRemote('broadcastMessage', message).addCallback(lambda _: reactor.stop()) rc.addErrback(self.errorMessage) def main(cli_arguments): if len(cli_arguments) > 1: message = cli_arguments[1] broadcastClient = BroadcastClient('http://127.0.0.1:7080/') broadcastClient.sendMessage(message) reactor.run() if __name__ == '__main__': main(sys.argv) Broadcast Server Code The server provides an RPC client on 7080, a web client on 8080, and a WebSocket on 9080 using TXJSONRPC, Twisted, and Autobahn. The Autobahn Web Client is useful for debugging and should be placed in the same directory as the server code. #!/usr/bin/env python import sys from twisted.internet import reactor from twisted.python import log from twisted.web.server import Site from twisted.web.static import File from txjsonrpc.web import jsonrpc from autobahn.twisted.websocket import WebSocketServerFactory, \ WebSocketServerProtocol, \ listenWS class BroadcastServerProtocol(WebSocketServerProtocol): def onOpen(self): self.factory.registerClient(self) def onMessage(self, payload, isBinary): if not isBinary: message = "{} from {}".format(payload.decode('utf8'), self.peer) self.factory.broadcastMessage(message) def connectionLost(self, reason): WebSocketServerProtocol.connectionLost(self, reason) self.factory.unregisterClient(self) class BroadcastServerFactory(WebSocketServerFactory): """ Simple broadcast server broadcasting any message it receives to all currently connected clients. """ def __init__(self, url, debug=False, debugCodePaths=False): WebSocketServerFactory.__init__(self, url, debug=debug, debugCodePaths=debugCodePaths) self.clients = [] def registerClient(self, client): if client not in self.clients: print("registered client {}".format(client.peer)) self.clients.append(client) def unregisterClient(self, client): if client in self.clients: print("unregistered client {}".format(client.peer)) self.clients.remove(client) def broadcastMessage(self, message): print("broadcasting message '{}' ..".format(message)) for client in self.clients: client.sendMessage(message.encode('utf8')) print("message sent to {}".format(client.peer)) class BroadcastPreparedServerFactory(BroadcastServerFactory): """ Functionally same as above, but optimized broadcast using prepareMessage and sendPreparedMessage. """ def broadcastMessage(self, message): print("broadcasting prepared message '{}' ..".format(message)) preparedMessage = self.prepareMessage(message.encode('utf8'), isBinary=False) for client in self.clients: client.sendPreparedMessage(preparedMessage) print("prepared message sent to {}".format(client.peer)) class MatlabClient(jsonrpc.JSONRPC): factory = None def jsonrpc_broadcastMessage(self, message): if self.factory is not None: print self.factory.broadcastMessage(message) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'debug': log.startLogging(sys.stdout) debug = True else: debug = False factory = BroadcastPreparedServerFactory(u"ws://127.0.0.1:9000", debug=debug, debugCodePaths=debug) factory.protocol = BroadcastServerProtocol listenWS(factory) matlab = MatlabClient() matlab.factory = factory reactor.listenTCP(7080, Site(matlab)) webdir = File(".") web = Site(webdir) reactor.listenTCP(8080, web) reactor.run() The Problem - Failed Attempts First a note, If you have trouble getting python working from Matlab you need to make sure you're pointing at the correct version of Python on your system using the pyversion command and you can correct it using pyversion('/path/to/python') Matlab can't run reactor clear all close all i = uint32(1) while true tic; packet = rand(100, 100); json_packet = uint8(savejson('', packet)); compressed = CompressLib.compress(json_packet); b64 = char(encoder.encode(compressed)); bc.sendMessage(py.str(b64.')); py.twisted.internet.reactor.run % This won't work. i = i + 1; toc; end Matlab POST Another attempt involved using Matlab's webwrite to POST to the server. Turns out webwrite will convert data to JSON simply by passing the correct weboptions. options = weboptions('MediaType', 'application/json'); data = struct('Matrix', rand(100, 100)); webwrite(server, data, options); This worked, but turns out to be slow (~0.1 seconds) per message. I should mention that the matrix is not the real data I'm sending, the real data serializes to about 280000 bytes per message, but this provides a reasonable approximation. How can I call bc.sendMessage so that it correctly manages to get reactor to run or solve this issue in another, faster way?
Setting up a WebSocket using Python and Matlab Check Matlab is pointing at the correct version of python First, you need to make sure you're using the correct python binary. On Mac you might be using the system standard version instead of the one that Homebrew installed for example. Check the location of your python install using: pyversion You can point Matlab to the correct version using: pyversion('path/to/python') this may require you restart python. As stated above I'm using Twisted to multiplex my Matlab data to the WebSocket clients. The best way I have found to solve this problem has been simply to create a server that handles POSTS and then passes that along to the WebSocket clients. Compression just slowed things down so I send 280 kBytes of JSON per request which is taking roughly 0.05 seconds per message. I would like this to be faster, .01 seconds, but this is a good start. Matlab Code server = 'http://127.0.0.1:7080/update.json'; headers = py.dict(pyargs('Charset','UTF-8','Content-Type','application/json')); while true tic; packet = rand(100, 100); json_packet = savejson('', packet); r = py.requests.post(server, pyargs('data', json_packet, 'headers', headers)); toc; end I could have used the Matlab webwrite function, but generally I find calling out to python to be more flexible. Python WebSocket-WebClient Server import sys from twisted.internet import reactor from twisted.python import log from twisted.web.resource import Resource from twisted.web.server import Site from twisted.web.static import File from autobahn.twisted.websocket import WebSocketServerFactory, \ WebSocketServerProtocol, \ listenWS class BroadcastServerProtocol(WebSocketServerProtocol): def onOpen(self): self.factory.registerClient(self) def onMessage(self, payload, isBinary): if not isBinary: message = "{} from {}".format(payload.decode('utf8'), self.peer) self.factory.broadcastMessage(message) def connectionLost(self, reason): WebSocketServerProtocol.connectionLost(self, reason) self.factory.unregisterClient(self) class BroadcastServerFactory(WebSocketServerFactory): def __init__(self, url, debug=False, debugCodePaths=False): WebSocketServerFactory.__init__(self, url, debug=debug, debugCodePaths=debugCodePaths) self.clients = [] def registerClient(self, client): if client not in self.clients: print("registered client {}".format(client.peer)) self.clients.append(client) def unregisterClient(self, client): if client in self.clients: print("unregistered client {}".format(client.peer)) self.clients.remove(client) def broadcastMessage(self, message): for client in self.clients: client.sendMessage(message.encode('utf8')) class BroadcastPreparedServerFactory(BroadcastServerFactory): def broadcastMessage(self, message, isBinary=False): if isBinary is True: message = message.encode('utf8') preparedMessage = self.prepareMessage(message, isBinary=isBinary) for client in self.clients: client.sendPreparedMessage(preparedMessage) class WebClient(Resource): webSocket = None def render_POST(self, request): self.webSocket.broadcastMessage(request.content.read()) return 'OK' if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'debug': log.startLogging(sys.stdout) debug = True else: debug = False factory = BroadcastPreparedServerFactory(u"ws://127.0.0.1:9000", debug=debug, debugCodePaths=debug) factory.protocol = BroadcastServerProtocol listenWS(factory) root = Resource() webClient = WebClient() webClient.webSocket = factory root.putChild('update.json', webClient) webFactory = Site(root) reactor.listenTCP(7080, webFactory) webdir = File(".") web = Site(webdir) reactor.listenTCP(8080, web) reactor.run() I got rid of the RPC attempt and just went with a straight POST. Still lots of opportunity for performance improvement.
Diffie-Hellman (to RC4) with Wincrypt From Python
I am currently working on a project written in C++ that leverages the CryptoAPI to perform a Diffie-Hellman key exchange. I'm having a bit of trouble getting this to work as the eventual RC4 session key I get cannot be used to encrypt the same text in Python (using pycrypto). The C++ code to perform the Diffie-Hellman key exchange was taken from msdn, but is included here for posterity: #include <tchar.h> #include <windows.h> #include <wincrypt.h> #pragma comment(lib, "crypt32.lib") // The key size, in bits. #define DHKEYSIZE 512 // Prime in little-endian format. static const BYTE g_rgbPrime[] = { 0x91, 0x02, 0xc8, 0x31, 0xee, 0x36, 0x07, 0xec, 0xc2, 0x24, 0x37, 0xf8, 0xfb, 0x3d, 0x69, 0x49, 0xac, 0x7a, 0xab, 0x32, 0xac, 0xad, 0xe9, 0xc2, 0xaf, 0x0e, 0x21, 0xb7, 0xc5, 0x2f, 0x76, 0xd0, 0xe5, 0x82, 0x78, 0x0d, 0x4f, 0x32, 0xb8, 0xcb, 0xf7, 0x0c, 0x8d, 0xfb, 0x3a, 0xd8, 0xc0, 0xea, 0xcb, 0x69, 0x68, 0xb0, 0x9b, 0x75, 0x25, 0x3d, 0xaa, 0x76, 0x22, 0x49, 0x94, 0xa4, 0xf2, 0x8d }; // Generator in little-endian format. static BYTE g_rgbGenerator[] = { 0x02, 0x88, 0xd7, 0xe6, 0x53, 0xaf, 0x72, 0xc5, 0x8c, 0x08, 0x4b, 0x46, 0x6f, 0x9f, 0x2e, 0xc4, 0x9c, 0x5c, 0x92, 0x21, 0x95, 0xb7, 0xe5, 0x58, 0xbf, 0xba, 0x24, 0xfa, 0xe5, 0x9d, 0xcb, 0x71, 0x2e, 0x2c, 0xce, 0x99, 0xf3, 0x10, 0xff, 0x3b, 0xcb, 0xef, 0x6c, 0x95, 0x22, 0x55, 0x9d, 0x29, 0x00, 0xb5, 0x4c, 0x5b, 0xa5, 0x63, 0x31, 0x41, 0x13, 0x0a, 0xea, 0x39, 0x78, 0x02, 0x6d, 0x62 }; BYTE g_rgbData[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; int _tmain(int argc, _TCHAR* argv[]) { UNREFERENCED_PARAMETER(argc); UNREFERENCED_PARAMETER(argv); BOOL fReturn; HCRYPTPROV hProvParty1 = NULL; HCRYPTPROV hProvParty2 = NULL; DATA_BLOB P; DATA_BLOB G; HCRYPTKEY hPrivateKey1 = NULL; HCRYPTKEY hPrivateKey2 = NULL; PBYTE pbKeyBlob1 = NULL; PBYTE pbKeyBlob2 = NULL; HCRYPTKEY hSessionKey1 = NULL; HCRYPTKEY hSessionKey2 = NULL; PBYTE pbData = NULL; /************************ Construct data BLOBs for the prime and generator. The P and G values, represented by the g_rgbPrime and g_rgbGenerator arrays respectively, are shared values that have been agreed to by both parties. ************************/ P.cbData = DHKEYSIZE/8; P.pbData = (BYTE*)(g_rgbPrime); G.cbData = DHKEYSIZE/8; G.pbData = (BYTE*)(g_rgbGenerator); /************************ Create the private Diffie-Hellman key for party 1. ************************/ // Acquire a provider handle for party 1. fReturn = CryptAcquireContext( &hProvParty1, NULL, MS_ENH_DSS_DH_PROV, PROV_DSS_DH, CRYPT_VERIFYCONTEXT); if(!fReturn) { goto ErrorExit; } // Create an ephemeral private key for party 1. fReturn = CryptGenKey( hProvParty1, CALG_DH_EPHEM, DHKEYSIZE << 16 | CRYPT_EXPORTABLE | CRYPT_PREGEN, &hPrivateKey1); if(!fReturn) { goto ErrorExit; } // Set the prime for party 1's private key. fReturn = CryptSetKeyParam( hPrivateKey1, KP_P, (PBYTE)&P, 0); if(!fReturn) { goto ErrorExit; } // Set the generator for party 1's private key. fReturn = CryptSetKeyParam( hPrivateKey1, KP_G, (PBYTE)&G, 0); if(!fReturn) { goto ErrorExit; } // Generate the secret values for party 1's private key. fReturn = CryptSetKeyParam( hPrivateKey1, KP_X, NULL, 0); if(!fReturn) { goto ErrorExit; } /************************ Create the private Diffie-Hellman key for party 2. ************************/ // Acquire a provider handle for party 2. fReturn = CryptAcquireContext( &hProvParty2, NULL, MS_ENH_DSS_DH_PROV, PROV_DSS_DH, CRYPT_VERIFYCONTEXT); if(!fReturn) { goto ErrorExit; } // Create an ephemeral private key for party 2. fReturn = CryptGenKey( hProvParty2, CALG_DH_EPHEM, DHKEYSIZE << 16 | CRYPT_EXPORTABLE | CRYPT_PREGEN, &hPrivateKey2); if(!fReturn) { goto ErrorExit; } // Set the prime for party 2's private key. fReturn = CryptSetKeyParam( hPrivateKey2, KP_P, (PBYTE)&P, 0); if(!fReturn) { goto ErrorExit; } // Set the generator for party 2's private key. fReturn = CryptSetKeyParam( hPrivateKey2, KP_G, (PBYTE)&G, 0); if(!fReturn) { goto ErrorExit; } // Generate the secret values for party 2's private key. fReturn = CryptSetKeyParam( hPrivateKey2, KP_X, NULL, 0); if(!fReturn) { goto ErrorExit; } /************************ Export Party 1's public key. ************************/ // Public key value, (G^X) mod P is calculated. DWORD dwDataLen1; // Get the size for the key BLOB. fReturn = CryptExportKey( hPrivateKey1, NULL, PUBLICKEYBLOB, 0, NULL, &dwDataLen1); if(!fReturn) { goto ErrorExit; } // Allocate the memory for the key BLOB. if(!(pbKeyBlob1 = (PBYTE)malloc(dwDataLen1))) { goto ErrorExit; } // Get the key BLOB. fReturn = CryptExportKey( hPrivateKey1, 0, PUBLICKEYBLOB, 0, pbKeyBlob1, &dwDataLen1); if(!fReturn) { goto ErrorExit; } /************************ Export Party 2's public key. ************************/ // Public key value, (G^X) mod P is calculated. DWORD dwDataLen2; // Get the size for the key BLOB. fReturn = CryptExportKey( hPrivateKey2, NULL, PUBLICKEYBLOB, 0, NULL, &dwDataLen2); if(!fReturn) { goto ErrorExit; } // Allocate the memory for the key BLOB. if(!(pbKeyBlob2 = (PBYTE)malloc(dwDataLen2))) { goto ErrorExit; } // Get the key BLOB. fReturn = CryptExportKey( hPrivateKey2, 0, PUBLICKEYBLOB, 0, pbKeyBlob2, &dwDataLen2); if(!fReturn) { goto ErrorExit; } /************************ Party 1 imports party 2's public key. The imported key will contain the new shared secret key (Y^X) mod P. ************************/ fReturn = CryptImportKey( hProvParty1, pbKeyBlob2, dwDataLen2, hPrivateKey1, 0, &hSessionKey2); if(!fReturn) { goto ErrorExit; } /************************ Party 2 imports party 1's public key. The imported key will contain the new shared secret key (Y^X) mod P. ************************/ fReturn = CryptImportKey( hProvParty2, pbKeyBlob1, dwDataLen1, hPrivateKey2, 0, &hSessionKey1); if(!fReturn) { goto ErrorExit; } /************************ Convert the agreed keys to symmetric keys. They are currently of the form CALG_AGREEDKEY_ANY. Convert them to CALG_RC4. ************************/ ALG_ID Algid = CALG_RC4; // Enable the party 1 public session key for use by setting the // ALGID. fReturn = CryptSetKeyParam( hSessionKey1, KP_ALGID, (PBYTE)&Algid, 0); if(!fReturn) { goto ErrorExit; } // Enable the party 2 public session key for use by setting the // ALGID. fReturn = CryptSetKeyParam( hSessionKey2, KP_ALGID, (PBYTE)&Algid, 0); if(!fReturn) { goto ErrorExit; } /************************ Encrypt some data with party 1's session key. ************************/ // Get the size. DWORD dwLength = sizeof(g_rgbData); fReturn = CryptEncrypt( hSessionKey1, 0, TRUE, 0, NULL, &dwLength, sizeof(g_rgbData)); if(!fReturn) { goto ErrorExit; } // Allocate a buffer to hold the encrypted data. pbData = (PBYTE)malloc(dwLength); if(!pbData) { goto ErrorExit; } // Copy the unencrypted data to the buffer. The data will be // encrypted in place. memcpy(pbData, g_rgbData, sizeof(g_rgbData)); // Encrypt the data. dwLength = sizeof(g_rgbData); fReturn = CryptEncrypt( hSessionKey1, 0, TRUE, 0, pbData, &dwLength, sizeof(g_rgbData)); if(!fReturn) { goto ErrorExit; } /************************ Decrypt the data with party 2's session key. ************************/ dwLength = sizeof(g_rgbData); fReturn = CryptDecrypt( hSessionKey2, 0, TRUE, 0, pbData, &dwLength); if(!fReturn) { goto ErrorExit; } ErrorExit: if(pbData) { free(pbData); pbData = NULL; } if(hSessionKey2) { CryptDestroyKey(hSessionKey2); hSessionKey2 = NULL; } if(hSessionKey1) { CryptDestroyKey(hSessionKey1); hSessionKey1 = NULL; } if(pbKeyBlob2) { free(pbKeyBlob2); pbKeyBlob2 = NULL; } if(pbKeyBlob1) { free(pbKeyBlob1); pbKeyBlob1 = NULL; } if(hPrivateKey2) { CryptDestroyKey(hPrivateKey2); hPrivateKey2 = NULL; } if(hPrivateKey1) { CryptDestroyKey(hPrivateKey1); hPrivateKey1 = NULL; } if(hProvParty2) { CryptReleaseContext(hProvParty2, 0); hProvParty2 = NULL; } if(hProvParty1) { CryptReleaseContext(hProvParty1, 0); hProvParty1 = NULL; } return 0; } I believe that I can complete the Diffie-Hellman key exchange in Python, as I can generate the same public and private keys without error. I've based my Diffie-Hellman key exchange on this repository. I haven't been able to test this, however as I can't seem to get the shared secret exported from the C++ code (similar to this thread, that was never satisfactorily answered). I can however get the RC4 session key with the following code: // Get the key length DWORD keylen; CryptExportKey( hSessionKey1, NULL, PLAINTEXTKEYBLOB, 0, NULL, &keylen); // Get the session key CryptExportKey( hSessionKey1, NULL, PLAINTEXTKEYBLOB, 0, encKey, &keylen); The output from this function gets me: 08 02 00 00 01 68 00 00 10 00 00 00 75 2c 59 8c 6e e0 8c 9f ed 30 17 7e 9d a5 85 2b I know there is a 12 byte header+length on this, so that leaves me with the following 16 byte RC4 session key: 75 2c 59 8c 6e e0 8c 9f ed 30 17 7e 9d a5 85 2b So I am currently trying to validate that I can encrypt the same plaintext using the RC4 that I have acquired from the CryptExportKey. I am currently trying to encrypt g_rgbData from the C++ code above, which is set to: BYTE g_rgbData[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; With the C++ code I get the following encrypted output: cc 94 aa ec 86 6e a8 26 Using pycrypto I have the following code: from Crypto.Cipher import ARC4 key = '75 2c 59 8c 6e e0 8c 9f ed 30 17 7e 9d a5 85 2b' key = key.replace(' ', '').decode('hex') plaintext = '0102030405060708' plaintext = plaintext.replace(' ', '').decode('hex') rc4 = ARC4.new(key) encrypted = rc4.encrypt(plaintext) print encrypted.encode('hex') This results in the following output: 00 5b 64 25 4e a5 62 e3 Which doesn't match the C++ output. I've played around with endianess, but I suspect something else might be going on. Sorry if this is long winded, but it brings me to my two questions: Whenever you transition from the shared key to RC4 (using CryptSetKeyParam with CALG_RC4), what is actually going on under the hood here? I can't seem to find any information about this process anywhere so that I can implement it in Python. Any idea why my RC4 will not work with the same key and the same plaintext in Python? Any help would be greatly appreciated!
Finally had some time to look over your code. When I run your code locally, I am able to export the session key and can use it successfully in pycrypto. My guess is that you are either not exporting the session key correctly (e.g. is what you posted what you are running?) or the data you are encrypting in C++ is not the same data that you are encrypting in Python - double check that the data you are encrypting is also correct. I suspect that it's probably the latter, as there isn't really much you can screw up with the CryptExportKey you've posted.
Cannot press button
I'm trying to code a bot for a game, and need some help to do it. Being a complete noob, I googled how to do it with python and started reading a bit about mechanize. <div class="clearfix"> <a href="#" onclick="return Index.submit_login('server_br73');"> <span class="world_button_active">Mundo 73</span> </a> </div> My problem is in logging in, where i have this raw code for now: import requests import requesocks import xlrd import socks import socket import mechanize import selenium from bs4 import BeautifulSoup # EXCEL file_location = "/home/luis/Dropbox/Projetos/TW/multisbr.xlsx" wb = xlrd.open_workbook(file_location) sheetname = wb.sheet_names () sh1 = wb.sheet_by_index(0) def nickNm(): lista = [sh1.col_values(0, x) for x in range (sh1.ncols)] listaNomes = lista [1] x < 1 print listaNomes def passwd(): lista = [sh1.col_values(1, x) for x in range (sh1.ncols)] listaPasswd = lista [1] x < 1 print listaPasswd # TOR def create_connection(address, timeout=None, source_address=None): sock = socks.socksocket() sock.connect(address) return sock socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050) # patch the socket module socket.socket = socks.socksocket socket.create_connection = create_connection #BeautifulSoup def get_source (): url = 'https://www.tribalwars.com.br' source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text, 'lxml') # ALFA br = mechanize.Browser () twbr = 'https://www.tribalwars.com.br/index.php' def alfa (): br.open(link) br.select_form(nr=0) br["user"] = "something" br["password"] = "pword" result = br.submit() br.geturl() nickNm() passwd() alfa()
There is quite a lot of javascript involved when you perform different actions on a page, mechanize is not a browser and cannot execute javascript. One option to make your life easier here would be to automate a real browser. Here is an example code to log into the tribalwars using selenium and a headless PhantomJS: from selenium import webdriver driver = webdriver.PhantomJS() driver.get("https://www.tribalwars.com.br/index.php") # logging in driver.find_element_by_id("user").send_keys("user") driver.find_element_by_id("password").send_keys("password") driver.find_element_by_css_selector("a.login_button").click()
Extending CSS selectors in BeautifulSoup
The Question: BeautifulSoup provides a very limited support for CSS selectors. For instance, the only supported pseudo-class is nth-of-type and it can only accept numerical values - arguments like even or odd are not allowed. Is it possible to extend BeautifulSoup CSS selectors or let it use lxml.cssselect internally as an underlying CSS selection mechanism? Let's take a look at an example problem/use case. Locate only even rows in the following HTML: <table> <tr> <td>1</td> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> <tr> <td>4</td> </tr> </table> In lxml.html and lxml.cssselect, it is easy to do via :nth-of-type(even): from lxml.html import fromstring from lxml.cssselect import CSSSelector tree = fromstring(data) sel = CSSSelector('tr:nth-of-type(even)') print [e.text_content().strip() for e in sel(tree)] But, in BeautifulSoup: print(soup.select("tr:nth-of-type(even)")) would throw an error: NotImplementedError: Only numeric values are currently supported for the nth-of-type pseudo-class. Note that we can workaround it with .find_all(): print([row.get_text(strip=True) for index, row in enumerate(soup.find_all("tr"), start=1) if index % 2 == 0])
After checking the source code, it seems that BeautifulSoup does not provide any convenient point in its interface to extend or monkey patch its existing functionality in this regard. Using functionality from lxml is not possible either since BeautifulSoup only uses lxml during parsing and uses the parsing results to create its own respective objects from them. The lxml objects are not preserved and cannot be accessed later. That being said, with enough determination and with the flexibility and introspection capabilities of Python, anything is possible. You can modify the BeautifulSoup method internals even at run-time: import inspect import re import textwrap import bs4.element def replace_code_lines(source, start_token, end_token, replacement, escape_tokens=True): """Replace the source code between `start_token` and `end_token` in `source` with `replacement`. The `start_token` portion is included in the replaced code. If `escape_tokens` is True (default), escape the tokens to avoid them being treated as a regular expression.""" if escape_tokens: start_token = re.escape(start_token) end_token = re.escape(end_token) def replace_with_indent(match): indent = match.group(1) return textwrap.indent(replacement, indent) return re.sub(r"^(\s+)({}[\s\S]+?)(?=^\1{})".format(start_token, end_token), replace_with_indent, source, flags=re.MULTILINE) # Get the source code of the Tag.select() method src = textwrap.dedent(inspect.getsource(bs4.element.Tag.select)) # Replace the relevant part of the method start_token = "if pseudo_type == 'nth-of-type':" end_token = "else" replacement = """\ if pseudo_type == 'nth-of-type': try: if pseudo_value in ("even", "odd"): pass else: pseudo_value = int(pseudo_value) except: raise NotImplementedError( 'Only numeric values, "even" and "odd" are currently ' 'supported for the nth-of-type pseudo-class.') if isinstance(pseudo_value, int) and pseudo_value < 1: raise ValueError( 'nth-of-type pseudo-class value must be at least 1.') class Counter(object): def __init__(self, destination): self.count = 0 self.destination = destination def nth_child_of_type(self, tag): self.count += 1 if pseudo_value == "even": return not bool(self.count % 2) elif pseudo_value == "odd": return bool(self.count % 2) elif self.count == self.destination: return True elif self.count > self.destination: # Stop the generator that's sending us # these things. raise StopIteration() return False checker = Counter(pseudo_value).nth_child_of_type """ new_src = replace_code_lines(src, start_token, end_token, replacement) # Compile it and execute it in the target module's namespace exec(new_src, bs4.element.__dict__) # Monkey patch the target method bs4.element.Tag.select = bs4.element.select This is the portion of code being modified. Of course, this is everything but elegant and reliable. I don't envision this being seriously used anywhere, ever.
SQLALchemy Many to Many model relationship configuration with polymorphic models
So, there are a few questions and answers that touch on this issue but I cannot reconcile them exactly with what I'm trying to achieve. Here, here and here I have a set of models that are self-referential and inherited. This is the basic design. class BaseUser(db.Model): id = db.Column(db.Integer, primary_key=True, nullable=False) org = db.Column(db.Boolean, default=False, nullable=False) # Shared Fields __mapper_args__ = { 'polymorphic_on': org, } class Customer(BaseUser): # Customer Fields __mapper_args__ = { 'polymorphic_identity': 0 } class Organization(BaseUser): # Organization Fields __mapper_args__ = { 'polymorphic_identity': 1 } class CustomerOrganization(db.Model): user_id = db.Column(db.ForeignKey('customer.id', ondelete=CASCADE, onupdate=CASCADE), primary_key=True, nullable=False) org_id = db.Column(db.ForeignKey('customer.id', ondelete=CASCADE, onupdate=CASCADE), primary_key=True, nullable=False) I've tried a few different ways to create an "orgs" and a "members" relationship on each of these types. Any advice on how to define the relationsihp() attributes?
It can be done using primaryjoin and secondaryjoin properties. Relevant documentation is here. Example: customer_organization = Table( 'base_user_customer_organization', ModelBase.metadata, Column('user_id', Integer, ForeignKey('base_user.id')), Column('org_id', Integer, ForeignKey('base_user.id')) ) class BaseUser(ModelBase): __tablename__ = 'base_user' id = Column(Integer, primary_key=True, nullable=False) org = Column(Boolean, default=False, nullable=False) # Shared Fields __mapper_args__ = { 'polymorphic_on': org, } customers = relationship( "BaseUser", backref=backref('organization', order_by=id), secondary=customer_organization, primaryjoin=id==customer_organization.c.org_id and org==True, secondaryjoin=id==customer_organization.c.user_id and org==False ) class CustomerUser(BaseUser): # Customer Fields __mapper_args__ = { 'polymorphic_identity': False } class OrganizationUser(BaseUser): # Organization Fields __mapper_args__ = { 'polymorphic_identity': True } And test: sql = sqldb.get_session() customer1 = sqldb.system.CustomerUser() sql.add(customer1) customer2 = sqldb.system.CustomerUser() sql.add(customer2) organization = sqldb.system.OrganizationUser() organization.customers = [customer1, customer2] sql.add(organization) sql.commit() # function prints all table data print get_sql_table_data(sqldb.system.BaseUser) print organization.customers print customer1.organization print customer2.organization Output: [{'org': False, 'id': 1}, {'org': False, 'id': 2}, {'org': True, 'id': 3}] [<CustomerUser(id=1, org=False)>, <CustomerUser(id=2, org=False)>] [<OrganizationUser(id=3, org=True)>] [<OrganizationUser(id=3, org=True)>]
Changing a variable inside a method with another method inside it
The following code raises an UnboundLocalError: def foo(): i = 0 def incr(): i += 1 incr() print(i) foo() Is there a way to accomplish this?
Use nonlocal statement def foo(): i = 0 def incr(): nonlocal i i += 1 incr() print(i) foo() For more information on this new statement added in python 3.x, go to https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement
Imports behave differently when in __init__.py that is imported
Imports in an __init__.py seem to behave differently when the file is run, to when it is imported. If we have the following files: run.py: import test test/b.py: class B(object): pass test/__init__.py: from b import B print B print b If we run __init__.py we get an error as I expect: % python test/__init__.py <class 'b.B'> Traceback (most recent call last): File "test/__init__.py", line 6, in <module> print b NameError: name 'b' is not defined But if we run.py then we don't: % python run.py <class 'test.b.B'> <module 'test.b' from '~/temp/test/b.py'> I would expect the behaviour to be the same. Why does this work? This only works if we do it in an __init__.py. If we: mv __init__.py a.py touch __init__.py and make run.py: import test.a Then we do get the error.
The situation is the following: you have a script (run.py), a package test and its submodule test.b. Whenever you import a submodule in Python, the name of that submodule is automatically stored into the parent package. So that when you do import collections.abc (or from collections.abc import Iterable, or similar), the package collections automatically gets the attribute abc. This is what's happening here. When you do: from b import B the name b is automatically loaded into test, because b is a submodule of the test package. Even if you don't do import b explicitly, whenever you import that module, the name is placed into test. Because b is a submodule of test, and it belongs to test. Side node: your code won't work with Python 3, because relative imports have been removed. To make your code work with Python 3, you would have to write: from test.b import B This syntax is perfectly identical to from b import B, but is much more explicit, and should help you understand what's going on. Reference: the Python reference documentation also explains this behavior, and includes a helpful example, very similar to this situation (the difference is just that an absolute import is used, instead of a relative import). When a submodule is loaded using any mechanism (e.g. importlib APIs, the import or import-from statements, or built-in __import__()) a binding is placed in the parent module's namespace to the submodule object. For example, if package spam has a submodule foo, after importing spam.foo, spam will have an attribute foo which is bound to the submodule. Let's say you have the following directory structure: spam/ __init__.py foo.py bar.py and spam/__init__.py has the following lines in it: from .foo import Foo from .bar import Bar then executing the following puts a name binding to foo and bar in the spam module: >>> import spam >>> spam.foo <module 'spam.foo' from '/tmp/imports/spam/foo.py'> >>> spam.bar <module 'spam.bar' from '/tmp/imports/spam/bar.py'> Given Python's familiar name binding rules this might seem surprising, but it's actually a fundamental feature of the import system. The invariant holding is that if you have sys.modules['spam'] and sys.modules['spam.foo'] (as you would after the above import), the latter must appear as the foo attribute of the former.
Wrap an open stream with io.TextIOWrapper
How can I wrap an open binary stream – a Python 2 file, a Python 3 io.BufferedReader, an io.BytesIO – in an io.TextIOWrapper? I'm trying to write code that will work unchanged: Running on Python 2. Running on Python 3. With binary streams generated from the standard library (i.e. I can't control what type they are) With binary streams made to be test doubles (i.e. no file handle, can't re-open). Producing an io.TextIOWrapper that wraps the specified stream. The io.TextIOWrapper is needed because its API is expected by other parts of the standard library. Other file-like types exist, but don't provide the right API. Example Wrapping the binary stream presented as the subprocess.Popen.stdout attribute: import subprocess import io gnupg_subprocess = subprocess.Popen( ["gpg", "--version"], stdout=subprocess.PIPE) gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout, encoding="utf-8") In unit tests, the stream is replaced with an io.BytesIO instance to control its content without touching any subprocesses or filesystems. gnupg_subprocess.stdout = io.BytesIO("Lorem ipsum".encode("utf-8")) That works fine on the streams created by Python 3's standard library. The same code, though, fails on streams generated by Python 2: [Python 2] >>> type(gnupg_subprocess.stdout) <type 'file'> >>> gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout, encoding="utf-8") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'file' object has no attribute 'readable' Not a solution: Special treatment for file An obvious response is to have a branch in the code which tests whether the stream actually is a Python 2 file object, and handle that differently from io.* objects. That's not an option for well-tested code, because it makes a branch that unit tests – which, in order to run as fast as possible, must not create any real filesystem objects – can't exercise. The unit tests will be providing test doubles, not real file objects. So creating a branch which won't be exercised by those test doubles is defeating the test suite. Not a solution: io.open Some respondents suggest re-opening (e.g. with io.open) the underlying file handle: gnupg_stdout = io.open( gnupg_subprocess.stdout.fileno(), mode='r', encoding="utf-8") That works on both Python 3 and Python 2: [Python 3] >>> type(gnupg_subprocess.stdout) <class '_io.BufferedReader'> >>> gnupg_stdout = io.open(gnupg_subprocess.stdout.fileno(), mode='r', encoding="utf-8") >>> type(gnupg_stdout) <class '_io.TextIOWrapper'> [Python 2] >>> type(gnupg_subprocess.stdout) <type 'file'> >>> gnupg_stdout = io.open(gnupg_subprocess.stdout.fileno(), mode='r', encoding="utf-8") >>> type(gnupg_stdout) <type '_io.TextIOWrapper'> But of course it relies on re-opening a real file from its file handle. So it fails in unit tests when the test double is an io.BytesIO instance: >>> gnupg_subprocess.stdout = io.BytesIO("Lorem ipsum".encode("utf-8")) >>> type(gnupg_subprocess.stdout) <type '_io.BytesIO'> >>> gnupg_stdout = io.open(gnupg_subprocess.stdout.fileno(), mode='r', encoding="utf-8") Traceback (most recent call last): File "<stdin>", line 1, in <module> io.UnsupportedOperation: fileno Not a solution: codecs.getreader The standard library also has the codecs module, which provides wrapper features: import codecs gnupg_stdout = codecs.getreader("utf-8")(gnupg_subprocess.stdout) That's good because it doesn't attempt to re-open the stream. But it fails to provide the io.TextIOWrapper API. Specifically, it doesn't inherit io.IOBase and doesn't have the encoding attribute: >>> type(gnupg_subprocess.stdout) <type 'file'> >>> gnupg_stdout = codecs.getreader("utf-8")(gnupg_subprocess.stdout) >>> type(gnupg_stdout) <type 'instance'> >>> isinstance(gnupg_stdout, io.IOBase) False >>> gnupg_stdout.encoding Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/codecs.py", line 643, in __getattr__ return getattr(self.stream, name) AttributeError: '_io.BytesIO' object has no attribute 'encoding' So codecs doesn't provide objects which substitute for io.TextIOWrapper. What do do? So how can I write code that works for both Python 2 and Python 3, with both the test doubles and the real objects, which wraps an io.TextIOWrapper around the already-open byte stream?
Use codecs.getreader to produce a wrapper object: text_stream = codecs.getreader("utf-8")(bytes_stream) Works on Python 2 and Python 3.
Replace single instances of a character that is sometimes doubled
I have a string with each character being separated by a pipe character (including the "|"s themselves), for example: "f|u|n|n|y||b|o|y||a||c|a|t" I would like to replace all "|"s which are not next to another "|" with nothing, to get the result: "funny|boy|a|cat" I tried using mytext.replace("|", ""), but that removes everything and makes one long word.
This can be achieved with a relatively simple regex without having to chain str.replace: >>> import re >>> s = "f|u|n|n|y||b|o|y||a||c|a|t" >>> re.sub('\|(?!\|)' , '', s) 'funny|boy|a|cat' Explanation: \|(?!\|) will look for a | character which is not followed by another | character. (?!foo) means negative lookahead, ensuring that whatever you are matching is not followed by foo.
In py.test, what is the use of conftest.py files?
I recently discovered py.test. It seems great. However I feel the documentation could be better. I'm trying to understand what conftest.py files are meant to be used for. In my (currently small) test suite I have one conftest.py file at the project root. I use it to define the fixtures that I inject into my tests. I have two questions: Is this the correct use of conftest.py? Does it have other uses? Can I have more than one conftest.py file? When would I want to do that? Examples will be appreciated. More generally, how would you define the purpose and correct use of conftest.py file(s) in a py.test test suite?
Is this the correct use of conftest.py? Yes it is, Fixtures are a potential and common use of conftest.py. The fixtures that you will define will be shared among all tests in your test suite. However defining fixtures in the root conftest.py might be useless and it would slow down testing if such fixtures are not used by all tests. Does it have other uses? Yes it does. Fixtures: Define fixtures for static data used by tests. This data can be accessed by all tests in the suite unless specified. This could be data as well as helpers of modules which will be passed to all tests. External plugin loading: conftest.py is used to import external plugins or modules. By defining the following global variable, pytest will load the module and make it available for its test. Plugins are generally files defined in your project or other modules which might be needed in your tests. You can also load a set of predefined plugins as of here. pytest_plugins = "someapp.someplugin" Hooks: You can specified hooks such as setup and teardown methods and much more to improve your tests. For a set of available hooks, read here. Example: def pytest_runtest_setup(item): """ called before ``pytest_runtest_call(item). """ #do some stuff` Test root path: This is a bit of a hidden feature. By defining conftest.py in your root path, you will have pytest recognizing your application modules without specifying PYTHONPATH. On the background, py.test modifies your sys.path by including all submodules which are found from the root path. Can I have more than one conftest.py file? Yes you can and it is strongly recommended if your test structure is somehow complex. conftest.py files have directory scope, therefor creating targeted fixtures and helpers is good practice. When would I want to do that? Examples will be appreciated. Several cases could fit: Creating a set of tools or hooks for a particular group of tests root/mod/conftest.py def pytest_runtest_setup(item): print("I am mod") #do some stuff test root/mod2/test.py will NOT produce "I am mod" Load a set of fixtures for some tests but not for others. root/mod/conftest.py @pytest.fixture() def fixture(): return "some stuff" root/mod2/conftest.py @pytest.fixture() def fixture(): return "some other stuff" root/mod2/test.py def test(fixture): print(fixture) Will print "some other stuff" Override hooks inherited from the root conftest.py root/mod/conftest.py def pytest_runtest_setup(item): print("I am mod") #do some stuff root/conftest.py def pytest_runtest_setup(item): print("I am root") #do some stuff By running any test inside root/mod, only "I am mod" is printed. You can read more about conftest.py here. EDIT: What if I need plain-old helper functions to be called from a number of tests in different moduls - will they be available to me if I put them in a conftest.py? Or should I simply put them in a helpers.py module and import and use it in my test modules? You can use conftest.py to define your helpers, however you should follow the common practice. helpers can be used as fixtures at least in py.test. For example in my tests I have a mocked redis helper which I inject into my tests this way. root/helper/redis/redis.py @pytest.fixture def mock_redis(): return MockRedis() root/tests/stuff/conftest.py pytest_plugin="helper.redis.redis" root/tests/stuff/test.py def test(mock_redis): print(mock_redis.get('stuff')) This will be a test module that you can freely import in your tests. NOTE that you could potentially name redis.py as conftest.py if your module redis contains more tests. However that practice is discouraged because of ambiguity. If you want to use conftest.py simply you can put that helper in your root conftest.py and inject it when needed. root/tests/conftest.py @pytest.fixture def mock_redis(): return MockRedis() root/tests/stuff/test.py def test(mock_redis): print(mock_redis.get(stuff)) Another thing you can do is to write an installable plugin. In that case your helper can be written anywhere but it needs to define an entry point to be installed in your and other potential test frameworks. See this. If you don't want to use fixtures, you could of course define a simple helper and just use the plain old import wherever it is needed. root/tests/helper/redis.py class MockRedis(): # stuff root/tests/stuff/test.py from helper.redis import MockRedis def test(): print(MockRedis().get(stuff)) However here you might have problems with the path since the module is not in a child folder of the test. You should be able to overcome this (not tested) by adding an init to your helper root/tests/helper/__init__.py from .redis import MockRedis Or simply adding the helper module to your PYTHONPATH.
Memory-efficient way to generate a large numpy array containing random boolean values
I need to create a large numpy array containing random boolean values without hitting the swap. My laptop has 8 GB of RAM. Creating a (1200, 2e6) array takes less than 2 s and use 2.29 GB of RAM: >>> dd = np.ones((1200, int(2e6)), dtype=bool) >>> dd.nbytes/1024./1024 2288.818359375 >>> dd.shape (1200, 2000000) For a relatively small (1200, 400e3), np.random.randint is still quite fast, taking roughly 5 s to generate a 458 MB array: db = np.array(np.random.randint(2, size=(int(400e3), 1200)), dtype=bool) print db.nbytes/1024./1024., 'Mb' But if I double the size of the array to (1200, 800e3) I hit the swap, and it takes ~2.7 min to create db ;( cmd = """ import numpy as np db = np.array(np.random.randint(2, size=(int(800e3), 1200)), dtype=bool) print db.nbytes/1024./1024., 'Mb'""" print timeit.Timer(cmd).timeit(1) Using random.getrandbits takes even longer (~8min), and also uses the swap: from random import getrandbits db = np.array([not getrandbits(1) for x in xrange(int(1200*800e3))], dtype=bool) Using np.random.randint for a (1200, 2e6) just gives a MemoryError. Is there a more efficient way to create a (1200, 2e6) random boolean array?
One problem with using np.random.randint is that it generates 64-bit integers, whereas numpy's np.bool dtype uses only 8 bits to represent each boolean value. You are therefore allocating an intermediate array 8x larger than necessary. A workaround that avoids intermediate 64-bit dtypes is to generate a string of random bytes using np.random.bytes, which can be converted to an array of 8-bit integers using np.fromstring. These integers can then be converted to boolean values, for example by testing whether they are less than 255 * p, where p is the desired probability of each element being True: import numpy as np def random_bool(shape, p=0.5): n = np.prod(shape) x = np.fromstring(np.random.bytes(n), np.uint8, n) return (x < 255 * p).reshape(shape) Benchmark: In [1]: shape = 1200, int(2E6) In [2]: %timeit random_bool(shape) 1 loops, best of 3: 12.7 s per loop One important caveat is that the probability will be rounded down to the nearest multiple of 1/256 (for an exact multiple of 1/256 such as p=1/2 this should not affect accuracy). Update: An even faster method is to exploit the fact that you only need to generate a single random bit per 0 or 1 in your output array. You can therefore create a random array of 8-bit integers 1/8th the size of the final output, then convert it to np.bool using np.unpackbits: def fast_random_bool(shape): n = np.prod(shape) nb = -(-n // 8) # ceiling division b = np.fromstring(np.random.bytes(nb), np.uint8, nb) return np.unpackbits(b)[:n].reshape(shape).view(np.bool) For example: In [3]: %timeit fast_random_bool(shape) 1 loops, best of 3: 5.54 s per loop
What is the currently correct way to dynamically update plots in Jupyter/iPython?
In the answers to how to dynamically update a plot in a loop in ipython notebook (within one cell), an example is given of how to dynamically update a plot inside a Jupyter notebook within a Python loop. However, this works by destroying and re-creating the plot on every iteration, and a comment in one of the threads notes that this situation can be improved by using the new-ish %matplotlib nbagg magic, which provides an interactive figure embedded in the notebook, rather than a static image. However, this wonderful new nbagg feature seems to be completely undocumented as far as I can tell, and I'm unable to find an example of how to use it to dynamically update a plot. Thus my question is, how does one efficiently update an existing plot in a Jupyter/Python notebook, using the nbagg backend? Since dynamically updating plots in matplotlib is a tricky issue in general, a simple working example would be an enormous help. A pointer to any documentation on the topic would also be extremely helpful. To be clear what I'm asking for: what I want to do is to run some simulation code for a few iterations, then draw a plot of its current state, then run it for a few more iterations, then update the plot to reflect the current state, and so on. So the idea is to draw a plot and then, without any interaction from the user, update the data in the plot without destroying and re-creating the whole thing. Here is some slightly modified code from the answer to the linked question above, which achieves this by re-drawing the whole figure every time. I want to achieve the same result, but more efficiently using nbagg. %matplotlib inline import time import pylab as pl from IPython import display for i in range(10): pl.clf() pl.plot(pl.randn(100)) display.display(pl.gcf()) display.clear_output(wait=True) time.sleep(1.0)
Here is an example that updates a plot in a loop. It updates the data in the figure and does not redraw the whole figure every time. It does block execution, though if you're interested in running a finite set of simulations and saving the results somewhere, it may not be a problem for you. %matplotlib notebook import numpy as np import matplotlib.pyplot as plt import time def pltsin(ax, colors=['b']): x = np.linspace(0,1,100) if ax.lines: for line in ax.lines: line.set_xdata(x) y = np.random.random(size=(100,1)) line.set_ydata(y) else: for color in colors: y = np.random.random(size=(100,1)) ax.plot(x, y, color) fig.canvas.draw() fig,ax = plt.subplots(1,1) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_xlim(0,1) ax.set_ylim(0,1) for f in range(5): pltsin(ax, ['b', 'r']) time.sleep(1) I put this up on nbviewer here. There is an IPython Widget version of nbagg that is currently a work in progress at the Matplotlib repository. When that is available, that will probably be the best way to use nbagg. EDIT: updated to show multiple plots
Issue warning for missing comma between list items bug
The Story: When a list of strings is defined on multiple lines, it is often easy to forget a comma between list items, like in this example case: test = [ "item1" "item2" ] The list test would now have a single item "item1item2". Quite often the problem appears after rearranging the items in a list. Sample Stack Overflow questions having this issue: Why do I get a KeyError? Python - Syntax error on colon in list The Question: Is there a way to, preferably using static code analysis, issue a warning in cases like this in order to spot the problem as early as possible?
These are merely probable solutions since I'm not really apt with static-analysis. With tokenize: I recently fiddled around with tokenizing python code and I believe it has all the information needed to perform these kind of checks when sufficient logic is added. For your given list, the tokens generated with python -m tokenize list1.py are as follows: python -m tokenize list1.py 1,0-1,4: NAME 'test' 1,5-1,6: OP '=' 1,7-1,8: OP '[' 1,8-1,9: NL '\n' 2,1-2,8: STRING '"item1"' 2,8-2,9: NL '\n' 3,1-3,8: STRING '"item2"' 3,8-3,9: NL '\n' 4,0-4,1: OP ']' 4,1-4,2: NEWLINE '\n' 5,0-5,0: ENDMARKER '' This of course is the 'problematic' case where the contents are going to get concatenated. In the case where a , is present, the output slightly changes to reflect this (I added the tokens only for the list body): 1,7-1,8: OP '[' 1,8-1,9: NL '\n' 2,1-2,8: STRING '"item1"' 2,8-2,9: OP ',' 2,9-2,10: NL '\n' 3,1-3,8: STRING '"item2"' 3,8-3,9: NL '\n' 4,0-4,1: OP ']' Now we have the additional OP ',' token signifying the presence of a second element seperated by comma. Given this information, we could use the really handy method generate_tokens in the tokenize module. Method tokenize.generate_tokens() , tokenize.tokenize() in Py3, has a single argument readline, a method on file-like objects which essentially returns the next line for that file like object (relevant answer). It returns a named tuple with 5 elements in total with information about the token type, the token string along with line number and position in the line. Using this information, one could theoretically loop through a file and when an OP ',' is absent inside a list initialization (whose beginning is detected by checking that the tokens NAME, OP '=' and OP '[' exist on the same line number) one can issue a warning on the lines on which it was detected. The good thing about this approach is that it is pretty straight-forward to generalize. To fit all cases where string literal concatenation takes place (namely, inside the 'grouping' operators (), {}, [] ) you check that the token is of type = 51 (or 53 for Python 3) or that a value in any of (, [, { exists on the same line (these are coarse, top of the head suggestions atm). Now, I'm not really sure how other people go about with these sort of problems but it seems like it could be something you can look into. All the information necessary is offered by tokenize, the logic to detect it is the only thing missing. Implementation Note: These values (for example, for type) do differ between versions and are subject to change so it is something one should be aware of. One could possibly leverage this by only working with constants for the tokens, though. With parser and ast: Another probable solution which is probably more tedious could involve the parser and ast modules. The concatenation of strings is actually performed during the creation of the Abstract Syntax Tree so you could alternatively detect it over there. I don't really want to dump the full output of the methods for parser and ast that I'm going to mention, but, just to make sure we're on the same page, I'm going to be using the following list initialization statement: l_init = """ test = [ "item1" "item2", "item3" ] """ In order to get the parse tree generated, use p = parser.suite(l_init). After this is done, you can get a view of it with p.tolist() (output is too large to add it). What you notice is that there will be three entries for the three different str objects item1, item2, item3. On the other hand, when the AST is created with node = ast.parse(l_init) and viewed with ast.dump(node) there are only two entries: one for the concatenated strs item1item2 and one for the other entry item3. So, this is another probable way to do it but, as I previously mentioned, it is way more tedious. I'm not sure if line information is available and you deal with two different modules. Just have it as a back thought if you maybe want to play around with internal objects higher in the compiler chain. Closing Comments: As a closing note, the tokenize approach seems to be most logical one in this case. On the contrary though, it seems that pylint actually works with astroid a python lib that eases analysis of Abstract Syntax Trees for python code. So, one should ideally look at it and how it is used inside pylint. Note: Of course, I might be completely over-analyzing it and a simpler 'check for white-space or newline' solution as you guys suggested would suffice. :-)
python equality precedence
class L(object): def __eq__(self, other): print 'invoked L.__eq__' return False class R(object): def __eq__(self, other): print 'invoked R.__eq__' return False left = L() right = R() With this code, left side gets the first shot at comparison, as documented in the data model: >>> left == right invoked L.__eq__ False But if we make a slight modification on line 6 (everything else the same): class R(L): Now the right side gets to have the first shot at comparison. >>> left == right invoked R.__eq__ False Why is that? Where is it documented, and what's the reason for the design decision?
This is documented under the numeric operations, further down the page, with an explanation for why it works that way: Note: If the right operand’s type is a subclass of the left operand’s type and that subclass provides the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations. The Python 3 documentation additionally mentions it in the section you were looking at: If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered.
WebDriver click() vs JavaScript click()
The Story: Here on StackOverflow, I've seen users reporting that they cannot click an element via selenium WebDriver "click" command and can workaround it with a JavaScript click by executing a script. Example in Python: element = driver.find_element_by_id("myid") driver.execute_script("arguments[0].click();", element) Example in WebDriverJS/Protractor: var elm = $("#myid"); browser.executeScript("arguments[0].click();", elm.getWebElement()); The Question: Why is clicking "via JavaScript" works when a regular WebDriver click does not? When exactly is this happening and what is the downside of this workaround (if any)? I personally used this workaround without fully understanding why I have to do it and what problems it can lead to.
Contrarily to what the currently accepted answer suggests, there's nothing specific to PhantomJS when it comes to the difference between having WebDriver do a click and doing it in JavaScript. The Difference The essential difference between the two methods is common to all browsers and can be explained pretty simply: WebDriver: When WebDriver does the click, it attempts as best as it can to simulate what happens when a real user uses the browser. Suppose you have an element A which is a button that says "Click me" and an element B which is a div element which is transparent but has its dimensions and zIndex set so that it completely covers A. Then you tell WebDriver to click A. WebDriver will simulate the click so that B receives the click first. Why? Because B covers A, and if a user were to try to click on A, then B would get the event first. Whether or not A would eventually get the click event depends on how B handles the event. At any rate, the behavior with WebDriver in this case is the same as when a real user tries to click on A. JavaScript: Now, suppose you use JavaScript to do A.click(). This method of clicking does not reproduce what really happens when the user tries to click A. JavaScript sends the click event directly to A, and B will not get any event. Why a JavaScript Click Works When a WebDriver Click Does Not? As I mentioned above WebDriver will try to simulate as best it can what happens when a real user is using a browser. The fact of the matter is that the DOM can contain elements that a user cannot interact with, and WebDriver won't allow you to click on these element. Besides the overlapping case I mentioned, this also entails that invisible elements cannot be clicked. A common case I see in Stack Overflow questions is someone who is trying to interact with a GUI element that already exists in the DOM but becomes visible only when some other element has been manipulated. This sometimes happens with dropdown menus: you have to first click on the button the brings up the dropdown before a menu item can be selected. If someone tries to click the menu item before the menu is visible, WebDriver will balk and say that the element cannot be manipulated. If the person then tries to do it with JavaScript, it will work because the event is delivered directly to the element, irrespective of visibility. When Should You Use JavaScript for Clicking? If you are using Selenium for testing an application, my answer to this question is "almost never". By and large, your Selenium test should reproduce what a user would do with the browser. Taking the example of the drop down menu: a test should click on the button that brings up the drop down first, and then click on the menu item. If there is a problem with the GUI because the button is invisible, or the button fails to show the menu items, or something similar, then your test will fail and you'll have detected the bug. If you use JavaScript to click around, you won't be able to detect these bugs through automated testing. I say "almost never" because there may be exceptions where it makes sense to use JavaScript. They should be very rare, though. If you are using Selenium for scraping sites, then it is not as critical to attempt to reproduce user behavior. So using JavaScript to bypass the GUI is less of an issue.
Why does Python allow function calls with wrong number of arguments?
Python is my first dynamic language. I recently coded a function call incorrectly supplying a wrong number of arguments. This failed with an exception at the time that function was called. I expected that even in a dynamic language, this kind of error can be detected when the source file is parsed. I understand that the type of actual arguments is not known until the function is called, because the same variable may contain values of any type at different times. But the number of arguments is known as soon as the source file is parsed. It is not going to change while the program is running. So that this is not a philosophical question To keep this in scope of Stack Overflow, let me phrase the question like this. Is there some feature, that Python offers, that requires it to delay checking the number of arguments in a function call until the code actually executes?
Python cannot know up-front what object you'll end up calling, because being dynamic, you can swap out the function object. At any time. And each of these objects can have a different number of arguments. Here is an extreme example: import random def foo(): pass def bar(arg1): pass def baz(arg1, arg2): pass the_function = random.choice([foo, bar, baz]) print(the_function()) The above code has a 2 in 3 chance of raising an exception. But Python cannot know a-priori if that'll be the case or not! And I haven't even started with dynamic module imports, dynamic function generation, other callable objects (any object with a __call__ method can be called), or catch-all arguments (*args and **kwargs). But to make this extra clear, you state in your question: It is not going to change while the program is running. This is not the case, not in Python, once the module is loaded you can delete, add or replace any object in the module namespace, including function objects.
Labels for clustermap in seaborn?
I have several questions about labeling for clustermap in seaborn. First is it possible to extract the the distance values for the hierarchical clustering, and plot the value on the tree structure visualization (maybe only the first three levels). Here is my example code for creating a clustermap plot: import pandas as pd import numpy as np import seaborn as sns get_ipython().magic(u'matplotlib inline') m = np.random.rand(50, 50) df = pd.DataFrame(m, columns=range(4123, 4173), index=range(4123, 4173)) sns.clustermap(df, metric="correlation") The other two questions are: - How to rotate the y labels since they overlaps together. - How to move the color bar to the bottom or right. (There was a question for heatmap, but does not work for my case. Also does not address the color bar position)
I had the exact same issue with the labels on the y-axis being rotated and found a solution. The issue is that if you do plt.yticks(rotation=0) like suggested in the question you referenced, it will rotate the labels on your colobar due to the way ClusterGrid works. To solve it and rotate the right labels, you need to reference the Axes from the underlying Heatmap and rotate these: cg = sns.clustermap(df, metric="correlation") plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0) For your other question about the colorbar placement, I don't think this is supported at the moment, as indicated by this Github issue unfortunately. And finally for the hierarchical clustering distance values, you can access the linkage matrics for rows or columns with: cg = sns.clustermap(df, metric="correlation") cg.dendrogram_col.linkage # linkage matrix for columns cg.dendrogram_row.linkage # linkage matrix for rows
What's the point of Django's collectstatic?
This is probably a stupid question, but it's just not clicking in my head. In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called static. So the structure would look like this: mysite/ manage.py mysite/ --> (settings.py, etc) myapp/ --> (models.py, views.py, etc) static/ In mysite/settings.py I have: STATIC_ROOT = 'staticfiles' So when I run the command: python manage.py collectstatic It creates a folder called staticfiles at the root level (so same directory as myapp/) What's the point of this? Isn't it just creating a copy of all my static files?
Collect static files from multiple apps into a single path Well, a single Django project may use several apps, so while there you only have one myapp, it may actually be myapp1, myapp2, etc By copying them from inside the individual apps into a single folder, you can point your frontend web server (e.g. nginx) to that single folder STATIC_ROOT and serve static files from a single location, rather than configure your web server to serve static files from multiple paths. Persistent URLs with ManifestStaticFilesStorage A note about the MD5 hash being appended to the filename for versioning: It's not part of the default behavior of collectstatic, as settings.STATICFILES_STORAGE defaults to StaticFilesStorage (which doesn't do that) The MD5 hash will kick in e.g. if you set it to use ManifestStaticFilesStorage, which ads that behavior. The purpose of this storage is to keep serving the old files in case some pages still refer to those files, e.g. because they are cached by you or a 3rd party proxy server. Additionally, it’s very helpful if you want to apply far future Expires headers to the deployed files to speed up the load time for subsequent page visits.
List comprehension as substitute for reduce() in Python
The following python tutorial says that: List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce(). http://python-course.eu/python3_list_comprehension.php However, it does not mention an example how a list comprehension can substitute a reduce() and I can't think of an example how it should be possible. Can please someone explain how to achieve a reduce-like functionality with list comprehension or confirm that it isn't possible?
Ideally, list comprehension is to create a new list. Quoting official documentation, List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. whereas reduce is used to reduce an iterable to a single value. Quoting functools.reduce, Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. So, list comprehension cannot be used as a drop-in replacement for reduce.
How to prefetch data using a custom python function in tensorflow
I am trying to prefetch training data to hide I/O latency. I would like to write custom Python code that loads data from disk and preprocesses the data (e.g. by adding a context window). In other words, one thread does data preprocessing and the other does training. Is this possible in TensorFlow? Update: I have a working example based on @mrry's example. import numpy as np import tensorflow as tf import threading BATCH_SIZE = 5 TRAINING_ITERS = 4100 feature_input = tf.placeholder(tf.float32, shape=[128]) label_input = tf.placeholder(tf.float32, shape=[128]) q = tf.FIFOQueue(200, [tf.float32, tf.float32], shapes=[[128], [128]]) enqueue_op = q.enqueue([label_input, feature_input]) label_batch, feature_batch = q.dequeue_many(BATCH_SIZE) c = tf.reshape(feature_batch, [BATCH_SIZE, 128]) + tf.reshape(label_batch, [BATCH_SIZE, 128]) sess = tf.Session() def load_and_enqueue(sess, enqueue_op, coord): with open('dummy_data/features.bin') as feature_file, open('dummy_data/labels.bin') as label_file: while not coord.should_stop(): feature_array = np.fromfile(feature_file, np.float32, 128) if feature_array.shape[0] == 0: print('reach end of file, reset using seek(0,0)') feature_file.seek(0,0) label_file.seek(0,0) continue label_value = np.fromfile(label_file, np.float32, 128) sess.run(enqueue_op, feed_dict={feature_input: feature_array, label_input: label_value}) coord = tf.train.Coordinator() t = threading.Thread(target=load_and_enqueue, args=(sess,enqueue_op, coord)) t.start() for i in range(TRAINING_ITERS): sum = sess.run(c) print('train_iter='+str(i)) print(sum) coord.request_stop() coord.join([t])
This is a common use case, and most implementations use TensorFlow's queues to decouple the preprocessing code from the training code. There is a tutorial on how to use queues, but the main steps are as follows: Define a queue, q, that will buffer the preprocessed data. TensorFlow supports the simple tf.FIFOQueue that produces elements in the order they were enqueued, and the more advanced tf.RandomShuffleQueue that produces elements in a random order. A queue element is a tuple of one or more tensors (which can have different types and shapes). All queues support single-element (enqueue, dequeue) and batch (enqueue_many, dequeue_many) operations, but to use the batch operations you must specify the shapes of each tensor in a queue element when constructing the queue. Build a subgraph that enqueues preprocessed elements into the queue. One way to do this would be to define some tf.placeholder() ops for tensors corresponding to a single input example, then pass them to q.enqueue(). (If your preprocessing produces a batch at once, you should use q.enqueue_many() instead.) You might also include TensorFlow ops in this subgraph. Build a subgraph that performs training. This will look like a regular TensorFlow graph, but will get its input by calling q.dequeue_many(BATCH_SIZE). Start your session. Create one or more threads that execute your preprocessing logic, then execute the enqueue op, feeding in the preprocessed data. You may find the tf.train.Coordinator and tf.train.QueueRunner utility classes useful for this. Run your training graph (optimizer, etc.) as normal. EDIT: Here's a simple load_and_enqueue() function and code fragment to get you started: # Features are length-100 vectors of floats feature_input = tf.placeholder(tf.float32, shape=[100]) # Labels are scalar integers. label_input = tf.placeholder(tf.int32, shape=[]) # Alternatively, could do: # feature_batch_input = tf.placeholder(tf.float32, shape=[None, 100]) # label_batch_input = tf.placeholder(tf.int32, shape=[None]) q = tf.FIFOQueue(100, [tf.float32, tf.int32], shapes=[[100], []]) enqueue_op = q.enqueue([label_input, feature_input]) # For batch input, do: # enqueue_op = q.enqueue_many([label_batch_input, feature_batch_input]) label_batch, feature_batch = q.dequeue_many(BATCH_SIZE) # Build rest of model taking label_batch, feature_batch as input. # [...] train_op = ... sess = tf.Session() def load_and_enqueue(): with open(...) as feature_file, open(...) as label_file: while True: feature_array = numpy.fromfile(feature_file, numpy.float32, 100) if not feature_array: return label_value = numpy.fromfile(feature_file, numpy.int32, 1)[0] sess.run(enqueue_op, feed_dict={feature_input: feature_array, label_input: label_value}) # Start a thread to enqueue data asynchronously, and hide I/O latency. t = threading.Thread(target=load_and_enqueue) t.start() for _ in range(TRAINING_EPOCHS): sess.run(train_op)
Using Popen in a thread blocks every incoming Flask-SocketIO request
I have the following situation: I receive a request on a socketio server. I answer it (socket.emit(..)) and then start something with heavy computation load in another thread. If the heavy computation is caused by subprocess.Popen (using subprocess.PIPE) it totally blocks every incoming request as long as it is being executed although it happens in a separate thread. No problem - in this thread it was suggested to asynchronously read the result of the subprocess with a buffer size of 1 so that between these reads other threads have the chance to do something. Unfortunately this did not help for me. I also already monkeypatched eventlet and that works fine - as long as I don't use subprocess.Popen with subprocess.PIPE in the thread. In this code sample you can see that it only happens using subprocess.Popen with subprocess.PIPE. When uncommenting #functionWithSimulatedHeavyLoad() and instead comment functionWithHeavyLoad() everything works like charm. from flask import Flask from flask.ext.socketio import SocketIO, emit import eventlet eventlet.monkey_patch() app = Flask(__name__) socketio = SocketIO(app) import time from threading import Thread @socketio.on('client command') def response(data, type = None, nonce = None): socketio.emit('client response', ['foo']) thread = Thread(target = testThreadFunction) thread.daemon = True thread.start() def testThreadFunction(): #functionWithSimulatedHeavyLoad() functionWithHeavyLoad() def functionWithSimulatedHeavyLoad(): time.sleep(5) def functionWithHeavyLoad(): from datetime import datetime import subprocess import sys from queue import Queue, Empty ON_POSIX = 'posix' in sys.builtin_module_names def enqueueOutput(out, queue): for line in iter(out.readline, b''): if line == '': break queue.put(line) out.close() # just anything that takes long to be computed shellCommand = 'find / test' p = subprocess.Popen(shellCommand, universal_newlines=True, shell=True, stdout=subprocess.PIPE, bufsize=1, close_fds=ON_POSIX) q = Queue() t = Thread(target = enqueueOutput, args = (p.stdout, q)) t.daemon = True t.start() t.join() text = '' while True: try: line = q.get_nowait() text += line print(line) except Empty: break socketio.emit('client response', {'text': text}) socketio.run(app) The client receives the message 'foo' after the blocking work in the functionWithHeavyLoad() function is completed. It should receive the message earlier, though. This sample can be copied and pasted in a .py file and the behavior can be instantly reproduced. I am using Python 3.4.3, Flask 0.10.1, flask-socketio1.2, eventlet 0.17.4 Update If I put this into the functionWithHeavyLoad function it actually works and everything's fine: import shlex shellCommand = shlex.split('find / test') popen = subprocess.Popen(shellCommand, stdout=subprocess.PIPE) lines_iterator = iter(popen.stdout.readline, b"") for line in lines_iterator: print(line) eventlet.sleep() The problem is: I used find for heavy load in order to make the sample for you more easily reproducable. However, in my code I actually use tesseract "{0}" stdout -l deu as the sell command. This (unlike find) still blocks everything. Is this rather a tesseract issue than eventlet? But still: how can this block if it happens in a separate thread where it reads line by line with context switch when find does not block?
Thanks to this question I learned something new today. Eventlet does offer a greenlet friendly version of subprocess and its functions, but for some odd reason it does not monkey patch this module in the standard library. Link to the eventlet implementation of subprocess: https://github.com/eventlet/eventlet/blob/master/eventlet/green/subprocess.py Looking at the eventlet patcher, the modules that are patched are os, select, socket, thread, time, MySQLdb, builtins and psycopg2. There is absolutely no reference to subprocess in the patcher. The good news is that I was able to work with Popen() in an application very similar to yours, after I replaced: import subprocess with: from eventlet.green import subprocess But note that the currently released version of eventlet (0.17.4) does not support the universal_newlines option in Popen, you will get an error if you use it. Support for this option is in master (here is the commit that added the option). You will either have to remove that option from your call, or else install the master branch of eventlet direct from github.
Are objects with the same id always equal when comparing them with ==?
If I have two objects o1 and o2, and we know that id(o1) == id(o2) returns true. Then, does it follow that o1 == o2 Or is this not always the case? The paper I'm working on says this is not the case, but in my opinion it should be true!
Not always: >>> nan = float('nan') >>> nan is nan True or formulated the same way as in the question: >>> id(nan) == id(nan) True but >>> nan == nan False NaN is a strange thing. Per definition it is not equal nor less or greater than itself. But it is the same object. More details why all comparisons have to return False in this SO question.
Recursively replace characters in a dictionary
How do I change all dots . to underscores (in the dict's keys), given an arbitrarily nested dictionary? What I tried is write two loops, but then I would be limited to 2-level-nested dictionaries. This ... { "brown.muffins": 5, "green.pear": 4, "delicious.apples": { "green.apples": 2 { } ... should become: { "brown_muffins": 5, "green_pear": 4, "delicious_apples": { "green_apples": 2 { } Is there an elegant way?
You can write a recursive function, like this from collections.abc import Mapping def rec_key_replace(obj): if isinstance(obj, Mapping): return {key.replace('.', '_'): rec_key_replace(val) for key, val in obj.items()} return obj and when you invoke this with the dictionary you have shown in the question, you will get a new dictionary, with the dots in keys replaced with _s {'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5} Explanation Here, we just check if the current object is an instance of dict and if it is, then we iterate the dictionary, replace the key and call the function recursively. If it is actually not a dictionary, then return it as it is.
Dict/Set Parsing Order Consistency
Containers that take hashable objects (such as dict keys or set items). As such, a dictionary can only have one key with the value 1, 1.0 or True etc. (note: simplified somewhat - hash collisions are permitted, but these values are considered equal) My question is: is the parsing order well-defined and is the resulting object predictable across implementations? For example, OSX Python 2.7.11 and 3.5.1 interprets dict like so: >>> { True: 'a', 1: 'b', 1.0: 'c', (1+0j): 'd' } {True: 'd'} In this case, it appears that the first key and the last value are preserved. Similar, in the case of set: >>> { True, 1, 1.0, (1+0j) } set([(1+0j)]) Here it appears that the last item is preserved. But (as mentioned in comments): >>> set([True, 1, 1.0]) set([True]) Now the first in the iterable is preserved. The documentation notes that the order of items (for example in dict.items) is undefined, however my question refers to the result of constructing dict or set objects.
dictionary-displays If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum. This means that you can specify the same key multiple times in the key/datum list, and the final dictionary’s value for that key will be the last one given. A dict comprehension, in contrast to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses. When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced. set displays A set display yields a new mutable set object, the contents being specified by either a sequence of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and added to the set object. When a comprehension is supplied, the set is constructed from the elements resulting from the comprehension. There is a difference in calling the set constructor or using a comprehension and the plain literal. def f1(): return {x for x in [True, 1]} def f2(): return set([True, 1]) def f3(): return {True, 1} print(f1()) print(f2()) print(f3()) import dis print("f1") dis.dis(f1) print("f2") dis.dis(f2) print("f3") dis.dis(f3) Output: {True} {True} {1} How they are created influences the outcome: 605 0 LOAD_CONST 1 (<code object <setcomp> at 0x7fd17dc9a270, file "/home/padraic/Dropbox/python/test.py", line 605>) 3 LOAD_CONST 2 ('f1.<locals>.<setcomp>') 6 MAKE_FUNCTION 0 9 LOAD_CONST 3 (True) 12 LOAD_CONST 4 (1) 15 BUILD_LIST 2 18 GET_ITER 19 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 22 RETURN_VALUE f2 608 0 LOAD_GLOBAL 0 (set) 3 LOAD_CONST 1 (True) 6 LOAD_CONST 2 (1) 9 BUILD_LIST 2 12 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 15 RETURN_VALUE f3 611 0 LOAD_CONST 1 (True) 3 LOAD_CONST 2 (1) 6 BUILD_SET 2 9 RETURN_VALUE Python only runs the BUILD_SET bytecode when you pass a pure literal separated by commas as per: When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and added to the set object. The line for the comprehension: When a comprehension is supplied, the set is constructed from the elements resulting from the comprehension. So thanks to Hamish filing a bug report it does indeed come down to the BUILD_SET opcode as per Raymond Hettinger's comment in the link The culprit is the BUILD_SET opcode in Python/ceval.c which unnecessarily loops backwards, the implementation of which is below: TARGET(BUILD_SET) { PyObject *set = PySet_New(NULL); int err = 0; if (set == NULL) goto error; while (--oparg >= 0) { PyObject *item = POP(); if (err == 0) err = PySet_Add(set, item); Py_DECREF(item); } if (err != 0) { Py_DECREF(set); goto error; } PUSH(set); DISPATCH(); }
Getting PKCS7 signer chain in python
I have PKCS7 message which is signed. It contains a data and a signing certificate (with the whole chain of trust). I have a code which uses m2crypto to get a certificate out of it. bio = BIO.MemoryBuffer(pkcs7message) p7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(bio._ptr())) sk = X509.X509_Stack() certStack = p7.get0_signers(sk) It works. However, certStack returns only one certificate (instead of returning the whole chain of certificates. Two questions: Am I missing something (may be there is an option to let it know that I need the whole chain) Are there other methods how to get the whole chain (may be using pyopenssl)?
I guess you are making a confusion between signers and certificate chain of a signer. PKCS7_get0_signers return the list of signers. In order to building a PKCS7 message with 2 signers, you can use following steps: Build key and certificate for first signer: openssl genrsa -out key1.pem openssl req -new -key key1.pem -subj "/CN=key1" | openssl x509 -req -signkey key1.pem -out cert1.pem Build key and certificate for second signer: openssl genrsa -out key2.pem openssl req -new -key key2.pem -subj "/CN=key2" | openssl x509 -req -signkey key2.pem -out cert2.pem Create an PKCS7 message using both signers : echo "Hello" | openssl smime -sign -nodetach \ -out signature.der -outform DER \ -inkey key1.pem -signer cert1.pem -inkey key2.pem -signer cert2.pem Then signers could be printed running your python script: from M2Crypto import * bio=BIO.File(open('signature.der')) smime_object = SMIME.PKCS7(m2.pkcs7_read_bio_der(bio._ptr())) signers = smime_object.get0_signers(X509.X509_Stack()) for cert in signers: print(cert.get_issuer().as_text()) It give the signers' issuer: CN=key1 CN=key2
Apply function to column before filtering
I have a column in my database called coordinates, now the coordinates column contains information on the range of time an object takes up within my graph. I want to allow the user to filter by the date, but the problem is I use a function to determine the date normally. Take: # query_result is the result of some filter operation for obj in query_result: time_range, altitude_range = get_shape_range(obj.coordinates) # time range for example would be "2006-06-01 07:56:17 - ..." Now if I wanted to filter by date, I would want to is a like: query_result = query_result.filter( DatabaseShape.coordinates.like('%%%s%%' % date)) But the problem is I first need to apply get_shape_range to coordinates in order to receive a string. Is there any way to do ... I guess a transform_filter operation? Such that before the like happens, I apply some function to coordinates? In this case I would need to write a get_time_range function that returned only time, but the question remains the same. EDIT: Here's my database class class DatabasePolygon(dbBase): __tablename__ = 'objects' id = Column(Integer, primary_key=True) # primary key tag = Column(String) # shape tag color = Column(String) # color of polygon time_ = Column(String) # time object was exported hdf = Column(String) # filename plot = Column(String) # type of plot drawn on attributes = Column(String) # list of object attributes coordinates = Column(String) # plot coordinates for displaying to user notes = Column(String) # shape notes lat = Column(String) @staticmethod def plot_string(i): return constants.PLOTS[i] def __repr__(self): """ Represent the database class as a JSON object. Useful as our program already supports JSON reading, so simply parse out the database as separate JSON 'files' """ data = {} for key in constants.plot_type_enum: data[key] = {} data[self.plot] = {self.tag: { 'color': self.color, 'attributes': self.attributes, 'id': self.id, 'coordinates': self.coordinates, 'lat': self.lat, 'notes': self.notes}} data['time'] = self.time_ data['hdfFile'] = self.hdf logger.info('Converting unicode to ASCII') return byteify(json.dumps(data)) and I'm using sqlite 3.0. The reasoning why behind most things are strings is because most of my values that are to be stored in the database are sent as strings, so storing is trivial. I'm wondering if I should do all this parsing magic with the functions before, and just have more database entries? for stuff like decimal time_begin, time_end, latitude_begin instead of having a string containing the range of time that I parse to find time_begin and time_end when i'm filtering
I think you should definitely parse strings to columns before storing it in the databases. Let the database do the job it was designed for! CREATE TABLE [coordinates] ( id INTEGER NOT NULL PRIMARY KEY, tag VARCHAR2(32), color VARCHAR2(32) default 'green', time_begin TIMESTAMP, time_end TIMESTAMP, latitude_begin INT ); create index ix_coord_tag on coordinates(tag); create index ix_coord_tm_beg on coordinates(time_begin); insert into coordinates(tag, time_begin, time_end, latitude_begin) values('tag1', '2006-06-01T07:56:17', '2006-06-01T07:56:19', 123); insert into coordinates(tag, time_begin, time_end, latitude_begin) values('tag1', '2016-01-01T11:35:01', '2016-01-01T12:00:00', 130); insert into coordinates(tag, color, time_begin, time_end, latitude_begin) values('tag2', 'blue', '2014-03-03T20:11:01', '2014-03-03T20:11:20', 2500); insert into coordinates(tag, color, time_begin, time_end, latitude_begin) values('tag2', 'blue', '2014-03-12T23:59:59', '2014-03-13T00:00:29', 2978); insert into coordinates(tag, color, time_begin, time_end, latitude_begin) values('tag3', 'red', '2016-01-01T11:35:01', '2016-01-01T12:00:00', 13000); insert into coordinates(tag, color, time_begin, time_end, latitude_begin) values('tag3', 'red', '2016-01-01T12:00:00', '2016-01-01T12:00:11', 13001); .headers on .mode column select * from coordinates where tag='tag1' and '2006-06-01T07:56:18' between time_begin and time_end; select * from coordinates where color='blue' and time_end between '2014-03-13T00:00:00' and '2014-03-13T00:10:00'; Output: sqlite> select * from coordinates where tag='tag1' and '2006-06-01T07:56:18' between time_begin and time_end; id tag color time_begin time_end latitude_begin ---------- ---------- ---------- ------------------- ------------------- -------------- 1 tag1 green 2006-06-01T07:56:17 2006-06-01T07:56:19 123 sqlite> sqlite> select * from coordinates where color='blue' and time_end between '2014-03-13T00:00:00' and '2014-03-13T00:10:00'; id tag color time_begin time_end latitude_begin ---------- ---------- ---------- ------------------- ------------------- -------------- 4 tag2 blue 2014-03-12T23:59:59 2014-03-13T00:00:29 2978
pronoun resolution backwards
The usual coreference resolution works in the following way: Provided The man likes math. He really does. it figures out that he refers to the man. There are plenty of tools to do this. However, is there a way to do it backwards? For example, given The man likes math. The man really does. I want to do the pronoun resolution "backwards," so that I get an output like The man likes math. He really does. My input text will mostly be 3~10 sentences, and I'm working with python.
This is perhaps not really an answer to be happy with, but I think the answer is that there's no such functionality built in anywhere, though you can code it yourself without too much difficulty. Giving an outline of how I'd do it with CoreNLP: Still run coref. This'll tell you that "the man" and "the man" are coreferent, and so you can replace the second one with a pronoun. Run the gender annotator from CoreNLP. This is a poorly-documented and even more poorly advertised annotator that tries to attach gender to tokens in a sentence. Somehow figure out plurals. Most of the time you could use the part-of-speech tag: plural nouns get the tags NNS or NNPS, but there are some complications so you might also want to consider (1) the existence of conjunctions in the antecedent; (2) the lemma of a word being different from its text; (3) especially in conjunction with 2, the word ending in 's' or 'es' -- this can distinguish between lemmatizations which strip out plurals versus lemmatizations which strip out tenses, etc. This is enough to figure out the right pronoun. Now it's just a matter of chopping up the sentence and putting it back together. This is a bit of a pain if you do it in CoreNLP -- the code is just not set up to change the text of a sentence -- but in the worst case you can always just re-annotate a new surface form. Hope this helps somewhat!
Fail during installation of Pillow (Python module) in Linux
I'm trying to install Pillow (Python module) using pip, but it throws this error: ValueError: jpeg is required unless explicitly disabled using --disable-jpeg, aborting So as the error says, I tried: pip install pillow --global-option="--disable-jpeg" But it fails with: error: option --disable-jpeg not recognized Any hints how to deal with it?
There is a bug reported for Pillow here, which indicates that libjpeg and zlib are now required as of Pillow 3.0.0. The installation instructions for Pillow on Linux give advice of how to install these packages. Note that not all of the following packages may be missing on your machine (comments suggest that only libjpeg8-dev is actually missing). Ubuntu 12.04 LTS or Raspian Wheezy 7.0 sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk Ubuntu 14.04 sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk Fedora 20 The Fedora 20 equivalent of libjpeg8-dev is libjpeg-devel. sudo yum install libtiff-devel libjpeg-devel libzip-devel freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel Mac OS X (via Homebrew) On Mac OS X with Homebrew this can be fixed using: brew install libjpeg zlib You may also need to force-link zlib using the following: brew link zlib --force Thanks to Panos Angelopoulous and nelsonvarela in the comments. Update 5th July 2016: In current versions of Homebrew the above may no longer work, as there is no longer a formula for zlib available in the main repository (Homebrew will prompt you to install lzlib which is a different library and will not solve this problem). There is a formula available in the dupes repository. You can either tap this repository, and install as normal: brew tap homebrew/dupes brew install zlib Or you can install zlib via xcode instead, as follows: xcode-select --install Thanks to benjaminz in the comments and Kal's answer below After these are installed the pip installation of Pillow should work normally.
Relative import error with py2exe
I was trying to generate an executable for a simple Python script. My setup.py code looks like this: from distutils.core import setup import py2exe setup(console=["script.py"]) However, I am getting the error shown in the screenshot. Is there something I could try to fix this? I am using Windows 10.
It seems that in your mf3.py you are importing beyond the top level. Let's suppose that your project structure is as follows: folder/ main.py mod/ __init__.py components/ __init__.py expander.py language_id.py utilities/ __init__.py functions.py First make sure that main.py refers to the subpackages as: from mod.components.expander import * from mod.utilities.functions import * expander.py and language_id.py have access to functions.py with: from ..utilities.functions import * Add options to your setup.py You can also use more py2exe options in order that you are importing all the modules and the packages required by your project. E.g. # setup.py from distutils.core import setup import py2exe setup(console=["script.py"], options={ "py2exe":{ "optimize": 2, "includes": ["mf1.py", "mf2.py", "mf3.py"], # List of all the modules you want to import "packages": ["package1"] # List of the package you want to make sure that will be imported } } ) In this way you can force the import of the missing script of your project
Tensorflow Strides Argument
I am trying to understand the strides argument in tf.nn.avg_pool, tf.nn.max_pool, tf.nn.conv2d. The documentation repeatedly says strides: A list of ints that has length >= 4. The stride of the sliding window for each dimension of the input tensor. My questions are: What do each of the 4+ integers represent? Why must they have strides[0] = strides[3] = 1 for convnets? In this example we see tf.reshape(_X,shape=[-1, 28, 28, 1]). Why -1? Sadly the examples in the docs for reshape using -1 don't translate too well to this scenario.
The pooling and convolutional ops slide a "window" across the input tensor. Using tf.nn.conv2d as an example: If the input tensor has 4 dimensions: [batch, height, width, channels], then the convolution operates on a 2D window on the height, width dimensions. strides determines how much the window shifts by in each of the dimensions. The typical use sets the first (the batch) and last (the depth) stride to 1. Let's use a very concrete example: Running a 2-d convolution over a 32x32 greyscale input image. I say greyscale because then the input image has depth=1, which helps keep it simple. Let that image look like this: 00 01 02 03 04 ... 10 11 12 13 14 ... 20 21 22 23 24 ... 30 31 32 33 34 ... ... Let's run a 2x2 convolution window over a single example (batch size = 1). We'll give the convolution an output channel depth of 8. The input to the convolution has shape=[1, 32, 32, 1]. If you specify strides=[1,1,1,1] with padding=SAME, then the output of the filter will be [1, 32, 32, 8]. The filter will first create an output for: F(00 01 10 11) And then for: F(01 02 11 12) and so on. Then it will move to the second row, calculating: F(10, 11 20, 21) then F(11, 12 21, 22) If you specify a stride of [2, 2] it won't do overlapping windows. It will compute: F(00, 01 10, 11) and then F(02, 03 12, 13) The stride operates similarly for the pooling operators. Question 2: Why strides [1, x, y, 1] for convnets The first 1 is the batch: You don't usually want to skip over examples in your batch, or you shouldn't have included them in the first place. :) The last 1 is the depth of the convolution: You don't usually want to skip inputs, for the same reason. The conv2d operator is more general, so you could create convolutions that slide the window along other dimensions, but that's not a typical use in convnets. The typical use is to use them spatially. Why reshape to -1 -1 is a placeholder that says "adjust as necessary to match the size needed for the full tensor." It's a way of making the code be independent of the input batch size, so that you can change your pipeline and not have to adjust the batch size everywhere in the code.
How can I split my Click commands, each with a set of sub-commands, into multiple files?
I have one large click application that I've developed, but navigating through the different commands/subcommands is getting rough. How do I organize my commands into separate files? Is it possible to organize commands and their subcommands into separate classes? Here's an example of how I would like to separate it: init import click @click.group() @click.version_option() def cli(): pass #Entry Point command_cloudflare.py @cli.group() @click.pass_context def cloudflare(ctx): pass @cloudflare.group('zone') def cloudflare_zone(): pass @cloudflare_zone.command('add') @click.option('--jumpstart', '-j', default=True) @click.option('--organization', '-o', default='') @click.argument('url') @click.pass_obj @__cf_error_handler def cloudflare_zone_add(ctx, url, jumpstart, organization): pass @cloudflare.group('record') def cloudflare_record(): pass @cloudflare_record.command('add') @click.option('--ttl', '-t') @click.argument('domain') @click.argument('name') @click.argument('type') @click.argument('content') @click.pass_obj @__cf_error_handler def cloudflare_record_add(ctx, domain, name, type, content, ttl): pass @cloudflare_record.command('edit') @click.option('--ttl', '-t') @click.argument('domain') @click.argument('name') @click.argument('type') @click.argument('content') @click.pass_obj @__cf_error_handler def cloudflare_record_edit(ctx, domain): pass command_uptimerobot.py @cli.group() @click.pass_context def uptimerobot(ctx): pass @uptimerobot.command('add') @click.option('--alert', '-a', default=True) @click.argument('name') @click.argument('url') @click.pass_obj def uptimerobot_add(ctx, name, url, alert): pass @uptimerobot.command('delete') @click.argument('names', nargs=-1, required=True) @click.pass_obj def uptimerobot_delete(ctx, names): pass
I'm looking for something like this at the moment, in your case is simple because you have groups in each of the files, you can solve this problema as explained in the documentation: In the init.py file: import click from command_cloudflare import cloudflare from command_uptimerobot import uptimerobot cli = click.CommandCollection(sources=[cloudflare, uptimerobot]) if __name__ == '__main__': cli() The best part of this solution is that is totally compliant with pep8 and other linters becaouse you don't need to import something you wouldn't use and you dont need to import * from anywhere. I hope this helps and good look with your cli.
Psycopg2 Python SSL Support is not compiled in
I am trying to connect to my postgres database using psycopg2 with sslmode='required' param; however, I get the following error psycopg2.OperationalError: sslmode value "require" invalid when SSL support is not compiled in Heres a couple details about my system Mac OS X El Capitan Python 2.7 Installed psycopg2 via pip Installed python via homebrew Here is what I tried to do to fix the problem brew uninstall python which python still shows python living in /usr/local/bin/python, tried to uninstall this but couldnt. And heard that this is the python that the OS uses and should not be uninstalled anyways brew install python --with-brewed-openssl --build-from-source pip uninstall psycopg2 pip install psycopg2 After doing all of this, the exception still happens. I am running this python script via #!/usr/bin/env python Not sure if it matters, but that is a different directory than the one that which python shows
Since you're installing via pip, you should be using the most recent version of psycopg2 (2.6.1). After a little digging through the code, it seems that the exception is being thrown in connection_int.c, which directly calls the postgresql-c-libraries to set up the db-connection. The call happens like so: self->pgconn = pgconn = PQconnectStart(self->dsn); Dprintf("conn_connect: new postgresql connection at %p", pgconn); if (pgconn == NULL) { Dprintf("conn_connect: PQconnectStart(%s) FAILED", self->dsn); PyErr_SetString(OperationalError, "PQconnectStart() failed"); return -1; } else if (PQstatus(pgconn) == CONNECTION_BAD) { Dprintf("conn_connect: PQconnectdb(%s) returned BAD", self->dsn); PyErr_SetString(OperationalError, PQerrorMessage(pgconn)); return -1; } The keywords which were specified in your connect statement to psycopg2.connect() are being handled to that function and errors are returned as OperationalError exception. The error is actually being generated directly in the postgresql-lib - you may want to check which version you are using, how it was built and, if possible, upgrade it to a version with SSL support or rebuilt it from source with SSL enabled. The postgresql-docs also state that missing SSL support will raise an error, if the sslmode is set to require, verify-ca or verify-full. See here under sslmode for reference. The postgres-website lists several ways to install postgres from binary packages, so you might choose one which suits your needs. I'm not familiar with OSX, so I don't have a recommendation what's best. This question may also be helpful. You also need to reinstall the psycopg2-module, be sure to use the newly installed lib when rebuilding it. Refer to the linked question (in short, you will need to place the path to pg_config which is included in your new installation to $PATH when running pip install psycopg2).
Insert 0s into 2d array
I have an array x: x = [0, -1, 0, 3] and I want y: y = [[0, -2, 0, 2], [0, -1, 0, 3], [0, 0, 0, 4]] where the first row is x-1, the second row is x, and the third row is x+1. All even column indices are zero. I'm doing: y=np.vstack(x-1, x, x+1) y[0][::2] = 0 y[1][::2] = 0 y[2][::2] = 0 I was thinking there might be a one-liner to do this instead of 4.
In two lines >>> x = np.array([0, -1, 0, 3]) >>> y = np.vstack((x-1, x, x+1)) >>> y[:,::2] = 0 >>> y array([[ 0, -2, 0, 2], [ 0, -1, 0, 3], [ 0, 0, 0, 4]]) Explanation y[:, ::2] gives the full first dimension. i.e all rows and every other entry form the second dimension, i.e. the columns: array([[-1, -1], [ 0, 0], [ 1, 1]]) This is different from: y[:][::2] because this works in two steps. Step one: y[:] gives a view of the whole array: array([[-1, -2, -1, 2], [ 0, -1, 0, 3], [ 1, 0, 1, 4]]) Therefore, step two is doing essentially this: y[::2] array([[-1, -2, -1, 2], [ 1, 0, 1, 4]]) It works along the first dimension. i.e. the rows.
How to link PyCharm with PySpark?
I'm new with apache spark and apparently I installed apache-spark with homebrew in my macbook: Last login: Fri Jan 8 12:52:04 on console user@MacBook-Pro-de-User-2:~$ pyspark Python 2.7.10 (default, Jul 13 2015, 12:05:58) [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin Type "help", "copyright", "credits" or "license" for more information. Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties 16/01/08 14:46:44 INFO SparkContext: Running Spark version 1.5.1 16/01/08 14:46:46 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 16/01/08 14:46:47 INFO SecurityManager: Changing view acls to: user 16/01/08 14:46:47 INFO SecurityManager: Changing modify acls to: user 16/01/08 14:46:47 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(user); users with modify permissions: Set(user) 16/01/08 14:46:50 INFO Slf4jLogger: Slf4jLogger started 16/01/08 14:46:50 INFO Remoting: Starting remoting 16/01/08 14:46:51 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkDriver@192.168.1.64:50199] 16/01/08 14:46:51 INFO Utils: Successfully started service 'sparkDriver' on port 50199. 16/01/08 14:46:51 INFO SparkEnv: Registering MapOutputTracker 16/01/08 14:46:51 INFO SparkEnv: Registering BlockManagerMaster 16/01/08 14:46:51 INFO DiskBlockManager: Created local directory at /private/var/folders/5x/k7n54drn1csc7w0j7vchjnmc0000gn/T/blockmgr-769e6f91-f0e7-49f9-b45d-1b6382637c95 16/01/08 14:46:51 INFO MemoryStore: MemoryStore started with capacity 530.0 MB 16/01/08 14:46:52 INFO HttpFileServer: HTTP File server directory is /private/var/folders/5x/k7n54drn1csc7w0j7vchjnmc0000gn/T/spark-8e4749ea-9ae7-4137-a0e1-52e410a8e4c5/httpd-1adcd424-c8e9-4e54-a45a-a735ade00393 16/01/08 14:46:52 INFO HttpServer: Starting HTTP Server 16/01/08 14:46:52 INFO Utils: Successfully started service 'HTTP file server' on port 50200. 16/01/08 14:46:52 INFO SparkEnv: Registering OutputCommitCoordinator 16/01/08 14:46:52 INFO Utils: Successfully started service 'SparkUI' on port 4040. 16/01/08 14:46:52 INFO SparkUI: Started SparkUI at http://192.168.1.64:4040 16/01/08 14:46:53 WARN MetricsSystem: Using default name DAGScheduler for source because spark.app.id is not set. 16/01/08 14:46:53 INFO Executor: Starting executor ID driver on host localhost 16/01/08 14:46:53 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 50201. 16/01/08 14:46:53 INFO NettyBlockTransferService: Server created on 50201 16/01/08 14:46:53 INFO BlockManagerMaster: Trying to register BlockManager 16/01/08 14:46:53 INFO BlockManagerMasterEndpoint: Registering block manager localhost:50201 with 530.0 MB RAM, BlockManagerId(driver, localhost, 50201) 16/01/08 14:46:53 INFO BlockManagerMaster: Registered BlockManager Welcome to ____ __ / __/__ ___ _____/ /__ _\ \/ _ \/ _ `/ __/ '_/ /__ / .__/\_,_/_/ /_/\_\ version 1.5.1 /_/ Using Python version 2.7.10 (default, Jul 13 2015 12:05:58) SparkContext available as sc, HiveContext available as sqlContext. >>> I would like start playing in order to learn more about MLlib. However, I use Pycharm to write scripts in python. The problem is: when I go to Pycharm and try to call pyspark, Pycharm can not found the module. I tried adding the path to Pycharm as follows: Then from a blog I tried this: import os import sys # Path for spark source folder os.environ['SPARK_HOME']="/Users/user/Apps/spark-1.5.2-bin-hadoop2.4" # Append pyspark to Python Path sys.path.append("/Users/user/Apps/spark-1.5.2-bin-hadoop2.4/python/pyspark") try: from pyspark import SparkContext from pyspark import SparkConf print ("Successfully imported Spark Modules") except ImportError as e: print ("Can not import Spark Modules", e) sys.exit(1) And still can not start using PySpark with Pycharm, any idea of how to "link" PyCharm with apache-pyspark?. Update: Then I search for apache-spark and python path in order to set the environment variables of Pycharm: apache-spark path: user@MacBook-Pro-User-2:~$ brew info apache-spark apache-spark: stable 1.6.0, HEAD Engine for large-scale data processing https://spark.apache.org/ /usr/local/Cellar/apache-spark/1.5.1 (649 files, 302.9M) * Poured from bottle From: https://github.com/Homebrew/homebrew/blob/master/Library/Formula/apache-spark.rb python path: user@MacBook-Pro-User-2:~$ brew info python python: stable 2.7.11 (bottled), HEAD Interpreted, interactive, object-oriented programming language https://www.python.org /usr/local/Cellar/python/2.7.10_2 (4,965 files, 66.9M) * Then with the above information I tried to set the environment variables as follows: Any idea of how to correctly link Pycharm with pyspark? Then when I run a python script with the above configuration I have this exception: /usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/user/PycharmProjects/spark_examples/test_1.py Traceback (most recent call last): File "/Users/user/PycharmProjects/spark_examples/test_1.py", line 1, in <module> from pyspark import SparkContext ImportError: No module named pyspark UPDATE: Then I tried this configurations proposed by @zero323 Configuration 1: /usr/local/Cellar/apache-spark/1.5.1/ out: user@MacBook-Pro-de-User-2:/usr/local/Cellar/apache-spark/1.5.1$ ls CHANGES.txt NOTICE libexec/ INSTALL_RECEIPT.json README.md LICENSE bin/ Configuration 2: /usr/local/Cellar/apache-spark/1.5.1/libexec out: user@MacBook-Pro-de-User-2:/usr/local/Cellar/apache-spark/1.5.1/libexec$ ls R/ bin/ data/ examples/ python/ RELEASE conf/ ec2/ lib/ sbin/
Create Run configuration: Go to Run -> Edit configurations Add new Python configuration Set Script path so it points to the script you want to execute Edit Environment variables field so it contains at least: SPARK_HOME - it should point to the directory with Spark installation. It should contain directories such as bin (with spark-submit, spark-shell, etc.) and conf (with spark-defaults.conf, spark-env.sh, etc.) PYTHONPATH - it should contain $SPARK_HOME/python and optionally $SPARK_HOME/python/lib/py4j-some-version.src.zip if not available otherwise. some-version should match Py4J version used by a given Spark installation (0.8.2.1 - 1.5, 0.9 - 1.6.0) Apply the settings Add PySpark library to the interpreter path (required for code completion): Go to File -> Settings -> Project Interpreter Open settings for an interpreter you want to use with Spark Edit interpreter paths so it contains path to $SPARK_HOME/python (an Py4J if required) Save the settings Use newly created configuration to run your script.
for loops and iterating through lists
Here is a snippet of code which gives the output: 0 1 2 2. I had expected the output 3 3 3 3 since a[-1] accesses the number 3 in the list. The explanation given online says "The value of a[-1] changes in each iteration" but I don't quite understand how or why. Any explanations would be great! a = [0, 1, 2, 3] for a[-1] in a: print(a[-1])
While doing for a[-1] in a, you actually iterate through the list and temporary store the value of the current element into a[-1]. You can see the loop like these instructions: a[-1] = a[0] # a = [0, 1, 2, 0] print(a[-1]) # 0 a[-1] = a[1] # a = [0, 1, 2, 1] print(a[-1]) # 1 a[-1] = a[2] # a = [0, 1, 2, 2] print(a[-1]) # 2 a[-1] = a[3] # a = [0, 1, 2, 2] print(a[-1]) # 2 So, when you are on the third element, then 2 is stored to a[-1] (which value is 1, but was 0 before and 3 on start). Finally, when it comes to the last element (and the end of the iteration), the last value stored into a[-1] is 2 which explains why it is printed twice.
Recursive factorial using dict causes RecursionError
A simple recursive factorial method works perfectly: def fact(n): if n == 0: return 1 return n * fact(n-1) But I wanted to experiment a little and use a dict instead. Logically, this should work, but a bunch of print statements tell me that n, instead of stopping at 0, glides down across the negative numbers until the maximum recursion depth is reached: def recursive_fact(n): lookup = {0: 1} return lookup.get(n, n*recursive_fact(n-1)) Why is that?
Python doesn't lazily evaluate parameters. The default value passed to dict.get call will also be evaluated before calling the dict.get. So, in your case, the default value has a recursive call and since your condition is never met, it does infinite recursion. You can confirm this, with this program >>> def getter(): ... print("getter called") ... return 0 ... >>> {0: 1}.get(0, getter()) getter called 1 Even though the key 0 exists in the dictionary, since all parameters passed to functions in Python will be evaluated, getter is also invoked, before the actual dict.get is made. If all you want to do is to avoid multiple recursive evaluations when the values are already evaluated, then you use functools.lru_cache, if you are using Python 3.2+ >>> @functools.lru_cache() ... def fact(n): ... print("fact called with {}".format(n)) ... if n == 0: ... return 1 ... return n * fact(n-1) ... >>> fact(3) fact called with 3 fact called with 2 fact called with 1 fact called with 0 6 >>> fact(4) fact called with 4 24 This decorator simply caches the results for the parameters passed and if the same call is made again, it will simply return the value from the cache. If you want to fix your custom caching function to work, then you need to define the look_up outside the function, so that it will not be created whenever the function is called. >>> look_up = {0: 1} >>> def fact(n): ... if n not in look_up: ... print("recursing when n is {}".format(n)) ... look_up[n] = n * fact(n - 1) ... return look_up[n] ... >>> fact(3) recursing when n is 3 recursing when n is 2 recursing when n is 1 6 >>> fact(4) recursing when n is 4 24 >>> fact(4) 24 Otherwise you can use the default parameter, like this >>> def fact(n, look_up={0: 1}): ... if n not in look_up: ... print("recursing when n is {}".format(n)) ... look_up[n] = n * fact(n - 1) ... return look_up[n]
Avoid `logger=logging.getLogger(__name__)`
We set up logging like the django docs told us: https://docs.djangoproject.com/en/1.9/topics/logging/#using-logging # import the logging library import logging # Get an instance of a logger logger = logging.getLogger(__name__) def my_view(request, arg1, arg): ... if bad_mojo: # Log an error message logger.error('Something went wrong!') I want to avoid this line in every Python file which wants to log: logger = logging.getLogger(__name__) I want it simple: logging.error('Something went wrong!') But we want to keep one feature: We want to see the Python file name in the logging output. Up to now we use this format: '%(asctime)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s' Example output: 2016-01-11 12:12:31 myapp.foo +68: ERROR Something went wrong How to avoid logger = logging.getLogger(__name__)?
You can use logging.basicConfig to define the default interface available through logging as follows: import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s', ) This definition will now be used whenever you do the following anywhere in your application: import logging logging.error(...) While __name__ is not available, the equivalent (and other options) are available through the default LogRecord attributes that can be used for error string formatting - including module, filename and pathname. The following is a two-script demonstration of this in action: scripta.py import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(module)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s', ) from scriptb import my_view my_view() scriptb.py import logging def my_view(): # Log an error message logging.error('Something went wrong!') The logging definition is defined in scripta.py, with the added module parameter. In scriptb.py we simply need to import logging to get access to this defined default. When running scripta.py the following output is generated: 2016-01-14 13:22:24,640 scriptb root.my_view +9: ERROR [14144] Something went wrong! Which shows the module (scriptb) where the logging of the error occurs. According to this answer you can continue to use any per-module configuration of logging from Django, by turning off Django handling and setting up the root handler as follows: # settings.py - django config LOGGING_CONFIG = None # disables Django handling of logging LOGGING = {...} # your standard Django logging configuration import logging.config logging.config.dictConfig(LOGGING)
Calling list() empties my iterable object?
a = range(1, 3) a = iter(a) list(a) a = list(a) a evaluates to [ ]. a = range(1, 3) a = iter(a) a = list(a) a evaluates to [1, 2]. The first result is unexpected to me. What semantics are going on here?
The issue is not list() but iter() which as documented returns a single-use iterator. Once something has accessed the iterator's elements, the iterator is permanently empty. The more commonly used iterable type is (normally) reusable, and the two types shouldn't be confused. Note that you don't need iter() in order to turn a range into a list, because list() takes an iterable as an argument: >>> a = range(1, 3) >>> list(a) [1, 2] >>> list(a) [1, 2] And it is only the iterator returned by iter() that is single-use: >>> b = iter(a) >>> list(b) [1, 2] >>> list(b) [] >>> list(a) [1, 2]
Using moviepy, scipy and numpy in amazon lambda
I'd like to generate video using AWS Lambda feature. I've followed instructions found here and here. And I now have the following process to build my Lambda function: Step 1 Fire a Amazon Linux EC2 instance and run this as root on it: #! /usr/bin/env bash # Install the SciPy stack on Amazon Linux and prepare it for AWS Lambda yum -y update yum -y groupinstall "Development Tools" yum -y install blas --enablerepo=epel yum -y install lapack --enablerepo=epel yum -y install atlas-sse3-devel --enablerepo=epel yum -y install Cython --enablerepo=epel yum -y install python27 yum -y install python27-numpy.x86_64 yum -y install python27-numpy-f2py.x86_64 yum -y install python27-scipy.x86_64 /usr/local/bin/pip install --upgrade pip mkdir -p /home/ec2-user/stack /usr/local/bin/pip install moviepy -t /home/ec2-user/stack cp -R /usr/lib64/python2.7/dist-packages/numpy /home/ec2-user/stack/numpy cp -R /usr/lib64/python2.7/dist-packages/scipy /home/ec2-user/stack/scipy tar -czvf stack.tgz /home/ec2-user/stack/* Step 2 I scp the resulting tarball to my laptop. And then run this script to build a zip archive. #! /usr/bin/env bash mkdir tmp rm lambda.zip tar -xzf stack.tgz -C tmp zip -9 lambda.zip process_movie.py zip -r9 lambda.zip *.ttf cd tmp/home/ec2-user/stack/ zip -r9 ../../../../lambda.zip * process_movie.py script is at the moment only a test to see if the stack is ok: def make_movie(event, context): import os print(os.listdir('.')) print(os.listdir('numpy')) try: import scipy except ImportError: print('can not import scipy') try: import numpy except ImportError: print('can not import numpy') try: import moviepy except ImportError: print('can not import moviepy') Step 3 Then I upload the resulting archive to S3 to be the source of my lambda function. When I test the function I get the following callstack: START RequestId: 36c62b93-b94f-11e5-9da7-83f24fc4b7ca Version: $LATEST ['tqdm', 'imageio-1.4.egg-info', 'decorator.pyc', 'process_movie.py', 'decorator-4.0.6.dist-info', 'imageio', 'moviepy', 'tqdm-3.4.0.dist-info', 'scipy', 'numpy', 'OpenSans-Regular.ttf', 'decorator.py', 'moviepy-0.2.2.11.egg-info'] ['add_newdocs.pyo', 'numarray', '__init__.py', '__config__.pyc', '_import_tools.py', 'setup.pyo', '_import_tools.pyc', 'doc', 'setupscons.py', '__init__.pyc', 'setup.py', 'version.py', 'add_newdocs.py', 'random', 'dual.pyo', 'version.pyo', 'ctypeslib.pyc', 'version.pyc', 'testing', 'dual.pyc', 'polynomial', '__config__.pyo', 'f2py', 'core', 'linalg', 'distutils', 'matlib.pyo', 'tests', 'matlib.pyc', 'setupscons.pyc', 'setup.pyc', 'ctypeslib.py', 'numpy', '__config__.py', 'matrixlib', 'dual.py', 'lib', 'ma', '_import_tools.pyo', 'ctypeslib.pyo', 'add_newdocs.pyc', 'fft', 'matlib.py', 'setupscons.pyo', '__init__.pyo', 'oldnumeric', 'compat'] can not import scipy 'module' object has no attribute 'core': AttributeError Traceback (most recent call last): File "/var/task/process_movie.py", line 91, in make_movie import numpy File "/var/task/numpy/__init__.py", line 122, in <module> from numpy.__config__ import show as show_config File "/var/task/numpy/numpy/__init__.py", line 137, in <module> import add_newdocs File "/var/task/numpy/numpy/add_newdocs.py", line 9, in <module> from numpy.lib import add_newdoc File "/var/task/numpy/lib/__init__.py", line 13, in <module> from polynomial import * File "/var/task/numpy/lib/polynomial.py", line 11, in <module> import numpy.core.numeric as NX AttributeError: 'module' object has no attribute 'core' END RequestId: 36c62b93-b94f-11e5-9da7-83f24fc4b7ca REPORT RequestId: 36c62b93-b94f-11e5-9da7-83f24fc4b7ca Duration: 112.49 ms Billed Duration: 200 ms Memory Size: 1536 MB Max Memory Used: 14 MB I cant understand why python does not found the core directory that is present in the folder structure. EDIT: Following @jarmod advice I've reduced the lambdafunction to: def make_movie(event, context): print('running make movie') import numpy I now have the following error: START RequestId: 6abd7ef6-b9de-11e5-8aee-918ac0a06113 Version: $LATEST running make movie Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch your python intepreter from there.: ImportError Traceback (most recent call last): File "/var/task/process_movie.py", line 3, in make_movie import numpy File "/var/task/numpy/__init__.py", line 127, in <module> raise ImportError(msg) ImportError: Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch your python intepreter from there. END RequestId: 6abd7ef6-b9de-11e5-8aee-918ac0a06113 REPORT RequestId: 6abd7ef6-b9de-11e5-8aee-918ac0a06113 Duration: 105.95 ms Billed Duration: 200 ms Memory Size: 1536 MB Max Memory Used: 14 MB
I was also following your first link and managed to import numpy and pandas in a Lambda function this way (on Windows): Started a (free-tier) t2.micro EC2 instance with 64-bit Amazon Linux AMI 2015.09.1 and used Putty to SSH in. Tried the same commands you used and the one recommended by the Amazon article: sudo yum -y update sudo yum -y upgrade sudo yum -y groupinstall "Development Tools" sudo yum -y install blas --enablerepo=epel sudo yum -y install lapack --enablerepo=epel sudo yum -y install Cython --enablerepo=epel sudo yum install python27-devel python27-pip gcc Created the virtual environment: virtualenv ~/env source ~/env/bin/activate Installed the packages: sudo ~/env/bin/pip2.7 install numpy sudo ~/env/bin/pip2.7 install pandas Then, using WinSCP, I logged in and downloaded everything (except _markerlib, pip*, pkg_resources, setuptools* and easyinstall*) from /home/ec2-user/env/lib/python2.7/dist-packages, and everything from /home/ec2-user/env/lib64/python2.7/site-packages from the EC2 instance. I put all these folders and files into one zip, along with the .py file containing the Lambda function. illustration of all files copied Because this .zip is larger than 10 MB, I created an S3 bucket to store the file. I copied the link of the file from there and pasted at "Upload a .ZIP from Amazon S3" at the Lambda function. With this, I could import numpy and pandas. I'm not familiar with moviepy, but scipy might already be tricky as Lambda has a limit for unzipped deployment package size at 262 144 000 bytes. I'm afraid numpy and scipy together are already over that.
Python with...as for custom context manager
I wrote a simple context manager in Python for handling unit tests (and to try to learn context managers): class TestContext(object): test_count=1 def __init__(self): self.test_number = TestContext.test_count TestContext.test_count += 1 def __enter__(self): pass def __exit__(self, exc_type, exc_value, exc_traceback): if exc_value == None: print 'Test %d passed' %self.test_number else: print 'Test %d failed: %s' %(self.test_number, exc_value) return True If I write a test as follows, everything works okay. test = TestContext() with test: print 'running test %d....' %test.test_number raise Exception('this test failed') However, if I try to use with...as, I don't get a reference to the TestContext() object. Running this: with TestContext() as t: print t.test_number Raises the exception 'NoneType' object has no attribute 'test_number'. Where am I going wrong?
__enter__ needs to return self. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any. This will work. class TestContext(object): test_count=1 def __init__(self): self.test_number = TestContext.test_count TestContext.test_count += 1 def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_traceback): if exc_value == None: print 'Test %d passed' % self.test_number else: print 'Test %d failed: %s' % (self.test_number, exc_value) return True
Difference between coroutine and future/task in Python 3.5?
Let's say we have a dummy function: async def foo(arg): result = await some_remote_call(arg) return result.upper() What's the difference between: coros = [] for i in range(5): coros.append(foo(i)) loop = get_event_loop() loop.run_until_complete(wait(coros)) And: from asyncio import ensure_future futures = [] for i in range(5): futures.append(ensure_future(foo(i))) loop = get_event_loop() loop.run_until_complete(wait(futures)) Note: The example returns a result, but this isn't the focus of the question. When return value matters, use gather() instead of wait(). Regardless of return value, I'm looking for clarity on ensure_future(). wait(coros) and wait(futures) both run the coroutines, so when and why should a coroutine be wrapped in ensure_future? Basically, what's the Right Way (tm) to run a bunch of non-blocking operations using Python 3.5's async? For extra credit, what if I want to batch the calls? For example, I need to call some_remote_call(...) 1000 times, but I don't want to crush the web server/database/etc with 1000 simultaneous connections. This is doable with a thread or process pool, but is there a way to do this with asyncio?
A coroutine is a generator function that can both yield values and accept values from the outside. The benefit of using a coroutine is that we can pause the execution of a function and resume it later. In case of a network operation, it makes sense to pause the execution of a function while we're waiting for the response. We can use the time to run some other functions. A future is like the Promise objects from Javascript. It is like a place holder for a value that will be materialized in the future. In the above mentioned case, while waiting on network I/O, a function can give us a container, a promise that it will fill the container with the value when the operation completes. We hold on to the future object and when it's fulfilled, we can call a method on it to retrieve the actual result. Direct Answer: You don't need ensure_future if you don't need the results. They are good if you need the results or retrieve exceptions occured. Extra Credits: I would choose run_in_executor and pass an Executor instance to control the number of max workers. Explanations and Sample codes In the first example, you are using coroutines. The wait function takes a bunch of coroutines and combines them together. So wait() finishes when all the coroutines are exhausted (completed/finished returning all the values). loop = get_event_loop() # loop.run_until_complete(wait(coros)) The run_until_complete method would make sure that the loop is alive until the execution is finished. Please notice how you are not getting the results of the async execution in this case. In the second example, you are using the ensure_future function to wrap a coroutine and return a Task object which is a kind of Future. The coroutine is scheduled to be executed in the main event loop when you call ensure_future. The returned future/task object doesn't yet have a value but over time, when the network operations finish, the future object will hold the result of the operation. from asyncio import ensure_future futures = [] for i in range(5): futures.append(ensure_future(foo(i))) loop = get_event_loop() loop.run_until_complete(wait(futures)) So in this example, we're doing the same thing except we're using futures instead of just using coroutines. Let's look at an example on how to use asyncio/coroutines/futures: import asyncio async def slow_operation(): await asyncio.sleep(1) return 'Future is done!' def got_result(future): print(future.result()) # We have result, so let's stop loop.stop() loop = asyncio.get_event_loop() task = loop.create_task(slow_operation()) task.add_done_callback(got_result) # We run forever loop.run_forever() Here, we have used the create_task method on the loop object. ensure_future would schedule the task in the main event loop. This method enables us to schedule a coroutine on a loop we choose. We also see the concept of adding a callback using the add_done_callback method on the task object. A Task is done when the coroutine returns a value, raises an exception or gets cancelled. There are methods to check these incidents. I have written some blog posts on these topics which might help: http://masnun.com/2015/11/13/python-generators-coroutines-native-coroutines-and-async-await.html http://masnun.com/2015/11/20/python-asyncio-future-task-and-the-event-loop.html http://masnun.com/2015/12/07/python-3-using-blocking-functions-or-codes-with-asyncio.html Of course, you can find more details on the official manual: https://docs.python.org/3/library/asyncio.html
Most pythonic way to interleave two strings
What's the most pythonic way to mesh two strings together? For example: Input: u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' l = 'abcdefghijklmnopqrstuvwxyz' Output: 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
For me, the most pythonic* way is the following which pretty much does the same thing but uses the + operator for concatenating the individual characters in each string: res = "".join(i + j for i, j in zip(u, l)) print(res) # 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz' It is also faster than using two join() calls: In [5]: l1 = 'A' * 1000000; l2 = 'a' * 1000000 In [6]: %timeit "".join("".join(item) for item in zip(l1, l2)) 1 loops, best of 3: 442 ms per loop In [7]: %timeit "".join(i + j for i, j in zip(l1, l2)) 1 loops, best of 3: 360 ms per loop Faster approaches exist, but they often obfuscate the code. Note: If the two input strings are not the same length then the longer one will be truncated as zip stops iterating at the end of the shorter string. In this case instead of zip one should use zip_longest (izip_longest in Python 2) from the itertools module to ensure that both strings are fully exhausted. *To take a quote from the Zen of Python: Readability counts. Pythonic = readability for me; i + j is just visually parsed more easily, at least for my eyes.
Python: Splat/unpack operator * in python cannot be used in an expression?
Does anybody know the reasoning as to why the unary (*) operator cannot be used in an expression involving iterators/lists/tuples? Why is it only limited to function unpacking? or am I wrong in thinking that? For example: >>> [1,2,3, *[4,5,6]] File "<stdin>", line 1 [1,2,3, *[4,5,6]] ^ SyntaxError: invalid syntax Why doesn't the * operator: [1, 2, 3, *[4, 5, 6]] give [1, 2, 3, 4, 5, 6] whereas when the * operator is used with a function call it does expand: f(*[4, 5, 6]) is equivalent to f(4, 5, 6) There is a similarity between the + and the * when using lists but not when extending a list with another type. For example: # This works gen = (x for x in range(10)) def hello(*args): print args hello(*gen) # but this does not work [] + gen TypeError: can only concatenate list (not "generator") to list
Not allowing unpacking in Python 2.x has noted and fixed in Python 3.5 which now has this feature as described in PEP 448: Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) on Windows (64 bits). >>> [1, 2, 3, *[4, 5, 6]] [1, 2, 3, 4, 5, 6] Here are some explanations for the rationale behind this change.
matplotlib taking time when being imported
I just upgraded to the latest stable release of matplotlib (1.5.1) and everytime I import matplotlib I get this message: /usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment. warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.') ... which always stalls for a few seconds. Is this the expected behaviour? Was it the same also before, but just without the printed message?
As tom suggested in the comment above, deleting the files: fontList.cache, fontList.py3k.cache and tex.cache solve the problem. In my case the files were under ~/.matplotlib.
Anaconda Python installation error
I get the following error during Python 2.7 64-bit windows installation. I previously installed python 3.5 64-bit and it worked fine. But during python 2.7 installation i get this error: Traceback (most recent call last): File "C:\Anaconda2\Lib\_nsis.py", line 164, in <module> main() File "C:\Anaconda2\Lib\_nsis.py", line 150, in main mk_menus(remove=False) File "C:\Anaconda2\Lib\_nsis.py", line 94, in mk_menus err("Traceback:\n%s\n" % traceback.format_exc(20)) IOError: [Errno 9] Bad file descriptor Kindly help me out.
I had the same problem today. I did the following to get this fixed: First, open a DOS prompt and admin rights. Then, go to your Anaconda2\Scripts folder. Then, type in: conda update conda and allow all updates. One of the updates should be menuinst. Then, change to the Anaconda2\Lib directory, and type in the following command: ..\python _nsis.py mkmenus Wait for this to complete, then check your Start menu for the new shortcuts. Steve
Updating a sliced list
I thought I understood Python slicing operations, but when I tried to update a sliced list, I got confused: >>> foo = [1, 2, 3, 4] >>> foo[:1] = ['one'] # OK, foo updated >>> foo ['one', 2, 3, 4] >>> foo[:][1] = 'two' # why foo not updated? >>> foo ['one', 2, 3, 4] >>> foo[:][2:] = ['three', 'four'] # Again, foo not updated >>> foo ['one', 2, 3, 4] Why isn't foo updated after foo[:][1] = 'two'? Update: Maybe I didn't explain my questions clearly. I know when slicing, a new list is created. My doubt is why a slicing assignment updates the list (e.g. foo[:1] = ['one']), but if there are two levels of slicing, it doesn't update the original list (e.g. foo[:][2:] = ['three', 'four']).
foo[:] is a copy of foo. You mutated the copy.
Python: optimal search for substring in list of strings
I have a particular problem where I want to search for many substrings in a list of many strings. The following is the gist of what I am trying to do: listStrings = [ACDE, CDDE, BPLL, ... ] listSubstrings = [ACD, BPI, KLJ, ...] The above entries are just examples. len(listStrings) is ~ 60,000, len(listSubstrings) is ~50,000-300,000, and len(listStrings[i]) is anywhere from 10 to 30,000. My current Python attempt is: for i in listSubstrings: for j in listStrings: if i in j: w.write(i+j) Or something along these lines. While this works for my task, it's horribly slow, using one core and taking on the order of 40 minutes to complete the task. Is there a way to speed this up? I don't believe that I can make a dict out of listStrings:listSubstrings because there is the possibility of duplicate entries which need to be stored on both ends (although I may try this if I can find a way to append a unique tag to each one, since dicts are so much faster). Similarly, I don't think I can pre-compute possible substrings. I don't even know if searching dict keys is faster than searching a list (since dict.get() is going to give the specific input and not look for sub-inputs). Is searching lists in memory just that slow relatively speaking?
For the sort of thing you're trying (searching for a fixed set of a whole bunch of strings in a whole bunch of other strings), parallelizing and minor tweaks won't help much. You need algorithmic improvements. For a start, I'd suggest using the Aho-Corasick string matching algorithm. Basically, in exchange for some precompute work to build a matcher object from your set of fixed strings, you can scan another string for all of those fixed strings at once, in a single pass. So instead of scanning 60K strings 50K+ times each (three BILLION scans?!?), you can scan them each once with only slightly higher cost than a normal single scan, and get all the hits. Best part is, you're not writing it yourself. PyPI (the Python package index) already has the pyahocorasick package written for you. So try it out. Example of use: import ahocorasick listStrings = [ACDE, CDDE, BPLL, ...] listSubstrings = [ACD, BPI, KLJ, ...] auto = ahocorasick.Automaton() for substr in listSubstrings: auto.add_word(substr, substr) auto.make_automaton() ... for astr in listStrings: for end_ind, found in auto.iter(astr): w.write(found+astr) This will write multiple times if a substring ("needle") is found in string being searched ("haystack") more than once. You could change the loop to make it only write on the first hit for a given needle in a given haystack by using a set to dedup: for astr in listStrings: seen = set() for end_ind, found in auto.iter(astr): if found not in seen: seen.add(found) w.write(found+astr) You can further tweak this to output the needles for a given haystack in the same order they appeared in listSubstrings (and uniquifying while you're at it) by storing the index of the words as or with their values so you can sort hits (presumably small numbers, so sort overhead is trivial): from future_builtins import map # Only on Py2, for more efficient generator based map from itertools import groupby from operator import itemgetter auto = ahocorasick.Automaton() for i, substr in enumerate(listSubstrings): # Store index and substr so we can recover original ordering auto.add_word(substr, (i, substr)) auto.make_automaton() ... for astr in listStrings: # Gets all hits, sorting by the index in listSubstrings, so we output hits # in the same order we theoretically searched for them allfound = sorted(map(itemgetter(1), auto.iter(astr))) # Using groupby dedups already sorted inputs cheaply; the map throws away # the index since we don't need it for found, _ in groupby(map(itemgetter(1), allfound)): w.write(found+astr) For performance comparisons, I used a variant on mgc's answer that is more likely to contain matches, as well as enlarging the haystacks. First, setup code: >>> from random import choice, randint >>> from string import ascii_uppercase as uppercase >>> # 5000 haystacks, each 1000-5000 characters long >>> listStrings = [''.join([choice(uppercase) for i in range(randint(1000, 5000))]) for j in range(5000)] >>> # ~1000 needles (might be slightly less for dups), each 3-12 characters long >>> listSubstrings = tuple({''.join([choice(uppercase) for i in range(randint(3, 12))]) for j in range(1000)}) >>> auto = ahocorasick.Automaton() >>> for needle in listSubstrings: ... auto.add_word(needle, needle) ... >>> auto.make_automaton() And now to actually test it (using ipython %timeit magic for microbenchmarks): >>> sum(needle in haystack for haystack in listStrings for needle in listSubstrings) 80279 # Will differ depending on random seed >>> sum(len(set(map(itemgetter(1), auto.iter(haystack)))) for haystack in listStrings) 80279 # Same behavior after uniquifying results >>> %timeit -r5 sum(needle in haystack for haystack in listStrings for needle in listSubstrings) 1 loops, best of 5: 9.79 s per loop >>> %timeit -r5 sum(len(set(map(itemgetter(1), auto.iter(haystack)))) for haystack in listStrings) 1 loops, best of 5: 460 ms per loop So for checking for ~1000 smallish strings in each of 5000 moderate size strings, pyahocorasick beats individual membership tests by a factor of ~21x on my machine. It scales well as the size of listSubstrings increases too; when I initialized it the same way, but with 10,000 smallish strings instead of 1000, the total time required increased from ~460 ms to ~852 ms, a 1.85x time multiplier to perform 10x as many logical searches. For the record, the time to build the automatons is trivial in this sort of context. You pay it once up front not once per haystack, and testing shows the ~1000 string automaton took ~1.4 ms to build and occupied ~277 KB of memory (above and beyond the strings themselves); the ~10000 string automaton took ~21 ms to build, and occupied ~2.45 MB of memory.
AttributeError: module 'html.parser' has no attribute 'HTMLParseError'
This is the hints,how can I resolve it? I use Python 3.5.1 created a virtual envirement by virtualenv The source code works well on my friend's computer machine Error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "A:\Python3.5\lib\site-packages\django\core\management\__init__.py", line 385, in execute_from_command_line utility.execute() File "A:\Python3.5\lib\site-packages\django\core\management\__init__.py", line 354, in execute django.setup() File "A:\Python3.5\lib\site-packages\django\__init__.py", line 18, in setup from django.utils.log import configure_logging File "A:\Python3.5\lib\site-packages\django\utils\log.py", line 13, in <module> from django.views.debug import ExceptionReporter, get_exception_reporter_filter File "A:\Python3.5\lib\site-packages\django\views\debug.py", line 10, in <module> from django.http import (HttpResponse, HttpResponseServerError, File "A:\Python3.5\lib\site-packages\django\http\__init__.py", line 4, in <module> from django.http.response import ( File "A:\Python3.5\lib\site-packages\django\http\response.py", line 13, in <module> from django.core.serializers.json import DjangoJSONEncoder File "A:\Python3.5\lib\site-packages\django\core\serializers\__init__.py", line 23, in <module> from django.core.serializers.base import SerializerDoesNotExist File "A:\Python3.5\lib\site-packages\django\core\serializers\base.py", line 6, in <module> from django.db import models File "A:\Python3.5\lib\site-packages\django\db\models\__init__.py", line 6, in <module> from django.db.models.query import Q, QuerySet, Prefetch # NOQA File "A:\Python3.5\lib\site-packages\django\db\models\query.py", line 13, in <module> from django.db.models.fields import AutoField, Empty File "A:\Python3.5\lib\site-packages\django\db\models\fields\__init__.py", line 18, in <module> from django import forms File "A:\Python3.5\lib\site-packages\django\forms\__init__.py", line 6, in <module> from django.forms.fields import * # NOQA File "A:\Python3.5\lib\site-packages\django\forms\fields.py", line 18, in <module> from django.forms.utils import from_current_timezone, to_current_timezone File "A:\Python3.5\lib\site-packages\django\forms\utils.py", line 15, in <module> from django.utils.html import format_html, format_html_join, escape File "A:\Python3.5\lib\site-packages\django\utils\html.py", line 16, in <module> from .html_parser import HTMLParser, HTMLParseError File "A:\Python3.5\lib\site-packages\django\utils\html_parser.py", line 12, in <module> HTMLParseError = _html_parser.HTMLParseError AttributeError: module 'html.parser' has no attribute 'HTMLParseError'
As you can read here this error is raised... because HTMLParseError is deprecated from Python 3.3 onwards and removed in Python 3.5. What you can do is downgrade your Python version or upgrade your Django version.
Comprehensions in Python to sample tuples from a list
I am trying to get the list of three-element tuples from the list [-4, -2, 1, 2, 5, 0] using comprehensions, and checking whether they fulfil the condition sum([] == 0). The following code works. However, there is no question that there ought to be an easier, much more elegant way of expressing these comprehensions: [ (i, j, k) for i in [-4, -2, 1, 2, 5, 0] for j in [-4, -2, 1, 2, 5, 0] for k in [-4, -2, 1, 2, 5, 0] if sum([i, j, k]) == 0 ] Output: [(-4, 2, 2), (-2, 1, 1), (-2, 2, 0), (-2, 0, 2), (1, -2, 1), (1, 1, -2), (2, -4, 2), (2, -2, 0), (2, 2, -4), (2, 0, -2), (0, -2, 2), (0, 2, -2), (0, 0, 0)] The question is searching for an expression like (i, j, k) for i, j, k in [-4, -2, 1, 2, 5, 0].
You can use itertools.product to hide the nested loops in your list comprehension. Use the repeat parameter to set the number of loops over the list (i.e. the number of elements in the tuple): >>> import itertools >>> lst = [-4, -2, 1, 2, 5, 0] >>> [x for x in itertools.product(lst, repeat=3) if sum(x) == 0] [(-4, 2, 2), (-2, 1, 1), (-2, 2, 0), (-2, 0, 2), (1, -2, 1), (1, 1, -2), (2, -4, 2), (2, -2, 0), (2, 2, -4), (2, 0, -2), (0, -2, 2), (0, 2, -2), (0, 0, 0)]
What does "list comprehension" in Python mean? How does it work and how can I use it?
I have the following code: [x**2 for x in range(10)] When I run it in the Python Shell, it returns: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] I've searched and it seems this is called a list comprehension, but how does it work?
From the documentation: List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. About your question, the list comprehension does the same thing as the following "plain" Python code: >>> l = [] >>> for x in range(10): ... l.append(x**2) >>> l [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] How do you write it in one line? Hmm...we can...probably...use map() with lambda: >>> list(map(lambda x: x**2, range(10))) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] But isn't it clearer and simpler to just use a list comprehension? >>> [x**2 for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Basically, we can do anything with x. Not only x**2. For example, run a method of x: >>> [x.strip() for x in ('foo\n', 'bar\n', 'baz\n')] ['foo', 'bar', 'baz'] Or use x as another function's argument: >>> [int(x) for x in ('1', '2', '3')] [1, 2, 3] We can also, for example, use x as the key of a dict object. Let's see: >>> d = {'foo': '10', 'bar': '20', 'baz': '30'} >>> [d[x] for x in ['foo', 'baz']] ['10', '30'] How about a combination? >>> d = {'foo': '10', 'bar': '20', 'baz': '30'} >>> [int(d[x].rstrip('0')) for x in ['foo', 'baz']] [1, 3] And so on. You can also use if or if...else in a list comprehension. For example, you only want odd numbers in range(10). You can do: >>> l = [] >>> for x in range(10): ... if x%2: ... l.append(x) >>> l [1, 3, 5, 7, 9] Ah that's too complex. What about the following version? >>> [x for x in range(10) if x%2] [1, 3, 5, 7, 9] To use an if...else ternary expression, you need put the if ... else ... after x, not after range(10): >>> [i if i%2 != 0 else None for i in range(10)] [None, 1, None, 3, None, 5, None, 7, None, 9] Have you heard about nested list comprehension? You can put two or more fors in one list comprehension. For example: >>> [i for x in [[1, 2, 3], [4, 5, 6]] for i in x] [1, 2, 3, 4, 5, 6] >>> [j for x in [[[1, 2], [3]], [[4, 5], [6]]] for i in x for j in i] [1, 2, 3, 4, 5, 6] Let's talk about the first part, for x in [[1, 2, 3], [4, 5, 6]] which gives [1, 2, 3] and [4, 5, 6]. Then, for i in x gives 1, 2, 3 and 4, 5, 6. Warning: You always need put for x in [[1, 2, 3], [4, 5, 6]] before for i in x: >>> [j for j in x for x in [[1, 2, 3], [4, 5, 6]]] Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'x' is not defined We also have set comprehensions, dict comprehensions, and generator expressions. set comprehensions and list comprehensions are basically the same, but the former returns a set instead of a list: >>> {x for x in [1, 1, 2, 3, 3, 1]} {1, 2, 3} It's the same as: >>> set([i for i in [1, 1, 2, 3, 3, 1]]) {1, 2, 3} A dict comprehension looks like a set comprehension, but it uses {key: value for key, value in ...} or {i: i for i in ...} instead of {i for i in ...}. For example: >>> {i: i**2 for i in range(5)} {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} And it equals: >>> d = {} >>> for i in range(5): ... d[i] = i**2 >>> d {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} Does (i for i in range(5)) give a tuple? No!, it's a generator expression. Which returns a generator: >>> (i for i in range(5)) <generator object <genexpr> at 0x7f52703fbca8> It's the same as: >>> def gen(): ... for i in range(5): ... yield i >>> gen() <generator object gen at 0x7f5270380db0> And you can use it as a generator: >>> gen = (i for i in range(5)) >>> next(gen) 0 >>> next(gen) 1 >>> list(gen) [2, 3, 4] >>> next(gen) Traceback (most recent call last): File "<input>", line 1, in <module> StopIteration Note: If you use a list comprehension inside a function, you don't need the [] if that function could loop over a generator. For example, sum(): >>> sum(i**2 for i in range(5)) 30 Related (about generators): Understanding Generators in Python.
Enumerating three variables in python list comprehension
I am trying to print all the possible enumerations of a list for three variables. For example if my input is: x = 1 y = 1 z = 1 I want the output to be like: [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 0, 1], [0, 1, 1], [1, 1, 1]] If any of the x,y,z variables are higher than 1, it would enumerate all the integers from 0 to the variable value. For example, if x=3 then 0, 1, 2, or 3 would be possible in the first slot of the 3-element lists. Right now I am creating the list comprehension like this: output = [ [x,y,z] for x,y,z in range(x,y,z)] I think something is wrong with the range function?
You could use the product() function from itertools as follows: from itertools import product answer = list(list(x) for x in product([0, 1], repeat=3)) print(answer) Output [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
Is unsetting a single bit in flags safe with Python variable-length integers?
In my program (written in Python 3.4) I have a variable which contains various flags, so for example: FLAG_ONE = 0b1 FLAG_TWO = 0b10 FLAG_THREE = 0b100 status = FLAG_ONE | FLAG_TWO | FLAG_THREE Setting another flag can easily be done with status |= FLAG_FOUR But what if I explicitly want to clear a flag? I'd do status &= ~FLAG_THREE Is this approach safe? As the size of an integer in Python is not defined, what if status and FLAG_THREE differ in size? (status needs to be a bit field because I need this value for a hardware protocol.)
You should be safe using that approach, yes. ~ in Python is simply implemented as -(x+1) (cf. the CPython source) and negative numbers are treated as if they have any required number of 1s padding the start. From the Python Wiki: Of course, Python doesn't use 8-bit numbers. It USED to use however many bits were native to your machine, but since that was non-portable, it has recently switched to using an INFINITE number of bits. Thus the number -5 is treated by bitwise operators as if it were written "...1111111111111111111011". In other words, with bitwise-and & you're guaranteed that those 1s will pad the length of ~FLAG (a negative integer) to the length of status. For example: 100000010000 # status & ~10000 # ~FLAG is treated as 100000010000 & 111111101111 = 100000000000 # new status This behaviour is described in a comment in the source here.
What causes the '' in ['h', 'e', 'l', 'l', 'o', ''] when you do re.findall('[\w]?', 'hello')
What causes the '' in ['h', 'e', 'l', 'l', 'o', ''] when you do re.findall('[\w]?', 'hello'). I thought the result would be ['h', 'e', 'l', 'l', 'o'], without the last empty string.
The question mark in your regex ('[\w]?') is responsible for the empty string being one of the returned results. A question mark is a quantifier meaning "zero-or-one matches." You are asking for all occurrences of either zero-or-one "word characters". The letters satisfy the "-or-one word characters" match. The empty string satisfies the “zero word characters” match condition. Change your regex to '\w' (remove the question mark and superfluous character class brackets) and the output will be as you expect.
What is the proper way to determine if an object is a bytes-like object in Python?
I have code that expects str but will handle the case of being passed bytes in the following way: if isinstance(data, bytes): data = data.decode() Unfortunately, this does not work in the case of bytearray. Is there a more generic way to test whether an object is either bytes or bytearray, or should I just check for both? Is hasattr('decode') as bad as I feel it would be?
There are a few approaches you could use here. Duck typing Since Python is duck typed, you could simply do as follows (which seems to be the way usually suggested): try: data = data.decode() except AttributeError: pass You could use hasattr as you describe, however, and it'd probably be fine. This is, of course, assuming the .decode() method for the given object returns a string, and has no nasty side effects. I personally recommend either the exception or hasattr method, but whatever you use is up to you. Use str() This approach is uncommon, but is possible: data = str(data, "utf-8") Other encodings are permissible, just like with the buffer protocol's .decode(). You can also pass a third parameter to specify error handling. Single-dispatch generic functions (Python 3.4+) Python 3.4 and above include a nifty feature called single-dispatch generic functions, via functools.singledispatch. This is a bit more verbose, but it's also more explicit: def func(data): # This is the generic implementation data = data.decode() ... @func.register(str) def _(data): # data will already be a string ... You could also make special handlers for bytearray and bytes objects if you so chose. Beware: single-dispatch functions only work on the first argument! This is an intentional feature, see PEP 433.
What does tf.nn.embedding_lookup function do?
tf.nn.embedding_lookup(params, ids, partition_strategy='mod', name=None) I cannot understand the duty of this function. Is it like a lookup table? which means return the param corresponding for each id (in ids)? For instance, in the skip-gram model if we use tf.nn.embedding_lookup(embeddings, train_inputs), then for each train_input it finds the correspond embedding?
embedding_lookup function retrieves rows of the params tensor. The behavior is similar to using indexing with arrays in numpy. E.g. matrix = np.random.random([1024, 64]) # 64-dimensional embeddings ids = np.array([0, 5, 17, 33]) print matrix[ids] # prints a matrix of shape [4, 64] params argument can be also a list of tensors in which case the ids will be distributed among the tensors. E.g. given a list of 3 [2, 64] tensors the default behavior is that they will represent ids: [0, 3], [1, 4], [2, 5]. partition_strategy controls the way how the ids are distributed among the list. The partitioning is useful for larger scale problems when the matrix might be too large to keep in one piece.
Seeking Elegant Python Dice Iteration
Is there an elegant way to iterate through possible dice rolls with up to five dice? I want to replace this hacky Python: self.rolls[0] = [str(a) for a in range(1,7)] self.rolls[1] = [''.join([str(a), str(b)]) for a in range(1, 7) for b in range(1, 7) if a <= b] self.rolls[2] = [''.join([str(a), str(b), str(c)]) for a in range(1, 7) for b in range(1, 7) for c in range(1, 7) if a <= b <= c] self.rolls[3] = [''.join([str(a), str(b), str(c), str(d)]) for a in range(1, 7) for b in range(1, 7) for c in range(1, 7) for d in range(1, 7) if a <= b <= c <= d] self.rolls[4] = [''.join([str(a), str(b), str(c), str(d), str(e)]) for a in range(1, 7) for b in range(1, 7) for c in range(1, 7) for d in range(1, 7) for e in range(1, 7) if a <= b <= c <= d <= e]
You can use itertools' combinations_with_replacement. For example with 3 4-sided dice (just because the output isn't too large): >>> from itertools import combinations_with_replacement >>> dice = 3 >>> faces = 4 >>> list(combinations_with_replacement(range(1, faces+1), dice)) [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 3, 3), (1, 3, 4), (1, 4, 4), (2, 2, 2), (2, 2, 3), (2, 2, 4), (2, 3, 3), (2, 3, 4), (2, 4, 4), (3, 3, 3), (3, 3, 4), (3, 4, 4), (4, 4, 4)]
Dump data from malformed SQLite in Python
I have a malformed database. When I try to get records from any of two tables, it throws an exception: DatabaseError: database disk image is malformed I know that through commandline I can do this: sqlite3 ".dump" base.db | sqlite3 new.db Can I do something like this from within Python?
As far as i know you cannot do that (alas, i might be mistaken), because the sqlite3 module for python is very limited. Only workaround i can think of involves calling the os command shell (e.g. terminal, cmd, ...) (more info) via pythons call-command: Combine it with the info from here to do something like this: This is done on an windows xp machine: Unfortunately i can't test it on a unix machine right now - hope it will help you: from subprocess import check_call def sqliterepair(): check_call(["sqlite3", "C:/sqlite-tools/base.db", ".mode insert", ".output C:/sqlite-tools/dump_all.sql", ".dump", ".exit"]) check_call(["sqlite3", "C:/sqlite-tools/new.db", ".read C:/sqlite-tools/dump_all.sql", ".exit"]) return The first argument is calling the sqlite3.exe. Because it is in my system path variable, i don't need to specify the path or the suffix ".exe". The other arguments are chained into the sqlite3-shell. Note that the argument ".exit" is required so the sqlite-shell will exit. Otherwise the check_call() will never complete because the outer cmd-shell or terminal will be in suspended. Of course the dump-file should be removed afterwards... EDIT: Much shorter solution (credit goes to OP (see comment)) os.system("sqlite3 C:/sqlite-tools/base.db .dump | sqlite3 C:/sqlite-tools/target.db") Just tested this: it works. Apparently i was wrong in the comments.
What happens in degenerate case of multiple assignment?
I'm teaching myself algorithms. I needed to swap two items in a list. Python makes all things easy: def swap(A, i, j): A[i], A[j] = A[j], A[i] This works a treat: >>> A = list(range(5)) >>> A [0, 1, 2, 3, 4] >>> swap(A, 0, 1) >>> A [1, 0, 2, 3, 4] Note the function is resilient to the degenerate case i = j. As you'd expect, it simply leaves the list unchanged: >>> A = list(range(5)) >>> swap(A, 0, 0) >>> A [0, 1, 2, 3, 4] Later I wanted to permute three items in a list. I wrote a function to permute them in a 3-cycle: def cycle(A, i, j, k): A[i], A[j], A[k] = A[j], A[k], A[i] This worked well: >>> A = list("tap") >>> A ['t', 'a', 'p'] >>> cycle(A, 0, 1, 2) >>> A ['a', 'p', 't'] However I (eventually) discovered it goes wrong in degenerate cases. I assumed a degenerate 3-cycle would be a swap. So it is when i = j, cycle(i, i, k) ≡ swap(i, k): >>> A = list(range(5)) >>> cycle(A, 0, 0, 1) >>> A [1, 0, 2, 3, 4] But when i = k something else happens: >>> A = list(range(5)) >>> sum(A) 10 >>> cycle(A, 1, 0, 1) >>> A [1, 1, 2, 3, 4] >>> sum(A) 11 What's going on? sum should be invariant under any permutation! Why does this case i = k degenerate differently? How can I achieve what I want? That is a 3-cycle function that degenerates to a swap if only 2 indices are distinct cycle(i, i, j) ≡ cycle(i, j, i) ≡ cycle(i, j, j) ≡ swap(i, j)
cycle is doing exactly what you ask it to: assigning to the left hand values the right hand values. def cycle(A, i, j, k): A[i], A[j], A[k] = A[j], A[k], A[i] is functionally equivalent to def cycle(A, i, j, k): new_values = A[j], A[k], A[i] A[i], A[j], A[k] = new_values So when you do cycle(A, 1, 0, 1) what you are saying is that you want A[1] = previous_A[0] A[0] = previous_A[1] A[1] = previous_A[1] If you want cycle to work sequentially then you must write it sequentially, otherwise python evaluates the right hand and then expands that to the arguments on the left hand.
When and why socket.send() returns 0 in python?
The python3 socket programming howto presents this code snippet class MySocket: """demonstration class only - coded for clarity, not efficiency """ def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self, host, port): self.sock.connect((host, port)) def mysend(self, msg): totalsent = 0 while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") totalsent = totalsent + sent def myreceive(self): chunks = [] bytes_recd = 0 while bytes_recd < MSGLEN: chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048)) if chunk == b'': raise RuntimeError("socket connection broken") chunks.append(chunk) bytes_recd = bytes_recd + len(chunk) return b''.join(chunks) where the send loop is interrupted if the socket send method returns 0. The logic behind this snippet is that when the send method returns '0 bytes sent', the sending side of a socket connection should give up its efforts to send data. This is for sure true for the recv method, where zero bytes read for a socket in blocking mode should be interpreted as EOF, and therefore the reading side should give up. However I cannot understand under which situations the send method could return zero. My understanding of python sockets is that send returns immediately due to buffering at the OS level. If the buffer is full send will block, or if the connections is closed at the remote side, an exception is raised. Finally suppose send returns zero without raising an exception: does this really indicate that all future send calls will return zero? I've done some testing (although using only socket connected to ::1 on OS X) and was not able to find a situation in which send returns 0. Edit The HOWTO states: But if you plan to reuse your socket for further transfers, you need to realize that there is no EOT on a socket. I repeat: if a socket send or recv returns after handling 0 bytes, the connection has been broken. If the connection has not been broken, you may wait on a recv forever, because the socket will not tell you that there’s nothing more to read (for now). It is pretty easy to find a situation in which recv returns 0: when the remote (sending) side calls socket.shutdown(SHUT_WR), further recv on the receiving side will return 0 and not raise any exception. I'm looking for a concrete example where you can show that receiving 0 zero from send indicates a broken connection (which will continue to return 0 on send.)
Upon seeing the question I was somehow stunned, because a send C call can return 0 bytes and the connection is of course still alive (the socket cannot simply send more bytes at that given moment in time) https://github.com/python/cpython/blob/master/Modules/socketmodule.c I decided to "use the source" and unless I am very wrong (which can always be and often is) this is a bug in the HOWTO. Chain: send is an alias for sock_send sock_send calls in turn sock_call sock_call calls in turn sock_call_ex sock_call calls in turn sock_send_impl (which has been passed down the chain starting with sock_send) Unwinding: sock_send_impl returns true or false (1 or 0) with return (ctx->result >= 0) sock_call_ex returns -1 if sock_send_impl returns false 0 if sock_send_impl returns true sock_call returns this value transparently. sock_send returns NULL for a -1 (because an error has been set and an exception will be raised) returns ctx->result for 0from sock_call And ctx->result is the number of bytes written by the C call send in sock_send_impl. The chain shows that if 0 bytes have been sent, there is no error and this actually is a potential real life socket situation. If my logic is wrong, someone please let me know.
How can I convert an absolutely massive number to a string in a reasonable amount of time?
This is quite an odd problem I know, but I'm trying to get a copy of the current largest prime number in a file. Getting the number in integer form is fairly easy. I just run this. prime = 2**74207281 - 1 It takes about half a second and it works just fine. Operations are fairly quick as well. Dividing it by 10 (without decimals) to shift the digits is quick. However, str(prime) is taking a very long time. I reimplemented str like this, and found it was processing about a hundred or so digits per second. while prime > 0: strprime += str(prime%10) prime //= 10 Is there a way to do this more efficiently? I'm doing this in Python. Should I even try this with Python, or is there a better tool for this?
Repeated string concatenation is notoriously inefficient since Python strings are immutable. I would go for strprime = str(prime) In my benchmarks, this is consistently the fastest solution. Here's my little benchmark program: import decimal def f1(x): ''' Definition by OP ''' strprime = "" while x > 0: strprime += str(x%10) x //= 10 return strprime def digits(x): while x > 0: yield x % 10 x //= 10 def f2(x): ''' Using string.join() to avoid repeated string concatenation ''' return "".join((chr(48 + d) for d in digits(x))) def f3(x): ''' Plain str() ''' return str(x) def f4(x): ''' Using Decimal class''' return decimal.Decimal(x).to_eng_string() x = 2**100 if __name__ == '__main__': import timeit for i in range(1,5): funcName = "f" + str(i) print(funcName+ ": " + str(timeit.timeit(funcName + "(x)", setup="from __main__ import " + funcName + ", x"))) For me, this prints (using Python 2.7.10): f1: 15.3430171013 f2: 20.8928260803 f3: 0.310356140137 f4: 2.80087995529
gitpython list changed files since last commit
Folks, I need to have the python script read in the files that have changed since the last git commit. Using GitPython, how would I get the same output as running from cli: $ git diff --name-only HEAD~1 HEAD I can do something like the following, however, I only need the file names: hcommit = repo.head.commit for diff_added in hcommit.diff('HEAD~1').iter_change_type('A'): print(diff_added) Thanks!
You need to pass the name_only keyword argument - it would automatically be used as --name-only command-line option when a git command would be issued. The following is the equivalent of git diff --name-only HEAD~1..HEAD: diff = repo.git.diff('HEAD~1..HEAD', name_only=True) print(diff)
static openCL class not properly released in python module using boost.python
EDIT: Ok, all the edits made the layout of the question a bit confusing so I will try to rewrite the question (not changing the content, but improving its structure). The issue in short I have an openCL program that works fine, if I compile it as an executable. Now I try to make it callable from Python using boost.python. However, as soon as I exit Python (after importing my module), python crashes. The reason seems to have something to do with statically storing only GPU CommandQueues and their release mechanism when the program terminates MWE and setup Setup IDE used: Visual Studio 2015 OS used: Windows 7 64bit Python version: 3.5 AMD OpenCL APP 3.0 headers cl2.hpp directly from Khronos as suggested here: empty openCL program throws deprecation warning Also I have an Intel CPU with integrated graphics hardware and no other dedicated graphics card I use version 1.60 of the boost library compiled as 64-bit versions The boost dll I use is called: boost_python-vc140-mt-1_60.dll The openCL program without python works fine The python module without openCL works fine MWE #include <vector> #define CL_HPP_ENABLE_EXCEPTIONS #define CL_HPP_TARGET_OPENCL_VERSION 200 #define CL_HPP_MINIMUM_OPENCL_VERSION 200 // I have the same issue for 100 and 110 #include "cl2.hpp" #include <boost/python.hpp> using namespace std; class TestClass { private: std::vector<cl::CommandQueue> queues; TestClass(); public: static const TestClass& getInstance() { static TestClass instance; return instance; } }; TestClass::TestClass() { std::vector<cl::Device> devices; vector<cl::Platform> platforms; cl::Platform::get(&platforms); //remove non 2.0 platforms (as suggested by doqtor) platforms.erase( std::remove_if(platforms.begin(), platforms.end(), [](const cl::Platform& platform) { int v = cl::detail::getPlatformVersion(platform()); short version_major = v >> 16; return !(version_major >= 2); }), platforms.end()); //Get all available GPUs for (const cl::Platform& pl : platforms) { vector<cl::Device> plDevices; try { pl.getDevices(CL_DEVICE_TYPE_GPU, &plDevices); } catch (cl::Error&) { // Doesn't matter. No GPU is available on the current machine for // this platform. Just check afterwards, that you have at least one // device continue; } devices.insert(end(devices), begin(plDevices), end(plDevices)); } cl::Context context(devices[0]); cl::CommandQueue queue(context, devices[0]); queues.push_back(queue); } int main() { TestClass::getInstance(); return 0; } BOOST_PYTHON_MODULE(FrameWork) { TestClass::getInstance(); } Calling program So after compiling the program as a dll I start python and run the following program import FrameWork exit() While the import works without issues, python crashes on exit(). So I click on debug and Visual Studio tells me there was an exception in the following code section (in cl2.hpp): template <> struct ReferenceHandler<cl_command_queue> { static cl_int retain(cl_command_queue queue) { return ::clRetainCommandQueue(queue); } static cl_int release(cl_command_queue queue) // -- HERE -- { return ::clReleaseCommandQueue(queue); } }; If you compile the above code instead as a simple executable, it works without issues. Also the code works if one of the following is true: CL_DEVICE_TYPE_GPU is replaced by CL_DEVICE_TYPE_ALL the line queues.push_back(queue) is removed Question So what could be the reason for this and what are possible solutions? I suspect it has something to do with the fact that my testclass is static, but since it works with the executable I am at a loss what is causing it.
I came across similar problem in the past. clRetain* functions are supported from OpenCL1.2. When getting devices for the first GPU platform (platforms[0].getDevices(...) for CL_DEVICE_TYPE_GPU) in your case it must happen to be a platform pre OpenCL1.2 hence you get a crash. When getting devices of any type (GPU/CPU/...) your first platform changes to be a OpenCL1.2+ and everything is fine. To fix the problem set: #define CL_HPP_MINIMUM_OPENCL_VERSION 110 This will ensure calls to clRetain* aren't made for unsupported platforms (pre OpenCL 1.2) Update: I think there is a bug in cl2.hpp which despite setting minimum OpenCL version to 1.1 it still tries to use clRetain* on pre OpenCL1.2 devices when creating a command queue. Setting minimum OpenCL version to 110 and version filtering works fine for me. Complete working example: #include "stdafx.h" #include <vector> #define CL_HPP_ENABLE_EXCEPTIONS #define CL_HPP_TARGET_OPENCL_VERSION 200 #define CL_HPP_MINIMUM_OPENCL_VERSION 110 #include <CL/cl2.hpp> using namespace std; class TestClass { private: std::vector<cl::CommandQueue> queues; TestClass(); public: static const TestClass& getInstance() { static TestClass instance; return instance; } }; TestClass::TestClass() { std::vector<cl::Device> devices; vector<cl::Platform> platforms; cl::Platform::get(&platforms); size_t x = 0; for (; x < platforms.size(); ++x) { cl::Platform &p = platforms[x]; int v = cl::detail::getPlatformVersion(p()); short version_major = v >> 16; if (version_major >= 2) // OpenCL 2.x break; } if (x == platforms.size()) return; // no OpenCL 2.0 platform available platforms[x].getDevices(CL_DEVICE_TYPE_GPU, &devices); cl::Context context(devices); cl::CommandQueue queue(context, devices[0]); queues.push_back(queue); } int main() { TestClass::getInstance(); return 0; } Update2: So what could be the reason for this and what are possible solutions? I suspect it has something to do with the fact that my testclass is static, but since it works with the executable I am at a loss what is causing it. TestClass static seems to be a reason. Looks like releasing memory is happening in wrong order when run from python. To fix that you may want to add a method which will have to be explicitly called to release opencl objects before python starts releasing memory. static TestClass& getInstance() // <- const removed { static TestClass instance; return instance; } void release() { queues.clear(); } BOOST_PYTHON_MODULE(FrameWork) { TestClass::getInstance(); TestClass::getInstance().release(); }
Robust endless loop for server written in Python
I write a server which handles events and uncaught exceptions during handling the event must not terminate the server. The server is a single non-threaded python process. I want to terminate on these errors types: KeyboardInterrupt MemoryError ... The list of built in exceptions is long: https://docs.python.org/2/library/exceptions.html I don't want to re-invent this exception handling, since I guess it was done several times before. How to proceed? Have a white-list: A list of exceptions which are ok and processing the next event is the right choice Have a black-list: A list of exceptions which indicate that terminating the server is the right choice. Hint: This question is not about running a unix daemon in background. It is not about double fork and not about redirecting stdin/stdout :-)
I would do this in a similar way you're thinking of, using the 'you shall not pass' Gandalf exception handler except Exception to catch all non-system-exiting exceptions while creating a black-listed set of exceptions that should pass and end be re-raised. Using the Gandalf handler will make sure GeneratorExit, SystemExit and KeyboardInterrupt (all system-exiting exceptions) pass and terminate the program if no other handlers are present higher in the call stack. Here is where you can check with type(e) that a __class__ of a caught exception e actually belongs in the set of black-listed exceptions and re-raise it. As a small demonstration: import exceptions # Py2.x only # dictionary holding {exception_name: exception_class} excptDict = vars(exceptions) exceptionNames = ['MemoryError', 'OSError', 'SystemError'] # and others # set containing black-listed exceptions blackSet = {excptDict[exception] for exception in exceptionNames} Now blackSet = {OSError, SystemError, MemoryError} holding the classes of the non-system-exiting exceptions we want to not handle. A try-except block can now look like this: try: # calls that raise exceptions: except Exception as e: if type(e) in blackSet: raise e # re-raise # else just handle it An example which catches all exceptions using BaseException can help illustrate what I mean. (this is done for demonstration purposes only, in order to see how this raising will eventually terminate your program). Do note: I'm not suggesting you use BaseException; I'm using it in order to demonstrate what exception will actually 'pass through' and cause termination (i.e everything that BaseException catches): for i, j in excptDict.iteritems(): if i.startswith('__'): continue # __doc__ and other dunders try: try: raise j except Exception as ex: # print "Handler 'Exception' caught " + str(i) if type(ex) in blackSet: raise ex except BaseException: print "Handler 'BaseException' caught " + str(i) # prints exceptions that would cause the system to exit Handler 'BaseException' caught GeneratorExit Handler 'BaseException' caught OSError Handler 'BaseException' caught SystemExit Handler 'BaseException' caught SystemError Handler 'BaseException' caught KeyboardInterrupt Handler 'BaseException' caught MemoryError Handler 'BaseException' caught BaseException Finally, in order to make this Python 2/3 agnostic, you can try and import exceptions and if that fails (which it does in Python 3), fall-back to importing builtins which contains all Exceptions; we search the dictionary by name so it makes no difference: try: import exceptions excDict = vars(exceptions) except ImportError: import builtins excDict = vars(builtins) I don't know if there's a smarter way to actually do this, another solution might be instead of having a try-except with a signle except, having 2 handlers, one for the black-listed exceptions and the other for the general case: try: # calls that raise exceptions: except tuple(blackSet) as be: # Must go first, of course. raise be except Exception as e: # handle the rest
Softmax function - python
From the Udacity's deep learning class, the softmax of y_i is simply the exponential divided by the sum of exponential of the whole Y vector: Where S(y_i) is the softmax function of y_i and e is the exponentia and j is the no. of columns in the input vector Y. I've tried the following: import numpy as np def softmax(x): """Compute softmax values for each sets of scores in x.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum() scores = [3.0, 1.0, 0.2] print(softmax(scores)) which returns: [ 0.8360188 0.11314284 0.05083836] And the suggested solution was: def softmax(x): """Compute softmax values for each sets of scores in x.""" return np.exp(x) / np.sum(np.exp(x), axis=0) And it outputs the same output as the first implementation that really tax the difference of each column and the max and then divided by the sum. Can someone show mathematically why? Is one correct and the other one wrong? Are the implementation similar in terms of code and time complexity? Which is more efficient?
They're both correct but yours has an unnecessary term. You start with e ^ (x - max(x)) / sum(e^(x - max(x)) By using the fact that a^(b - c) = (a^b)/(a^c) we have = e ^ x / e ^ max(x) * sum(e ^ x / e ^ max(x)) = e ^ x / sum(e ^ x) Which is what the other answer says. You could replace max(x) with any variable and it would cancel out.
Why does range(0) == range(2, 2, 2) equal True in Python 3?
Why do range objects which are initialized with different values compare equal to one another in Python 3 (this doesn't happen in Python 2)? When I execute the following commands in my interpreter: >>> r1 = range(0) >>> r2 = range(2, 2, 2) >>> r1 == r2 True >>> The result is True. Why is this so? Why are two different range objects with different parameter values treated as equal?
The range objects are special: Python will compare range objects as Sequences. What that essentially means is that the comparison doesn't evaluate how they represent a given sequence but rather what they represent. The fact that the start, stop and step parameters are completely different plays no difference here because they all represent an empty list when expanded: For example, the first range object: list(range(0)) # [] and the second range object: list(range(2, 2, 2)) # [] Both represent an empty list and since two empty lists compare equal (True) so will the range objects that represent them. As a result, you can have completely different looking range objects; if they represent the same sequence they will compare equal: range(1, 5, 100) == range(1, 30, 100) Both represent a list with a single element [1] so these two will also compare equal. No, range objects are really special: Do note, though, that even though the comparison doesn't evaluate how they represent a sequence the result of comparing can be achieved using solely the values of start, step along with the len of the range objects; this has very interesting implications with the speed of comparisons: r0 = range(1, 1000000) r1 = range(1, 1000000) l0 = list(r0) l1 = list(r1) Ranges compares super fast: %timeit r0 == r1 The slowest run took 28.82 times longer than the fastest. This could mean that an intermediate result is being cached 10000000 loops, best of 3: 160 ns per loop on the other hand, the lists.. %timeit l0 == l1 10 loops, best of 3: 27.8 ms per loop Yeah.. As @SuperBiasedMan noted, this only applies to the range objects in Python 3. Python 2 range() is a plain ol' function that returns a list while the 2.x xrange object doesn't have the comparing capabilies (and not only these..) that range objects have in Python 3. Look at @ajcr's answer for quotes directly from the source code on Python 3 range objects. It's documented in there what the comparison between two different ranges actually entails: Simple quick operations. The range_equals function is utilized in the range_richcompare function for EQ and NE cases and assigned to the tp_richcompare member for PyRange_Type.
Why is max slower than sort in Python?
I've found that max is slower than the sort function in Python 2 and 3. Python 2 $ python -m timeit -s 'import random;a=range(10000);random.shuffle(a)' 'a.sort();a[-1]' 1000 loops, best of 3: 239 usec per loop $ python -m timeit -s 'import random;a=range(10000);random.shuffle(a)' 'max(a)' 1000 loops, best of 3: 342 usec per loop Python 3 $ python3 -m timeit -s 'import random;a=list(range(10000));random.shuffle(a)' 'a.sort();a[-1]' 1000 loops, best of 3: 252 usec per loop $ python3 -m timeit -s 'import random;a=list(range(10000));random.shuffle(a)' 'max(a)' 1000 loops, best of 3: 371 usec per loop Why is max (O(n)) slower than the sort function (O(nlogn))?
You have to be very careful when using the timeit module in Python. python -m timeit -s 'import random;a=range(10000);random.shuffle(a)' 'a.sort();a[-1]' Here the initialisation code runs once to produce a randomised array a. Then the rest of the code is run several times. The first time it sorts the array, but every other time you are calling the sort method on an already sorted array. Only the fastest time is returned, so you are actually timing how long it takes Python to sort an already sorted array. Part of Python's sort algorithm is to detect when the array is already partly or completely sorted. When completely sorted it simply has to scan once through the array to detect this and then it stops. If instead you tried: python -m timeit -s 'import random;a=range(100000);random.shuffle(a)' 'sorted(a)[-1]' then the sort happens on every timing loop and you can see that the time for sorting an array is indeed much longer than to just find the maximum value. Edit: @skyking's answer explains the part I left unexplained: a.sort() knows it is working on a list so can directly access the elements. max(a) works on any arbitrary iterable so has to use generic iteration.
How do I transform a multi-level list into a list of strings in Python?
I have a list that looks something like this: a = [('A', 'V', 'C'), ('A', 'D', 'D')] And I want to create another list that transforms a into: ['AVC', 'ADD'] How would I go on to do this?
Use str.join() in a list comprehension (works in both Python 2.x and 3.x): >>> a = [('A', 'V', 'C'), ('A', 'D', 'D')] >>> [''.join(x) for x in a] ['AVC', 'ADD']
Python - Plotting velocity and acceleration vectors at certain points
Here, i have a parametric equation. import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D t = np.linspace(0,2*np.pi, 40) # Position Equation def rx(t): return t * np.cos(t) def ry(t): return t * np.sin(t) # Velocity Vectors def vx(t): return np.cos(t) - t*np.sin(t) def vy(t): return np.sin(t) + t*np.cos(t) # Acceleration Vectors def ax(t): return -2*np.sin(t) - t*np.cos(t) def ay(t): return 2*np.cos(t) - t*np.sin(t) fig = plt.figure() ax1 = fig.gca(projection='3d') z = t ax1.plot(rx(z), r(z), z) plt.xlim(-2*np.pi,2*np.pi) plt.ylim(-6,6) ax.legend() So i have this parametric equation that creates this graph. I have defined my velocity and acceleration parametric equations above in my code. What i am wanting to do is to plot the acceleration and velocity vectors in my position graph above at defined points. (Id est, t = pi/2, 3pi/2, 2pi) Something like this: Python/matplotlib : plotting a 3d cube, a sphere and a vector? but i want to do something more straight forward since i have to define each point t into two equations. Is such a thing possible? I can only find vector fields and what not. Something like this. Thank you. Edit Question # t = pi/4 t_val_start_pi4 = np.pi/4 vel_start_pi4 = [rx(t_val_start_pi4), ry(t_val_start_pi4), t_val_start_pi4] vel_end_pi4 = [rx(t_val_start_pi4 ) + vx(t_val_start_pi4 ), ry(t_val_start_pi4 )+vy(t_val_start_pi4 ), t_val_start_pi4 ] vel_vecs_pi4 = (t_val_start_pi4 , vel_end_pi4) vel_arrow_pi4 = Arrow3D(vel_vecs_pi4[0],vel_vecs_pi4[1], vel_vecs_pi4[2], mutation_scale=20, lw=1, arrowstyle="-|>", color="b") axes.add_artist(vel_arrow_pi4) It'll give me an error saying Tuple out of index
I feel like this is close... Even got the colors to match the sample picture :) I'm not too experienced with plotting on polar coordinates, though (mostly confused on the third-dimension t coordinate). Hopefully this will help and you could figure out how to extend it I took what you had, added the Arrow3D class from this answer, and added a simple for-loop over some sample values from t. #draw a vector from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d class Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, zs, *args, **kwargs): FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0],ys[0]),(xs[1],ys[1])) FancyArrowPatch.draw(self, renderer) axes = fig.gca(projection='3d') t_step = 8 for t_pos in range(0, len(t)-1, t_step): t_val_start = t[t_pos] # t_val_end = t[t_pos+1] vel_start = [rx(t_val_start), ry(t_val_start), t_val_start] vel_end = [rx(t_val_start)+vx(t_val_start), ry(t_val_start)+vy(t_val_start), t_val_start] vel_vecs = list(zip(vel_start, vel_end)) vel_arrow = Arrow3D(vel_vecs[0],vel_vecs[1],vel_vecs[2], mutation_scale=20, lw=1, arrowstyle="-|>", color="g") axes.add_artist(vel_arrow) acc_start = [rx(t_val_start), ry(t_val_start), t_val_start] acc_end = [rx(t_val_start)+ax(t_val_start), ry(t_val_start)+ay(t_val_start), t_val_start] acc_vecs = list(zip(acc_start, acc_end)) acc_arrow = Arrow3D(acc_vecs[0],acc_vecs[1],acc_vecs[2], mutation_scale=20, lw=1, arrowstyle="-|>", color="m") axes.add_artist(acc_arrow) axes.plot(rx(t), ry(t), t) plt.xlim(-2*np.pi,2*np.pi) plt.ylim(-6,6)
Difference between a -= b and a = a - b in Python
I have recently applied this solution for averaging every N rows of matrix. Although the solution works in general I had problems when applied to a 7x1 array. I have noticed that the problem is when using the -= operator. To make a small example: import numpy as np a = np.array([1,2,3]) b = np.copy(a) a[1:] -= a[:-1] b[1:] = b[1:] - b[:-1] print a print b which outputs: [1 1 2] [1 1 1] So, in the case of an array a -= b produces a different result than a = a - b. I thought until now that these two ways are exactly the same. What is the difference? How come the method I am mentioning for summing every N rows in a matrix is working e.g. for a 7x4 matrix but not for a 7x1 array?
Mutating arrays while they're being used in computations can lead to unexpected results! In the example in the question, subtraction with -= modifies the second element of a and then immediately uses that modified second element in the operation on the third element of a. Here is what happens with a[1:] -= a[:-1] step by step: a is the array with the data [1, 2, 3]. We have two views onto this data: a[1:] is [2, 3], and a[:-1] is [1, 2]. The inplace subtraction -= begins. The first element of a[:-1], 1, is subtracted from the first element of a[1:]. This has modified a to be [1, 1, 3]. Now we have that a[1:] is a view of the data [1, 3], and a[:-1] is a view of the data [1, 1] (the second element of array a has been changed). a[:-1] is now [1, 1] and NumPy must now subtract its second element which is 1 (not 2 anymore!) from the second element of a[1:]. This makes a[1:] a view of the values [1, 2]. a is now an array with the values [1, 1, 2]. b[1:] = b[1:] - b[:-1] does not have this problem because b[1:] - b[:-1] creates a new array first and then assigns the values in this array to b[1:]. It does not modify b itself during the subtraction, so the views b[1:] and b[:-1] do not change. The general advice is to avoid modifying one view inplace with another if they overlap. This includes the operators -=, *=, etc. and using the out parameter in universal functions (like np.subtract and np.multiply) to write back to one of the arrays.
Performance degradation of matrix multiplication of single vs double precision arrays on multi-core machine
UPDATE Unfortunately, due to my oversight, I had an older version of MKL (11.1) linked against numpy. Newer version of MKL (11.3.1) gives same performance in C and when called from python. What was obscuring things, was even if linking the compiled shared libraries explicitly with the newer MKL, and pointing through LD_* variables to them, and then in python doing import numpy, was somehow making python call old MKL libraries. Only by replacing in python lib folder all libmkl_*.so with newer MKL I was able to match performance in python and C calls. Background / library info. Matrix multiplication was done via sgemm (single-precision) and dgemm (double-precision) Intel's MKL library calls, via numpy.dot function. The actual call of the library functions can be verified with e.g. oprof. Using here 2x18 core CPU E5-2699 v3, hence a total of 36 physical cores. KMP_AFFINITY=scatter. Running on linux. TL;DR 1) Why is numpy.dot, even though it is calling the same MKL library functions, twice slower at best compared to C compiled code? 2) Why via numpy.dot you get performance decreasing with increasing number of cores, whereas the same effect is not observed in C code (calling the same library functions). The problem I've observed that doing matrix multiplication of single/double precision floats in numpy.dot, as well as calling cblas_sgemm/dgemm directly from a compiled C shared library give noticeably worse performance compared to calling same MKL cblas_sgemm/dgemm functions from inside pure C code. import numpy as np import mkl n = 10000 A = np.random.randn(n,n).astype('float32') B = np.random.randn(n,n).astype('float32') C = np.zeros((n,n)).astype('float32') mkl.set_num_threads(3); %time np.dot(A, B, out=C) 11.5 seconds mkl.set_num_threads(6); %time np.dot(A, B, out=C) 6 seconds mkl.set_num_threads(12); %time np.dot(A, B, out=C) 3 seconds mkl.set_num_threads(18); %time np.dot(A, B, out=C) 2.4 seconds mkl.set_num_threads(24); %time np.dot(A, B, out=C) 3.6 seconds mkl.set_num_threads(30); %time np.dot(A, B, out=C) 5 seconds mkl.set_num_threads(36); %time np.dot(A, B, out=C) 5.5 seconds Doing exactly the same as above, but with double precision A, B and C, you get: 3 cores: 20s, 6 cores: 10s, 12 cores: 5s, 18 cores: 4.3s, 24 cores: 3s, 30 cores: 2.8s, 36 cores: 2.8s. The topping up of speed for single precision floating points seem to be associated with cache misses. For 28 core run, here is the output of perf. For single precision: perf stat -e task-clock,cycles,instructions,cache-references,cache-misses ./ptestf.py 631,301,854 cache-misses # 31.478 % of all cache refs And double precision: 93,087,703 cache-misses # 5.164 % of all cache refs C shared library, compiled with /opt/intel/bin/icc -o comp_sgemm_mkl.so -openmp -mkl sgem_lib.c -lm -lirc -O3 -fPIC -shared -std=c99 -vec-report1 -xhost -I/opt/intel/composer/mkl/include #include <stdio.h> #include <stdlib.h> #include "mkl.h" void comp_sgemm_mkl(int m, int n, int k, float *A, float *B, float *C); void comp_sgemm_mkl(int m, int n, int k, float *A, float *B, float *C) { int i, j; float alpha, beta; alpha = 1.0; beta = 0.0; cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, alpha, A, k, B, n, beta, C, n); } Python wrapper function, calling the above compiled library: def comp_sgemm_mkl(A, B, out=None): lib = CDLL(omplib) lib.cblas_sgemm_mkl.argtypes = [c_int, c_int, c_int, np.ctypeslib.ndpointer(dtype=np.float32, ndim=2), np.ctypeslib.ndpointer(dtype=np.float32, ndim=2), np.ctypeslib.ndpointer(dtype=np.float32, ndim=2)] lib.comp_sgemm_mkl.restype = c_void_p m = A.shape[0] n = B.shape[0] k = B.shape[1] if np.isfortran(A): raise ValueError('Fortran array') if m != n: raise ValueError('Wrong matrix dimensions') if out is None: out = np.empty((m,k), np.float32) lib.comp_sgemm_mkl(m, n, k, A, B, out) However, explicit calls from a C-compiled binary calling MKL's cblas_sgemm / cblas_dgemm, with arrays allocated through malloc in C, gives almost 2x better performance compared to the python code, i.e. the numpy.dot call. Also, the effect of performance degradation with increasing number of cores is NOT observed. The best performance was 900 ms for single-precision matrix multiplication and was achieved when using all 36 physical cores via mkl_set_num_cores and running the C code with numactl --interleave=all. Perhaps any fancy tools or advice for profiling/inspecting/understanding this situation further? Any reading material is much appreciated as well. UPDATE Following @Hristo Iliev advice, running numactl --interleave=all ./ipython did not change the timings (within noise), but improves the pure C binary runtimes.
I suspect this is due to unfortunate thread scheduling. I was able to reproduce an effect similar to yours. Python was running at ~2.2 s, while the C version was showing huge variations from 1.4-2.2 s. Applying: KMP_AFFINITY=scatter,granularity=thread This ensures that the 28 threads are always running on the same processor thread. Reduces both runtimes to more stable ~1.24 s for C and ~1.26 s for python. This is on a 28 core dual socket Xeon E5-2680 v3 system. Interestingly, on a very similar 24 core dual socket Haswell system, both python and C perform almost identical even without thread affinity / pinning. Why does python affect the scheduling? Well I assume there is more runtime environment around it. Bottom line is, without pinning your performance results will be non-deterministic. Also you need to consider, that the Intel OpenMP runtime spawns an extra management thread that can confuse the scheduler. There are more choices for pinning, for instance KMP_AFFINITY=compact - but for some reason that is totally messed up on my system. You can add ,verbose to the variable to see how the runtime is pinning your threads. likwid-pin is a useful alternative providing more convenient control. In general single precision should be at least as fast as double precision. Double precision can be slower because: You need more memory/cache bandwidth for double precision. You can build ALUs that have higher througput for single precision, but that usually doesn't apply to CPUs but rather GPUs. I would think that once you get rid of the performance anomaly, this will be reflected in your numbers. When you scale up the number of threads for MKL/*gemm, consider Memory /shared cache bandwidth may become a bottleneck, limiting the scalability Turbo mode will effectively decrease the core frequency when increasing utilization. This applies even when you run at nominal frequency: On haswell processors, AVX instructions will impose a lower "AVX base frequency" - but the processor is allowed to exceed that when less cores are utilized / thermal headroom is available and in general even more for a short time. If you want perfectly neutral results, you would have to use the AVX base frequency, which is 1.9 GHz for you. It is documented here, and explained in one picture. I don't think there is a really simple way to measure how your application is affected by bad scheduling. You can expose this with perf trace -e sched:sched_switch and there is some software to visualize this, but this will come with a high learning curve. And then again - for parallel performance analysis you should have the threads pinned anyway.
Subtraction over a list of sets
Given a list of sets: allsets = [set([1, 2, 4]), set([4, 5, 6]), set([4, 5, 7])] What is a pythonic way to compute the corresponding list of sets of elements having no overlap with other sets? only = [set([1, 2]), set([6]), set([7])] Is there a way to do this with a list comprehension?
To avoid quadratic runtime, you'd want to make an initial pass to figure out which elements appear in more than one set: import itertools import collections element_counts = collections.Counter(itertools.chain.from_iterable(allsets)) Then you can simply make a list of sets retaining all elements that only appear once: nondupes = [{elem for elem in original if element_counts[elem] == 1} for original in allsets] Alternatively, instead of constructing nondupes from element_counts directly, we can make an additional pass to construct a set of all elements that appear in exactly one input. This requires an additional statement, but it allows us to take advantage of the & operator for set intersection to make the list comprehension shorter and more efficient: element_counts = collections.Counter(itertools.chain.from_iterable(allsets)) all_uniques = {elem for elem, count in element_counts.items() if count == 1} # ^ viewitems() in Python 2.7 nondupes = [original & all_uniques for original in allsets] Timing seems to indicate that using an all_uniques set produces a substantial speedup for the overall duplicate-elimination process. It's up to about a 3.5x speedup on Python 3 for heavily-duplicate input sets, though only about a 30% speedup for the overall duplicate-elimination process on Python 2 due to more of the runtime being dominated by constructing the Counter. This speedup is fairly substantial, though not nearly as important as avoiding quadratic runtime by using element_counts in the first place. If you're on Python 2 and this code is speed-critical, you'd want to use an ordinary dict or a collections.defaultdict instead of a Counter. Another way would be to construct a dupes set from element_counts and use original - dupes instead of original & all_uniques in the list comprehension, as suggested by munk. Whether this performs better or worse than using an all_uniques set and & would depend on the degree of duplication in your input and what Python version you're on, but it doesn't seem to make much of a difference either way.
Adding data to Pandas Dataframe from a CSV file causing Value Errors
I am trying to add an int to an existing value in a Pandas DataFrame with >>> df.ix['index 5','Total Dollars'] += 10 I get the error: ValueError: Must have equal len keys and value when setting with an iterable. I think the error comes from the datatype as gotten from: >>> print type(df.ix['index 5','Total Dollars'] int64 <class 'pandas.core.series.Series'> The dataframe is populated via CSV file. I tried loading the database from another CSV file: >>> print type(df.ix['index 5','Total Dollars'] int64 What could be causing this difference in type?
This looks like a bug for some earlier pandas versions, fixed at least with 0.16.2 if not earlier as discussed here and here. With 0.17.1, this works fine: df = pd.DataFrame(data=[5], columns=['Total Dollars'], index=['index 5']) Total Dollars index 5 5 df.ix['index 5', 'Total Dollars'] += 10 Total Dollars index 5 15
Multi-threaded integer matrix multiplication in NumPy/SciPy
Doing something like import numpy as np a = np.random.rand(10**4, 10**4) b = np.dot(a, a) uses multiple cores, and it runs nicely. The elements in a, though, are 64-bit floats (or 32-bit in 32-bit platforms?), and I'd like to multiply 8-bit integer arrays. Trying the following, though: a = np.random.randint(2, size=(n, n)).astype(np.int8) results in the dot product not using multiple cores, and thus running ~1000x slower on my PC. array: np.random.randint(2, size=shape).astype(dtype) dtype shape %time (average) float32 (2000, 2000) 62.5 ms float32 (3000, 3000) 219 ms float32 (4000, 4000) 328 ms float32 (10000, 10000) 4.09 s int8 (2000, 2000) 13 seconds int8 (3000, 3000) 3min 26s int8 (4000, 4000) 12min 20s int8 (10000, 10000) It didn't finish in 6 hours float16 (2000, 2000) 2min 25s float16 (3000, 3000) Not tested float16 (4000, 4000) Not tested float16 (10000, 10000) Not tested I understand NumPy uses BLAS, which doesn't support integers, but if I use the SciPy BLAS wrappers, ie. import scipy.linalg.blas as blas a = np.random.randint(2, size=(n, n)).astype(np.int8) b = blas.sgemm(alpha=1.0, a=a, b=a) the computation is multi-threaded. Now, blas.sgemm runs with exactly the same timing as np.dot for float32's, but for non-floats it converts everything to float32 and outputs floats, which is something np.dot doesn't do. (In addition, b is now in F_CONTIGUOUS order, which is a lesser issue). So, if I want to do integer matrix multiplication, I have to do one of the following: Use NumPy's painfully slow np.dot and be glad I get to keep the 8-bit integers. Use SciPy's sgemm and use up 4x memory. Use Numpy's np.float16 and only use up 2x memory, with the caveat that np.dot is much slower on float16 arrays than on float32 arrays, more so than int8. Find an optimized library for multi-threaded integer matrix multiplication (actually, Mathematica does this, but I'd prefer a Python solution), ideally supporting 1-bit arrays, although 8-bit arrays is also fine... (I'm actually aiming to do multiplication of matrices over the finite field Z/2Z, and I know I can do this with Sage, which is quite Pythonic, but, again, is there something strictly Python?) Can I follow option 4? Does such a library exist? Disclaimer: I'm actually running NumPy + MKL, but I've tried a similar test on vanilly NumPy, with similar results.
Option 5 - Roll a custom solution: Partition the matrix product in a few sub-products and perform these in parallel. This can be relatively easy implemented with standard Python modules. The sub-products are computed with numpy.dot, which releases the global interpreter lock. Thus, it is possible to use threads which are relatively lightweight and can access the arrays from the main thread for memory efficiency. Implementation: import numpy as np from numpy.testing import assert_array_equal import threading from time import time def blockshaped(arr, nrows, ncols): """ Return an array of shape (nrows, ncols, n, m) where n * nrows, m * ncols = arr.shape. This should be a view of the original array. """ h, w = arr.shape n, m = h // nrows, w // ncols return arr.reshape(nrows, n, ncols, m).swapaxes(1, 2) def do_dot(a, b, out): #np.dot(a, b, out) # does not work. maybe because out is not C-contiguous? out[:] = np.dot(a, b) # less efficient because the output is stored in a temporary array? def pardot(a, b, nblocks, mblocks, dot_func=do_dot): """ Return the matrix product a * b. The product is split into nblocks * mblocks partitions that are performed in parallel threads. """ n_jobs = nblocks * mblocks print('running {} jobs in parallel'.format(n_jobs)) out = np.empty((a.shape[0], b.shape[1]), dtype=a.dtype) out_blocks = blockshaped(out, nblocks, mblocks) a_blocks = blockshaped(a, nblocks, 1) b_blocks = blockshaped(b, 1, mblocks) threads = [] for i in range(nblocks): for j in range(mblocks): th = threading.Thread(target=dot_func, args=(a_blocks[i, 0, :, :], b_blocks[0, j, :, :], out_blocks[i, j, :, :])) th.start() threads.append(th) for th in threads: th.join() return out if __name__ == '__main__': a = np.ones((4, 3), dtype=int) b = np.arange(18, dtype=int).reshape(3, 6) assert_array_equal(pardot(a, b, 2, 2), np.dot(a, b)) a = np.random.randn(1500, 1500).astype(int) start = time() pardot(a, a, 2, 4) time_par = time() - start print('pardot: {:.2f} seconds taken'.format(time_par)) start = time() np.dot(a, a) time_dot = time() - start print('np.dot: {:.2f} seconds taken'.format(time_dot)) With this implementation I get a speedup of approximately x4, which is the physical number of cores in my machine: running 8 jobs in parallel pardot: 5.45 seconds taken np.dot: 22.30 seconds taken
NLTK ViterbiParser fails in parsing words that are not in the PCFG rule
import nltk from nltk.parse import ViterbiParser def pcfg_chartparser(grammarfile): f=open(grammarfile) grammar=f.read() f.close() return nltk.PCFG.fromstring(grammar) grammarp = pcfg_chartparser("wsjp.cfg") VP = ViterbiParser(grammarp) print VP for w in sent: for tree in VP.parse(nltk.word_tokenize(w)): print tree When I run the above code, it produces the following output for the sentence, "turn off the lights"- (S (VP (VB turn) (PRT (RP off)) (NP (DT the) (NNS lights)))) (p=2.53851e-14) However, it raises the following error for the sentence, "please turn off the lights"- ValueError: Grammar does not cover some of the input words: u"'please'" I am building a ViterbiParser by supplying it a probabilistic context free grammar. It works well in parsing sentences that have words which are already in the rules of the grammar. It fails to parse sentences in which the Parser has not seen the word in the grammar rules. How to get around this limitation? I am referring to this assignment.
Firstly, try to use (i) namespaces and (ii) unequivocal variable names, e.g.: >>> from nltk import PCFG >>> from nltk.parse import ViterbiParser >>> import urllib.request >>> response = urllib.request.urlopen('https://raw.githubusercontent.com/salmanahmad/6.863/master/Labs/Assignment5/Code/wsjp.cfg') >>> wsjp = response.read().decode('utf8') >>> grammar = PCFG.fromstring(wsjp) >>> parser = ViterbiParser(grammar) >>> list(parser.parse('turn off the lights'.split())) [ProbabilisticTree('S', [ProbabilisticTree('VP', [ProbabilisticTree('VB', ['turn']) (p=0.002082678), ProbabilisticTree('PRT', [ProbabilisticTree('RP', ['off']) (p=0.1089101771)]) (p=0.10768769667270556), ProbabilisticTree('NP', [ProbabilisticTree('DT', ['the']) (p=0.7396712852), ProbabilisticTree('NNS', ['lights']) (p=4.61672e-05)]) (p=4.4236397464693323e-07)]) (p=1.0999324002161311e-13)]) (p=2.5385077255727538e-14)] If we look at the grammar: >>> grammar.check_coverage('please turn off the lights'.split()) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.4/dist-packages/nltk/grammar.py", line 631, in check_coverage "input words: %r." % missing) ValueError: Grammar does not cover some of the input words: "'please'". To resolve the unknown word issues, there're several options: Use wildcard non-terminals nodes to replace the unknown words. Find some way to replace the words that the grammar don't cover from check_coverage() with the wildcard, then parse the sentence with the wildcard this will usually decrease the parser's accuracy unless you have specifically train the PCFG with a grammar that handles unknown words and the wildcard is a superset of the unknown words. Go back to your grammar production file that you have before creating the learning the PCFG with learn_pcfg.py and add all possible words in the terminal productions. Add the unknown words into your pcfg grammar and then renormalize the weights, given either very small weights to the unknown words (you can also try smarter smoothing/interpolation techniques) Since this is a homework question I will not give the answer with the full code. But the hints above should be enough to resolve the problem.
Where should you update Celery settings? On the remote worker or sender?
Where should you update celery settings? On the remote worker or the sender? For example, I have an API using Django and Celery. The API sends remote jobs to my remote workers via a broker (RabbitMQ). The workers are running a python script (not using Django) sometimes these works spawn sub tasks. I've created celery settings on both sides (sender and worker) i.e. they both need the setting BROKER_URL. However, say I want to add the setting CELERY_ACKS_LATE = True, which end do I add this setting to? Each of the remote workers or the sender (API)? Both the API and the remote workers connect to the same Broker, each start celery differently. The API creates a celery instance via Django __init__.py and the workers start celery via supervisor i.e. celery -A tasks worker -l info
the django celery settings affects only workers running on the django server itself. if all your workers are remote workers (the way as i do it), then on the sender side all you need is to put the configuration necessary to submit a task to the task queue. and all the other settings need to be set on the remote workers. and for the tasks, on the sender side, all i need to do is to define the task signature like this: @app.task(name='report_task') def reportTask(self, link): pass then on the worker side, you need to create a new Celery app with the same name and pointing to the same broker; for other celery settings you need to declare them on the remote workers. and implement the tasks logic on the remote workeres (you can have different tasks logic per worker as long as they have the same task name and the function arguments)
Dot notation string manipulation
Is there a way to manipulate a string in Python using the following ways? For any string that is stored in dot notation, for example: s = "classes.students.grades" Is there a way to change the string to the following: "classes.students" Basically, remove everything up to and including the last period. So "restaurants.spanish.food.salty" would become "restaurants.spanish.food". Additionally, is there any way to identify what comes after the last period? The reason I want to do this is I want to use isDigit(). So, if it was classes.students.grades.0 could I grab the 0 somehow, so I could use an if statement with isdigit, and say if the part of the string after the last period (so 0 in this case) is a digit, remove it, otherwise, leave it.
you can use split and join together: s = "classes.students.grades" print '.'.join(s.split('.')[:-1]) You are splitting the string on . - it'll give you a list of strings, after that you are joining the list elements back to string separating them by . [:-1] will pick all the elements from the list but the last one To check what comes after the last .: s.split('.')[-1] Another way is to use rsplit. It works the same way as split but if you provide maxsplit parameter it'll split the string starting from the end: rest, last = s.rsplit('.', 1) 'classes.students' 'grades' You can also use re.sub to substitute the part after the last . with an empty string: re.sub('\.[^.]+$', '', s) And the last part of your question to wrap words in [] i would recommend to use format and list comprehension: ''.join("[{}]".format(e) for e in s.split('.')) It'll give you the desired output: [classes][students][grades]
Why do 3 backslashes equal 4 in a Python string?
Could you tell me why '?\\\?'=='?\\\\?' gives True? That drives me crazy and I can't find a reasonable answer... >>> list('?\\\?') ['?', '\\', '\\', '?'] >>> list('?\\\\?') ['?', '\\', '\\', '?']
Basically, because python is slightly lenient in backslash processing. Quoting from https://docs.python.org/2.0/ref/strings.html : Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (Emphasis in the original) Therefore, in python, it isn't that three backslashes are equal to four, it's that when you follow backslash with a character like ?, the two together come through as two characters, because \? is not a recognized escape sequence.
Unable to run odoo properly in Mac OS X
I have installed Odoo 9 Community version from Git in my Mac OS X El Capitan 10.11.2, all my steps: python --version Python 2.7.10 git clone https://github.com/odoo/odoo.git Checking out files: 100% (20501/20501), done. Installed PostgresApp into Applications and added path in ~/.bash_profile, executed the same. export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/latest/bin Installed pip sudo easy_install pip Finished processing dependencies for pip I have nodejs installed in my system, node -v v5.0.0 npm -v 3.3.9 Installed less and less-plugin-clean-css sudo npm install -g less less-plugin-clean-css I have latest xcode installed, xcode-select --install xcode-select: error: command line tools are already installed, use "Software Update" to install updates I have homebrew installed, /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" It appears Homebrew is already installed. If your intent is to reinstall you should do the following before running this installer again: ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)" The current contents of /usr/local are bin Cellar CODEOFCONDUCT.md CONTRIBUTING.md etc include lib Library LICENSE.txt opt README.md sbin share SUPPORTERS.md var .git .gitignore Installed other libs brew install autoconf automake libtool brew install libxml2 libxslt libevent Installed Python dependencies sudo easy_install -U setuptools Finished processing dependencies for setuptools cd odoo/ sudo pip install --user -r requirements.txt Successfully installed Mako-1.0.1 Pillow-2.7.0 Werkzeug-0.9.6 argparse-1.2.1 lxml-3.4.1 psutil-2.2.0 psycopg2-2.5.4 pyparsing-2.0.1 python-dateutil-1.5 python-ldap-2.4.19 pytz-2013.7 pyusb-1.0.0b2 qrcode-5.1 six-1.4.1 Running odoo export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 ./odoo.py --addons-path=addons --db-filter=mydb It says 2016-02-10 16:51:42,351 3389 INFO ? openerp: OpenERP version 9.0c 2016-02-10 16:51:42,351 3389 INFO ? openerp: addons paths: ['/Users/anshad/Library/Application Support/Odoo/addons/9.0', u'/Users/anshad/odoo/addons', '/Users/anshad/odoo/openerp/addons'] 2016-02-10 16:51:42,352 3389 INFO ? openerp: database: default@default:default 2016-02-10 16:51:42,444 3389 INFO ? openerp.service.server: HTTP service (werkzeug) running on 0.0.0.0:8069 And the browser says 500 500 Internal Server Error and in terminal, conn = _connect(dsn, connection_factory=connection_factory, async=async) OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? Started PostgresApp to solve this issue. Now I got the database setup window appears without CSS as in the below screen-shot. Created database mydbodoo with password admin and navigated to main page http://localhost:8069/web/ It shows a blank page with black header and odoo logo, some error in terminal as well. ImportError: No module named pyPdf ./odoo.py --addons-path=addons --db-filter=mydb 2016-02-10 17:02:12,220 3589 INFO ? openerp: OpenERP version 9.0c 2016-02-10 17:02:12,220 3589 INFO ? openerp: addons paths: ['/Users/anshad/Library/Application Support/Odoo/addons/9.0', u'/Users/anshad/odoo/addons', '/Users/anshad/odoo/openerp/addons'] 2016-02-10 17:02:12,221 3589 INFO ? openerp: database: default@default:default 2016-02-10 17:02:12,314 3589 INFO ? openerp.service.server: HTTP service (werkzeug) running on 0.0.0.0:8069 2016-02-10 17:02:16,855 3589 INFO ? openerp.addons.bus.models.bus: Bus.loop listen imbus on db postgres 2016-02-10 17:02:16,888 3589 INFO ? werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:16] "GET /web/ HTTP/1.1" 500 - 2016-02-10 17:02:16,895 3589 ERROR ? werkzeug: Error on request: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/werkzeug/serving.py", line 177, in run_wsgi execute(self.server.app) File "/Library/Python/2.7/site-packages/werkzeug/serving.py", line 165, in execute application_iter = app(environ, start_response) File "/Users/anshad/odoo/openerp/service/server.py", line 245, in app return self.app(e, s) File "/Users/anshad/odoo/openerp/service/wsgi_server.py", line 184, in application return application_unproxied(environ, start_response) File "/Users/anshad/odoo/openerp/service/wsgi_server.py", line 170, in application_unproxied result = handler(environ, start_response) File "/Users/anshad/odoo/openerp/http.py", line 1487, in __call__ self.load_addons() File "/Users/anshad/odoo/openerp/http.py", line 1508, in load_addons m = __import__('openerp.addons.' + module) File "/Users/anshad/odoo/openerp/modules/module.py", line 61, in load_module mod = imp.load_module('openerp.addons.' + module_part, f, path, descr) File "/Users/anshad/odoo/addons/document/__init__.py", line 4, in <module> import models File "/Users/anshad/odoo/addons/document/models/__init__.py", line 4, in <module> import ir_attachment File "/Users/anshad/odoo/addons/document/models/ir_attachment.py", line 8, in <module> import pyPdf ImportError: No module named pyPdf 2016-02-10 17:02:17,708 3589 INFO mydbodoo openerp.modules.loading: loading 1 modules... 2016-02-10 17:02:17,716 3589 INFO mydbodoo openerp.modules.loading: 1 modules loaded in 0.01s, 0 queries 2016-02-10 17:02:17,719 3589 INFO mydbodoo openerp.modules.loading: loading 4 modules... 2016-02-10 17:02:17,727 3589 INFO mydbodoo openerp.modules.loading: 4 modules loaded in 0.01s, 0 queries 2016-02-10 17:02:17,899 3589 INFO mydbodoo openerp.modules.loading: Modules loaded. 2016-02-10 17:02:17,900 3589 INFO mydbodoo openerp.addons.base.ir.ir_http: Generating routing map 2016-02-10 17:02:18,249 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "GET /web/ HTTP/1.1" 200 - 2016-02-10 17:02:18,308 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "GET /web/content/341-42af255/web.assets_common.0.css HTTP/1.1" 304 - 2016-02-10 17:02:18,350 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "GET /web/static/src/css/full.css HTTP/1.1" 404 - 2016-02-10 17:02:18,367 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "GET /web/content/343-4d5beef/web.assets_backend.0.css HTTP/1.1" 304 - 2016-02-10 17:02:18,411 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "GET /web/content/344-4d5beef/web.assets_backend.js HTTP/1.1" 304 - 2016-02-10 17:02:18,428 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "GET /web/content/342-42af255/web.assets_common.js HTTP/1.1" 304 - 2016-02-10 17:02:18,663 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "GET /web/binary/company_logo HTTP/1.1" 304 - 2016-02-10 17:02:18,838 3589 INFO mydbodoo openerp.service.common: successful login from 'admin' using database 'mydbodoo' 2016-02-10 17:02:18,859 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "POST /web/session/get_session_info HTTP/1.1" 200 - 2016-02-10 17:02:18,893 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "POST /web/proxy/load HTTP/1.1" 200 - 2016-02-10 17:02:18,915 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "POST /web/session/modules HTTP/1.1" 200 - 2016-02-10 17:02:18,945 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "POST /web/dataset/search_read HTTP/1.1" 200 - 2016-02-10 17:02:18,945 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "POST /web/webclient/translations HTTP/1.1" 200 - 2016-02-10 17:02:18,991 3589 INFO mydbodoo werkzeug: 127.0.0.1 - - [10/Feb/2016 17:02:18] "GET /web/webclient/locale/en_US HTTP/1.1" 500 - 2016-02-10 17:02:18,998 3589 ERROR mydbodoo werkzeug: Error on request: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/werkzeug/serving.py", line 177, in run_wsgi execute(self.server.app) File "/Library/Python/2.7/site-packages/werkzeug/serving.py", line 165, in execute application_iter = app(environ, start_response) File "/Users/anshad/odoo/openerp/service/server.py", line 245, in app return self.app(e, s) File "/Users/anshad/odoo/openerp/service/wsgi_server.py", line 184, in application return application_unproxied(environ, start_response) File "/Users/anshad/odoo/openerp/service/wsgi_server.py", line 170, in application_unproxied result = handler(environ, start_response) File "/Users/anshad/odoo/openerp/http.py", line 1488, in __call__ return self.dispatch(environ, start_response) File "/Users/anshad/odoo/openerp/http.py", line 1652, in dispatch result = ir_http._dispatch() File "/Users/anshad/odoo/openerp/addons/base/ir/ir_http.py", line 186, in _dispatch return self._handle_exception(e) File "/Users/anshad/odoo/openerp/addons/base/ir/ir_http.py", line 157, in _handle_exception return request._handle_exception(exception) File "/Users/anshad/odoo/openerp/http.py", line 781, in _handle_exception return super(HttpRequest, self)._handle_exception(exception) File "/Users/anshad/odoo/openerp/addons/base/ir/ir_http.py", line 182, in _dispatch result = request.dispatch() File "/Users/anshad/odoo/openerp/http.py", line 840, in dispatch r = self._call_function(**self.params) File "/Users/anshad/odoo/openerp/http.py", line 316, in _call_function return checked_call(self.db, *args, **kwargs) File "/Users/anshad/odoo/openerp/service/model.py", line 118, in wrapper return f(dbname, *args, **kwargs) File "/Users/anshad/odoo/openerp/http.py", line 309, in checked_call result = self.endpoint(*a, **kw) File "/Users/anshad/odoo/openerp/http.py", line 959, in __call__ return self.method(*args, **kw) File "/Users/anshad/odoo/openerp/http.py", line 509, in response_wrap response = f(*args, **kw) File "/Users/anshad/odoo/addons/web/controllers/main.py", line 505, in load_locale addons_path = http.addons_manifest['web']['addons_path'] KeyError: 'web' Screen-shot:Terminal and file system Screen-shot:Database selection window Screen-shot: Main window Tried sudo pip install pyPdf and it says Requirement already satisfied (use --upgrade to upgrade): pyPdf in /Users/anshad/Library/Python/2.7/lib/python/site-packages
I just went through the setup on two systems, one is Mac OS X El Capitan 10.11.2 and another one is my primary OS - Ubuntu 15.04 (where things went much easier, but maybe it is just because I use Ubuntu on daily basis). Below are installation steps for both systems. Make sure that every command finishes successfully (at least doesn't report any errors). Mac OS X El Capitan 10.11.2 Prerequisites: I already had git and python 2.7.10. 1) Clone odoo repository: git clone https://github.com/odoo/odoo.git 2) Download and install Postgresapp Go to http://postgresapp.com/, download Open it in Finder, drag to Applications, double click Postgres application appears, double click it Sorry if these steps are obvious, it is just for me since I am not a Mac OS user Now add to ~/.bash_profile: export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/latest/bin And just execute the command above it if you already have the open terminal. 3) Install pip sudo easy_install pip 4) Install nodejs Go to https://nodejs.org, Download node v4.3.0 Move to Applications, run and install Open terminal and check that node and npm commands are available 5) Install less and less-plugin-clean-css sudo npm install -g less less-plugin-clean-css Should show output like this: /usr/local/bin/lessc -> /usr/local/lib/node_modules/less/bin/lessc less-plugin-clean-css@1.5.1 /usr/local/lib/node_modules/less-plugin-clean-css └── clean-css@3.4.9 (source-map@0.4.4, commander@2.8.1) less@2.6.0 /usr/local/lib/node_modules/less ├── mime@1.3.4 ├── graceful-fs@3.0.8 ├── image-size@0.3.5 ├── errno@0.1.4 (prr@0.0.0) ├── promise@6.1.0 (asap@1.0.0) ├── source-map@0.4.4 (amdefine@1.0.0) ├── mkdirp@0.5.1 (minimist@0.0.8) └── request@2.69.0 (aws-sign2@0.6.0, forever-agent@0.6.1, tunnel-agent@0.4.2, oauth-sign@0.8.1, is-typedarray@1.0.0, caseless@0.11.0, stringstream@0.0.5, isstream@0.1.2, json-stringify-safe@5.0.1, extend@3.0.0, tough-cookie@2.2.1, node-uuid@1.4.7, qs@6.0.2, combined-stream@1.0.5, mime-types@2.1.9, form-data@1.0.0-rc3, aws4@1.2.1, hawk@3.1.3, bl@1.0.2, har-validator@2.0.6, http-signature@1.1.1) 6) Install binary dependencies I think not all the steps below are really necessary, but I performed them, so include just for the case they actually were needed. Run in the terminal xcode-select --install, when dialog appears - agree to install Go to http://brew.sh and follow instructions to install homebrew Once you have brew, run the following in the terminal: brew install autoconf automake libtool brew install libxml2 libxslt libevent 7) Install python dependencies sudo easy_install -U setuptools pip install --user -r requirements.txt It should show something like this at the end: Successfully installed Babel-1.3 Jinja2-2.7.3 Mako-1.0.1 MarkupSafe-0.23 Pillow-2.7.0 PyYAML-3.11 Python-Chart-1.39 Werkzeug-0.9.6 argparse-1.2.1 beautifulsoup4-4.4.1 decorator-3.4.0 docutils-0.12 feedparser-5.1.3 gdata-2.0.18 gevent-1.0.2 greenlet-0.4.7 jcconv-0.2.3 lxml-3.4.1 mock-1.0.1 ofxparse-0.14 passlib-1.6.2 psutil-2.2.0 psycogreen-1.0 psycopg2-2.5.4 pyPdf-1.13 pydot-1.0.2 pyparsing-2.0.1 pyserial-2.7 python-dateutil-1.5 python-ldap-2.4.19 python-openid-2.2.5 python-stdnum-1.2 pytz-2013.7 pyusb-1.0.0b2 qrcode-5.1 reportlab-3.1.44 requests-2.6.0 six-1.4.1 suds-jurko-0.6 vatnumber-1.2 vobject-0.6.6 xlwt-0.7.5 8) Run odoo cd odoo # change dir to the folder you cloned odoo to export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 # Re-check parameters, it looks like addons path you used is incorrect ./odoo.py --addons-path=addons --db-filter=mydb Now you should see the output like this: INFO ? openerp: OpenERP version 9.0c INFO ? openerp: addons paths: ['/Users/dev/Library/Application Support/Odoo/addons/9.0', u'/Users/dev/projects/odoo/addons', '/Users/dev/projects/odoo/openerp/addons'] INFO ? openerp: database: default@default:default INFO ? openerp.service.server: HTTP service (werkzeug) running on 0.0.0.0:8069 9) Open odoo in your browser Go to http://localhost:8069 The database setup window appears (see the first screenshot below) Enter databse name = mydbodoo (I think the prefix mydb is important here) and password admin You can also check the checkbox to load the demo data Click Create database Wait and you should be redirected to the odoo interface (see the second screenshot) Done! Update: Mac OS X El Capitan 10.11.2 with virtualenv Do the same as above, on step (7) do not run pip install --user -r requirements.txt and instead to this: pip install virtualenv # not sure here, sudo may be needed mkdir ~/venv cd ~/venv mkdir odoo virtualenv odoo source ~/venv/odoo/bin/activate cd ~/path/to/odoo pip install -r requirements.txt # no sudo here! Now continue with step (8). Each time, before starting odoo make sure to activate the virtualenv first: source ~/venv/odoo/bin/activate export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 ./odoo.py --addons-path=addons --db-filter=mydb Ubuntu 15.04 Prerequisites: I already had postgresql 9.4.5, nodejs 0.10.25 and python 2.7.8. Installation: git clone https://github.com/odoo/odoo.git cd odoo sudo apt-get install libldap2-dev libsasl2-dev libevent-dev libxslt1-dev libxml2-dev pip install -r requirements.txt sudo npm install -g less less-plugin-clean-css ./odoo.py --addons-path=addons --db-filter=mydb That's all, now setup the same way as in the step (9) for Mac OS.