How to add a new custom lib file to create-react-app - create-react-app

I have started a new create-react-app that uses bokeh to render some plots. Since i have complex plots i need to be able to import/include a custom library that pull some modules from bokehjs.
How I do it: in my index.js file i include the lib like this
require('./_beadselection.ts')
my beadselection.ts file looks like this:
import {Span, SpanView} from "#bokeh/bokehjs"
import {Plot} from "#bokeh/bokehjs"
import {FactorRange} from "#bokeh/bokehjs"
import {Mapping} from "#bokeh/bokehjs"
import {BoxedFactor} from "#bokeh/bokehjs"
import * as p from "core/properties"
export class CpxSpanView extends SpanView {
model: CpxSpan
connect_signals(): void {
super.connect_signals()
this.connect(this.model.properties.selected.change, () => { this.on_selected() })
}
on_selected(): void {
let val = NaN
const rng = this.model.range.factors
const width = Math.round(Math.max(
3, this.model.plot.inner_width / (.5+this.model.range.synthetic(rng[rng.length-1])) * .5
))
if(this.model.selected >= 0 && this.model.selected < rng.length)
val = this.model.range.synthetic(rng[this.model.selected])
this.model.setv({line_width: width, location: isNaN(val) ? -1. : val});
}
}
export namespace CpxSpan {
export type Attrs = p.AttrsOf<Props>
export type Props = Span.Props & {
plot: p.Property<Plot>
range: p.Property<FactorRange>
selected: p.Property<number>
}
}
The errors that come up are these:
Compiled with problems:
ERROR in ./src/_beadselection.ts 4:0-37
Module not found: Error: Can't resolve 'core/properties' in '/home/ubuntu/reactAPP/react-flask-app/src'
ERROR in ./src/_beadselection.ts 5:33-41
export 'SpanView' (imported as 'SpanView') was not found in '#bokeh/bokehjs' (possible exports: ActionTool, AdaptiveTicker, AjaxDataSource, AllLabels, Annotation, AnnularWedge, Annulus, Arc, Arrow, ArrowHead, Ascii, Axis, BBoxTileSource, Band, BasicTickFormatter, BasicTicker, Bezier, BinnedTicker, BooleanFilter, Box, BoxAnnotation, BoxEditTool, BoxSelectTool, BoxZoomTool, ButtonTool, CDSView, Canvas, CanvasTexture, CartesianFrame, CategoricalAxis, CategoricalColorMapper, CategoricalMarkerMapper, CategoricalPatternMapper, CategoricalScale, CategoricalTickFormatter, CategoricalTicker, Charts, Circle, ColorBar, ColorMapper, Column, ColumnDataSource, ColumnarDataSource, CompositeTicker, ContinuousAxis, ContinuousColorMapper, ContinuousScale, ContinuousTicker, CoordinateMapping, CrosshairTool, CumSum, CustomAction, CustomJS, CustomJSExpr, CustomJSFilter, CustomJSHover, CustomJSTransform, CustomLabelingPolicy, DataRange, DataRange1d, DataSource, DatetimeAxis, DatetimeTickFormatter, DatetimeTicker, DaysTicker, Document, Dodge, EdgeCoordinates, EdgesAndLinkedNodes, EdgesOnly, EditTool, Ellipse, EllipseOval, EqHistColorMapper, Expression, FactorRange, Filter, FixedTicker, FreehandDrawTool, FuncTickFormatter, GMapOptions, GMapPlot, GeoJSONDataSource, GestureTool, Glyph, GlyphRenderer, GraphCoordinates, GraphHitTestPolicy, GraphRenderer, Grid, GridBox, GroupFilter, GuideRenderer, HArea, HBar, HTMLBox, HelpTool, HexTile, HoverTool, Image, ImageRGBA, ImageURL, ImageURLTexture, IndexFilter, InspectTool, Interpolator, IntersectRenderers, Jitter, Label, LabelSet, LabelingPolicy, LassoSelectTool, LayoutDOM, LayoutProvider, Legend, LegendItem, LinAlg, Line, LineEditTool, LinearAxis, LinearColorMapper, LinearInterpolationScale, LinearInterpolator, LinearScale, LogAxis, LogColorMapper, LogScale, LogTickFormatter, LogTicker, MapOptions, MathML, MathText, Maximum, MercatorAxis, MercatorTickFormatter, MercatorTicker, MercatorTileSource, Minimum, Models, MonthsTicker, MultiLine, MultiPolygons, NoOverlap, NodeCoordinates, NodesAndLinkedEdges, NodesOnly, NormalHead, NumeralTickFormatter, OpenHead, OpenURL, Oval, Palettes, PanTool, Panel, Patch, Patches, PlainText, Plot, Plotting, PointDrawTool, PolarTransform, PolyAnnotation, PolyDrawTool, PolyEditTool, PolySelectTool, PolyTool, PrintfTickFormatter, ProxyToolbar, QUADKEYTileSource, Quad, Quadratic, Range, Range1d, RangeTool, Ray, Rect, RedoTool, Renderer, RendererGroup, ResetTool, Row, SaveTool, ScalarExpression, Scale, ScanningColorMapper, Scatter, Segment, SelectTool, Selection, SelectionPolicy, ServerSentDataSource, SingleIntervalTicker, Slope, Spacer, Span, Spline, Stack, StaticLayoutProvider, Step, StepInterpolator, TMSTileSource, Tables, Tabs, TapTool, TeX, TeeHead, Text, TextAnnotation, Texture, TickFormatter, Ticker, TileRenderer, TileSource, Title, Tool, ToolProxy, Toolbar, ToolbarBase, ToolbarBox, ToolbarPanel, Tooltip, Transform, UndoTool, UnionRenderers, VArea, VBar, VeeHead, WMTSTileSource, WebDataSource, Wedge, WheelPanTool, WheelZoomTool, Whisker, WidgetBox, Widgets, XComponent, YComponent, YearsTicker, ZoomInTool, ZoomOutTool, _testing, documents, embed, index, logger, protocol, safely, set_log_level, settings, sprintf, version)
I guess I am not connecting them properly, I even added the full path to the library file from where SpanView should be pulled and it still does not like it.
import {Span, SpanView} from "../node_modules/#bokeh/bokehjs/build/js/lib/models/annotations"

Related

html2pdf fit image to pdf

I finally got my html2pdf to work showing my web page just how I want it in the pdf(Any other size was not showing right so I kept adjusting the format size until it all fit properly), and the end result is exactly what I want it to look like... EXCEPT even though my aspect ratio is correct for a landscape, it is still using a very large image and the pdf is not standard letter size (Or a4 for that matter), it is the size I set. This makes for a larger pdf than necessary and does not print well unless we adjust it for the printer. I basically want this exact image just converted to a a4 or letter size to make a smaller pdf. If I don't use the size I set though things are cut off.
Anyway to take this pdf that is generated and resize to be an a4 size(Still fitting the image on it). Everything I try is not working, and I feel like I am missing something simple.
const el = document.getElementById("test);
var opt = {
margin: [10, 10, 10, 10],
filename: label,
image: { type: "jpeg", quality: 0.98 },
//pagebreak: { mode: ["avoid-all", "css"], after: ".newPage" },
pagebreak: {
mode: ["css"],
avoid: ["tr"],
// mode: ["legacy"],
after: ".newPage",
before: ".newPrior"
},
/*pagebreak: {
before: ".newPage",
avoid: ["h2", "tr", "h3", "h4", ".field"]
},*/
html2canvas: {
scale: 2,
logging: true,
dpi: 192,
letterRendering: true
},
jsPDF: {
unit: "mm",
format: [463, 600],
orientation: "landscape"
}
};
var doc = html2pdf()
.from(el)
.set(opt)
.toContainer()
.toCanvas()
.toImg()
.toPdf()
.save()
I have been struggling with this a lot as well. In the end I was able to resolve the issue for me. What did the trick for me was setting the width-property in html2canvas. My application has a fixed width, and setting the width of html2canvas to the width of my application, scaled the PDF to fit on an A4 paper.
html2canvas: { width: element_width},
Try adding the above option to see if it works. Try to find out the width of your print area in pixels and replace element_width with that width.
For completeness: I am using Plotly Dash to create web user interfaces. On my interface I include a button that when clicked generates a PDF report of my dashboard. Below I added the code that I used for this, in case anybody is looking for a Dash solution. To get this working in Dash, download html2pdf.bundlemin.js and copy it to the assets/ folder. The PDF file will be downloaded to the browsers default downloads folder (it might give a download prompt, however that wasn't how it worked for me).
from dash import html, clientside_callback
import dash_bootstrap_components as dbc
# Define your Dash app in the regular way
# In the layout define a component that will trigger the download of the
# PDF report. In this example a button will be responsible.
app.layout = html.Div(
id='main_container',
children = [
dbc.Button(
id='button_download_report',
children='Download PDF report',
className='me-1')
])
# Clientside callbacks allow you to directly insert Javascript code in your
# dashboards. There are also other ways, like including your own js files
# in the assets/ directory.
clientside_callback(
'''
function (button_clicked) {
if (button_clicked > 0) {
// Get the element that you want to print. In this example the
// whole dashboard is printed
var element = document.getElementById("main_container")
// create a date-time string to use for the filename
const d = new Date();
var month = (d.getMonth() + 1).toString()
if (month.length == 1) {
month = "0" + month
}
let text = d.getFullYear().toString() + month + d.getDay() + '-' + d.getHours() + d.getMinutes();
// Set the options to be used when printing the PDF
var main_container_width = element.style.width;
var opt = {
margin: 10,
filename: text + '_my-dashboard.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 3, width: main_container_width, dpi: 300 },
jsPDF: { unit: 'mm', format: 'A4', orientation: 'p' },
// Set pagebreaks if you like. It didn't work out well for me.
// pagebreak: { mode: ['avoid-all'] }
};
// Execute the save command.
html2pdf().from(element).set(opt).save();
}
}
''',
Output(component_id='button_download_report', component_property='n_clicks'),
Input(component_id='button_download_report', component_property='n_clicks')
)

How can I move my camera sideways in ThreeJS

I want to move my camera sideways using the arrow keys. For this I can use something like this to move forward:
const facingDir = this.camera.getWorldDirection(new THREE.Vector3())
this.camera.position.addScaledVector(facingDir, 1)
How do I calculate the vector to go sideways?
I got it working like this:
import * as THREE from 'three'
export default function calcOrthogonalVector(object: THREE.Object3D): THREE.Vector3 {
// create default plane using normal vector
const normalVector = new THREE.Vector3(0, 1, 0)
const normalPlane = new THREE.Plane(normalVector, 0)
// copy rotation of camera to plane
normalPlane.normal.set(0, 1, 0).applyQuaternion(object.quaternion.clone())
// get new normal vector
const newNormalVector = normalPlane.normal
// create new vector from cross product
const crossVector = new THREE.Vector3()
crossVector.crossVectors(newNormalVector, object.getWorldDirection(new THREE.Vector3()))
return crossVector
}

Kotlin lets-plot: minimal example

I would like to write a completely minimal example of lets-plot, which just saves png and doesn't use any frontend. For this, I created a "helloworld" Kotlin project in IntelliJ IDEA. Then I added Maven dependency org.jetbrains.lets-plot:lets-plot-common:2.1.0. Now if I try to import jetbrains.letsPlot.letsPlot, I get the error "Unresolved reference: letsPlot". Thus, the question is how to write the most minimal lets-plot example, without using any frontend and Gradle.
The right dependencies are org.jetbrains.lets-plot:lets-plot-kotlin-jvm:3.0.2 (for API) and org.jetbrains.lets-plot:lets-plot-image-export:2.1.0 (to be able to export to raster). Now it works, and the resulting image in lets-plot-images directory.
The code:
import jetbrains.letsPlot.export.ggsave
import jetbrains.letsPlot.geom.geomPoint
import jetbrains.letsPlot.letsPlot
fun main() {
val xs = listOf(0, 0.5, 1, 2)
val ys = listOf(0, 0.25, 1, 4)
val data = mapOf<String, Any>("x" to xs, "y" to ys)
val fig = letsPlot(data) + geomPoint(
color = "dark-green",
size = 4.0
) { x = "x"; y = "y" }
ggsave(fig, "plot.png")
}
The resulting image:

Why ‘on_<propname>’ in kivy is not called?

in the kivy document (1.9.0-dev), it says
Observe using ‘on_<propname>’ If you created the class yourself, you
can use the ‘on_<propname>’ callback:
class MyClass(EventDispatcher):
a = NumericProperty(1)
def on_a(self, instance, value):
print(’My property a changed to’, value)
My code is
class MyClass(EventDispatcher):
a = StringProperty('')
def __init__(self, **kwargs):
...
self.bind(a=self.on_a) <--- if I remove this
def on_a(self, instance, value):
print(’My property a changed to’, value)
This works. But if I remove self.bind(a=self.on_a)
Then on_a function is not called. I thought if I put on_ as a function name then I do not need to do bind(). Do I miss something?
=================================================
Ps. I simplified my code below. It is a full run-able code.
course_view.py:
from kivy.app import App
from kivy.properties import StringProperty
from kivy.event import EventDispatcher
from kivy.uix.listview import ListView, ListItemButton
from kivy.adapters.dictadapter import DictAdapter
from kivy.uix.boxlayout import BoxLayout
from kivy.factory import Factory
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.properties import ObjectProperty
from kivy.properties import StringProperty
class ChangeTest(App):
pass
class StartScreen(Screen):
pass
def load_view(self):
self.course_view_object = CourseCnDetailListView(view_box = self.ids.view_box)
self.clear_widgets()
self.add_widget(self.course_view_object.master_item_list)
class CourseCnDetailListView(EventDispatcher):
course_code = StringProperty('course_code_str')
def __init__(self, **kwargs):
self.view_box = kwargs.get('view_box', None)
self.course_data= {"1": {"course_code": "it123"},
"2": {"course_code": "it456"}
}
list_item_args_converter = \
lambda row_index, rec: {'text': rec["course_code"],
'size_hint_y': None,
'height': 25}
dict_adapter = DictAdapter(sorted_keys=sorted(self.course_data.keys()),
data=self.course_data,
args_converter=list_item_args_converter,
selection_mode='single',
allow_empty_selection=False,
cls=ListItemButton)
self.master_item_list = ListView(adapter=dict_adapter,
size_hint=(.3, 1.0))
dict_adapter.bind(on_selection_change=self.course_changed)
#self.bind(course_code=self.on_course_code) <-- un-comment this will work
def on_course_code(self, instance, value):
print "on_course_code: update string value:", value
def redraw(self, *args):
pass
def course_changed(self, list_adapter, *args):
if len(list_adapter.selection) != 0:
selection = list_adapter.selection[0]
if type(selection) is str:
self.course_code = selection
else:
self.course_code = selection.text
self.redraw()
ChangeTest().run()
Factory.register('StartScreen', cls=StartScreen)
ChangeTest.kv
#: kivy 1.9
#: import ScreenManager kivy.uix.screenmanager.ScreenManager
#: import Screen kivy.uix.screenmanager.ScreenManager
ScreenManager:
id: screen_manager
StartScreen:
id: start_screen
name: 'StartScreen'
manager: screen_manager
<StartScreen>:
BoxLayout:
id: view_box
Button:
text: "load view"
on_release: root.load_view()
Thank you zeeMonkeez.
Yes. That is exactly the problem. After I add the constructor super(CourseCnDetailListView, self).__init__(**kwargs). It works perfectly.
It was accidentally removed when I changed the structure. Thank you very much.
Also it is good to know that it is the default constructor of EventDispatcher make <on_propname> work.

Ironpython in Spotfire - draw curve and modify chart

I have a code that changes my visualisation type from a Line to a Bar chart based on a property type. I need add a query to draw a straight line based on a property within my visualisation. The code I have so far is this:
from Spotfire.Dxp.Application.Visuals import VisualContent
from Spotfire.Dxp.Application.Visuals import VisualTypeIdentifiers
vc1 = viz1.As[VisualContent]()
Yaxis=vc1.YAxis.Expression
Xaxis=vc1.XAxis.Expression
ColorAxis=vc1.ColorAxis.Expression
if type=="LINE":
viz1.TypeId = VisualTypeIdentifiers.LineChart
if type == "BAR":
viz1.TypeId = VisualTypeIdentifiers.BarChart
vc1.XAxis.Expression=Xaxis
vc1.YAxis.Expression=Yaxis
vc1.ColorAxis.Expression=ColorAxis
Thanks in advance for your help!
from Spotfire.Dxp.Application.Visuals import LineChart
if vis.As[LineChart]().FittingModels[0].Enabled == False:
vis.As[LineChart]().FittingModels[0].Enabled = True
else:
vis.As[LineChart]().FittingModels[0].Enabled = False
This code requires a vis parameter defined as Type: Visualization Value: Page > Line Chart