How to constrain SystemVerilog queue to values in another queue? - constraints

Is there a way to populate a queue using elements from another random queue in a constraint-based way? For example,
class some_class;
rand bit [7:0] choices [$];
rand bit [7:0] chosen [$];
int num_choices = 20;
int num_chosen = 5;
function new();
endfunction
constraint choices_size_c { choices.size() == num_choices; }
constraint chosen_c {
chosen.size() == num_chosen;
foreach (chosen[i]) {
// check chosen[i] exists somewhere within choices
}
}
endclass
The idea is we have a number of valid choices that, for example, get programmed somewhere. Then we choose 5 of those valid choices for testing. Can this be done with constraints, or do I need to do this manually post-randomization?

Use the set membership operator inside
constraint chosen_c {
chosen.size() == num_chosen;
foreach (chosen[i]) {
chosen[i] inside {choices};
}
}
You can also add unique constraints to prevent repetition if that is a requirement you failed to mention
constraint uniq {
unique {choices};
unique {chosen};
}

Related

Modified function not working as intended without recursion

I have a recursive function which iterates though directory trees listing the file names located in them.
Here is the function:
void WINAPI SearchFile(PSTR Directory)
{
HANDLE hFind;
WIN32_FIND_DATA FindData;
char SearchName[1024],FullPath[1024];
memset(SearchName,0,sizeof(SearchName));
memset(&FindData,0,sizeof(WIN32_FIND_DATA));
sprintf(SearchName,"%s\\*",Directory);
hFind=FindFirstFile(SearchName,&FindData);
if(hFind!=INVALID_HANDLE_VALUE)
{
while(FindNextFile(hFind,&FindData))
{
if(FindData.cFileName[0]=='.')
{
continue;
}
memset(FullPath,0,sizeof(FullPath));
sprintf(FullPath,"%s\\%s",Directory,FindData.cFileName);
if(FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
MessageBoxA(NULL, FullPath, "Directory", MB_OK);
SearchFile(FullPath);
}
else
{
MessageBoxA(NULL, FullPath, "File", MB_OK);
}
}
FindClose(hFind);
}
}
There are obviously differences between both functions but I don't understand what's making them act differently. Does anyone know why I am having this problem?
for fast understand error need look for line
goto label;
//SearchFile(FullPath);
at this point hFind containing valid data and FindClose(hFind); need be called for it. but after goto label; executed - your overwrite hFind with hFind = FindFirstFile(SearchName, &FindData); - so you already never close original hFind, never can return to iterate folder after such go to sub-folder. this is key point - need save original hFind before go to sub directory and restore it after. when you do recursive function call - this is done auto - because every sub directory in this case enumerated in self stack frame, which have separate hFind. this is native solution use recursion here.
but possible convert recursion to loop here because we call self always from the single place and as result to this single place. so we can not save return address in stack but do unconditional jump (goto) to known place.
then code have some extra errors, you never check for string buffers overflow, why 1024 as max length is hard-coded when file path can be up to 32768 chars, you not check for reparse point as result can enter to infinite loop, use FindFirstFile instead FindFirstFileEx, etc.
correct code for enumerate sub-folder in loop can be next
void DoEnum(PCWSTR pcszRoot)
{
SIZE_T FileNameLength = wcslen(pcszRoot);
// initial check for . and ..
switch (FileNameLength)
{
case 2:
if (pcszRoot[1] != '.') break;
case 1:
if (pcszRoot[0] == '.') return;
}
static const WCHAR mask[] = L"\\*";
WCHAR FileName[MAXSHORT + 1];
if (_countof(FileName) < FileNameLength + _countof(mask))
{
return;
}
ULONG dwError;
HANDLE hFindFile = 0;
WIN32_FIND_DATA FindData{};
enum { MaxDeep = 0x200 };
//++ stack
HANDLE hFindFileV[MaxDeep];
PWSTR pszV[MaxDeep];
char prefix[MaxDeep+1];
//--stack
ULONG Level = MaxDeep;
memset(prefix, '\t', MaxDeep);
prefix[MaxDeep] = 0;
PWSTR psz = FileName;
goto __enter;
__loop:
hFindFile = FindFirstFileEx(FileName, FindExInfoBasic, &FindData, FindExSearchNameMatch, 0, FIND_FIRST_EX_LARGE_FETCH);
if (hFindFile != INVALID_HANDLE_VALUE)
{
do
{
pcszRoot = FindData.cFileName;
// skip . and ..
switch (FileNameLength = wcslen(pcszRoot))
{
case 2:
if (pcszRoot[1] != '.') break;
case 1:
if (pcszRoot[0] == '.') continue;
}
if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if ((SIZE_T)(FileName + _countof(FileName) - psz) < FileNameLength + _countof(mask))
{
continue;
}
__enter:
memcpy(psz, pcszRoot, (1 + FileNameLength) * sizeof(WCHAR));
if (FindData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
{
DbgPrint("%sreparse point: <%S>\n", prefix + Level, pcszRoot);
}
else
{
if (Level)
{
DbgPrint("%s<%S>\n", prefix + Level, psz);
hFindFileV[--Level] = hFindFile;
pszV[Level] = psz;
memcpy(psz += FileNameLength, mask, sizeof(mask));
psz++;
goto __loop;
__return:
*--psz = 0;
psz = pszV[Level];
hFindFile = hFindFileV[Level++];
DbgPrint("%s</%S>\n", prefix + Level, psz);
}
}
}
else
{
DbgPrint("%s[%u%u] %S\n", prefix + Level, FindData.nFileSizeLow, FindData.nFileSizeHigh, pcszRoot);
}
if (!hFindFile)
{
// top level exit
return ;
}
} while (FindNextFile(hFindFile, &FindData));
if ((dwError = GetLastError()) == ERROR_NO_MORE_FILES)
{
dwError = NOERROR;
}
FindClose(hFindFile);
}
else
{
dwError = GetLastError();
}
if (dwError)
{
DbgPrint("<%S> err = %u\n", FileName, dwError);
}
goto __return;
}
The reason for the difference is actually the confusion brought to you by goto label.If you are using the recursive version, after the recursive execution is completed, it will return to the recursive place to continue execution.
In your code, you continue to execute while (FindNextFile(hFind, &FindData)), but when you use goto label, it will jump out of the original loop and restart the program from the label, which leads to what you said list a single directory tree before ending.
If you modify the modified code to the following iterative version, you can understand why there is such a problem.
void fun()
{
char* Directory = "D:\\test";
HANDLE hFind;
WIN32_FIND_DATA FindData;
char SearchName[1024], FullPath[1024];
char LastName[1024] = "";
while (1)
{
memset(SearchName, 0, sizeof(SearchName));
memset(&FindData, 0, sizeof(WIN32_FIND_DATA));
sprintf(SearchName, "%s\\*", Directory);
if (strcmp(SearchName, LastName) == 0)
{
return;
}
strcpy(LastName, SearchName);
hFind = FindFirstFile(SearchName, &FindData);
if (hFind != INVALID_HANDLE_VALUE)
{
while (FindNextFile(hFind, &FindData))
{
if (FindData.cFileName[0] == '.')
{
continue;
}
memset(FullPath, 0, sizeof(FullPath));
sprintf(FullPath, "%s\\%s", Directory, FindData.cFileName);
if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
MessageBoxA(NULL, Directory, "Directory", MB_OK);
char cArray[1024];
memset(cArray, 0, sizeof(cArray));
sprintf(cArray, "%s", FullPath);
Directory = cArray;
break;
}
else
{
MessageBoxA(NULL, FullPath, "File", MB_OK);
}
}
FindClose(hFind);
}
}
}
So you cannot achieve the same purpose as recursion by using goto, here you can only use recursion. Of course, I have provided a way to traverse directories non-recursively using queues, which is a more scientific way.
One of the key things that you obtain from recursion is a separate set of local variables for each call to the recursive function. When a function calls itself, and in the recursive call modifies local variables, those local-variable changes do not (directly) affect the local variables of the caller. In your original program, this applies to variables hFind, FindData, SearchName, and FullPath.
If you want similar behavior in a non-recursive version of the function then you need to manually preserve the state of your traversal of one level of the tree when you descend to another level. The goto statement doesn't do any such thing -- it just redirects the control flow of your program. Although there are a few good use cases for goto in C, they are uncommon, and yours is not one of them.
There are several ways to implement manually preserving state, but I would suggest
creating a structure type in which to store those data that characterize the state of your traversal of a particular level. Those appear to be only hFind and FindData -- it looks like the other locals don't need to be preserved. Maybe something like this, then:
struct dir_state {
HANDLE hFind;
WIN32_FIND_DATA FindData;
};
Dynamically allocating an array of structures of that type.
unsigned depth_limit = DEFAULT_DEPTH_LIMIT;
struct dir_state *traversal_states
= malloc(depth_limit * sizeof(*traversal_states));
if (traversal_states == NULL) // ... handle allocation error ...
Tracking the depth of your tree traversal, and for each directory you process, using the array element whose index is the relative depth of that directory.
// For example:
traversal_states[depth].hFind
= FindFirstFile(SearchName, &traversal_states[depth].FindData);
// etc.
Remembering the size of the array, so as to be able to reallocate it larger if the traversal descends too deep for its current size.
// For example:
if (depth >= depth_limit) {
depth_limit = depth_limit * 3 / 2;
struct dir_state *temp
= realloc(traversal_states, depth_limit * sizeof(*traversal_states));
if (temp == NULL) {
// handle error, discontinuing traversal
}
traversal_states = temp;
}
Also, use an ordinary for, while, or do loop instead of a backward-jumping goto. There will be a few details to work out to track when to use FindFirstFile and when FindNextFile (which you would still have with goto), but I'm sure you can sort it out.
Details are left as an exercise.
Unless necessary due to memory or processing constraints or infinite recursion tail conditions that would be complication to introduce there really isn't much need to not use recursion here, since it leads to a readable and elegant solution.
I also want to point out that in "modern" C, any solution using a GOTO is likely not a solution you want since they are so often confusing to use and leads to memory issues (we have loops now to make all of that so much simpler).
Instead of the GOTOs I would suggest implementing a stack of the directories. Wrap the printing logic a while or do-while, and as you are iterating over the files add any directories to the stack. At every new iteration pop and walk the directory at the head of the stack. The loop condition just needs to check if the directory stack is empty, before continuing its block.

xBestIndex malfunction (passing non-literal parameters to table valued function)

I'm trying to implement a table valued function (as a SQLite virtual table).
It's a function that would take a string and return a table with all the words of the string.
If I call it with literal values like below, it works fine.
SELECT word FROM splitstring("abc def ghi")
If, however, I call it with a column from another table it doesn't work:
SELECT a.Name, word FROM article a, splitstring(a.Text)
The xBestIndex method gets called all right, but right after that, I get an exception from the ExecuteReader method. The exception message is "xBestIndex malfunction". The xFilter method does not get called because of the exception.
My xBestIndex implementation is simple, it just marks the parameter so I can see it in xFilter:
public override SQLiteErrorCode BestIndex(SQLiteVirtualTable table, SQLiteIndex index)
{
index.Outputs.ConstraintUsages.ElementAt(0).argvIndex = 1;
index.Outputs.ConstraintUsages.ElementAt(0).omit = 1;
return SQLiteErrorCode.Ok;
}
Am I'm doing something wrong or is it impossible to pass non-literal parameters to table valued functions?
Found the issue! I was using constraints that had usable=0. The BestIndex method gets called multiple times by SQLite, the second time with a non-usable constraint.
Here is the fixed body of the BestIndex method.
public override SQLiteErrorCode BestIndex(SQLiteVirtualTable table, SQLiteIndex index)
{
if (index.Inputs.Constraints.Count() != 2)
throw new ArgumentException("The generate_series function requires two integer (long) parameters!");
if (index.Inputs.Constraints.All(c=>c.usable == 1))
{
index.Outputs.ConstraintUsages.ElementAt(0).argvIndex = 1;
index.Outputs.ConstraintUsages.ElementAt(0).omit = 1;
index.Outputs.ConstraintUsages.ElementAt(1).argvIndex = 2;
index.Outputs.ConstraintUsages.ElementAt(1).omit = 1;
}
else
{
index.Outputs.IndexNumber = -1;
index.Outputs.EstimatedCost = double.MaxValue;
}
return SQLiteErrorCode.Ok;
}
Now I check the usable flag. When BestIndex gets called with a constraint with usable=0 I skip it i.e. return a high estimated cost for that index so it doesn't get used.

Faster database access by index

I have this code
using (var contents = connection.CreateCommand())
{
contents.CommandText = "SELECT [subject],[note] FROM tasks";
var r = contents.ExecuteReader();
int zaehler = 0;
int zielzahl = 5;
while (r.Read())
{
if (zaehler == zielzahl)
{
//access r["subject"].ToString()
}
zaehler++;
}
}
I want to make it faster by accessing zielzahl directly like r[zielzahl] instead of iterating through all entries. But
r[zielzahl]["subject"]
does not work aswell as
r["subject"][zielzahl]
How do I access the column subject of result number zielzahl?
To get only the sixth record, use the OFFSET clause:
SELECT subject, note
FROM tasks
LIMIT 1 OFFSET 5
Please note that the order of returned records is not guaranteed unless you use the ORDER BY clause.

Using Count To Split A Checklist Into 2 Columns in X++ Fetch Method

Here is what I have so far, this is returning two columns, but each counter is stopping and then duplicating the same value over and over...
if(lLogisticsControlTable.APMJobTypeId)
select count (RecID) from jobTypeCheck where jobTypeCheck.APMJobTypeId == lLogisticsControlTable.APMJobTypeId;
{
counter = jobTypeCheck.RecId;
}
while select jobTypeCheck where jobTypeCheck.APMJobTypeId == lLogisticsControlTable.APMJobTypeId
{
counter1 = counter / 2;
halfCount1 = counter - counter1;
if(halfcount <= counter1)
{
halfCount++;
jobListCheck1 = jobTypeCheck.Name;
}
if (halfCount1 > halfCount)
{
halfCount1++;
jobListCheck2 = jobTypeCheck.Name;
}
element.execute(2);
}
}
As Michael Brown indicated, it's difficult to understand the problem with half of the code ;)
However, I would suggest that you call the element.execute(2) method on every second pass through the loop? That way jobListCheck1 would be on the left, and jobListCheck2 would be on the right hand side. Finally you would then need to check immediately outside of your loop if you had an odd number of jobTypeCheck elements, and call the element.execute(2) method one last time remembering to set the jobListCheck2 variable as empty beforehand.
Regards

Regarding to retrieve values inside the array

Hi
I am creating online quiz in asp.net c#. For that i have one form that displays testlist in dropdownlist & start button. After clicking 2nd form appears, 2nd form shows one label for question, radiobuttonlist for answers ,next & checkbox for review. I am creating array of random question ids in start button click event of the 1stform. when i click next button in 2nd form then next random question appears, i want array of questions those are checked for review. I used code for arrays of values ( eg.10101) 1 for true & 0 for false as follows but i want array of that question ids those are checked:
int[] a = (int[])Session["values"];//this is array of random question ids created in 1st form
int g;
if (chkmark.Checked == true)
{
g = 1;
}
else
{
g = 0;
}
int[] chkarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
int[] temp1 = (int[])Session["arrofchk"];
int k, no;
if (temp1 == null)
no = 0;
else
no = temp.Length;
for (k = 0; k < no; k++)
{
chkarray[k] = temp1[k];
}
chkarray[j] = g;
Personally, i would use a Dictionary<int, bool> for this.
In the key of the dictionary, you can store the random Question ID, in the value of the pair, you can store the checked item state. It might take you more work now to refactor it, but I believe it will save you a lot of time in the end when you want to do more actions on your quiz items.
Using a dictionary - or at least a well chosen collection, I think it will be easier to get the right data back.
For your example, it can work only if the positions of both arrays are the same.
Dictionary<int, bool> quizAnswers = new Dictionary<int, bool>(); // <questionID, checked>
// Fill dictionary with questions and answers
for(int i=0;i<a.length;i++)
{
if(temp1.length > i) // Make sure we don't get an IndexOutOfBoundsException
{
quizAnswers.Add(a[i], temp1[i] == 1);
}
}
// Get Answered question in array ( LINQ )
int[] checkedAnswers = (from KeyValuePair<int, bool> pair in quizAnswers
where pair.Value == true
select pair.Key).ToArray<int>();
The reason I am using a Dictionary here, is because I personally think it's neater than having two separate arrays.
I believe you should implement a Dictionary in your quiz, in stead of those arrays. What if the array indexes don't match, or you want to dynamically add a question to a fixed size array, etc..
It's something to take into consideration. Hope I could help you out.

Resources