Nested IF in Gnu Mathprog - gnu

I want to ask if it is possible to have two nested if in a GnuMathprog model and how i can write in the code something like that. For an example:
if a<>0
a*x=y
if b<>0
b*c=d
else 0
else 0
;
Thank you very much

First the bad news: GMPL does not support If-Then-Else statements.
But you can use conditionals in for-loops which can be nested. Here is a small working non-nested example:
for{a in {1..2}} {
for {{0}: a == 1} {
printf "First\n";
} for {{0}: a != 1} {
printf "Second\n";
}
}
end;
This works fine while post-processing the model results/data.

Related

Is it possible to sort a vector of string with std::sort(), based on a complex criteria?

I need to sort a std::vector<std::wstring> which contains folder names, in a such manner that the parent folder is always located after all its children, e.g:
C:\Main\App\QtGraphicalEffects\private
C:\Main\App\QtGraphicalEffects
C:\Main\App\Qt\labs\platform
C:\Main\App\Qt\labs
C:\Main\App\Qt
C:\Main\App
C:\Main\
To reach a such sorting I may use a Bubble Sort algorithm, as the following one:
void BubbleSortDirs(std::vector<std::wstring>& dirs)
{
bool swapped = false;
do
{
swapped = false;
for (std::size_t i = 0; i < dirs.size() - 1; ++i)
// swap positions if first dir is entirely contained in the second
if (dirs[i] != dirs[i + 1] && dirs[i + 1].find(dirs[i]) == 0)
{
std::swap(dirs[i], dirs[i + 1]);
swapped = true;
}
}
while (swapped);
}
This code works well, but I feel that a better solution should exist. So I tried to use the std::sort function in order to optimize my sorting, at least to provide a more elegant solution.
I tried the following implementation:
bool SortDirs(const std::wstring& first, const std::wstring& second)
{
// swap positions if first dir is entirely contained in the second
return (first == second || first.find(second) == 0);
}
...
std::sort(dirs.begin(), dirs.end(), SortDirs);
I expected that std::sort() would provide the same result as the BubbleSortDirs() function, but it wasn't the case and the result failed in several locations. At this point I strongly suspect that std::sort() isn't adapted for a complex sorting criteria like the one I'm trying to apply.
So my questions are:
What is the reason why my call to std::sort doesn't provide the expected result?
Is there a way to achieve the above described sorting using the std::sort() function?
If yes, what am I doing wrong?
If no, is the above BubbleSortDirs() function the best way to achieve a such sorting, or does it exist something better?
I finally resolved my issue this way:
std::sort(dirs.rbegin(), dirs.rend());

Implementing pipes without using threads

I am working on a small language for fun and to try out some ideas. One of the ideas I am trying to implement is piping like in the shell but with arbitrary objects. An example might make this clearer.
The functions range and show_pipe can be defined like this:
range(n) => {
x := 0;
while x < n do {
push x;
x := x + 1;
}
}
show_pipe() => {
while true do {
x := pull;
if x = FinishedPipe then {
return 0
} else {
print(x)
};
}
}
push pushes a value into the next part of the pipeline and suspends the function until another value is needed and pull pulls a value from the pipe and returns it or FinishedPipe if the previous part of the pipeline has finished executing.
You can then pipe these two function together with range(10) | show_pipe() which will show the numbers 0 through 9 on console.
I'm implementing this by using a thread for each part of the pipeline and using thread safe queues for passing values from one part of the pipe the other. I would really like to find a way to implement pipes without using threads. I am using Rust so I can't use coroutines.

Why this Perl script run out of memory gradually

I have a trouble in running a Perl script in muti-threads. It continued consume memory and finally the system ran out of memory and killed it. It seems that the sub-threads were detached but the system resource were not released when they finished. I am pretty new to Perl and couldn't find which part went wrong. This is part of the script that may cause this problem. Could anyone help me with this?
use strict;
use warnings;
print "different number:\t";
my $num1=<>;
chomp $num1;
if($num1!~/[1 2 3 4 5]/)
{
print "invalid input number\n";
END;
}
my $i=0;
my $no;
my #spacer1;
my $nn;
my #spacer2;
open IN,"file1.txt"or die"$!";
while(<IN>)
{
chomp;
if($_=~ /^>((\d)+)\|((\d)+)/)
{
$no=$1;
$spacer1[$no][0]=$3;
}
else
{
$spacer1[$no][1]=$_;
}
}
close IN;
open IN, "file2.txt" or die "$!";
while(<IN>)
{
chomp;
if($_=~ /^>((\d)+)\|((\d)+)/)
{
$nn=$1;
$spacer2[$nn][0]=$3;
}
else
{
$spacer2[$nn][1]=$_;
}
}
close IN;
#-----------------------------------------------------------------#create threads
use subs qw(sg_ana);
use threads;
use Thread::Semaphore;
my $cycl=(int($no/10000))+1;
my $c;
my #thd;
my $thread_limit= Thread::Semaphore -> new (3);
foreach $c(1..$cycl)
{
$thread_limit->down();
$thd[$c]=threads->create("sg_ana",$c-1,$c,$num1);
$thd[$c]->detach();
}
&waitquit;
#-------------------------------------------------------------#limite threads num
sub waitquit
{
print "waiting\n";
my $num=0;
while($num<3)
{
$thread_limit->down();
$num++;
}
}
#---------------------------------------------------------------#alignment
my $n;
my $n1;
my $j;
my $k;
my $l;
my $m;
my $num;#number of match
my $num2=0;;#arrange num
sub sg_ana
{
my $c1=shift;
my $c2=shift;
$num1=shift;
open OUT,">$num1.$c2.txt" or die "$!";
if($num1==1)
{
foreach $n($c1*10000..$c2*10000-1)
{
if($spacer2[$n][1])
{
my $presult1;
my $presult2;
$num2=-1;
foreach $i(0..19)
{
$num=0;
$num2++;
my $tmp1=(substr $spacer2[$n][1],0,$i)."\\"."w".(substr $spacer2[$n][1],$i+1,19-$i);
foreach $n1(0..#spacer1-1)
{
if($spacer1[$n1][1])
{
my $tmp2=substr $spacer1[$n1][1],0,20;
if($tmp2=~/$tmp1/)
{
$num++;
$presult1.=$n1.",";
}
}
}
$presult2=$i+1;
if($num>=4)
{
print OUT "\n";
}
}
}
}
}
close OUT;
$thread_limit->up();
}
Rule one of debugging perl is enable use strict; and use
warnings; and then sort out the errors. Actually, you should
probably do that first of all, before you even start writing code.
You're creating and limiting threads via a Semaphore - but actually
this is really inefficient because of how perl does threads - they
aren't lightweight, so spawning loads is a bad idea. A better way of doing this is via Thread::Queue a bit like this.
Please use 3 arg open and lexical file handles. e.g. open ( my
$out, '>', "$num.$c2.txt" ) or die $!;. You're probably getting
away with it here, but you have got OUT as a global namespace
variable being used by multiple threads. That way lies dragons.
Don't use single letter variables. And given how you you use $c
then you'd be far better off:
foreach my $value ( 1..$cycl ) {
## do stuff
}
The same is true of all your other single letter variables though - they're not meaningful.
You pass $num before it's initialised, so it's always going to
be undef within your sub. So your actual subroutine is just:
sub sg_ana
{
my $c1=shift;
my $c2=shift;
$num1=shift;
open OUT,">$num1.$c2.txt" or die "$!";
close OUT;
$semaphore->up();
}
Looking at it - I think you may be trying to do something with a shared variable there, but you're not actually sharing it. I can't decode the logic of your program though (thanks to having a load of single letter variables most likely) so I can't say for sure.
You're calling a subroutine &waitquit;. That's not good style -
prefixing with an ampersand and supplying no arguments does
something subtly different to just invoking the sub 'normally' - so
you should avoid it.
Don't instantiate your semaphore like this:
my $semaphore=new Thread::Semaphore(3);
That's an indirect procedure call, and bad style. It would be better written as:
my $thread_limit = Thread::Semaphore -> new ( 3 );
I would suggest rather than using Semaphores like that, you'd be far better off not detatching your threads, and just using join. You also don't need an array of threads - threads -> list does that for you.
I can't reproduce your problem, because your sub isn't doing
anything. Have you by any chance modified it for posting? But a classic reason for perl memory exhaustion when threading is because each thread clones the parent process - and so 100 threads is 100x the memory.

Fork/Join example with GPars

I found an example for fork/join in GPars here: Fork/Join
import static groovyx.gpars.GParsPool.runForkJoin
import static groovyx.gpars.GParsPool.withPool
withPool() {
println """Number of files: ${
runForkJoin(new File("./src")) {file ->
long count = 0
file.eachFile {
if (it.isDirectory()) {
println "Forking a child task for $it"
forkOffChild(it) //fork a child task
} else {
count++
}
}
return count + (childrenResults.sum(0))
//use results of children tasks to calculate and store own result
}
}"""
}
It works and returns the correct number of files, but unfortunately I don't understand this line:
return count + (childrenResults.sum(0))
How exactly work count and childrenResult?
Why is a 0 passed as a parameter to sum()?
I'm not much familiar with GPars, but the link you provided says it is a Divide-and-Conquer algorithm and clarifies a bit more what's implicit later on, explaining that forkOffChild() does not wait -- instead getChildrenResults() does.
You may find easier to understand the provided alternative approach in the same page, that uses a more Java-ish style, if you're more familiar to that.
childrenResults results in calling the method getChildrenResults(), this is the "join" in "Fork/Join", it waits for all children to finish and then returns a list with the results of them (or re-throws any exception a children may have thrown).
0 is just the initial value for the sum. If childrenResult is empty, that's what gets summed to count:
groovy:000> [].sum(1)
===> 1
groovy:000> [1].sum(1)
===> 2

Switch fallthrough in Dart

I started learning Dart today, and I've come across something that my google skills are having trouble finding.
How do I have a fall-through in a non-empty case?
My use case is this: I'm writing a sprintf implementation (since dart doesn't have this too), which would work except for this fall-through thing. When parsing the variable type you can, for example, have "%x" versus "%X" where the upper case type tells the formatter that the output is supposed to be uppercase.
The semi-pseudocode looks like:
bool is_upper = false;
switch (getType()) {
case 'X':
is_upper = true;
case 'x':
return formatHex(is_upper);
}
The other ways I can think of doing this, would one of the following
1:
switch (getType()) {
case 'X': case 'x':
return formatHex('X' == getType());
}
2:
var type = getType();
if (type in ['x', 'X']) {
return formatHex('X' == getType());
}
Now, the second choice almost looks good, but then you have to remember that there are eleven cases, which would mean having eleven if (type in []), which is more typing that I'd like.
So, does dart have some // //$FALL-THROUGH$ that I don't know about?
Thanks.
The Dart specification gives a way for a switch case to continue to another switch case using "continue":
switch (x) {
case 42: print("hello");
continue world;
case 37: print("goodbye");
break;
world: // This is a label on the switch case.
case 87: print("world");
}
It works in the VM, but sadly the dart2js switch implementation doesn't yet support that feature.
From the dart language tour, your example of (2) should be correct.
var command = 'CLOSED';
switch (command) {
case 'CLOSED': // Empty case falls through.
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeClose();
break;
}
It would be an error if you tried to do something as follows
var command = 'OPEN';
switch (command) {
case 'OPEN':
executeOpen();
// ERROR: Missing break causes an exception to be thrown!!
case 'CLOSED':
executeClose();
break;
}
EDIT: This seems to only have worked due to a bug in the implementation of Dart. See the Dart 1.x language spec, section "17.15 Continue".
The bug is now fixed, as reported in a comment, so this no longer works. Keeping for historical reasons.
Also, a simplification of Lasse's answer is to use a simple continue; instead of continue <label>; as in:
bool is_upper = false;
switch (getType()) {
case 'X':
is_upper = true;
continue;
case 'x':
return formatHex(is_upper);
}
You can't have a non-empty case body in Dart that falls through, this will raise an error.
What I tend to do with anything other than very simple switch statements is to refactor all the common code out into functions, so that you don't have this multi-level control flow in the switch itself.
In other words, something like:
switch (getType()) {
case 'X':
return formatHex(true);
case 'x':
return formatHex(false);
}
There's no reason why you need to have fallthrough. It comes in handy when the actions in a case section can be carried out in toto at the end of another case section, but this method can do that without fallthrough and without making your switch statement complex.
It can also handle more complex cases where there are common actions that aren't included in toto at the end. For example, you may want to do something at the start or in the middle of the case section. Calling common functions handles that more than well enough:
switch (getType()) {
case 'X':
doSomethingOnlyForUpperCase();
doSomethingCommon();
doSomethingElseOnlyForUpperCase();
return formatHex(true);
case 'x':
doSomethingCommon();
return formatHex(false);
}
I actually also do this for languages (such as C) that support this sort of non-empty fall-through since I believe it aids in readability and maintainability.
Dart in 202207, just empty, instead of continue label
PermissionStatus recordStatus =
await Permission.requestSinglePermission(
PermissionName.Microphone);
switch (recordStatus) {
case PermissionStatus.allow:
case PermissionStatus.always:
case PermissionStatus.whenInUse:
return;
default:
break;
}

Resources