my using Rosencrantz to Api Server.
but
DELETE method set is run compile to error
not working?
i Document copy and path , message, http method to Edited only
nim versin : 0.19.6
rosencrantz : 0.3.8
import
asyncdispatch,
asynchttpserver,
strutils,
rosencrantz
let handler = get[
path("/api/users")[
ok("Get Users")
] ~
pathChunk("/api/users")[
intSegment(proc(id: int): auto =
ok("Get User by " & intToStr(id) & "!")
)
]
] ~ delete[
pathChunk("/api/users")[
intSegment(proc(id: int): auto =
ok("Delete User by " & intToStr(id) & "!")
)
]
]
let server = newAsyncHttpServer()
waitFor server.serve(Port(8080), handler)
Error Message
:
:
... api.nim(16, 3) Error: type mismatch: got <Handler, proc (x: var seq[Handler], i: Natural){.noSideEffect, gcsafe, locks: 0.}>
... but expected one of:
... proc `~`(h1, h2: Handler): Handler
... first type mismatch at position: 2
... required type: Handler
... but expression 'delete' is of type: proc (x: var seq[Handler], i: Natural){.noSideEffect, gcsafe, locks: 0.}
... expression: (get ->
... (path("/api/users") -> ok("Get Users")) ~
... (pathChunk("/api/users") ->
... intSegment(proc (id: int): auto = result = ok(
... `&`("Get User by ", intToStr(id, 1), "!"))))) ~ delete
Yo have to qualify the delete method:
] ~ rosencranz.delete[
pathChunk("/api/users")[
intSegment(proc(id: int): auto =
ok("Delete User by " & intToStr(id) & "!")
)
]
Or you will call the system.delete.
Related
I am relatively new in groovy/java, and struggle with a simple task, to process all files following a given pattern in a given directory.
I tried this below, but as soon as try to use a variable instead of a fixed string for the directory of a fileset, it tells me that it doesn't find the directory - although it found it when entered as literal string.
My question, how to fix the error in line 34/32?
My code:
import groovy.ant.AntBuilder
String hotinfoNumber = new String('5152');
String unzipSpec = new String('*.zip')
String hotinfoDownloadDir = new String('.\\hotinfo_5125')
String[] hotinfoUnzips
hotinfoUnzips = [ '*.zip' , 'H*.zip']
println ('GO, hotinfoNumber=' + hotinfoNumber + ', unzipSpec=' + unzipSpec + ', hotinfoDownloadDir=' + hotinfoDownloadDir + ', hotinfoUnzips=' + hotinfoUnzips)
AntBuilder ant = new AntBuilder();
println 'c+c'
ant.fileScanner {
fileset(dir: '.\\hotinfo_5152', includes: '*.zip')
}.each { File f ->
println "c+c - Found file ${f.path}"
}
println ("c+v")
hotinfoUnzips.each { unzipFilespec ->
println 'c+v-unzipFilespec=' + unzipFilespec
ant.fileScanner {
fileset(dir: '.\\hotinfo_5152', includes: unzipFilespec.toString())
}.each { File f ->
println "c+v - Found file ${f.path}"
}
}
println ("v+v")
hotinfoUnzips.each { unzipFilespec -> // line 32
println 'v+v-unzipFilespec=' + unzipFilespec
ant.fileScanner { // line 34
fileset(dir: hotinfoDownloadDir.toString(), includes: unzipSpec.toString())
}.each { File f ->
println "v+v - unzips-Found file ${f.path}"
}
}
and the result:
c+v - Found file G:\TESTS_SAMPLES\GROOVY\test_misc\hotinfo_5152\HotInfo_5125.zip
c+v-unzipFilespec=H*.zip
c+v - Found file G:\TESTS_SAMPLES\GROOVY\test_misc\hotinfo_5152\HotInfo_5125.zip
v+v
v+v-unzipFilespec=*.zip
Caught: G:\TESTS_SAMPLES\GROOVY\test_misc\hotinfo_5125 does not exist.
G:\TESTS_SAMPLES\GROOVY\test_misc\hotinfo_5125 does not exist.
at org.apache.tools.ant.types.AbstractFileSet.getDirectoryScanner(AbstractFileSet.java:512)
at DirAndFile2$_run_closure4.doCall(DirAndFile2.groovy:34)
at DirAndFile2.run(DirAndFile2.groovy:32)
Disconnected from the target VM, address: '127.0.0.1:57397', transport: 'socket'
Process finished with exit code 1
Any hints and suggestions are highly appreciated.
Use new String('string') or directly 'string' are equivalent.
The problem in your case is the typo in the hotinfoDownloadDir definition.
Note that you change the order of the last two numbers in new String('.\\hotinfo_5125') definition compared with the '.\\hotinfo_5152'.
new String('.\\hotinfo_5125') must be new String('.\\hotinfo_5152'), if you change this, your code will work.
I'm looking to bind data through my SQL string:
#[derive(Debug, sqlx::FromRow)]
struct CurrencyExchangeRateBdd {
currency_exchange_rate_id: i64,
from_currency: String,
to_currency: String,
rate_date: Date,
rate: f64,
creation_date: OffsetDateTime,
rate_down: Option<f64>,
rate_up: Option<f64>,
}
async fn get_data(date: &String) -> Result<Vec<CurrencyExchangeRateBdd>, sqlx::Error> {
let pool = PgPoolOptions::new()
.max_connections(5)
.connect("postgres")
.await?;
let row = sqlx::query_as!(
CurrencyExchangeRateBdd,
"SELECT * FROM currency_exchange_rate WHERE rate_date = ?"
)
.bind(date)
.fetch_all(&pool)
.await;
row
}
I get this error:
error: error returned from database: syntax error at end of input
--> src/main.rs:50:15
|
50 | let row = sqlx::query_as!(CurrencyExchangeRateBdd,"SELECT * FROM currency_exchange_rate WHERE rate_date = ?")
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
I have tried:
let row = sqlx::query_as!(CurrencyExchangeRateBdd, "SELECT * FROM currency_exchange_rate WHERE rate_date = ?", date)
Or with a $ or # rather than ?. I have the same as the documentation.
How I can fix this error?
The correct syntax is:
let row = sqlx::query_as!(
CurrencyExchangeRateBdd,
"SELECT * FROM currency_exchange_rate WHERE rate_date = $1"
)
Postgres uses identifiers $1, $2, etc. to indicate parameters in a prepared statement. See documentation.
The very first example in sqlx's README also shows proper usage of parameters with Postgres.
Im using EmberJS and im trying to get data from the backend using websocket (socket.io) so i've set this Application Route
App.ApplicationRoute = Ember.Route.extend(
setupController: (controller, data) ->
store = #get 'store'
socket = io.connect "http://localhost:4000/orders" ## Line 4
socket.on "new_order", (order) ->
store.load(App.Order, order)
socket.on "new_billing", (bill) ->
store.load(App.Bill, bill)
socket.on "connected", ->
console.log "Ready"
model: ->
return { title: "Ordenes" }
actions:
markAsDone: (type, type_id) ->
# Send value to backend
socket.emit "confirm_" + type, ## Line 16
id: type_id
# Find record by id
if type == "order"
record = App.Order.find(type_id)
transition = "orders"
else if type == "bill"
record = App.Bill.find(type_id)
transition = "bills"
# Delete from store
record.then( (r) ->
r.deleteRecord()
)
# Display list of record type
#transitionTo(transition)
)
on line 4 the connection is being set and object are being fetched when i hit "/", but after i enter a route "/orders" object are not being fetched anymore, and on line 16 in the code above, i cant use the socket variable
Uncaught ReferenceError: socket is not defined
Is there a better way to manage this ?
so the correct way to use a reusable socket is setting it inside the Store
App.Store = DS.Store.extend(
revision: 12
adapter: adapter
socket: io.connect "http://localhost:4000/orders"
)
so then i can access to it inside any part of the code using
socket = #get 'store.socket'
socket is out of scope once you've hit the markAsDone method, you can set a reference to it on the controller and retrieve it later (pardon my botched coffeescript)
App.ApplicationRoute = Ember.Route.extend(
setupController: (controller, data) ->
store = #get 'store'
socket = io.connect "http://localhost:4000/orders" ## Line 4
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
controller.set 'socket', socket
socket.on "new_order", (order) ->
store.load(App.Order, order)
socket.on "new_billing", (bill) ->
store.load(App.Bill, bill)
socket.on "connected", ->
console.log "Ready"
model: ->
return { title: "Ordenes" }
actions:
markAsDone: (type, type_id) ->
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
socket = #get 'controller.socket'
# Send value to backend
socket.emit "confirm_" + type, ## Line 16
id: type_id
# Find record by id
if type == "order"
record = App.Order.find(type_id)
transition = "orders"
else if type == "bill"
record = App.Bill.find(type_id)
transition = "bills"
# Delete from store
record.then( (r) ->
r.deleteRecord()
)
# Display list of record type
#transitionTo(transition)
)
I have a tsv file in the form of "key \t value", and I need to read into a map. Currently i do it like this:
referenceFile.eachLine { line ->
def (name, reference) = line.split(/\t/)
referencesMap[name.toLowerCase()] = reference
}
Is there a shorter/nicer way to do it?
It's already quite short. Two answers I can think of:
First one avoids the creation of a temporary map object:
referenceFile.inject([:]) { map, line ->
def (name, reference) = line.split(/\t/)
map[name.toLowerCase()] = reference
map
}
Second one is more functional:
referenceFile.collect { it.split(/\t/) }.inject([:]) { map, val -> map[val[0].toLowerCase()] = val[1]; map }
The only other way I can think of doing it would be with an Iterator like you'd find in Commons IO:
#Grab( 'commons-io:commons-io:2.4' )
import org.apache.commons.io.FileUtils
referencesMap = FileUtils.lineIterator( referenceFile, 'UTF-8' )
.collectEntries { line ->
line.tokenize( '\t' ).with { k, v ->
[ (k.toLowerCase()): v ]
}
}
Or with a CSV parser:
#Grab('com.xlson.groovycsv:groovycsv:1.0')
import static com.xlson.groovycsv.CsvParser.parseCsv
referencesMap = referenceFile.withReader { r ->
parseCsv( [ separator:'\t', readFirstLine:true ], r ).collectEntries {
[ (it[ 0 ].toLowerCase()): it[ 1 ] ]
}
}
But neither of them are shorter, and not necessarily nicer either...
Though I prefer option 2 as it can handle cases such as:
"key\twith\ttabs"\tvalue
As it deals with quoted strings
This is the comment tim_yates added to melix's answer, and I think it's the shortest/clearest answer:
referenceFile.collect { it.tokenize( '\t' ) }.collectEntries { k, v -> [ k.toLowerCase(), v ] }
I want to find an one-line function to implement substringAfter in scala, which is the same as commons-lang's StringUtils.substringAfter().
def substringAfter(str:String, key:String) = ...
Some tests:
substringAfter("1234512345", "23") // ==> 4512345
substringAfter("1234512345", "a") // ==> ""
substringAfter("1234512345", "") // ==> 1234512345
substringAfter("", "23") // ==> ""
No need to consider null str here.
For now, I have such a solution:
def substringAfter(s:String,k:String) = {
s.indexOf(k) match {
case -1 => ""
case i => s.substring(i+k.length)
}
}
How to get an one-line one?
def substringAfter(s:String,k:String) = { s.indexOf(k) match { case -1 => ""; case i => s.substring(i+k.length) } }
Less efficient, but slightly shorter:
def substringAfter(s: String, k: String) =
s.tails.find(_.startsWith(k)).map(_.drop(k.length)).getOrElse("")
or if regexes are your thing:
def substringAfter(s: String, k: String) =
(".*?(?:\Q"+k+"\E)(.*)").r.unapplySeq(s).flatten.mkString
Your version rewritten to use a Map with default function:
def substringAfter(s: String, k: String) =
Map(-1 -> "").withDefault(i => s.substring(i + k.length))(s.indexOf(k))
My friend gave me a solution:
def substringAfter(str:String, key:String) =
str.stripPrefix(str.take(str.indexOf(key))+key)