instruction stringlengths 12 148 | input stringlengths 16 30.2k | output stringlengths 11 27.3k |
|---|---|---|
Elegant way to create empty pandas DataFrame with NaN of type float | I want to create a Pandas DataFrame filled with NaNs. During my research I found an answer:
import pandas as pd
df = pd.DataFrame(index=range(0,4),columns=['A'])
This code results in a DataFrame filled with NaNs of type "object". So they cannot be used later on for example with the interpolate() method. Therefore, I ... | This one-liner seems to work as well:
>>> df = pd.DataFrame(np.nan, index=[0,1,2,3], columns=['A'])
>>> df.dtypes
A float64
dtype: object
|
Complex numbers in Cython | What is the correct way to work with complex numbers in Cython?
I would like to write a pure C loop using a numpy.ndarray of dtype np.complex128. In Cython, the associated C type is defined in
Cython/Includes/numpy/__init__.pxd as
ctypedef double complex complex128_t
so it seems this is just a simple C double comple... | The simplest way I can find to work around this issue is to simply switch the order of multiplication.
If in testcplx.pyx I change
varc128 = varc128 * varf64
to
varc128 = varf64 * varc128
I change from the failing situation to described to one that works correctly. This scenario is useful as it allows a direct diff ... |
Pythonic way to merge two overlapping lists, preserving order | Alright, so I have two lists, as such:
They can and will have overlapping items, for example, [1, 2, 3, 4, 5], [4, 5, 6, 7].
There will not be additional items in the overlap, for example, this will not happen: [1, 2, 3, 4, 5], [3.5, 4, 5, 6, 7]
The lists are not necessarily ordered nor unique. [9, 1, 1, 8, 7], [8, 6,... | You can try the following:
>>> a = [1, 3, 9, 8, 3, 4, 5]
>>> b = [3, 4, 5, 7, 8]
>>> matches = (i for i in xrange(len(b), 0, -1) if b[:i] == a[-i:])
>>> i = next(matches, 0)
>>> a + b[i:]
[1, 3, 9, 8, 3, 4, 5, 7, 8]
The idea is we check the first i elements of b (b[:i]) with the last i elements of a (a[-i:]). We take... |
How to find out Chinese or Japanese Character in a String in Python? | Such as:
str = 'sdf344asfasf天尿¹ç3権sdfsdf'
Add () to Chinese and Japanese Characters:
strAfterConvert = 'sdfasfasf(天尿¹ç)3(権)sdfsdf'
| As a start, you can check if the character is in one of the following unicode blocks:
Unicode Block 'CJK Unified Ideographs' - U+4E00 to U+9FFF
Unicode Block 'CJK Unified Ideographs Extension A' - U+3400 to U+4DBF
Unicode Block 'CJK Unified Ideographs Extension B' - U+20000 to U+2A6DF
Unicode Block 'CJK Unified Ideog... |
How to get current time in python and break up into year, month, day, hour, minute? | I would like to get the current time in Python and assign them into variables like year, month, day, hour, minute. How can this be done in Python 2.7?
| The datetime module is your friend:
import datetime
now = datetime.datetime.now()
print now.year, now.month, now.day, now.hour, now.minute, now.second
# 2015 5 6 8 53 40
You don't need separate variables, the attributes on the returned datetime object have all you need.
|
Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? | It is my understanding that the range() function, which is actually an object type in Python 3, generates its contents on the fly, similar to a generator.
This being the case, I would have expected the following line to take an inordinate amount of time, because in order to determine whether 1 quadrillion is in the ra... | The Python 3 range() object doesn't produce numbers immediately; it is a smart sequence object that produces numbers on demand. All it contains is your start, stop and step values, then as you iterate over the object the next integer is calculated each iteration.
The object also implements the object.__contains__ hook,... |
How to join list in Python but make the last separator different? | I'm trying to turn a list into separated strings joined with an ampersand if there are only two items, or commas and an ampersand between the last two e.g.
Jones & Ben
Jim, Jack & James
I currently have this:
pa = ' & '.join(listauthors[search])
and don't know how to make sort out the comma/ampersand issue. Beginner ... | "&".join([",".join(my_list[:-1]),my_list[-1]])
I would think would work
or maybe just
",".join(my_list[:-1]) +"&"+my_list[-1]
to handle edge cases where only 2 items you could
"&".join([",".join(my_list[:-1]),my_list[-1]] if len(my_list) > 2 else my_list)
|
Why are some float < integer comparisons four times slower than others? | When comparing floats to integers, some pairs of values take much longer to be evaluated than other values of a similar magnitude.
For example:
>>> import timeit
>>> timeit.timeit("562949953420000.7 < 562949953421000") # run 1 million times
0.5387085462592742
But if the float or integer is made smaller or larger by a ... | A comment in the Python source code for float objects acknowledges that:
Comparison is pretty much a nightmare
This is especially true when comparing a float to an integer, because, unlike floats, integers in Python can be arbitrarily large and are always exact. Trying to cast the integer to a float might lose precis... |
Looking for idiomatic way to evaluate to False if argument is False in Python 3 | I have a chain of functions, all defined elsewhere in the class:
fus(roh(dah(inp)))
where inp is either a dictionary, or bool(False).
The desired result is that if inp, or any of the functions evaluate to False, False is returned by the function stack.
I attempted to use ternary operators, but they don't evaluate corr... | Decorator should look like:
def validate_inp(fun):
def wrapper(inp):
return fun(inp) if inp else False
return wrapper
@validate_inp
def func(inp):
return int(inp['value']) + 1
print(func(False))
print(func({'value': 1}))
If you want to use your decorator with a class member:
def validate_inp(fun... |
Why does assigning to an empty list (e.g. [] = "") raise no error? | In python 3.4, I am typing
[] = ""
and it works fine, no Exception is raised. Though of course [] is not equal to "" afterwards.
[] = ()
also works fine.
"" = []
raises an exception as expected though,
() = ""
raises an exception as expected though. So, what's going on?
| You are not comparing for equality. You are assigning.
Python allows you to assign to multiple targets:
foo, bar = 1, 2
assigns the two values to foo and bar, respectively. All you need is a sequence or iterable on the right-hand side, and a list or tuple of names on the left.
When you do:
[] = ""
you assigned an emp... |
Python in Browser: How to choose between Brython, PyPy.js, Skulpt and Transcrypt? | EDIT: Please note I'm NOT asking for a (subjective) product recommendation. I am asking for objective information -- that I can then use to make my own decision.
I'm very excited to see that it is now possible to code Python inside a browser page. The main candidates appear to be:
http://www.brython.info/
http://www.sk... | This might be helpful too:
http://stromberg.dnsalias.org/~strombrg/pybrowser/python-browser.html
It compares several Python-in-the-browser technologies.
|
Is there a faster way to clean out control characters in a file? | Previously, I had been cleaning out data using the code snippet below
import unicodedata, re, io
all_chars = (unichr(i) for i in xrange(0x110000))
control_chars = ''.join(c for c in all_chars if unicodedata.category(c)[0] == 'C')
cc_re = re.compile('[%s]' % re.escape(control_chars))
def rm_control_chars(s): # see http... | found a solution working character by charater, I bench marked it using a 100K file:
import unicodedata, re, io
from time import time
# This is to generate randomly a file to test the script
from string import lowercase
from random import random
all_chars = (unichr(i) for i in xrange(0x110000))
control_chars = [c fo... |
Obtain a list containing string elements excluding elements prefixed with any other element from initial list | I have some trouble with filtering a list of strings. I found a similar question here but is not what i need.
The input list is:
l = ['ab', 'xc', 'abb', 'abed', 'sdfdg', 'abfdsdg', 'xccc']
and the expected result is
['ab', 'xc', 'sdfdg']
The order of the items in the result is not important
The filter function must... | This algorithm completes the task in 0.97 second on my computer, with the input file submitted by the author (154MB):
l.sort()
last_str = l[0]
filtered = [last_str]
app = filtered.append
for str in l:
if not str.startswith(last_str):
last_str = str
app(str)
# Commented because of the massive... |
"yield from iterable" vs "return iter(iterable)" | When wrapping an (internal) iterator one often has to reroute the __iter__ method to the underlying iterable. Consider the following example:
class FancyNewClass(collections.Iterable):
def __init__(self):
self._internal_iterable = [1,2,3,4,5]
# ...
# variant A
def __iter__(self):
retur... | The only significant difference is what happens when an exception is raised from within the iterable. Using return iter() your FancyNewClass will not appear on the exception traceback, whereas with yield from it will. It is generally a good thing to have as much information on the traceback as possible, although there ... |
How can I use super() with one argument in python | While reading about the super() object in Python, I read the following statement:
If the second argument is omitted, the super object returned is unbound
What does this exactly mean and how do I use super() with one argument in code?
| Python function objects are descriptors, and Python uses the descriptor protocol to bind functions to an instance. This process produces a bound method.
Binding is what makes the 'magic' self argument appear when you call a method, and what makes a property object automatically call methods when you try to use the prop... |
How to multiply functions in python? | def sub3(n):
return n - 3
def square(n):
return n * n
It's dead easy to compose functions in python:
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [square(sub3(n)) for n in my_list]
[9, 4, 1, 0, 1, 4, 9, 16, 25, 36]
Unfortunately, when wanting to use the composition as a key, it's kind of lame:
>>> sorted(... | You can use your hack class as a decorator pretty much as it's written, though you'd likely want to choose a more appropriate name for the class.
Like this:
class Composable(object):
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
return self.function(... |
How to save Python NLTK alignment models for later use? | In Python, I'm using NLTK's alignment module to create word alignments between parallel texts. Aligning bitexts can be a time-consuming process, especially when done over considerable corpora. It would be nice to do alignments in batch one day and use those alignments later on.
from nltk import IBMModel1 as ibm
biverse... | The immediate answer is to pickle it, see https://wiki.python.org/moin/UsingPickle
But because IBMModel1 returns a lambda function, it's not possible to pickle it with the default pickle / cPickle (see https://github.com/nltk/nltk/blob/develop/nltk/align/ibm1.py#L74 and https://github.com/nltk/nltk/blob/develop/nltk/al... |
running a python package after compiling and uploading to pypicloud server | Folks,
After building and deploying a package called myShtuff to a local pypicloud server, I am able to install it into a separate virtual env.
Everything seems to work, except for the path of the executable...
(venv)[ec2-user@ip-10-0-1-118 ~]$ pip freeze
Fabric==1.10.1
boto==2.38.0
myShtuff==0.1
ecdsa==0.13
paramiko... | You need a __main__.py in your package, and an entry point defined in setup.py.
See here and here but in short, your __main__.py runs whatever your main functionality is when running your module using python -m, and setuptools can make whatever arbitrary functions you want to run as scripts. You can do either or both. ... |
Calling Scrapy from another file without threading | I have to call a crawler from another python file, for which I use :
def crawl_koovs():
spider = SomeSpider()
settings = get_project_settings()
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configure()
crawler.crawl(spider)
crawler.st... | The first thing I would say to you is when you're executing Scrapy from external file the loglevel is set to INFO,you should change it to DEBUG to see what's happening if your code doesn't work
you should change the line:
log.start()
for:
log.start(loglevel=log.DEBUG)
To store everything in the log and generate a te... |
Basics of recursion in Python |
"Write a recursive function, "listSum" that takes a list of integers and returns the sum of all integers in the list".
Example:
>>>> listSum([1,3,4,5,6])
19
I know how to do this another way but not in the recursive way.
def listSum(ls):
i = 0
s = 0
while i < len(ls):
s = s + ls[i]
i = i... | Whenever you face a problem like this, try to express the result of the function with the same function.
In your case, you can get the result by adding the first number with the result of calling the same function with rest of the elements in the list.
For example,
listSum([1, 3, 4, 5, 6]) = 1 + listSum([3, 4, 5, 6])
... |
Errata (erasures+errors) Berlekamp-Massey for Reed-Solomon decoding | I am trying to implement a Reed-Solomon encoder-decoder in Python supporting the decoding of both erasures and errors, and that's driving me crazy.
The implementation currently supports decoding only errors or only erasures, but not both at the same time (even if it's below the theoretical bound of 2*errors+erasures <=... | After reading lots and lots of research papers and books, the only place where I have found the answer is in the book (readable online on Google Books, but not available as a PDF):
"Algebraic codes for data transmission", Blahut, Richard E., 2003, Cambridge university press.
Here are some extracts of this book, which... |
Why is [] faster than list()? | I recently compared the processing speeds of [] and list() and was surprised to discover that [] runs more than three times faster than list(). I ran the same test with {} and dict() and the results were practically identical: [] and {} both took around 0.128sec / million cycles, while list() and dict() took roughly 0.... | Because [] and {} are literal syntax. Python can create bytecode just to create the list or dictionary objects:
>>> import dis
>>> dis.dis(compile('[]', '', 'eval'))
1 0 BUILD_LIST 0
3 RETURN_VALUE
>>> dis.dis(compile('{}', '', 'eval'))
1 0 BUILD_MAP ... |
matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot? | I have this so far:
x,y,z = data.nonzero()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, zdir='z', c= 'red')
plt.savefig("plot.png")
Which creates:
What I'd like to do is stretch this out to make the Z axis 9 times taller and keep X and Y the same. I'd like to keep the same co... | The code example below provides a way to scale each axis relative to the others. However, to do so you need to modify the Axes3D.get_proj function. Below is an example based on the example provided by matplot lib: http://matplotlib.org/1.4.0/mpl_toolkits/mplot3d/tutorial.html#line-plots
(There is a shorter version at t... |
How to make an Python subclass uncallable | How do you "disable" the __call__ method on a subclass so the following would be true:
class Parent(object):
def __call__(self):
return
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
object.__setattr__(self, '__call__', None)
>>> c = Child()
>>> callable(c)
Fals... | You can't. As jonrsharpe points out, there's no way to make Child appear to not have the attribute, and that's what callable(Child()) relies on to produce its answer. Even making it a descriptor that raises AttributeError won't work, per this bug report: https://bugs.python.org/issue23990 . A python 2 example:
>>> clas... |
Raise error if a Python dict comprehension overwrites a key | Is there a way to get a dict comprehension to raise an exception if it would override a key?
For example, I would like the following to error because there are two values for the key 'a':
>>> {k:v for k, v in ('a1', 'a2', 'b3')}
{'a': '2', 'b': '3'}
I realise this can be done with a for loop. Is there a way to do it w... | You can use a generator with a helper function:
class DuplicateKeyError(ValueError): pass
def dict_no_dupl(it):
d = {}
for k, v in it:
if k in d: raise DuplicateKeyError(k)
d[k] = v
return d
dict_no_dupl((k, v) for k, v in ('a1', 'a2', 'b3'))
This does add a helper function, but keeps the... |
Listing contents of a bucket with boto3 | How can I see what's inside a bucket in S3 with boto3? (i.e. do an "ls")?
Doing the following:
import boto3
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('some/path/')
returns:
s3.Bucket(name='some/path/')
How do I see its contents?
| One way to see the contents would be:
for object in mybucket.objects.all():
print(object)
|
Proper way to consume data from RESTFUL API in django | I'm trying to learn django so while I have a current solution I'm not sure if it follows best practices in django. I would like to display information from a web api on my website. Let's say the api url is as follows:
http://api.example.com/books?author=edwards&year=2009
Thsis would return a list of books by Edwards w... | I like the approach of putting that kind of logic in a separate service layer (services.py); the data you are rendering is quite not a "model" in the Django ORM sense, and it's more than simple "view" logic. A clean encapsulation ensures you can do things like control the interface to the backing service (i.e., make it... |
Reshaping/Pivoting data in Spark RDD and/or Spark DataFrames | I have some data in the following format (either RDD or Spark DataFrame):
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
rdd = sc.parallelize([('X01',41,'US',3),
('X01',41,'UK',1),
('X01',41,'CA',2),
('X02',72,'US',4),
... | First up, this is probably not a good idea, because you are not getting any extra information, but you are binding yourself with a fixed schema (ie you must need to know how many countries you are expecting, and of course, additional country means change in code)
Having said that, this is a SQL problem, which is shown ... |
A fast way to find an all zero answer | For every array of length n+h-1 with values from 0 and 1, I would like to check if there exists another non-zero array of length n with values from -1,0,1 so that all the h inner products are zero. My naive way to do this is
import numpy as np
import itertools
(n,h)= 4,3
for longtuple in itertools.product([0,1], repea... | Consider the following "meet in the middle" approach.
First, recast the situation in the matrix formulation provided by leekaiinthesky.
Next, note that we only have to consider "short" vectors s of the form {0,1}^n (i.e., short vectors containing only 0's and 1's) if we change the problem to finding an h x n Hankel m... |
Limit memory usage? | I run Python 2.7 on a Linux machine with 16GB Ram and 64 bit OS. A python script I wrote can load too much data into memory, which slows the machine down to the point where I cannot even kill the process any more.
While I can limit memory by calling:
ulimit -v 12000000
in my shell before running the script, I'd like t... | resource.RLIMIT_VMEM is the resource corresponding to ulimit -v.
RLIMIT_DATA only affects brk/sbrk system calls while newer memory managers tend to use mmap instead.
The second thing to note is that ulimit/setrlimit only affects the current process and its future children.
Regarding the AttributeError: 'module' object ... |
How can a python 2 doctest fail and yet have no difference in the values in the failure message? | I'm using Python 2.7.9 in Windows.
I have a UTF-8-encoded python script file with the following contents:
# coding=utf-8
def test_func():
u"""
>>> test_func()
u'â'
"""
return u'â'
I get a curious failure when I run the doctest:
Failed example:
test_func()
Expected:
u'\u2603'
Got:
u... | My Findings
Using the original doc-string and return value.
Expected:
u'\u2603'
Got:
u'\u2603'
Seemingly paradoxical.
Using a modified doc-string and original return value.
def test_func():
u"""
>>> test_func()
u'\\u2603'
"""
return u'â'
Outputting the correct result:
Trying:
test_fu... |
Apache Spark: How to use pyspark with Python 3 | I built Spark 1.4 from the GH development master, and the build went through fine. But when I do a bin/pyspark I get the Python 2.7.9 version. How can I change this?
| Just set the environment variable:
export PYSPARK_PYTHON=python3
incase you want this change to be permanent add this line to pyspark script
|
Why does CalibratedClassifierCV underperform a direct classifer? | I noticed that sklearn's new CalibratedClassifierCV seems to underperform the direct base_estimator when the base_estimator is GradientBoostingClassifer, (I haven't tested other classifiers). Interestingly, if make_classification's parameters are:
n_features = 10
n_informative = 3
n_classes = 2
then the CalibratedCla... | The probability calibration itself requires cross-validation, therefore the CalibratedClassifierCV trains a calibrated classifier per fold (in this case using StratifiedKFold), and takes the mean of the predicted probabilities from each classifier when you call predict_proba(). This could lead to the explanation of the... |
Selenium: Trying to log in with cookies - "Can only set cookies for current domain" | What I am trying to achieve
I am trying to log in to a website where cookies must be enabled using Selenium headless, I am using PhantomJS for driver.
Problem
I first recorded the procedure using Selenium IDE where it works fine using Firefox (not headless). Then I exported the code to Python and now I can't log in bec... | Investigate the each cookies pairs. I ran into the similar issues and some of the cookies belonged to Google. You need to make sure cookies are being added only to the current Domain and also belong to the same Domain. In that case your exception is expected. On a side note, if I recall it correctly you cannot use loca... |
Any elegant way to add a method to an existing object in python? | After a lot of searching, I have found that there are a few ways to add an bound method or unbound class methods to an existing instance objects
Such ways include approaches the code below is taking.
import types
class A(object):
pass
def instance_func(self):
print 'hi'
def class_func(self):
print 'hi'... | Normally, functions stored in object dictionaries don't automatically turn into boundmethods when you look them up with dotted access.
That said, you can use functools.partial to pre-bind the function and store it in the object dictionary so it can be accessed like a method:
>>> from functools import partial
>>> clas... |
tar.extractall() does not recognize unexpected EOF | The Python tarfile library does not detect a broken tar.
user@host$ wc -c good.tar
143360 good.tar
user@host$ head -c 130000 good.tar > cut.tar
user@host$ tar -tf cut.tar
...
tar: Unexpected EOF in archive
tar: Error is not recoverable: exiting now
Very nice, the command line tool recognizes an unexpected EOF.
use... | I wrote a work around. It works with my tar files. I guess it supports not all types of objects which can be stored in a tar file.
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function
import os
import tarfile
class TarfileWhichRaisesOnEOF(tarfile.TarFile):
def ... |
"pip install --editable ./" vs "python setup.py develop" | Is there any significant difference between
pip install -e /path/to/mypackage
and the setuptools variant?
python /path/to/mypackage/setup.py develop
| There is no big difference.
With pip install -e for local projects, the "SomeProject.egg-info" directory is created
relative to the project path. This is one advantage over just using
setup.py develop, which creates the "egg-info" directly relative the
current working directory.
More: docs
Also read the setu... |
Deploying a minimal flask app in docker - server connection issues | I have an app who's only dependency is flask, which runs fine outside docker and binds to the default port 5000. Here is the full source:
from flask import Flask
app = Flask(__name__)
app.debug = True
@app.route('/')
def main():
return 'hi'
if __name__ == '__main__':
app.run()
The problem is that when I dep... | The problem is you are only binding to the localhost interface, you should be binding to 0.0.0.0 if you want the container to be accessible from outside. If you change:
if __name__ == '__main__':
app.run()
to
if __name__ == '__main__':
app.run(host='0.0.0.0')
It should work.
|
List comprehension, check if item is unique | I am trying to write a list comprehension statement that will only add an item if it's not currently contained in the list. Is there a way to check the current items in the list that is currently being constructed? Here is a brief example:
Input
{
"Stefan" : ["running", "engineering", "dancing"],
"Bob" : ["danc... | You can use set and set comprehension:
{hobby for name, hobbies in input.items() for hobby in hobbies}
As m.wasowski mentioned, we don't use the name here, so we can use item.values() instead:
{hobby for hobbies in input.values() for hobby in hobbies}
If you really need a list as the result, you can do this (but noti... |
Finding red color using Python & OpenCV | I am trying to extract red color from an image. I have code that applies threshold to leave only values from specified range:
img=cv2.imread('img.bmp')
img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_red = np.array([0,50,50]) #example value
upper_red = np.array([10,255,255]) #example value
mask = cv2.inRange(img_hsv... | I would just add the masks together, and use np.where to mask the original image.
img=cv2.imread("img.bmp")
img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# lower mask (0-10)
lower_red = np.array([0,50,50])
upper_red = np.array([10,255,255])
mask0 = cv2.inRange(img_hsv, lower_red, upper_red)
# upper mask (170-180)
lowe... |
django 1.7.8 not sending emails with password reset | Relevant part of urls.py for the project:
from django.conf.urls import include, url, patterns
urlpatterns = patterns('',
# other ones ...
url(r'^accounts/password/reset/$',
'django.contrib.auth.views.password_reset',
{'post_reset_redirect' : '/accounts/password/reset/done/'}),
url(r'^accounts/password/rese... | I tried to recreate your situation and I faced the following scenarios:
Mail is only sent to active users. Email associated with no user will not get any email(obviously).
I got an error form's save method in line 270 for email = loader.render_to_string(email_template_name, c):
NoReverseMatch at /accounts/password/... |
How to get one number specific times in an array python | I have one array like A = [1,2,3] and another array B = [4,5,6]. Now, I need another array C so that the elements in C should be the same elements of B having occurrence in the order of element A. Like,
C = [4, 5, 5, 6, 6, 6]
| A = [1,2,3]
B = [4,5,6]
C = [b_item for a_item, b_item in zip(A,B) for _ in range(a_item)]
print C
Result:
[4, 5, 5, 6, 6, 6]
This is a one-line equivalent to:
C = []
for a_item, b_item in zip(A,B):
for _ in range(a_item):
C.append(b_item)
... Which is roughly equivalent to
C = []
for i in range(min(len(... |
Asynchronous exception handling in Python | I've the following code using asyncio and aiohttp to make asynchronous HTTP requests.
import sys
import asyncio
import aiohttp
@asyncio.coroutine
def get(url):
try:
print('GET %s' % url)
resp = yield from aiohttp.request('GET', url)
except Exception as e:
raise Exception("%s has error '... | asyncio.wait doesn't actually consume the Futures passed to it, it just waits for them to complete, and then returns the Future objects:
coroutine asyncio.wait(futures, *, loop=None, timeout=None,
return_when=ALL_COMPLETED)
Wait for the Futures and coroutine objects
given by the sequence futures to complete. Corou... |
How do I extend, mimic, or emulate the range function? | I made a little generator function for character ranges:
>>> def crange(start, end):
... for i in range(ord(start), ord(end)+1):
... yield chr(i)
...
And then I can do this:
>>> print(*crange('a','e'))
a b c d e
Yay! But this doesn't work:
>>> crange('a','e')[::2]
Traceback (most recent call last):
... |
At that point, my first thought was to simply subclass range.
range was a function in Python2 and a "final" class in Python3 (more info here) - in both cases not something you can sub-class. You will need to create a class crange that extends from an object as the base type.
class crange(object):
And this works, ... |
Is it possible to use Angular with the Jinja2 template engine? | I have a Flask site and I want to use the Angular JavaScript framework. Unfortunately, it seems as if the delimiters overlap.
How do I use Angular with Jinja2 if both rely on double curly braces ({{ expr }})? Is it even possible?
| You have some options.
1) Change the delimiter notation for Angular:
var app = angular.module('Application', []);
app.config(['$interpolateProvider', function($interpolateProvider) {
$interpolateProvider.startSymbol('{a');
$interpolateProvider.endSymbol('a}');
}]);
Whatever is chosen for the start and end symbols... |
Optimizing a reed-solomon encoder (polynomial division) | I am trying to optimize a Reed-Solomon encoder, which is in fact simply a polynomial division operation over Galois Fields 2^8 (which simply means that values wrap-around over 255). The code is in fact very very similar to what can be found here for Go: http://research.swtch.com/field
The algorithm for polynomial divis... | The following is 3x faster than pypy on my machine (0.04s vs 0.15s). Using Cython:
ctypedef unsigned char uint8_t # does not work with Microsoft's C Compiler: from libc.stdint cimport uint8_t
cimport cpython.array as array
cdef uint8_t[::1] gf_exp = bytearray([1, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, ... |
Alternative to `any` that returns the last evaluated object? | I just wrote a bit of code where I wanted to do:
def foo(container)
return any((some_obj.attr <= 0 for some_obj in container))
where foo would return the first some_obj where some_obj.attr is zero or less. The alternative, I suppose, would be
def foo(container):
return next((some_obj for some_obj in container ... | The docs for any explain that it's equivalent to:
def any(iterable):
for element in iterable:
if element:
return True
return False
So, I don't think your code is too deeply nested if it has exactly the same structure as code that's used to illustrate the functionality of any itself.
Still, ... |
Remove spurious small islands of noise in an image - Python OpenCV | I am trying to get rid of background noise from some of my images. This is the unfiltered image.
To filter, I used this code to generate a mask of what should remain in the image:
element = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
mask = cv2.erode(mask, element, iterations = 1)
mask = cv2.dilate(mask, eleme... | A lot of your questions stem from the fact that you're not sure how morphological image processing works, but we can put your doubts to rest. You can interpret the structuring element as the "base shape" to compare to. 1 in the structuring element corresponds to a pixel that you want to look at in this shape and 0 is... |
SSLError: Can't connect to HTTPS URL because the SSL module is not available on google app engine | Want to use wechat sdk to create menu
WeChat.create_menu({
"button":[
{
"type":"click",
"name":"Daily Song",
"key":"V1001_TODAY_MUSIC"
},
{
"type":"click",
"name":" Artist Profile",
"key":"V1001_TODAY_SINGER"
},
{
... | If you're using GAE's Sockets, you can get SSL support without any hacks by simply loading the SSL library.
Simply add this to your app.yaml file:
libraries:
- name: ssl
version: latest
This is documented on Google Cloud's OpenSSL Support documentation.
|
How can I register a single view (not a viewset) on my router? | I am using Django REST framework and have been trying to create a view that returns a small bit of information, as well as register it on my router.
I have four models which store information, and all of them have a created_time field. I am trying to make a view that returns the most recent objects (based on the create... | Routers work with a ViewSet and aren't designed for normal views, but that doesn't mean that you cannot use them with a normal view. Normally they are used with models (and a ModelViewSet), but they can be used without them using the GenericViewSet (if you would normally use a GenericAPIView) and ViewSet (if you would ... |
ImportError: No module named django.core.management when using manage.py | I'm trying to run python manage.py runserver on a Django application I have and I get this error:
Traceback (most recent call last):
File "manage.py", line 8, in <module>
from django.core.management import execute_from_command_line
ImportError: No module named django.core.management
Here is the output of pip freeze |... | Possible issues that may cause your problem:
PYTHONPATH is not well configured, to configure it you should do:
export PYTHONPATH=/usr/local/lib/python2.7/site-packages
You forgot the line #!/usr/bin/env python at the beginning of manage.py
If you're working on virtualenv you forgot to activate the virtual env to exec... |
Is it possible to implement Python yield functionality in freestanding C? | I recently came accross the yield keyword in Python (as well as JavaScript) - I understand that this is primarliy used for the generator pattern, but the language construct seems to be used in asynchronous functions as well where my interests lie. In asynchronous functions it may merely act as syntatic-sugar and I know... | Iterators in Python follow this pattern: You call them (with arguments) and they return an object. You call that object's .next() or .__next__() method repeatedly and it runs through the iterator.
We can do something similar:
typedef struct iterator{
int yield_position; /* Where to jump to */
void *yield_state... |
Shift elements in a numpy array | Following-up from this question years ago, is there a canonical "shift" function in numpy? I don't see anything from the documentation.
Here's a simple version of what I'm looking for:
def shift(xs, n):
if n >= 0:
return np.r_[np.full(n, np.nan), xs[:-n]]
else:
return np.r_[xs[-n:], np.full(-n, ... | Not numpy but scipy provides exactly the shift functionality you want,
import numpy as np
from scipy.ndimage.interpolation import shift
xs = np.array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
shift(xs, 3, cval=np.NaN)
where default is to bring in a constant value from outside the array with value cval, set... |
Error " 'dict' object has no attribute 'iteritems' " when trying to use NetworkX's write_shp() | I'm trying to use NetworkX to read a Shapefile and use the function write_shp() to generate the Shapefiles that will contain the nodes and edges (following this example - https://networkx.github.io/documentation/latest/reference/readwrite.nx_shp.html), but when I try to run the code it gives me the following error:
Tra... | As you are in python3 , use dict.items() instead of dict.iteritems()
iteritems() was removed in python3, so you can't use this method anymore.
Take a look at Python Wiki (Link)
In Built-in Changes part, it is stated that
Removed dict.iteritems(), dict.iterkeys(), and dict.itervalues().
Instead: use dict.items(), dict.... |
Functional Breadth First Search | Functional depth first search is lovely in directed acyclic graphs.
In graphs with cycles however, how do we avoid infinite recursion? In a procedural language I would mark nodes as I hit them, but let's say I can't do that.
A list of visited nodes is possible, but will be slow because using one will result in a linea... | One option is to use inductive graphs, which are a functional way of representing and working with arbitrary graph structures. They are provided by Haskell's fgl library and described in "Inductive Graphs and Funtional Graph Algorithms" by Martin Erwig.
For a gentler introduction (with illustrations!), see my blog pos... |
Padding or truncating a Python list | I'd like to truncate or pad a list. E.g. for size 4:
[1,2,3] -> [1,2,3,0]
[1,2,3,4,5] -> [1,2,3,4]
I can see a couple of ways:
def trp(l, n):
""" Truncate or pad a list """
r = l[:n]
if len(r) < n:
r.extend([0] * (n - len(r)))
return r
Or a shorter, but less efficient:
map(lambda x, y: x if x ... | You can use itertools module to make it completely lazy, like this
>>> from itertools import repeat, chain, islice
>>> def trimmer(seq, size, filler=0):
... return islice(chain(seq, repeat(filler)), size)
...
>>> list(trimmer([1, 2, 3], 4))
[1, 2, 3, 0]
>>> list(trimmer([1, 2, 3, 4, 5], 4))
[1, 2, 3, 4]
Here, we ... |
Interact with celery ongoing task | We have a distributed architecture based on rabbitMQ and Celery.
We can launch in parallel multiple tasks without any issue. The scalability is good.
Now we need to control the task remotely: PAUSE, RESUME, CANCEL.
The only solution we found is to make in the Celery task a RPC call to another task that replies the com... | It look like the Control Bus pattern.
For a better scalability and in order to reduce the RPC call, I recommend to reverse the logic. The PAUSE, RESUME, CANCEL command are push to the Celery tasks through a control bus when the state change occurs. The Celery app will store the current state of the Celery app in a stor... |
Python: openpyxl how to read a cell font color | I have tried to print some_cell.font.color.rgb and got various results.
For some I got what I want (like "FF000000"), but for others it gives me Value must be type 'basetring'. I assume that the latter is because I haven't actually defined the font color for these cells.
I'm using openpyxl 2.2.2
| I think this is a bug in openpyxl and I think you should report it here.
Debugging the following code (with trepan of course):
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
c = ws['A4'] # cell gets created here
print(ws['A4'].font.color)
I get:
Color(rgb=Value must be type 'str', indexed=Value must be... |
Is it possible to modify the behavior of len()? | I'm aware of creating a custom __repr__ or __add__ method (and so on), to modify the behavior of operators and functions. Is there a method override for len?
For example:
class Foo:
def __repr__(self):
return "A wild Foo Class in its natural habitat."
foo = Foo()
print(foo) # A wild Foo Class in i... | Yes, implement the __len__ method:
def __len__(self):
return 42
Demo:
>>> class Foo(object):
... def __len__(self):
... return 42
...
>>> len(Foo())
42
From the documentation:
Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object th... |
Check if argparse optional argument is set or not | I would like to check whether an optional argparse argument has been set by the user or not.
Can I safely check using isset?
Something like this:
if(isset(args.myArg)):
#do something
else:
#do something else
Does this work the same for float / int / string type arguments?
I could set a default parameter and ch... | I think that optional arguments (specified with --) are initialized to None if they are not supplied. So you can test with is not None. Try the example below:
import argparse as ap
def main():
parser = ap.ArgumentParser(description="My Script")
parser.add_argument("--myArg")
args, leftovers = parser.parse_... |
Using both Python 2.x and Python 3.x in IPython Notebook | I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.
I initially had Anaconda. With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started. This is not what I was looking for so I un... | The idea here is to install multiple ipython kernels. Here are instructions for anaconda. If you are not using anaconda, I recently added instructions using pure virtualenvs.
Anaconda 4.1.0
Since version 4.1.0, anaconda includes a special package nb_conda_kernels that detects conda environments with notebook kernels an... |
Installing lxml, libxml2, libxslt on Windows 8.1 | After additional exploration, I found a solution to installing lxml with pip and wheel. Additional comments on approach welcomed.
I'm finding the existing Python documentation for Linux distributions excellent. For Windows... not so much. I've configured my Linux system fine but I need some help getting a Windows 8.1 t... | I was able to fix the installation with the following steps. I hope others find this helpful.
My installation of "pip" was working fine before the problem. I went to the Windows command line and made sure that "wheel" was installed.
C:\Python34>python -m pip install wheel
Requirement already satisfied (use --upgrade to... |
Turning string with embedded brackets into a dictionary | What's the best way to build a dictionary from a string like the one below:
"{key1 value1} {key2 value2} {key3 {value with spaces}}"
So the key is always a string with no spaces but the value is either a string or a string in curly brackets (it has spaces)?
How would you dict it into:
{'key1': 'value1', 'key2': 'val... | import re
x="{key1 value1} {key2 value2} {key3 {value with spaces}}"
print dict(re.findall(r"\{(\S+)\s+\{*(.*?)\}+",x))
You can try this.
Output:
{'key3': 'value with spaces', 'key2': 'value2', 'key1': 'value1'}
Here with re.findall we extract key and its value.re.findall returns a list with tuples of all key,value p... |
open cv error: (-215) scn == 3 || scn == 4 in function cvtColor | I'm currently in Ubuntu 14.04, using python 2.7 and cv2.
When I run this code:
import numpy as np
import cv2
img = cv2.imread('2015-05-27-191152.jpg',0)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
it returns:
File "face_detection.py", line 11, in <module>
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error... | Give the full path of image with forward slash..it solved the error for me. eg.
import numpy as np
import cv2
img = cv2.imread('C:/Python34/images/2015-05-27-191152.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
also if you give 0 in second parameter while loading image using cv2.imread than no need to convert im... |
Returning a String from Rust function to Python | I'm very new to Rust. How would I return a String from a Rust function that can be used in Python?
Here is my Rust implementation:
use std::ffi::CString;
#[no_mangle]
pub extern fn query() -> CString {
let s = CString::new("Hello!").unwrap();
return s;
}
And the Python code that calls it:
from ctypes import c... | The most direct version would be this:
use libc::c_char;
use std::ffi::CString;
use std::mem;
#[no_mangle]
pub extern fn query() -> *mut c_char {
let s = CString::new("Hello!").unwrap();
s.into_raw()
}
Here we return a pointer to a zero-terminated sequence of chars which can be passed to Python's c_char_p. Yo... |
Split string into list in jinja? | I have some variables in a jinja2 template which are strings seperated by a ';'.
I need to use these strings separately in the code.
i.e. the variable is variable1 = "green;blue"
{% list1 = {{ variable1 }}.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
I can split them up before rendering the... | It works with:
{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
|
Pandas error - invalid value encountered | New to Pandas. I downloaded and installed Anaconda. Then I tried running the following code via the Spyder app
import pandas as pd
import numpy as np
train = pd.read_csv('/Users/Ben/Documents/Kaggle/Titanic/train.csv')
train
Although this prints the dataframe as I expected, it also shows these errors
//anaconda/lib... | I have the same error and have decided that it is a bug. It seems to be caused by the presence of NaN values in a DataFrame in Spyder. I have uninstalled and reinstalled all packages and nothing has effected it. NaN values are supported and are completely valid in DataFrames especially if they have a DateTime index.
... |
List with many dictionaries VS dictionary with few lists? | I am doing some exercises with datasets like so:
List with many dictionaries
users = [
{"id": 0, "name": "Ashley"},
{"id": 1, "name": "Ben"},
{"id": 2, "name": "Conrad"},
{"id": 3, "name": "Doug"},
{"id": 4, "name": "Evin"},
{"id": 5, "name": "Florian"},
{"id": 6, "name": "Gerald"}
]
Dictio... | This relates to column oriented databases versus row oriented. Your first example is a row oriented data structure, and the second is column oriented. In the particular case of Python, the first could be made notably more efficient using slots, such that the dictionary of columns doesn't need to be duplicated for every... |
cannot import name GoogleMaps in python | I am using the code below to get the latitude & longitude of an address:
from googlemaps import GoogleMaps
gmaps = GoogleMaps(api_key)
address = 'Constitution Ave NW & 10th St NW, Washington, DC'
lat, lng = gmaps.address_to_latlng(address)
print lat, lng
but am getting the error below
File "C:/Users/Pavan/PycharmProje... | Use geopy instead, no need for api-key.
From their example:
from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.geocode("175 5th Avenue NYC")
print(location.address)
print((location.latitude, location.longitude))
prints:
Flatiron Building, 175, 5th Avenue, Flatiron, New York, NYC, New ... |
Python dictionary as html table in ipython notebook | Is there any (existing) way to display a python dictionary as html table in an ipython notebook. Say I have a dictionary
d = {'a': 2, 'b': 3}
then i run
magic_ipython_function(d)
to give me something like
| You're probably looking for something like ipy_table.
A different way would be to use pandas for a dataframe, but that might be an overkill.
|
How to upload files to another user's Google Drive without asking permission every time? | Is there any way to upload files to another user's Google Drive without asking for login or verification code each time except the first time?
Until now I used pydrive, but it asks to login each time. Is there anyway other than this, such that a key or something to use to skip the login of the user?
| To clarify: you want to enable others to upload files into your own Google Drive? If that is the case, you can do this with this embed widget that you can copy & paste into your website: http://developers.cloudwok.com
If you want to allow users to upload files to a random Google Drive account of some other user, that w... |
What's the deal with Python 3.4, Unicode, different languages and Windows? | Happy examples:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
czech = u'LeoÅ¡ JanáÄek'.encode("utf-8")
print(czech)
pl = u'ZdzisÅaw BeksiÅski'.encode("utf-8")
print(pl)
jp = u'ãªã³ã° å±±æ è²å'.encode("utf-8")
print(jp)
chinese = u'äºè¡'.encode("utf-8")
print(chinese)
MIR = u'ÐаÑина Ð´Ð»Ñ ÐнÐ... | Update: Since Python 3.6, the code example that prints Unicode strings directly should just work now (even without py -mrun).
Python can print text in multiple languages in Windows console whatever chcp says:
T:\> py -mpip install win-unicode-console
T:\> py -mrun your_script.py
where your_script.py prints Unicode di... |
Is it possible to hide Python function arguments in Sphinx? | Suppose I have the following function that is documented in the Numpydoc style, and the documentation is auto-generated with the Sphinx autofunction directive:
def foo(x, y, _hidden_argument=None):
"""
Foo a bar.
Parameters
----------
x: str
The first argument to foo.
y: str
The... | I don't think there is an option for that in Sphinx. One possible way to accomplish this without having to hack into the code, is to use customized signature.
In this case, you need something like:
.. autofunction:: some_module.foo(x, y)
This will override the parameter list of the function and hide the unwanted argum... |
"Firefox quit unexpectedly." when running basic Selenium script in Python | I'm trying to scrape and print the HTML of a page using Selenium in Python, but every time I run it I get the error message
Firefox quit unexpectedly.
I'm new to Selenium, so any help would be greatly appreciated. I'm hoping for the simplest fix possible. Thank you!
My code:
import selenium
from selenium import webdr... | My experience since the upgrade to Firefox 38.x on Windows a couple of weeks back has been that it has a problem with Selenium 2.45.x. When invoking the browser it produces a "Firefox has stopped working" error which I have to close manually, at which point the test runs. Others have reported similar issues.
The soluti... |
sys_platform is not defined x64 Windows | This has been bugging me for a little while. I recently upgraded to x64 Python, and I started getting this error (example pip install).
C:\Users\<uname>\distribute-0.6.35>pip install python-qt
Collecting python-qt
Downloading python-qt-0.50.tar.gz
Building wheels for collected packages: python-qt
Running setup.py b... |
Might be a bug. Check out: https://bugs.python.org/
You can manually check the markers.py file and try to fix it. I think there would a reference to sys_platform that has to be changed to sys.platform
Regarding markerlib, you can try this out-
import markerlib
marker = markerlib.compile("sys.platform == 'win32'")
mark... |
How to check if a value is present in any of given sets | Say I have different sets (they have to be different, I cannot join them as per the kind of data I am working with):
r = set([1,2,3])
s = set([4,5,6])
t = set([7,8,9])
What is the best way to check if a given variable is present in either of them?
I am using:
if myvar in r \
or myvar in s \
or myvar in t:
But I... | You can use builtin any:
r = set([1,2,3])
s = set([4,5,6])
t = set([7,8,9])
if any(myvar in x for x in [r,s,t]):
print "I'm in one of them"
any will short circuit on the first condition that returns True so you can get around constructing a potentially huge union or checking potentially lots of sets for inclusion.... |
get playing wav audio level as output | I want to make a speaking mouth which moves or emits light or something when a playing wav file emits sound. So I need to detect when a wav file is speaking or when it is in a silence between words. Currently I'm using a pygame script that I have found
import pygame
pygame.mixer.init()
pygame.mixer.music.load("my_sente... | You'll need to inspect the WAV file to work out when the voice is present. The simplest way to do this is look for loud and quiet periods. Because sound works with waves, when it's quiet the values in the wave file won't change very much, and when it's loud they'll be changing a lot.
One way of estimating loudness is t... |
Find objects with date and time less then 24 hours from now | I have model with two fields:
class Event(models.Model):
date = models.DateField(_(u'Date'))
time = models.TimeField(_(u'Time'))
I need to find all objects where date&time is in 24 hours from now.
I am able to do this when using DateTime field, but I am not sure how to achieve this when fields are separated. ... | For the simple case (not sure if all are simple cases though...), this should do the trick:
import datetime
today = datetime.datetime.now()
tomorrow = today + datetime.timedelta(days=1)
qs_today = queryset.filter(
date=today.date(),
time__gte=today.time(),
)
qs_tomorrow = queryset.filter(
date=tomorrow.da... |
Using coverage, how do I test this line? | I have a simple test:
class ModelTests(TestCase):
def test_method(self):
instance = Activity(title="Test")
self.assertEqual(instance.get_approved_member_count(), 0)
My problem is that coverage still shows get_approved_member_count line as NOT tested:
How do I satisfy the above for coverage?
To r... | The coverage report shows that the method is being called (line 80 is green). But it also shows that it was never defined (line 75 is red).
This is a classic problem of starting coverage too late. The simplest way to fix this is to use coverage to run your test runner, instead of using the test runner to run coverage... |
Disable hash randomization from within python program | Starting with Python 3.3, the hashing algorithm is non-deterministically salted to avoid a certain kind of attack. This is nice for webservers but it's a pain when trying to debug a program: Every time I run my script, dict contents are iterated in a different order.
Some earlier versions of python had a -R flag for en... | I suspect this isn't possible, unfortunately. Looking at test_hash.py the HashRandomizationTests class and its descendants were added in the commit that introduced this behavior. They test the hashing behavior by modifying the environment and starting a new process with PYTHONHASHSEED explicitly set. You could try t... |
Move models between Django (1.8) apps with required ForeignKey references | This is an extension to this question: How to move a model between two Django apps (Django 1.7)
I need to move a bunch of models from old_app to new_app. The best answer seems to be Ozan's, but with required foreign key references, things are bit trickier. @halfnibble presents a solution in the comments to Ozan's answe... | Migrating a model between apps.
The short answer is, don't do it!!
But that answer rarely works in the real world of living projects and production databases. Therefore, I have created a sample GitHub repo to demonstrate this rather complicated process.
I am using MySQL. (No, those aren't my real credentials).
The Prob... |
What does ,= mean in python? | I wonder what ,= or , = means in python?
Example from matplotlib:
plot1, = ax01.plot(t,yp1,'b-')
| It's a form of tuple unpacking. With parentheses:
(plot1,) = ax01.plot(t,yp1,'b-')
ax01.plot() returns a tuple containing one element, and this element is assigned to plot1. Without that comma (and possibly the parentheses), plot1 would have been assigned the whole tuple. Observe the difference between a and b in the ... |
Why does `mylist[:] = reversed(mylist)` work? | The following reverses a list "in-place" and works in Python 2 and 3:
>>> mylist = [1, 2, 3, 4, 5]
>>> mylist[:] = reversed(mylist)
>>> mylist
[5, 4, 3, 2, 1]
Why/how? Since reversed gives me an iterator and doesn't copy the list beforehand, and since [:]= replaces "in-place", I am surprised. And the following, also u... | CPython list slice assigment will convert the iterable to a list first by calling PySequence_Fast. Source: https://hg.python.org/cpython/file/7556df35b913/Objects/listobject.c#l611
v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Even PyPy does something similar:
def setslice__List_ANY_ANY_ANY(space, w_l... |
How not to miss the next element after itertools.takewhile() | Say we wish to process an iterator and want to handle it by chunks.
The logic per chunk depends on previously-calculated chunks, so groupby() does not help.
Our friend in this case is itertools.takewhile():
while True:
chunk = itertools.takewhile(getNewChunkLogic(), myIterator)
process(chunk)
The problem i... | takewhile() indeed needs to look at the next element to determine when to toggle behaviour.
You could use a wrapper that tracks the last seen element, and that can be 'reset' to back up one element:
_sentinel = object()
class OneStepBuffered(object):
def __init__(self, it):
self._it = iter(it)
self... |
Is filter thread-safe | I have a thread which is updating a list called l. Am I right in saying that it is thread-safe to do the following from another thread?
filter(lambda x: x[0] == "in", l)
If its not thread safe, is this then the correct approach:
import threading
import time
import Queue
class Logger(threading.Thread):
def __init... | First, to answer your question in the title: filter is just a function. Hence, its thread-safety will rely on the data-structure you use it with.
As pointed out in the comments already, list operations themselves are thread-safe in CPython and protected by the GIL, but that is arguably only an implementation detail of ... |
Flask and React routing | I'm building the Flask app with React, I ended up having a problem with routing.
The backend is responsible to be an API, hence some routes look like:
@app.route('/api/v1/do-something/', methods=["GET"])
def do_something():
return something()
and the main route which leads to the React:
@app.route('/')
def index()... | We used catch-all URLs for this.
from flask import Flask
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return 'You want path: %s' % path
if __name__ == '__main__':
app.run()
You can also go an extra mile and reuse the Flask routing system to matc... |
Python List Slicing with None as argument | Via trial and error I found out that
my_list = range(10)
my_list[:None] == my_list[:]
I use this for django query sets so I can define a size or take all:
some_queryset[:length if length else None]
# @IanAuld
some_queryset[:length or None]
# @Bakuriu
# length works for all numbers and None if you want all elements
... | Yes, it is fine to use None, as its behavior is specified by the documentation:
The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or eq... |
No such file or directory "limits.h" when installing Pillow on Alpine Linux | I'm running alpine-linux on a Raspberry Pi 2. I'm trying to install Pillow via this command:
pip install pillow
This is the output from the command:
Installing collected packages: pillow
Running setup.py install for pillow
Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp... | Alpine linux uses musl libc. You probably need to install musl-dev.
|
Pycharm Django Debugging is really slow | I have a moderate size website but it takes about 30 seconds for PyCharm to start Runserver and be ready to run the app. If I "Run" the app instead of "Debugging" it will only take about 3 seconds to start.
What are some of the things I can do speed up the code change and debugging cycle.
I am using a decent MBP with ... | Well, the debugger is just slow and there is not much you can do about it. Just don't use the debugger unless you absolutely need it (i.e. you are troubleshooting a particularly elusive bug).
I can think of only one thing that may speed up the PyCharm's debugger and that is to turn off the "Collect run-time types infor... |
Writing to MySQL database with pandas using SQLAlchemy, to_sql | trying to write pandas dataframe to MySQL table using to_sql. Previously been using flavor='mysql', however it will be depreciated in the future and wanted to start the transition to using SQLAlchemy engine.
sample code:
import pandas as pd
import mysql.connector
from sqlalchemy import create_engine
engine = create_e... | Using the engine in place of the raw_connection() worked:
import pandas as pd
import mysql.connector
from sqlalchemy import create_engine
engine = create_engine('mysql+mysqlconnector://[user]:[pass]@[host]:[port]/[schema]', echo=False)
data.to_sql(name='sample_table2', con=engine, if_exists = 'append', index=False)
n... |
django countries encoding is not giving correct name | I am using django_countries module for countries list, the problem is there are couple of countries with special characters like 'Ã
land Islands' and 'Saint Barthélemy'.
I am calling this method to get the country name:
country_label = fields.Country(form.cleaned_data.get('country')[0:2]).name
I know that country_lab... | Django stores unicode string using code points and identifies the string as unicode for further processing.
UTF-8 uses four 8-bit bytes encoding, so the unicode string that's being used by Django needs to be decoded or interpreted from code point notation to its UTF-8 notation at some point.
In the case of Ã
land Isl... |
How to reshape a networkx graph in Python? | So I created a really naive (probably inefficient) way of generating hasse diagrams.
Question:
I have 4 dimensions... p q r s .
I want to display it uniformly (tesseract) but I have no idea how to reshape it. How can one reshape a networkx graph in Python?
I've seen some examples of people using spring_layout() and ... | This is a pragmatic, rather than purely mathematical answer.
I think you have two issues - one with layout, the other with your network.
1. Network
You have too many edges in your network for it to represent the unit tesseract. Caveat I'm not an expert on the maths here - just came to this from the plotting angle (matp... |
A + B without arithmetic operators, Python vs C++ | I was trying to solve an old question:
Write a function that add two [integer] numbers A and B. You should not use + or any arithmetic operators.
The best solution is like this, quoted from "LintCode-A+B Problem":
For a + b in any base, we can treat the plus as two part: 1. a + b without carry; 2. the carry generate... | The binary, 2's complement representation of -4 is
...11100
Yes, I really do mean infinitely many 1's to the left; this is a binary repeating numeral. Technically, 4 is a repeating numeral too:
...00100
it's just repeating 0's to the left.
Your addition problem is
...11100
+ ...00100
--------------------
...00... |
How to use jinja2 as a templating engine in Django 1.8 | I have been looking on how to use jinja2 in django 1.8, but there is no complete source for using django with jinja2. I was wondering if you guys knew the process for using jinja2 in django. I have looked through the the official documentation and I have looked at the following question: How to setup django 1.8 to use ... | Frist you have to install jinja2:
$ pip install Jinja2
Then modify your TEMPLATES list in the settings.py to contain the jinja2 BACKEND :
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [os.path.join(BASE_DIR, 'templates/jinja2')],
'APP_DIRS': True,
'OP... |
Which Model Field to use in Django to store longitude and latitude values? | I want to store my users location using longitude and latitude, at the moment this comes from Google Maps, but I will be using GeoDango and some point to work out distances between to points also.
However, my first confusion is which field in Django I should be using to store the longitude and latitude values? The inf... | Float is generally an approximation, see here for some simple examples. You could get very nice results modifying your model to something like DecimalField(max_digits=9, decimal_places=6), since decimals are very important in coordinates but using more than 6 is basically meaningless.
|
Python: What is the difference between math.exp and numpy.exp and why do numpy creators choose to introduce exp again | exp means exponential function
exp in math module: https://docs.python.org/2/library/math.html
exp in numpy module: http://docs.scipy.org/doc/numpy/reference/generated/numpy.exp.html
Why do numpy creators introduce this function again?
| The math.exp works only for scalars as EdChum mentions. Whereas numpy.exp will work for arrays.
Example:
>>> import math
>>> import numpy as np
>>> x = [1.,2.,3.,4.,5.]
>>> math.exp(x)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
math.exp(x)
TypeError: a float is required
>>> np.e... |
Are these two python statements the same? | I have these two statements
return self.getData() if self.getData() else ''
and
return self.getData() or ''
I want to know are they same or there is any difference
| I would say No because if self.getData() changes something during its operation, then the first statement has the possibility of returning a different result since it will make a 2nd call to it.
|
How to filter objects for count annotation in Django? | Consider simple Django models Event and Participant:
class Event(models.Model):
title = models.CharField(max_length=100)
class Participant(models.Model):
event = models.ForeignKey(Event, db_index=True)
is_paid = models.BooleanField(default=False, db_index=True)
It's easy to annotate events query with tota... | Just discovered that Django 1.8 has new conditional expressions feature, so now we can do like this:
events = Event.objects.all().annotate(paid_participants=models.Sum(
models.Case(
models.When(participant__is_paid=True, then=1),
default=0, output_field=models.IntegerField()
)))
|
How to add any new library like spark-csv in Apache Spark prebuilt version | I have build the Spark-csv and able to use the same from pyspark shell using the following command
bin/spark-shell --packages com.databricks:spark-csv_2.10:1.0.3
error getting
>>> df_cat.save("k.csv","com.databricks.spark.csv")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ab... | At the time I used spark-csv, I also had to download commons-csv jar (not sure it is still relevant). Both jars where in the spark distribution folder.
I downloaded the jars as follow:
wget http://search.maven.org/remotecontent?filepath=org/apache/commons/commons-csv/1.1/commons-csv-1.1.jar -O commons-csv-1.1.jar<br/>... |
What's the correct way to clean up after an interrupted event loop? | I have an event loop that runs some co-routines as part of a command line tool. The user may interrupt the tool with the usual Ctrl + C, at which point I want to clean up properly after the interrupted event loop.
Here's what I tried.
import asyncio
@asyncio.coroutine
def shleepy_time(seconds):
print("Shleeping f... | When you CTRL+C, the event loop gets stopped, so your calls to t.cancel() don't actually take effect. For the tasks to be cancelled, you need to start the loop back up again.
Here's how you can handle it:
import asyncio
@asyncio.coroutine
def shleepy_time(seconds):
print("Shleeping for {s} seconds...".format(s=sec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.