instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has...
I had used home-brew to install 2.7 on OS X 10.10 and the new install was missing the sym links. I ran brew link --overwrite python as mentioned in How to symlink python in Homebrew? and it solved the problem.
Stop Django from creating migrations if the list of choices of a field changes
I have a django core app called "foocore". There are several optional pluging-like apps. For example "superfoo". In my case every plugin adds a new choice in a model CharField which belongs to "foocore". Django migrations detect changes if the list of choices get changed. I think this is not necessary. At least one oth...
See this bug report and discussion for more info: https://code.djangoproject.com/ticket/22837 The proposed solution was to use a callable as the argument for choices, but it appears this has not been executed for fields but for forms only. If you really need dynamic choices than a ForeignKey is the best solution. An al...
How does python "know" what to do with the "in" keyword?
I'm a bit bewildered by the "in" keyword in python. If I take a sample list of tuples: data = [ (5, 1, 9.8385465), (10, 1, 8.2087544), (15, 1, 7.8788187), (20, 1, 7.5751283) ] I can do two different "for - in" loops and get different results: for G,W,V in data: print G,W,V This prints each set of ...
According to the for compound statement documentation: Each item in turn is assigned to the target list using the standard rules for assignments... Those "standard rules" are in the assignment statement documentation, specifically: Assignment of an object to a target list is recursively defined as follows. If t...
Python 2.7: round number to nearest integer
I've been trying to round long float numbers like: 32.268907563; 32.268907563; 31.2396694215; 33.6206896552; ... With no success so far. I tried math.ceil(x) , math.floor(x) (although that would round up or down, which is not what I'm looking for) and round(x) which didn't work either (still float numbers). What could...
int(round(x)) Will round it and change it to integer EDIT: You are not assigning int(round(h)) to any variable. When you call int(round(h)), it returns the integer number but does nothing else; you have to change that line for: h = int(round(h)) To assign the new value to h
Classifying Python array by nearest "seed" region?
I have a raster of ecological habitats which I've converted into a two-dimensional Python numpy array (example_array below). I also have an array containing "seed" regions with unique values (seed_array below) which I'd like to use to classify my habitat regions. I'd like to 'grow' my seed regions 'into' my habitat reg...
You can use watershed segmentation from scikits-image: Distance transform from scipy import ndimage as nd distance = nd.distance_transform_edt(example_array) Watershed segmentation from skimage.morphology import watershed, square result = watershed(-distance, seed_array, mask=example_array, \ conn...
What's the best way to share Jupyter notebooks with non-programmers?
I am trying to wrap my head around what I can/cannot do with Jupyter. I have a Jupyter server running on our internal server, accessible via VPN and password protected. I am the only one actually creating notebooks but I would like to make some notebooks visible to other team members in a read-only way. Ideally I coul...
The "best" way to share a Jupyter notebook is to simply to place it on GitHub (and view it directly) or some other public link and use the Jupyter Notebook Viewer. When privacy is more of an issue then there are alternatives but it's certainly more complex, there's no built in way to do this in Jupyter alone but a coup...
Pandas DataFrame: How to natively get minimum across range of rows and columns
I have a Pandas DataFrame that looks similar to this but with 10,000 rows and 500 columns. For each row, I would like to find the minimum value between 3 days ago at 15:00 and today at 13:30. Is there some native numpy way to do this quickly? My goal is to be able to get the minimum value for each row by saying some...
You can first stack the DataFrame to create a series and then index slice it as required and take the min. For example: first, last = ('2011-01-07', datetime.time(15)), ('2011-01-10', datetime.time(13, 30)) df.stack().loc[first: last].min() The result of df.stack is a Series with a MultiIndex where the inner level is ...
Why are .pyc files created on import?
I've seen several resources describing what .pyc files are and when they're created. But now I'm wondering why they're created when .py files are imported? Also, why not create a .pyc file for the main Python file doing the importing? I'm guessing it has to do with performance optimization and learning this has encoura...
Python source code is compiled to bytecode, and it is the bytecode that is run. A .pyc file contains a copy of that bytecode, and by caching that Python doesn't have to re-compile the Python code each time it needs to load the module. You can get an idea of how much time is saved by timing the compile() function: >>> i...
"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)
I'm trying to install Scrapy Python framework in OSX 10.11 (El Capitan) via pip. The installation script downloads the required modules and at some point returns the following error: OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib...
pip install --ignore-installed six Would do the trick. Source: github.com/pypa/pip/issues/3165
Why is 'a' in ('abc') True while 'a' in ['abc'] is False?
When using the interpreter, the expression 'a' in ('abc') returns True, while 'a' in ['abc'] returns False. Can somebody explain this behaviour?
('abc') is the same as 'abc'. 'abc' contains the substring 'a', hence 'a' in 'abc' == True. If you want the tuple instead, you need to write ('abc', ). ['abc'] is a list (containing a single element, the string 'abc'). 'a' is not a member of this list, so 'a' in ['abc'] == False
Interactive plots placement in ipython notebook widget
I've got two plots which I'd like to make interactive with ipython notebook widgets. The code below is a simplified sample of what I'm trying to do. import matplotlib.pyplot as plt import IPython.html.widgets as wdg def displayPlot1(rngMax = 10): plt.figure(0) plt.plot([x for x in range(0, rngMax)]) wdg1 = wd...
IPython Notebook displays widgets before any output. One thing you can do is to place your plots inside an HTML widget. This can be placed in any position relative to other widgets. If you do this however, you need to explicitly need to place your plot within the HTML widget. This can be a bit tricky, but a quick solut...
Why is string's startswith slower than in?
Surprisingly, I find startswith is slower than in: In [10]: s="ABCD"*10 In [11]: %timeit s.startswith("XYZ") 1000000 loops, best of 3: 307 ns per loop In [12]: %timeit "XYZ" in s 10000000 loops, best of 3: 81.7 ns per loop As we all know, the in operation needs to search the whole string and startswith just needs to...
As already mentioned in the comments, if you use s.__contains__("XYZ") you get a result that is more similar to s.startswith("XYZ") because it needs to take the same route: Member lookup on the string object, followed by a function call. This is usually somewhat expensive (not enough that you should worry about of cour...
Boto3 to download all files from a S3 Bucket
I'm using boto3 to get files from s3 bucket. I need a similar functionality like aws s3 sync My current code is #!/usr/bin/python import boto3 s3=boto3.client('s3') list=s3.list_objects(Bucket='my_bucket_name')['Contents'] for key in list: s3.download_file('my_bucket_name', key['Key'], key['Key']) This is working ...
I got the same needs and create the following function that download recursively the files. The directories are created locally only if they contain files. import boto3 import os def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'): paginator = client.get_paginator('list_objects') for r...
How to convert dictionary values to int in Python?
I have a program that returns a set of domains with ranks like so: ranks = [ {'url': 'example.com', 'rank': '11,279'}, {'url': 'facebook.com', 'rank': '2'}, {'url': 'google.com', 'rank': '1'} ] I'm trying to sort them by ascending rank with sorted: results = sorted(ranks,key=itemgetter("rank")) However, s...
You are almost there. You need to convert the picked values to integers after replacing ,, like this results = sorted(ranks, key=lambda x: int(x["rank"].replace(",", ""))) For example, >>> ranks = [ ... {'url': 'example.com', 'rank': '11,279'}, ... {'url': 'facebook.com', 'rank': '2'}, ... {'url': 'google....
Plot a (polar) color wheel based on a colormap using Python/Matplotlib
I am trying to create a color wheel in Python, preferably using Matplotlib. The following works OK: import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt xval = np.arange(0, 2*pi, 0.01) yval = np.ones_like(xval) colormap = plt.get_cmap('hsv') norm = mpl.colors.Normalize(0.0, 2*np.pi) ax = plt.s...
One way I have found is to produce a colormap and then project it onto a polar axis. Here is a working example - it includes a nasty hack, though (clearly commented). I'm sure there's a way to either adjust limits or (harder) write your own Transform to get around it, but I haven't quite managed that yet. I thought ...
Localhost Endpoint to DynamoDB Local with Boto3
Although Amazon provides documentation regarding how to connect to dynamoDB local with Java, PHP and .Net, there is no description of how to connect to localhost:8000 using Python. Existing documentation on the web points to the use of the DynamoDBConnection method inside boto.dynamodb2.layer1, but this creates an inco...
It does support DynamoDB Local. You just need to set the appropriate endpoint such as you can do with other language SDKs Here is a code snippet of how you can use boto3's client and resource interface via DynamoDB Local: import boto3 # For a Boto3 client. ddb = boto3.client('dynamodb', endpoint_url='http://localhost:...
How to limit python traceback to specific files
I write a lot of Python code that uses external libraries. Frequently I will write a bug, and when I run the code I get a big long traceback in the Python console. 99.999999% of the time it's due to a coding error in my code, not because of a bug in the package. But the traceback goes all the way to the line of erro...
In order to print your own stacktrace, you would need to handle all unhandled exceptions yourself; this is how the sys.excepthook becomes handy. The signature for this function is sys.excepthook(type, value, traceback) and its job is: This function prints out a given traceback and exception to sys.stderr. So as long ...
Django and Dropzone.js
When I upload files with dropzone it adds them to the database, but they don't have a file, just an ID and creation date. I think the view is the problem but I've tried tons of stuff and I can't figure it out. See my edit below for a more detailed account. Here is the view @login_required(login_url='/dashboard-login/'...
I'm working with Dropzone and Django myself for creating Image objects for each file uploaded, which seems to be akin to what you want to do. I'd like to point out some things that I've experienced and show you how I'm doing it to see if that helps. What you need The things that you need in order to create a record in...
Start IPython notebook server without running web browser?
I would like to use Emacs as main editor for ipython notebooks (with package ein). I want to ask you if there is a way to run the server without the need to open a web browser.
Is this what you want? $ ipython notebook --no-browser
Python string formatting with percent sign
I am trying to do exactly the following: >>> x = (1,2) >>> y = 'hello' >>> '%d,%d,%s' % (x[0], x[1], y) '1,2,hello' However, I have a long x, more than two items, so I tried: >>> '%d,%d,%s' % (*x, y) but it is syntax error. What would be the proper way of doing this without indexing like the first example?
str % .. accepts a tuple as a right-hand operand, so you can do the following: >>> x = (1, 2) >>> y = 'hello' >>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')` '1,2,hello' Your try should work in Python 3. where Additional Unpacking Generalizations is supported, but not in Python 2.x: >>> '%d,%d,%s'...
IPython notebook won't read the configuration file
I used the following command to initialize a profile: ipython profile create myserver Added thses lines to ~/.ipython/profile_myserver/ipython_notebook_config.py: c = get_config() c.NotebookApp.ip = '*' c.NotebookApp.port = 8889 Tried starting the notebook with: ipython notebook --profile=myserver --debug It does no...
IPython has now moved to version 4.0, which means that if you are using it, it will be reading its configuration from ~/.jupyter, not ~/.ipython. You have to create a new configuration file with jupyter notebook --generate-config and then edit the resulting ~/.jupyter/jupyter_notebook_config.py file according to your ...
Open S3 object as a string with Boto3
I'm aware that with Boto 2 it's possible to open an S3 object as a string with: get_contents_as_string() http://boto.readthedocs.org/en/latest/ref/file.html?highlight=contents%20string#boto.file.key.Key.get_contents_as_string Is there an equivalent function in boto3 ?
This isn't in the boto3 documentation. This worked for me: object.get()["Body"].read() object being an s3 object: http://boto3.readthedocs.org/en/latest/reference/services/s3.html#object
numpy array, difference between a /= x vs. a = a / x
I'm using python 2.7.3, when I execute the following piece of code: import numpy as np a = np.array([[1,2,3],[4,5,6]]) a = a / float(2**16 - 1) print a This will result in he following output: >> array([[1.52590219e-05, 3.05180438e-05, 4.57770657e-05], >> [6.10360876e-05, 7.62951095e-05, 9.15541314e-05]]) Exac...
From the documentation: Warning: In place operations will perform the calculation using the precision decided by the data type of the two operands, but will silently downcast the result (if necessary) so it can fit back into the array. Therefore, for mixed precision calculations, A {op}= B can be different than A = A ...
Replace single quotes with double with exclusion of some elements
I want to replace all single quotes in the string with double with the exception of occurrences such as "n't", "'ll", "'m" etc. input="the stackoverflow don\'t said, \'hey what\'" output="the stackoverflow don\'t said, \"hey what\"" Code 1:(@https://stackoverflow.com/users/918959/antti-haapala) def convert_regex(text)...
First attempt You can also use this regex: (?:(?<!\w)'((?:.|\n)+?'?)'(?!\w)) DEMO IN REGEX101 This regex match whole sentence/word with both quoting marks, from beginning and end, but also campure the content of quotation inside group nr 1, so you can replace matched part with "\1". (?<!\w) - negative lookbehind for ...
Spline with constraints at border
I have measured data on a three dimensional grid, e.g. f(x, y, t). I want to interpolate and smooth this data in the direction of t with splines. Currently, I do this with scipy.interpolate.UnivariateSpline: import numpy as np from scipy.interpolate import UnivariateSpline # data is my measured data # data.shape is (l...
The best thing I can think of is to do a minimization with a constraint with scipy.optimize.minimize. It is pretty easy to take the derivative of a spline, so the constraint is simply. I would use a regular spline fit (UnivariateSpline) to get the knots (t), and hold the knots fixed (and degree k, of course), and vary ...
Exiting Python Debugger ipdb
I use ipdb fairly often in a way to just jump to a piece of code that is isolated i.e. it is hard to write a real script that uses it. Instead I write a minimal test case with mocking and jump into it. Exemplary for the workflow: def func(): ... import ipdb ipdb.set_trace() ... def test_case(): ... ...
I put the following in my .pdbrc import os alias kk os.system('kill -9 %d' % os.getpid()) kk kills the debugger and (the process that trigger the debugger).
Compact way of writing (a + b == c or a + c == b or b + c == a)
Is there a more compact or pythonic way to write the boolean expression a + b == c or a + c == b or b + c == a I came up with a + b + c in (2*a, 2*b, 2*c) but that is a little strange.
If we look at the Zen of Python, emphasis mine: The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren'...
Can't install virtualenvwrapper on OSX 10.11 El Capitan
I recently wiped my Mac and reinstalled OSX El Capitan public beta 3. I installed pip with sudo easy_install pip and installed virtualenv with sudo pip install virtualenv and did not have any problems. Now, when I try to sudo pip install virtualenvwrapper, I get the following: Users-Air:~ User$ sudo pip install virtual...
You can manually install the dependencies that don't exist on a stock 10.11 install, then install the other packages with --no-deps to ignore the dependencies. That way it will skip six (and argparse which is also already installed). This works on my 10.11 beta 6 install: sudo pip install pbr sudo pip install --no-deps...
Python Gaussian Kernel density calculate score for new values
this is my code: import numpy as np from scipy.stats.kde import gaussian_kde from scipy.stats import norm from numpy import linspace,hstack from pylab import plot,show,hist import re import json attribute_file="path" attribute_values = [line.rstrip('\n') for line in open(attribute_file)] obs=[] #Assume the list ob...
The reason for that is that you have many more 1's in your observations than 768's. So even if -1 is not exactly 1, it gets a high predicted value, because the histogram has a much larger larger value at 1 than at 768. Up to a multiplicative constant, the formula for prediction is: where K is your kernel, D your obser...
Why is math.floor(x/y) != x // y for two evenly divisible floats in Python?
I have been reading about division and integer division in Python and the differences between division in Python2 vs Python3. For the most part it all makes sense. Python 2 uses integer division only when both values are integers. Python 3 always performs true division. Python 2.2+ introduced the // operator for intege...
I didn't find the other answers satisfying. Sure, .1 has no finite binary expansion, so our hunch is that representation error is the culprit. But that hunch alone doesn't really explain why math.floor(.5/.1) yields 5.0 while .5 // .1 yields 4.0. The punchline is that a // b is actually doing floor((a - (a % b))/b), as...
Python Assignment Operator Precedence - (a, b) = a[b] = {}, 5
I saw this Python snippet on Twitter and was quite confused by the output: >>> a, b = a[b] = {}, 5 >>> a {5: ({...}, 5)} What is going on here?
From the Assignment statements documentation: An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. You have two assignment ta...
yield in list comprehensions and generator expressions
The following behaviour seems rather counterintuitive to me (Python 3.4): >>> [(yield i) for i in range(3)] <generator object <listcomp> at 0x0245C148> >>> list([(yield i) for i in range(3)]) [0, 1, 2] >>> list((yield i) for i in range(3)) [0, None, 1, None, 2, None] The intermediate values of the last line are actual...
Generator expressions, and set and dict comprehensions are compiled to (generator) function objects. In Python 3, list comprehensions get the same treatment; they are all, in essence, a new nested scope. You can see this if you try to disassemble a generator expression: >>> dis.dis(compile("(i for i in range(3))", '', ...
pyautogui.locateCenterOnScreen() returns None instead of coordinates
import pyautogui print (pyautogui.locateCenterOnScreen("C:\Users\Venkatesh_J\PycharmProjects\mouse_event\mouse_event.png")) Instead of returning coordinates, it returns None.
Seems like it couldn't find anything matching your image on the screen. locateCenterOnScreen(image, grayscale=False) - Returns (x, y) coordinates of the center of the first found instance of the image on the screen. Returns None if not found on the screen.
Python Multiple Assignment Statements In One Line
(Don't worry, this isn't another question about unpacking tuples.) In python, a statement like foo = bar = baz = 5 assigns the variables foo, bar, and baz to 5. It assigns these variables from left to right, as can be proved by nastier examples like >>> foo[0] = foo = [0] Traceback (most recent call last): File "<st...
All credit goes to @MarkDickinson, who answered this in a comment: Notice the + in (target_list "=")+, which means one or more copies. In foo = bar = 5, there are two (target_list "=") productions, and the expression_list part is just 5 All target_list productions (i.e. things that look like foo =) in an assignment s...
How can I efficiently read and write files that are too large to fit in memory?
I am trying to calculate the cosine similarity of 100,000 vectors, and each of these vectors has 200,000 dimensions. From reading other questions I know that memmap, PyTables and h5py are my best bets for handling this kind of data, and I am currently working with two memmaps; one for reading the vectors, the other for...
Memory maps are exactly what the name says: mappings of (virtual) disk sectors into memory pages. The memory is managed by the operating system on demand. If there is enough memory, the system keeps parts of the files in memory, maybe filling up the whole memory, if there is not enough left, the system may discard page...
Best practices for turning jupyter notebooks into python scripts
Jupyter (iPython) notebook is deservedly known as a good tool for prototyping the code and doing all kinds of machine learning stuff interactively. But when I use it, I inevitably run into the following: the notebook quickly becomes too complex and messy to be maintained and improved further as notebook, and I have to...
We are having the similar issue. However we are using several notebooks for prototyping the outcomes which should become also several python scripts after all. Our approach is that we put aside the code, which seams to repeat across those notebooks. We put it into the python module, which is imported by each notebook a...
Finding the "best" combination for a set
I have a set, sentences, which contains sentences from the English language in the form of strings. I wish to create a subset of sentences, sentences2, which contains sentences containing only 20 unique words. Of course, there are many, many such subsets, but I'm looking for the "best" one and by "best" I mean that sub...
Disclaimer: You have not specified data characteristics, so my answer will assume that it is not too large(more than 1,000,000 sentences, each at most 1,000). Also Description is a bit complicated and I might have not understood the problem fully. Solution: Instead of focusing on different combinations, why don't you...
Why can a floating point dictionary key overwrite an integer key with the same value?
I'm working through http://www.mypythonquiz.com, and question #45 asks for the output of the following code: confusion = {} confusion[1] = 1 confusion['1'] = 2 confusion[1.0] = 4 sum = 0 for k in confusion: sum += confusion[k] print sum The output is 6, since the key 1.0 replaces 1. This feels a bit dangerous to...
First of all: the behaviour is documented explicitly in the docs for the hash function: hash(object) Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash val...
Why does this Jython loop fail after a single run?
I've got the following code: public static String getVersion() { PythonInterpreter interpreter = new PythonInterpreter(); try { interpreter.exec(IOUtils.toString(new FileReader("./Application Documents/Scripts/Version.py"))); PyObject get_version = interpreter.get("get_latest_version"); ...
The python library urllib2, which you use, uses Netty. Netty has a problem, which is widely known: Hopper: java.util.concurrent.RejectedExecutionException: event executor terminated Error recurrent : DefaultPromise Failed to notify a listener. Event loop shut down? Calling HttpClient.shutdown() causes problem to later...
How to save a Seaborn plot into a file
I tried the following code (test_seaborn.py): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt matplotlib.style.use('ggplot') import seaborn as sns sns.set() df = sns.load_dataset('iris') sns_plot = sns.pairplot(df, hue='species', size=2.5) fig = sns_plot.get_figure() fig.savefig("output.png") #s...
Remove the get_figure and just use sns_plot.savefig('output.png') df = sns.load_dataset('iris') sns_plot = sns.pairplot(df, hue='species', size=2.5) sns_plot.savefig("output.png")
Complexity of len() with regard to sets and lists
The complexity of len() with regards to sets and lists is equally O(1). How come it takes more time to process sets? ~$ python -m timeit "a=[1,2,3,4,5,6,7,8,9,10];len(a)" 10000000 loops, best of 3: 0.168 usec per loop ~$ python -m timeit "a={1,2,3,4,5,6,7,8,9,10};len(a)" 1000000 loops, best of 3: 0.375 usec per loop I...
Firstly, you have not measured the speed of len(), you have measured the speed of creating a list/set together with the speed of len(). Use the --setup argument of timeit: $ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "len(a)" 10000000 loops, best of 3: 0.0369 usec per loop $ python -m timeit --setup "a={1,2,3,...
Installing iPython: "ImportError cannot import name path"?
I'm trying to install IPython. I have run pip install ipython[notebook] without any errors, but now I get this: $ ipython notebook Traceback (most recent call last): File "/Users/me/.virtualenvs/.venv/bin/ipython", line 7, in <module> from IPython import start_ipython File "/Users/me/.virtualenvs/.venv/lib/pyth...
Looks like this is a known issue, caused by a change in the path.py package. Reverting to an older version of path.py solves this : sudo pip3 install -I path.py==7.7.1
How to interactively display and hide lines in a Bokeh plot?
It would be nice to be able to interactively display and hide lines in a bokeh plot. Say, I have created my plot something like this: from bokeh.plotting import output_file, figure, show from numpy.random import normal, uniform meas_data_1 = normal(0, 1, 100) meas_data_2 = uniform(-0.5, 0.5, 100) output_file("myplot....
This appears on track to be implemented at some point as interactive legends: https://github.com/bokeh/bokeh/issues/3715 Currently (v0.12.1), there is an example that uses CustomJS on checkboxes to achieve this: https://github.com/bokeh/bokeh/pull/4868 Relevant code: import numpy as np from bokeh.io import output_file...
Why is bytearray not a Sequence in Python 2?
I'm seeing a weird discrepancy in behavior between Python 2 and 3. In Python 3 things seem to work fine: Python 3.5.0rc2 (v3.5.0rc2:cc15d736d860, Aug 25 2015, 04:45:41) [MSC v.1900 32 b it (Intel)] on win32 >>> from collections import Sequence >>> isinstance(bytearray(b"56"), Sequence) True But not in Python 2: Python...
Abstract classes from collections use ABCMeta.register(subclass) to Register subclass as a “virtual subclass” of this ABC. In Python 3 issubclass(bytearray, Sequence) returns True because bytearray is explicitly registered as a subclass of ByteString (which is derived from Sequence) and MutableSequence. See the r...
Could not find a version that satisfies the requirement
I'm installing several Python packages in Ubuntu 12.04 using the following requirements.txt file: numpy>=1.8.2,<2.0.0 matplotlib>=1.3.1,<2.0.0 scipy>=0.14.0,<1.0.0 astroML>=0.2,<1.0 scikit-learn>=0.14.1,<1.0.0 rpy2>=2.4.3,<3.0.0 and these two commands: $ pip install --download=/tmp -r requirements.txt $ pip install --...
This approach (having all dependencies in a directory and not downloading from an index) only works when the directory contains all packages. The directory should therefore contain all dependencies but also all packages that those dependencies depend on (e.g., six, pytz etc). You should therefore manually include these...
What is the difference between the AWS boto and boto3
I'm new to AWS using Python and I'm trying to learn the boto API however I notice there are two major versions/packages for Python. That would be boto, and boto3. I haven't been able to find an article with the major advantages/disadvantages or differences between these packages.
The boto package is the hand-coded Python library that has been around since 2006. It is very popular and is fully supported by AWS but because it is hand-coded and there are so many services available (with more appearing all the time) it is difficult to maintain. So, boto3 is a new version of the boto library based ...
Numpy item faster than operator[]
I have a following code in python that at least for me produces strange results: import numpy as np import timeit a = np.random.rand(3,2) print timeit.timeit('a[2,1] + 1', 'from __main__ import a', number=1000000) print timeit.timeit('a.item((2,1)) + 1', 'from __main__ import a', number=1000000) This gives the resul...
In this case, they don't return quite the same thing. a[2,1] returns a numpy.float64, while a.item((2,1)) returns a native python float. Native vs numpy scalars (float, int, etc) A numpy.float64 scalar isn't quite identical to a native python float (they behave identically, however). Simple operations on a single e...
How to use the same line of code in all functions?
I am newbie in Python. I wonder if it is possible that all functions inherit the same line of code? with open(filename, 'r') as f: as this line of code is the same in all three functions. Is it possible to inherit the code without using classes? I tried to find the answer on stackoverflow and python documentation, bu...
The common code in your case is with open(filename, 'r') as f: contents = f.read() So just move it to its own function: def get_file_contents(filename): with open(filename, 'r') as f: return f.read() def word_count(filename): return len(get_file_contents(filename).split()) def line_count(filename...
Using Spyder IDE, how do you return from "goto definition"?
Description of the problem: I like to jump around code a lot with the keyboard but I am hitting a wall of usability in Spyder IDE. I can use the "goto definition" feature to jump to the definition of some function but then I can't go back to where my cursor was (so it takes a while to manually find where I was before b...
Spyder have a one strange bug. Shortcut "Previous cursor position" only work if "Source toolbar" is present. Turn on "View -> Toolbars -> Source toolbar". You can try it.
How to Include image or picture in jupyter notebook
I would like to include image in a jupyter notebook. If I did the following, it works : from IPython.display import Image Image("img/picture.png") But I would like to include the images in a markdown cell and the following code gives a 404 error : ![title]("img/picture.png") I also tried ![texte]("http://localhost:88...
You mustn't use quotation marks around the name of the image files in markdown! If you carefully read your error message, you will see the two %22 parts in the link. That is the html encoded quotation mark. You have to change the line ![title]("img/picture.png") to ![title](img/picture.png)
Precision difference when printing Python and C++ doubles
I'm currently marvelling over this: C++ 11 #include <iostream> #include <iomanip> #include <limits> int main() { double d = 1.305195828773568; std::cout << std::setprecision(std::numeric_limits<double>::max_digits10) << d << std::endl; // Prints 1.3051958287735681 } Python >>> repr(1.305195828773568) '1.305195...
you can force python to print the 1 as well (and many more of the following digits): print('{:.16f}'.format(1.305195828773568)) # -> 1.3051958287735681 from https://docs.python.org/2/tutorial/floatingpoint.html: >>> 7205759403792794 * 10**30 // 2**56 100000000000000005551115123125L In versions prior to Python 2.7 an...
How to get reproducible results in keras
I get different results (test accuracy) every time I run the imdb_lstm.py example from Keras framework (https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py) The code contains np.random.seed(1337) in the top, before any keras imports. It should prevent it from generating different numbers for every run. ...
Theano's documentation talks about the difficulties of seeding random variables and why they seed each graph instance with its own random number generator. Sharing a random number generator between different {{{RandomOp}}} instances makes it difficult to producing the same stream regardless of other ops in graph,...
Django app works fine, but getting a TEMPLATE_* warning message
When I use runserver, it gives this warning message: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DEBUG. Quoth the Django Documentation: "T...
Set debug in OPTIONS dictionary of your templates settings. DEBUG = True TEMPLATES = [ { ... 'OPTIONS': { 'debug': DEBUG, }, }, ] Then remove this line from your settings to stop the warnings TEMPLATE_DEBUG = DEBUG
Spark performance for Scala vs Python
I prefer Python over Scala. But, as Spark is natively written in Scala, I was expecting my code to run faster in the Scala than the Python version for obvious reasons. With that assumption, I thought to learn & write the Scala version of some very common preprocessing code for some 1 GB of data. Data is picked from the...
The original answer discussing the code can be found below. First of all you have to distinguish between different types of API, each with its own performance consideration. RDD API (pure Python structures with JVM based orchestration) This is the component which will be most affected by a performance of the Python c...
wxPython threads blocking
This is in the Phoenix fork of wxPython. I'm trying to run a couple threads in the interests of not blocking the GUI. Two of my threads work fine, but the other one never seem to hit its bound result function. I can tell that it's running, it just doesn't seem to properly post the event. Here's the result function for ...
the problem is that the event system ends up calling the update function(event handler) from the threads themselves , you should pretty much never do that(basically you end up with strange race conditions and artifacts) ... always make the callback in the main thread. wxPython has taken this into consideration and any...
How to use viridis in matplotlib 1.4
I want to use the colormap "viridis" (http://bids.github.io/colormap/), and I won't be updating to the development version 1.5 quite yet. Thus, I have downloaded colormaps.py from https://github.com/BIDS/colormap. Unfortunately, I'm not able to make it work. This is what I do: import matplotlib.pyplot as plt import ...
Rather than using set_cmap, which requires a matplotlib.colors.Colormap instance, you can set the cmap directly in the pcolormesh call (cmaps.viridis is a matplotlib.colors.ListedColormap) import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import colormaps as cmaps img=mpimg.imread('...
Convert a 64 bit integer into 8 separate 1 byte integers in python
In python, I have been given a 64 bit integer. This Integer was created by taking several different 8 bit integers and mashing them together into one giant 64 bit integer. It is my job to separate them again. For example: Source number: 2592701575664680400 Binary (64 bits): 001000111111101100100000010110001010101000...
Solution Solution without converting the number to a string: x = 0b0010001111111011001000000101100010101010000101101011111000000000 numbers = list((x >> i) & 0xFF for i in range(0,64,8)) print(numbers) # [0, 190, 22, 170, 88, 32, 251, 35] print(list(reversed(numbers))) # [35, 251, 32, 88, 170, 22...
Boto3/S3: Renaming an object using copy_object
I'm trying to rename a file in my s3 bucket using python boto3, I couldn't clearly understand the arguments. can someone help me here? What I'm planing is to copy object to a new object, and then delete the actual object. I found similar questions here, but I need a solution using boto3.
I found another solution s3 = boto3.resource('s3') s3.Object('my_bucket','my_file_new').copy_from(CopySource='my_bucket/my_file_old') s3.Object('my_bucket','my_file_old').delete()
Generator as function argument
Can anyone explain why passing a generator as the only positional argument to a function seems to have special rules? If we have: >>> def f(*args): >>> print "Success!" >>> print args This works, as expected. >>> f(1, *[2]) Success! (1, 2) This does not work, as expected. >>> f(*[2], 1) File "<stdin>", line...
Both 3. and 4. should be syntax errors on all Python versions. However you've found a bug that affects Python versions 2.5 - 3.4, and which was subsequently posted to the Python issue tracker. Because of the bug, an unparenthesized generator expression was accepted as an argument to a function if it was accompanied onl...
How to set React to production mode when using Gulp
I need to run React in production mode, which presumably entails defining the following somewhere in the enviornment: process.env.NODE_ENV = 'production'; The issue is that I'm running this behind Tornado (a python web-server), not Node.js. I also use Supervisord to manage the tornado instances, so it's not abundantly...
Step I: Add the following to your gulpfile.js somewhere gulp.task('apply-prod-environment', function() { process.env.NODE_ENV = 'production'; }); Step II: Add it to your default task (or whichever task you use to serve/build your app) // before: // gulp.task('default',['browsersync','watch'], function() {}); // a...
pip doesn't work after upgrade
Today I upgraded from pip 7.1.0 to 7.1.2, and now it doesn't work. $ pip search docker-compose Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/search...
I wasn't able to reproduce this with pip 7.1.2 and either Python 2.7.8 or 3.5.1 on Linux. The xmlrpclib docs have this to say on 'faults': Method calls may also raise a special Fault instance, used to signal XML-RPC server errors This implies that pip is reporting a problem on the server (pypi) side. The Python Inf...
Python stop multiple process when one returns a result?
I am trying to write a simple proof-of-work nonce-finder in python. def proof_of_work(b, nBytes): nonce = 0 # while the first nBytes of hash(b + nonce) are not 0 while sha256(b + uint2bytes(nonce))[:nBytes] != bytes(nBytes): nonce = nonce + 1 return nonce Now I am trying to do this multiprocess...
A general method to do this is to: think of work packets, e.g. to perform the calculation for a particular range, a range should not take long, say 0.1 seconds to a second have some manager distribute the work packets to the worker after a work packet has been concluded, tell the manager the result and request a new w...
How to print from Flask @app.route to python console
I would like to simply print a "hello world" to the python console after /button is called by the user. This is my naive approach: @app.route('/button/') def button_clicked(): print 'Hello world!' return redirect('/') Background: I would like to execute other python commands from flask (not shell). "print" sho...
It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this: from __future__ import print_function # In python 2.7 import sys @app.route('/button/') def button_clicked(): print('Hello world!', file=sys.stderr) return r...
Flask validates decorator multiple fields simultaneously
I have been using the @validates decorator in sqlalchemy.orm from flask to validate fields, and all has gone well as long as all of the fields are independent of one another such as: @validates('field_one') def validates_field_one(self, key, value): #field one validation @validates('field_two') def validates_field_...
Order the fields in the order they were defined on the model. Then check if the last field is the one being validated. Otherwise just return the value unchecked. If the validator is validating one of the earlier fields, some of them will not be set yet. @validates('field_one', 'field_two') def validates_fields(self,...
What are Type hints in Python 3.5
One of the talked about features in Python 3.5 is said to be type hints. An example of type hints is mentioned in this article and this while also mentioning to use type hints responsibly. Can someone explain more about it and when it should be used and when not?
I would suggest reading PEP 483 and PEP 484 and watching this presentation by Guido on Type Hinting. In addition, more examples on Type Hints can be found at their documentation topic. In a nutshell: Type hinting is literally what it means, you hint the type of the object(s) you're using. Due to the highly dynamic nat...
How to list all exceptions a function could raise in Python 3?
Is there a programmatic way to get a list of all exceptions a function could raise? I know for example that os.makedirs(path[, mode]) can raise PermissionError (and maybe others), but the documentation only mentions OSError. (This is just an example - maybe even a bad one; I am not especially interested in this functio...
You can't get reliable results for some (if not most) functions. Some examples: functions that execute arbitrary code (e.g. exec(')(rorrEeulaV esiar'[::-1]) raises ValueError) functions that aren't written in Python functions that call other functions that can propagate errors to the caller functions re-raising active...
Simple way to measure cell execution time in ipython notebook
I would like to get the time spent on the cell execution in addition to the original output from cell. To this end, I tried %%timeit -r1 -n1 but it doesn't expose the variable defined within cell. %%time works for cell which only contains 1 statement. In[1]: %%time 1 CPU times: user 4 µs, sys: 0 ns, total: 4 µ...
Use cell magic and this project on github by Phillip Cloud: Load it by putting this at the top of your notebook or put it in your config file if you always want to load it by default: %install_ext https://raw.github.com/cpcloud/ipython-autotime/master/autotime.py %load_ext autotime If loaded, every output of subseque...
Does spark predicate pushdown work with JDBC?
According to this Catalyst applies logical optimizations such as predicate pushdown. The optimizer can push filter predicates down into the data source, enabling the physical execution to skip irrelevant data. Spark supports push down of predicates to the data source. Is this feature also available / expected for...
Spark DataFrames support predicate push-down with JDBC sources but term predicate is used in a strict SQL meaning. It means it covers only WHERE clause. Moreover it looks like it is limited to the logical conjunction (no IN and OR I am afraid) and simple predicates. Everything else, like limits, counts, ordering, group...
Python not working in the command line of git bash
Python will not run in git bash (Windows). When I type python in the command line, it takes me to a blank line without saying that it has entered python 2.7.10 like its does in Powershell. It doesn't give me an error message, but python just doesn't run. I have already made sure the environmental variables in PATH incl...
This is a known bug in MSys2, which provides the terminal used by Git Bash. You can work around it by running a Python build without ncurses support, or by using WinPTY, used as follows: To run a Windows console program in mintty or Cygwin sshd, prepend console.exe to the command-line: $ build/console.exe c:/Python27/...
Can you fix the false negative rate in a classifier in scikit learn
I am using a Random Forest classifer in scikit learn with an imbalanced data set of two classes. I am much more worried about false negatives than false positives. Is it possible to fix the false negative rate (to, say, 1%) and ask scikit to optimize the false positive rate somehow? If this classifier doesn't support...
I believe the problem of class imbalance in sklearn can be partially resolved by using the class_weight parameter. this parameter is either a dictionary, where each class is assigned a uniform weight, or is a string that tells sklearn how to build this dictionary. For instance, setting this parameter to 'auto', will w...
Why is a class __dict__ a mappingproxy?
I wonder why a class __dict__ is a mappingproxy, but an instance __dict__ is just a plain dict >>> class A: pass >>> a = A() >>> type(a.__dict__) <class 'dict'> >>> type(A.__dict__) <class 'mappingproxy'>
This helps the interpreter assure that the keys for class-level attributes and methods can only be strings. Elsewhere, Python is a "consenting adults language", meaning that dicts for objects are exposed and mutable by the user. However, in the case of class-level attributes and methods for classes, if we can guarante...
Python's equivalent of Ruby's ||=
To check if a variable exist, and if exits, use the original value, other wise, use the new value assigned. In ruby, it's var ||= var_new How to write it in python? PS: I don't know the name of ||=, I simply can't search it in Bing.
I think there is some confusion from the people who aren't really sure what the conditional assignment operator (||=) does, and also some misunderstanding about how variables are spawned in Ruby. Everyone should read this article on the subject. A TLDR quote: A common misconception is that a ||= b is equivalent to a =...
Create Spark DataFrame. Can not infer schema for type:
Could someone help me solve this problem I have with spark DataFrame? When I do myFloatRDD.toDF() i get an error: TypeError: Can not infer schema for type: type 'float' I don't understand why... example: myFloatRdd = sc.parallelize([1.0,2.0,3.0]) df = myFloatRdd.toDF() Thanks
SqlContext.createDataFrame, which is used under the hood, requires an RDD of Row/tuple/list/dict* or pandas.DataFrame. Try something like this: myFloatRdd.map(lambda x: (x, )).toDF() or even better: from pyspark.sql import Row row = Row("val") # Or some other column name myFloatRdd.map(row).toDF() * No longer supp...
What are the pitfalls of using Dill to serialise scikit-learn/statsmodels models?
I need to serialise scikit-learn/statsmodels models such that all the dependencies (code + data) are packaged in an artefact and this artefact can be used to initialise the model and make predictions. Using the pickle module is not an option because this will only take care of the data dependency (the code will not be ...
Ok to begin with, in your sample code pickle could work fine, I use pickle all the time to package a model and use it later, unless you want to send the model directly to another server or save the interpreter state, because that is what Dill is good at and pickle can not do. It also depends on your code, what types et...
Django 1.9 ImportError for import_module
When trying to run either runserver or shell using manage.py I get an ImportError exception. I'm using Django 1.9. ImportError: No module named 'django.utils.importlib'
django.utils.importlib is a compatibility library for when Python 2.6 was still supported. It has been obsolete since Django 1.7, which dropped support for Python 2.6, and is removed in 1.9 per the deprecation cycle. Use Python's import_module function instead: from importlib import import_module The reason you can i...
Optimization Break-even Point: iterate many times over set or convert to list first?
Here's something I've always wondered about. I'll pose the question for Python, but I would also welcome answers which address the standard libraries in Java and C++. Let's say you have a Python list called "my_list", and you would like to iterate over its unique elements. There are two natural approaches: #iterate o...
I'm looking for a rule of thumb... Rule of thumb Here's the best rule of thumb for writing optimal Python: use as few intermediary steps as possible and avoid materializing unnecessary data structures. Applied to this question: sets are iterable. Don't convert them to another data structure just to iterate over them...
How to add a constant column in a Spark DataFrame?
I want to add a column in a DataFrame with some arbitrary value (that is the same for each row). I get an error when I use withColumn as follows: dt.withColumn('new_column', 10).head(5) --------------------------------------------------------------------------- AttributeError Traceback (most...
The second argument for DataFrame.withColumn should be a Column so you have to use a literal: from pyspark.sql.functions import lit df.withColumn('new_column', lit(10)) If you need complex columns you can build these using blocks like array: from pyspark.sql.functions import array, struct df.withColumn("some_array",...
'PipelinedRDD' object has no attribute 'toDF' in PySpark
I'm trying to load an SVM file and convert it to a DataFrame so I can use the ML module (Pipeline ML) from Spark. I've just installed a fresh Spark 1.5.0 on an Ubuntu 14.04 (no spark-env.sh configured). My my_script.py is: from pyspark.mllib.util import MLUtils from pyspark import SparkContext sc = SparkContext("local...
toDF method is a monkey patch executed inside SQLContext (SparkSession constructor in 2.0+) constructor so to be able to use it you have to create a SQLContext (or SparkSession) first: from pyspark.sql import SQLContext # or from pyspark.sql import HiveContext rdd = sc.parallelize([("a", 1)]) hasattr(rdd, "toDF") ## ...
Selenium unexpectedly having issues
I have been using selenium now for a while on a number of projects. With code that was running I am now receiving the following error: C:\Users\%USER%\Miniconda\python.exe C:/Users/%USER%/PycharmProjects/c_r/quick_debug.py Traceback (most recent call last): File "C:/Users/%USER%/PycharmProjects/c_r/quick_...
After having a quick look at the source code, I think this is a compatibility issue between ChromeDriver and Chrome itself - I suspect your Chrome auto-updated and now is too new for ChromeDriver 2.10. In other words: update ChromeDriver, latest is currently 2.19.
PyCrypto on python 3.5
i found some exes of PyCrypto for python 3.3 and 3.4, but nothing for python 3.5. When i try to install PyCrypton using pip install, it says: warning: GMP or MPIR library not found; Not building Crypto.PublicKey._fastmath. Is there any way how to install PyCrypto on python 3.5 in Windows 10? Thanks!
That warning shouldn't stop the build, more likely you are lacking the Visual Studio 2015 compiler which is necessary to build binary extensions (which PyCrypto has). See the Python Packaging User Guide for which compiler you need for your version of Python. The reason you need the compiler is PyCrypto only offers a So...
How to use async/await in Python 3.5?
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import time async def foo(): await time.sleep(1) foo() I couldn't make this dead simple example to run: RuntimeWarning: coroutine 'foo' was never awaited foo()
Running coroutines requires an event loop. Use the asyncio() library to create one: import asyncio loop = asyncio.get_event_loop() loop.run_until_complete(foo()) loop.close() Also see the Tasks and Coroutines chapter of the asyncio documentation. Note however that time.sleep() is not an awaitable object. It returns N...
Are global variables thread safe in flask?
In my app the state of a common object is changed by making requests, and the response depends on the state. class SomeObj(): def __init__(self, param): self.param = param def query(self): self.param += 1 return self.param global_obj = SomeObj(0) @app.route('/') def home(): flash(g...
You can't use global variables to hold this sort of data. Not only is it not thread safe, it's not process safe, and WSGI servers in production spawn multiple processes. So not only would your counts be wrong if you were using threads to handle requests, they would also vary depending on which process handled the req...
Why does open(True, 'w') print the text like sys.stdout.write?
I have the following code: with open(True, 'w') as f: f.write('Hello') Why does this code print the text Hello instead of raise an error?
From the built-in function documentation on open(): open(file, mode='r', buffering=-1... file is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped That "integer file descriptor" i...
Unable to install nltk on Mac OS El Capitan
I did sudo pip install -U nltk as suggested by the nltk documentation. However, I am getting the following output: Collecting nltk Downloading nltk-3.0.5.tar.gz (1.0MB) 100% |████████████████████████████████| 1.0MB 516kB/s Collecting six>=1.9.0 (fro...
Here is the way how I fixed the issues: First, install Xcode CLI: xcode-select --install Then reinstall Python: sudo brew reinstall python Finally, install nltk: sudo pip install -U nltk Hope it helps :)
Flask: 'session' vs. 'g'?
I'm trying to understand the differences in functionality and purpose between g and session. Both are objects to 'hang' session data on, am I right? If so, what exactly are the differences and which one should I use in what cases?
No, g is not an object to hang session data on. g data is not persisted between requests. session gives you a place to store data per specific browser. As a user of your Flask app, using a specific browser, returns for more requests, the session data is carried over across those requests. g on the other hand is data sh...
Methods for writing Parquet files using Python?
I'm having trouble finding a library that allows Parquet files to be written using Python. Bonus points if I can use Snappy or a similar compression mechanism in conjunction with it. Thus far the only method I have found is using Spark with the pyspark.sql.DataFrame Parquet support. I have some scripts that need to wr...
As of 2.2016 there seems to be NO python-only library capable of writing Parquet files. If you only need to read Parquet files there is python-parquet. As a workaround you will have to rely on some other process like e.g. pyspark.sql (which uses Py4J and runs on the JVM and can thus not be used directly from your avera...
Error installing Pillow on ubuntu 14.04
I'm trying to install Pillow on Ubuntu 14.04 using this command: pip install Pillow but the installation fails with this error: ValueError: --enable-jpeg requested but jpeg not found, aborting.
The problem was that the package libjpeg-dev was not installed. To solve the problem you should do this: sudo apt-get install libjpeg-dev
In Python, is there an async equivalent to multiprocessing or concurrent.futures?
Basically, I'm looking for something that offers a parallel map using python3 coroutines as the backend instead of threads or processes. I believe there should be less overhead when performing highly parallel IO work. Surely something similar already exists, be it in the standard library or some widely used package?
DISCLAIMER PEP 0492 defines only syntax and usage for coroutines. They require an event loop to run, which is most likely asyncio's event loop. Asynchronous map I don't know any implementation of map based on coroutines. However it's trivial to implement basic map functionality using asyncio.gather(): def async_map(cor...
Python pickle error: UnicodeDecodeError
I'm trying to do some text classification using Textblob. I'm first training the model and serializing it using pickle as shown below. import pickle from textblob.classifiers import NaiveBayesClassifier with open('sample.csv', 'r') as fp: cl = NaiveBayesClassifier(fp, format="csv") f = open('sample_classifier.p...
By choosing to open the file in mode wb, you are choosing to write in raw binary. There is no character encoding being applied. Thus to read this file, you should simply open in mode rb.
How to return a specific point after an error in 'while' loop
I'm trying to write a program that include a while loop, in this loop I have an error message if something goes wrong. It's kinda like this; while True: questionx = input("....") if x =="SomethingWrongabout questionX": print ("Something went wrong.") continue other codes... questiony =...
[EDIT from generator to function] You can try a function: def check_answer(question, answer): while True: current_answer = input(question) if current_answer == answer: break print "Something wrong with question {}".format(question) return current_answer answerX = check_answe...
How do I run psycopg2 on El Capitan without hitting a libssl error
I've got a python django dev setup on my mac and have just upgraded to El Capitan. I've got psycopg2 installed in a virtualenv but when I run my server I get the following error - django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/aidan/Environments/supernova/lib/python2.7/site-pa...
I tried the following: I have brew installed on my machine. Running $ brew doctor gave me a suggestion to do the following: $ sudo chown -R $(whoami):admin /usr/local Once this was done, I re-installed psycopg2 and performed the following: $ sudo ln -s /Library/PostgreSQL/9.3/lib/libssl.1.0.0.dylib /usr/local/lib/ $ su...
Are constant computations cached in Python?
Say I have a function in Python that uses a constant computed float value like 1/3. def div_by_3(x): return x * (1/3) If I call the function repeatedly, will the value of 1/3 be automatically cached for efficiency? Or do I have to do something manually such as the following? def div_by_3(x, _ONE_THIRD=1/3): re...
Find out for yourself! The dis module is great for inspecting this sort of stuff: >>> from dis import dis >>> def div_by_3(x): ... return x * (1/3.) ... >>> dis(div_by_3) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 1 (1) 6 LOAD_CONST 2 (3.0) ...
Cassandra cqlsh "unable to connect to any servers"
I get the following message when executing cqlsh.bat on the command line Connection error: ('Unable to connect to any servers', {'127.0.0.1': ProtocolError("cql_version '3.3.0' is not supported by remote (w/ native protocol). Supported versions: [u'3.2.0']",)}) I'm running Python version 2.7.10 along with Cassandra ve...
You can force cqlsh to use a specific cql version using the flag --cqlversion="#.#.#" Example cqlsh usage (and key/values): cqlsh 12.34.56.78 1234 -u username -p password --cqlversion="3.2.0" cqlsh (IP ADDR) (PORT) (DB_USERN) (DB_PASS) (VER)
How can i count occurrence of each word in document using Dictionary comprehension
I have a list of lists in python full of texts. It is like set words from each document. So for every document i have a list and then on list for all documents. All the list contains only unique words. My purpose is to count occurrence of each word in the complete document. I am able to do this successfully using the b...
Like explained in the other answers, the issue is that dictionary comprehension creates a new dictionary, so you don't get reference to that new dictionary until after it has been created. You cannot do dictionary comprehension for what you are doing. Given that, what you are doing is trying to re-implement what is alr...
built-in max heap API in Python
Default heapq is min queue implementation and wondering if there is an option for max queue? Thanks. I tried the solution using _heapify_max for max heap, but how to handle dynamically push/pop element? It seems _heapify_max could only be used during initialization time. import heapq def heapsort(iterable): h = []...
In the past I have simply used sortedcontainers's SortedList for this, as: > a = SortedList() > a.add(3) > a.add(2) > a.add(1) > a.pop() 3 It's not a heap, but it's fast and works directly as required. If you absolutely need it to be a heap, you could make a general negation class to hold your items. class Neg(): ...
Confusing about a Python min quiz
Just now I saw a quiz on this page: >>> x, y = ??? >>> min(x, y) == min(y, x) False The example answer is x, y = {0}, {1} From the documentation I know that: min(iterable[, key=func]) -> value min(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its smallest item. With two or more argum...
The comparison operators <, <=, >=, and > check whether one set is a strict subset, subset, superset, or strict superset of another, respectively. {0} and {1} are False for all of these, so the result depends on the check order and operator.
Accessing attributes on literals work on all types, but not `int`; why?
I have read that everything in python is an object, and as such I started to experiment with different types and invoking __str__ on them — at first I was feeling really excited, but then I got confused. >>> "hello world".__str__() 'hello world' >>> [].__str__() '[]' >>> 3.14.__str__() '3.14' >>> 3..__str__() '3.0' >>>...
You need parens: (4).__str__() The problem is the lexer thinks "4." is going to be a floating-point number. Also, this works: x = 4 x.__str__()
python 3.5: TypeError: a bytes-like object is required, not 'str'
I've very recently migrated to Py 3.5. This code was working properly in Python 2.7: with open(fname, 'rb') as f: lines = [x.strip() for x in f.readlines()] for line in lines: tmp = line.strip().lower() if 'some-pattern' in tmp: continue # ... code After upgrading to 3.5, I'm getting the: TypeError: a...
You opened the file in binary mode: with open(fname, 'rb') as f: This means that all data read from the file is returned as bytes objects, not str. You cannot then use a string in a containment test: if 'some-pattern' in tmp: continue You'd have to use a bytes object to test against tmp instead: if b'some-pattern' in...
Python Requests/urllib — monitoring bandwidth usage
I want to log the total bytes downloaded and uploaded by my Python script. total_downloaded_bytes = 0 def bandwidth_hook(r, *args, **kwargs): global total_downloaded_bytes total_downloaded_bytes += len(r.content) req = requests.session() req.hooks = {'response': bandwidth_hook} The above code doesn't take into...
You can access the r.request object to calculate outgoing bytes, and you can determine incoming bytes (compressed or not) by looking at the content-length header for the incoming request. This should suffice for 99% of all requests you normally would make. Calculating the byte size of headers is easy enough; just add u...
Why 2700 records (320KB each) should take 30 seconds to be fetched?
I have 2700 records in MongoDB. Each document has a size of approximately 320KB. The engine I use is wiredTiger and the total size of collection is about 885MB. My MongoDB config is as below: systemLog: destination: file path: /usr/local/var/log/mongodb/mongo.log logAppend: true storage: dbPath: /usr/local/...
The methods I used to improve performance: First of all instead of using for loop to traverse query and fetch data, I give the cursor to Pandas rather than creating a large list object in python: cursor = mycol.find({'date': {"$lte": end_date, '$gte': start_date}}, {'_id': False}) df = pandas.DataFrame(list(cursor))...