error about tabs function in rmarkdown(in MASS library) - r-markdown

what should i do with this error?it was correct in my R file but cant make Rmark down because of this error
Error in loglin(data, margins, start = start, fit = fitted, param = param, :
'margin' must contain names or numbers corresponding to 'table'
Calls: ... eval -> loglm -> loglm1 -> loglm1.default -> loglin
Execution halted

Related

Core.Command.run : API changed between v0.14 and v0.15?

The following code that was compiling successfully with Core v0.14 (ocaml 4.10), but fails with v0.15 (ocaml 4.11).
open Core;;
let command = Command.basic ~summary:"essai" (
let open Command.Let_syntax in
let%map_open s = anon(sequence ("n" %: int)) in
fun () ->
List.iter s ~f:(fun x -> Printf.printf "n = %d\n" x ) ;
)
let () = Command.run ~version:"0.0" ~build_info:"RWO" command;;
The error (with 4.11) :
File "cli.ml", line 10, characters 9-20:
10 | let () = Command.run ~version:"0.0" ~build_info:"RWO" command;;
^^^^^^^^^^^
Error (alert deprecated): Core.Command.run
[since 2021-03] Use [Command_unix]
File "cli.ml", line 10, characters 9-20:
10 | let () = Command.run ~version:"0.0" ~build_info:"RWO" command;;
^^^^^^^^^^^
Error: This expression has type [ `Use_Command_unix ]
This is not a function; it cannot be applied.
The documentation of Core.Command.run states that it is obsolete - but I fail to find how to replace it.
I think you're looking for Command_unix as indicated by the message you received. Documentation link for Command_unix.run.
The core library has been restructured in version 0.15: Unix-specific modules and functions have been moved to the core_unix library in order to make the main core library more portable (or at least javascript compatible).
The function Command_unix.run in core_unix library is exactly the same as the Command.run function in previous versions of the core library.

How to satisfy module type including polymorphic set

I am trying to create a module that exposes a set without exposing the type of the elements in the set. Here is a simplified version:
open Core
module type M_t = sig
module Id : Comparator.S
val set : (Id.t, Id.comparator_witness) Set_intf.Tree.t
end
module M : M_t = struct
module Id = Int
module S = Set.Make (Id)
let set = S.empty
end
With this signature, client applications could use the M_t signature and not know that under the hood, set contains ints. Not only is my implementation not particularly idiomatic, but it doesn't compile:
❯ dune build
File "hello_world.ml", lines 9-14, characters 17-3:
9 | .................struct
10 | module Id = Int
11 | module S = Set.Make (Id)
12 |
13 | let set = S.empty
14 | end
Error: Signature mismatch:
...
Values do not match:
val set : S.t
is not included in
val set : (int, Id.comparator_witness) Set_intf.Tree.t
File "hello_world.ml", line 6, characters 2-57: Expected declaration
File "hello_world.ml", line 13, characters 6-9: Actual declaration
I have found everal similar questions but I haven't succeeded in transferring the answers to my setting, so I apologize if this is a duplicate.
The solution I could come up with is the following:
open Core
module type M_t = sig
module Id : Comparator.S
module S : Set.S with type Elt.t = Id.t
val set : S.t
end
module M : M_t = struct
module Id = Int
module S = Set.Make (Id)
let set = S.empty
end
The thing is I couldn't find a way to force Elt.comparator_witness to be equal to Id.comparator_witness and this is the closest working solution I got to correspond to your initial problem (I'm not a Core user).

Catch multiple Exception with Lenses

I am using Lens with Amazonka to deal with errors but I struggle to deal with errors:
doSignup e p = (AWS.send $ AWS.signUp "secret" e p)
$> Right ()
& catching_ AWS._UsernameExistsException (return $ Left AlreadyExistingEmail)
& catching_ AWS._InvalidPasswordException (return $ Left WeakPassword)
& catching AWS._SertviceError (return . UnknownSignUpError)
data SignUpError where
AlreadyExistingEmail :: SignUpError
NotAnEmail :: SignUpError
WeakPassword :: SignUpError
UnknownSignUpError :: forall a. Show a => a -> SignUpError
I struggle to have a consistent catching behavior, when a _UsernameExistsException is thrown I got a Left WeakPassword.
It becomes weirder because it works when I drop the WeakPassword line.
While I get the right error (keeping only the last line):
expected: Right ()
but got: Left UnknownSignUpError ServiceError' {_serviceAbbrev = Abbrev "CognitoIdentityProvider", _serviceStatus = Status {statusCode = 400, statusMessage = "Bad Request"}, _serviceHeaders = [("Date","Tue, 06 Oct 2020 05:38:56 GMT"),("Content-Type","application/x-amz-json-1.1"),("Content-Length","96"),("Connection","keep-alive"),("x-amzn-RequestId","b09210a3-41ed-46ee-af4f-46db58b98695"),("x-amzn-ErrorType","UsernameExistsException:"),("x-amzn-ErrorMessage","An account with the given email already exists.")], _serviceCode = ErrorCode "UsernameExists", _serviceMessage = Just (ErrorMessage "An account with the given email already exists."), _serviceRequestId = Just (RequestId "b09210a3-41ed-46ee-af4f-46db58b98695")}
I have tried to use catches but handler requires Typeable Lenses which is not the case.
How can I have a "pattern matching-like" way to deal with exceptions? Thanks in advance.
In fact Control.Lens.catching was used instead of Network.AWS.Prelude.catching which was messing up the exception handling.

Yesod Persistent using Aeson to parse UTCTime into record

I have my model from models.persistentmodels
...
Thing
title Text
price Int
kosher Bool
optionalstuff [Text] Maybe
createdat UTCTime
updatedat UTCTime
deriving Show
...
It contains two time fields, which are UTCTime.
I am receiving via AJAX what is almost a Thing, in JSON. But the user JSON should not have createdat and updatedat or kosher. So we need to fill them in.
postNewEventR = do
inputjson <- requireCheckJsonBody :: Handler Value
...
-- get rawstringofthings from inputjson
...
let objectsMissingSomeFields = case (decode (BL.fromStrict $ TE.encodeUtf8 rawstringofthings) :: Maybe [Object]) of
Nothing -> error "Failed to get a list of raw objects."
Just x -> x
now <- liftIO getCurrentTime
-- Solution needs to go here:
let objectsWithAllFields = objectsMissingSomeFields
-- We hope to be done
let things = case (eitherDecode $ encode objectsWithAllFields) :: Either String [Thing] of
Left err -> error $ "Failed to get things because: " <> err
Right xs -> xs
The error "Failed to get things" comes here because the JSON objects we parsed are missing fields that are needed in the model.
Solution
let objectsWithAllFields = Import.map (tackOnNeccessaryThingFields now True) objectsMissingSomeFields
So we take the current object and tack on the missing fields e.g. kosher and createdat.
But there is some strange difference in the way UTCTime is read vs aeson's way to parse UTCTime. So when I print UTCTime in to a Aeson String, I needed to print out the UTCTime into the format that it is expecting later:
tackOnNeccessaryThingFields :: UTCTime -> Bool -> Object -> Object
tackOnNeccessaryThingFields t b hm = G.fromList $ (G.toList hm) <> [
("createdat", String (pack $ formatTime defaultTimeLocale "%FT%T%QZ" t)),
("updatedat", String (pack $ formatTime defaultTimeLocale "%FT%T%QZ" t)),
("kosher", Bool b)
]
tackOnNeccessaryThingFields _ _ _ = error "This isn't an object."
After this fix, the object has all the fields needed to make the record, so the code gives [Thing].
And also the code runs without runtime error, instead of failing to parse the tshow t as UTCTime.
Note:
This aeson github issue about this problem seems to be closed but it seems to be not any more permissive: https://github.com/bos/aeson/issues/197
Thanks to Artyom:
https://artyom.me/aeson#records-and-json-generics
Thanks to Pbrisbin:
https://pbrisbin.com/posts/writing_json_apis_with_yesod/
Thanks to Snoyman:
For everything

Operating on an F# List of Union Types

This is a continuation of my question at F# List of Union Types. Thanks to the helpful feedback, I was able to create a list of Reports, with Report being either Detail or Summary. Here's the data definition once more:
module Data
type Section = { Header: string;
Lines: string list;
Total: string }
type Detail = { State: string;
Divisions: string list;
Sections: Section list }
type Summary = { State: string;
Office: string;
Sections: Section list }
type Report = Detail of Detail | Summary of Summary
Now that I've got the list of Reports in a variable called reports, I want to iterate over those Report objects and perform operations based on each one. The operations are the same except for the cases of dealing with either Detail.Divisions or Summary.Office. Obviously, I have to handle those differently. But I don't want to duplicate all the code for handling the similar State and Sections of each.
My first (working) idea is something like the following:
for report in reports do
let mutable isDetail = false
let mutable isSummary = false
match report with
| Detail _ -> isDetail <- true
| Summary _ -> isSummary <- true
...
This will give me a way to know when to handle Detail.Divisions rather than Summary.Office. But it doesn't give me an object to work with. I'm still stuck with report, not knowing which it is, Detail or Summary, and also unable to access the attributes. I'd like to convert report to the appropriate Detail or Summary and then use the same code to process either case, with the exception of Detail.Divisions and Summary.Office. Is there a way to do this?
Thanks.
You could do something like this:
for report in reports do
match report with
| Detail { State = s; Sections = l }
| Summary { State = s; Sections = l } ->
// common processing for state and sections (using bound identifiers s and l)
match report with
| Detail { Divisions = l } ->
// unique processing for divisions
| Summary { Office = o } ->
// unique processing for office
The answer by #kvb is probably the approach I would use if I had the data structure you described. However, I think it would make sense to think whether the data types you have are the best possible representation.
The fact that both Detail and Summary share two of the properties (State and Sections) perhaps implies that there is some common part of a Report that is shared regardless of the kind of report (and the report can either add Divisions if it is detailed or just Office if if is summary).
Something like that would be better expressed using the following (Section stays the same, so I did not include it in the snippet):
type ReportInformation =
| Divisions of string list
| Office of string
type Report =
{ State : string;
Sections : Section list
Information : ReportInformation }
If you use this style, you can just access report.State and report.Sections (to do the common part of the processing) and then you can match on report.Information to do the varying part of the processing.
EDIT - In answer to Jeff's comment - if the data structure is already fixed, but the view has changed, you can use F# active patterns to write "adaptor" that provides access to the old data structure using the view that I described above:
let (|Report|) = function
| Detail dt -> dt.State, dt.Sections
| Summary st -> st.State, st.Sections
let (|Divisions|Office|) = function
| Detail dt -> Divisions dt.Divisions
| Summary st -> Office st.Office
The first active pattern always succeeds and extracts the common part. The second allows you to distinguish between the two cases. Then you can write:
let processReport report =
let (Report(state, sections)) = report
// Common processing
match report wiht
| Divisions divs -> // Divisions-specific code
| Office ofc -> // Offices-specific code
This is actually an excellent example of how F# active patterns provide an abstraction that allows you to hide implementation details.
kvb's answer is good, and probably what I would use. But the way you've expressed your problem sounds like you want classic inheritance.
type ReportPart(state, sections) =
member val State = state
member val Sections = sections
type Detail(state, sections, divisions) =
inherit ReportPart(state, sections)
member val Divisions = divisions
type Summary(state, sections, office) =
inherit ReportPart(state, sections)
member val Office = office
Then you can do precisely what you expect:
for report in reports do
match report with
| :? Detail as detail -> //use detail.Divisions
| :? Summary as summary -> //use summary.Office
//use common properties
You can pattern match on the Detail or Summary record in each of the union cases when you match and handle the Divisions or Office value with a separate function e.g.
let blah =
for report in reports do
let out = match report with
| Detail({ State = state; Divisions = divisions; Sections = sections } as d) ->
Detail({ d with Divisions = (handleDivisions divisions) })
| Summary({ State = state; Office = office; Sections = sections } as s) ->
Summary( { s with Office = handleOffice office })
//process out
You can refactor the code to have a utility function for each common field and use nested pattern matching:
let handleReports reports =
reports |> List.iter (function
| Detail {State = s; Sections = ss; Divisions = ds} ->
handleState s
handleSections ss
handleDivisions ds
| Summary {State = s; Sections = ss; Office = o} ->
handleState s
handleSections ss
handleOffice o)
You can also filter Detail and Summary to process them separately in different functions:
let getDetails reports =
List.choose (function Detail d -> Some d | _ -> None) reports
let getSummaries reports =
List.choose (function Summary s -> Some s | _ -> None) reports