Line Wrapping in Collaboratory Google results - google-colaboratory

Working on Google Collaboratoy (colab) as Notebook, some cell results a long line text which is bigger than the screen resolution, so it is shown a scrollbar with no wrapping.
Does anyone know how to activate text wrapping to see all text without using scrollbar?
Thanks in advance.
Regards,

Normally on my own machine, I put this the following css snippit in the ~/.jupyter/custom/custom.css file.
pre {
white-space: pre-wrap;
}
But, the above does not work for google colab: I tried creating a file /usr/local/share/jupyter/custom/custom.css, but this didn't work.
Instead, put this in the first cell of your notebook.
from IPython.display import HTML, display
def set_css():
display(HTML('''
<style>
pre {
white-space: pre-wrap;
}
</style>
'''))
get_ipython().events.register('pre_run_cell', set_css)
Explanation: As described in Google Colab advanced output , get_ipython().events.register('pre_run_cell', <function name>)...
defines an execution hook that loads it [our custom set_css() function in our
case] automatically each time you execute a cell
My interpretation is that you need to specify 'pre_run_cell' as the first argument in the events.register, which tells the events.register function that you wish to run your custom set_css() function before the contents of the cell is executed.
This answer was inspired by How to import CSS file into Google Colab notebook (Python3)

from IPython.display import HTML, display
def set_css():
display(HTML('''
<style>
pre {
white-space: pre-wrap;
}
</style>
'''))
get_ipython().events.register('pre_run_cell', set_css)
As Bon Ryu mentioned above, this should solve the issue.
It will wrap your output properly

I use the following snippet:
from IPython.display import HTML, display
def my_css():
display(HTML("""<style>table.dataframe td{white-space: nowrap;}</style>"""))
get_ipython().events.register('pre_run_cell', my_css)

I create a function to help with that. It works with List and String.
def set_wrap(N=100):
''' create a wrap function for list '''
def wrap(obj):
s = str(obj)
out = '<pre>'
while True:
if len(s) < N:
out += s
break
i = s.rfind(' ', 0, N)
if i==-1:
i = N
out += s[:i]+"\n"
s = s[i:]
out += "</pre>"
return out
''' register it '''
Formatter = get_ipython().display_formatter.formatters['text/html']
Formatter.for_type(list, wrap)
Formatter.for_type(str, wrap)
You can use it by just calling set_wrap(80).

Related

Setting the view of a scene via mlab in traitsui is not working

I am trying to code a program based on traitsUI and Mayavi, but I have some problems. Following the code I am using:
#!/usr/bin/env python
import os
from traits.api import HasTraits, Instance, String, on_trait_change
from traitsui.api import View, Item
from tvtk.pyface.scene_editor import SceneEditor
from mayavi.tools.mlab_scene_model import MlabSceneModel
from mayavi.core.ui.mayavi_scene import MayaviScene
class ActorViewer(HasTraits):
scene = Instance(MlabSceneModel, ())
view = View(Item(name='scene',
editor=SceneEditor(scene_class=MayaviScene),
show_label=True,
resizable=True,
dock='tab',
height=500,
width=500),
resizable=True
)
def __init__(self, engine=None, **traits):
HasTraits.__init__(self, **traits)
if engine is not None:
self.scene=MlabSceneModel(engine=engine)
else:
self.scene=MlabSceneModel()
self.generate_data()
#on_trait_change('scene.activated')
def generate_data(self):
src=self.scene.mlab.pipeline.open(Path+i)
self.scene.mlab.view(40, 50)
self.scene.mlab.pipeline.outline(src)
self.scene.mlab.pipeline.iso_surface(src, contours=60, opacity=0.5)
if __name__ == '__main__':
Path = "/path/to/my/folder"
filelist = os.listdir(Path)
for i in filelist:
if i.endswith(".vtr"):
if ("E1_" in i) or ("E2_" in i):
print("file name ", i)
a = ActorViewer()
a.configure_traits()
The call self.scene.mlab.view(40, 50) returns AttributeError: 'NoneType' object has no attribute 'active_camera', thus I don't know how to set the camera. I have read that it is related to when the scene is activated, but I couldn't find a solution.
Without setting the view, the code works, but each file is loaded and rendered alone. In order to proceed with the main loop, each render has to be closed. I would like to dock each of the file without closing them.
I couldn't find a way to set a custom label to each tab after allowing show_label=True and to have it aligned horizontally at the top of the scene.
I tried to set the outline with the 'cornered' layout, but I couldn't find a way to do that. self.scene.mlab.pipeline.outline.outline_mode('cornered') gets simply ignored.
Thank you for your help!

max_height doesn't work for MDTextField in KivyMD

I was trying use max_height to limit the number of lines that the multiline=True MD TextField can expand to. In the KivyMD documentation for the TextField class (https://kivymd.readthedocs.io/en/latest/components/text-field/#module-kivymd.uix.textfield), there is sample code that is accompanied by a gif of what running it should look like, but when I copy/pasted it into a python file by itself to test it and ran it in PyCharm, the MDTextField didn't stop like it does in the gif or at all.
The example code given:
from kivy.lang import Builder
from kivymd.app import MDApp
KV = '''
MDScreen
MDTextField:
size_hint_x: .5
hint_text: "multiline=True"
max_height: "200dp"
mode: "fill"
fill_color: 0, 0, 0, .4
multiline: True
pos_hint: {"center_x": .5, "center_y": .5}
'''
class Example(MDApp):
def build(self):
return Builder.load_string(KV)
Example().run()
gif of what it should do
Is this some kind of bug or is there something I can do about it? I'm trying to implement this in my project, but not even the example code is working for me.
max_height only limits the height that the text box can reach, not the number of lines the user can input, as stated here: https://kivymd.readthedocs.io/en/1.1.1/components/textfield/#kivymd.uix.textfield.textfield.MDTextField.max_height
There is no built-in way to limit the number of lines the user can input, you'll have to do it manually yourself such as counting number of lines of input.

what is the proper way to set kivy scrollview effects_cls property?

I want to stop the user from over scrolling. kivy doc say that the effects_cls property will change this behavior, but I have not found a way to make it work.
Although you have solved your problem I will provide an example for future users.
You can change what effect is being used by setting effect_cls to any effect class. If you want to disable the overscroll effect to prevent the scroll bouncing effect ScrollEffect solve the problem.
Example using kivy Language:
from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.lang import Builder
Builder.load_string('''
#:import ScrollEffect kivy.effects.scroll.ScrollEffect
#:import Button kivy.uix.button.Button
<RootWidget>
effect_cls: ScrollEffect
GridLayout:
size_hint_y: None
height: self.minimum_height
cols: 1
on_parent:
for i in range(10): self.add_widget(Button(text=str(i), size_hint_y=None))
''')
class RootWidget(ScrollView):
pass
class MainApp(App):
def build(self):
root = RootWidget()
return root
if __name__ == '__main__':
MainApp().run()
Output:
so I was trying to use effect_cls: ScrollEffect when it should be effect_cls: 'ScrollEffect'.
have to pass it as a string.

How can I make sure scrapy-splash had render the entire page successfully

Problem Occurred When I Was Crawled The Whole Website By Using splash To Render The Entire Target Page.Some Page Was Not Random Successfully So I Was False To Get The Information That Supports To Be There When Render Job Had Done.That Means I Just Get Part Of The Information From The Render Result Although I Can Get The Entire Information From Other Render Result.
Here Is My Code:
yield SplashRequest(url,self.splash_parse,args = {"wait": 3,},endpoint="render.html")
settings:
SPLASH_URL = 'XXX'
DOWNLOADER_MIDDLEWARES = {
'scrapy_splash.SplashCookiesMiddleware': 723,
'scrapy_splash.SplashMiddleware': 725,
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}
# Enable SplashDeduplicateArgsMiddleware:
SPIDER_MIDDLEWARES = {
'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
}
# Set a custom DUPEFILTER_CLASS:
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter
# a custom cache storage backend:
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'
I am replying this late because the question has no answer and because it is visible on Google search.
I had similar problem and the only solution I found (besides increasing the wait argument, which may or may not work, but is not reliable) is using the execute endpoint and custom lua script for waiting for an element. If this sounds unnecessarily complex, it is, Scrapy and Splash are not well designed in my opinion, but I have found nothing better yet for my needs.
My Lua script looks something like this:
lua_base = '''
function main(splash)
splash:init_cookies(splash.args.cookies)
splash:go(splash.args.url)
while not splash:select("{}") do
splash:wait(0.1)
end
splash:wait(0.1)
return {{
cookies = splash:get_cookies(),
html=splash:html()
}}
end
'''
css = 'table > tr > td.mydata'
lua_script = lua_base.format(css)
and I generate requests like this:
yield SplashRequest(link, self.parse, endpoint='execute',
args={
'wait': 0.1,
'images': 0,
'lua_source': lua_script,
})
It is very ugly, but it works.

Rally API: How to print or export to pdf from Custom HTML

I have created table with data using "custom html app".
I want now print this page but when I try to do it, it cuts few last columns.
I have tried to set style of body to "width:1000px" and then it prints ok but then it doesn't shows on whole screen and I have table of size 1000px
We usually end up having slightly different css for printing than runtime.
Try this:
#media print {
body {
width: 1000px;
}
}