How do you create a link with query string parameters:
/path/to/view?param=358&name=Something+with+spaces
in Lift? I know you can simply write it, I am looking for a wise approach, which encode spaces and other special characters. For example:
Link("path/to/view").param("param", 358).param("name", "Something with spaces")
Thanks in advance,
Etam.
There is appendParams method in net.liftweb.util.HttpHelpers trait:
import net.liftweb._
import util.Helpers._
val url = appendParams("/path/to/view",
("param" -> "358") ::
("name" -> "Something with spaces") :: Nil)
Reply from Scala REPL:
url: String = /path/to/view?param=358&name=Something+with+spaces
As you can see, it gets URL as a String, Seq of param tuples and finally returns String.
Related
Based on this post and thanks to the #glennsl iam getting some where.
First if someone has a link that i could learn about the parses i will be very glad.
page : Url.Url -> String
page url =
case (Parser.parse (Parser.query (Query.string "name")) url) of
Nothing -> "My query string: " ++ (Maybe.withDefault "empty" url.query)
Just v -> case v of
Just v2 -> "Finnaly a name"
Nothing -> "????"
As far i can understand the expression Parser.parse (Parser.query (Query.string "name")) urlis returning a Maybe (Maybe String) I see this as the parser could return something, and if do it could be an string, is that right?
In my mind if i have the parameter name in my url then my first Just would be executed and then i can get the name.
But no mather what i put on my url it always go the the first Nothing
The result i got
The problem is that you're not parsing the path part of the URL, which is what Url.Parser is primarily for. You have to match the path exactly.
Here's a parser that will match your URL:
s "src" </> s "Main.elm" <?> (Query.string "name")
Note also that parsing the query string is optional, meaning this will also match your URL:
s "src" </> s "Main.elm"
But as long as you include a query param parser, that also has to match.
If all you care about is the query parameter, you'll have to parse the query string specifically, by either writing your own function to do so, or using a library like qs for example:
QS.parse
QS.config
"?a=1&b=x"
== Dict.fromList
[ ( "a", One <| Number 1 )
, ( "b", One <| Str "x" )
]
Hi newbie here and I am trying to master recursive functions in Erlang. This function looks like it should work, but I cannot understand why it does not. I am trying to create a function that will take N and a string and will print out to stdout the string the number of times.
My code:
-module(print_out_n_times).
-export([print_it/2).
print_it(0, _) ->
"";
print_it(N, string) ->
io:fwrite(string),
print_it(N - 1, string).
The error I get is:
** exception error: no function clause matching print_it(5, "hello')
How can I make this work ?
Variables in Erlang start with a capital letter. string is an atom, not a variable named "string". When you define a function print_it(N, string), it can be called with any value for the first argument and only the atom string as the second. Your code should work if you replace string with String:
print_it(N, String) ->
io:fwrite(String),
print_it(N - 1, String).
I am trying to understand elm's type signatures. What does this function return exactly? It appears to be a function that accepts no arguments and returns ...
route : Parser (Page -> a) a
As a learning exercise for myself I'm going to try to answer this. Others will chip in if I get something wrong.
I'm sure you are used to something like
type Person = Adult String | Child String Age
Child is a type that takes two parameters. Parser is the same. But it's definition is pretty formidable
type Parser a b =
Parser (State a -> List (State b))
type alias State value =
{ visited : List String
, unvisited : List String
, params : Dict String String
, value : value
}
That said, you see how Parser is ultimately a wrapper around a function from a State to a list of States. Ultimately it is going to be passed a List of 'unvisited' strings or params; it will progressively 'visit' each one and the result will be combined into the final 'value'.
Next, note that while Parser takes two type parameters - a, b - parseHash is defined
parseHash : Parser (a -> a) a -> Location -> Maybe a
So, your original
route : Parser (Page -> a) a
is going to have to be
route : Parser (Page -> Page) Page
to type check.
To return to your original question, therefore, route is a Parser (which is a very general object) that encapsulates instructions on how to go from one Page to another, and can be used - via parseHash - to tell you what Page to go to next, and that is of course what you would expect from a router.
Hope this gets you started
I'm trying to learn Haskell, specifically Snap, Blaze HTML5 and Persist. I would like to take every row in a table, select a single column from it, and then concatenate the values into a single string.
I've previously worked with C#'s LINQ quite extensively and under Entity Framework I could do it like this:
String.Join(", ", dbContext.People.Select(p => p.Name));
This would compile down to SELECT Name FROM People, with C# then concatenating those rows into a string with ", " in between.
To try and get the concatenation part right, I put this together, which seems to work:
intercalate ", " $ map show [1..10]
(it counts 1-9, concatenates with ", " in between the items)
However, I can't get this to work with Database.Persist.Sqlite. I'm not sure I quite understand the syntax here in Haskell. To contact the DB and retrieve the rows, I have to call: (as far as I understand)
runSqlite "TestDB" $ selectList ([] :: [Filter Person]) [] 0 0
The problem is that I'm not sure how to get the list out of runSqlite. runSqlite doesn't return the type I'm after, so I can't use the return value of runSqlite. How would I do this?
Thank you for reading.
To clarify:
Snap requires that I define a function to return the HTML I wish to send back to the client making the HTTP request. This means that:
page = runSqlite "TestDB" $ do
{pull data from the DB)
Is no-go as I can't return the data via the runSqlite call, and as far as I know I can't have a variable in the page function which is set within the runSqlite do block. All examples I can find just write to IO in the runSqlite do block, which is not what needs to be done here.
The type of runSqlite is:
runSqlite :: (MonadBaseControl IO m, MonadIO m) => Text -> SqlPersistT (NoLoggingT (ResourceT m)) a -> m a
And the type of selectList is:
[Filter val] -> [SelectOpt val] -> m [Entity val]
So, you can actually, use the nice do notation of Monad, to extract it:
runSqlite "TestDB" $ do
myData <- selectList ([] :: [Filter Person]) [] 0 0
-- Now do stuff with myData
The <- thing gets the list out of the monad. I would suggest you to go through this chapter to get an idea of how Persistent is used. Note that the chapters in the book assume a basic Haskell understanding.
The issue is that I want to use the selectList outside of runSqlite as
I need to pass the concatenated string to a Blaze HTML5 tag builder:
body $ do p (concatenated list...)
For this case, just define a function that does your intended task:
myLogic :: [SqlColumnData] -> String -- Note that SqlColumnData is hypothetical
myLogic xs = undefined
And then just call them appropriately in your main function:
main = runSqlite "TestDB" $ do
myData <- selectList ([] :: [Filter Person]) [] 0 0
let string = myLogic myData
-- do any other remaining stuff
It hadn't clicked that if I didn't use a do block with runSqlite, the result of the last call in the statement was the return value of the statement - this makes total sense.
https://gist.github.com/egonSchiele/5400694
In this example (not mine) the readPosts function does exactly what I'm after and cleared up some Haskell syntax confusion.
Thank you for your help #Sibi.
I'm trying to send parameters with an URL, like http://localhost:3000/register?name=Chris&job=typist. I can send that all at once as a string with httpc:request, but I can't find a function to put the query parameters in the URL(given a dictionary).
Is there another HTTP library I should be using that has this capability?
I'd like to give it a root URL with a hash/dictonary/map (in json {"a" : "b", "c" : "d"}) that then appends it correctly to the end of the url. For example, given "www.facebook.com" and [{"a", "b"}, {"c", "d"}] would give "www.facebook.com?a=b&c=d".
Here is a similar question for Ruby: Ruby: How to turn a hash into HTTP parameters?
I'm not sure exactly what you mean by "hash", but if you'd like to construct a query string from tuples, that is a fairly straitforward task.
I'm not familiar with a method in httpc to provide the functionality you desire. You can write a wrapper around request/4 very easily, similar to this.
(This program is hastily constructed to give you the idea, forgive any errors).
request(Method, Domain, {Path, Query, Fragment}, HTTPOptions, Options) ->
QueryString = lists:flatten([Path,
case Query of "" -> ""; _ -> [$? | Query] end,
case Fragment of "" -> ""; _ -> [$# | Fragment] end]);
Request = concat(Domain, QueryString);
httpc:request(Method, {Request, []}, HTTPOptions, Options).
You can invoke it like
request(get, "http://www.example.com", {"/path", "", "bar?baz}, HTTPOptions, Options)
try this function
test(URL,QP)->URL++"?"++loop(QP,[]).
loop([{A,B}],QP)->QP++A++"="++B;
loop([{A,B}|T],QP)->loop(T,QP++A++"="++B++"&").
call test("www.facebook.com",[{"a", "b"}, {"c", "d"}]).
it returns "www.facebook.com?a=b&c=d".