Menu
  • HOME
  • TAGS

Promela (ispin) stucks at the end of loop

Tag: loops,spin,promela

well, i have this (it is part of code):

20  proctype Main(byte myID) {
21    do
22    ::int J=0;
23      int K=0;
24    
25      atomic{
26        requestCS[myID]=true;
27        myNum[myID]=highestNum[myID]+1;
28    }
29  
30      do
31      :: J <= NPROCS-1 ->
32        if
33          :: J != myID -> ch[J] ! request, myID, myNum[myID];
34        fi;
35        J++;
36      :: else break;
37      od;//////////////////////////////////
38  
39    
40    do
41    :: K <= NPROCS-2 ->
42      ch[myID] ?? reply, _, _;
43      K++;
44    :: else break;
45    od;
46    
47    
48    cs: critical++;
49    assert (critical==1);
50    critical--;
51    requestCS[myID]=false;
52  
53    byte N;
54       do
55       :: empty(deferred[myID]) -> break;
56          deferred [myID] ? N -> ch[N] ! reply, 0, 0;
57       od;
58    od;
59  }

on ///////////// it stucks (writing timeout), and there is no way forward, to step 40, for example.

it is the part of Ricart-Agrawala algoritm, here it is et al:

1   #define  NPROCS 2
2   int critical = 0;
3   byte myNum[NPROCS];
4   byte highestNum[NPROCS];
5   bool requestCS[NPROCS];
6   chan deferred[NPROCS] = [NPROCS] of {byte};
7   mtype={request, reply};
8   chan ch[NPROCS]=[NPROCS] of {mtype, byte, byte};
9   
10  init {  
11    atomic {
12      int i;
13      for (i : 0 .. NPROCS-1){
14        run Main(i);
15        run Receive(i);
16      }
17    }
18  }
19  
20  proctype Main(byte myID) {
21    do
22    ::int J=0;
23      int K=0;
24    
25      atomic{
26        requestCS[myID]=true;
27        myNum[myID]=highestNum[myID]+1;
28    }
29  
30      do
31      :: J <= NPROCS-1 ->
32        if
33          :: J != myID -> ch[J] ! request, myID, myNum[myID];
34        fi;
35        J++;
36      :: else break;
37      od;
38  
39    
40    do
41    :: K <= NPROCS-2 ->
42      ch[myID] ?? reply, _, _;
43      K++;
44    :: else break;
45    od;
46    
47    
48    cs: critical++;
49    assert (critical==1);
50    critical--;
51    requestCS[myID]=false;
52  
53    byte N;
54       do
55       :: empty(deferred[myID]) -> break;
56          deferred [myID] ? N -> ch[N] ! reply, 0, 0;
57       od;
58    od;
59  }
60  
61  proctype Receive(byte myID){
62    byte reqNum, source;
63    do
64     :: ch[myID] ?? request, source, reqNum;
65  
66       highestNum[myID] = ((reqNum > highestNum[myID]) -> reqNum : highestNum[myID]);
67  
68       atomic {
69        if
70        :: requestCS[myID] && ((myNum[myID] < reqNum) || ((myNum[myID] == reqNum) && (myID < source))) -> deferred[myID] ! source
71        :: else -> ch[source] ! reply, 0, 0;
72        fi;
73    }
74    od;
75  }

what i doing wrong? Thank You in advance

P.S. critical - is a critical section "simulator", 'cause this algoritm is for distributed systems...

Best How To :

The verification can be stuck at line 37/40 for a couple of reasons. Your code just prior to then is:

32        if
33          :: J != myID -> ch[J] ! request, myID, myNum[myID];
34        fi;

This if statement will block forever if: J == myID or if ch[J] is full and never empties. You can 'fix' this problem by adding an else to the if and being careful to handle the 'queue is full' case. Of course, the 'fix' might not be consistent with what you are trying to model.

How to match words in 2 list against another string of words without sub-string matching in Python?

python,regex,string,loops,twitter

Store slangNames and riskNames as sets, split the strings and check if any of the words appear in both sets slangNames = set(["Vikes", "Demmies", "D", "MS", "Contin"]) riskNames = set(["enough", "pop", "final", "stress", "trade"]) d = {1: "Vikes is not enough for me", 2:"Demmies is okay", 3:"pop a D"} for...

How to create series of pandas dataframe by iteration

python,loops,pandas

To create variables by string, you can use - globals() function , which returns the dictionary of global namespace, and then create a new element in that dictionary for your variable and set the value to the value you want. Also , you can directly call - pandas.DataFrame(Series) - and...

Creating an auto incrementing loop within a function in python

python,loops,tkinter,increment

You can use itertools.count() for that. It creates a generator, that just returns one number after the other, when you call it's next() method: from itertools import count counter = count(1) for row in rows: row_id = counter.next() In this example on every iteration through the rows you will get...

Calling function and passing arguments multiple times

python,function,loops

a,b,c = 1,2,3 while i<n: a,b,c = myfunction(a,b,c) i +=1 ...

An error while looping a linear regression

r,loops,data.frame,regression

The problem arises from you mixture of subsetting types here: df$target[which(df$snakes=='a'),] Once you use $ the output is no longer a data.frame, and the two parameter [ subsetting is no longer valid. You are better off compacting it to: sum(df[df$snakes=="a","target"]) [1] 23 As for your model, you can just create...

IllegalStateException: Iterator already obtained [duplicate]

java,file,loops,path

You have to call DirectoryStream<Path> files = Files.newDirectoryStream(dir); each time you iterate over the files. Pls check this question... java.lang.IllegalStateException: Iterator already obtained...

How do I use the Find function with a variable term, for example Run1, Run2, RunX

vba,excel-vba,loops,variables

Yes, you need a variable, and just concatenate it. Use something like this: Dim counter as long counter = 1 Cells.Find(What:="Run:" & counter, After:=Cells(1, 1), _ ...yaddayadda Or use it in a loop: For i=1 to 100 Cells.Find(What:="Run:" & i, After:=Cells(1, 1), _ ...yaddayadda Next i ...

Matching key/value pairs in two dictionaries and creating a third one

python,loops,dictionary

The problem is this line matched = {i: data1[i]} It is overwriting the previous values of the dictionary. It should be matched[i] = data1[i] Or you can use update matched.update({i: data1[i]}) ...

Appending a data frame with for if and else statements or how do put print in dataframe

r,loops,data.frame,append

It's generally not a good idea to try to add rows one-at-a-time to a data.frame. it's better to generate all the column data at once and then throw it into a data.frame. For your specific example, the ifelse() function can help list<-c(10,20,5) data.frame(x=list, y=ifelse(list<8, "Greater","Less")) ...

Escape out of 2 Javascript loops (or stop script)

javascript,loops

To stop setInterval you have to use this clearInterval(n); And put var n = setInterval(function () {.... ...

Php counting with $i++

php,loops

<?php for($i = 0; $i < count($collection); $i++){ echo '<div id="'.$i.'">' . 'Anchor' . '</div>'; echo '<a href="#'.$i.'">' . 'Link-A ' . '</a>'; echo '<a href="#'.$i.'">' . 'Link-B ' . '</a>'; } ?> It is a basic for loop....

Infinite loop with fread

c,arrays,loops,malloc,fread

If you're "trying to allocate an array 64 bytes in size", you may consider uint8_t Buffer[64]; instead of uint8_t *Buffer[64]; (the latter is an array of 64 pointers to byte) After doing this, you will have no need in malloc as your structure with a 64 bytes array inside is...

How to create bootstrap html structure in php loop?

php,html,loops,bootstrap

You can do some thing like this. You can modify according to your need. I just mentioned logic <div class="row"> <?php $i = 0; foreach(....../*your code*/){ if($i == 4){ $i = 0; ?> </div><div class="row"> <?php } ?> <div class="col-sm-3"> <!--content--> </div> <?php $i++; } ?> </div> ...

Counter not working after jumps - assembly language

loops,assembly,counter,increment

The fault is caused because the mouse interrupt 33h function AX=0003h returns the mouse position in CX and DX. This overwrites your "counter" in register CX. It is always a dangerous game to keep values in registers throughout a program. Better to have a memory variable location. You could also...

Methods within my while Loop not working

python,loops

Calling open(output.txt) returns a file object, not the the text within the file. Calling str on the file object just gives a description of the object, not the text. To get that you need to something like output = open('output.txt') past_results = output.read() Also, it looks like you're calling str...

How to innerHTML a function with array as parameter?

javascript,arrays,loops,foreach,innerhtml

Just take a variable for the occurrence of even or odd numbers. var myArray = function (nums) { var average = 0; var totalSum = 0; var hasEven = false; // flag if at least one value is even => true, otherwise false nums.forEach(function (value) { totalSum = totalSum +...

Matlab: Writing to a file

arrays,matlab,loops,math,for-loop

If you want to get the matrices to be displayed in each column, that's going to be ugly. If I'm interpreting your request correctly, you are concatenating row vectors so that they appear as a single row. That's gonna look pretty bad. What I would suggest you do is split...

JQuery loop on multiple items of the same CSS class

jquery,loops,each,keyup,word-count

I'd wrap each textarea + word count (eg. in a div), and in the keyup event find the other child tag based on the shared parent element. This example just grabs the immediate parent but you could do it based on a common ancestor or its class name. eg. http://jsfiddle.net/mzqo2ruk/...

How to make function in loop run synchronously?

javascript,jquery,loops,google-chrome-extension,synchronization

One option would be to make your function(response) recursive. When it runs, call this same method again. Pass in some of your "looping" variables, and just do an if check at the beginning. function AnotherGoRound(i,data) { if (i<data[i2].data.length) { console.log("SENDING: i=" + i + "; i2=" + i2); // Send...

How do I write a loop to read text file and insert it to the database

sql-server,loops,powershell

To add a simple loop, you can use your existing AutoImportFlatFiles function like this: $Folder= $(read-host "Folder Location ('C:\Test\' okay)") foreach ($file in (get-childitem $Folder)) { $location = split-path $file.FullName -Parent $filename = (split-path $file.FullName -Leaf).split(".")[0] $extension = (split-path $file.FullName -Leaf).split(".")[1] AutoImportFlatFiles -location $location -file $filename -extension $extension -server "WIN123"...

Matlab: Looping through an array

matlab,loops,for-loop,while-loop,do-while

You could do this using conv without loops avg_2 = mean([A(1:end-1);A(2:end)]) avg_4 = conv(A,ones(1,4)/4,'valid') avg_8 = conv(A,ones(1,8)/8,'valid') Output for the sample Input: avg_2 = 0.8445 5.9715 -0.6205 -3.5505 2.5530 6.9475 10.6100 12.5635 6.4600 avg_4 = 0.1120 1.2105 0.9662 1.6985 6.5815 9.7555 8.5350 avg_8 = 3.3467 5.4830 4.7506 Finding Standard Deviation...

Index out of Range exception in arrays

c#,loops

This line: public static string [] starGenerated = new string[numberOfForbiddenWords]; ... is executed when the class is initialized. That will happen while numberOfForbiddenWords is still 0, i.e. long before this line is executed: numberOfForbiddenWords = int.Parse(Console.ReadLine()); So when you call StarGenerator, unless numberOfForbiddenWords is still 0, you're going to be...

2 Foreach Loop Inside A Table

php,loops,laravel-4,foreach,blade

You create new TD for each member. The nested foreach has to be: <td> @foreach($user as $mem) {{ $mem->name }}<br> @endforeach </td> The result will be: <td> Name 1<br> Name 2<br> Name 3<br> </td> I don't know the template engine you used, add inside a loop condition and don't put...

How can I iterate through nested HTML lists without returning the “youngest” children?

javascript,jquery,html,list,loops

You could just check the nesting level by counting parents $("ul li").each(function() { if ( $(this).parents('ul').length < 3 ) { // do stuff } }); FIDDLE To make it more dynamic one could simply find the deepest nesting level and filter based on that var lis = $("ul li"); var...

Creating a number list with nested For loops in Python

python,loops,nested

For the first instance, try this: print('', end = '') For the second instance, the mistake is that you are adding 0 to the second for loop. Change it to: for j in range(0, 1+i): The thing with range is that it goes until one number lower. Have a look...

performance issues executing list of stored procedures

c#,multithreading,performance,loops

What I would do is something like this: int openThread = 0; ConcurrentQueue<Type> queue = new ConcurrentQueue<Type>(); foreach (var sp in lstSps) { Thread worker = new Thread(() => { Interlocked.Increment(ref openThread); if(sp.TimeToRun() && sp.HasResult) { queue.add(sp); } Interlocked.Decrement(ref openThread); }) {Priority = ThreadPriority.AboveNormal, IsBackground = false}; worker.Start(); } //...

Array values are not being read correctly inside gameloop

javascript,arrays,loops

So it turns out I was wrong in my other comment. The non-detection of edges was causing you to index into unset parts of your array causing those weird messages and was all of your problems I scaled it back a bit to look at it see https://jsfiddle.net/goujdwog/2/ the important...

echo both users

php,mysql,sql,database,loops

Why don't you just do it in one single query? Just replace the necessary table and column name, and variables/values/parameters to be bind in your query: $query = mysqli_query($conn, "SELECT first_name, last_name, description, role FROM `wp_usermeta` WHERE `first_name` = '$first_name' OR `last_name` = '$last_name' OR `description` = '$description' OR `role`...

Using Yahoo! database without quantmod functions

r,loops,yahoo-finance

x<-c('AAIT', 'AAL', 'AAME') kk<-lapply(x,function(i) download.file(paste0("http://ichart.finance.yahoo.com/table.csv?s=",i),paste0(i,".csv"))) if you want to directly read the file: jj<- lapply(x,function(i) read.csv(paste0("http://ichart.finance.yahoo.com/table.csv?s=",i))) ...

Interface Controls for DoEvent in Excel

excel,vba,excel-vba,loops,doevents

How about changing your 'do until' loop to a 'for next' loop? Something like?... Sub rowinput() Dim lngInputStartRow As Long Dim lngInputEndRow As Long Dim row_number As Long lngInputStartRow = Range("A1").Value 'specify your input cell here lngInputEndRow = Range("A2").Value For row_number = lngInputStartRow To lngInputEndRow DoEvents Next row_number 'Then a...

Comparing two values in the same row and change if needed

php,mysql,loops

Below query will work, unless you need to do query optimization and reduce the locking period UPDATE Product SET Voorraad = Minvoorraad WHERE Minvoorraad > Voorraad ...

Python - Using a created list as a parameter

python,list,loops,if-statement,compare

I believe you are incorrectly referencing to num instead of line which is the counter variable in your for loops, you either need to use num as the counter variable, or use line in the if condition. def countGasGuzzlers(list1, list2): total = 0 CCount = 0 HCount = 0 for...

Matlab Calculating mean of distribution quantile in a for-loop

matlab,loops,for-loop,distribution,quantile

Your test variable is a three-dimensional variable, so when you do test2 = test(:,1); and then test2(:) <VaR_Calib_EVT/100 it's not the same as in your second example when you do test(:,i)<(VaR_Calib_EVT(:,i)/100) To replicate the results of your first example you could explicitly do the test2 assignment inside the loop, which...

Run 3 variables at once in a python for loop.

python,loops,variables,csv,for-loop

zip the lists and use a for loop: def downloadData(n,i,d): for name, id, data in zip(n,i,d): URL = "http://www.website.com/data/{}".format(name) #downloads the file from the website. The last part of the URL is the name r = requests.get(URL) with open("data/{}_{}_{}.csv".format(name, id, data), "wb") as code: #create the file in the format...

Nested foreach loop in a While loop can make the condition for the while loop go over?

php,loops,foreach,while-loop

Glad you found an answer. Here is something I was working on while you found it. // SET START DATE $startDate = new DateTime($dateStart); $nextBill = new DateTime(); for($i=1;$i<$countDays;$i++){ switch(true){ case ($startDate->format('j') > $days[2]): // go to next month $nextBill->setDate( $startDate->format('Y'), $startDate->format('m')+1, $days[0]; ); break; case ($startDate->format('j') > $days[1]): //...

Get next item in array using iterator using flags

javascript,jquery,loops,iterator,iteration

$.each(playlist,function(index, value){ if( !value.played ){ if( stop ){ song = index; return false; } else { if ( !value.playing ) { playlist[index].playing = false; stop = true; } } } }); outputs (index):87 hash2 (index):87 hash3 (index):87 hash4 (index):87 hash5 (index):87 hash1 ...

How to print iterations per second?

python,performance,loops,cmd,progress

You can get a total average number of events per second like this: #!/usr/bin/env python3 import time import datetime as dt start_time = dt.datetime.today().timestamp() i = 0 while(True): time.sleep(0.1) time_diff = dt.datetime.today().timestamp() - start_time i += 1 print(i / time_diff) Which in this example would print approximately 10. Please note...

How can i make a jQuery animation loop on infinite, after it finish?

jquery,loops,animation

You can achieve this in CSS alone through the use of @keyframes. Try this: @-moz-keyframes rotating { 0% { -moz-transform: rotate(-20deg); } 50% { -moz-transform: rotate(20deg); } 100% { -moz-transform: rotate(-20deg); } } @-webkit-keyframes rotating { 0% { -webkit-transform: rotate(-20deg); } 50% { -webkit-transform: rotate(20deg); } 100% { -webkit-transform: rotate(-20deg);...

Why is my C code printing out an extra line of rows?

c,loops,for-loop,macros,printf

There is no issue with the #define, there is one issue with the conditional statement in the for loop. I believe, you'er overlooking the <= operator. You need to have only < operator. Change for(i=0;i<=rows;++i) to for(i=0;i<rows;++i) That said, the recommended signature of main() is int main(void)....

How do I format the logic for 3 conditions and use a previous condition as well?

java,loops,if-statement,while-loop,logic

The second condition should be changed, otherwise the third if won't be reached. Also the third condition should be changed to check if the daysLate variable is greater or equal to zero: if (daysLate > 90) { costDue = bookPrice + 10; } else if (daysLate >= 7) { costDue...

How to build a 'for' loop with input$i in R Shiny

r,loops,for-loop,shiny

Use [[ or [ if you want to subset by string names, not $. From Hadley's Advanced R, "x$y is equivalent to x[["y", exact = FALSE]]." ## Create input input <- `names<-`(lapply(landelist, function(x) sample(0:1, 1)), landelist) filterland <- c() for (landeselect in landelist) if (input[[landeselect]] == TRUE) # use `[[`...

for loop - checking if numbers in array move more up or down

java,arrays,loops

A small semantic correction - the compiler isn't throwing any exception - your code compiles just fine. The runtime execution of this code causes an exception. And more to the point, an array a has elements from 0 to a.length - 1. Your code attempts to access element number a.length...

Javascript: Forloop Difference between i++ and (i+1)

javascript,loops,for-loop

The i++ is using post increment, so the value of the expression i++ is what the value was in the variable i before the increment. This code: if(sortedLetters[i] !== sortedLetters[i++]) return true; does the same thing as: if(sortedLetters[i] !== sortedLetters[i]) return true; i = i + 1; As x !==...

Python: TypeError: list indices must be integers, not list

python,list,loops,indices

You are indexing your lists with a non-int type index: for count in list_kp2_ok: for count1 in list_kp2_2_ok: if list_kp2_ok[count]==list_kp2_2_ok[count1]: So a quick fix for that is to do it this way: for coord1 in list_kp2_ok: for coord2 in list_kp2_2_ok: if coord1==coord2: You can even do the whole coding in...

How to iterate through a table in its exact order?

loops,for-loop,lua,order

You may utilize integer part of the table to store keys in order: function add(t, k, v, ...) if k ~= nil then t[k] = v t[#t+1] = k return add(t, ...) end return t end t = add({ }, "A", "hi", "B", "my", "C", "name", "D", "is") for i,k...

PHP: How to push Select results to multi-dimensional array (partially working)

php,arrays,loops,select,multidimensional-array

You are getting this output because you are overwriting the keys in your array. You would need to save to another array (aka not 2-dimensional): <?php $tbl = "TranslationsMain"; $conn = new mysqli($servername, $username, $password, $dbname); if($conn->connect_error){ die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM " ....

How to repeat this statement in R probably using apply()

r,loops

Here's a recommended way to ask a question, focusing on the fact that your actual data is too big, too complicated, or too private to share. Question: how to apply a function on each row of a data.frame? My data: # make up some data s <- "Lorem ipsum dolor...

for each loop: how to step out of conditions

loops,vbscript,condition

Use else as follows: for each file in folder.files if (filename = "foo.bar") then log.writeline("found foo.bar -> delete!") fs.deletefile (folder & file.name), true 'exit for else if (isNumeric(firstPosition)) then if (isNumeric(secondPosition)) then log.writeline("2 numbers seen -> alright!") else log.writeline("Filename is corrupt!") fs.copyFile file, errorFolder, true fs.deleteFile file, true 'exit for...

How to make sure to draw two different random cards [closed]

python,loops,random,while-loop

There are three different options you have to choose from here, I will explain each one: Option 1 - break while first_draw == second_draw: first_draw = random.choice(card_values) + random.choice(card_classes) second_draw = random.choice(card_values) + random.choice(card_classes) break break will end the innermost loop. In this case, the loop will only run once....

Add mouseListener to Labels in Array Loop

java,loops,mouselistener

the problem is when mouse-event fire value of i have value 6 or last value of for-loop for (i = 0; i < 6; i++){} you can create a jlable class and give a instance variable like lableindex so when mouse-event occurs you first get the lable index and then...