images in Elm 0.17 - elm

I am trying a test example with a single image:
import Html exposing (Html)
import Graphics.Element
main = image 960 500 "starry-night.jpg"
I am trying this out with elm-reactor and this simple result doesn't compile:
I cannot find module 'Graphics.Element'.
Module 'Main' is trying to import it.
Potential problems could be:
* Misspelled the module name
* Need to add a source directory or new dependency to elm-package.json
I tried importing the necessary grahics package, evancz/elm-graphics
john#me:~/Documents/Elm$ cat elm-package.json
{
"version": "1.0.0",
"summary": "helpful summary of your project, less than 80 characters",
"repository": "https://github.com/user/project.git",
"license": "BSD3",
"source-directories": [
"."
],
"exposed-modules": [],
"dependencies": {
"elm-lang/core": "4.0.1 <= v < 5.0.0",
"elm-lang/html": "1.0.0 <= v < 2.0.0",
"elm-lang/svg": "1.0.0 <= v < 2.0.0",
"evancz/elm-graphics": "1.0.0 <= v < 2.0.0"
},
"elm-version": "0.17.0 <= v < 0.18.0"
}
I came up with:
import Html exposing (Html)
import Element exposing (image, toHtml)
main = toHtml ( image 960 500 "starry-night.jpg" )

The name of the module is Element, not Graphics.Element, so that's why the compiler cannot find it.
Moreover, the image function returns an Element, while the main function desires something of the Html type.
A running version of your program could be something like
import Element exposing (..)
main =
toHtml (image 960 500 "starry-night.jpg")

Related

How to add a new custom lib file to 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"

How to export and import js script?

Hello I have a code like this which works fine in main.js
Vue.prototype.$assetsResolution =
document.body.clientWidth * devicePixelRatio <= 1920 && document.body.clientHeight * devicePixelRatio <= 1080
? 1080
: 2160;
However, I have a lot of similar things and I would like to move the prototype code into another file.
For example, I tried to do it like this
//main.js
import "./vue-extensions/prototypes"
//prototypes.js
import Vue from "vue"
export {
Vue.prototype.$assetsResolution =
document.body.clientWidth * devicePixelRatio <= 1920 &&
document.body.clientHeight * devicePixelRatio <= 1080
? 1080
: 2160
}
But I have an error Unexpected token, expected "," in Vue.prototype
That syntax looks incorrect.
The external file does not need to export anything. It should just include the Vue.prototype.$assetsResolution assignment:
// prototypes.js
import Vue from 'vue'
Vue.prototype.$assetsResolution =
document.body.clientWidth * devicePixelRatio <= 1920 &&
document.body.clientHeight * devicePixelRatio <= 1080
? 1080
: 2160;
demo 1
You could also make this a Vue plugin by exporting a function that receives the Vue to modify:
// prototypes.js
export default Vue => {
Vue.prototype.$assetsResolution =
document.body.clientWidth * devicePixelRatio <= 1920 &&
document.body.clientHeight * devicePixelRatio <= 1080
? 1080
: 2160;
}
...which would be used like this:
// main.js
import Vue from 'vue'
import MyPlugin from './prototypes'
Vue.use(MyPlugin)
demo 2

Properly accessing cluster_config '__default__' values

I have a cluster.json file that looks like this:
{
"__default__":
{
"queue":"normal",
"memory":"12288",
"nCPU":"1",
"name":"{rule}_{wildcards.sample}",
"o":"logs/cluster/{wildcards.sample}/{rule}.o",
"e":"logs/cluster/{wildcards.sample}/{rule}.e",
"jvm":"10240m"
},
"aln_pe":
{
"memory":"61440",
"nCPU":"16"
},
"GenotypeGVCFs":
{
"jvm":"102400m",
"memory":"122880"
}
}
In my snakefile I have a few rules that try to access the cluster_config object in their params
params:
memory=cluster_config['__default__']['jvm']
But this will give me a 'KeyError'
KeyError in line 27 of home/bwubb/projects/Germline/S0330901/haplotype.snake:
'__default__'
Does this have something to do with '__default__' being a special object? It pprints in a visually appealing dictionary where as the others are labeled OrderDict, but when I look at the json it looks the same.
If nothing is wrong with my json, then should I refrain from accessing '__default__'?
The default value is accessed via the keyword "cluster", not
__default__
See here in this example in the tutorial:
{
"__default__" :
{
"account" : "my account",
"time" : "00:15:00",
"n" : 1,
"partition" : "core"
},
"compute1" :
{
"time" : "00:20:00"
}
}
The JSON list in the URL above and listed above is the one being accessed in this example. It's unfortunate they are not on the same page.
To access time, J.K. uses the following call.
#!python
#!/usr/bin/env python3
import os
import sys
from snakemake.utils import read_job_properties
jobscript = sys.argv[1]
job_properties = read_job_properties(jobscript)
# do something useful with the threads
threads = job_properties[threads]
# access property defined in the cluster configuration file (Snakemake >=3.6.0)
job_properties["cluster"]["time"]
os.system("qsub -t {threads} {script}".format(threads=threads, script=jobscript))

Elm seed for Random.initialSeed - prefer current time [duplicate]

This question already has answers here:
elm generate random number
(2 answers)
Closed 7 years ago.
What's a simple way to do this?
The documentation for Random.initialSeed says:
"A good way to get an unexpected seed is to use the current time."
http://package.elm-lang.org/packages/elm-lang/core/2.1.0/Random#initialSeed
After a ton of reading, I can only find "solutions" that are well beyond my understanding of Elm and Functional Programming. They also don't seem to be solutions to this problem.
I'm currently hardcoding:
Random.initialSeed 314
If you use a library, please include the name used to get it from elm package. I've seen a solution that says use Native.now but I can't figure out how to get that one.
stackoverflow is suggesting this one but I can't understand how to apply it to my usecase Elm Current Date
You can try case nelson's answer from How do I get the current time in Elm?
From elm repl:
> import Now
> import Random
> Now.loadTime |> round -- get current time in Int
1455406828183 : Int
> Now.loadTime |> round |> Random.initialSeed -- get the Seed
Seed { state = State 1560073230 678, next = <function>, split = <function>, range = <function> }
: Random.Seed
I also have the code on my repo here.
Note: don't forget "native-modules": true in elm-package.json.
Edit:
to try the code,
git clone https://github.com/prt2121/elm-backup.git
cd elm-backup/now
elm make Now.elm
add "native-modules": true in elm-package.json
elm repl
The simplest way I can think of is to use the Elm Architecture and Effects.tick mechanism to initialise the seed with a time value.
Here is an example of how this works:
import Html exposing (..)
import Html.Events exposing (onClick)
import Random exposing (Seed, generate, int, initialSeed)
import Time exposing (Time)
import Effects exposing (Effects, Never)
import Task exposing (Task)
import StartApp
type alias Model = { seed : Seed, value : Int}
type Action = Init Time | Generate
init : (Model, Effects Action)
init = (Model (initialSeed 42) 0, Effects.tick Init)
modelFromSeed : Seed -> (Model, Effects Action)
modelFromSeed seed =
let
(value', seed') = generate (int 1 1000) seed
in
(Model seed' value', Effects.none)
update : Action -> Model -> (Model, Effects Action)
update action model =
case action of
Init time ->
modelFromSeed (initialSeed (round time))
Generate ->
modelFromSeed model.seed
view : Signal.Address Action -> Model -> Html
view address model =
div []
[ text ("Current value: " ++ (toString model.value))
, br [] []
, button [onClick address Generate] [text "New Value"]
]
app : StartApp.App Model
app = StartApp.start
{ init = init
, update = update
, view = view
, inputs = []
}
main : Signal Html
main = app.html
port tasks : Signal (Task Never ())
port tasks = app.tasks

Can Typescript consume Existing AMD's?

Dojo 1.8 already defines AMD modules. For example you can do things like this:
require(["dojo/_base/lang"], function (lang) {
var ab = lang.mixin({a: 1}, {b: 2});
});
But how to I avoid getting an error when I attempt to import this module?
import lang = module ("dojo/_base/lang");
Is is possible?
You will need a typescript definition file for lang. Assuming that lang.d.ts exists in the same directory as lang.js this code:
import lang = module('dojo/_base/lang')
var ab = lang.mixin({a: 1}, {b: 2});
compiled with
tsc --module amd yourfile.ts
generates
define(["require", "exports", 'dojo/_base/lang'], function(require, exports, __lang__) {
var lang = __lang__;
var ab = lang.mixin({a: 1}, {b: 2});
}
If you don't want to have to match up the directory structures for whatever reason do this instead. Assuming lang.d.ts is in in a subdirectory called 3rd that is a sibling of test.ts.
test.ts:
///<reference path="3rd/lang.d.ts"/>
import lang = module('dojo/_base/lang');
var ab = lang.mixin({a: 1}, {b: 2});
3rd/lang.d.ts:
declare module 'dojo/_base/lang' {
...
}
generates the same as above.
You can normally load modules via the dojo loader, you don't have to use the import statement. But if you want you have to declare the module:
declare module "dojo/_base/lang" {
export function ...
export class ...
}