diff --git "a/data/f-sharp/data.json" "b/data/f-sharp/data.json"
new file mode 100644--- /dev/null
+++ "b/data/f-sharp/data.json"
@@ -0,0 +1,100 @@
+{"size":19922,"ext":"fs","lang":"F#","max_stars_count":null,"content":"\ufeff\/\/ $begin{copyright}\n\/\/\n\/\/ This file is part of WebSharper\n\/\/\n\/\/ Copyright (c) 2008-2018 IntelliFactory\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you\n\/\/ may not use this file except in compliance with the License. You may\n\/\/ obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\/\/\n\/\/ $end{copyright}\n\n(*! Samples !*)\n (*![\n
Multiple samples for the Google Maps Extenstion. It demonstrates how to:<\/p>\n
\n - Create simple maps.<\/li>\n
- Add markers and behavior.<\/li>\n <\/ul>\n
Source Code Explained<\/h2>\n ]*)\n\nnamespace WebSharper.Google.Maps.Tests\n\nopen WebSharper\n\nmodule Util =\n\n open WebSharper.JavaScript\n\n []\n let Alert (msg: obj) : unit = X\n\n []\n let SetTimeout (f: unit -> unit) (ms: int) = X\n\nmodule SamplesInternals =\n\n open WebSharper.JavaScript\n open WebSharper.Google.Maps\n open WebSharper.Html.Client\n open WebSharper.JQuery\n\n []\n let Sample buildMap =\n Div [Attr.Style \"margin-bottom:20px; width:500px; height:300px; display: block;\"]\n |>! OnAfterRender (fun mapElement ->\n let center = new LatLng(37.4419, -122.1419)\n let options = new MapOptions(center, 8)\n let map = new Google.Maps.Map(mapElement.Body, options)\n buildMap map)\n\n []\n let SimpleMap() =\n Sample <| fun (map: Map) ->\n let latLng = new LatLng(-34.397, 150.644)\n let options = new MapOptions(latLng, 8)\n map.SetOptions options\n\n []\n let PanTo() =\n Sample <| fun map ->\n\n let center = new LatLng(37.4419, -122.1419)\n let options = new MapOptions(center, 8)\n map.SetOptions options\n let move () = map.PanTo(new LatLng(37.4569, -122.1569))\n \/\/ Window.SetTimeout(move, 5000)\n Util.SetTimeout move 5000\n\n []\n let RandomMarkers() =\n Sample <| fun map ->\n\n let addMarkers (_:obj) =\n \/\/ bounds is only available in the \"bounds_changed\" event.\n let bounds = map.GetBounds()\n\n let sw = bounds.GetSouthWest()\n let ne = bounds.GetNorthEast()\n let lngSpan = ne.Lng() - sw.Lng()\n let latSpan = ne.Lat() - sw.Lat()\n let rnd = Math.Random\n for i in 1 .. 10 do\n let point = new LatLng(sw.Lat() + (latSpan * rnd()),\n sw.Lng() + (lngSpan * rnd()))\n let markerOptions = new MarkerOptions(point)\n markerOptions.Map <- map\n new Marker(markerOptions) |> ignore\n\n Event.AddListener(map, \"bounds_changed\", As addMarkers) |> ignore\n\n []\n let MarkersWithLabel() =\n Sample <| fun map ->\n\n let addMarkers (_:obj) =\n \/\/ bounds is only available in the \"bounds_changed\" event.\n let bounds = map.GetBounds()\n\n let sw = bounds.GetSouthWest()\n let ne = bounds.GetNorthEast()\n let lngSpan = ne.Lng() - sw.Lng()\n let latSpan = ne.Lat() - sw.Lat()\n let rnd = Math.Random\n for i in 1 .. 10 do\n let point = new LatLng(sw.Lat() + (latSpan * rnd()),\n sw.Lng() + (lngSpan * rnd()))\n let markerOptions = new MarkerOptions(point)\n markerOptions.Map <- map\n let marker = new Marker(markerOptions)\n if i % 2 = 0 then\n marker.SetLabel (string i)\n else\n let markerLabel = new MarkerLabel (string i)\n markerLabel.FontSize <- \"10px\"\n marker.SetLabel markerLabel\n ()\n\n Event.AddListener(map, \"bounds_changed\", As addMarkers) |> ignore\n\n []\n let MarkersWithSymbol() =\n Sample <| fun map ->\n\n let addMarkers (_:obj) =\n \/\/ bounds is only available in the \"bounds_changed\" event.\n let bounds = map.GetBounds()\n\n let sw = bounds.GetSouthWest()\n let ne = bounds.GetNorthEast()\n let lngSpan = ne.Lng() - sw.Lng()\n let latSpan = ne.Lat() - sw.Lat()\n let rnd = Math.Random\n for i in 1 .. 10 do\n let point = new LatLng(sw.Lat() + (latSpan * rnd()),\n sw.Lng() + (lngSpan * rnd()))\n let markerOptions = new MarkerOptions(point)\n markerOptions.Map <- map\n let marker = new Marker(markerOptions)\n let newSymbol = new Symbol(SymbolPath.FORWARD_OPEN_ARROW)\n newSymbol.Scale <- 8.5\n newSymbol.FillColor <- \"#F00\"\n newSymbol.FillOpacity <- 0.4\n newSymbol.StrokeWeight <- 0.4\n marker.SetIcon newSymbol\n ()\n\n Event.AddListener(map, \"bounds_changed\", As addMarkers) |> ignore\n\n []\n let MarkersWithIcon() =\n Sample <| fun map ->\n\n let addMarkers (_:obj) =\n \/\/ bounds is only available in the \"bounds_changed\" event.\n let bounds = map.GetBounds()\n\n let sw = bounds.GetSouthWest()\n let ne = bounds.GetNorthEast()\n let lngSpan = ne.Lng() - sw.Lng()\n let latSpan = ne.Lat() - sw.Lat()\n let rnd = Math.Random\n for i in 1 .. 10 do\n let point = new LatLng(sw.Lat() + (latSpan * rnd()),\n sw.Lng() + (lngSpan * rnd()))\n let markerOptions = new MarkerOptions(point)\n markerOptions.Map <- map\n let marker = new Marker(markerOptions)\n let newIcon = \n new Icon(\n Url = \"websharper-icon.png\"\n )\n newIcon.Size <- new Size(32., 32.)\n newIcon.ScaledSize <- new Size(32., 32.)\n marker.SetIcon newIcon\n ()\n\n Event.AddListener(map, \"bounds_changed\", As addMarkers) |> ignore\n\n []\n let InfoWindow() =\n Sample <| fun map ->\n let center = map.GetCenter()\n let helloWorldElement = Span [Text \"Hello World\"]\n let iwOptions = new InfoWindowOptions()\n iwOptions.Content <- Union1Of2 helloWorldElement.Body\n iwOptions.Position <- center\n let iw = new InfoWindow(iwOptions)\n iw.Open(map)\n\n []\n let Controls() =\n Sample <| fun map ->\n let center = new LatLng(37.4419, -122.1419)\n let options = new MapOptions(center, 8)\n \/\/options.DisableDefaultUI <- true\n options.ZoomControl <- false\n options.FullscreenControl <- false\n\n let scOptions = new StreetViewControlOptions()\n scOptions.Position <- ControlPosition.TOP_RIGHT\n options.StreetViewControl <- true\n options.StreetViewControlOptions <- scOptions\n\n let mcOptions = new MapTypeControlOptions()\n mcOptions.Position <- ControlPosition.TOP_CENTER\n mcOptions.Style <- MapTypeControlStyle.DROPDOWN_MENU\n options.MapTypeControl <- true\n options.MapTypeControlOptions <- mcOptions\n\n \/\/ Pan control Won't work anymore. From comments:\n \/\/ Note: The Pan control is not available in the new set of controls introduced in v3.22 of the Google Maps JavaScript API.\n \/\/options.PanControl <- true\n \/\/let pcOptions = new PanControlOptions()\n \/\/pcOptions.Position <- ControlPosition.TOP_CENTER\n \/\/options.PanControlOptions <- pcOptions\n\n \/\/ NavigationControlOptions has been removed from API.\n \/\/let ncOptions = new NavigationControlOptions()\n \/\/ncOptions.Style <- NavigationControlStyle.ZOOM_PAN\n\n map.SetOptions options\n\n []\n let SimpleDirections() =\n Sample <| fun map ->\n let directionsService = new DirectionsService()\n let directionsDisplay = new DirectionsRenderer();\n map.SetCenter(new LatLng(41.850033, -87.6500523))\n map.SetZoom 7\n map.SetMapTypeId MapTypeId.ROADMAP\n let a = DirectionsRendererOptions()\n directionsDisplay.SetMap(map)\n let mapDiv = map.GetDiv()\n let dirPanel = Div [ Attr.Name \"directionsDiv\"]\n let j = JQuery.Of(mapDiv)\n j.After(dirPanel.Dom).Ignore\n directionsDisplay.SetPanel dirPanel.Dom\n let calcRoute () =\n let start = \"chicago, il\"\n let destination = \"st louis, mo\"\n let request = new DirectionsRequest(start, destination, TravelMode.DRIVING)\n directionsService.Route(request, fun (result, status) ->\n if status = DirectionsStatus.OK then\n directionsDisplay.SetDirections result)\n calcRoute ()\n\n []\n let DirectionsWithWaypoints() =\n Sample <| fun map ->\n let directionsService = new DirectionsService()\n let directionsDisplay = new DirectionsRenderer();\n map.SetCenter(new LatLng(41.850033, -87.6500523))\n map.SetZoom 7\n map.SetMapTypeId MapTypeId.ROADMAP\n let a = DirectionsRendererOptions()\n directionsDisplay.SetMap(map)\n let mapDiv = map.GetDiv()\n let dirPanel = Div [Attr.Name \"directionsDiv\"]\n let j = JQuery.Of mapDiv\n j.After(dirPanel.Dom).Ignore\n directionsDisplay.SetPanel dirPanel.Dom\n let calcRoute () =\n let start = \"chicago, il\"\n let destination = \"st louis, mo\"\n\n let request = new DirectionsRequest(start, destination, TravelMode.DRIVING)\n let waypoints =\n [|\"champaign, il\"\n \"decatur, il\" |]\n |> Array.map (fun x ->\n let wp = new DirectionsWaypoint()\n wp.Location <- Place(x)\n wp)\n\n request.Waypoints <- waypoints\n directionsService.Route(request, fun (result, status) ->\n if status = DirectionsStatus.OK then\n directionsDisplay.SetDirections result)\n calcRoute ()\n\n []\n \/\/\/ Since it's not available in v3. We make it using the ImageMapType\n \/\/\/ Taken from: http:\/\/code.google.com\/p\/gmaps-samples-v3\/source\/browse\/trunk\/planetary-maptypes\/planetary-maptypes.html?r=206\n \/\/ NOTE: the URL doesn't work anymore.\n let Moon() =\n Sample <| fun map ->\n \/\/Normalizes the tile URL so that tiles repeat across the x axis (horizontally) like the\n \/\/standard Google map tiles.\n let getHorizontallyRepeatingTileUrl(coord: Point, zoom: int, urlfunc: (Point * int -> string)) : string =\n let mutable x = coord.X\n let y = coord.Y\n let tileRange = float (1 <<< zoom)\n if (y < 0. || y >= tileRange)\n then null\n else\n if x < 0. || x >= tileRange\n then x <- (x % tileRange + tileRange) % tileRange\n urlfunc(new Point(x, y), zoom)\n\n let itOptions = new ImageMapTypeOptions()\n\n itOptions.GetTileUrl <-\n ThisFunc<_,_,_,_>(fun _ coord zoom ->\n getHorizontallyRepeatingTileUrl (coord, zoom,\n (fun (coord, zoom) ->\n let bound = Math.Pow(float 2, float zoom)\n (\"http:\/\/mw1.google.com\/mw-planetary\/lunar\/lunarmaps_v1\/clem_bw\/\"\n + (string zoom) + \"\/\" + (string coord.X) + \"\/\" + (string (bound - coord.Y - 1.) + \".jpg\")))))\n\n itOptions.TileSize <- new Size(256., 256.)\n itOptions.MaxZoom <- 9\n itOptions.MinZoom <- 0\n itOptions.Name <- \"Moon\"\n\n let it = new ImageMapType(itOptions)\n let center = new LatLng(0., 0.)\n \/\/let mapIds = [| box \"Moon\" |> unbox |]\n let mapIds = [| \"Moon\" |]\n let mapControlOptions =\n let mco = new MapTypeControlOptions()\n mco.Style <- MapTypeControlStyle.DROPDOWN_MENU\n mco.MapTypeIds <- mapIds\n mco\n\n \/\/let options = new MapOptions(center, 0, MapTypeId = mapIds.[0])\n \/\/let mapTypeIdU = Union.Union2Of2 mapIds.[0]\n let mapTypeIdU = Union2Of2 mapIds.[0]\n let options = new MapOptions(center, 0, MapTypeId = mapTypeIdU)\n options.MapTypeControlOptions <- mapControlOptions\n map.SetOptions options\n \/\/ FIXME\n \/\/ map.MapTypes.Set(\"Moon\", it)\n \/\/ TODO: Add the credit part\n ()\n\n []\n let Weather() =\n Sample <| fun map ->\n let images = [| \"sun\"; \"rain\"; \"snow\"; \"storm\" |]\n let getWeatherIcon () =\n let i = int <| Math.Floor(float images.Length * Math.Random())\n \/\/TODO: Invalid path to imagens. Find alternative icons.\n Google.Maps.Icon(\n Url = (\"http:\/\/gmaps-utility-library.googlecode.com\/svn\/trunk\/markermanager\/release\/examples\/images\/\"\n + images.[i] + \".png\"))\n\n let addMarkers (_:obj) =\n let bounds = map.GetBounds()\n let sw = bounds.GetSouthWest()\n let ne = bounds.GetNorthEast()\n let lngSpan = ne.Lng() - sw.Lng()\n let latSpan = ne.Lat() - sw.Lat()\n let rnd = Math.Random\n for i in 1..10 do\n let point = new LatLng(sw.Lat() + (latSpan * rnd()),\n sw.Lng() + (lngSpan * rnd()))\n let markerOptions = new MarkerOptions(point)\n markerOptions.Icon <- getWeatherIcon()\n markerOptions.Map <- map\n new Marker(markerOptions) |> ignore\n\n Event.AddListener(map, \"bounds_changed\", As addMarkers) |> ignore\n\n\/\/ Not supported in v3.\n\/\/\n\/\/ []\n\/\/ let IconSize() =\n\/\/ Sample <| fun map ->\n\/\/\n\/\/ let addMarkers (_:obj) =\n\/\/ let bounds = map.GetBounds()\n\/\/ let sw = bounds.GetSouthWest()\n\/\/ let ne = bounds.GetNorthEast()\n\/\/ let lngSpan = ne.Lng() - sw.Lng()\n\/\/ let latSpan = ne.Lat() - sw.Lat()\n\/\/ let rnd = JMath.Random\n\/\/ for i in 1..10 do\n\/\/ let point = new LatLng(sw.Lat() + (latSpan * rnd()),\n\/\/ sw.Lng() + (lngSpan * rnd()))\n\/\/ let markerOptions = new MarkerOptions(point)\n\/\/ markerOptions.Map <- map\n\/\/ new Marker(markerOptions) |> ignore\n\/\/\n\/\/ Event.AddListener(map, \"bounds_changed\", addMarkers) |> ignore\n\n []\n let SimplePolygon() =\n Sample <| fun map ->\n map.SetCenter(new LatLng(37.4419, -122.1419))\n map.SetZoom(13)\n let polygon = new Polygon()\n let coords = [| new LatLng(37.4419, -122.1419)\n new LatLng(37.4519, -122.1519)\n new LatLng(37.4419, -122.1319)\n new LatLng(37.4419, -122.1419) |]\n polygon.SetPath coords\n polygon.SetMap map\n\n []\n let StreetView() =\n Sample <| fun map ->\n let fenwayPark = new LatLng(42.345573, -71.098623)\n map.SetCenter(fenwayPark)\n map.SetZoom(15)\n let marker = new Marker()\n marker.SetPosition fenwayPark\n marker.SetMap map\n let options = new MapOptions(fenwayPark, 14)\n options.StreetViewControl <- true\n map.SetOptions options\n\n []\n let StreetViewPanoramaOnly() =\n Sample <| fun map ->\n let fenwayPark = new LatLng(42.345573, -71.098623)\n map.SetCenter(fenwayPark)\n map.SetZoom(15)\n\n let panorama = new StreetViewPanorama(map.GetDiv())\n panorama.SetPosition(fenwayPark)\n let svPov = new StreetViewPov()\n svPov.Heading <- 34.\n svPov.Pitch <- 10.\n panorama.SetPov(svPov)\n map.SetStreetView(panorama)\n\n []\n let PrimitiveEvent () =\n Sample <| fun map ->\n let clickAction (_:obj) = Util.Alert \"Map Clicked!\" \/\/ Window.Alert \"Map Clicked!\"\n Event.AddListener(map, \"click\", As clickAction)\n |> ignore\n\n []\n let SimplePolyline() =\n Sample <| fun map ->\n let coords = [| new LatLng(37.4419, -122.1419)\n new LatLng(37.4519, -122.1519)|]\n \n let polylineOptions = new PolylineOptions()\n polylineOptions.StrokeColor <- \"#ff0000\"\n \/\/polylineOptions.Path <- Union MVC.MVCArray.[LatLng],Type.ArrayOf LatLng>.Union2Of2 coords\n \/\/ Union,LatLng []>\n \/\/polylineOptions.Path <- Union,LatLng []>.Union2Of2 coords\n polylineOptions.Path <- Union2Of2 coords\n polylineOptions.Map <- map\n new Polyline(polylineOptions)\n |> ignore\n\n []\n let Samples () =\n Div [\n H1 [Text \"Google Maps Samples\"]\n MarkersWithLabel ()\n MarkersWithSymbol ()\n MarkersWithIcon ()\n SimpleMap ()\n PanTo ()\n RandomMarkers ()\n InfoWindow ()\n Controls ()\n SimpleDirections ()\n DirectionsWithWaypoints ()\n \/\/Moon ()\n Weather ()\n SimplePolygon ()\n StreetView ()\n StreetViewPanoramaOnly ()\n PrimitiveEvent ()\n SimplePolyline ()\n H1 [Text \"HeatMaps\"]\n Div [HeatMapSample.Sample()]\n H1 [Text \"Unit Tests\"]\n Div [UnitTests.RunTests()]\n ]\n\n[]\ntype Samples() =\n inherit Web.Control()\n\n []\n override this.Body = SamplesInternals.Samples () :> _\n\n\nopen WebSharper.Sitelets\n\ntype Action = | Index\n\nmodule Site =\n\n open WebSharper.Html.Server\n\n let HomePage ctx =\n Content.Page(\n Title = \"WebSharper Google Maps Tests\",\n Body = [Div [new Samples()]]\n )\n\n let Main = Sitelet.Content \"\/\" Index HomePage\n\n[]\ntype Website() =\n interface IWebsite with\n member this.Sitelet = Site.Main\n member this.Actions = [Action.Index]\n\n[)>]\ndo ()\n","avg_line_length":38.3853564547,"max_line_length":135,"alphanum_fraction":0.5230900512}
+{"size":1638,"ext":"fs","lang":"F#","max_stars_count":null,"content":"module Homework2Tests\n\nopen Homework2\nopen NUnit.Framework\nopen FsUnit\nopen FsCheck\nopen CountingEvenNumbers\nopen MapForBinaryTree\nopen ArithmeticExpressionTree\nopen GeneratorOfPrimeNumbers\n\n\n[]\nlet testForCountEvenUsingMap () =\n let list1 = [1; 5; 4; 2; 222; 9; 0]\n let list2 = []\n (countEvenUsingMap list1, countEvenUsingMap list2) |> should equal (4, 0)\n\n[]\nlet mapShouldBeEqualFoldAndFilter () =\n let inner (list: list) =\n let test1 = countEvenUsingMap list = countEvenUsingFold list\n let test2 = countEvenUsingFilter list = countEvenUsingFold list\n let test3 = countEvenUsingFilter list = countEvenUsingMap list\n (test1, test2, test3) |> should equal (true, true, true)\n Check.QuickThrowOnFailure inner\n \n[] \nlet testForMapBinaryTree () =\n let tree1 = BinaryTree.Node(BinaryTree.Node(None, 2, None), 1, BinaryTree.Node(None, 3, None))\n let tree2 = BinaryTree.Node(BinaryTree.Node(None, 4, None), 2, BinaryTree.Node(None, 6, None))\n mapForTree (fun x -> x * 2) tree1 |> should equal tree2\n \n[] \nlet testForSubAndMult () =\n let tree = Node(Node(Leaf 6, Subtraction, Leaf 3), Multiplication, Leaf 5)\n calculateTree tree |> should equal 15\n\n[]\nlet testForDivSumAndMult () =\n let tree = Node(Node(Leaf 10, Division, Leaf 2), Multiplication, (Node (Leaf 1, Addition, Leaf 0)))\n calculateTree tree |> should equal 5\n \n[]\nlet testForGeneratorPrimeNumbers () =\n let res = seq { for i in 0 .. 9 do Seq.item i generatePrimeNumbers}\n let expect = seq { 2; 3; 5; 7; 11; 13; 17; 19; 23; 29 }\n res |> should equal expect","avg_line_length":34.125,"max_line_length":103,"alphanum_fraction":0.6898656899}
+{"size":80,"ext":"fs","lang":"F#","max_stars_count":100.0,"content":"[]\nmodule Abc\n\nlet test () =\n printfn \"fs: %A\" fsi.CommandLineArgs\n","avg_line_length":13.3333333333,"max_line_length":40,"alphanum_fraction":0.65}
+{"size":3549,"ext":"fs","lang":"F#","max_stars_count":null,"content":"namespace Ionide.VSCode.FSharp\n\nopen System\nopen Fable.Core\nopen Fable.Core.JsInterop\nopen Fable.Import\nopen Fable.Import.vscode\nopen Fable.Import.Node\n\nopen DTO\nopen Ionide.VSCode\nopen Ionide.VSCode.Helpers\n\n\n\nmodule WebPreview =\n let private previewUri = Uri.parse \"webpreview:\/\/preview\"\n let private eventEmitter = vscode.EventEmitter()\n let private update = eventEmitter.event\n\n let mutable linuxPrefix = \"\"\n let mutable command = \"packages\/FAKE\/tools\/FAKE.exe\"\n let mutable host = \"\"\n let mutable port = 8083\n let mutable script = \"\"\n let mutable build = \"\"\n let mutable startString = \"\"\n let mutable parameters = [||]\n let mutable startingPage = \"\"\n let mutable fakeProcess : child_process_types.ChildProcess Option = None\n\n let loadSettings () =\n linuxPrefix <- Settings.loadOrDefault (fun s -> s.WebPreview.linuxPrefix) \"mono\"\n command <- Settings.loadOrDefault (fun s -> s.WebPreview.command) \"packages\/FAKE\/tools\/FAKE.exe\"\n host <- Settings.loadOrDefault (fun s -> s.WebPreview.host) \"localhost\"\n port <- Settings.loadOrDefault (fun s -> s.WebPreview.port) 8888\n script <- Settings.loadOrDefault (fun s -> s.WebPreview.script) \"build.fsx\"\n build <- Settings.loadOrDefault (fun s -> s.WebPreview.build) \"Serve\"\n startString <- Settings.loadOrDefault (fun s -> s.WebPreview.startString) \"listener started\"\n parameters <- Settings.loadOrDefault (fun s -> s.WebPreview.parameters) [||]\n startingPage <- Settings.loadOrDefault (fun s -> s.WebPreview.startingPage) \"\"\n ()\n\n let private createProvider () =\n\n let generate () =\n let src = sprintf \"http:\/\/%s:%d\/%s\" host port startingPage\n let style = \"height: 100%; width: 100%; background-color: white;\"\n sprintf \"\" style src\n let v = eventEmitter.event\n\n let p =\n { new TextDocumentContentProvider\n with\n member this.provideTextDocumentContent () = generate ()\n }\n p?onDidChange <- eventEmitter.event\n p\n\n\n let parseResponse o =\n if JS.isDefined o && isNotNull o then\n let str = o.ToString ()\n if str.Contains startString then\n vscode.commands.executeCommand(\"vscode.previewHtml\", previewUri, 2)\n |> ignore\n ()\n\n let close () =\n try\n fakeProcess |> Option.iter (fun p ->\n p.kill ()\n fakeProcess <- None)\n with\n | _ -> ()\n\n let show () =\n loadSettings ()\n if fakeProcess.IsSome then close ()\n let cp =\n let args = sprintf \"%s %s port=%d\" script build port\n let args' = parameters |> Array.fold (fun acc e -> acc + \" \" + e) args\n Process.spawn command linuxPrefix args'\n\n cp.stdout?on $ (\"readable\", (fun n -> cp.stdout?read $ () |> parseResponse )) |> ignore\n cp.stderr?on $ (\"readable\", (cp.stdout?read $ () |> (fun o -> if JS.isDefined o && isNotNull o then Browser.console.error(o.ToString())) )) |> ignore\n fakeProcess <- Some cp\n\n\n\n let activate (disposables : Disposable[]) =\n let prov = createProvider ()\n workspace.registerTextDocumentContentProvider(\"webpreview\" |> unbox, prov) |> ignore\n\n commands.registerCommand(\"webpreview.Show\", show |> unbox) |> ignore\n commands.registerCommand(\"webpreview.Refresh\", (fun _ -> eventEmitter.fire previewUri) |> unbox) |> ignore\n ()","avg_line_length":36.587628866,"max_line_length":157,"alphanum_fraction":0.6162299239}
+{"size":1128,"ext":"fs","lang":"F#","max_stars_count":null,"content":"[]\nmodule JetBrains.ReSharper.Plugins.FSharp.Util.FSharpAssemblyUtil\n\nopen JetBrains.ProjectModel\nopen JetBrains.ReSharper.Psi\nopen JetBrains.ReSharper.Psi.Modules\nopen JetBrains.ReSharper.Resources.Shell\nopen JetBrains.Util\n\n[]\nlet interfaceDataVersionAttrTypeName = clrTypeName \"Microsoft.FSharp.Core.FSharpInterfaceDataVersionAttribute\"\n\nlet isFSharpAssemblyKey = Key(\"IsFSharpAssembly\")\n\n[]\nlet isFSharpAssembly (psiModule: IPsiModule) =\n match psiModule.ContainingProjectModule with\n | :? IProject -> false\n | _ ->\n\n match psiModule.GetData(isFSharpAssemblyKey) with\n | null ->\n use cookie = ReadLockCookie.Create()\n let attrs = psiModule.GetPsiServices().Symbols.GetModuleAttributes(psiModule)\n let isFSharpAssembly = attrs.HasAttributeInstance(interfaceDataVersionAttrTypeName, false)\n\n psiModule.PutData(isFSharpAssemblyKey, if isFSharpAssembly then BooleanBoxes.True else BooleanBoxes.False)\n isFSharpAssembly\n\n | value -> value == BooleanBoxes.True\n","avg_line_length":36.3870967742,"max_line_length":114,"alphanum_fraction":0.7854609929}
+{"size":4467,"ext":"fs","lang":"F#","max_stars_count":20.0,"content":"\ufeffmodule Chimayo.Ssis.Reader2008.ExecuteProcessTask\r\n\r\nopen Chimayo.Ssis.Common\r\nopen Chimayo.Ssis.Common.CustomOperators\r\n\r\nopen Chimayo.Ssis.Xml.XPath\r\nopen Chimayo.Ssis.Ast.ControlFlow\r\nopen Chimayo.Ssis.Reader2008.Internals\r\n\r\nlet taskNames =\r\n [\r\n \"Microsoft.SqlServer.Dts.Tasks.ExecuteProcess.ExecuteProcess, Microsoft.SqlServer.ExecProcTask, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91\"\r\n \"STOCK:ExecuteProcessTask\"\r\n ]\r\n\r\n\r\nmodule ArguemntParser =\r\n open FParsec\r\n\r\n type ParserState = unit\r\n type StringParser = Parser\r\n type CharParser = Parser\r\n\r\n let joinStringFromList : string list -> string = List.toArray >> fun a -> System.String.Join(\"\",a)\r\n\r\n let escapedCharacterWithEscape : StringParser =\r\n pchar '\\\\' >>. anyChar |>> sprintf \"\\\\%c\"\r\n\r\n let quotedChar : StringParser =\r\n escapedCharacterWithEscape <|> (notFollowedByString \"\\\"\" >>. anyChar |>> (string))\r\n\r\n let quotedString : StringParser =\r\n skipChar '\"' >>. many quotedChar .>> skipChar '\"' |>> joinStringFromList |>> sprintf \"\\\"%s\\\"\"\r\n\r\n let tokenSeparator = many1 (skipString \" \" <|> skipString \"\\t\")\r\n\r\n let unquotedChar : StringParser =\r\n escapedCharacterWithEscape <|> (notFollowedBy tokenSeparator >>. anyChar |>> (string))\r\n\r\n let textPartial : StringParser =\r\n many1 unquotedChar |>> joinStringFromList\r\n\r\n let token =\r\n (attempt quotedString)\r\n <|> (attempt textPartial)\r\n\r\n let expressionParser =\r\n sepBy token tokenSeparator .>> CharParsers.eof\r\n\r\n let parse arguments =\r\n CharParsers.runParserOnString expressionParser () \"arguments\" arguments\r\n |> function\r\n | Success (x,_,_) -> x\r\n | Failure (msg,_,_) -> failwith (sprintf \"Unable to parse arguments: '%s'\" msg)\r\n\r\nlet parseArguments arguments = ArguemntParser.parse arguments\r\n\r\nlet read nav =\r\n let objectData = nav |> select1 \"DTS:ObjectData\/ExecuteProcessData\"\r\n CftExecuteProcess\r\n {\r\n executableTaskBase = nav |> ExecutableTaskBase.read\r\n \r\n targetExecutable = objectData |> Extractions.anyString \"self::*\/@Executable\" \"\"\r\n requireFullFilename = objectData |> Extractions.anyBool \"self::*\/@RequireFullFileName\" true\r\n arguments = objectData |> Extractions.anyString \"self::*\/@Arguments\" \"\" |> parseArguments\r\n workingDirectory = objectData |> Extractions.anyString \"self::*\/@WorkingDirectory\" \"\"\r\n failTaskOnReturnCodeNotEqualToValue =\r\n (objectData |> Extractions.anyBool \"self::*\/@FailTaskIfReturnCodeIsNotSuccessValue\" true, objectData |> Extractions.anyInt \"self::*\/@SuccessValue\" 0)\r\n |> function | false, _ -> None | _, successValue -> Some successValue\r\n terminateAfterTimeoutSeconds =\r\n (objectData |> Extractions.anyBool \"self::*\/@TerminateAfterTimeout\" true, objectData |> Extractions.anyInt \"self::*\/@TimeOut\" 0)\r\n |> function | false, _ -> None | _, 0 -> None | _, timeout -> Some timeout\r\n standardInputVariable =\r\n objectData |> Extractions.anyString \"self::*\/@StandardInputVariable\" \"\"\r\n |> fun s -> s.Trim()\r\n |> function \"\" -> None | vname -> nav |> Common.getFullyQualifiedVariableName vname |> Some\r\n standardOutputVariable =\r\n objectData |> Extractions.anyString \"self::*\/@StandardOutputVariable\" \"\"\r\n |> fun s -> s.Trim()\r\n |> function \"\" -> None | vname -> nav |> Common.getFullyQualifiedVariableName vname |> Some\r\n standardErrorVariable =\r\n objectData |> Extractions.anyString \"self::*\/@StandardErrorVariable\" \"\"\r\n |> fun s -> s.Trim()\r\n |> function \"\" -> None | vname -> nav |> Common.getFullyQualifiedVariableName vname |> Some\r\n windowStyle = \r\n objectData |> Extractions.anyString \"self::*\/WindowStyle\" \"Normal\"\r\n |> fun s -> s.Trim()\r\n |> function\r\n | \"Normal\" -> CfWindowStyle.Normal\r\n | \"Hidden\" -> CfWindowStyle.Hidden\r\n | \"Minimized\" -> CfWindowStyle.Minimized\r\n | \"Maximized\" -> CfWindowStyle.Maximized\r\n | _ -> failwith \"Unexpected window style in ExecuteProcess task\"\r\n\r\n }\r\n\r\n\r\n\r\n","avg_line_length":44.67,"max_line_length":172,"alphanum_fraction":0.6118200134}
+{"size":6422,"ext":"fs","lang":"F#","max_stars_count":null,"content":"\ufeffnamespace FSharpKoans\r\nopen NUnit.Framework\r\n\r\n(*\r\n In functional programming, we often care about the \"shape\" of data, rather\r\n than the data itself. For example, if we are trying to find the length of a list,\r\n it doesn't matter whether we have a list-of-strings or a list-of-floats or a\r\n list-of-something-elses. All that matters is that the data occurs in the shape\r\n of a list. Similarly, if we are given a tuple of two items and we only look at\r\n the second item, then the type of the first item doesn't matter to us - it\r\n could be anything, and the meaning of the program wouldn't change at all!\r\n \r\n But what if we are given a tuple of 4 items, and our function outputs the\r\n third item? Now we have an interesting situation. We hope to be able to\r\n take in a tuple of ANY four types, but output a value that has the type of\r\n the third item. We can achieve this if we specify the type of the tuple\r\n generically, as\r\n \r\n 'a * 'b * 'c * 'd\r\n\r\n This gives each component of the tuple a \"fake\" type (indicated by the ' symbol\r\n before the type-name). The function returns the third element, so we can\r\n say that the type of the function is\r\n\r\n 'a * 'b * 'c * 'd -> 'c\r\n\r\n ...and now we have a perfectly generic function, which can be use with any\r\n 4-tuple, and which is also completely safe to use. And as a side-effect,\r\n by looking at the function type, we can tell what the function does without\r\n even looking at the code of the function! The function cannot know what\r\n 'a, 'b, 'c, or 'd types are, and it cannot know how to construct them. The\r\n only way that it can get hold of a 'c value is by having it passed in. Since\r\n we know this to be true, it must be the case that the function is returning\r\n the third item in the tuple [0]!\r\n\r\n The ability to look at the *shape* of data, and ignore unnecessarily-specific\r\n types, is called \"parametric polymorphism\". The non-specific (or \"generic\")\r\n types are given as 'a, 'b, 'c, and so on. We sometimes say that types which are\r\n parametrically polymorphic are \"generic types\".\r\n\r\n We may sometimes want to make our more structured types, like records\r\n or discriminated unions, generic.\r\n*)\r\n\r\nmodule ``10: Parametric polymorphism`` =\r\n (*\r\n The next test demonstrates *type inference*.\r\n \r\n Not all functional languages are typed. The first (and, arguably, the most powerful)\r\n functional language was Lisp, and Lisp isn't strongly typed. Typing is something that tends\r\n to work very well with functional programming, but isn't something that is essential to\r\n functional programming. In the case of F#, typing often stops you from making \"silly\" errors.\r\n\r\n F# uses type inference extensively. Type inference means that it tries to work out\r\n (or \"infer\") what type a particular name is by looking at code around it. A readable, if\r\n simplified, explanation of how this works can be found at:\r\n http:\/\/fsharpforfunandprofit.com\/posts\/type-inference\/\r\n *)\r\n \r\n []\r\n let ``01 The type of symbols in variable patterns are inferred`` () = \r\n let x = 50\r\n let y = \"a string\"\r\n let z = -4.23\r\n let a = false\r\n let b = 't'\r\n x |> should be ofType\r\n y |> should be ofType\r\n z |> should be ofType\r\n a |> should be ofType\r\n b |> should be ofType\r\n\r\n []\r\n let ``02 id: the simplest built-in generic function`` () =\r\n \/\/ `id` is the identify function: it takes an input ... and gives it back immediately.\r\n id 8 |> should equal 8\r\n id 7.6 |> should equal 7.6\r\n id \"wut!\" |> should equal \"wut!\"\r\n \/\/ id can be surprisingly useful. Remember it :).\r\n\r\n []\r\n let ``03 Defining a generic function`` () =\r\n let f x y = (x,y,y)\r\n f 4 5 |> should equal (4, 5, 5)\r\n f \"k\" 'p' |> should equal (\"k\", 'p', 'p')\r\n\r\n \/\/ this is how we might define a record type with two generic fields.\r\n type GenericRecordExample<'a,'b> = {\r\n Something : 'a\r\n Blah : int\r\n Otherwise : 'b\r\n What : 'a * string * 'b\r\n }\r\n \/\/ we might create this with: { Something=5; Blah=8; Otherwise=9.3; What=77,\"hi\",0.88 }\r\n\r\n type MyRecord<'a,'b> = {\r\n Who : 'a \/\/ <-- should be generic\r\n What : 'b \/\/ <-- should be generic, and a different type to Who\r\n Where : string\r\n }\r\n\r\n []\r\n let ``04 Creating a generic record`` () =\r\n \/\/ You need to edit the definition of MyRecord first! It's just above this test.\r\n let a = {Who=\"The Doctor\";What=4.53;Where=\"TTFN\"}\r\n let b = {Who='R';What=false;Where=\"tiffin\"} \r\n a.Who |> should equal \"The Doctor\"\r\n b.Who |> should equal 'R'\r\n a.What |> should equal 4.53\r\n b.What |> should equal false\r\n a.Where |> should equal \"TTFN\"\r\n b.Where |> should equal \"tiffin\"\r\n \r\n type GenericDiscriminatedUnionExample<'a,'b> =\r\n | Frist\r\n | Secnod of 'a * 'b\r\n | Thrid of ('a -> ('b * 'a * int)) \/\/ <-- this shouldn't look odd. Functions are first-class!\r\n\r\n []\r\n let ``05 Creating a generic discriminated union (Part 1).`` () =\r\n let a = Secnod (6.55, 7)\r\n let b = Thrid (fun k -> true, k, 8)\r\n \/\/ how do you write a generic type?\r\n a |> should be ofType->(float*int)>\r\n b |> should be ofType->(bool*'a*int)>\r\n\r\n type MyDiscriminatedUnion<'a,'b> =\r\n | Furoth of 'a\r\n | Fevi\r\n | Sxi of 'b\r\n\r\n []\r\n let ``06 Creating a generic discriminated union (Part 2).`` () =\r\n \/\/ You need to edit the definition of MyDiscriminatedUnion first! It's just above this test.\r\n let a = Furoth 7\r\n let b = Sxi \"bleh\"\r\n let c = Furoth 't'\r\n let d = Sxi true\r\n match a with\r\n | Furoth n -> n |> should equal 7\r\n | _ -> Assert.Fail ()\r\n match b with\r\n | Sxi x -> x |> should equal \"bleh\"\r\n | _ -> Assert.Fail ()\r\n match c with\r\n | Furoth p -> p |> should equal 't'\r\n | _ -> Assert.Fail ()\r\n match d with\r\n | Sxi y -> y |> should equal true\r\n | _ -> Assert.Fail ()\r\n","avg_line_length":42.5298013245,"max_line_length":103,"alphanum_fraction":0.6001245718}
+{"size":8964,"ext":"fs","lang":"F#","max_stars_count":null,"content":"namespace Plotly.NET.TraceObjects\n\nopen Plotly.NET\nopen Plotly.NET.LayoutObjects\nopen DynamicObj\nopen System\nopen System.Runtime.InteropServices\n\n\/\/\/ Marker type inherits from dynamic object\ntype Marker () =\n inherit DynamicObj ()\n\n \/\/\/ Initialized Marker object\n static member init\n ( \n [] ?AutoColorScale : bool,\n [] ?CAuto : bool,\n [] ?CMax : float,\n [] ?CMid : float,\n [] ?CMin : float,\n [] ?Color : Color,\n [] ?Colors : seq,\n [] ?ColorAxis : StyleParam.SubPlotId,\n [] ?ColorBar : ColorBar,\n [] ?Colorscale : StyleParam.Colorscale,\n [] ?Gradient : Gradient,\n [] ?Outline : Line,\n [] ?Size : int,\n [] ?MultiSize : seq,\n [] ?Opacity : float,\n [] ?Pattern : Pattern,\n [] ?MultiOpacity : seq,\n [] ?Symbol : StyleParam.MarkerSymbol,\n [] ?MultiSymbol : seq,\n [] ?OutlierColor : Color,\n [] ?OutlierWidth : int,\n [] ?Maxdisplayed : int,\n [] ?ReverseScale : bool,\n [] ?ShowScale : bool,\n [] ?SizeMin : int,\n [] ?SizeMode : StyleParam.MarkerSizeMode,\n [] ?SizeRef : int\n\n ) =\n Marker () \n |> Marker.style\n (\n ?AutoColorScale = AutoColorScale,\n ?CAuto = CAuto ,\n ?CMax = CMax ,\n ?CMid = CMid ,\n ?CMin = CMin ,\n ?Color = Color ,\n ?Colors = Colors ,\n ?ColorAxis = ColorAxis ,\n ?ColorBar = ColorBar ,\n ?Colorscale = Colorscale ,\n ?Gradient = Gradient ,\n ?Outline = Outline ,\n ?Size = Size ,\n ?MultiSize = MultiSize ,\n ?Opacity = Opacity ,\n ?Pattern = Pattern ,\n ?MultiOpacity = MultiOpacity ,\n ?Symbol = Symbol ,\n ?MultiSymbol = MultiSymbol ,\n ?OutlierColor = OutlierColor ,\n ?OutlierWidth = OutlierWidth ,\n ?Maxdisplayed = Maxdisplayed ,\n ?ReverseScale = ReverseScale ,\n ?ShowScale = ShowScale ,\n ?SizeMin = SizeMin ,\n ?SizeMode = SizeMode ,\n ?SizeRef = SizeRef \n )\n\n \/\/ Applies the styles to Marker()\n static member style\n ( \n [] ?AutoColorScale : bool,\n [] ?CAuto : bool,\n [] ?CMax : float,\n [] ?CMid : float,\n [] ?CMin : float,\n [] ?Color : Color,\n [] ?Colors : seq,\n [] ?ColorAxis : StyleParam.SubPlotId,\n [] ?ColorBar : ColorBar,\n [] ?Colorscale : StyleParam.Colorscale,\n [] ?Gradient : Gradient,\n [] ?Outline : Line,\n [] ?Size : int,\n [] ?MultiSize : seq,\n [] ?Opacity : float,\n [] ?MultiOpacity : seq,\n [] ?Pattern : Pattern,\n [] ?Symbol : StyleParam.MarkerSymbol,\n [] ?MultiSymbol : seq, \n [] ?Symbol3D : StyleParam.MarkerSymbol3D,\n [] ?MultiSymbol3D : seq,\n [] ?OutlierColor : Color,\n [] ?OutlierWidth : int,\n [] ?Maxdisplayed : int,\n [] ?ReverseScale : bool,\n [] ?ShowScale : bool,\n [] ?SizeMin : int,\n [] ?SizeMode : StyleParam.MarkerSizeMode,\n [] ?SizeRef : int\n ) =\n (fun (marker: Marker) -> \n \n AutoColorScale |> DynObj.setValueOpt marker \"autocolorscale\"\n CAuto |> DynObj.setValueOpt marker \"cauto\"\n CMax |> DynObj.setValueOpt marker \"cmax\"\n CMid |> DynObj.setValueOpt marker \"cmid\"\n CMin |> DynObj.setValueOpt marker \"cmin\"\n Color |> DynObj.setValueOpt marker \"color\"\n Colors |> DynObj.setValueOpt marker \"colors\"\n ColorAxis |> DynObj.setValueOptBy marker \"coloraxis\" StyleParam.SubPlotId.convert\n ColorBar |> DynObj.setValueOpt marker \"colorbar\"\n Colorscale |> DynObj.setValueOptBy marker \"colorscale\" StyleParam.Colorscale.convert\n Gradient |> DynObj.setValueOpt marker \"gradient\"\n Outline |> DynObj.setValueOpt marker \"line\"\n (Size, MultiSize) |> DynObj.setSingleOrMultiOpt marker \"size\"\n (Opacity, MultiOpacity) |> DynObj.setSingleOrMultiOpt marker \"opacity\"\n Pattern |> DynObj.setValueOpt marker \"pattern\"\n (Symbol, MultiSymbol) |> DynObj.setSingleOrMultiOptBy marker \"symbol\" StyleParam.MarkerSymbol.convert\n (Symbol3D, MultiSymbol3D) |> DynObj.setSingleOrMultiOptBy marker \"symbol\" StyleParam.MarkerSymbol3D.convert\n OutlierColor |> DynObj.setValueOpt marker \"outliercolor\"\n OutlierWidth |> DynObj.setValueOpt marker \"outlierwidth\"\n Maxdisplayed |> DynObj.setValueOpt marker \"maxdisplayed\"\n ReverseScale |> DynObj.setValueOpt marker \"reversescale\"\n ShowScale |> DynObj.setValueOpt marker \"showscale\"\n SizeMin |> DynObj.setValueOpt marker \"sizemin\"\n SizeMode |> DynObj.setValueOpt marker \"sizemode\"\n SizeRef |> DynObj.setValueOpt marker \"sizeref\"\n\n marker\n )\n\n\n\n","avg_line_length":62.6853146853,"max_line_length":125,"alphanum_fraction":0.5242079429}
+{"size":90,"ext":"fs","lang":"F#","max_stars_count":14.0,"content":"varying vec2 vUv;\r\n\r\nvoid main( void ) {\r\n\r\n\tgl_FragColor = vec4( vec3( 1.0 ), 0.8 );\r\n\r\n}","avg_line_length":12.8571428571,"max_line_length":42,"alphanum_fraction":0.5555555556}
+{"size":7465,"ext":"fsx","lang":"F#","max_stars_count":1.0,"content":"\/\/ --------------------------------------------------------------------------------------\n\/\/ FAKE build script\n\/\/ --------------------------------------------------------------------------------------\n\n#r @\"packages\/FAKE\/tools\/NuGet.Core.dll\"\n#r @\"packages\/FAKE\/tools\/FakeLib.dll\"\nopen Fake\nopen Fake.Git\nopen Fake.AssemblyInfoFile\nopen Fake.ReleaseNotesHelper\nopen System\n#if MONO\n#else\n#load \"packages\/SourceLink.Fake\/Tools\/Fake.fsx\"\nopen SourceLink\n#endif\n\n\n\/\/ --------------------------------------------------------------------------------------\n\/\/ START TODO: Provide project-specific details below\n\/\/ --------------------------------------------------------------------------------------\n\n\/\/ Information about the project are used\n\/\/ - for version and project name in generated AssemblyInfo file\n\/\/ - by the generated NuGet package\n\/\/ - to run tests and to publish documentation on GitHub gh-pages\n\/\/ - for documentation, you also need to edit info in \"docs\/tools\/generate.fsx\"\n\n\/\/ The name of the project\n\/\/ (used by attributes in AssemblyInfo, name of a NuGet package and directory in 'src')\nlet project = \"laughing-wookie\"\n\n\/\/ Short summary of the project\n\/\/ (used as description in AssemblyInfo and as a short summary for NuGet package)\nlet summary = \"wookie\"\n\n\/\/ Longer description of the project\n\/\/ (used as a description for NuGet package; line breaks are automatically cleaned up)\nlet description = \"CQRS event Sourcing App\"\n\n\/\/ List of author names (for NuGet package)\nlet authors = [ \"Arthis\" ]\n\n\/\/ Tags for your project (for NuGet package)\nlet tags = \"F# CQRS ES GES\"\n\n\/\/ File system information \nlet solutionFile = \"laughing-wookie.sln\"\n\n\/\/ Pattern specifying assemblies to be tested using NUnit\nlet testAssemblies = \"tests\/**\/bin\/Release\/*Tests*.dll\"\n\n\/\/ Git configuration (used for publishing documentation in gh-pages branch)\n\/\/ The profile where the project is posted \nlet gitHome = \"https:\/\/github.com\/cannelle-plus\"\n\n\/\/ The name of the project on GitHub\nlet gitName = \"laughing-wookie\"\n\n\/\/ The url for the raw files hosted\nlet gitRaw = environVarOrDefault \"gitRaw\" \"https:\/\/raw.github.com\/cannelle-plus\"\n\n\/\/ The projection to deploy\nlet appToDeploy = \"src\/server\/bin\/Release\"\n\n\/\/ The files to deploy\nlet deployDir = \".\/deploy\/\"\n\n\n\/\/ --------------------------------------------------------------------------------------\n\/\/ END TODO: The rest of the file includes standard build steps\n\/\/ --------------------------------------------------------------------------------------\n\n\/\/ Read additional information from the release notes document\nEnvironment.CurrentDirectory <- __SOURCE_DIRECTORY__\nlet release = parseReleaseNotes (IO.File.ReadAllLines \"RELEASE_NOTES.md\")\n\nlet genFSAssemblyInfo (projectPath) =\n let projectName = System.IO.Path.GetFileNameWithoutExtension(projectPath)\n let basePath = \"src\/\" + projectName\n let fileName = basePath + \"\/AssemblyInfo.fs\"\n CreateFSharpAssemblyInfo fileName\n [ Attribute.Title (projectName)\n Attribute.Product project\n Attribute.Description summary\n Attribute.Version release.AssemblyVersion\n Attribute.FileVersion release.AssemblyVersion ]\n\nlet genCSAssemblyInfo (projectPath) =\n let projectName = System.IO.Path.GetFileNameWithoutExtension(projectPath)\n let basePath = \"src\/\" + projectName + \"\/Properties\"\n let fileName = basePath + \"\/AssemblyInfo.cs\"\n CreateCSharpAssemblyInfo fileName\n [ Attribute.Title (projectName)\n Attribute.Product project\n Attribute.Description summary\n Attribute.Version release.AssemblyVersion\n Attribute.FileVersion release.AssemblyVersion ]\n\n\/\/ Generate assembly info files with the right version & up-to-date information\nTarget \"AssemblyInfo\" (fun _ ->\n let fsProjs = !! \"src\/**\/*.fsproj\"\n let csProjs = !! \"src\/**\/*.csproj\"\n fsProjs |> Seq.iter genFSAssemblyInfo\n csProjs |> Seq.iter genCSAssemblyInfo\n)\n\n\/\/ --------------------------------------------------------------------------------------\n\/\/ Clean build results & restore NuGet packages\n\nTarget \"RestorePackages\" RestorePackages\n\nTarget \"Clean\" (fun _ ->\n CleanDirs [\"deploy\"; \"temp\"]\n)\n\nTarget \"CleanDocs\" (fun _ ->\n CleanDirs [\"docs\/output\"]\n)\n\n\/\/ --------------------------------------------------------------------------------------\n\/\/ Build library & test project\n\nTarget \"Build\" (fun _ ->\n !! solutionFile\n |> MSBuildRelease \"\" \"Rebuild\"\n |> ignore\n)\n\n\/\/ --------------------------------------------------------------------------------------\n\/\/ Run the unit tests using test runner\n\nTarget \"RunTests\" (fun _ ->\n !! testAssemblies\n |> xUnit (fun p ->\n { p with\n ToolPath = __SOURCE_DIRECTORY__ @@ \"\/tools\/xUnit-1.9.1\/xunit.console.clr4.exe\"\n ShadowCopy = false\n TimeOut = TimeSpan.FromMinutes 20.\n NUnitXmlOutput =true })\n)\n\n#if MONO\n#else\n\/\/ --------------------------------------------------------------------------------------\n\/\/ SourceLink allows Source Indexing on the PDB generated by the compiler, this allows\n\/\/ the ability to step through the source code of external libraries https:\/\/github.com\/ctaggart\/SourceLink\n\nTarget \"SourceLink\" (fun _ ->\n let baseUrl = sprintf \"%s\/%s\/{0}\/%%var2%%\" gitRaw (project.ToLower())\n use repo = new GitRepo(__SOURCE_DIRECTORY__)\n !! \"src\/**\/*.fsproj\"\n |> Seq.iter (fun f ->\n let proj = VsProj.LoadRelease f\n logfn \"source linking %s\" proj.OutputFilePdb\n let files = proj.Compiles -- \"**\/AssemblyInfo.fs\"\n repo.VerifyChecksums files\n proj.VerifyPdbChecksums files\n proj.CreateSrcSrv baseUrl repo.Revision (repo.Paths files)\n Pdbstr.exec proj.OutputFilePdb proj.OutputFilePdbSrcSrv\n )\n)\n#endif\n\n\/\/ --------------------------------------------------------------------------------------\n\/\/ deploy the app\n\nlet deployTarget t = (deployDir + t + \"\/\", t)\n\nlet deployTask (deployTarget,t) = \n let from = directoryInfo(appToDeploy)\n let towards =directoryInfo(deployTarget)\n copyRecursive from towards false\n |> Log \"Deploy-Output:\"\n (deployTarget,t)\n\nlet setConfig (deployTarget,t) =\n DeleteFile (deployTarget + \"server.exe.config\")\n Rename (deployTarget + \"server.exe.config\") (deployTarget + \"App.config_\" + t)\n\nTarget \"Deploy\" (fun _ ->\n [\"windows\"; \"linux\"; \"prod\"]\n |> List.map deployTarget\n |> List.map deployTask \n |> List.filter (fun (p,t) -> t<> \"windows\")\n |> List.iter setConfig \n )\n\n\/\/ --------------------------------------------------------------------------------------\n\/\/ Generate the documentation\n\nTarget \"GenerateReferenceDocs\" (fun _ ->\n if not <| executeFSIWithArgs \"docs\/tools\" \"generate.fsx\" [\"--define:RELEASE\"; \"--define:REFERENCE\"] [] then\n failwith \"generating reference documentation failed\"\n)\n\nTarget \"GenerateHelp\" (fun _ ->\n if not <| executeFSIWithArgs \"docs\/tools\" \"generate.fsx\" [\"--define:RELEASE\"; \"--define:HELP\"] [] then\n failwith \"generating help documentation failed\"\n)\n\nTarget \"GenerateDocs\" DoNothing\n\n\/\/ --------------------------------------------------------------------------------------\n\/\/ Run all targets by default. Invoke 'build ' to override\n\nTarget \"All\" DoNothing\n\n\"Clean\"\n ==> \"RestorePackages\"\n ==> \"AssemblyInfo\"\n ==> \"Build\"\n ==> \"RunTests\"\n ==> \"Deploy\"\n\/\/ =?> (\"GenerateReferenceDocs\",isLocalBuild && not isMono)\n\/\/ =?> (\"GenerateDocs\",isLocalBuild && not isMono)\n ==> \"All\"\n\n\nRunTargetOrDefault \"All\"\n","avg_line_length":33.778280543,"max_line_length":111,"alphanum_fraction":0.5931681179}
+{"size":43833,"ext":"fs","lang":"F#","max_stars_count":1.0,"content":"\/\/ Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.\n\nnamespace Internal.Utilities.Library \n\nopen System\nopen System.Collections.Generic\nopen System.Collections.Concurrent\nopen System.Diagnostics\nopen System.IO\nopen System.Threading\nopen System.Threading.Tasks\nopen System.Runtime.CompilerServices\n\n[]\nmodule internal PervasiveAutoOpens =\n \/\/\/ Logical shift right treating int32 as unsigned integer.\n \/\/\/ Code that uses this should probably be adjusted to use unsigned integer types.\n let (>>>&) (x: int32) (n: int32) = int32 (uint32 x >>> n)\n\n let notlazy v = Lazy<_>.CreateFromValue v\n\n let inline isNil l = List.isEmpty l\n\n \/\/\/ Returns true if the list has less than 2 elements. Otherwise false.\n let inline isNilOrSingleton l =\n match l with\n | [] \n | [_] -> true\n | _ -> false\n\n \/\/\/ Returns true if the list contains exactly 1 element. Otherwise false.\n let inline isSingleton l =\n match l with\n | [_] -> true\n | _ -> false\n\n let inline isNonNull x = not (isNull x)\n\n let inline nonNull msg x = if isNull x then failwith (\"null: \" + msg) else x\n\n let inline (===) x y = LanguagePrimitives.PhysicalEquality x y\n\n \/\/\/ Per the docs the threshold for the Large Object Heap is 85000 bytes: https:\/\/docs.microsoft.com\/en-us\/dotnet\/standard\/garbage-collection\/large-object-heap#how-an-object-ends-up-on-the-large-object-heap-and-how-gc-handles-them\n \/\/\/ We set the limit to be 80k to account for larger pointer sizes for when F# is running 64-bit.\n let LOH_SIZE_THRESHOLD_BYTES = 80_000\n\n let runningOnMono =\n#if ENABLE_MONO_SUPPORT\n \/\/ Officially supported way to detect if we are running on Mono.\n \/\/ See http:\/\/www.mono-project.com\/FAQ:_Technical\n \/\/ \"How can I detect if am running in Mono?\" section\n try\n Type.GetType \"Mono.Runtime\" <> null\n with _ ->\n \/\/ Must be robust in the case that someone else has installed a handler into System.AppDomain.OnTypeResolveEvent\n \/\/ that is not reliable.\n \/\/ This is related to bug 5506--the issue is actually a bug in VSTypeResolutionService.EnsurePopulated which is\n \/\/ called by OnTypeResolveEvent. The function throws a NullReferenceException. I'm working with that team to get\n \/\/ their issue fixed but we need to be robust here anyway.\n false\n#else\n false\n#endif\n\n type String with\n member inline x.StartsWithOrdinal value =\n x.StartsWith(value, StringComparison.Ordinal)\n\n member inline x.EndsWithOrdinal value =\n x.EndsWith(value, StringComparison.Ordinal)\n\n \/\/\/ Get an initialization hole \n let getHole (r: _ ref) = match r.Value with None -> failwith \"getHole\" | Some x -> x\n\n let reportTime =\n let mutable tFirst =None\n let mutable tPrev = None\n fun showTimes descr ->\n if showTimes then \n let t = Process.GetCurrentProcess().UserProcessorTime.TotalSeconds\n let prev = match tPrev with None -> 0.0 | Some t -> t\n let first = match tFirst with None -> (tFirst <- Some t; t) | Some t -> t\n printf \"ilwrite: TIME %10.3f (total) %10.3f (delta) - %s\\n\" (t - first) (t - prev) descr\n tPrev <- Some t\n\n let foldOn p f z x = f z (p x)\n\n let notFound() = raise (KeyNotFoundException())\n\n type Async with\n static member RunImmediate (computation: Async<'T>, ?cancellationToken ) =\n let cancellationToken = defaultArg cancellationToken Async.DefaultCancellationToken\n let ts = TaskCompletionSource<'T>()\n let task = ts.Task\n Async.StartWithContinuations(\n computation,\n (fun k -> ts.SetResult k),\n (fun exn -> ts.SetException exn),\n (fun _ -> ts.SetCanceled()),\n cancellationToken)\n task.Result\n\n\/\/\/ An efficient lazy for inline storage in a class type. Results in fewer thunks.\n[]\ntype InlineDelayInit<'T when 'T : not struct> = \n new (f: unit -> 'T) = {store = Unchecked.defaultof<'T>; func = Func<_>(f) } \n val mutable store : 'T\n val mutable func : Func<'T>\n\n member x.Value = \n match x.func with \n | null -> x.store \n | _ -> \n let res = LazyInitializer.EnsureInitialized(&x.store, x.func) \n x.func <- Unchecked.defaultof<_>\n res\n\n\/\/-------------------------------------------------------------------------\n\/\/ Library: projections\n\/\/------------------------------------------------------------------------\n\nmodule Order = \n let orderBy (p : 'T -> 'U) = \n { new IComparer<'T> with member _.Compare(x, xx) = compare (p x) (p xx) }\n\n let orderOn p (pxOrder: IComparer<'U>) = \n { new IComparer<'T> with member _.Compare(x, xx) = pxOrder.Compare (p x, p xx) }\n\n let toFunction (pxOrder: IComparer<'U>) x y = pxOrder.Compare(x, y)\n\n\/\/-------------------------------------------------------------------------\n\/\/ Library: arrays, lists, options, resizearrays\n\/\/-------------------------------------------------------------------------\n\nmodule Array = \n\n let mapq f inp =\n match inp with\n | [| |] -> inp\n | _ -> \n let res = Array.map f inp \n let len = inp.Length \n let mutable eq = true\n let mutable i = 0 \n while eq && i < len do \n if not (inp.[i] === res.[i]) then eq <- false\n i <- i + 1\n if eq then inp else res\n\n let lengthsEqAndForall2 p l1 l2 = \n Array.length l1 = Array.length l2 &&\n Array.forall2 p l1 l2\n\n let order (eltOrder: IComparer<'T>) = \n { new IComparer> with \n member _.Compare(xs, ys) = \n let c = compare xs.Length ys.Length \n if c <> 0 then c else\n let rec loop i = \n if i >= xs.Length then 0 else\n let c = eltOrder.Compare(xs.[i], ys.[i])\n if c <> 0 then c else\n loop (i+1)\n loop 0 }\n\n let existsOne p l = \n let rec forallFrom p l n =\n (n >= Array.length l) || (p l.[n] && forallFrom p l (n+1))\n\n let rec loop p l n =\n (n < Array.length l) && \n (if p l.[n] then forallFrom (fun x -> not (p x)) l (n+1) else loop p l (n+1))\n \n loop p l 0\n\n let existsTrue (arr: bool[]) = \n let rec loop n = (n < arr.Length) && (arr.[n] || loop (n+1))\n loop 0\n \n let findFirstIndexWhereTrue (arr: _[]) p = \n let rec look lo hi = \n assert ((lo >= 0) && (hi >= 0))\n assert ((lo <= arr.Length) && (hi <= arr.Length))\n if lo = hi then lo\n else\n let i = (lo+hi)\/2\n if p arr.[i] then \n if i = 0 then i \n else\n if p arr.[i-1] then \n look lo i\n else \n i\n else\n \/\/ not true here, look after\n look (i+1) hi\n look 0 arr.Length\n \n \/\/\/ pass an array byref to reverse it in place\n let revInPlace (array: 'T []) =\n if Array.isEmpty array then () else\n let arrLen, revLen = array.Length-1, array.Length\/2 - 1\n for idx in 0 .. revLen do\n let t1 = array.[idx] \n let t2 = array.[arrLen-idx]\n array.[idx] <- t2\n array.[arrLen-idx] <- t1\n\n \/\/\/ Async implementation of Array.map.\n let mapAsync (mapping : 'T -> Async<'U>) (array : 'T[]) : Async<'U[]> =\n let len = Array.length array\n let result = Array.zeroCreate len\n\n async { \/\/ Apply the mapping function to each array element.\n for i in 0 .. len - 1 do\n let! mappedValue = mapping array.[i]\n result.[i] <- mappedValue\n\n \/\/ Return the completed results.\n return result\n }\n \n \/\/\/ Returns a new array with an element replaced with a given value.\n let replace index value (array: _ []) =\n if index >= array.Length then raise (IndexOutOfRangeException \"index\")\n let res = Array.copy array\n res.[index] <- value\n res\n\n \/\/\/ Optimized arrays equality. ~100x faster than `array1 = array2` on strings.\n \/\/\/ ~2x faster for floats\n \/\/\/ ~0.8x slower for ints\n let inline areEqual (xs: 'T []) (ys: 'T []) =\n match xs, ys with\n | null, null -> true\n | [||], [||] -> true\n | null, _ | _, null -> false\n | _ when xs.Length <> ys.Length -> false\n | _ ->\n let mutable break' = false\n let mutable i = 0\n let mutable result = true\n while i < xs.Length && not break' do\n if xs.[i] <> ys.[i] then \n break' <- true\n result <- false\n i <- i + 1\n result\n\n \/\/\/ Returns all heads of a given array.\n \/\/\/ For [|1;2;3|] it returns [|[|1; 2; 3|]; [|1; 2|]; [|1|]|]\n let heads (array: 'T []) =\n let res = Array.zeroCreate<'T[]> array.Length\n for i = array.Length - 1 downto 0 do\n res.[i] <- array.[0..i]\n res\n\n \/\/\/ check if subArray is found in the wholeArray starting \n \/\/\/ at the provided index\n let inline isSubArray (subArray: 'T []) (wholeArray:'T []) index = \n if isNull subArray || isNull wholeArray then false\n elif subArray.Length = 0 then true\n elif subArray.Length > wholeArray.Length then false\n elif subArray.Length = wholeArray.Length then areEqual subArray wholeArray else\n let rec loop subidx idx =\n if subidx = subArray.Length then true \n elif subArray.[subidx] = wholeArray.[idx] then loop (subidx+1) (idx+1) \n else false\n loop 0 index\n \n \/\/\/ Returns true if one array has another as its subset from index 0.\n let startsWith (prefix: _ []) (whole: _ []) =\n isSubArray prefix whole 0\n \n \/\/\/ Returns true if one array has trailing elements equal to another's.\n let endsWith (suffix: _ []) (whole: _ []) =\n isSubArray suffix whole (whole.Length-suffix.Length)\n \nmodule Option = \n\n let mapFold f s opt = \n match opt with \n | None -> None, s \n | Some x -> \n let x2, s2 = f s x \n Some x2, s2\n\n let attempt (f: unit -> 'T) = try Some (f()) with _ -> None\n \nmodule List = \n\n let sortWithOrder (c: IComparer<'T>) elements = List.sortWith (Order.toFunction c) elements\n \n let splitAfter n l = \n let rec split_after_acc n l1 l2 = if n <= 0 then List.rev l1, l2 else split_after_acc (n-1) ((List.head l2) :: l1) (List.tail l2) \n split_after_acc n [] l\n\n let existsi f xs = \n let rec loop i xs = match xs with [] -> false | h :: t -> f i h || loop (i+1) t\n loop 0 xs\n \n let lengthsEqAndForall2 p l1 l2 = \n List.length l1 = List.length l2 &&\n List.forall2 p l1 l2\n\n let rec findi n f l = \n match l with \n | [] -> None\n | h :: t -> if f h then Some (h, n) else findi (n+1) f t\n\n let splitChoose select l =\n let rec ch acc1 acc2 l = \n match l with \n | [] -> List.rev acc1, List.rev acc2\n | x :: xs -> \n match select x with\n | Choice1Of2 sx -> ch (sx :: acc1) acc2 xs\n | Choice2Of2 sx -> ch acc1 (sx :: acc2) xs\n\n ch [] [] l\n\n let rec checkq l1 l2 = \n match l1, l2 with \n | h1 :: t1, h2 :: t2 -> h1 === h2 && checkq t1 t2\n | _ -> true\n\n let mapq (f: 'T -> 'T) inp =\n assert not typeof<'T>.IsValueType \n match inp with\n | [] -> inp\n | [h1a] -> \n let h2a = f h1a\n if h1a === h2a then inp else [h2a]\n | [h1a; h1b] -> \n let h2a = f h1a\n let h2b = f h1b\n if h1a === h2a && h1b === h2b then inp else [h2a; h2b]\n | [h1a; h1b; h1c] -> \n let h2a = f h1a\n let h2b = f h1b\n let h2c = f h1c\n if h1a === h2a && h1b === h2b && h1c === h2c then inp else [h2a; h2b; h2c]\n | _ -> \n let res = List.map f inp \n if checkq inp res then inp else res\n \n let frontAndBack l = \n let rec loop acc l = \n match l with\n | [] -> \n Debug.Assert(false, \"empty list\")\n invalidArg \"l\" \"empty list\" \n | [h] -> List.rev acc, h\n | h :: t -> loop (h :: acc) t\n loop [] l\n\n let tryRemove f inp = \n let rec loop acc l = \n match l with\n | [] -> None\n | h :: t -> if f h then Some (h, List.rev acc @ t) else loop (h :: acc) t\n loop [] inp\n\n let zip4 l1 l2 l3 l4 = \n List.zip l1 (List.zip3 l2 l3 l4) |> List.map (fun (x1, (x2, x3, x4)) -> (x1, x2, x3, x4))\n\n let unzip4 l = \n let a, b, cd = List.unzip3 (List.map (fun (x, y, z, w) -> (x, y, (z, w))) l)\n let c, d = List.unzip cd\n a, b, c, d\n\n let rec iter3 f l1 l2 l3 = \n match l1, l2, l3 with \n | h1 :: t1, h2 :: t2, h3 :: t3 -> f h1 h2 h3; iter3 f t1 t2 t3\n | [], [], [] -> ()\n | _ -> failwith \"iter3\"\n\n let takeUntil p l =\n let rec loop acc l =\n match l with\n | [] -> List.rev acc, []\n | x :: xs -> if p x then List.rev acc, l else loop (x :: acc) xs\n loop [] l\n\n let order (eltOrder: IComparer<'T>) =\n { new IComparer> with \n member _.Compare(xs, ys) = \n let rec loop xs ys = \n match xs, ys with\n | [], [] -> 0\n | [], _ -> -1\n | _, [] -> 1\n | x :: xs, y :: ys -> \n let cxy = eltOrder.Compare(x, y)\n if cxy=0 then loop xs ys else cxy \n loop xs ys }\n\n let indexNotFound() = raise (KeyNotFoundException(\"An index satisfying the predicate was not found in the collection\"))\n\n let rec assoc x l = \n match l with \n | [] -> indexNotFound()\n | (h, r) :: t -> if x = h then r else assoc x t\n\n let rec memAssoc x l = \n match l with \n | [] -> false\n | (h, _) :: t -> x = h || memAssoc x t\n\n let rec memq x l = \n match l with \n | [] -> false \n | h :: t -> LanguagePrimitives.PhysicalEquality x h || memq x t\n\n let mapNth n f xs =\n let rec mn i = function\n | [] -> []\n | x :: xs -> if i=n then f x :: xs else x :: mn (i+1) xs\n \n mn 0 xs\n let count pred xs = List.fold (fun n x -> if pred x then n+1 else n) 0 xs\n\n let headAndTail l = \n match l with \n | [] -> failwith \"headAndTail\"\n | h::t -> (h,t)\n\n \/\/ WARNING: not tail-recursive \n let mapHeadTail fhead ftail = function\n | [] -> []\n | [x] -> [fhead x]\n | x :: xs -> fhead x :: List.map ftail xs\n\n let collectFold f s l = \n let l, s = List.mapFold f s l\n List.concat l, s\n\n let collect2 f xs ys = List.concat (List.map2 f xs ys)\n\n let toArraySquared xss = xss |> List.map List.toArray |> List.toArray\n\n let iterSquared f xss = xss |> List.iter (List.iter f)\n\n let collectSquared f xss = xss |> List.collect (List.collect f)\n\n let mapSquared f xss = xss |> List.map (List.map f)\n\n let mapFoldSquared f z xss = List.mapFold (List.mapFold f) z xss\n\n let forallSquared f xss = xss |> List.forall (List.forall f)\n\n let mapiSquared f xss = xss |> List.mapi (fun i xs -> xs |> List.mapi (fun j x -> f i j x))\n\n let existsSquared f xss = xss |> List.exists (fun xs -> xs |> List.exists (fun x -> f x))\n\n let mapiFoldSquared f z xss = mapFoldSquared f z (xss |> mapiSquared (fun i j x -> (i, j, x)))\n\n let duplicates (xs: 'T list) =\n xs\n |> List.groupBy id\n |> List.filter (fun (_, elems) -> Seq.length elems > 1) \n |> List.map fst \n\n let internal allEqual (xs: 'T list) =\n match xs with \n | [] -> true\n | h::t -> t |> List.forall (fun h2 -> h = h2)\n\nmodule ResizeArray =\n\n \/\/\/ Split a ResizeArray into an array of smaller chunks.\n \/\/\/ This requires `items\/chunkSize` Array copies of length `chunkSize` if `items\/chunkSize % 0 = 0`,\n \/\/\/ otherwise `items\/chunkSize + 1` Array copies.\n let chunkBySize chunkSize f (items: ResizeArray<'t>) =\n \/\/ we could use Seq.chunkBySize here, but that would involve many enumerator.MoveNext() calls that we can sidestep with a bit of math\n let itemCount = items.Count\n if itemCount = 0\n then [||]\n else\n let chunksCount =\n match itemCount \/ chunkSize with\n | n when itemCount % chunkSize = 0 -> n\n | n -> n + 1 \/\/ any remainder means we need an additional chunk to store it\n\n [| for index in 0..chunksCount-1 do\n let startIndex = index * chunkSize\n let takeCount = min (itemCount - startIndex) chunkSize\n\n let holder = Array.zeroCreate takeCount\n \/\/ we take a bounds-check hit here on each access.\n \/\/ other alternatives here include\n \/\/ * iterating across an IEnumerator (incurs MoveNext penalty)\n \/\/ * doing a block copy using `List.CopyTo(index, array, index, count)` (requires more copies to do the mapping)\n \/\/ none are significantly better.\n for i in 0 .. takeCount - 1 do\n holder.[i] <- f items.[i]\n yield holder |]\n\n \/\/\/ Split a large ResizeArray into a series of array chunks that are each under the Large Object Heap limit.\n \/\/\/ This is done to help prevent a stop-the-world collection of the single large array, instead allowing for a greater\n \/\/\/ probability of smaller collections. Stop-the-world is still possible, just less likely.\n let mapToSmallArrayChunks f (inp: ResizeArray<'t>) =\n let itemSizeBytes = sizeof<'t>\n \/\/ rounding down here is good because it ensures we don't go over\n let maxArrayItemCount = LOH_SIZE_THRESHOLD_BYTES \/ itemSizeBytes\n\n \/\/ chunk the provided input into arrays that are smaller than the LOH limit\n \/\/ in order to prevent long-term storage of those values\n chunkBySize maxArrayItemCount f inp\n\nmodule ValueOptionInternal =\n\n let inline ofOption x = match x with Some x -> ValueSome x | None -> ValueNone\n\n let inline bind f x = match x with ValueSome x -> f x | ValueNone -> ValueNone\n\nmodule String =\n let make (n: int) (c: char) : string = String(c, n)\n\n let get (str: string) i = str.[i]\n\n let sub (s: string) (start: int) (len: int) = s.Substring(start, len)\n\n let contains (s: string) (c: char) = s.IndexOf c <> -1\n\n let order = LanguagePrimitives.FastGenericComparer\n \n let lowercase (s: string) =\n s.ToLowerInvariant()\n\n let uppercase (s: string) =\n s.ToUpperInvariant()\n\n \/\/ Scripts that distinguish between upper and lower case (bicameral) DU Discriminators and Active Pattern identifiers are required to start with an upper case character.\n \/\/ For valid identifiers where the case of the identifier can not be determined because there is no upper and lower case we will allow DU Discriminators and upper case characters \n \/\/ to be used. This means that developers using unicameral scripts such as hindi, are not required to prefix these identifiers with an Upper case latin character. \n \/\/\n let isLeadingIdentifierCharacterUpperCase (s:string) =\n let isUpperCaseCharacter c =\n \/\/ if IsUpper and IsLower return the same value, then we can't tell if it's upper or lower case, so ensure it is a letter\n \/\/ otherwise it is bicameral, so must be upper case\n let isUpper = Char.IsUpper c\n if isUpper = Char.IsLower c then Char.IsLetter c\n else isUpper\n\n s.Length >= 1 && isUpperCaseCharacter s.[0]\n\n let capitalize (s: string) =\n if s.Length = 0 then s \n else uppercase s.[0..0] + s.[ 1.. s.Length - 1 ]\n\n let uncapitalize (s: string) =\n if s.Length = 0 then s\n else lowercase s.[0..0] + s.[ 1.. s.Length - 1 ]\n\n let dropPrefix (s: string) (t: string) = s.[t.Length..s.Length - 1]\n\n let dropSuffix (s: string) (t: string) = s.[0..s.Length - t.Length - 1]\n\n let inline toCharArray (str: string) = str.ToCharArray()\n\n let lowerCaseFirstChar (str: string) =\n if String.IsNullOrEmpty str \n || Char.IsLower(str, 0) then str else \n let strArr = toCharArray str\n match Array.tryHead strArr with\n | None -> str\n | Some c -> \n strArr.[0] <- Char.ToLower c\n String strArr\n\n let extractTrailingIndex (str: string) =\n match str with\n | null -> null, None\n | _ ->\n let charr = str.ToCharArray() \n Array.revInPlace charr\n let digits = Array.takeWhile Char.IsDigit charr\n Array.revInPlace digits\n String digits\n |> function\n | \"\" -> str, None\n | index -> str.Substring (0, str.Length - index.Length), Some (int index)\n\n \/\/\/ Remove all trailing and leading whitespace from the string\n \/\/\/ return null if the string is null\n let trim (value: string) = if isNull value then null else value.Trim()\n \n \/\/\/ Splits a string into substrings based on the strings in the array separators\n let split options (separator: string []) (value: string) = \n if isNull value then null else value.Split(separator, options)\n\n let (|StartsWith|_|) pattern value =\n if String.IsNullOrWhiteSpace value then\n None\n elif value.StartsWithOrdinal pattern then\n Some()\n else None\n\n let (|Contains|_|) pattern value =\n if String.IsNullOrWhiteSpace value then\n None\n elif value.Contains pattern then\n Some()\n else None\n\n let getLines (str: string) =\n use reader = new StringReader(str)\n [|\n let mutable line = reader.ReadLine()\n while not (isNull line) do\n yield line\n line <- reader.ReadLine()\n if str.EndsWithOrdinal(\"\\n\") then\n \/\/ last trailing space not returned\n \/\/ http:\/\/stackoverflow.com\/questions\/19365404\/stringreader-omits-trailing-linebreak\n yield String.Empty\n |]\n\nmodule Dictionary = \n let inline newWithSize (size: int) = Dictionary<_, _>(size, HashIdentity.Structural)\n\n let inline ofList (xs: ('Key * 'Value) list) = \n let t = Dictionary<_, _>(List.length xs, HashIdentity.Structural)\n for k,v in xs do\n t.Add(k,v)\n t\n\n[]\ntype DictionaryExtensions() =\n\n []\n static member inline BagAdd(dic: Dictionary<'key, 'value list>, key: 'key, value: 'value) =\n match dic.TryGetValue key with\n | true, values -> dic.[key] <- value :: values\n | _ -> dic.[key] <- [value]\n\n []\n static member inline BagExistsValueForKey(dic: Dictionary<'key, 'value list>, key: 'key, f: 'value -> bool) =\n match dic.TryGetValue key with\n | true, values -> values |> List.exists f\n | _ -> false\n\nmodule Lazy = \n let force (x: Lazy<'T>) = x.Force()\n\n\/\/----------------------------------------------------------------------------\n\/\/ Single threaded execution and mutual exclusion\n\n\/\/\/ Represents a permission active at this point in execution\ntype ExecutionToken = interface end\n\n\/\/\/ Represents a token that indicates execution on the compilation thread, i.e. \n\/\/\/ - we have full access to the (partially mutable) TAST and TcImports data structures\n\/\/\/ - compiler execution may result in type provider invocations when resolving types and members\n\/\/\/ - we can access various caches in the SourceCodeServices\n\/\/\/\n\/\/\/ Like other execution tokens this should be passed via argument passing and not captured\/stored beyond\n\/\/\/ the lifetime of stack-based calls. This is not checked, it is a discipline within the compiler code. \n[]\ntype CompilationThreadToken() = interface ExecutionToken\n\n\/\/\/ A base type for various types of tokens that must be passed when a lock is taken.\n\/\/\/ Each different static lock should declare a new subtype of this type.\ntype LockToken = inherit ExecutionToken\n\n\/\/\/ Represents a token that indicates execution on any of several potential user threads calling the F# compiler services.\n[]\ntype AnyCallerThreadToken() = interface ExecutionToken\n\n[]\nmodule internal LockAutoOpens =\n \/\/\/ Represents a place where we are stating that execution on the compilation thread is required. The\n \/\/\/ reason why will be documented in a comment in the code at the callsite.\n let RequireCompilationThread (_ctok: CompilationThreadToken) = ()\n\n \/\/\/ Represents a place in the compiler codebase where we are passed a CompilationThreadToken unnecessarily.\n \/\/\/ This represents code that may potentially not need to be executed on the compilation thread.\n let DoesNotRequireCompilerThreadTokenAndCouldPossiblyBeMadeConcurrent (_ctok: CompilationThreadToken) = ()\n\n \/\/\/ Represents a place in the compiler codebase where we assume we are executing on a compilation thread\n let AssumeCompilationThreadWithoutEvidence () = Unchecked.defaultof\n\n let AnyCallerThread = Unchecked.defaultof\n\n let AssumeLockWithoutEvidence<'LockTokenType when 'LockTokenType :> LockToken> () = Unchecked.defaultof<'LockTokenType>\n\n\/\/\/ Encapsulates a lock associated with a particular token-type representing the acquisition of that lock.\ntype Lock<'LockTokenType when 'LockTokenType :> LockToken>() = \n let lockObj = obj()\n member _.AcquireLock f = lock lockObj (fun () -> f (AssumeLockWithoutEvidence<'LockTokenType>()))\n\n\/\/---------------------------------------------------\n\/\/ Misc\n\nmodule Map = \n let tryFindMulti k map = match Map.tryFind k map with Some res -> res | None -> []\n\n[]\ntype ResultOrException<'TResult> =\n | Result of result: 'TResult\n | Exception of ``exception``: Exception\n \nmodule ResultOrException = \n\n let success a = Result a\n\n let raze (b: exn) = Exception b\n\n \/\/ map\n let (|?>) res f = \n match res with \n | Result x -> Result(f x )\n | Exception err -> Exception err\n \n let ForceRaise res = \n match res with \n | Result x -> x\n | Exception err -> raise err\n\n let otherwise f x =\n match x with \n | Result x -> success x\n | Exception _err -> f()\n\n[] \ntype ValueOrCancelled<'TResult> =\n | Value of result: 'TResult\n | Cancelled of ``exception``: OperationCanceledException\n\n\/\/\/ Represents a cancellable computation with explicit representation of a cancelled result.\n\/\/\/\n\/\/\/ A cancellable computation is passed may be cancelled via a CancellationToken, which is propagated implicitly. \n\/\/\/ If cancellation occurs, it is propagated as data rather than by raising an OperationCanceledException. \n[]\ntype Cancellable<'TResult> = Cancellable of (CancellationToken -> ValueOrCancelled<'TResult>)\n\nmodule Cancellable = \n\n \/\/\/ Run a cancellable computation using the given cancellation token\n let run (ct: CancellationToken) (Cancellable oper) = \n if ct.IsCancellationRequested then \n ValueOrCancelled.Cancelled (OperationCanceledException ct) \n else\n oper ct \n\n \/\/\/ Bind the result of a cancellable computation\n let inline bind f comp1 = \n Cancellable (fun ct -> \n match run ct comp1 with \n | ValueOrCancelled.Value v1 -> run ct (f v1) \n | ValueOrCancelled.Cancelled err1 -> ValueOrCancelled.Cancelled err1)\n\n \/\/\/ Map the result of a cancellable computation\n let inline map f oper = \n Cancellable (fun ct -> \n match run ct oper with \n | ValueOrCancelled.Value res -> ValueOrCancelled.Value (f res)\n | ValueOrCancelled.Cancelled err -> ValueOrCancelled.Cancelled err)\n \n \/\/\/ Return a simple value as the result of a cancellable computation\n let inline ret x = Cancellable (fun _ -> ValueOrCancelled.Value x)\n\n \/\/\/ Fold a cancellable computation along a sequence of inputs\n let fold f acc seq = \n Cancellable (fun ct -> \n (ValueOrCancelled.Value acc, seq) \n ||> Seq.fold (fun acc x -> \n match acc with \n | ValueOrCancelled.Value accv -> run ct (f accv x)\n | res -> res))\n \n \/\/\/ Iterate a cancellable computation over a collection\n let inline each f seq =\n fold (fun acc x -> f x |> map (fun y -> (y :: acc))) [] seq |> map List.rev\n \n \/\/\/ Delay a cancellable computation\n let inline delay (f: unit -> Cancellable<'T>) = Cancellable (fun ct -> let (Cancellable g) = f() in g ct)\n\n \/\/\/ Run the computation in a mode where it may not be cancelled. The computation never results in a \n \/\/\/ ValueOrCancelled.Cancelled.\n let runWithoutCancellation comp = \n let res = run CancellationToken.None comp \n match res with \n | ValueOrCancelled.Cancelled _ -> failwith \"unexpected cancellation\" \n | ValueOrCancelled.Value r -> r\n\n let toAsync c =\n async {\n let! ct = Async.CancellationToken\n let res = run ct c\n return! Async.FromContinuations (fun (cont, _econt, ccont) -> \n match res with \n | ValueOrCancelled.Value v -> cont v\n | ValueOrCancelled.Cancelled ce -> ccont ce)\n }\n\n \/\/\/ Bind the cancellation token associated with the computation\n let token () = Cancellable (fun ct -> ValueOrCancelled.Value ct)\n\n \/\/\/ Represents a canceled computation\n let canceled() = Cancellable (fun ct -> ValueOrCancelled.Cancelled (OperationCanceledException ct))\n\n \/\/\/ Catch exceptions in a computation\n let inline catch e = \n let (Cancellable f) = e\n Cancellable (fun ct -> \n try \n match f ct with \n | ValueOrCancelled.Value r -> ValueOrCancelled.Value (Choice1Of2 r) \n | ValueOrCancelled.Cancelled e -> ValueOrCancelled.Cancelled e \n with err -> \n ValueOrCancelled.Value (Choice2Of2 err))\n\n \/\/\/ Implement try\/finally for a cancellable computation\n let inline tryFinally e compensation =\n catch e |> bind (fun res ->\n compensation()\n match res with Choice1Of2 r -> ret r | Choice2Of2 err -> raise err)\n\n \/\/\/ Implement try\/with for a cancellable computation\n let inline tryWith e handler = \n catch e |> bind (fun res ->\n match res with Choice1Of2 r -> ret r | Choice2Of2 err -> handler err)\n \ntype CancellableBuilder() = \n\n member inline _.BindReturn(e, k) = Cancellable.map k e\n\n member inline _.Bind(e, k) = Cancellable.bind k e\n\n member inline _.Return v = Cancellable.ret v\n\n member inline _.ReturnFrom (v: Cancellable<'T>) = v\n\n member inline _.Combine(e1, e2) = e1 |> Cancellable.bind (fun () -> e2)\n\n member inline _.For(es, f) = es |> Cancellable.each f \n\n member inline _.TryWith(e, handler) = Cancellable.tryWith e handler\n\n member inline _.Using(resource, e) = Cancellable.tryFinally (e resource) (fun () -> (resource :> IDisposable).Dispose())\n\n member inline _.TryFinally(e, compensation) = Cancellable.tryFinally e compensation\n\n member inline _.Delay f = Cancellable.delay f\n\n member inline _.Zero() = Cancellable.ret ()\n\n[]\nmodule CancellableAutoOpens =\n let cancellable = CancellableBuilder()\n\n\/\/\/ Generates unique stamps\ntype UniqueStampGenerator<'T when 'T : equality>() = \n let gate = obj ()\n let encodeTab = ConcurrentDictionary<'T, int>(HashIdentity.Structural)\n let mutable nItems = 0\n let encode str =\n match encodeTab.TryGetValue str with\n | true, idx -> idx\n | _ ->\n lock gate (fun () ->\n let idx = nItems\n encodeTab.[str] <- idx\n nItems <- nItems + 1\n idx)\n\n member this.Encode str = encode str\n\n member this.Table = encodeTab.Keys\n\n\/\/\/ memoize tables (all entries cached, never collected)\ntype MemoizationTable<'T, 'U>(compute: 'T -> 'U, keyComparer: IEqualityComparer<'T>, ?canMemoize) = \n \n let table = new ConcurrentDictionary<'T, 'U>(keyComparer) \n\n member t.Apply x = \n if (match canMemoize with None -> true | Some f -> f x) then \n match table.TryGetValue x with\n | true, res -> res\n | _ ->\n lock table (fun () -> \n match table.TryGetValue x with\n | true, res -> res\n | _ ->\n let res = compute x\n table.[x] <- res\n res)\n else compute x\n\n\nexception UndefinedException\n\ntype LazyWithContextFailure(exn: exn) =\n\n static let undefined = LazyWithContextFailure(UndefinedException)\n\n member _.Exception = exn\n\n static member Undefined = undefined\n \n\/\/\/ Just like \"Lazy\" but EVERY forcer must provide an instance of \"ctxt\", e.g. to help track errors\n\/\/\/ on forcing back to at least one sensible user location\n[]\n[]\ntype LazyWithContext<'T, 'ctxt> = \n { \/\/\/ This field holds the result of a successful computation. It's initial value is Unchecked.defaultof\n mutable value : 'T\n\n \/\/\/ This field holds either the function to run or a LazyWithContextFailure object recording the exception raised \n \/\/\/ from running the function. It is null if the thunk has been evaluated successfully.\n mutable funcOrException: obj\n\n \/\/\/ A helper to ensure we rethrow the \"original\" exception\n findOriginalException : exn -> exn }\n\n static member Create(f: 'ctxt->'T, findOriginalException) : LazyWithContext<'T, 'ctxt> = \n { value = Unchecked.defaultof<'T>\n funcOrException = box f\n findOriginalException = findOriginalException }\n\n static member NotLazy(x:'T) : LazyWithContext<'T, 'ctxt> = \n { value = x\n funcOrException = null\n findOriginalException = id }\n\n member x.IsDelayed = (match x.funcOrException with null -> false | :? LazyWithContextFailure -> false | _ -> true)\n\n member x.IsForced = (match x.funcOrException with null -> true | _ -> false)\n\n member x.Force(ctxt:'ctxt) = \n match x.funcOrException with \n | null -> x.value \n | _ -> \n \/\/ Enter the lock in case another thread is in the process of evaluating the result\n Monitor.Enter x;\n try \n x.UnsynchronizedForce ctxt\n finally\n Monitor.Exit x\n\n member x.UnsynchronizedForce ctxt = \n match x.funcOrException with \n | null -> x.value \n | :? LazyWithContextFailure as res -> \n \/\/ Re-raise the original exception \n raise (x.findOriginalException res.Exception)\n | :? ('ctxt -> 'T) as f -> \n x.funcOrException <- box(LazyWithContextFailure.Undefined)\n try \n let res = f ctxt \n x.value <- res\n x.funcOrException <- null\n res\n with e -> \n x.funcOrException <- box(LazyWithContextFailure(e))\n reraise()\n | _ -> \n failwith \"unreachable\"\n\n\/\/\/ Intern tables to save space.\nmodule Tables = \n let memoize f = \n let t = ConcurrentDictionary<_, _>(Environment.ProcessorCount, 1000, HashIdentity.Structural)\n fun x -> \n match t.TryGetValue x with\n | true, res -> res\n | _ ->\n let res = f x\n t.[x] <- res\n res\n\n\/\/\/ Interface that defines methods for comparing objects using partial equality relation\ntype IPartialEqualityComparer<'T> = \n inherit IEqualityComparer<'T>\n \/\/\/ Can the specified object be tested for equality?\n abstract InEqualityRelation : 'T -> bool\n\nmodule IPartialEqualityComparer = \n\n let On f (c: IPartialEqualityComparer<_>) = \n { new IPartialEqualityComparer<_> with \n member _.InEqualityRelation x = c.InEqualityRelation (f x)\n member _.Equals(x, y) = c.Equals(f x, f y)\n member _.GetHashCode x = c.GetHashCode(f x) }\n \n \/\/ Wrapper type for use by the 'partialDistinctBy' function\n []\n type private WrapType<'T> = Wrap of 'T\n \n \/\/ Like Seq.distinctBy but only filters out duplicates for some of the elements\n let partialDistinctBy (per: IPartialEqualityComparer<'T>) seq =\n let wper = \n { new IPartialEqualityComparer> with\n member _.InEqualityRelation (Wrap x) = per.InEqualityRelation x\n member _.Equals(Wrap x, Wrap y) = per.Equals(x, y)\n member _.GetHashCode (Wrap x) = per.GetHashCode x }\n \/\/ Wrap a Wrap _ around all keys in case the key type is itself a type using null as a representation\n let dict = Dictionary, obj>(wper)\n seq |> List.filter (fun v -> \n let key = Wrap v\n if (per.InEqualityRelation v) then \n if dict.ContainsKey key then false else (dict.[key] <- null; true)\n else true)\n\n\/\/-------------------------------------------------------------------------\n\/\/ Library: Name maps\n\/\/------------------------------------------------------------------------\n\ntype NameMap<'T> = Map\n\ntype NameMultiMap<'T> = NameMap<'T list>\n\ntype MultiMap<'T, 'U when 'T : comparison> = Map<'T, 'U list>\n\nmodule NameMap = \n\n let empty = Map.empty\n\n let range m = List.rev (Map.foldBack (fun _ x sofar -> x :: sofar) m [])\n\n let foldBack f (m: NameMap<'T>) z = Map.foldBack f m z\n\n let forall f m = Map.foldBack (fun x y sofar -> sofar && f x y) m true\n\n let exists f m = Map.foldBack (fun x y sofar -> sofar || f x y) m false\n\n let ofKeyedList f l = List.foldBack (fun x acc -> Map.add (f x) x acc) l Map.empty\n\n let ofList l : NameMap<'T> = Map.ofList l\n\n let ofSeq l : NameMap<'T> = Map.ofSeq l\n\n let toList (l: NameMap<'T>) = Map.toList l\n\n let layer (m1 : NameMap<'T>) m2 = Map.foldBack Map.add m1 m2\n\n \/\/\/ Not a very useful function - only called in one place - should be changed \n let layerAdditive addf m1 m2 = \n Map.foldBack (fun x y sofar -> Map.add x (addf (Map.tryFindMulti x sofar) y) sofar) m1 m2\n\n \/\/\/ Union entries by identical key, using the provided function to union sets of values\n let union unionf (ms: NameMap<_> seq) = \n seq { for m in ms do yield! m } \n |> Seq.groupBy (fun (KeyValue(k, _v)) -> k) \n |> Seq.map (fun (k, es) -> (k, unionf (Seq.map (fun (KeyValue(_k, v)) -> v) es))) \n |> Map.ofSeq\n\n \/\/\/ For every entry in m2 find an entry in m1 and fold \n let subfold2 errf f m1 m2 acc =\n Map.foldBack (fun n x2 acc -> try f n (Map.find n m1) x2 acc with :? KeyNotFoundException -> errf n x2) m2 acc\n\n let suball2 errf p m1 m2 = subfold2 errf (fun _ x1 x2 acc -> p x1 x2 && acc) m1 m2 true\n\n let mapFold f s (l: NameMap<'T>) = \n Map.foldBack (fun x y (l2, sx) -> let y2, sy = f sx x y in Map.add x y2 l2, sy) l (Map.empty, s)\n\n let foldBackRange f (l: NameMap<'T>) acc = Map.foldBack (fun _ y acc -> f y acc) l acc\n\n let filterRange f (l: NameMap<'T>) = Map.foldBack (fun x y acc -> if f y then Map.add x y acc else acc) l Map.empty\n\n let mapFilter f (l: NameMap<'T>) = Map.foldBack (fun x y acc -> match f y with None -> acc | Some y' -> Map.add x y' acc) l Map.empty\n\n let map f (l : NameMap<'T>) = Map.map (fun _ x -> f x) l\n\n let iter f (l : NameMap<'T>) = Map.iter (fun _k v -> f v) l\n\n let partition f (l : NameMap<'T>) = Map.filter (fun _ x-> f x) l, Map.filter (fun _ x -> not (f x)) l\n\n let mem v (m: NameMap<'T>) = Map.containsKey v m\n\n let find v (m: NameMap<'T>) = Map.find v m\n\n let tryFind v (m: NameMap<'T>) = Map.tryFind v m \n\n let add v x (m: NameMap<'T>) = Map.add v x m\n\n let isEmpty (m: NameMap<'T>) = (Map.isEmpty m)\n\n let existsInRange p m = Map.foldBack (fun _ y acc -> acc || p y) m false \n\n let tryFindInRange p m = \n Map.foldBack (fun _ y acc -> \n match acc with \n | None -> if p y then Some y else None \n | _ -> acc) m None \n\nmodule NameMultiMap = \n\n let existsInRange f (m: NameMultiMap<'T>) = NameMap.exists (fun _ l -> List.exists f l) m\n\n let find v (m: NameMultiMap<'T>) = match m.TryGetValue v with true, r -> r | _ -> []\n\n let add v x (m: NameMultiMap<'T>) = NameMap.add v (x :: find v m) m\n\n let range (m: NameMultiMap<'T>) = Map.foldBack (fun _ x sofar -> x @ sofar) m []\n\n let rangeReversingEachBucket (m: NameMultiMap<'T>) = Map.foldBack (fun _ x sofar -> List.rev x @ sofar) m []\n \n let chooseRange f (m: NameMultiMap<'T>) = Map.foldBack (fun _ x sofar -> List.choose f x @ sofar) m []\n\n let map f (m: NameMultiMap<'T>) = NameMap.map (List.map f) m \n\n let empty : NameMultiMap<'T> = Map.empty\n\n let initBy f xs : NameMultiMap<'T> = xs |> Seq.groupBy f |> Seq.map (fun (k, v) -> (k, List.ofSeq v)) |> Map.ofSeq \n\n let ofList (xs: (string * 'T) list) : NameMultiMap<'T> = xs |> Seq.groupBy fst |> Seq.map (fun (k, v) -> (k, List.ofSeq (Seq.map snd v))) |> Map.ofSeq \n\nmodule MultiMap = \n\n let existsInRange f (m: MultiMap<_, _>) = Map.exists (fun _ l -> List.exists f l) m\n\n let find v (m: MultiMap<_, _>) = match m.TryGetValue v with true, r -> r | _ -> []\n\n let add v x (m: MultiMap<_, _>) = Map.add v (x :: find v m) m\n\n let range (m: MultiMap<_, _>) = Map.foldBack (fun _ x sofar -> x @ sofar) m []\n\n let empty : MultiMap<_, _> = Map.empty\n\n let initBy f xs : MultiMap<_, _> = xs |> Seq.groupBy f |> Seq.map (fun (k, v) -> (k, List.ofSeq v)) |> Map.ofSeq \n\ntype LayeredMap<'Key, 'Value when 'Key : comparison> = Map<'Key, 'Value>\n\n[]\nmodule MapAutoOpens =\n type Map<'Key, 'Value when 'Key : comparison> with\n \n static member Empty : Map<'Key, 'Value> = Map.empty\n \n#if USE_SHIPPED_FSCORE \n member x.Values = [ for KeyValue(_, v) in x -> v ]\n#endif\n\n member x.AddMany (kvs: _[]) = (x, kvs) ||> Array.fold (fun x (KeyValue(k, v)) -> x.Add(k, v))\n\n member x.AddOrModify (key, f: 'Value option -> 'Value) = x.Add (key, f (x.TryFind key))\n\n\/\/\/ Immutable map collection, with explicit flattening to a backing dictionary \n[]\ntype LayeredMultiMap<'Key, 'Value when 'Key : equality and 'Key : comparison>(contents : LayeredMap<'Key, 'Value list>) = \n\n member x.Add (k, v) = LayeredMultiMap(contents.Add(k, v :: x.[k]))\n\n member _.Item with get k = match contents.TryGetValue k with true, l -> l | _ -> []\n\n member x.AddMany (kvs: _[]) = \n (x, kvs) ||> Array.fold (fun x (KeyValue(k, v)) -> x.Add(k, v))\n\n member _.TryFind k = contents.TryFind k\n\n member _.TryGetValue k = contents.TryGetValue k\n\n member _.Values = contents.Values |> List.concat\n\n static member Empty : LayeredMultiMap<'Key, 'Value> = LayeredMultiMap LayeredMap.Empty\n","avg_line_length":37.8196721311,"max_line_length":233,"alphanum_fraction":0.5779207446}
+{"size":2267,"ext":"fs","lang":"F#","max_stars_count":null,"content":"\n#if defined paraboloid_point_shape\n#extension GL_EXT_frag_depth : enable\n#endif\n\nprecision highp float;\nprecision highp int;\n\nuniform mat4 viewMatrix;\nuniform mat4 uViewInv;\nuniform mat4 uProjInv;\nuniform vec3 cameraPosition;\n\nuniform mat4 projectionMatrix;\nuniform float uOpacity;\n\nuniform float blendHardness;\nuniform float blendDepthSupplement;\nuniform float fov;\nuniform float uSpacing;\nuniform float near;\nuniform float far;\nuniform float uPCIndex;\nuniform float uScreenWidth;\nuniform float uScreenHeight;\n\nvarying vec3 vColor;\nvarying float vLogDepth;\nvarying vec3 vViewPosition;\nvarying float vRadius;\nvarying float vPointSize;\nvarying vec3 vPosition;\n\n\/\/ CLOI\n#if defined(use_cloi)\n\tuniform float cloiValue;\n\tvarying float vImp;\n#endif\n\nfloat specularStrength = 1.0;\n\nvoid main()\n{\n\n\t\/\/ gl_FragColor = vec4(vColor, 1.0);\n\n\tvec3 color = vColor;\n\tvec4 finalColor = vec4(color, 1.0);\n\n\tfloat depth = gl_FragCoord.z;\n\n\t#if defined(circle_point_shape) || defined(paraboloid_point_shape)\n\t\tfloat u = 2.0 * gl_PointCoord.x - 1.0;\n\t\tfloat v = 2.0 * gl_PointCoord.y - 1.0;\n\t#endif\n\n\t#if defined(circle_point_shape)\n\t\tfloat cc = u * u + v * v;\n\t\tif (cc > 1.0)\n\t\t{\n\t\t\tdiscard;\n\t\t}\n\t#endif\n\n\t#if defined color_type_indices\n\t\tfinalColor = vec4(color, uPCIndex \/ 255.0);\n\t#else\n\t\tfinalColor = vec4(color, uOpacity);\n\t#endif\n\n\t#if defined paraboloid_point_shape\n\t\tfloat wi = 0.0 - (u * u + v * v);\n\t\tvec4 pos = vec4(vViewPosition, 1.0);\n\t\tpos.z += wi * vRadius;\n\t\tfloat linearDepth = -pos.z;\n\t\tpos = projectionMatrix * pos;\n\t\tpos = pos \/ pos.w;\n\t\tfloat expDepth = pos.z;\n\t\tdepth = (pos.z + 1.0) \/ 2.0;\n\t\tgl_FragDepthEXT = depth;\n\n\t#if defined(color_type_depth)\n\t\tcolor.r = linearDepth;\n\t\tcolor.g = expDepth;\n\t#endif\n\n\t#if defined(use_edl)\n\t\tfinalColor.a = log2(linearDepth);\n\t#endif\n\n\t#else\n\t#if defined(use_edl)\n\t\tfinalColor.a = vLogDepth;\n\t#endif\n\t#endif\n\n\t#if defined(weighted_splats)\n\t\tfloat distance = 2.0 * length(gl_PointCoord.xy - 0.5);\n\t\tfloat weight = max(0.0, 1.0 - distance);\n\t\tweight = pow(weight, 1.5);\n\n\t\tfinalColor.a = weight;\n\t\tfinalColor.xyz = finalColor.xyz * weight;\n\t#endif\n\n\t\/\/ CLOI\n\t#if defined(use_cloi)\n\t\tfinalColor.a = vImp;\n\t#endif\n\n\t\/\/ finalColor.a = cloiValue \/ 8.0;\n\n\tgl_FragColor = finalColor;\n\n\t\/\/ gl_FragColor = vec4(0.0, 0.7, 0.0, 1.0);\n}\n","avg_line_length":19.3760683761,"max_line_length":67,"alphanum_fraction":0.7062196736}
+{"size":33740,"ext":"fs","lang":"F#","max_stars_count":null,"content":"\/\/ Copyright (c) Microsoft Corporation.\n\/\/ Licensed under the MIT License.\n\n[]\nmodule Microsoft.Research.CRNEngine.JSAPI\nopen Microsoft.Research.CRNEngine.InferenceSiteGraph\nopen Microsoft.Research.CRNEngine.Graph\nopen Microsoft.Research.CRNEngine\nopen Microsoft.Research.Filzbach\n\ntype export_def =\n {\n \/\/\/MIME type. The GUI may use this to decide how to present this export. Supported: image\/svg+xml, text\/plain, text\/html, application\/x-tex.\n content_type : string\n \/\/\/An identifier for this export. This can be used to request a specific export. The GUI may rely on this to identify a specific export for special purposes.\n id : string\n \/\/\/A string that can be user as a header for this export.\n display_name : string\n \/\/\/A node identifier, in case this export refers to a specific node. If None, the export refers to the whole graph.\n node_id : string option\n \/\/\/An instance identifier, in case the model is producing multiple exports for this export ID. If None, the export refers to the whole model.\n instance : string option\n \/\/\/The export content. If None, the export is available for lazy generation.\n content : string[] option\n \/\/\/The export content, when saved to disk. If None, is assumed to be the same as the content. If blank, saving is not allowed.\n save_content : string option\n }\n\ntype SynthesisDispersionResult = \n {\n markersX: float[];\n markersY: float[];\n plotX: float[];\n plotY: float[];\n xMin: float;\n xMax: float;\n yMin: float;\n yMax: float;\n }\n\ntype SynthesisValue =\n {\n value: float;\n lowerBound: float option;\n upperBound: float option;\n }\n\ntype SynthesisEquations =\n {\n rateEquations: string;\n jacobian: string;\n diffusion: string;\n csts: string;\n }\n\ntype SynthesisResult =\n {\n message: string;\n values: Map;\n equations: SynthesisEquations;\n dispersion: SynthesisDispersionResult option;\n jacobian: Graph option;\n crn: Gui option;\n code: string option;\n }\n\ntype BistabilityPlot =\n {\n speciesX: string;\n speciesY: string;\n state1x: float;\n state1y: float;\n state2x: float;\n state2y: float;\n initialsX: float list;\n initialsY: float list;\n state1simsX: float list list;\n state1simsY: float list list;\n state2simsX: float list list;\n state2simsY: float list list;\n }\n\ntype ValueType = \n | [] Float\n | [] MeanStdev\n | [] MeanStdevProbabilities\n | [] Spatial1D\n | [] Spatial2D\n | [] MeanStdevTable\n\nlet valueTypeCaseString = \n function \n | Float -> \"Float\"\n | MeanStdev -> \"MeanStdev\"\n | MeanStdevProbabilities -> \"MeanStdevProbabilities\"\n | Spatial1D -> \"Spatial1D\"\n | Spatial2D -> \"Spatial2D\"\n | MeanStdevTable -> \"MeanStdevTable\"\n\ntype sim_run = \n { value_type : ValueType\n instances : Instance list }\n\nlet parse_code (s : string) : IGraph =\n let inferencegraph = match Parser.from_string_first_error_with_msg InferenceSiteGraph.parse s with \n | Choice1Of2 m -> m\n | Choice2Of2 err -> raise (Parser.Exception(err.text, [|err|]))\n \/\/ Expand and lift. Is this necessary?\n \/\/let inferencegraph = InferenceSiteGraph.expandAndLift inferencegraph\n let initialise_model (model:Model) : Model = { top = model.top.initialise(); systems = List.map (fun (crn:Crn) -> crn.initialise()) model.systems }\n let initialised = { inferencegraph with nodes = inferencegraph.nodes |> Map.map (fun _ model -> initialise_model model) }\n initialised\n\nlet prepare_Model (gui:GuiIG) (model_id:string) : Model =\n let ig = gui.to_ig()\n let ig = InferenceSiteGraph.expandAndLift ig\n let model = Map.find model_id ig.nodes\n let model = model.merge_shared_settings()\n model\n\nlet prepare_CRN_for_sim (gui : GuiIG) (model_id:string) (instance : Instance) =\n \/\/ Convert from the gui form.\n let model = prepare_Model gui model_id\n \/\/ Find the CRN for this instance.\n let crn = match instance.model with\n | \"\" -> model.top\n | m -> match List.tryFind (fun (s:Crn) -> s.name = m) model.systems with\n | Some crn -> crn\n | None -> model.top\n let settings = instance.settings.map (Functional2.from_string_plot >> Expression.map (Crn.species_to_rates crn.settings.rates))\n \/\/ Insert the settings and environment in the crn.\n let crn = {crn with settings = crn.settings.update_simulation settings}\n let crn = crn.substitute instance.environment\n crn\n\n\/\/ I can't ship a Populations directly. I need to render it to SVG first. But I can't render a Populations directly, either (the renderer runs on Initials[]). So I need to convert it to Initials, then render it to SVG, and then ship it.\nlet pop_to_svg (crn:Crn) (x:Populations) =\n let pop_to_init (p:Population) = Initial.create(Expression.Float p.value, p.species, None)\n let initials = x.index_to_species |> Array.map pop_to_init |> List.ofArray\n let crnx = { crn with initials = initials }\n let svg = (try Svg.to_string Crn.default_svg_style <| Crn.initials_to_svg crnx with e -> e.Message)\n svg\n\nlet get_instances (gui:GuiIG) (model_id:string) : Instance list =\n let model = prepare_Model gui model_id\n let crninstances (crn:Crn) = \n let instances = crn.get_instances()\n let map_instance instance = Instance.create(instance.model, instance.sweep, instance.assignment, instance.environment, instance.settings.map Functional2.to_string_plot, instance.name)\n let instances = List.map map_instance instances\n instances\n let instances =\n match model.systems with\n [] -> crninstances model.top\n | _ -> model.systems |> List.collect crninstances\n instances\n\nlet make_instance_name (instance:Instance) =\n if instance.name <> \"\" then instance.name else\n let name = instance.model\n let name = if instance.sweep = \"\" then name else name + \".\" + instance.sweep\n name\n\nlet simulateFloat (ig : GuiIG) (node_id:string) (instance : Instance) (output : Row -> unit) (output_export : export_def->unit) (cancel:bool ref) = \n let crn = prepare_CRN_for_sim ig node_id instance\n let instance_name = make_instance_name instance\n let output_finals (x:Populations) =\n let svg = pop_to_svg crn x\n let svg = [|svg|]\n let exportDef = { content_type = \"image\/svg+xml\"; id = \"finals\"; display_name = \"Finals\"; node_id = Some node_id; instance = (match instance_name with \"\" -> None | name -> Some name); content = Some svg; save_content = None }\n output_export exportDef\n match crn.settings.simulator with\n | Simulator.Oslo -> crn.to_oslo().simulate_callback cancel output output_finals |> ignore\n | Simulator.SSA -> crn.to_ssa().simulate_callback cancel output output_finals (Some (fun _ _ _ -> ())) |> ignore \/\/ Note: if I use None here, W# compilation produces invalid code. Unable to create a simple repro.\n \/\/ N.B. The Sundials solver produces chunks of output points, not individual time-points.\n | Simulator.Sundials -> crn.to_sundials().simulate_callback cancel (List.iter output) |> ignore\n | _ -> failwithf \"The %s simulator cannot be used here\" crn.settings.simulator.to_string \n\ntype jit<'s> when 's : equality and 's:comparison =\n { jit: Jit.t<'s>\n calculus: Calculus<'s> }\n\nlet simulateMeanStdev (ig : GuiIG) (model_id:string) (instance : Instance) (output : Row -> unit) (output_export:export_def->unit) (cancel:bool ref) = \n let crn = prepare_CRN_for_sim ig model_id instance\n match crn.settings.simulator with\n | Simulator.LNA -> crn.to_lna().simulate_callback cancel output |> ignore\n | Simulator.CME -> crn.simulate_cme_callback cancel ignore output |> ignore \/\/ Note: Calling simulate_cme_callback will always regenerate the state-space. It would be better to only regenerate if the state-space has changed.\n | Simulator.MC -> failwith \"MC simulator cannot be invoked this way\"\n | _ -> failwith \"simulator does not return mean+stdev\"\n\nlet simulateSpatial1D (ig : GuiIG) (model_id:string) (instance : Instance) (output : Row -> unit) (output_export:export_def->unit) (cancel:bool ref) = \n let crn = prepare_CRN_for_sim ig model_id instance\n match crn.settings.simulator with\n | Simulator.PDE -> \n match crn.settings.spatial.dimensions with\n | 1 -> crn.to_pde1d() |> Pde.simulate_1d_callback cancel output\n | _ -> failwith \"wrong number of dimensions\"\n | _ -> failwith \"simulator does not return 1d spatial\"\n\nlet simulateSpatial2D (ig : GuiIG) (model_id:string) (instance : Instance) (output : Row -> unit) (output_export:export_def->unit) (cancel:bool ref) = \n let crn = prepare_CRN_for_sim ig model_id instance\n match crn.settings.simulator with\n | Simulator.PDE -> \n match crn.settings.spatial.dimensions with\n | 2 -> crn.to_pde2d() |> Pde.simulate_2d_callback cancel output\n | _ -> failwith \"wrong number of dimensions\"\n | _ -> failwith \"simulator does not return 2d spatial\"\n\nlet simulateMeanStdevTable (ig : GuiIG) (model_id:string) (instance : Instance) (output : Table -> unit) (output_export:export_def->unit) (cancel:bool ref) =\n let crn = prepare_CRN_for_sim ig model_id instance\n if crn.settings.stochastic.trajectories > 1 then\n crn.to_ssa().simulate_trajectories_callback cancel output\n else\n failwith \"simulator does not return mean+stdev table\"\n\ntype probabilityMap = \n { times : float list\n values : int list\n probabilities : float [] list }\n\n\ntype transition = \n { target : int \/\/ this is the index in the state_space structure.\n propensity : string }\n\ntype state = \n { species : int Stringmap.t \/\/ this goes from species name to population count\n transitions : transition [] }\n\ntype state_space = \n { states : state []\n start_index : int\n attributes : Attributes [] }\n\nlet convert_state_space (ctmc_result : ctmc_result<'t>) (namer:'t->Attributes) : state_space = \n \/\/ I'll maintain a map from each state to its index in the array, so I can find them quickly while doing transitions.\n let idmap = Dictionary.empty()\n \n \/\/ I've rewritten this function into iterative form as the recursive one was overflowing stacks when transpiled into JavaScript\n let originalStates = \n ctmc_result.ctmc.graph\n |> Dictionary.toSeq\n |> Array.ofSeq\n\n let attributes = new System.Collections.Generic.List()\n let namer sp =\n let attrib = namer sp\n attributes.Add attrib\n attrib.name\n \n \/\/First we form the states without transitions so they get their IDs\n let statesToTransmitWithoutTransitions = \n originalStates |> Array.mapi (fun i (k, v) -> \n let state = k\n Dictionary.add idmap state i \/\/keep for fast lookups\n let species = \n Seq.map \n (fun (kv : System.Collections.Generic.KeyValuePair) -> \n (ctmc_result.to_species.[kv.Key] |> namer, kv.Value)) state\n { species = \n species\n |> List.ofSeq\n |> Stringmap.of_list\n transitions = [||] })\n \n \/\/Then we patch in the transitions to IDs\n let statesToTransmitWithTransitions = \n (originalStates, statesToTransmitWithoutTransitions) \n ||> Array.mapi2 (fun i (k, v) withoutTransitions -> \n let transitions = v\n \n let mapTransition (transition : Transition) = \n { target = Dictionary.find idmap transition.target\n \/\/ I'm converting the propensity to a string, so that the UI doesn't have to bother stringifying it.\n propensity = Expression.to_string (fun s -> s) transition.propensity }\n \n let mappedTransitions = \n transitions\n |> List.map mapTransition\n |> List.toArray\n \n { withoutTransitions with transitions = mappedTransitions })\n \n { states = statesToTransmitWithTransitions\n start_index = Dictionary.find idmap ctmc_result.ctmc.initial_state\n attributes = attributes.ToArray() }\n\nlet simulateMeanStdevProbabilities (ig : GuiIG) (model_id:string) (instance : Instance) (ctmc_output:state_space -> unit) (output : Row -> unit) (output_export:export_def->unit) (cancel:bool ref) : Probabilities = \n let crn = prepare_CRN_for_sim ig model_id instance\n let attributes (sp:Species) = Stringmap.find sp.name crn.attributes\n let ctmc_output ctmc = convert_state_space ctmc attributes |> ctmc_output\n let cme = \n match crn.settings.simulator with\n | Simulator.CME -> crn.simulate_cme_callback cancel ctmc_output output\n | Simulator.CMESundials -> let (cme,_) = crn.simulate_cmesundials_callback cancel ctmc_output output in cme\n | _ -> failwith \"simulator does not return mean+stdev and probabilities\"\n let idx = new System.Collections.Generic.Dictionary()\n Array.iter (fun (p : Population) -> idx.Add(p.species.name, p.species)) \n cme.simulator.populations.index_to_species\n cme.probabilities\n\nlet getProbabilityMap (p : Probabilities) (speciesName : string) (lowerBound: float): probabilityMap = \n let times = Cme.get_times p\n let (_, max, min) = Probabilities.get_bounds p speciesName\n let values = List.init (max - min + 1) (fun i -> i + min)\n let probabilities = Probabilities.probability_map (Some lowerBound) p speciesName\n { times = times\n values = values\n probabilities = probabilities }\n\nlet simulateFloatJIT (gui:GuiModel) (jit:jit<'a>) (output : Row -> unit) (output_plottable:Jit.newplottable->unit) (output_export:export_def->unit) (output_program:GuiIG->unit) (cancel:bool ref)=\n Jit.simulate_callback cancel output output_plottable jit.jit jit.calculus\n let crn = gui.top.to_crn()\n let final_crn = Jit.to_crn jit.jit crn\n \/\/ Workaround for https:\/\/github.com\/dotnet-websharper\/core\/issues\/1091\n let mutable svg = \"\"\n try svg <- Svg.to_string Crn.default_svg_style <| Crn.initials_to_svg final_crn\n with e -> svg <- e.Message\n let svg = [|svg|]\n let exp = { content_type = \"image\/svg+xml\" ; id = \"finals\" ; display_name = \"Finals\" ; node_id = Some gui.top.name ; instance = None ; content = Some svg; save_content = None }\n output_export exp\n let mutable svg = \"\"\n try svg <- Svg.to_string Crn.default_svg_style <| Crn.reactions_to_svg final_crn\n with e -> svg <- e.Message\n let svg = [|svg|]\n let exp = { content_type = \"image\/svg+xml\" ; id = \"reactions\" ; display_name = \"Reactions\" ; node_id = Some gui.top.name ; instance = None ; content = Some svg; save_content = None }\n output_export exp\n let mutable code = \"\"\n try code <- final_crn.to_string()\n with e -> code <- e.Message\n let code = [|code|]\n let exp = { content_type = \"text\/plain\" ; id = \"code\" ; display_name = \"Code\" ; node_id = Some gui.top.name ; instance = None ; content = Some code; save_content = None }\n output_export exp\n let final_crn = { final_crn with initials = crn.initials }\n let final_crn = final_crn.saturate_initials()\n let gui = Gui.from_crn final_crn\n let gui = { top = gui; systems = [] }\n let gui = { task = None; nodes = [(\"\",gui)] |> Map.ofList; edges = Map.empty; expanded = false }\n output_program gui\n\nlet simulator_to_value_type (settings:Crn_settings) =\n match settings.simulator with\n | Simulator.LNA -> MeanStdev\n | Simulator.CME | Simulator.CMESundials -> MeanStdevProbabilities\n | Simulator.Oslo -> Float\n | Simulator.SSA ->\n if settings.stochastic.trajectories > 1 then MeanStdevTable else Float\n | Simulator.Sundials -> Float\n | Simulator.PDE -> \n match settings.spatial.dimensions with\n | 1 -> Spatial1D\n | 2 -> Spatial2D\n | _ -> failwith \"unsupported number of dimensions\"\n | Simulator.MC -> MeanStdev\n\nlet user_get_sim_runs (guiig: GuiIG) (model_id:string) : sim_run = \n let ig = guiig.to_ig()\n let igEx = InferenceSiteGraph.expandAndLift ig\n let model = Map.find model_id igEx.nodes\n \/\/ Verify that all systems use the same simulator. Systems with different simulators can work in theory, but would require changing the way sim runs are declared and processed.\n let base_settings = match model.systems with [] -> model.top.settings | first::_ -> first.settings\n model.systems |> List.iter (fun crn -> if crn.settings.simulator <> base_settings.simulator then failwith \"Systems with different simulators are not supported\")\n let value_type = simulator_to_value_type base_settings\n let instances = get_instances guiig model_id\n { value_type = value_type\n \/\/jit = false \/\/ TODO: set jit appropriately\n \/\/AP\/\/instances = crn.get_instances() }\n instances = instances }\n\n\/\/This is what happens when the user clicks Parse when the CRN -> Code tab is selected\nlet user_parse_code (code : string) = \n let igraph = (parse_code code)\n let gui = GuiIG.from_ig igraph\n gui\n\nlet model_to_single_export (ig:IGraph) (nodeId:string) (id:string) : export_def =\n let node = Map.find nodeId ig.nodes\n let model = node.saturate_initials()\n match id with\n | \"code\" ->\n \/\/ Workaround for https:\/\/github.com\/dotnet-websharper\/core\/issues\/1091\n let mutable content = \"\"\n try\n if nodeId = \"\" then\n content <- { IGraph.task=ig.task; IGraph.nodes=Map.ofList[\"\",model]; IGraph.edges=Map.empty; IGraph.expanded=false }.to_string()\n else\n content <- model.string()\n with e -> content <- e.Message\n let content = [|content|]\n { content_type = \"text\/plain\"; id = id; display_name = \"Code\"; node_id = Some nodeId; instance = None ; content = Some content; save_content = None }\n | \"sbml\" ->\n let mutable content = \"\"\n try content <- Sbml.to_xml (model.to_sbml())\n with e -> content <- e.Message\n let content = [|content|]\n { content_type = \"text\/plain\"; id = id; display_name = \"SBML\"; node_id = Some nodeId;instance = None ; content = Some content; save_content = None }\n | \"initials\" ->\n let mutable content = \"\"\n try content <- Svg.to_string Crn.default_svg_style <| Model.initials_to_svg model\n with e -> content <- e.Message\n let content = [|content|]\n { content_type = \"image\/svg+xml\"; id = id; display_name = \"Initials\"; node_id = Some nodeId;instance = None ; content = Some content; save_content = None }\n | \"finals\" ->\n let content = \"Finals not available for single export\"\n let content = [|content|]\n { content_type = \"image\/svg+xml\"; id = id; display_name = \"Finals\"; node_id = Some nodeId;instance = None ; content = Some content; save_content = None }\n | \"reactions\" ->\n let mutable content = [||]\n try content <- Model.reactions_to_svgs model |> List.map (Svg.to_string Crn.default_svg_style) |> List.toArray\n with e -> content <- [|e.Message|]\n let mutable scontent = \"\"\n try scontent <- Svg.to_string Crn.default_svg_style <| Model.reactions_to_svg model\n with e -> scontent <- e.Message\n { content_type = \"image\/svg+xml\"; id = id; display_name = \"Reactions\"; node_id = Some nodeId;instance = None ; content = Some content; save_content = Some scontent }\n | \"matlab\" ->\n let mutable content = \"\"\n try content <- model.to_matlab()\n with e -> content <- e.Message\n let content = [|content|]\n { content_type = \"text\/plain\"; id = id; display_name = \"Matlab\"; node_id = Some nodeId;instance = None ; content = Some content; save_content = None }\n | _ ->\n let content = \"Unknown export ID \" + id\n let content = [|content|]\n { content_type = \"text\/plain\"; id = id; display_name = id; node_id = Some nodeId;instance = None ; content = Some content; save_content = None }\n\nlet model_to_export final (ig:IGraph) (nodeId:string) : export_def[] = \n let node = Map.find nodeId ig.nodes\n let model = node.saturate_initials()\n let initials = try if final then None else Svg.to_string Crn.default_svg_style <| Model.initials_to_svg model |> Some with e -> Some e.Message\n let initials = match initials with Some initials -> Some [|initials|] | None -> None\n let finals = try if final then Svg.to_string Crn.default_svg_style <| Model.initials_to_svg model |> Some else Some \"\" with e -> Some e.Message\n let finals = match finals with Some finals -> Some [|finals|] | None -> None\n [| { content_type = \"text\/plain\"; id = \"code\"; display_name = \"Code\"; node_id = Some nodeId; instance = None ;content = None; save_content = None }\n { content_type = \"text\/plain\"; id = \"sbml\"; display_name = \"SBML\"; node_id = Some nodeId; instance = None ;content = None; save_content = None }\n { content_type = \"image\/svg+xml\" ; id = \"initials\" ; display_name = \"Initials\" ; node_id = Some nodeId; instance = None ;content = initials; save_content = None }\n { content_type = \"image\/svg+xml\" ; id = \"finals\" ; display_name = \"Finals\" ; node_id = Some nodeId; instance = None ;content = finals; save_content = None }\n { content_type = \"image\/svg+xml\"; id = \"reactions\"; display_name = \"Reactions\"; node_id = Some nodeId; instance = None ;content = None; save_content = None }\n { content_type = \"text\/plain\"; id = \"matlab\"; display_name = \"Matlab\"; node_id = Some nodeId; instance = None ;content = None; save_content = None } |]\n\n\/\/This is what happens when the user clicks Parse when one of the CRN -> Directives, Parameters, Species or Reactions tab is selected (currently, all this does is generate the exports). The \"final\" flag indicates whether the population should be considered a final population (and therefore go in the \"finals\" export); this concept should be reworked.\nlet user_get_exports final (gui : GuiIG) (nodeId: string) =\n let ig = gui.to_ig()\n let exports = model_to_export final ig nodeId\n exports\n\nlet user_get_export (gui:GuiIG) (nodeId: string) (id:string) =\n let ig = gui.to_ig()\n let export = model_to_single_export ig nodeId id\n export\n\ntype inference_evaluated_values = \n { values : System.Collections.Generic.Dictionary\n lglk : float }\n\nlet convert_evaluated_values (ev : Microsoft.Research.Filzbach.Parameters.EvaluatedValues) = \n let convert_associative_array (aa : Microsoft.Research.Filzbach.DataStructures.AssociativeArray<'t>) = \n let ret = new System.Collections.Generic.Dictionary()\n Array.iter (fun name -> ret.Add(name, aa.Item(name))) aa.Names\n ret\n { values = convert_associative_array ev.values\n lglk = ev.logLikelihood }\n\ntype inference_burnin = \n { space : System.Collections.Generic.Dictionary \/\/contains only non-fixed parameters information\n state : inference_evaluated_values \/\/contains all parameters (non-fixed followed by fixed)\n stats : Microsoft.Research.Filzbach.Parameters.ParameterStatistics\n mle : inference_evaluated_values\n priors : Microsoft.Research.Filzbach.Parameters.PriorValue option array\n indexes : int array }\n\ntype inference_sampling = \n { space : System.Collections.Generic.Dictionary \/\/contains only non-fixed parameters information\n state : inference_evaluated_values \/\/contains all parameters (non-fixed followed by fixed)\n thinningSkippedCount : int \/\/how many steps are passed after last save of state to the chain\n chain : inference_evaluated_values list\n mle : inference_evaluated_values\n priors : Microsoft.Research.Filzbach.Parameters.PriorValue option array\n indexes : int array }\n\n[]\ntype inference_phase = \n | BurninPhase of BurninPhase : inference_burnin\n | SamplingPhase of SamplingPhase : inference_sampling\n\ntype inference_result = \n { nodeId : string\n iteration : int\n lkincreased : bool\n state : inference_phase\n mlesims : Microsoft.Research.CRNEngine.Result list option\n summary : string }\n\nlet convert_inference_result nodeId (res : Inference.mcmc_intermediate_result) (lkincreased:bool) : inference_result = \n let convert_associative_array (aa : Microsoft.Research.Filzbach.DataStructures.AssociativeArray<'t>) = \n let ret = new System.Collections.Generic.Dictionary()\n Array.iter (fun name -> ret.Add(name, aa.Item(name))) aa.Names\n ret\n let convert_phase (p : Filzbach.RunPhase) : inference_phase = \n match p with\n | Filzbach.BurninPhase p -> \n BurninPhase { inference_burnin.space = convert_associative_array p.space\n inference_burnin.state = convert_evaluated_values p.state\n inference_burnin.stats = p.stats\n inference_burnin.mle = convert_evaluated_values p.mle\n inference_burnin.priors = p.priors\n inference_burnin.indexes = p.indexes }\n | Filzbach.SamplingPhase p -> \n SamplingPhase { inference_sampling.space = convert_associative_array p.space\n inference_sampling.state = convert_evaluated_values p.state\n inference_sampling.thinningSkippedCount = p.thinningSkippedCount\n inference_sampling.chain = List.map convert_evaluated_values p.chain\n inference_sampling.mle = convert_evaluated_values p.mle\n inference_sampling.priors = p.priors\n inference_sampling.indexes = p.indexes }\n { nodeId = nodeId\n iteration = res.iteration\n lkincreased = lkincreased\n state = convert_phase res.state\n mlesims = if lkincreased then Some res.mlesims else None\n summary = res.summary }\n\ntype InferenceParameterType = | [] Real\n | [] Log\n | [] Fixed\ntype InferenceParameterRange =\n { pType: InferenceParameterType\n lb: float\n ub:float }\ntype InferenceParameter =\n { name : string\n range : InferenceParameterRange\n initValue: float option }\ntype InferenceParameters =\n { nodeId : string\n parameters : InferenceParameter list }\n\nlet combine_dynchar_exports (exports:(string*Plotting.html_content) list) : export_def =\n match exports with\n | [(_,export)] ->\n let html_string = Plotting.structured_tabbed_embedded \"top_tabs\" export\n let html_string = [|html_string|]\n let html_page = Plotting.structured_tabbed \"\" \"top_tabs\" export\n {content_type = \"text\/html\"; id = \"dynamicCharacterization\"; display_name = \"Dynamic Characterization\"; node_id = None; instance = None ;content = Some html_string; save_content = Some html_page }\n | _ ->\n let embedded = List.mapi (fun i (name,content) -> name,(Plotting.structured_tabbed_embedded (sprintf \"group%d\" i) content)) exports |> Seq.toList\n let html_string = Plotting.arbitrary_tabbed_content \"top_tabs\" embedded |> Plotting.make_embedded\n let html_string = [|html_string|]\n let html_page = Plotting.arbitrary_tabbed \"Dynamic Characterisation\" embedded\n {content_type = \"text\/html\"; id = \"dynamicCharacterization\"; display_name = \"Dynamic Characterization\"; node_id = None; instance = None ;content = Some html_string; save_content = Some html_page }\n\n\/\/ Produces a stream of inference results, in GUI-friendly format.\nlet user_infer_gui (gui : GuiIG) (output_export : export_def -> unit) (output_parameter_definitions : InferenceParameters -> unit) (output_inference : inference_result -> unit) (cancel:bool ref) =\n \/\/ Prepare the inference graph.\n let ig = gui.to_ig()\n let ig = InferenceSiteGraph.expandAndLift ig\n let dynchar_exports = new System.Collections.Generic.List()\n \/\/ This is the function that runs inference on a single model. It will report its progress through the callbacks.\n let infer_model (model:Model) =\n \/\/ Maintain the last unconverted result, which will be required to perform final export operations.\n let mutable final_result : Inference.mcmc_result option = None\n let results, parameters = model.infer_seq (fun result -> final_result <- Some result)\n \/\/ Convert the Filzbach-style parameters into GUI-style parameters.\n let convert_parameter (filzpar:Parameters.Parameter) : InferenceParameter =\n { name = filzpar.name\n range = { pType = match filzpar.range.pType with Parameters.ParameterType.Real -> Real\n | Parameters.ParameterType.Log -> Log\n | Parameters.ParameterType.Fixed -> Fixed\n lb = filzpar.range.lb\n ub = filzpar.range.ub }\n initValue = filzpar.initValue }\n let parameters = List.map convert_parameter parameters\n \/\/ Convert the stream and output accessory informations.\n let results = results |> Seq.choose (fun (a,_,increased) -> match a with None -> None | Some a -> convert_inference_result model.top.name a increased |> Some)\n output_parameter_definitions { nodeId = model.top.name; parameters = parameters }\n \/\/ Output the stream.\n Seq.iter output_inference results\n \/\/ Look at the final result. If inference terminated correctly, it should be a SamplingPhase.\n match final_result with\n | Some result ->\n \/\/ Generate the final exports.\n if result.posterior <> [] then\n let exp = Html.mcmc_to_results model.top.settings model result |> Html.results_to_html_content\n dynchar_exports.Add(model.top.name,exp);\n | None -> ()\n final_result.Value.to_summary()\n \/\/ Run inference on the graph.\n InferenceSiteGraph.inferWith infer_model ig |> ignore\n \/\/ Combine and output the dynamic characterisation exports\n let export = dynchar_exports |> List.ofSeq |> combine_dynchar_exports \n output_export export\n \nlet user_state_space (gui : GuiIG) = \n let model = gui.nodes |> Map.toSeq |> Seq.head |> snd\n let crn = model.top.to_crn()\n let ctmc_result = crn.to_ctmc()\n let attributes (sp:Species) = Stringmap.find sp.name crn.attributes\n convert_state_space ctmc_result attributes\n\nlet user_state_space_jit (jit:jit<'a>) =\n let (ss,attributes) = Jit.to_ctmc jit.jit jit.calculus\n convert_state_space ss attributes\n\nlet expression_to_string (exp : Expression.t) = exp |> Expression.to_string id\n\nlet mcplot_to_string (mcplot : Moment_closure_settings.monomial) = Moment_closure_settings.to_string_monomial mcplot\n\ntype column_array<'v> = \n { name : string\n values : 'v [] }\n\ntype table_array<'v> = \n { times : float []\n columns : column_array<'v> [] }\n\nlet test_crn_deterministic (crn : string) : table_array = \n let table = (Parser.from_string Crn.parse crn).to_oslo().simulate()\n { \/\/table \n \/\/Expando lists are awkward to work with in JavaScript, turn them into arrays\n times = table.times |> Array.ofList\n columns = \n (table.columns |> List.map (fun column -> \n { name = column.name\n values = column.values |> Array.ofList }))\n |> Array.ofList }\n\nlet test_crn_sundials (crn : string) : table_array = \n let table = (Parser.from_string Crn.parse crn).to_sundials().simulate()\n { \/\/table \n \/\/Expando lists are awkward to work with in JavaScript, turn them into arrays\n times = table.times |> Array.ofList\n columns = \n (table.columns |> List.map (fun column -> \n { name = column.name\n values = column.values |> Array.ofList }))\n |> Array.ofList }\n\nlet prepare_for_cme (crnStr:string) =\n let crn = Parser.from_string Crn.parse crnStr\n let ctmc = crn.to_ctmc()\n let cme = crn.to_cme ctmc\n let env = Parameters.to_env crn.settings.parameters\n let rates = Crn.to_inlined_rates crn.settings\n cme, env, rates\n\nlet test_crn_cme_sundials (crn : string) : table_array = \n\n let cme, env, rates = prepare_for_cme crn\n let cme, table = cme.simulate_sundials env rates\n {\n times = table.times |> Array.ofList\n columns = \n (table.columns |> List.map (fun column -> \n { name = column.name\n values = column.values |> Array.ofList }))\n |> Array.ofList }","avg_line_length":51.5902140673,"max_line_length":351,"alphanum_fraction":0.6660343806}
+{"size":8058,"ext":"fs","lang":"F#","max_stars_count":null,"content":"\ufeff\/\/ *********************************************************\r\n\/\/\r\n\/\/ Copyright (c) Microsoft. All rights reserved.\r\n\/\/ This code is licensed under the Apache License, Version 2.0.\r\n\/\/ THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF\r\n\/\/ ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY\r\n\/\/ IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR\r\n\/\/ PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.\r\n\/\/\r\n\/\/ *********************************************************\r\n\r\nnamespace Microsoft.Research.Dkal\r\n\r\nopen NLog\r\nopen System\r\nopen System.IO\r\nopen System.Diagnostics\r\nopen System.Text\r\nopen System.Threading\r\nopen System.Text.RegularExpressions\r\nopen System.Collections.Generic\r\n\r\n\r\nopen Microsoft.Research.Dkal.Interfaces\r\nopen Microsoft.Research.Dkal.Infostrate.Factories\r\nopen Microsoft.Research.Dkal.Executor.Factories\r\nopen Microsoft.Research.Dkal.LogicEngine.Factories\r\nopen Microsoft.Research.Dkal.MailBox.Factories\r\nopen Microsoft.Research.Dkal.SignatureProvider.Factories\r\nopen Microsoft.Research.Dkal.Router.Factories\r\nopen Microsoft.Research.Dkal.Router.Local\r\nopen Microsoft.Research.Dkal.Ast.Infon.Syntax.Factories\r\nopen Microsoft.Research.Dkal.Ast\r\nopen Microsoft.Research.Dkal.Ast.Infon\r\nopen Microsoft.Research.Dkal.Factories.Initializer\r\nopen Microsoft.Research.Dkal.Utils.Exceptions\r\nopen Microsoft.Research.Dkal.Utils.ErrorCodes\r\nopen Microsoft.Research.Dkal.Globals\r\nopen Microsoft.Research.Dkal.LogicEngine.UFOL\r\nopen Microsoft.Research.Dkal.LogicEngine.Datalog\r\n\r\n\/\/\/ Console front-end for many principals\r\nmodule MultiMain =\r\n \r\n \/\/ TODO: change log format to match RiSE4fun.com standards\r\n \/\/ (it is used in Code Contracts, for instance)\r\n let private log = LogManager.GetLogger(\"MultiMain\")\r\n\r\n let private messagesLimitExceeded = new AutoResetEvent(false)\r\n\r\n \/\/ TODO see how to avoid linking to UFOLEngine just to check the appropriate infostrate\r\n let private createExec(router: IRouter, assembly: Assembly, assemblyInfo: MultiAssembly, logicEngineKind: string) =\r\n \r\n let logicEngine = LogicEngineFactory.LogicEngine (logicEngineKind, Some assemblyInfo)\r\n let kind =\r\n match logicEngine with\r\n | :? UFOLogicEngine as engine -> \"ufol\"\r\n | :? DatalogLogicEngine as engine -> \"datalog\"\r\n | _ -> \"simple\"\r\n let infostrate = InfostrateFactory.Infostrate kind\r\n let signatureProvider = SignatureProviderFactory.SignatureProvider kind \r\n let mailbox = MailBoxFactory.MailBox kind logicEngine\r\n let executor = ExecutorFactory.Executor (kind, router, logicEngine, signatureProvider, infostrate, mailbox)\r\n\r\n\/\/ if assembly.Signature.Substrates.Length > 0 then \/\/ TODO: forbid SQL substrate\r\n\/\/ printfn \"%s: Substrate declarations are fobidden\" router.Me\r\n \r\n for ka in assembly.Policy.KA do\r\n infostrate.Learn ka |> ignore\r\n for rule in assembly.Policy.Rules do\r\n executor.InstallRule rule |> ignore\r\n executor\r\n \r\n let lineCount (s: string) = s.Split('\\n').Length\r\n\r\n let splitPolicies (policy : string) =\r\n let rec splitrec (s: string) =\r\n let mutable i = 0\r\n while i < s.Length && s.[i]='-' do\r\n i <- i + 1\r\n let ppalName = StringBuilder()\r\n while i < s.Length && s.[i]<>'-' do\r\n ppalName.Append(s.[i]) |> ignore\r\n i <- i + 1\r\n if ppalName.Length = 0 then failwithf \"invalid policy header:\\n%s\" s\r\n while i < s.Length && s.[i]='-' do\r\n i <- i + 1\r\n let s = s.Substring(i)\r\n let j = s.IndexOf(\"---\")\r\n if j<0 then\r\n [(ppalName.ToString(), s)]\r\n else\r\n (ppalName.ToString(), s.Substring(0, j)) :: splitrec(s.Substring(j))\r\n let i = policy.IndexOf(\"---\")\r\n if i<0 then failwith \"headers not found in policy file\"\r\n let commonPolicy = policy.Substring(0, i)\r\n (commonPolicy, splitrec (policy.Substring(i)))\r\n\r\n let private execute (policy: string, timeLimit: int, msgsLimit: int, logicEngineKind: string) =\r\n \/\/ Populate factories\r\n FactoriesInitializer.Init()\r\n\r\n let (commonPolicy,ppals) = splitPolicies policy\r\n let mlogic = Regex.Match(commonPolicy, \"^\/\/\/\\s*logic:\\s*(\\w+)\", RegexOptions.IgnoreCase)\r\n let logicEngineKind = if mlogic.Success then mlogic.Groups.[1].Value else logicEngineKind\r\n let routers = RouterFactory.LocalRouters (ppals |> List.map fst)\r\n\r\n let ppalsWithOffset = ppals |> List.fold (fun acc x -> \r\n match acc with\r\n | [] -> [fst x, snd x, 0]\r\n | (_,pol,l) :: _ -> (fst x, snd x, l + lineCount(pol)-1) :: acc) [] |> List.rev\r\n let parse (ppal,policy,lineOffset) =\r\n let parser = ParserFactory.InfonParser(\"simple\", routers.[ppal].Me)\r\n try\r\n (ppal, parser.ParseAssembly (commonPolicy + policy))\r\n with\r\n | ParseException(msg, text, line, col) ->\r\n log.Error(\"{0}.dkal({1},{2}): error {3}: {4}\", ppal, lineOffset + line, col, errorParsing, msg)\r\n Environment.Exit(1); failwith \"\"\r\n | SemanticCheckException(desc, o) ->\r\n log.Error(\"{0}.dkal(0,0): error {1}: {2} at {3}\", ppal, errorSemanticCheck, desc, o)\r\n Environment.Exit(1); failwith \"\"\r\n let assemblies = ppalsWithOffset |> List.map parse\r\n \r\n \/\/ collect all distinct relation declarations from the assemblies\r\n let signatures=\r\n assemblies |>\r\n List.collect (fun assembly -> (snd assembly).Signature.Relations) |>\r\n List.fold (fun acc sign ->\r\n match acc with\r\n | _ when List.exists (fun sign' -> sign' = sign) acc -> acc\r\n | _ -> sign::acc ) []\r\n let multiAssembly= { TypeRenames = Dictionary(); Relations= signatures; PrincipalPolicies= \r\n assemblies |>\r\n List.fold (fun acc x -> \r\n acc.[fst x] <- snd x\r\n acc) (Dictionary()) }\r\n\r\n let fixedPointCounter = new CountdownEvent(assemblies.Length)\r\n let executors = assemblies |> List.mapi (fun i x ->\r\n let exec = createExec(routers.[fst x], snd x, multiAssembly, logicEngineKind)\r\n exec.FixedPointCallback \r\n (fun _ ->\r\n let reachedGlobalFixedPoint = try fixedPointCounter.Signal() with e -> true\r\n log.Trace(\"{0} went to sleep (reached global fixed-point = {1} -- counter = {2})\", fst x, reachedGlobalFixedPoint, fixedPointCounter.CurrentCount)\r\n if reachedGlobalFixedPoint then\r\n messagesLimitExceeded.Set() |> ignore)\r\n exec.WakeUpCallback \r\n (fun _ -> \r\n let success = fixedPointCounter.TryAddCount()\r\n log.Trace(\"{0} woke up (success = {1} -- counter = {2})\", fst x, success, fixedPointCounter.CurrentCount))\r\n if i = 0 then\r\n let localMailer = (routers.[fst x] :?> LocalRouter).LocalMailer\r\n localMailer.AddCallback msgsLimit \r\n (fun _ -> messagesLimitExceeded.Set() |> ignore)\r\n exec\r\n )\r\n executors |> List.iter (fun x -> x.Start())\r\n let reachedTimeLimit = not <| messagesLimitExceeded.WaitOne(timeLimit) \r\n executors |> List.iter (fun x -> x.Stop())\r\n if reachedTimeLimit then\r\n log.Info(\"Time limit exceeded at {0} milliseconds\", timeLimit)\r\n elif fixedPointCounter.IsSet then\r\n log.Info(\"Fixed-point reached\")\r\n else\r\n log.Info(\"Message limit exceeded at {0} messages\", msgsLimit)\r\n \/\/ Do a hard kill (in case the last round takes too long after stop was signaled)\r\n Thread.Sleep(500)\r\n Process.GetCurrentProcess().Kill()\r\n\r\n let private args = System.Environment.GetCommandLineArgs() |> Seq.toList\r\n match args with\r\n | exe :: \"-ws\" :: tail ->\r\n Rise4FunWebService.startWebService tail\r\n | exe :: policyFile :: timeLimit :: msgsLimit :: tail ->\r\n if not (File.Exists (policyFile)) then\r\n log.Fatal(\"File not found: {0}\", policyFile)\r\n else\r\n try\r\n execute(File.ReadAllText(policyFile), Int32.Parse(timeLimit), Int32.Parse(msgsLimit), LogicEngineFactory.parseLogicEngineKind tail)\r\n with\r\n e -> log.ErrorException(\"Something went wrong\", e)\r\n | _ -> log.Fatal(\"Wrong number of parameters; expecting multi-policy file, time limit (ms), messages limit\")\r\n","avg_line_length":43.7934782609,"max_line_length":157,"alphanum_fraction":0.6542566394}
+{"size":1068,"ext":"fs","lang":"F#","max_stars_count":null,"content":"\ufeffmodule Paket.IntegrationTests.InfoSpecs\n\nopen Fake\nopen System\nopen NUnit.Framework\nopen FsUnit\nopen System\nopen System.IO\nopen System.Diagnostics\n\n[]\nlet ``#3200 info should locate paket.dependencies``() = \n let repoDir = createScenarioDir \"i003200-info-paketdeps-dir\"\n\n let subDir = repoDir <\/> \"src\" <\/> \"app\"\n Directory.CreateDirectory(subDir) |> ignore\n\n let ``paket info --paket-dependencies-dir`` workingDir =\n directPaketInPathEx \"info --paket-dependencies-dir\" workingDir\n |> Seq.map PaketMsg.getMessage\n |> List.ofSeq\n\n \/\/ paket.dependencies not exists\n \n CollectionAssert.DoesNotContain(``paket info --paket-dependencies-dir`` repoDir, repoDir)\n CollectionAssert.DoesNotContain(``paket info --paket-dependencies-dir`` subDir, repoDir)\n\n \/\/ empty paket.dependencies\n File.WriteAllText(repoDir <\/> \"paket.dependencies\", \"\")\n\n CollectionAssert.Contains(``paket info --paket-dependencies-dir`` repoDir, repoDir)\n CollectionAssert.Contains(``paket info --paket-dependencies-dir`` subDir, repoDir)\n\n","avg_line_length":31.4117647059,"max_line_length":93,"alphanum_fraction":0.7219101124}
+{"size":734,"ext":"fsx","lang":"F#","max_stars_count":null,"content":"open System\n\n\/\/ prelude\nlet readStr () = stdin.ReadLine()\n\nlet readInt () = stdin.ReadLine() |> int\nlet readInts () = stdin.ReadLine().Split() |> Array.map int64\n\nlet pair = function\n| [|a; b|] -> (a, b)\n| _ -> failwith \"owatta\"\n\nlet triple = function\n| [|a; b; c|] -> (a, b, c)\n| _ -> failwith \"owatta\"\n\nlet inc n = n + 1\nlet dec n = n - 1\n\nlet inline flip f a b = f b a\nlet rec fix f = fun x -> (f (fix f)) x\n\nmodule Option =\n let getOr defaultValue = function\n | Some x -> x\n | None -> defaultValue\n\nmodule Array =\n let modify (arr: _ []) i f =\n arr.[i] <- f arr.[i]\n\nmodule Array2D =\n let modify (arr: _ [,]) i j f =\n arr.[i, j] <- f arr.[i, j]\n\n\/\/ start\nlet (N,K)=readInts() |> pair\n\nprintfn \"%d\" (min (N%K) (K-(N%K)))","avg_line_length":18.8205128205,"max_line_length":61,"alphanum_fraction":0.5613079019}
+{"size":206,"ext":"fs","lang":"F#","max_stars_count":2.0,"content":"#version 330 core\n\nlayout (location = 0) out vec4 FragColor;\n\nvoid main() {\n\tvec3 objectColor = vec3(0.3f, 0.3f, 1.0f);\n\tvec3 lightColor = vec3( 1.0f );\n\tFragColor = vec4(objectColor * lightColor, 1.0f);\n}\n","avg_line_length":20.6,"max_line_length":50,"alphanum_fraction":0.6747572816}
+{"size":2893,"ext":"fsx","lang":"F#","max_stars_count":null,"content":"\/\/\/ Problem 8 - Largest product in a series\n\/\/\/\n\/\/\/ Find the greatest product of five consecutive digits in the 1000-digit number.\n\/\/\/\n\/\/\/ 73167176531330624919225119674426574742355349194934\n\/\/\/ 96983520312774506326239578318016984801869478851843\n\/\/\/ 85861560789112949495459501737958331952853208805511\n\/\/\/ 12540698747158523863050715693290963295227443043557\n\/\/\/ 66896648950445244523161731856403098711121722383113\n\/\/\/ 62229893423380308135336276614282806444486645238749\n\/\/\/ 30358907296290491560440772390713810515859307960866\n\/\/\/ 70172427121883998797908792274921901699720888093776\n\/\/\/ 65727333001053367881220235421809751254540594752243\n\/\/\/ 52584907711670556013604839586446706324415722155397\n\/\/\/ 53697817977846174064955149290862569321978468622482\n\/\/\/ 83972241375657056057490261407972968652414535100474\n\/\/\/ 82166370484403199890008895243450658541227588666881\n\/\/\/ 16427171479924442928230863465674813919123162824586\n\/\/\/ 17866458359124566529476545682848912883142607690042\n\/\/\/ 24219022671055626321111109370544217506941658960408\n\/\/\/ 07198403850962455444362981230987879927244284909188\n\/\/\/ 84580156166097919133875499200524063689912560717606\n\/\/\/ 05886116467109405077541002256983155200055935729725\n\/\/\/ 71636269561882670428252483600823257530420752963450\n\/\/\/\n\/\/\/ Author: Vili L\u00e4htev\u00e4noja\n\/\/\/\n\n#time\nlet nStr = \"73167176531330624919225119674426574742355349194934\"\n + \"96983520312774506326239578318016984801869478851843\"\n + \"85861560789112949495459501737958331952853208805511\"\n + \"12540698747158523863050715693290963295227443043557\"\n + \"66896648950445244523161731856403098711121722383113\"\n + \"62229893423380308135336276614282806444486645238749\"\n + \"30358907296290491560440772390713810515859307960866\"\n + \"70172427121883998797908792274921901699720888093776\"\n + \"65727333001053367881220235421809751254540594752243\"\n + \"52584907711670556013604839586446706324415722155397\"\n + \"53697817977846174064955149290862569321978468622482\"\n + \"83972241375657056057490261407972968652414535100474\"\n + \"82166370484403199890008895243450658541227588666881\"\n + \"16427171479924442928230863465674813919123162824586\"\n + \"17866458359124566529476545682848912883142607690042\"\n + \"24219022671055626321111109370544217506941658960408\"\n + \"07198403850962455444362981230987879927244284909188\"\n + \"84580156166097919133875499200524063689912560717606\"\n + \"05886116467109405077541002256983155200055935729725\"\n + \"71636269561882670428252483600823257530420752963450\"\nlet ns =\n nStr.ToCharArray()\n |> Seq.ofArray\n |> Seq.windowed 13\n |> Seq.map ( fun a -> a|> Array.map (fun c -> int64(int(c) - int('0'))))\nlet products = ns |> Seq.map (fun x -> Array.fold (fun acc n -> acc*n) (int64(1)) x) \nlet res = string(Seq.max products)\n#time\nprintfn \"%s\" res \n","avg_line_length":49.0338983051,"max_line_length":85,"alphanum_fraction":0.7943311441}
+{"size":32893,"ext":"fs","lang":"F#","max_stars_count":1.0,"content":"\/\/ Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.\n\nnamespace Microsoft.FSharp.Collections\n\n open System\n open System.Collections.Generic\n open System.Diagnostics\n open Microsoft.FSharp.Core\n open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators\n\n []\n []\n type MapTree<'Key,'Value when 'Key : comparison > = \n | MapEmpty \n | MapOne of 'Key * 'Value\n | MapNode of 'Key * 'Value * MapTree<'Key,'Value> * MapTree<'Key,'Value> * int\n \/\/ REVIEW: performance rumour has it that the data held in MapNode and MapOne should be\n \/\/ exactly one cache line. It is currently ~7 and 4 words respectively. \n\n []\n module MapTree = \n\n let rec sizeAux acc m = \n match m with \n | MapEmpty -> acc\n | MapOne _ -> acc + 1\n | MapNode(_,_,l,r,_) -> sizeAux (sizeAux (acc+1) l) r \n\n let size x = sizeAux 0 x\n\n\n #if TRACE_SETS_AND_MAPS\n let mutable traceCount = 0\n let mutable numOnes = 0\n let mutable numNodes = 0\n let mutable numAdds = 0\n let mutable numRemoves = 0\n let mutable numLookups = 0\n let mutable numUnions = 0\n let mutable totalSizeOnNodeCreation = 0.0\n let mutable totalSizeOnMapAdd = 0.0\n let mutable totalSizeOnMapLookup = 0.0\n let mutable largestMapSize = 0\n let mutable largestMapStackTrace = Unchecked.defaultof<_>\n let report() = \n traceCount <- traceCount + 1 \n if traceCount % 1000000 = 0 then \n System.Console.WriteLine(\"#MapOne = {0}, #MapNode = {1}, #Add = {2}, #Remove = {3}, #Unions = {4}, #Lookups = {5}, avMapTreeSizeOnNodeCreation = {6}, avMapSizeOnCreation = {7}, avMapSizeOnLookup = {8}\",numOnes,numNodes,numAdds,numRemoves,numUnions,numLookups,(totalSizeOnNodeCreation \/ float (numNodes + numOnes)),(totalSizeOnMapAdd \/ float numAdds),(totalSizeOnMapLookup \/ float numLookups))\n System.Console.WriteLine(\"#largestMapSize = {0}, largestMapStackTrace = {1}\",largestMapSize, largestMapStackTrace)\n\n let MapOne n = \n report(); \n numOnes <- numOnes + 1; \n totalSizeOnNodeCreation <- totalSizeOnNodeCreation + 1.0; \n MapTree.MapOne n\n\n let MapNode (x,l,v,r,h) = \n report(); \n numNodes <- numNodes + 1; \n let n = MapTree.MapNode(x,l,v,r,h)\n totalSizeOnNodeCreation <- totalSizeOnNodeCreation + float (size n); \n n\n #endif\n\n let empty = MapEmpty \n\n let height = function\n | MapEmpty -> 0\n | MapOne _ -> 1\n | MapNode(_,_,_,_,h) -> h\n\n let isEmpty m = \n match m with \n | MapEmpty -> true\n | _ -> false\n\n let mk l k v r = \n match l,r with \n | MapEmpty,MapEmpty -> MapOne(k,v)\n | _ -> \n let hl = height l \n let hr = height r \n let m = if hl < hr then hr else hl \n MapNode(k,v,l,r,m+1)\n\n let rebalance t1 k v t2 =\n let t1h = height t1 \n let t2h = height t2 \n if t2h > t1h + 2 then (* right is heavier than left *)\n match t2 with \n | MapNode(t2k,t2v,t2l,t2r,_) -> \n (* one of the nodes must have height > height t1 + 1 *)\n if height t2l > t1h + 1 then (* balance left: combination *)\n match t2l with \n | MapNode(t2lk,t2lv,t2ll,t2lr,_) ->\n mk (mk t1 k v t2ll) t2lk t2lv (mk t2lr t2k t2v t2r) \n | _ -> failwith \"rebalance\"\n else (* rotate left *)\n mk (mk t1 k v t2l) t2k t2v t2r\n | _ -> failwith \"rebalance\"\n else\n if t1h > t2h + 2 then (* left is heavier than right *)\n match t1 with \n | MapNode(t1k,t1v,t1l,t1r,_) -> \n (* one of the nodes must have height > height t2 + 1 *)\n if height t1r > t2h + 1 then \n (* balance right: combination *)\n match t1r with \n | MapNode(t1rk,t1rv,t1rl,t1rr,_) ->\n mk (mk t1l t1k t1v t1rl) t1rk t1rv (mk t1rr k v t2)\n | _ -> failwith \"rebalance\"\n else\n mk t1l t1k t1v (mk t1r k v t2)\n | _ -> failwith \"rebalance\"\n else mk t1 k v t2\n\n let rec add (comparer: IComparer<'Value>) k v m = \n match m with \n | MapEmpty -> MapOne(k,v)\n | MapOne(k2,_) -> \n let c = comparer.Compare(k,k2) \n if c < 0 then MapNode (k,v,MapEmpty,m,2)\n elif c = 0 then MapOne(k,v)\n else MapNode (k,v,m,MapEmpty,2)\n | MapNode(k2,v2,l,r,h) -> \n let c = comparer.Compare(k,k2) \n if c < 0 then rebalance (add comparer k v l) k2 v2 r\n elif c = 0 then MapNode(k,v,l,r,h)\n else rebalance l k2 v2 (add comparer k v r) \n\n let rec find (comparer: IComparer<'Value>) k m = \n match m with \n | MapEmpty -> raise (KeyNotFoundException())\n | MapOne(k2,v2) -> \n let c = comparer.Compare(k,k2) \n if c = 0 then v2\n else raise (KeyNotFoundException())\n | MapNode(k2,v2,l,r,_) -> \n let c = comparer.Compare(k,k2) \n if c < 0 then find comparer k l\n elif c = 0 then v2\n else find comparer k r\n\n let rec tryFind (comparer: IComparer<'Value>) k m = \n match m with \n | MapEmpty -> None\n | MapOne(k2,v2) -> \n let c = comparer.Compare(k,k2) \n if c = 0 then Some v2\n else None\n | MapNode(k2,v2,l,r,_) -> \n let c = comparer.Compare(k,k2) \n if c < 0 then tryFind comparer k l\n elif c = 0 then Some v2\n else tryFind comparer k r\n\n let partition1 (comparer: IComparer<'Value>) (f:OptimizedClosures.FSharpFunc<_,_,_>) k v (acc1,acc2) = \n if f.Invoke(k, v) then (add comparer k v acc1,acc2) else (acc1,add comparer k v acc2) \n \n let rec partitionAux (comparer: IComparer<'Value>) (f:OptimizedClosures.FSharpFunc<_,_,_>) s acc = \n match s with \n | MapEmpty -> acc\n | MapOne(k,v) -> partition1 comparer f k v acc\n | MapNode(k,v,l,r,_) -> \n let acc = partitionAux comparer f r acc \n let acc = partition1 comparer f k v acc\n partitionAux comparer f l acc\n\n let partition (comparer: IComparer<'Value>) f s = partitionAux comparer (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) s (empty,empty)\n\n let filter1 (comparer: IComparer<'Value>) (f:OptimizedClosures.FSharpFunc<_,_,_>) k v acc = if f.Invoke(k, v) then add comparer k v acc else acc \n\n let rec filterAux (comparer: IComparer<'Value>) (f:OptimizedClosures.FSharpFunc<_,_,_>) s acc = \n match s with \n | MapEmpty -> acc\n | MapOne(k,v) -> filter1 comparer f k v acc\n | MapNode(k,v,l,r,_) ->\n let acc = filterAux comparer f l acc\n let acc = filter1 comparer f k v acc\n filterAux comparer f r acc\n\n let filter (comparer: IComparer<'Value>) f s = filterAux comparer (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) s empty\n\n let rec spliceOutSuccessor m = \n match m with \n | MapEmpty -> failwith \"internal error: Map.spliceOutSuccessor\"\n | MapOne(k2,v2) -> k2,v2,MapEmpty\n | MapNode(k2,v2,l,r,_) ->\n match l with \n | MapEmpty -> k2,v2,r\n | _ -> let k3,v3,l' = spliceOutSuccessor l in k3,v3,mk l' k2 v2 r\n\n let rec remove (comparer: IComparer<'Value>) k m = \n match m with \n | MapEmpty -> empty\n | MapOne(k2,_) -> \n let c = comparer.Compare(k,k2) \n if c = 0 then MapEmpty else m\n | MapNode(k2,v2,l,r,_) -> \n let c = comparer.Compare(k,k2) \n if c < 0 then rebalance (remove comparer k l) k2 v2 r\n elif c = 0 then \n match l,r with \n | MapEmpty,_ -> r\n | _,MapEmpty -> l\n | _ -> \n let sk,sv,r' = spliceOutSuccessor r \n mk l sk sv r'\n else rebalance l k2 v2 (remove comparer k r) \n\n let rec mem (comparer: IComparer<'Value>) k m = \n match m with \n | MapEmpty -> false\n | MapOne(k2,_) -> (comparer.Compare(k,k2) = 0)\n | MapNode(k2,_,l,r,_) -> \n let c = comparer.Compare(k,k2) \n if c < 0 then mem comparer k l\n else (c = 0 || mem comparer k r)\n\n let rec iterOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) m =\n match m with \n | MapEmpty -> ()\n | MapOne(k2,v2) -> f.Invoke(k2, v2)\n | MapNode(k2,v2,l,r,_) -> iterOpt f l; f.Invoke(k2, v2); iterOpt f r\n\n let iter f m = iterOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) m\n\n let rec tryPickOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) m =\n match m with \n | MapEmpty -> None\n | MapOne(k2,v2) -> f.Invoke(k2, v2) \n | MapNode(k2,v2,l,r,_) -> \n match tryPickOpt f l with \n | Some _ as res -> res \n | None -> \n match f.Invoke(k2, v2) with \n | Some _ as res -> res \n | None -> \n tryPickOpt f r\n\n let tryPick f m = tryPickOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) m\n\n let rec existsOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) m = \n match m with \n | MapEmpty -> false\n | MapOne(k2,v2) -> f.Invoke(k2, v2)\n | MapNode(k2,v2,l,r,_) -> existsOpt f l || f.Invoke(k2, v2) || existsOpt f r\n\n let exists f m = existsOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) m\n\n let rec forallOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) m = \n match m with \n | MapEmpty -> true\n | MapOne(k2,v2) -> f.Invoke(k2, v2)\n | MapNode(k2,v2,l,r,_) -> forallOpt f l && f.Invoke(k2, v2) && forallOpt f r\n\n let forall f m = forallOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) m\n\n let rec map f m = \n match m with \n | MapEmpty -> empty\n | MapOne(k,v) -> MapOne(k,f v)\n | MapNode(k,v,l,r,h) -> \n let l2 = map f l \n let v2 = f v \n let r2 = map f r \n MapNode(k,v2,l2, r2,h)\n\n let rec mapiOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) m = \n match m with\n | MapEmpty -> empty\n | MapOne(k,v) -> MapOne(k, f.Invoke(k, v))\n | MapNode(k,v,l,r,h) -> \n let l2 = mapiOpt f l \n let v2 = f.Invoke(k, v) \n let r2 = mapiOpt f r \n MapNode(k,v2, l2, r2,h)\n\n let mapi f m = mapiOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) m\n\n let rec foldBackOpt (f:OptimizedClosures.FSharpFunc<_,_,_,_>) m x = \n match m with \n | MapEmpty -> x\n | MapOne(k,v) -> f.Invoke(k,v,x)\n | MapNode(k,v,l,r,_) -> \n let x = foldBackOpt f r x\n let x = f.Invoke(k,v,x)\n foldBackOpt f l x\n\n let foldBack f m x = foldBackOpt (OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f)) m x\n\n let rec foldOpt (f:OptimizedClosures.FSharpFunc<_,_,_,_>) x m = \n match m with \n | MapEmpty -> x\n | MapOne(k,v) -> f.Invoke(x,k,v)\n | MapNode(k,v,l,r,_) -> \n let x = foldOpt f x l\n let x = f.Invoke(x,k,v)\n foldOpt f x r\n\n let fold f x m = foldOpt (OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f)) x m\n\n let foldSectionOpt (comparer: IComparer<'Value>) lo hi (f:OptimizedClosures.FSharpFunc<_,_,_,_>) m x =\n let rec foldFromTo (f:OptimizedClosures.FSharpFunc<_,_,_,_>) m x = \n match m with \n | MapEmpty -> x\n | MapOne(k,v) ->\n let cLoKey = comparer.Compare(lo,k)\n let cKeyHi = comparer.Compare(k,hi)\n let x = if cLoKey <= 0 && cKeyHi <= 0 then f.Invoke(k, v, x) else x\n x\n | MapNode(k,v,l,r,_) ->\n let cLoKey = comparer.Compare(lo,k)\n let cKeyHi = comparer.Compare(k,hi)\n let x = if cLoKey < 0 then foldFromTo f l x else x\n let x = if cLoKey <= 0 && cKeyHi <= 0 then f.Invoke(k, v, x) else x\n let x = if cKeyHi < 0 then foldFromTo f r x else x\n x\n \n if comparer.Compare(lo,hi) = 1 then x else foldFromTo f m x\n\n let foldSection (comparer: IComparer<'Value>) lo hi f m x =\n foldSectionOpt comparer lo hi (OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f)) m x\n\n let toList m = \n let rec loop m acc = \n match m with \n | MapEmpty -> acc\n | MapOne(k,v) -> (k,v)::acc\n | MapNode(k,v,l,r,_) -> loop l ((k,v)::loop r acc)\n loop m []\n let toArray m = m |> toList |> Array.ofList\n let ofList comparer l = List.fold (fun acc (k,v) -> add comparer k v acc) empty l\n\n let rec mkFromEnumerator comparer acc (e : IEnumerator<_>) = \n if e.MoveNext() then \n let (x,y) = e.Current \n mkFromEnumerator comparer (add comparer x y acc) e\n else acc\n \n let ofArray comparer (arr : array<_>) =\n let mutable res = empty\n for (x,y) in arr do\n res <- add comparer x y res \n res\n\n let ofSeq comparer (c : seq<'Key * 'T>) =\n match c with \n | :? array<'Key * 'T> as xs -> ofArray comparer xs\n | :? list<'Key * 'T> as xs -> ofList comparer xs\n | _ -> \n use ie = c.GetEnumerator()\n mkFromEnumerator comparer empty ie \n\n \n let copyToArray s (arr: _[]) i =\n let j = ref i \n s |> iter (fun x y -> arr.[!j] <- KeyValuePair(x,y); j := !j + 1)\n\n\n \/\/\/ Imperative left-to-right iterators.\n []\n type MapIterator<'Key,'Value when 'Key : comparison > = \n { \/\/\/ invariant: always collapseLHS result \n mutable stack: MapTree<'Key,'Value> list; \n \/\/\/ true when MoveNext has been called \n mutable started : bool }\n\n \/\/ collapseLHS:\n \/\/ a) Always returns either [] or a list starting with MapOne.\n \/\/ b) The \"fringe\" of the set stack is unchanged. \n let rec collapseLHS stack =\n match stack with\n | [] -> []\n | MapEmpty :: rest -> collapseLHS rest\n | MapOne _ :: _ -> stack\n | (MapNode(k,v,l,r,_)) :: rest -> collapseLHS (l :: MapOne (k,v) :: r :: rest)\n \n let mkIterator s = { stack = collapseLHS [s]; started = false }\n\n let notStarted() = raise (InvalidOperationException(SR.GetString(SR.enumerationNotStarted)))\n let alreadyFinished() = raise (InvalidOperationException(SR.GetString(SR.enumerationAlreadyFinished)))\n\n let current i =\n if i.started then\n match i.stack with\n | MapOne (k,v) :: _ -> new KeyValuePair<_,_>(k,v)\n | [] -> alreadyFinished()\n | _ -> failwith \"Please report error: Map iterator, unexpected stack for current\"\n else\n notStarted()\n\n let rec moveNext i =\n if i.started then\n match i.stack with\n | MapOne _ :: rest -> i.stack <- collapseLHS rest\n not i.stack.IsEmpty\n | [] -> false\n | _ -> failwith \"Please report error: Map iterator, unexpected stack for moveNext\"\n else\n i.started <- true (* The first call to MoveNext \"starts\" the enumeration. *)\n not i.stack.IsEmpty\n\n let mkIEnumerator s = \n let i = ref (mkIterator s) \n { new IEnumerator<_> with \n member __.Current = current !i\n interface System.Collections.IEnumerator with\n member __.Current = box (current !i)\n member __.MoveNext() = moveNext !i\n member __.Reset() = i := mkIterator s\n interface System.IDisposable with \n member __.Dispose() = ()}\n\n\n\n [>)>]\n []\n []\n []\n []\n type Map<[]'Key,[]'Value when 'Key : comparison >(comparer: IComparer<'Key>, tree: MapTree<'Key,'Value>) =\n\n#if !FX_NO_BINARY_SERIALIZATION\n []\n \/\/ This type is logically immutable. This field is only mutated during deserialization. \n let mutable comparer = comparer \n \n []\n \/\/ This type is logically immutable. This field is only mutated during deserialization. \n let mutable tree = tree \n\n \/\/ This type is logically immutable. This field is only mutated during serialization and deserialization. \n \/\/\n \/\/ WARNING: The compiled name of this field may never be changed because it is part of the logical \n \/\/ WARNING: permanent serialization format for this type.\n let mutable serializedData = null \n#endif\n\n \/\/ We use .NET generics per-instantiation static fields to avoid allocating a new object for each empty\n \/\/ set (it is just a lookup into a .NET table of type-instantiation-indexed static fields).\n static let empty = \n let comparer = LanguagePrimitives.FastGenericComparer<'Key> \n new Map<'Key,'Value>(comparer,MapTree<_,_>.MapEmpty)\n\n#if !FX_NO_BINARY_SERIALIZATION\n []\n member __.OnSerializing(context: System.Runtime.Serialization.StreamingContext) =\n ignore(context)\n serializedData <- MapTree.toArray tree |> Array.map (fun (k,v) -> KeyValuePair(k,v))\n\n \/\/ Do not set this to null, since concurrent threads may also be serializing the data\n \/\/[]\n \/\/member __.OnSerialized(context: System.Runtime.Serialization.StreamingContext) =\n \/\/ serializedData <- null\n\n []\n member __.OnDeserialized(context: System.Runtime.Serialization.StreamingContext) =\n ignore(context)\n comparer <- LanguagePrimitives.FastGenericComparer<'Key>\n tree <- serializedData |> Array.map (fun (KeyValue(k,v)) -> (k,v)) |> MapTree.ofArray comparer \n serializedData <- null\n#endif\n\n static member Empty : Map<'Key,'Value> = empty\n\n static member Create(ie : IEnumerable<_>) : Map<'Key,'Value> = \n let comparer = LanguagePrimitives.FastGenericComparer<'Key> \n new Map<_,_>(comparer,MapTree.ofSeq comparer ie)\n \n static member Create() : Map<'Key,'Value> = empty\n\n new(elements : seq<_>) = \n let comparer = LanguagePrimitives.FastGenericComparer<'Key> \n new Map<_,_>(comparer,MapTree.ofSeq comparer elements)\n \n []\n member internal m.Comparer = comparer\n \/\/[]\n member internal m.Tree = tree\n member m.Add(key,value) : Map<'Key,'Value> = \n#if TRACE_SETS_AND_MAPS\n MapTree.report()\n MapTree.numAdds <- MapTree.numAdds + 1\n let size = MapTree.size m.Tree + 1\n MapTree.totalSizeOnMapAdd <- MapTree.totalSizeOnMapAdd + float size\n if size > MapTree.largestMapSize then \n MapTree.largestMapSize <- size\n MapTree.largestMapStackTrace <- System.Diagnostics.StackTrace().ToString()\n#endif\n new Map<'Key,'Value>(comparer,MapTree.add comparer key value tree)\n\n []\n member m.IsEmpty = MapTree.isEmpty tree\n member m.Item \n with get(key : 'Key) = \n#if TRACE_SETS_AND_MAPS\n MapTree.report()\n MapTree.numLookups <- MapTree.numLookups + 1\n MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree)\n#endif\n MapTree.find comparer key tree\n member m.TryPick(f) = MapTree.tryPick f tree \n member m.Exists(f) = MapTree.exists f tree \n member m.Filter(f) : Map<'Key,'Value> = new Map<'Key,'Value>(comparer ,MapTree.filter comparer f tree)\n member m.ForAll(f) = MapTree.forall f tree \n member m.Fold f acc = MapTree.foldBack f tree acc\n\n member m.FoldSection (lo:'Key) (hi:'Key) f (acc:'z) = MapTree.foldSection comparer lo hi f tree acc \n\n member m.Iterate f = MapTree.iter f tree\n\n member m.MapRange f = new Map<'Key,'b>(comparer,MapTree.map f tree)\n\n member m.Map f = new Map<'Key,'b>(comparer,MapTree.mapi f tree)\n\n member m.Partition(f) : Map<'Key,'Value> * Map<'Key,'Value> = \n let r1,r2 = MapTree.partition comparer f tree in \n new Map<'Key,'Value>(comparer,r1), new Map<'Key,'Value>(comparer,r2)\n\n member m.Count = MapTree.size tree\n\n member m.ContainsKey(key) = \n#if TRACE_SETS_AND_MAPS\n MapTree.report()\n MapTree.numLookups <- MapTree.numLookups + 1\n MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree)\n#endif\n MapTree.mem comparer key tree\n\n member m.Remove(key) : Map<'Key,'Value> = \n new Map<'Key,'Value>(comparer,MapTree.remove comparer key tree)\n\n member m.TryFind(key) = \n#if TRACE_SETS_AND_MAPS\n MapTree.report()\n MapTree.numLookups <- MapTree.numLookups + 1\n MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree)\n#endif\n MapTree.tryFind comparer key tree\n\n member m.ToList() = MapTree.toList tree\n\n member m.ToArray() = MapTree.toArray tree\n\n static member ofList(l) : Map<'Key,'Value> = \n let comparer = LanguagePrimitives.FastGenericComparer<'Key> \n new Map<_,_>(comparer,MapTree.ofList comparer l)\n \n member this.ComputeHashCode() = \n let combineHash x y = (x <<< 1) + y + 631 \n let mutable res = 0\n for (KeyValue(x,y)) in this do\n res <- combineHash res (hash x)\n res <- combineHash res (Unchecked.hash y)\n abs res\n\n override this.Equals(that) = \n match that with \n | :? Map<'Key,'Value> as that -> \n use e1 = (this :> seq<_>).GetEnumerator() \n use e2 = (that :> seq<_>).GetEnumerator() \n let rec loop () = \n let m1 = e1.MoveNext() \n let m2 = e2.MoveNext()\n (m1 = m2) && (not m1 || let e1c, e2c = e1.Current, e2.Current in ((e1c.Key = e2c.Key) && (Unchecked.equals e1c.Value e2c.Value) && loop()))\n loop()\n | _ -> false\n\n override this.GetHashCode() = this.ComputeHashCode()\n\n interface IEnumerable> with\n member __.GetEnumerator() = MapTree.mkIEnumerator tree\n\n interface System.Collections.IEnumerable with\n member __.GetEnumerator() = (MapTree.mkIEnumerator tree :> System.Collections.IEnumerator)\n\n interface IDictionary<'Key, 'Value> with \n member m.Item \n with get x = m.[x] \n and set x v = ignore(x,v); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated)))\n\n \/\/ REVIEW: this implementation could avoid copying the Values to an array \n member s.Keys = ([| for kvp in s -> kvp.Key |] :> ICollection<'Key>)\n\n \/\/ REVIEW: this implementation could avoid copying the Values to an array \n member s.Values = ([| for kvp in s -> kvp.Value |] :> ICollection<'Value>)\n\n member s.Add(k,v) = ignore(k,v); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated)))\n member s.ContainsKey(k) = s.ContainsKey(k)\n member s.TryGetValue(k,r) = if s.ContainsKey(k) then (r <- s.[k]; true) else false\n member s.Remove(k : 'Key) = ignore(k); (raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))) : bool)\n\n interface ICollection> with \n member __.Add(x) = ignore(x); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated)));\n member __.Clear() = raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated)));\n member __.Remove(x) = ignore(x); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated)));\n member s.Contains(x) = s.ContainsKey(x.Key) && Unchecked.equals s.[x.Key] x.Value\n member __.CopyTo(arr,i) = MapTree.copyToArray tree arr i\n member s.IsReadOnly = true\n member s.Count = s.Count\n\n interface System.IComparable with \n member m.CompareTo(obj: obj) = \n match obj with \n | :? Map<'Key,'Value> as m2->\n Seq.compareWith \n (fun (kvp1 : KeyValuePair<_,_>) (kvp2 : KeyValuePair<_,_>)-> \n let c = comparer.Compare(kvp1.Key,kvp2.Key) in \n if c <> 0 then c else Unchecked.compare kvp1.Value kvp2.Value)\n m m2 \n | _ -> \n invalidArg \"obj\" (SR.GetString(SR.notComparable))\n\n interface IReadOnlyCollection> with\n member s.Count = s.Count\n\n interface IReadOnlyDictionary<'Key, 'Value> with\n member s.Item with get(key) = s.[key]\n member s.Keys = seq { for kvp in s -> kvp.Key }\n member s.TryGetValue(key, value) = if s.ContainsKey(key) then (value <- s.[key]; true) else false\n member s.Values = seq { for kvp in s -> kvp.Value }\n member s.ContainsKey key = s.ContainsKey key\n\n override x.ToString() = \n match List.ofSeq (Seq.truncate 4 x) with \n | [] -> \"map []\"\n | [KeyValue h1] -> System.Text.StringBuilder().Append(\"map [\").Append(LanguagePrimitives.anyToStringShowingNull h1).Append(\"]\").ToString()\n | [KeyValue h1;KeyValue h2] -> System.Text.StringBuilder().Append(\"map [\").Append(LanguagePrimitives.anyToStringShowingNull h1).Append(\"; \").Append(LanguagePrimitives.anyToStringShowingNull h2).Append(\"]\").ToString()\n | [KeyValue h1;KeyValue h2;KeyValue h3] -> System.Text.StringBuilder().Append(\"map [\").Append(LanguagePrimitives.anyToStringShowingNull h1).Append(\"; \").Append(LanguagePrimitives.anyToStringShowingNull h2).Append(\"; \").Append(LanguagePrimitives.anyToStringShowingNull h3).Append(\"]\").ToString()\n | KeyValue h1 :: KeyValue h2 :: KeyValue h3 :: _ -> System.Text.StringBuilder().Append(\"map [\").Append(LanguagePrimitives.anyToStringShowingNull h1).Append(\"; \").Append(LanguagePrimitives.anyToStringShowingNull h2).Append(\"; \").Append(LanguagePrimitives.anyToStringShowingNull h3).Append(\"; ... ]\").ToString() \n\n and\n []\n MapDebugView<'Key,'Value when 'Key : comparison>(v: Map<'Key,'Value>) = \n\n []\n member x.Items =\n v |> Seq.truncate 10000 |> Seq.map KeyValuePairDebugFriendly |> Seq.toArray\n \n and\n []\n KeyValuePairDebugFriendly<'Key,'Value>(keyValue : KeyValuePair<'Key, 'Value>) =\n \n []\n member x.KeyValue = keyValue\n \n\nnamespace Microsoft.FSharp.Collections\n\n open System\n open System.Diagnostics\n open System.Collections.Generic\n open Microsoft.FSharp.Core\n open Microsoft.FSharp.Core.Operators\n open Microsoft.FSharp.Collections\n\n []\n []\n module Map = \n\n []\n let isEmpty (table:Map<_,_>) = table.IsEmpty\n\n []\n let add key value (table:Map<_,_>) = table.Add(key,value)\n\n []\n let find key (table:Map<_,_>) = table.[key]\n\n []\n let tryFind key (table:Map<_,_>) = table.TryFind(key)\n\n []\n let remove key (table:Map<_,_>) = table.Remove(key)\n\n []\n let containsKey key (table:Map<_,_>) = table.ContainsKey(key)\n\n []\n let iter action (table:Map<_,_>) = table.Iterate(action)\n\n []\n let tryPick chooser (table:Map<_,_>) = table.TryPick(chooser)\n\n []\n let pick chooser (table:Map<_,_>) = match tryPick chooser table with None -> raise (KeyNotFoundException()) | Some res -> res\n\n []\n let exists predicate (table:Map<_,_>) = table.Exists(predicate)\n\n []\n let filter predicate (table:Map<_,_>) = table.Filter(predicate)\n\n []\n let partition predicate (table:Map<_,_>) = table.Partition(predicate)\n\n []\n let forall predicate (table:Map<_,_>) = table.ForAll(predicate)\n\n let mapRange f (m:Map<_,_>) = m.MapRange(f)\n\n []\n let map mapping (table:Map<_,_>) = table.Map(mapping)\n\n []\n let fold<'Key,'T,'State when 'Key : comparison> folder (state:'State) (table:Map<'Key,'T>) = MapTree.fold folder state table.Tree\n\n []\n let foldBack<'Key,'T,'State when 'Key : comparison> folder (table:Map<'Key,'T>) (state:'State) = MapTree.foldBack folder table.Tree state\n \n []\n let toSeq (table:Map<_,_>) = table |> Seq.map (fun kvp -> kvp.Key, kvp.Value)\n\n []\n let findKey predicate (table : Map<_,_>) = table |> toSeq |> Seq.pick (fun (k,v) -> if predicate k v then Some(k) else None)\n\n []\n let tryFindKey predicate (table : Map<_,_>) = table |> toSeq |> Seq.tryPick (fun (k,v) -> if predicate k v then Some(k) else None)\n\n []\n let ofList (elements: ('Key * 'Value) list) = Map<_,_>.ofList(elements)\n\n []\n let ofSeq elements = Map<_,_>.Create(elements)\n\n [