w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Import error in IPython notebook only with coopr.pyomo
I have to guess, but: Try something like the following in the notebook: import coopr print coopr.__file__ It looks like you're picking up a different coopr module than the installed one, and the __file__ attribute should tell you which one you're using. Perhaps there's a script called coopr; such a script would not contain a submodule pyomo. Why would this only happen in the IPython notebook and not in the IPython console? My guess is that, if there is indeed a different coopr module, it lives in your home directory or somewhere else on the system that the IPython notebook uses as its "base". The IPython console base directory is where you started it, but the IPython notebook is probably decoupled and has a default base directory. I don't know how the notebook is run under Windows, so

Categories : Python

IPython Kernel Non-Responsive: Running a Django development server from an IPython Notebook
I opened up an issue on IPython dev's github. Minrk found this solution: import subprocess server = subprocess.Popen(["python", "manage.py", "runserver"]) it allows me to view the dev server and continue to develop it in the IPython Notebook. sweet!

Categories : Django

Is there a IPython notebook api?
There is, you can do: import io from IPython.nbformat import current def convert(py_file, ipynb_file): with io.open(py_file, 'r', encoding='utf-8') as f: notebook = current.reads(f.read(), format='py') with io.open(ipynb_file, 'w', encoding='utf-8') as f: current.write(notebook, f, format='ipynb') convert('test.py', 'test.ipynb') But it's not that smart and it will place all the code from the python file into one IPython Notebook cell. But you can always do a little bit of parsing. import io import re from IPython.nbformat import current def parse_into_cells(py_file): with io.open(py_file, 'r', encoding='utf-8') as f: data = f.readlines() in_cell = True cell = '' for line in data: if line.rstrip() == '': # If a blan

Categories : Python

ipython notebook on RHEL 6?
If you have all the prerequisites installed, then ipython can simply be installed using easy_install without needing a package. Details of how to do this are given in the ipython documentation - you should take note of both the general ipython requirements and the notebook specific ones. The major thing which might cause a hassle is pyzmq. This will involve compiling and installing the zeromq C libraries, which obviously require C compilers etc. I think by default the pyzmq installer tries to do this for you, but if it fails then you may have to do this compilation manually. If you don't have root access to your machine, or if you want to test things before mucking around with system libraries, then I suggest using virtualenv to create an isolated python package directory in your own hom

Categories : Python

IPython Notebook Security
If you run the notebook on your machine, then no, it doesn't send anything externally. There are sites like Wakari where you can use the IPython notebook that's running on a server, and obviously that will send your code and data to their servers. If you did want to expose your notebook server on the internet, then there are security measures that you should take, but that's not necessary if you're just running ipython notebook locally, which is the default way it starts up.

Categories : Security

How to use iPython notebook with ngrok
Author of ngrok here: ipython notebooks and any other websocket connections now work properly as of ngrok 0.22 which is available at https://ngrok.com/download

Categories : Python

How to install ipython notebook locally?
Take a look at the adamdklein blog post. It takes you step-by-step through how to setup ipython and other mathematical goodies in a virtualenv (using Ubuntu).

Categories : Python

read-only cells in ipython notebook
There is an extension for IPython that is supposed to that: Read Only Cell extension. Getting it to work is something else, but it is there.

Categories : Python

How to get LaTeX to work in IPython notebook?
If you want to write latex you should write in in a Markdown cell, not in a code cell. Still, consider migrating to 0.13, 0.12 cannot read notebook generated from newer version and has a design flaw in notebook format.

Categories : Ubuntu

How can I play a local video in my IPython notebook?
You have to read the video into memory and base64 encode it, since the IPython Notebook is not a static file server: import io import base64 from IPython.display import HTML video = io.open('test.mp4', 'r+b').read() encoded = base64.b64encode(video) HTML(data='''<video alt="test" controls> <source src="data:video/mp4;base64,{0}" type="video/mp4" /> </video>'''.format(encoded.decode('ascii')))

Categories : HTML

IPython Notebook NB convert formatting Footers?
Finally found if I added: pagestyle{plain} pagenumbering{arabic} To the generated Tex file I get nicely formatted footers with page numbers... I can include that in the original Ipython notebook souce file as a raw cell I put it in a new 1st cell and desinated it as raw,, and it works fine. I still have to edit the 'unknown author' in the tex file though... Edit see the below comment to fix the Author field..

Categories : Python

Formatting output on Ipython Notebook with Pandas
You could achieve this by concatenating the results of the describe method for each DataFrame. For instance if the INVERNESS DataFrame was named df and RIVERCHASE df2: pd.concat([df.describe(), df2.describe()], keys = ['INVERNESS', 'RIVERCHASE'], axis = 1)

Categories : Python

Avoid antialising of R plots in iPython Notebook
The git version of IPython's rmagic extension ( https://github.com/ipython/ipython/blob/master/IPython/extensions/rmagic.py#L380) has the option to specify image resolution (e.g., %R -r 96 plot(7)). However, the needs_local_scope decorator causes the calls to %R to fail. A quick hack that seems to work more or less (setting plot resolution works and haven't seen anything break yet) would be to uncomment it on line 401. Before (72dpi): After (96 dpi):

Categories : Python

iPython Notebook in Windows - Error on Startup
It would be helpful to know what your sys.path is. You can find that by doing: $ ipython In [1]: import sys In [2]: sys.path And then share here the output. Next, you want to check what files you have in this directory: C:UserstibertAppDataRoamingPythonPython27site-packageszmqeventloopplatform Ideally, you'll see auto.py there, and if C:UserstibertAppDataRoamingPythonPython27site-packages is in your sys.path then it is a mystery why it isn't working, but if that file isn't there, the directory doesn't exist, or the path to site-packages isn't in your sys.path, then those need to be resolved first. Let us know and we can try to take it from there!

Categories : Windows

Running GAE remote_api_shell.py in a iPython notebook web interface
iPython Notebook has profile directories in ~/.ipython, which have a startup directory for Python scripts that can be used to do the customization of sys.path and login credentials as remote_api_shell.py does.

Categories : Google App Engine

Get Output From the logging Module in IPython Notebook
Try following: import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) logging.debug("test") According to logging.basicConfig: Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger. This function does nothing if the root logger already has handlers configured for it. It seems like ipython notebook call basicConfig (or set handler) somewhere.

Categories : Python

How do I reuse a plot layout in iPython notebook>?
I would suggest packaging different ideas into functions. E.g This is how I import data: def Import_Data(file_name,...): # Stuff to import data return data This is how I plot my data: def Plot(data..) Plotting just the base plot seems like a special case that you may do once, but if you really want to be able to show this, and minimise the amount of repeated code just allow data=None to ignore errors and not plot anything. The great thing about splitting code up like this is that it is easy to make changes to just one function, provided then just worry about inputs and outputs. For instance to filter you can either add a filter paramateter to the plot function, or create new filtered data that is plotted in the same way!

Categories : Python

Save IPython notebook directly to RST format?
With the IPython 1.0 you can use the nbconvert command: ipython nbconvert --to rst your.ipynb It will convert all the cels and outputs to rst. Images will be placed in a separate folder and included in the document using the standard rst .. image:: syntax.

Categories : Python

prevent plot from showing in ipython notebook
Perhaps just clear the axis, for example: fig= plt.figure() plt.plot(range(10)) fig.savefig("save_file_name.pdf") plt.close() will not plot the output in inline mode. I can't work out if is really clearing the data though.

Categories : Python

include IPython Notebook in my stackoverflow post
This is the best solution I found in addition to nbviewer: https://www.wakari.io/sharing/bundle/hrojas/How%20to%20plot%20selective%20data%20from%20a%20text%20file

Categories : Misc

Python: How to import sub-modules, from packages with the same name?
You need to have _init_.py files within those directories to make python treat then as a package instead of plain directories. Refer to this discussion to learn more about init.py files. Note:I have edited my previous answer by removing the irrelevant content based on the discussion with the poster of the query.

Categories : Python

How to get a latex table of sympy expressions in ipython-notebook?
Undoubtedly, part of the problem is that the latex you get out of df.to_latex() is not actually valid latex. For example, if you just take the output of that function and paste it into a dedicated latex document, it won't compile. In particular, some of the entries in the table contain things like Delta, but these are outside of a math environment (no dollar signs). So that's definitely a problem. Another possible problem is the use of oprule, etc. Those are non-standard latex constructions (though they can be used with the right latex package), but I don't know if those rules are recognized by the Latex function. All of that said, I can't even get the simplest tabular environment to display properly. For example, even if I do Latex(r"""egin{tabular}{l} 1 \ 2 end{tabular}""")

Categories : Python

Plot Size - Using ggplot2 in IPython Notebook (via rmagic)
The rmagic command has optional arguments to specify the size of the plot. The default is a width and height of 480 pixels. Thus, the code below replicates the default settings: %%R -w 480 -h 480 -u px library(ggplot2) dat <- data.frame(x = rnorm(10), y = rnorm(10), lab = sample(c('A', 'B'), 10, replace = TRUE)) x <- ggplot(dat, aes(x = x, y = y, color = lab)) + geom_point() print(x) And this code below creates a plot with a width of 50 cm and a height of 25 cm: %%R -w 50 -h 25 -u cm library(ggplot2) dat <- data.frame(x = rnorm(10), y = rnorm(10), lab = sample(c('A', 'B'), 10, replace = TRUE)) x <- ggplot(dat, aes(x = x, y = y, color = lab)) + geom_point() print(x) You can also specify the size in inches or millimeters.

Categories : R

IPython Notebook: how to display() multiple objects without newline
No, display cannot prevent newlines, in part because there are no newlines to prevent. Each displayed object gets its own div to sit in, and these are arranged vertically. You might be able to adjust this by futzing with CSS, but I wouldn't recommend that. The only way you could really get two objects to display side-by-side is to build your own object which encapsulates multiple displayed objects, and display that instead. For instance, your simple string case: class ListOfStrings(object): def __init__(self, *strings): self.strings = strings def _repr_html_(self): return ''.join( [ "<span class='listofstr'>%s</span>" % s for s in self.strings ]) display(ListOfStrings("hi", "hello", "hello there")) example noteboo

Categories : Python

Javascript to scroll an iPython Notebook cell to the top of the window
have a look here slidemode extension in slidemode folder. If you saw some scipy talk, this is what Fernando Perez/ Paul Ivanov and some other people use.

Categories : Javascript

Hosting an IPython notebook with external dependencies on github
The nice thing about nbviewer is that it simply shares the state of the IPython notebook at the time of save. What this means is that all your plots (PNGs base64 encoded), code, html, markdown, everything that was rendered will show up. Your potential audience doesn't need access to the original data/modules when viewing gists on nbviewer. Of course, if they need to be able to reproduce your work or add on to it, then yes they'll need access to your data/modules.

Categories : Github

Change font & background color in ipython notebook
You can use a file named custom.css in <ipython profile dir>/profile_<profilename>/static/custom/custom.css that will be applied to your notebook. Browser caching might be aggressive, you might need to force refresh a few times. Coloring of words is done through codemirror, which supports theming. Changing this will be slightly more involved and might require some JavaScript injection in <ipython profile dir>/profile_<profilename>/static/custom/custom.js. I wrote a more detailed, but outdated, explanation which can probably be adapted to new versions.

Categories : Python

importing system in python - import packages
import dir1 Imports dir1's __init__.py. You can access whatever is there using dir1.my_var_from_dir1_init. You cannot access the modules, only what's on dir1's __init__. from dir1 import * Imports the modules specified on the __all__ variable defined on dir1's __init__.py. If there isn't such variable, then it imports all of dir1's modules. You can access them directly, like main_code1.myvar. from dir1 import maincode Assuming it's a typo and you actually have a maincode module or class, it imports the maincode module/class from dir1. You can access it directly like mentioned above. Note that each option imports dir1's __init__.py, implicitly or explicitly. If you import the modules on __init__.py, then using import dir1 will allow you to use dir1.module. To import dir3's mainc

Categories : Python

Python: I can't import a module even though it's in site-packages
I extracted the package and placed it in site-packages: No, that's the wrong way of "installing" a package. Python packages come with a setup.py script that should be used to install them. Simply do: python setup.py install And the module will be installed correctly in the site-packages of the python interpreter you are using. If you want to install it for a specific python version use python2/python3 instead of python.

Categories : Python

IPython Notebook doesn't see environment variables with "bash magic"
I needed to actually export the variable in the script itself. sudo echo "JYTHON_HOME=/usr/lib/jvm/jython" | sudo tee -a /etc/environment source /etc/environment export JYTHON_HOME=/usr/lib/jvm/jython

Categories : Bash

Use a symbol for multiplication operator in sympy output in ipython notebook
Try the following code: from IPython.display import display, Math from sympy import * x1 = var('x_1') x2 = var('x_2') display(Math(latex(x1*x2,mul_symbol='dot'))) You can change dot to times or ldot. This makes IPython render the latex using the desired symbol. If you don't want that last line messing up all your code just define a function: def Latex(expr): return display(Math(latex(expr,mul_symbol='dot'))) and now you can just use: Latex(x1*x2)

Categories : Python

How to structure python packages without repeating top level name for import
Follow following structure : bagoftricks ── bagoftricks │ ├── __init__.py │ └── bagoftricks.py ├── README.md └── setup.py and then you should be able to use it as : from bagoftricks.bagoftricks import levenshtein, geofind but after you make the change in folder structure do :- pip uninstall <your package name mostly mentioned in setup.py> and reinstall the package meanwhile check your setup.py #!/bin/env python import os.path from setuptools import setup, find_packages def current_path(file_name): return os.abspath(os.path.join(__file__, os.path.pardir, file_name)) setup( name = 'bagoftricks', version = '0.1', include_package_data = True, packages=find_packages(), ) setup might have some other

Categories : Python

Why is matplotlib plot produced from ipython notebook slightly different from terminal version?
The font size issues are due to differences in the dpi. I'd guess the slightly different size of the figure (in pixels) changes the "best" location for the legend, as well. The default dpi a figure is displayed at is 80, while savefig defaults to 100. This means that by default, matplotlib figures will look slightly different when saved compared to what's displayed on the screen. I don't know for sure, but I'm guessing that ipython notebooks set the dpi to something other than 100 (most likely 80) and use that when saving figures. Try doing savefig('filename.pdf', dpi=80) in your standalone script.

Categories : Python

%Rpush >> lists of complex objects (e.g. pandas DataFrames in IPython Notebook)
Rmagic's push uses the name that you give it both to look up the Python variable, and to name the R variable it creates. So it needs a valid name, not just any expression, on both sides. There's a trick you can do to get the name from a Python variable: d1=DataFrame(np.arange(16).reshape(4,4)) name = 'd1' %Rpush {name} # equivalent to %Rpush d1 But if you want to do more advanced things, it's best to get hold of the r object and use that to put your objects in. Rmagic is just a convenience wrapper over rpy2, which is a full API. So you can do: from rpy2.robjects import r r.assign('a', 1) You can mix and match which interface you use - rmagic and rpy2 are talking to the same instance of R.

Categories : R

ipython notebook .png figures after nbconvert not loaded by latest chrome/firefox
Install BeautifulSoup4 first: pip install BeautifulSoup4 Then use following function to freeze your generated html file. The images will be placed in the images folder under the same directory as the html file. import os import re import base64 from bs4 import BeautifulSoup as BS from uuid import uuid4 def dump(path, data): root = os.path.dirname(path) if not os.path.exists(root): os.makedirs(root) with open(path, 'wb') as f: f.write(data) # for windows return path.replace('\', '/') def freeze_html(path): '''pass in absolute path of your html''' root = os.path.dirname(path) with open(path, 'rb') as f: soup = BS(f.read()) for img in soup.find_all('img'): m = re.search(r"data:image/png;base64,b'(.*)'", img['src'])

Categories : HTML

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?
I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment here), which is the same thing that hitting CTRL+C would do. Some processes within python handle SIGINTs more abruptly than others. If you desperately need to stop something that is running in iPython Notebook and you started iPython Notebook from a terminal, you can hit CTRL+C twice in that terminal to interrupt the entire iPython Notebook server. This will stop iPython Notebook alltogether, which means it won't be possible to restart or save your work, so this is obviously not a great solution (you need to hit CTRL+C twice because it's a safety feature so that people don't do it by accident). In case

Categories : Python

How to set the port for HTTP(S) in EC2 Security Group Inbound settings for a secure public iPython Notebook server?
HTTP and HTTPs are both a TCP/IP protocol: http://www.w3schools.com/tcpip/tcpip_protocols.asp I also found this video which confirms this: http://youtu.be/JMedTCa5lec?t=4m29s and the red, crossed-out https in the url reflects the unverified certificate (probably because it's self-signed).

Categories : Http

Load iPython with custom packages imported
What you want is a startup script. First run ipython locate profile to find the profile folder. Then find a startup folder in there. Create a .py file (any name) in the startup folder with the imports you want, and IPython will run that whenever you it starts.

Categories : Python

Import from ipython
is your PYTHONPATH different in ipython and IDLE? try the following import sys print(sys.path) I suspect the two won't match. have you launched IDLE and ipython from the same terminal?

Categories : Python

python packages -- overriding built-in packages and the dreaded "Module xxxx was already imported" warning
Rename myprogramxlrd to myprogramfrozen_xlrd. Then import it with try: import xlrd except ImportError: import frozen_xlrd as xlrd Alternatively, you could tell Python to silently ignore this particular UserWarning: import warnings warnings.filterwarnings("ignore", message="Module xlrd was already imported", category=UserWarning) Place this early on in the program, before scikits gets imported.

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.