How should I handle Perl 6 $*ARGFILES that can't be read by lines()? - io

I'm playing around with lines which reads lines from the files you specify on the command line:
for lines() { put $_ }
If it can't read one of the filenames it throws X::AdHoc (one day maybe it will have better exception types so we can grab the filename with a .path method). Fine, so catch that:
try {
CATCH { default { put .^name } }
for lines() { put $_ }
}
So this catches the X::AdHoc error but that's it. The try block is done at that point. It can't .resume and try the next file:
try {
CATCH { default { put .^name; .resume } } # Nope
for lines() { put $_ }
}
Back in Perl 5 land you get a warning about the bad filename and the program moves on to the next thing.
I could filter #*ARGS first then reconstruct $*ARGFILES if there are some arguments:
$*ARGFILES = IO::CatHandle.new:
#*ARGS.grep( { $^a.IO.e and $^a.IO.r } ) if +#*ARGS;
for lines() { put $_ }
That works although it silently ignores bad files. I could handle that but it's a bit tedious to handle the argument list myself, including - for standard input as a filename and the default with no arguments:
my $code := { put $_ };
#*ARGS = '-' unless +#*ARGS;
for #*ARGS -> $arg {
given $arg {
when '-' { $code.($_) for $*IN.lines(); next }
when ! .IO.e { note "$_ does not exist"; next }
when ! .IO.r { note "$_ is not readable"; next }
default { $code.($_) for $arg.IO.lines() }
}
}
But that's a lot of work. Is there a simpler way to handle this?

To warn on bad open and move on, you could use something like this:
$*ARGFILES does role { method next-handle { loop {
try return self.IO::CatHandle::next-handle;
warn "WARNING: $!.message"
}}}
.say for lines
Simply mixing in a role that makes the IO::CatHandle.next-handle method re-try getting next handle. (you can also use but operator to mixin on a copy instead).
If it can't read one of the filenames it throws X::AdHoc
The X::AdHoc is from .open call; there's a somewhat moldy PR to make those exceptions typed, so once that's fixed, IO::CatHandle would throw typed exceptions as well.
It can't .resume
Yeah, you can only resume from a CATCH block that caught it, but in this case it's caught inside .open call and is made into a Failure, which is then received by IO::CatHandle.next-handle and its .exception is re-.thrown.
However, even if it were resumable here, it'd simply resume into a path where exception was thrown, not re-try with another handle. It wouldn't help. (I looked into making it resumable, but that adds vagueness to on-switch and I'm not comfortable speccing that resuming Exceptions from certain places must be able to meaningfully continue—we currently don't offer such a guarantee for any place in core).
including - for standard input as a filename
Note that that special meaning is going away in 6.d language as far as IO::Handle.open (and by extension IO::CatHandle.new) goes. It might get special treatment in IO::ArgFiles, but I've not seen that proposed.
Back in Perl 5 land you get a warning about the bad filename and the program moves on to the next thing.
In Perl 6, it's implemented as a generalized IO::CatHandle type users can use for anything, not just file arguments, so warning and moving on by default feels too lax to me.
IO::ArgFiles could be special-cased to offer such behaviour. Personally, I'm against special casing stuff all over the place and I think that is the biggest flaw in Perl 5, but you could open an Issue proposing that and see if anyone backs it.

Related

Reactive streams map operator never getting executed

For the below code
Mono<String> input =
Mono.just("input")
.map {
println "inside map"
it + "added"
}
.transform {
Mono.just("hello")
}
input.subscribe {println it}
The console looks like as below.
16:11:49.056 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
hello
The code inside the map function was never executed. I understand that transform method executes at assembly time rather than the subscription.
Why did Reactor just decide to not process my upstream map operator. Did it intelligently decide that since I am not in anyway referring to the output of the map operator that it need not execute map at all ?
Is this behaviour configurable ?
The reason is that transform does not automatically subscribe to your original Mono. It's your responsibility to chain your logic onto it. Since nothing subscribes to it, it will never get triggered.
As the example you sent is dummy, it's difficult to say what would be the right thing to do. It depends on your use case.
A few thing you can do, though:
Get rid of transform and just simply use then operator:
Mono<String> input =
Mono.just("input")
.map {
println "inside map"
it + "added"
}
.then(Mono.just("hello"))
If for some reason you need transform, then chain your logic onto your original Mono:
Mono<String> input =
Mono.just("input")
.map {
println "inside map"
it + "added"
}
.transform {
it.then(Mono.just("hello"))
}

ChucK - storing id values of sporked shreds

A little bit of a beginner so bear with me.
I was writing a bit of code to experiment with shred sporking and removing, but encountered a problem. Here is a portion of my code:
while(hid.recv(msg)) //Hid hid is above
{
if(msg.isButtonDown()) //HidMsg msg is above
{
spork ~ test() #=> Shred # s; //test is just an empty function
}
if(msg.isButtonUp())
{
Machine.remove(s.id());
}
}
With this, however, I get the error "undefined variable 's'...". I could tell that since defining 's' only happens after msg.isButtonDown() is true, so I tried a different method.
while(hid.recv(msg))
{
Shred s;
if(msg.isButtonDown()) //HidMsg msg is above
{
spork ~ test() #=> s; //test is just an empty function
}
if(msg.isButtonUp())
{
Machine.remove(s.id());
}
}
However, this results in the error "cannot remove: no shred with id 0...". I don't understand why s.id() would be 0? Shouldn't the chucking in the first if statement define s.id() as the sporked id? I can't seem to get past this.
Thanks,
Kevin Kim
Shred s is scoped to the body of the while loop. You're creating a new Shred variable on each iteration of the loop. They're different references. Put the variable declaration (Shred s in this case) outside of the while loop.

Checking if control exists throws an error

Really what I am after is a way to check if the control exists without throwing an error.
The code should look something like this:
Control myControl = UIMap.MyMainWindow;
if (!myControl.Exists)
{
//Do something here
}
The problem is that the control throws an error because it is invalid if it doesn't exist, essentially making the exists property useless.
What is the solution?
In this case I am using the tryfind method.
Like this:
HtmlDiv list = new HtmlDiv(Window.GetWebtop());
list.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
list.SearchProperties.Add(HtmlDiv.PropertyNames.InnerText, "Processing search", PropertyExpressionOperator.Contains);
if (list.TryFind())
{
//DO Something
}
I am re-posting the comment kida gave as a answer, because I think its the best solution.
Control myControl = UIMap.MyMainWindow;
if (!myControl.FindMatchingControls().Count == 0)
{
//Do something here
}
The FindMatchingControls().Count is much faster then the Try Catch or the TryFind. Since it does not wait for SearchTimeoutto check if the element is now there. Default it waits 30 seconds for the element to not be there, but I like my tests to fail fast.
Alternatively its possible to lower the Playback.PlaybackSettings.SearchTimeout before the Catch or TryFind and restore it afterwards, but this is unnecessary code if you ask me.
You can do one of two things: Wrap your code in a try-catch block so the exception will be swallowed:
try
{
if (!myControl.Exists)
{
// Do something here.
}
}
catch (System.Exception ex)
{
}
Or, you could add more conditions:
if (!myControl.Exists)
{
// Do something here.
}
else if (myControlExists)
{
// Do something else.
}
else
{
// If the others don't qualify
// (for example, if the object is null), this will be executed.
}
Personally, I like the catch block, because if I expect the control to be there as part of my test, I can Assert.Fail(ex.ToString()); to stop the test right there and log the error message for use in bug reporting.
If you are sure that control will exist or enabled after some time you can use WaitForControlExist() or WaitForControlEnabled() methods with a default timeout or specified timeout.
I have a situation like this and I am looping until the control is available :
bool isSaveButtonExist = uISaveButton.WaitForControlEnabled();
while (!isSaveButtonExist )
{
try
{
uISaveButton.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
uISaveButton.SetFocus(); // setting focus for the save button if found
isSaveButtonExist = uISaveButton.WaitForControlExist(100);
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message); // exception for every set focus message if the control not exist
}
}
// do something with found save button
// Click 'Save' button
Mouse.Click(uISaveButton, new Point(31, 37));
please refer to this link for more about these Methods:
Make playback wait methods

Is there a language that breaks out of conditional statements as soon as they become false?

I thought that I had come across this before, but I can't remember when or what language it was.
Basically if I have the following in C#:
someCondition = true
if(someCondition)
{
// Do Something
if(anotherCond) {
someCondition = false;
continue;
}
// Do Something Else
}
In C# this will break out of the body of the if statement when someCondition changes, meaning that //DO Something Else only gets processed if someCondition doesn't change...
Is there a language that will do the interior if statement checking/continue automatically i.e. be able to write:
someCondition = true
if(someCondition)
{
// Do Something
if(anotherCond){
someCondition = false;
}
// Do Something Else
}
with the same behaviors as the previous? Obviously there are multiple ways to get this behavior in every language conceivable, what I am interested in is if there is a language that by design has this functionality.
Edit: Reduced the examples so hopefully people can see what is happening, when someCondition changes (i.e. the condition that the if statement relied on to begin, we should break out of the remaining if statement. I am not looking for a way to do this in C#, or any particular language, but for a language that does this automatically.
You can create a property in C# that throws an exception on any condition you set, aka truth=true. The exception will break out of the loop to wherever you have your catch.
An example in C#:
public class MyException : Exception { }
public bool truth
{
get { return _truth; }
set
{
_truth = value;
if(value)
throw new MyException();
}
}
bool _truth;
I think you can simulate what you want in C# like so:
void ExecuteWhile( Func<bool> condition,
IEnumerable<Action> executeWhileTrue,
IEnumerable<Action> executeWhileFalse)
{
if (condition())
{
foreach (Action action in executeWhileTrue)
{
action();
if (!condition())
return;
}
}
else
{
foreach (Action action in executeWhileFalse)
{
action();
if (condition())
return;
}
}
}
and then use it as such:
truth = true;
while (true) // loop forever
{
ExecuteWhile( () => truth,
new List<Action> { () => { /* do something that might set truth to false*/},
() => { /* do something else*/}},
new List<Action> { () => { /* do something that might set truth to true*/},
() => { /* do something else*/}});
}
And to answer your question: no, I don't think there is a language with this as a build-in feature.
As far as I understood, the following is wanted:
if (cond) {
A;
B;
C;
}
shall behave as if written thus:
if (cond) {
A;
if (cond) {
B;
if (cond) {
C
}
}
}
IMHO, this would be a silly feature, unlikely to be implemented in any language except maybe in INTERCAL.
Why do I think that?
Well, suppose someone wants to refactor the code and moves B;C to a subroutine.
if (cond) {
A;
BC();
}
subroutine BC() { B;C }
The block - according to our feature - will mean as before:
if (cond) {
A;
if (cond) BC();
}
But what about our subroutine? The language designer has 2 choices here:
Treat the call BC() as atomic, i.e. in the subroutine, the
condition cond is not checked before statement C. This would mean
such a simple refactoring would change the meaning of the program
drastically.
Somehow pass the information that every statement must be guarded
with cond to the subroutine so that the behaviour of our block remains
unchanged. This, of course, leads to the silly situation that the
behaviour of any subroutine would depend upon the context it was
called in. A subroutine with n atomic statements would have n possible ways to behave even if it had no arguments and would not use non local mutable state explicitely, depending on how many of the statements would be actually executed. (Note that nowadays the trend is to minimize the most often harmful effects of shared non-local state. OO languages do it with encapsulation, FP languages by banning mutable state altogether.)
In any case, no matter how the language designer decides, we would have a feature that is the direct contradiction of the principle of the least surprise. It is clear that programs in such a language would be utterly hard to maintain.
If you broke you big bunch if/else statements into succinct little methods which tested each little piece of the puzzle, you could rely on the compilers short circuit boolean evaluation
I'm not sure if that helps as your example is a big vague. You don't say if you're doing any processing or if it's just a bunch of checks. Either way, breaking your code into smaller methods may help you out.
You can use a do..while loop:
do
{
} while (truth == true);
thats if i've understood correctly!
You say while true... but while what is true. I would think your loop will run infinitely regardless of the language used. Assuming true will be a real condition... I would say just set the exit condition in one of the if blocks. You question is a bit hard to understand. Also the continue is unnecessary.

Best pattern for simulating "continue" in Groovy closure

It seems that Groovy does not support break and continue from within a closure. What is the best way to simulate this?
revs.eachLine { line ->
if (line ==~ /-{28}/) {
// continue to next line...
}
}
You can only support continue cleanly, not break. Especially with stuff like eachLine and each. The inability to support break has to do with how those methods are evaluated, there is no consideration taken for not finishing the loop that can be communicated to the method. Here's how to support continue --
Best approach (assuming you don't need the resulting value).
revs.eachLine { line ->
if (line ==~ /-{28}/) {
return // returns from the closure
}
}
If your sample really is that simple, this is good for readability.
revs.eachLine { line ->
if (!(line ==~ /-{28}/)) {
// do what you would normally do
}
}
another option, simulates what a continue would normally do at a bytecode level.
revs.eachLine { line ->
while (true) {
if (line ==~ /-{28}/) {
break
}
// rest of normal code
break
}
}
One possible way to support break is via exceptions:
try {
revs.eachLine { line ->
if (line ==~ /-{28}/) {
throw new Exception("Break")
}
}
} catch (Exception e) { } // just drop the exception
You may want to use a custom exception type to avoid masking other real exceptions, especially if you have other processing going on in that class that could throw real exceptions, like NumberFormatExceptions or IOExceptions.
Closures cannot break or continue because they are not loop/iteration constructs. Instead they are tools used to process/interpret/handle iterative logic. You can ignore given iterations by simply returning from the closure without processing as in:
revs.eachLine { line ->
if (line ==~ /-{28}/) {
return
}
}
Break support does not happen at the closure level but instead is implied by the semantics of the method call accepted the closure. In short that means instead of calling "each" on something like a collection which is intended to process the entire collection you should call find which will process until a certain condition is met. Most (all?) times you feel the need to break from a closure what you really want to do is find a specific condition during your iteration which makes the find method match not only your logical needs but also your intention. Sadly some of the API lack support for a find method... File for example. It's possible that all the time spent arguing wether the language should include break/continue could have been well spent adding the find method to these neglected areas. Something like firstDirMatching(Closure c) or findLineMatching(Closure c) would go a long way and answer 99+% of the "why can't I break from...?" questions that pop up in the mailing lists. That said, it is trivial to add these methods yourself via MetaClass or Categories.
class FileSupport {
public static String findLineMatching(File f, Closure c) {
f.withInputStream {
def r = new BufferedReader(new InputStreamReader(it))
for(def l = r.readLine(); null!=l; l = r.readLine())
if(c.call(l)) return l
return null
}
}
}
using(FileSupport) { new File("/home/me/some.txt").findLineMatching { line ==~ /-{28}/ }
Other hacks involving exceptions and other magic may work but introduce extra overhead in some situations and convolute the readability in others. The true answer is to look at your code and ask if you are truly iterating or searching instead.
If you pre-create a static Exception object in Java and then throw the (static) exception from inside a closure, the run-time cost is minimal. The real cost is incurred in creating the exception, not in throwing it. According to Martin Odersky (inventor of Scala), many JVMs can actually optimize throw instructions to single jumps.
This can be used to simulate a break:
final static BREAK = new Exception();
//...
try {
... { throw BREAK; }
} catch (Exception ex) { /* ignored */ }
Use return to continue and any closure to break.
Example
File content:
1
2
----------------------------
3
4
5
Groovy code:
new FileReader('myfile.txt').any { line ->
if (line =~ /-+/)
return // continue
println line
if (line == "3")
true // break
}
Output:
1
2
3
In this case, you should probably think of the find() method. It stops after the first time the closure passed to it return true.
With rx-java you can transform an iterable in to an observable.
Then you can replace continue with a filter and break with takeWhile
Here is an example:
import rx.Observable
Observable.from(1..100000000000000000)
.filter { it % 2 != 1}
.takeWhile { it<10 }
.forEach {println it}

Resources