compiler error using tryRecv - channel

I have the following Nim program:
import threadpool
var channel: TChannel[string]
proc consumer(channel: TChannel[string]) =
let (flag,msg) = tryRecv(channel)
if flag:
echo msg
channel.open()
spawn consumer(channel)
channel.send("hello")
channel.close()
sync()
When I try to compile it, it gives me this error message:
testchannels.nim(6, 27) Error: type mismatch: got (TChannel[system.string])
but expected one of:
system.tryRecv(c: var TChannel[tryRecv.TMsg])
I don't understand what the error message is trying to tell me...

Ahh, I think I got it now!
The important part of the error message was the var in system.tryRecv(c: var TChannel[tryRecv.TMsg]): tryRecv expects the channel variable to be mutable, which it wasn't in the above code.
The solution is to remove the parameter from the consume proc:
import threadpool
var channel: TChannel[string]
proc consumer() {.gcsafe.} =
if peek[string](channel) != -1:
echo recv(channel)
channel.open()
spawn consumer()
channel.send("hello")
channel.close()
sync()

Related

Gatling feeder/parameter issue - Exception in thread "main" java.lang.UnsupportedOperationException

I just involved the new project for API test for our service by using Gatling. At this point, I want to search query, below is the code:
def chnSendToRender(testData: FeederBuilderBase[String]): ChainBuilder = {
feed(testData)
exec(api.AdvanceSearch.searchAsset(s"{\"all\":[{\"all:aggregate:text\":{\"contains\":\"#{edlAssetId}_Rendered\"}}]}", "#{authToken}")
.check(status.is(200).saveAs("searchStatus"))
.check(jsonPath("$..asset:id").findAll.optional.saveAs("renderedAssetList"))
)
.doIf(session => session("searchStatus").as[Int] == 200) {
exec { session =>
printConsoleLog("Rendered Asset ID List: " + session("renderedAssetList").as[String], "INFO")
session
}
}
}
I declared the feeder already in the simulation scala file:
class GVRERenderEditor_new extends Simulation {
private val edlToRender = csv("data/render/edl_asset_ids.csv").queue
private val chnPostRender = components.notifications.notice.JobsPolling_new.chnSendToRender(edlToRender)
private val scnSendEDLForRender = scenario("Search Post Render")
.exitBlockOnFail(exec(preSimAuth))
.exec(chnPostRender)
setUp(
scnSendEDLForRender.inject(atOnceUsers(1)).protocols(httpProtocol)
)
.maxDuration(sessionDuration.seconds)
.assertions(global.successfulRequests.percent.is(100))
}
But Gatling test failed to run, showing this error: Exception in thread "main" java.lang.UnsupportedOperationException: There were no requests sent during the simulation, reports won't be generated
If I hardcode the #{edlAssetId} (put the real edlAssetId in that query), I will get result. I think I passed the parameter wrongly in this case. I've tried to print the output in console log but no luck. What's wrong with this code? I would appreciate your help. Thanks!
feed(testData)
exec(api.AdvanceSearch.searchAsset(s"{\"all\":[{\"all:aggregate:text\":{\"contains\":\"#{edlAssetId}_Rendered\"}}]}", "#{authToken}")
.check(status.is(200).saveAs("searchStatus"))
.check(jsonPath("$..asset:id").findAll.optional.saveAs("renderedAssetList"))
)
You're missing a . (dot) before the exec to attach it to the feed.
As a result, your method is returning the last instruction, ie the exec only.

How can I know the command used? - Discord.py

I am trying to make a errorhandling for my Discord.py, how do I know what command was used for the error to pop up?
#bot.event
async def on_command_error(ctx, error):
print("error: ",error)
if search("not found", str(error)):
c_f = random.choice([f"`{command used}` was not found, silly.", "Ehm.. Since when do we have `{command used}`?", "I don't know what `{command used}` is?"])
embed=discord.Embed(title=c_f, description=f"Please use existing commands. {ctx.author.mention}", color=error_color)
embed.timestamp = datetime.utcnow()
embed.set_footer(text=bot_name, icon_url=icon_uri)
await ctx.send(embed=embed)
elif search("cooldown", str(error)):
c_d = random.choice(["Did you drink energy drinks!?", "Why are you stressing, buddy.", "Duhh, wait, you're on cooldown!"])
second_remain = round(error.retry_after, 1)
embed=discord.Embed(title=c_d, description=f"Try again after {second_remain}s. {ctx.author.mention}", color=error_color)
embed.timestamp = datetime.utcnow()
embed.set_footer(text=bot_name, icon_url=icon_uri)
await ctx.send(embed=embed)
else:
raise error
Any attribute I can use?
You can use ctx.command
#bot.event
async def on_command_error(ctx, exception):
error = getattr(exception, "original", exception)
if hasattr(ctx.command, "on_error"): # If a command has it's own handler
return
elif isinstance(error, CommandNotFound):
return
if isinstance(error, discord.CommandInvokeError):
print(ctx.command)
Your solution is to add them to the command specifically, this also means it can help diagnose an issue with a command more exact.
You can also add any error events to the specific listener, just like how you done it for all commands, instead add them individually.
#bot.command()
async def command_name(ctx):
# ...
#command_name.error
async def command_name_error(ctx, error):
if isinstance(error, commands.CommandInvokeError):
await ctx.send("An error from this command" + error)
With #command_name.error put your command name before the .error, then this makes an error listener for that command, if it produces an error.

How to duplicate output of process to file and console (in Kotlin program)

I have a simple snippet of Kotlin code
import java.io.*
import java.util.concurrent.TimeUnit.MINUTES
import java.util.concurrent.TimeUnit
val proc = ProcessBuilder("C:\\tools\\build\\maven\\3.6.1\\bin\\mvn.cmd")
.directory(null)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
println("Started")
proc.waitFor(60, TimeUnit.MINUTES)
println("Ended")
val output : String = proc.inputStream.bufferedReader().readText()
println("Output : " + output)
var log : File = File("cmd.log")
log.writeText(output)
This code run command then saves output in string then print output to console
But printing is occured when external program is completed.
My question is:
I would like to see program output in real time mode.
From other hands I would like to see output of external program while it works.
This code run as Kotlin script : kotlinc -script script.ktc
If place string
val output : String = proc.inputStream.bufferedReader().readText()
Before waitFor call. I observed that execution is blocked as expected
I'm sorry for this question, it was quite simple,I found simple answer today.
val proc = ProcessBuilder("ls", "-lR", "c:\\toolchains")
.directory(null)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
println("Started")
val output: BufferedReader = proc.inputStream.bufferedReader()
var line: String? = output.readLine()
val log: File = File("cmd.log")
while (line != null) {
println("Next Line " + line)
log.appendText(line.toString() + System.lineSeparator())
line = output.readLine()
}
proc.waitFor(60, TimeUnit.MINUTES)
println("Ended")

How can I convert a std::process::Command into a command line string?

For example:
let mut com = std::process::Command::new("ProgramA");
com.env("ENV_1", "VALUE_1")
.arg("-a")
.arg("foo")
.arg("-b")
.arg("--argument=bar");
// Get the command line string somehow here.
com.output().unwrap();
This will spawn a process with this command line "ProgramA" -a foo -b "--argument=with space" associated with it.
Is there a way to get this back out from the com object?
It turns out Command implements Debug; this will give me the desired result:
let answer = format!("{:?}", com);

TCL, get full error message in catch command

#!/usr/bin/tclsh
proc test {} {
aaa
}
test
When I run this script I get error message:
invalid command name "aaa"
while executing
"aaa"
(procedure "test" line 2)
invoked from within
"test"
(file "./a.tcl" line 7)
If I run test command in catch I get only first line of error message.
#!/usr/bin/tclsh
proc test {} {
aaa
}
catch test msg
puts $msg
This prints:
invalid command name "aaa"
Is it possible to get full error message (file, line, procedure) in catch command? My program has many files and by getting just one line of error message it is difficult to find from where is it.
The short answer is to look at the value of errorInfo which will contain the stack trace.
The more complete answer is to look at the catch and the return manual pages and make use of the -optionsVarName parameter to the catch statement to collect the more detailed information provided. The return manual page gives some information on using this. But a rough example from an interactive session:
% proc a {} { catch {funky} err detail; return $detail }
% a
-code 1 -level 0 -errorstack {INNER {invokeStk1 funky} CALL a} -errorcode NONE -errorinfo {invalid command name "funky"
while executing
"funky"} -errorline 1
%
The detail variable is a dictionary, so use dict get $detail -errorinfo to get that particular item.