instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
PyMySQL different updates in one query?
So I have a python script that goes through roughly 350,000 data objects, and depending on some tests, it needs to update a row which represents each one of those objects in a MySQl db. I'm also using pymysql as I've had the least trouble with it especially when sending over large select queries (select statements with...
Your best performance will be if you can encode your "tests" into the SQL logic itself, so you can boil everything down to a handful of UPDATE statements. Or at least get as many as possible done that way, so that fewer rows need to be updated individually. For example: UPDATE tablename set firstname = [some logic] WH...
Implementing an iterator in Julia for an animation with PyPlot
I am just trying to reproduce this simple example of an animation in Matplotlib but using PyPlot in Julia. I am having difficulties with the definition of the iterator simData() that is passed to the function funcAnimation , because it seems that PyPlot doesn't recognize the iterator that I defined in Julia (via a Tas...
In your code, you invoke FuncAnimation this way: ani = anim.FuncAnimation(fig, simPoints, simData, blit = false, interval=10, repeat= true) In the original code, simData was a generator, but in your code it isn't, it returns a generator, so I'd expect your code to invoke it this way: ani = anim.FuncAnimation(fig, simP...
How to install cryptography on ubuntu?
My ubuntu is 14.04 LTS. When I install cryptography, the error is: Installing egg-scripts. uses namespace packages but the distribution does not require setuptools. Getting distribution for 'cryptography==0.2.1'. no previously-included directories found matching 'documentation/_build' zip_safe flag not set; analyzing ...
The answer is on the docs of cryptography's installation section which pretty much reflects Angelos' answer: Quoting it: For Debian and Ubuntu, the following command will ensure that the required dependencies are installed: $ sudo apt-get install build-essential libssl-dev libffi-dev python-dev For Fedora and RHEL-...
Tensorflow python : Accessing individual elements in a tensor
This question is with respect to accessing individual elements in a tensor, say [[1,2,3]]. I need to access the inner element [1,2,3] (This can be performed using .eval() or sess.run()) but it takes longer when the size of the tensor is huge) Is there any method to do the same faster? Thanks in Advance.
There are two main ways to access subsets of the elements in a tensor, either of which should work for your example. Use the indexing operator (based on tf.slice()) to extract a contiguous slice from the tensor. input = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) output = input[0, :] print sess.run(output) # ==> ...
Fast way of crossing strings in a list
If have a list like so: shops=['A','B','C','D'] And would like to create the following new lists (I cross each element with every other and create a string where first part is alphanumerically before the second): ['A-B', 'A-C', 'A-D'] ['A-B', 'B-C', 'B-D'] ['A-C', 'B-C', 'C-D'] ['A-D', 'B-D', 'C-D'] I have somethi...
You can create a nested list-comprehension with some additional checks: >>> shops=['A','B','C','D'] >>> [["-".join((min(a,b), max(a,b))) for b in shops if b != a] for a in shops] [['A-B', 'A-C', 'A-D'], ['A-B', 'B-C', 'B-D'], ['A-C', 'B-C', 'C-D'], ['A-D', 'B-D', 'C-D']] Note that this will probably not be much fas...
In TensorFlow is there any way to just initialize uninitialised variables?
The standard way of initializing variables in TensorFlow is init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) After running some learning for a while I create a new set of variables but once I initialize them it resets all my existing variables. At the moment my way around this is to save all the...
There is no elegant* way to enumerate the uninitialized variables in a graph. However, if you have access to the new variable objects—let's call them v_6, v_7, and v_8—you can selectively initialize them using tf.initialize_variables(): init_new_vars_op = tf.initialize_variables([v_6, v_7, v_8]) sess.run(init_new_vars_...
Is there a pythonic way to skip decoration on a subclass' method?
I have an class which decorates some methods using a decorator from another library. Specifically, the class subclasses flask-restful resources, decorates the http methods with httpauth.HTTPBasicAuth().login_required(), and does some sensible defaults on a model service. On most subclasses I want the decorator applied...
Flask-HTTPAuth uses functools.wraps in the login_required decorator: def login_required(self, f): @wraps(f) def decorated(*args, **kwargs): ... From Python 3.2, as this calls update_wrapper, you can access the original function via __wrapped__: To allow access to the original function for introspectio...
How do I avoid the "self.x = x; self.y = y; self.z = z" pattern in __init__?
I see patterns like def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... quite frequently, often with a lot more parameters. Is there a good way to avoid this type of tedious repetitiveness? Should I inherit from namedtuple?
EDIT It seems that several people are concerned about presenting this solution, so I will provide a very clear disclaimer. You should not use this solution. I only provide it as information, so you know that the language is capable of this. The rest of the answer is just showing language capabilities, not endorsing usi...
Python keyword arguments unpack and return dictionary
I have a function definition as below and I am passing keyword arguments. How do I get to return a dictionary with the same name as the keyword arguments? Manually I can do: def generate_student_dict(first_name=None, last_name=None , birthday=None, gender =None): return { 'first_name': first_name, '...
If that way is suitable for you, use kwargs (see Understanding kwargs in Python) as in code snippet below: def generate_student_dict(self, **kwargs): return kwargs Otherwise, you can create a copy of params with built-in locals() at function start and return that copy: def generate_student_dict(first_...
Python: ensure os.environ and sys.path are equal: web-requests, shell, cron, celery
I want to ensure that os.environ and sys.path are identical for all ways we start the Python interpreter: web requests via Django, and Apache mod_wsgi Cron jobs Interactive logins via ssh Celery jobs Jobs started via systemd Is there a common way to solve this? If yes, great: How does it look like? If no, sad: Everyb...
You can use envdir python port (here is the original) for managing the environment variables. If you are only concerned about Django, I suggest using envdir from your settings.py programmatically You can update the environment programmatically (e.g.: in the wsgi file, django's manage.py, settings.py, etc.) import envd...
Why is calling float() on a number slower than adding 0.0 in Python?
What is the reason that casting an integer to a float is slower than adding 0.0 to that int in Python? import timeit def add_simple(): for i in range(1000): a = 1 + 0.0 def cast_simple(): for i in range(1000): a = float(1) def add_total(): total = 0 for i in range(1000): to...
If you use the dis module, you can start to see why: In [11]: dis.dis(add_simple) 2 0 SETUP_LOOP 26 (to 29) 3 LOAD_GLOBAL 0 (range) 6 LOAD_CONST 1 (1000) 9 CALL_FUNCTION 1 (1 positional, 0 keyword pair) ...
Can you create a Python list from a string, while keeping characters in specific keywords together?
I want to create a list from the characters in a string, but keep specific keywords together. For example: keywords: car, bus INPUT: "xyzcarbusabccar" OUTPUT: ["x", "y", "z", "car", "bus", "a", "b", "c", "car"]
With re.findall. Alternate between your keywords first. >>> import re >>> s = "xyzcarbusabccar" >>> re.findall('car|bus|[a-z]', s) ['x', 'y', 'z', 'car', 'bus', 'a', 'b', 'c', 'car'] In case you have overlapping keywords, note that this solution will find the first one you encounter: >>> s = 'abcaratab' >>> re.findall...
Print letters in specific pattern in Python
I have the follwing string and I split it: >>> st = '%2g%k%3p' >>> l = filter(None, st.split('%')) >>> print l ['2g', 'k', '3p'] Now I want to print the g letter two times, the k letter one time and the p letter three times: ggkppp How is it possible?
You could use generator with isdigit() to check wheter your first symbol is digit or not and then return following string with appropriate count. Then you could use join to get your output: ''.join(i[1:]*int(i[0]) if i[0].isdigit() else i for i in l) Demonstration: In [70]: [i[1:]*int(i[0]) if i[0].isdigit() else i fo...
What could cause NetworkX & PyGraphViz to work fine alone but not together?
I'm working to learning some Python graph visualization. I found a few blog posts doing some things I wanted to try. Unfortunately I didn't get too far, encountering this error: AttributeError: 'module' object has no attribute 'graphviz_layout' The simplest snip of code which reproduces the error on my system is this, ...
There is a small bug in the draw_graphviz function in networkx-1.11 triggered by the change that the graphviz drawing tools are no longer imported into the top level namespace of networkx. The following is a workaround In [1]: import networkx as nx In [2]: G = nx.complete_graph(5) In [3]: from networkx.drawing.nx_ag...
In python, how do I cast a class object to a dict
Let's say I've got a simple class in python class Wharrgarbl(object): def __init__(self, a, b, c, sum, version='old'): self.a = a self.b = b self.c = c self.sum = 6 self.version = version def __int__(self): return self.sum + 9000 def __what_goes_here__(self)...
You need to override ' __iter__'. Like this, for example: def __iter__(self): yield 'a', self.a yield 'b', self.b yield 'c', self.c Now you can just do: dict(my_object) I would also suggest looking into the 'collections.abc' module. This answer might be helpful: http://stackoverflow.com/a/27803404/243751...
"freeze" some variables/scopes in tensorflow: stop_gradient vs passing variables to minimize
I am trying to implement Adversarial NN, which requires to 'freeze' one or the other part of the graph during alternating training minibatches. I.e. there two sub-networks: G and D. G( Z ) -> Xz D( X ) -> Y where loss function of G depends on D[G(Z)], D[X]. First I need to train parameters in D with all G parameters...
The easiest way to achieve this, as you mention in your question, is to create two optimizer operations using separate calls to opt.minimize(cost, ...). By default, the optimizer will use all of the variables in tf.trainable_variables(). If you want to filter the variables to a particular scope, you can use the optiona...
How to sort an array of integers faster than quicksort?
Sorting an array of integers with numpy's quicksort has become the bottleneck of my algorithm. Unfortunately, numpy does not have radix sort yet. Although counting sort would be a one-liner in numpy: np.repeat(np.arange(1+x.max()), np.bincount(x)) see the accepted answer to the How can I vectorize this python count ...
No, you are not stuck with quicksort. You could use, for example, integer_sort from Boost.Sort or u4_sort from usort. When sorting this array: array(randint(0, high=1<<32, size=10**8), uint32) I get the following results: NumPy quicksort: 8.636 s 1.0 (baseline) Boost.Sort integer_sort: 4.327 s 2.0x speedu...
Find elements that occur in some but not all lists
Suppose I have several lists of integers like so: [0,3,4] [2,3,4,7] [2,3,4,6] What's the most efficient / most pythonic way to build a single list of all elements that occur in at least one list but do not occur in all lists? In this case it would be [0,2,7,6]
The answer is implied in your question .. if you substitute "set" for "lists". As StephenTG posted, simply get the difference between the union and the intersection of all lists. The advantage of using sets over Counter is that you need make no assumptions about values appearing only once in each list. The following wo...
Keep the order of list in sql pagination
I have a list with an order of insertion. I want to paginate the results using the same order. As you can see currently the output will be a different order. following_companies_list_data = Company.query.filter(Company.id.in_(['2', '24', '1', '7', '373'])).paginate( page, per_page=10, error_out=False) com...
Solution based on this answer from related question company_ids = ['2', '24', '1', '7', '373'] order_expressions = [(Company.id==i).desc() for i in company_ids] query = Company.query.filter(Company.id.in_(company_ids)).order_by(*order_expressions) following_companies_list_data = query.paginate(page, per_page=10, error_...
Python list order
In the small script I wrote, the .append() function adds the entered item to the beginning of the list, instead of the end of that list. (As you can clearly understand, am quite new to the Python, so go easy on me) list.append(x) Add an item to the end of the list; equivalent to a[len(a):] = [x]. That's what is say...
Ok, this is what's happening. When your text isn't "done", you've programmed it so that you immediately call the function again (i.e, recursively call it). Notice how you've actually set it to append an item to the list AFTER you do the getting_text(raw_input("Enter the text or write done to finish entering ")) line. S...
How do I search a list that is in a nested list (list of list) without loop in Python?
I am perfectly aware of that.. sample=[[1,[1,0]],[1,1]] [1,[1,0]] in sample This will return True. But what I want to do here is this. sample=[[1,[1,0]],[1,1]] [1,0] in sample I want the return to be True, but this returns False. I can do this: sample=[[1,[1,0]],[1,1]] for i in range(len(sample)): [1,0] in sample...
you can use chain from itertools to merge the lists and then search in the returned list. >>> sample=[[1,[1,0]],[1,1]] >>> from itertools import chain >>> print [1,0] in chain(*sample) True
Why isn't this alternative to the deprecated Factory.set_creation_function working with nosetests?
Factory Boy deprecated set_creation_function (see ChangeLog 2.6.1) and recommends that developers Replace factory.set_creation_function(SomeFactory, creation_function) with an override of the _create() method of SomeFactory I have i) a number of derivative factory classes and ii) my db session instantiated in anot...
Two major issues with your sample not-working code: the class should be derived from SQLAlchemyModelFactory class the _create() method should be defined as classmethod Fixed version: from factory.alchemy import SQLAlchemyModelFactory as Factory from myapp.core import db class MyFactory(Factory): class Meta: ...
Correctly extract Emojis from a Unicode string
I am working in Python 2 and I have a string containing emojis as well as other unicode characters. I need to convert it to a list where each entry in the list is a single character/emoji. x = u'😘😘xyz😊😊' char_list = [c for c in x] The desired output is: ['😘', '😘', 'x', 'y', 'z', '😊',...
First of all, in Python2, you need to use Unicode strings (u'<...>') for Unicode characters to be seen as Unicode characters. And correct source encoding if you want to use the chars themselves rather than the \UXXXXXXXX representation in source code. Now, as per Python: getting correct string length when it contains s...
Get the number of all keys in a dictionary of dictionaries in Python
I have a dictionary of dictionaries in Python 2.7. I need to quickly count the number of all keys, including the keys within each of the dictionaries. So in this example I would need the number of all keys to be 6: dict_test = {'key2': {'key_in3': 'value', 'key_in4': 'value'}, 'key1': {'key_in2': 'value', 'key_in1': 'v...
Keeping it Simple If we know all the values are dictionaries, and do not wish to check that any of their values are also dictionaries, then it is as simple as: len(dict_test) + sum(len(v) for v in dict_test.itervalues()) Refining it a little, to actually check that the values are dictionaries before counting them: len...
What can `__init__` do that `__new__` cannot?
In Python, __new__ is used to initialize immutable types and __init__ typically initializes mutable types. If __init__ were removed from the language, what could no longer be done (easily)? For example, class A: def __init__(self, *, x, **kwargs): super().__init__(**kwargs) self.x = x class B(A)...
Note about difference between __new__ and __init__ Before explaining missing functionality let's get back to definition of __new__ and __init__: __new__ is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class. However, __init__ doesn't return anything; it...
Setting up the EB CLI - error nonetype get_frozen_credentials
Select a default region 1) us-east-1 : US East (N. Virginia) 2) us-west-1 : US West (N. California) 3) us-west-2 : US West (Oregon) 4) eu-west-1 : EU (Ireland) 5) eu-central-1 : EU (Frankfurt) 6) ap-southeast-1 : Asia Pacific (Singapore) 7) ap-southeast-2 : Asia Pacific (Sydney) 8) ap-northeast-1 : Asia Pacific (Tokyo)...
You got this error because you didn't initialize your AWS Access Key ID and AWS Secret Access Key you should install first awscli by runing pip install awscli. After you need to configure aws: aws configure After this you can run eb init
Can I use index information inside the map function?
Let's assume there is a list a = [1, 3, 5, 6, 8]. I want to apply some transformation on that list and I want to avoid doing it sequentially, so something like map(someTransformationFunction, a) would normally do the trick, but what if the transformation needs to have knowledge of the index of each object? For example...
Use the enumerate() function to add indices: map(function, enumerate(a)) Your function will be passed a tuple, with (index, value). In Python 2, you can specify that Python unpack the tuple for you in the function signature: map(lambda (i, el): i * el, enumerate(a)) Note the (i, el) tuple in the lambda argument speci...
Break statement in finally block swallows exception
Consider: def raiseMe( text="Test error" ): raise Exception( text ) def break_in_finally_test(): for i in range(5): if i==2: try: raiseMe() except: raise else: print "succeeded!" finally: pri...
From https://docs.python.org/2.7/reference/compound_stmts.html#finally: If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause...
numpy array set ones between two values, fast
having been looking for solution for this problem for a while but can't seem to find anything. For example, I have an numpy array of [ 0, 0, 2, 3, 2, 4, 3, 4, 0, 0, -2, -1, -4, -2, -1, -3, -4, 0, 2, 3, -2, -1, 0] what I would like to achieve is the generate another array to indicate the elements betwee...
Quite a problem that is! Listed in this post is a vectorized solution (hopefully the inlined comments would help to explain the logic behind it). I am assuming A as the input array with T1, T2 as the start and stop triggers. def setones_between_triggers(A,T1,T2): # Get start and stop indices corresponding to r...
Celery (Redis) results backend not working
I have a web application using Django and i am using Celery for some asynchronous tasks processing. For Celery, i am using Rabbitmq as a broker, and Redis as a result backend. Rabbitmq and Redis are running on the same Ubuntu 14.04 server hosted on a local virtual machine. Celery workers are running on remote machines ...
My guess is that your problem is in the password. Your password has @ in it, which could be interpreted as a divider between the user:pass and the host section. The workers stay in pending because they could not connect to the broker correctly. From celery's documentation http://docs.celeryproject.org/en/latest/usergui...
Django application 504 error after saving model
I have a Django website running Django 1.8 with Python 3.4 and hosted on AWS via ElasticBeanstalk. Recently, I've been having some issues with the Django admin area and 504 errors. The problem is very difficult to reproduce, it seems to happen randomly. When I save an instance of a model, sometimes the website hangs an...
It is probably due to this bug https://github.com/pyca/cryptography/issues/2299 How to fix discussed here https://github.com/pyca/cryptography/issues/2473 Which seems to say uninstall python Cryptography library and then pip install version 1.1 of it
check if two lists are equal by type Python
I want to check if two lists have the same type of items for every index. For example if I have y = [3, "a"] x = [5, "b"] z = ["b", 5] the check should be True for x and y. The check should be False for y and z because the types of the elements at the same positions are not equal.
Just map the elements to their respective type and compare those: >>> x = [5, "b"] >>> y = [3, "a"] >>> z = ["b", 5] >>> map(type, x) == map(type, y) True >>> map(type, x) == map(type, z) False For Python 3, you will also have to turn the map generators into proper lists, either by using the list function or with a l...
How to check if two permutations are symmetric?
Given two permutations A and B of L different elements, L is even, let's call these permutations "symmetric" (for a lack of a better term), if there exist n and m, m > n such as (in python notation): - A[n:m] == B[L-m:L-n] - B[n:m] == A[L-m:L-n] - all other elements are in place Informally, consider A = 0 1 2 3 4 ...
Here is the working solution for the question: def isSymmetric(A, B): L = len(A) #assume equivalent to len(B), modifying this would be as simple as checking if len(A) != len(B), return [] la = L//2 # half-list length Al = A[:la] Ar = A[la:] Bl = B[:la] Br = B[la:] for i in range(la): ...
Using python decorator with or without parentheses
What is the difference in Python when using the same decorator with or without parentheses? For example: Without parentheses @someDecorator def someMethod(): pass With parentheses @someDecorator() def someMethod(): pass
someDecorator in the first code snippet is a regular decorator: @someDecorator def someMethod(): pass is equivalent to someMethod = someDecorator(someMethod) On the other hand, someDecorator in the second code snippet is a callable that returns a decorator: @someDecorator() def someMethod(): pass is equival...
Python - If not statement with 0.0
I have a question regarding if not statement in Python 2.7. I have written some code and used if not statements. In one part of the code I wrote, I refer to a function which includes an if not statement to determine whether an optional keyword has been entered. It works fine, except when 0.0 is the keyword's value. I...
Problem You understand it right. not 0 (and also not 0.0) returns True in Python. Simple test can be done to see this: a = not 0 print(a) Result: True Thus, the problem is explained. This line: if not x: Must be changed to something else. Solutions There are couple of ways which can be done to fix the issue. I am ...
Why does bit-wise shift left return different results in Python and Java?
I'm trying to port some functionality from a Java app to Python. In Java, System.out.println(155 << 24); Returns: -1694498816 In Python: print(155 << 24) Returns 2600468480 Many other bitwise operations have worked in the same way in both languages. Why is there a different result in these two operations? EDIT: I'm ...
Java has 32-bit fixed width integers, so 155 << 24 shifts the uppermost set bit of 155 (which is bit 7, counting bits from zero, because 155 is greater than 27 but less than 28) into the sign bit (bit 31) and you end up with a negative number. Python has arbitrary-precision integers, so 155 << 24 is numerically equal t...
Loop while checking if element in a list in Python
Let's say I have a simple piece of code like this: for i in range(1000): if i in [150, 300, 500, 750]: print(i) Does the list [150, 300, 500, 750] get created every iteration of the loop? Or can I assume that the interpreter (say, CPython 2.7) is smart enough to optimize this away?
You can view the bytecode using dis.dis. Here's the output for CPython 2.7.11: 2 0 SETUP_LOOP 40 (to 43) 3 LOAD_GLOBAL 0 (range) 6 LOAD_CONST 1 (1000) 9 CALL_FUNCTION 1 12 GET_ITER >...
Removing data between double squiggly brackets with nested sub brackets in python
I'm having some difficulty with this problem. I need to remove all data that's contained in squiggly brackets. Like such: Hello {{world of the {{ crazy}} {{need {{ be}}}} sea }} there. Becomes: Hello there. Here's my first try (I know it's terrible): while 1: firstStartBracket = text.find('{{') if (firstStar...
You can use pyparsing module here. Solution based on this answer: from pyparsing import nestedExpr s = "Hello {{world of the {{ crazy}} {{need {{ be}}}} sea }} there {{my }} friend." expr = nestedExpr('{{', '}}') result = expr.parseString("{{" + s + "}}").asList()[0] print(" ".join(item for item in result if not isi...
Merging Key-Value Pairings in Dictionary
I have a dictionary that consists of employee-manager as key-value pairs: {'a': 'b', 'b': 'd', 'c': 'd', 'd': 'f'} I want to show the relations between employee-manager at all levels (employee's boss, his boss's boss, his boss's boss's boss etc.) using a dictionary. The desired output is: {'a': [b,d,f], 'b': [d,f], 'c...
>>> D = {'a': 'b', 'b': 'd', 'c': 'd', 'd': 'f'} >>> res = {} >>> for k in D: ... res[k] = [j] = [D[k]] ... while j in D: ... j = D[j] ... res[k].append(j) ... >>> res {'b': ['d', 'f'], 'c': ['d', 'f'], 'd': ['f'], 'a': ['b', 'd', 'f']}
An Object is created twice in Python
I have read Expert Python Programming which has an example for multi-inheritance. The book author has explained but I did not understand it, so I would like to have another view. The example shows that object B is created two times! Could you please give me an intuitive explanation. In [1]: class A(object): ...: ...
The super() just means "next in line", where the line is the mro ['C', 'A', 'B', 'object']. So next in line for A is B. The mro is calculated according to an algorithm called C3 linearization. When you use super(), Python just goes along this order. When you write your class A you don't know yet which class will be nex...
Using a pre-trained word embedding (word2vec or Glove) in TensorFlow
I've recently reviewed an interesting implementation for convolutional text classification. However all TensorFlow code I've reviewed uses a random (not pre-trained) embedding vectors like the following: with tf.device('/cpu:0'), tf.name_scope("embedding"): W = tf.Variable( tf.random_uniform([vocab_size, em...
There are a few ways that you can use a pre-trained embedding in TensorFlow. Let's say that you have the embedding in a NumPy array called embedding, with vocab_size rows and embedding_dim columns and you want to create a tensor W that can be used in a call to tf.nn.embedding_lookup(). Simply create W as a tf.constant...
Why is there a performance difference between the order of a nested loop?
I have a process that loops through two lists, one being relatively large while the other being significantly smaller. Example: larger_list = list(range(15000)) smaller_list = list(range(2500)) for ll in larger_list: for sl in smaller_list: pass I scaled the sized down of the lists to test pe...
When you disassemble one of your functions you get: >>> dis.dis(small_then_large) 2 0 SETUP_LOOP 31 (to 34) 3 LOAD_GLOBAL 0 (smaller_list) 6 GET_ITER >> 7 FOR_ITER 23 (to 33) 10 STORE_FAST 0 (sl) 3 ...
Find tuple structure containing an unknown value inside a list
Say I have list of tuples: list = [(1,5), (1,7), (2,3)] Is there a way in Python to write something like if (1, *) in list: do things where * means "I don’t care about this value"? So we are checking if there is a tuple with 1 at the first position and with whatever value on the second one. As far as I know there ...
You can use the any() function: if any(t[0] == 1 for t in yourlist): This efficiently tests and exits early if 1 is found in the first position of a tuple.
module imports and __init__.py in Python
I am trying to understand what the best practices are with regards to Python's (v2.7) import mechanics. I have a project that has started to grow a bit and lets say my code is organised as follows: foo/ __init__.py Foo.py module1.py module2.py module3.py The package name is foo and underneath it I ...
A couple things you could do to improve your organizaton, if only to adhere to some popular python conventions and standards. If you search this topic, you will inevitably run across people recommending the PEP8 guidelines. These are the de facto canonical standards for organizing python code. Modules should have s...
Problems using MySQL with AWS Lambda in Python
I am trying to get up and running with AWS Lambda Python (beginner in Python btw) but having some problems with including MySQL dependency. I am trying to follow the instructions here on my Mac. For step number 3, I am getting some problems with doing the command at the root of my project sudo pip install MySQL-python ...
For a use case like Lambda you'll be a lot happier using a pure python implementation like PyMySQL. It's a drop in replacement for MySQLdb that follows the Python Database API specification. For most things like triggered Lambda events it will be just as fast. I've used it in production a lot and it works great.
Python: understanding class and instance variables
I think I have some misconception about class and instance variables. Here is an example code: class Animal(object): energy = 10 skills = [] def work(self): print 'I do something' self.energy -= 1 def new_skill(self, skill): self.skills.append(skill) if __name__ == '__main__'...
The trick here is in understanding what self.energy -= 1 does. It's really two expressions; one getting the value of self.energy - 1, and one assigning that back to self.energy. But the thing that's confusing you is that the references are not interpreted the same way on both sides of that assignment. When Python is to...
Why do dict keys support list subtraction but not tuple subtraction?
Presumably dict_keys are supposed to behave as a set-like object, but they are lacking the difference method and the subtraction behaviour seems to diverge. >>> d = {0: 'zero', 1: 'one', 2: 'two', 3: 'three'} >>> d.keys() - [0, 2] {1, 3} >>> d.keys() - (0, 2) TypeError: 'int' object is not iterable Why does dict_keys ...
This looks to be a bug. The implementation is to convert the dict_keys to a set, then call .difference_update(arg) on it. It looks like they misused _PyObject_CallMethodId (an optimized variant of PyObject_CallMethod), by passing a format string of just "O". Thing is, PyObject_CallMethod and friends are documented to r...
Python eval: is it still dangerous if I disable builtins and attribute access?
We all know that eval is dangerous, even if you hide dangerous functions, because you can use Python's introspection features to dig down into things and re-extract them. For example, even if you delete __builtins__, you can retrieve them with [c for c in ().__class__.__base__.__subclasses__() if c.__name__ == 'cat...
I'm going to mention one of the new features of Python 3.6 - f-strings. They can evaluate expressions, >>> eval('f"{().__class__.__base__}"', {'__builtins__': None}, {}) "<class 'object'>" but the attribute access won't be detected by Python's tokenizer: 0,0-0,0: ENCODING 'utf-8' 1,0-1,1: ...
Multi POST query (session mode)
I am trying to interrogate this site to get the list of offers. The problem is that we need to fill 2 forms (2 POST queries) before receiving the final result. This what I have done so far: First I am sending the first POST after setting the cookies: library(httr) set_cookies(.cookies = c(a = "1", b = "2")) first_url...
using a python requests.Session object with the following data gets to the results page: form1 = {"energy_category": "electricity", "location": "home", "location-home": "shift", "distributor": "7", "postcode": "3000", "energy_concession": "0", "solar": "0", ...
sine calculation orders of magnitude slower than cosine
tl;dr Of the same numpy array, calculating np.cos takes 3.2 seconds, wheras np.sin runs 548 seconds (nine minutes) on Linux Mint. See this repo for full code. I've got a pulse signal (see image below) which I need to modulate onto a HF-carrier, simulating a Laser Doppler Vibrometer. Therefore signal and its time basis...
I don't think numpy has anything to do with this: I think you're tripping across a performance bug in the C math library on your system, one which affects sin near large multiples of pi. (I'm using "bug" in a pretty broad sense here -- for all I know, since the sine of large floats is poorly defined, the "bug" is actu...
`object in list` behaves different from `object in dict`?
I've got an iterator with some objects in it and I wanted to create a collection of uniqueUsers in which I only list every user once. So playing around a bit I tried it with both a list and a dict: >>> for m in ms: print m.to_user # let's first look what's inside ms ... Pete Kramer Pete Kramer Pete Kramer >>> >>> uni...
In order to understand what’s going on, you have to understand how the in operator, the membership test, behaves for the different types. For lists, this is pretty simple due to what lists fundamentally are: Ordered arrays that do not care about duplicates. The only possible way to peform a membership test here is to...
Python 3: super() raises TypeError unexpectedly
Coming from Java, I'm struggling a bit getting down inheritance, abstract classes, static methods and similar concepts of OO programming in Python. I have an implementation of an expression tree class, given (simplified) by # Generic node class class Node(ABC): @abstractmethod def to_expr(self): pass ...
You're using super() without arguments in a generator expression. The super() is magic - it relies on information in the caller frame. Since the generator expression creates an additional function, super() without arguments does not work there. However since your superclass is not probable to change in the middle of ex...
Is there a one line code to find maximal value in a matrix?
To find the maximal value in a matrix of numbers, we can code 5 lines to solve the problem: ans = matrix[0][0] for x in range(len(matrix)): for y in range(len(matrix[0])): ans = max(ans, matrix[x][y]) return ans Is there a one line solution for this problem? The one that I came up with is pretty awkward ac...
You can use generator expression to find the maximum in your matrix. That way you can avoid building the full list of matrix elements in memory. maximum = max(max(row) for row in matrix) instead of list comprehension as given in a previous answer here maximum = max([max(row) for row in matrix]) This is from PEP (the ...
Efficiently count word frequencies in python
I'd like to count frequencies of all words in a text file. >>> countInFile('test.txt') should return {'aaa':1, 'bbb': 2, 'ccc':1} if the target text file is like: # test.txt aaa bbb ccc bbb I've implemented it with pure python following some posts. However, I've found out pure-python ways are insufficient due to huge...
The most succinct approach is to use the tools Python gives you. from future_builtins import map # Only on Python 2 from collections import Counter from itertools import chain def countInFile(filename): with open(filename) as f: return Counter(chain.from_iterable(map(str.split, f))) That's it. map(str.s...
Create empty conda environment
I can create a new conda environment, with program biopython with this: conda create --name snowflakes biopython What if I do not want to install any program? It seems I can not do that: » conda create --name tryout Error: too few arguments, must supply command line package specs or --file You can specify one or mor...
You can give a package name of just "python" to get a base, empty install. conda create --name myenv python conda create --name myenv python=3.4
Cleanest way to obtain the numeric prefix of a string
What is the cleanest way to obtain the numeric prefix of a string in Python? By "clean" I mean simple, short, readable. I couldn't care less about performance, and I suppose that it is hardly measurable in Python anyway. For example: Given the string '123abc456def', what is the cleanest way to obtain the string '123'?...
You can use itertools.takewhile which will iterate over your string (the iterable argument) until it encounters the first item which returns False (by passing to predictor function): >>> from itertools import takewhile >>> input = '123abc456def' >>> ''.join(takewhile(str.isdigit, input)) '123'
how to print 3x3 array in python?
I need to print a 3 x 3 array for a game called TicTackToe.py. I know we can print stuff from a list in a horizontal or vertical way by using listA=['a','b','c','d','e','f','g','h','i','j'] # VERTICAL PRINTING for item in listA: print item Output: a b c or # HORIZONTAL PRINTING for item in listA: p...
You can enumerate the items, and print a newline only every third item: for index, item in enumerate('abcdefghij', start=1): print item, if not index % 3: print Output: a b c d e f g h i j enumerate starts counting from zero by default, so I set start=1. As @arekolek comments, if you're using Python 3...
Python - create an EXE that runs code as written, not as it was when compiled
I'm making a pygame program that is designed to be modular. I am building an exe with pygame2exe of the file main.py, which basically just imports the real main game and runs it. What I'm hoping for is a sort of launcher that will execute Python scripts from an EXE, rather than a single program containing all immutable...
After some experiments I've found a solution. Create a separate folder source in the main folder of the application. Here will be placed source files. Also place file __init__.py to the folder. Lets name a main file like main_module.py. Add all of its contents as a data files to the py2exe configuration setup.py. Now ...
Disable Tensorflow Debugging information
By debugging information I mean what TensorFlow shows in my terminal about loaded libraries and found devices etc. not the python errors. I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library...
There currently isn't a way of suppressing/controlling logging in TensorFlow EDIT: View the page below for information on TensorFlow logging; with the new update, you're able to set the logging verbosity to either DEBUG, INFO, WARN, ERROR, or FATAL. For example: tf.logging.set_verbosity(tf.logging.ERROR) The page addi...
Python Iterate through list of list to make a new list in index sequence
How would you iterate through a list of lists, such as: [[1,2,3,4], [5,6], [7,8,9]] and construct a new list by grabbing the first item of each list, then the second, etc. So the above becomes this: [1, 5, 7, 2, 6, 8, 3, 9, 4]
You can use a list comprehension along with itertools.izip_longest (or zip_longest in Python 3) from itertools import izip_longest a = [[1,2,3,4], [5,6], [7,8,9]] [i for sublist in izip_longest(*a) for i in sublist if i is not None] # [1, 5, 7, 2, 6, 8, 3, 9, 4]
Error running basic tensorflow example
I have just reinstalled latest tensorflow on ubuntu: $ sudo pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl [sudo] password for ubuntu: The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cac...
From the path in your stack trace (/git/tensorflow/tensorflow/…), it looks like your Python path may be loading the tensorflow libraries from the source directory, rather than the version that you have installed. As a result, it is unable to find the (compiled) pywrap_tensorflow library, which is installed in a diffe...
How to generate multiple plots by clicking a single plot for more infomation using clickable python events
I am in the process of developing an application which can generate a 2nd plot by clicking data point in the 1st plot. I am using events to accomplish this. Question: How to generate a 3rd plot by clicking a 2nd plot data point? Is it possible to accomplish to this? How to generate a simpler 3 layer synthetic data? C...
synthetic 3 level data import matplotlib.pyplot as plt import numpy as np # data source data_bucket = {} # l1: randn # l2: sum(l1) # l3: sum(l2) # generate some 3 layer synthetic data N = 1000 l1_count = 50 l2_count = 50 l3_count = 2 x = np.arange(N) for j in range(l3_count): l3 = [] for k in range(l2_count)...
Python pip install gives "Command "python setup.py egg_info" failed with error code 1"
I'm new to python and have been trying to install some packages with pip. I always get this error message though: "Command "python setup.py egg_info" failed with error code 1 in C:\Users\MARKAN~1\AppData\Local\Temp\pip-build-wa7uco0k\unroll\" As an example this is with the package "unroll". Any suggestions? Benjamin
About the error code According to python documentation This module makes available standard errno system symbols. The value of each symbol is the corresponding integer value. The names and descriptions are borrowed from linux/include/errno.h, which should be pretty all-inclusive. Error code 1 is defined in errno.h an...
Edit the value of every Nth item in a list
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] I would like to add 1 to every second item, which would give: list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] I've tried: list1[::2]+1 and also: for x i...
You could use slicing with a list comprehension as follows: In [26]: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [27]: list1[1::2] = [x+1 for x in list1[1::2]] In [28]: list1 Out[28]: [1, 3, 3, 5, 5, 7, 7, 9, 9, 11]
What is a DynamicClassAttribute and how do I use it?
As of Python 3.4, there is a descriptor called DynamicClassAttribute. The documentation states: types.DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None) Route attribute access on a class to __getattr__. This is a descriptor, used to define attributes that act differently when accessed through an instanc...
New Version: I was a bit disappointed with the previous answer so I decided to rewrite it a bit: First have a look at the source code of DynamicClassAttribute and you'll probably notice, that it looks very much like the normal property. Except for the __get__-method: def __get__(self, instance, ownerclass=None): if...
Is there a need to close files that have no reference to them?
As a complete beginner to programming, I am trying to understand the basic concepts of opening and closing files. One exercise I am doing is creating a script that allows me to copy the contents from one file to another. in_file = open(from_file) indata = in_file.read() out_file = open(to_file, 'w') out_file.write(in...
The pythonic way to deal with this is to use the with context manager: with open(from_file) as in_file, open(to_file, 'w') as out_file: indata = in_file.read() out_file.write(indata) Used with files like this, with will ensure all the necessary cleanup is done for you, even if read() or write() throw errors.
Mysterious exceptions when making many concurrent requests from urllib.request to HTTPServer
I am trying to do this Matasano crypto challenge that involves doing a timing attack against a server with an artificially slowed-down string comparison function. It says to use "the web framework of your choosing", but I didn't feel like installing a web framework, so I decided to use the HTTPServer class built into t...
You're using the default listen() backlog value, which is probably the cause of a lot of those errors. This is not the number of simultaneous clients with connection already established, but the number of clients waiting on the listen queue before the connection is established. Change your server class to: class FancyH...
Why did Django 1.9 replace tuples () with lists [] in settings and URLs?
I am bit curious to know why Django 1.9 replaced tuples () with lists [] in settings, URLs and other configuration files I just upgraded to Django 1.9 and noticed these changes. What is the logic behind them? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', ...
It is explained in issue #8846 (emphasis mine): In the documentation for ​Creating your own settings there's a recommendation which reads "For settings that are sequences, use tuples instead of lists. This is purely for performance." This is bunk. Profiling shows that tuples run no faster than lists for most o...
Counterintuitive behaviour of int() in python
It's clearly stated in the docs that int(number) is a flooring type conversion: int(1.23) 1 and int(string) returns an int if and only if the string is an integer literal. int('1.23') ValueError int('1') 1 Is there any special reason for that? I find it counterintuitive that the function floors in one case, but not ...
There is no special reason. Python is simply applying its general principle of not performing implicit conversions, which are well-known causes of problems, particularly for newcomers, in languages such as Perl and Javascript. int(some_string) is an explicit request to convert a string to integer format; the rules for ...
Difference in sequence of query generated in Django and Postgres for select_for_update
I'm facing a strange situation, where sequence of query logged in Django and Postgres is different when using select_for_update() inside transaction.atomic() block. Basically I've a ModelForm where I'm validating the cleaned_data against the database, for duplicate request. And then in create view's form_valid() method...
EDITED: How to make Django validate overlapping reservations? It is possible to add special method for a model validate_unique: from django.db import models from django.core.validators import ValidationError from django.forms.forms import NON_FIELD_ERRORS class Dish(models.Model): name = models...
How to call a function with a dictionary that contains more items than the function has parameters?
I am looking for the best way to combine a function with a dictionary that contains more items than the function's inputs basic **kwarg unpacking fails in this case: def foo(a,b): return a + b d = {'a':1, 'b':2, 'c':3} foo(**d) --> TypeError: foo() got an unexpected keyword argument 'c' After some rese...
How about making a decorator that would filter allowed keyword arguments only: import inspect def get_input_names(function): '''get arguments names from function''' return inspect.getargspec(function)[0] def filter_dict(dict_,keys): return {k:dict_[k] for k in keys} def filter_kwargs(func): def fun...
Alowing 'fuzzy' translations in django pages?
I've done some research and found that django translations don't show up when a string is marked as "fuzzy". However, I haven't been able to find any documentation on whether I can override this behaviour. Is there a Django setting that can be used to allow Django (or gettext) to use "fuzzy translations"? I know a lot...
It would be unfortunate to show these translations as some of them are most certainly wrong. You are supposed to remove the fuzzy tag when you update the translations and revise the guessed translations that are marked as fuzzy. However, you may run a tool to quickly delete the fuzzy markers from a .po file: Removing ...
Why is a double semicolon a SyntaxError in Python?
I know that semicolons are unnecessary in Python, but they can be used to cram multiple statements onto a single line, e.g. >>> x = 42; y = 54 I always thought that a semicolon was equivalent to a line break. So I was a bit surprised to learn (h/t Ned Batchelder on Twitter) that a double semicolon is a SyntaxError: >>...
From the Python grammar, we can see that ; is not defined as \n. The parser expects another statement after a ;, except if there's a newline after it: Semicolon w/ statement Maybe a semicolon Newline \/ \/ \/ \/ simple_stmt: small_stmt ...
Pythonic way to avoid "if x: return x" statements
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x x =...
Alternatively to Martijn's fine answer, you could chain or. This will return the first truthy value, or None if there's no truthy value: def check_all_conditions(): return check_size() or check_color() or check_tone() or check_flavor() or None Demo: >>> x = [] or 0 or {} or -1 or None >>> x -1 >>> x = [] or 0 or {...
Python the same char not equals
I have a text in my database. I send some text from xhr to my view. Function find does not find some unicode chars. I want find selected text using just: text.find(selection) but sometimes variable 'selection' has char like that: ę # in xhr unichr(281) in variable 'text' there is a char: ę # in db has two chars un...
Here unicodedata.normalize might help you. Basically if you normalize the data coming from the db, and normalize your selection to the same form, you should have a better result when using str.find, str.__contains__ (i.e. in), str.index, and friends. >>> u1 = chr(281) >>> u2 = chr(101) + chr(808) >>> print(u1, u2) Ä...
Difference between "raise" and "raise e"?
In python, is there a difference between raise and raise e in an except block? dis is showing me different results, but I don't know what it means. What's the end behavior of both? import dis def a(): try: raise Exception() except Exception as e: raise def b(): try: raise Exception...
There is no difference in this case. raise without arguments will always raise the last exception thrown (which is also accessible with sys.exc_info()). The reason the bytecode is different is because Python is a dynamic language and the interpreter doesn't really "know" that e refers to the (unmodified) exception that...
How to use inverse of a GenericRelation
I must be really misunderstanding something with the GenericRelation field from Django's content types framework. To create a minimal self contained example, I will use the polls example app from the tutorial. Add a generic foreign key field into the Choice model, and make a new Thing model: class Choice(models.Model)...
TL;DR This was a bug in Django 1.7 that was fixed in Django 1.8. Fix commit: 1c5cbf5e5d5b350f4df4aca6431d46c767d3785a Fix PR: GenericRelation filtering targets related model's pk Bug ticket: Should filter on related model primary key value, not the object_id value The change went directly to master and did not go und...
Python send control + Q then control + A (special keys)
I need to send some special keystrokes and am unsure of how to do it. I need to send Ctrl + Q followed by Ctrl + A to a terminal (I'm using Paramiko). i have tried shell = client.invoke_shell() shell.send(chr(10)) time.sleep(5) shell.send(chr(13)) shell.send('\x11') shell.send('\x01') print 'i tried' I can see the ...
Just as assumption: maybe pseudoterminal would help import paramiko client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(...) channel = сlient.get_transport().open_session() channel.get_pty() channel.settimeout(5) channel.exec_command('\x11\x01')
Importing installed package from script raises "AttributeError: module has no attribute" or "ImportError: cannot import name"
I have a script named requests.py that imports the requests package. The script either can't access attributes from the package, or can't import them. Why isn't this working and how do I fix it? The following code raises an AttributeError. import requests res = requests.get('http://www.google.ca') print(res) Traceb...
This happens because your local module named requests.py shadows the installed requests module you are trying to use. The current directory is prepended to sys.path, so the local name takes precedence over the installed name. An extra debugging tip when this comes up is to look at the Traceback carefully, and realize ...
limit() and sort() order pymongo and mongodb
Despite reading peoples answers stating that the sort is done first, evidence shows something different that the limit is done before the sort. Is there a way to force sort always first? views = mongo.db.view_logging.find().sort([('count', 1)]).limit(10) Whether I use .sort().limit() or .limit().sort(), the limit take...
According to the documentation, regardless of which goes first in your chain of commands, sort() would be always applied before the limit(). You can also study the .explain() results of your query and look at the execution stages - you will find that the sorting input stage examines all of the filtered (in your case al...
All possible ways to interleave two strings
I am trying to generate all possible ways to interleave any two arbitrary strings in Python. For example: If the two strings are 'ab' and 'cd', the output I wish to get is: ['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab'] See a is always before b (and c before d). I am struggling to find a solution to this. I have tri...
The Idea Let the two strings you want to interleave be s and t. We will use recursion to generate all the possible ways to interleave these two strings. If at any point of time we have interleaved the first i characters of s and the first j characters of t to create some string res, then we have two ways to interleave...
Why can't I break out of this itertools infinite loop?
In the REPL, we can usually interrupt an infinite loop with a sigint, i.e. ctrl+c, and regain control in the interpreter. >>> while True: pass ... ^CTraceback (most recent call last): File "<stdin>", line 1, in <module> KeyboardInterrupt >>> But in this loop, the interrupt seems to be blocked and I have to kill the...
The KeyboardInterrupt is checked after each Python instruction. itertools.repeat and the tuple generation is handled in C Code. The interrupt is handled afterwards, i.e. never.
Iterator selector in Python
Is there a standard pythonic way of selecting a value from a list of provided iterators without advancing those that were not selected? Something in the vein of this for two iterators (don't judge this too hard: it was quickly thrown together just to illustrate the idea): def iselect(i1, i2, f): e1_read = False ...
The more-itertools package has a peekable wrapper for iterators. It would seem like this should allow for a very clean solution if I understand your question correctly. You need to peek at the current values of a set of iterators and only modify the chosen iterator by calling next() on it. from more_itertools import pe...
pip install - locale.Error: unsupported locale setting
Full stacktrace: ➜ ~ pip install virtualenv Traceback (most recent call last): File "/usr/bin/pip", line 11, in <module> sys.exit(main()) File "/usr/lib/python3.4/site-packages/pip/__init__.py", line 215, in main locale.setlocale(locale.LC_ALL, '') File "/usr/lib64/python3.4/locale.py", line 592, in ...
try it: $ export LC_ALL=C Here is my locale settings: $ locale LANG=en_US.UTF-8 LANGUAGE= LC_CTYPE="C" LC_NUMERIC="C" LC_TIME="C" LC_COLLATE="C" LC_MONETARY="C" LC_MESSAGES="C" LC_PAPER="C" LC_NAME="C" LC_ADDRESS="C" LC_TELEPHONE="C" LC_MEASUREMENT="C" LC_IDENTIFICATION="C" LC_ALL=C Python2.7 $ uname -a Linux...
map vs list; why different behaviour?
In the course of implementing the "Variable Elimination" algorithm for a Bayes' Nets program, I encountered an unexpected bug that was the result of an iterative map transformation of a sequence of objects. For simplicity's sake, I'll use an analogous piece of code here: >>> nums = [1, 2, 3] >>> for x in [4, 5, 6]: ......
The answer is very simple: map is a lazy function in Python 3, it returns an iterable object (in Python 2 it returns a list). Let me add some output to your example: In [6]: nums = [1, 2, 3] In [7]: for x in [4, 5, 6]: ...: nums = map(lambda n: n if x % 2 else n + 10, nums) ...: print(x) ...: prin...
Cycle a list from alternating sides
Given a list a = [0,1,2,3,4,5,6,7,8,9] how can I get b = [0,9,1,8,2,7,3,6,4,5] That is, produce a new list in which each successive element is alternately taken from the two sides of the original list?
>>> [a[-i//2] if i % 2 else a[i//2] for i in range(len(a))] [0, 9, 1, 8, 2, 7, 3, 6, 4, 5] Explanation: This code picks numbers from the beginning (a[i//2]) and from the end (a[-i//2]) of a, alternatingly (if i%2 else). A total of len(a) numbers are picked, so this produces no ill effects even if len(a) is odd. [-i//2...
Variable assignment faster than one liner
I have encountered this weird behavior and failed to explain it. These are the benchmarks: py -3 -m timeit "tuple(range(2000)) == tuple(range(2000))" 10000 loops, best of 3: 97.7 usec per loop py -3 -m timeit "a = tuple(range(2000)); b = tuple(range(2000)); a==b" 10000 loops, best of 3: 70.7 usec per loop How come co...
My results were similar to yours: the code using variables was pretty consistently 10-20 % faster. However when I used IPython on the very same Python 3.4, I got these results: In [1]: %timeit -n10000 -r20 tuple(range(2000)) == tuple(range(2000)) 10000 loops, best of 20: 74.2 µs per loop In [2]: %timeit -n10000 -r20 ...
Making len() work with instance methods
Is there a way to make len() work with instance methods without modifying the class? Example of my problem: >>> class A(object): ... pass ... >>> a = A() >>> a.__len__ = lambda: 2 >>> a.__len__() 2 >>> len(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'A' has ...
No. Python always looks up special methods through the object's class. There are several good reasons for this, one being that repr(A) should use type(A).__repr__ instead of A.__repr__, which is intended to handle instances of A instead of the A class itself. If you want different instances of A to compute their len di...
Is it possible to get pip to print the configuration it is using?
Is there any way to get pip to print the config it will attempt to use? For debugging purposes it would be very nice to know that: config.ini files are in the correct place and pip is finding them. The precedence of the config settings is treated in the way one would expect from the docs
Updated(answering comment) You can start python console and do. (If you have virtaulenv don't forget to activate it first) from pip import create_main_parser parser = create_main_parser() # print all config files that it will try to read print(parser.files) # reads parser files that are actually found and prints their...
Square root of complex numbers in python
I have run across some confusing behaviour with square roots of complex numbers in python. Running this code: from cmath import sqrt a = 0.2 b = 0.2 + 0j print(sqrt(a / (a - 1))) print(sqrt(b / (b - 1))) gives the output 0.5j -0.5j A similar thing happens with print(sqrt(-1 * b)) print(sqrt(-b)) It appears these pa...
Both answers (+0.5j and -0.5j) are correct, since they are complex conjugates -- i.e. the real part is identical, and the imaginary part is sign-flipped. Looking at the code makes the behavior clear - the imaginary part of the result always has the same sign as the imaginary part of the input, as seen in lines 790 and ...
What does x[x < 2] = 0 mean in Python?
I came across some code with a line similar to x[x<2]=0 Playing around with variations, I am still stuck on what this syntax does. Examples: >>> x = [1,2,3,4,5] >>> x[x<2] 1 >>> x[x<3] 1 >>> x[x>2] 2 >>> x[x<2]=0 >>> x [0, 2, 3, 4, 5]
This only makes sense with NumPy arrays. The behavior with lists is useless, and specific to Python 2 (not Python 3). You may want to double-check if the original object was indeed a NumPy array (see further below) and not a list. But in your code here, x is a simple list. Since x < 2 is False i.e 0, therefore x[x<2] ...
Compare two large dictionaries and create lists of values for keys they have in common
I have a two dictionaries like: dict1 = { (1,2) : 2, (2,3): 3, (1,3): 3} dict2 = { (1,2) : 1, (1,3): 2} What I want as output is two list of values for the items which exist in both dictionaries: [2,3] [1,2] What I am doing right now is something like this: list1 = [] list2 = [] for key in dict1.keys(): if key i...
commons = set(dict1).intersection(set(dict2)) list1 = [dict1[k] for k in commons] list2 = [dict2[k] for k in commons]
Decorator for a class method that caches return value after first access
My problem, and why I'm trying to write a decorator for a class method, @cachedproperty. I want it to behave so that when the method is first called, the method is replaced with its return value. I also want it to behave like @property so that it doesn't need to be explicitly called. Basically, it should be indistingui...
If you don't mind alternative solutions, I'd recommend lru_cache for example from functools import lru_cache class Test: @property @lru_cache(maxsize=None) def calc(self): print("Calculating") return 1 Expected output In [2]: t = Test() In [3]: t.calc Calculating Out[3]: 1 In [4]: t.calc ...
Let a class behave like it's a list in Python
I have a class which is essentially a collection/list of things. But I want to add some extra functions to this list. What I would like, is the following: I have an instance li = MyFancyList(). Variable li should behave as it was a list whenever I use it as a list: [e for e in li], li.expand(...), for e in li. Plus ...
If you want only part of the list behavior, use composition (i.e. your instances hold a reference to an actual list) and implement only the methods necessary for the behavior you desire. These methods should delegate the work to the actual list any instance of your class holds a reference to, for example: def __getitem...
Django REST Framework + Django REST Swagger + ImageField
I created a simple Model with an ImageField and I wanna make an api view with django-rest-framework + django-rest-swagger, that is documented and is able to upload the file. Here is what I got: models.py from django.utils import timezone from django.db import models class MyModel(models.Model): source = models.Im...
I got this working by making a couple of changes to your code. First, in models.py, change ImageField name to file and use relative path to upload folder. When you upload file as binary stream, it's available in request.data dictionary under file key (request.data.get('file')), so the cleanest option is to map it to th...
Image processing issues with blood vessels
I'm trying to extract the blood vessels from an image, and to do so, I'm first equalizing the image, applying CLAHE histogram to obtain the following result: clahe = cv2.createCLAHE(clipLimit=100.0, tileGridSize=(100,100)) self.cl1 = clahe.apply(self.result_array) self.cl1 = 255 - self.cl1 And...
Getting really good results is a difficult problem (you'll probably have to somehow model the structure of the blood vessels and the noise) but you can probably still do better than filtering. One technique for addressing this kind of problems, inspired by the Canny edge detector, is using two thresholds - [hi,low] and...
Why are Python's arrays slow?
I expected array.array to be faster than lists, as arrays seem to be unboxed. However, I get the following result: In [1]: import array In [2]: L = list(range(100000000)) In [3]: A = array.array('l', range(100000000)) In [4]: %timeit sum(L) 1 loop, best of 3: 667 ms per loop In [5]: %timeit sum(A) 1 loop, best of 3...
The storage is "unboxed", but every time you access an element Python has to "box" it (embed it in a regular Python object) in order to do anything with it. For example, your sum(A) iterates over the array, and boxes each integer, one at a time, in a regular Python int object. That costs time. In your sum(L), all th...
Numpy: Why doesn't 'a += a.T' work?
As stated in scipy lecture notes, this will not work as expected: a = np.random.randint(0, 10, (1000, 1000)) a += a.T assert np.allclose(a, a.T) But why? How does being a view affect this behavior?
This problem is due to internal designs of numpy. It basically boils down to that the inplace operator will change the values as it goes, and then those changed values will be used where you were actually intending for the original value to be used. This is discussed in this bug report, and it does not seem to be fixab...
What exactly is __weakref__ in Python?
Surprisingly, there's no explicit documentation for __weakref__. Weak references are explained here. __weakref__ is also shortly mentioned in the documentation of __slots__. But I could not find anything about __weakref__ itself. What exactly is __weakref__? - Is it just a member acting as a flag: If present, the objec...
[Edit 1: Explain the linked list nature and when weakrefs are re-used] Interestingly enough, the official documentation is somewhat non-enlightening on this topic: Without a __weakref__ variable for each instance, classes defining __slots__ do not support weak references to its instances. If weak reference support is ...
On what CPU cores are my Python processes running?
The setup I have written a pretty complex piece of software in Python (on a Windows PC). My software starts basically two Python interpreter shells. The first shell starts up (I suppose) when you double click the main.py file. Within that shell, other threads are started in the following way: # Start TCP_thread ...
Q: Is it true that a Python interpreter uses only one CPU core at a time to run all the threads? No. GIL and CPU affinity are unrelated concepts. GIL can be released during blocking I/O operations, long CPU intensive computations inside a C extension anyway. If a thread is blocked on GIL; it is probably not on any CP...