Specman: How to find if a list of bytes exists in another list taking order of the list into account - specman

I have a payload which is a lists of type bytes:
var payload : list of byte;
payload= {1;2;3;4;5;6};
var item1 :list of byte;
item = {3;4;5};
var item2 :list of byte;
item = {1;4};
I would like to implement a code that checks if a list is a sub-list of another. Using "if ..in.." doesn't quite work as it does not take into account the order of the items or if they appear successively or not. I want something that does the following:
if (item1 in payload) ...... should return TRUE. Items exist in payload in the same order.
if (item2 in payload) ...... should return FALSE because although each element in the list exists in the payload, but the item2 elements do not appear successively in the payload list.
Is there an easy way to achieve this? There must be a build -in function in specman for this.
Thanks

The following code should work:
if (item.size()==0) {return TRUE};
for i from 0 to payload.size()-item.size() {
if (item == payload[i..i+item.size()-1]) {
return TRUE;
};
};
return FALSE;
Note that this code is quite expensive memory-wise (the list[a..b] syntax creates a new list every time) so if you have memory considerations it should be modified.

Related

RetainWhere Function Dart Uncertanties

I have a following code.
void onItemSelected(String status) {
print("default list count: " + transactionList.length.toString());
List<trx.Transaction> filteredTrx = transactionList;
print("default2 list count: " + transactionList.length.toString());
filteredTrx.retainWhere((element) => element.status == status);
print("default3 list count: " + transactionList.length.toString());
filteredTransactionList = filteredTrx;
}
I am doing a dropdownbutton to allow user to filter based on their status selection. In this example, the status of the transaction can be (processing, approved, rejected).
I know that I can use foreach loop to compare and assign into a new list. But i would like to use a function which is more efficient. And i think that retainWhere could be a good solution for it.
So, I had a list of Transactions recorded into transactionList variable. And to prevent this list from changing, i declare a new list to store into it and apply it with retainWhere function. However, i noticed that once it runs the retainWhere function, the default transactionList will be empty as well. Does anyone know why?
The debug result is as below:
I/flutter (12068): default list count: 2
I/flutter (12068): default2 list count: 2
I/flutter (12068): default3 list count: 0
You are not copying the list, you are copying the reference to same list (see the second sentence here: https://dart.dev/guides/language/language-tour#variables). This is the reason why both lists are affected by retainWhere.
You probably want to (shallow) copy the list like this:
List<trx.Transaction> filteredTrx = List.from(transactionList)
https://api.dart.dev/stable/2.18.0/dart-core/List/List.from.html

Flutter shared_preferences - how to get all the stored values begin with specific word

I have stored in shared_preferences key value pairs like below....
item_001 = 'some data'
item_103 = 'some data'
item_007 = 'some data'
item_059 = 'some data'
I am trying get all the stored values begins with item_***
I know how to read and write with single key (example below)... but I am trying to get a list of items from shared_preferences where the key name begins with item_.
string
read: final myString = prefs.getString('my_string_key') ?? '';
write: prefs.setString('my_string_key', 'hello');
stringList
read: final myStringList = prefs.getStringList('my_string_list_key') ?? [];
write: prefs.setStringList('my_string_list_key', ['horse', 'cow', 'sheep']);
due to some reason, I don't want to store all the items in one list.... I want to store each item with separate key.
I searched in google and in stackoverflow, unfortunately no where found proper answer....
also I looked into this one, but not understood how to implement partial key search...
esetintis got to this first but I doodled this code so I guess I'll share it. But yes, you have to first get all of the keys in the shared preferences and then get the value for matching keys.
SharedPreferences prefs = await SharedPreferences.getInstance();
Set<String> keys = prefs.getKeys().where((key)=>key.startsWith('item_'));
for (String key in keys) {
String value = prefs.getString(key); // Throws an error if you store something other than a String
// Do your thing
}
I don't think there is a way to make such query. However, you can tackle the issue with some extra steps.
1 step :
Get all keys from SharedPreferences with prefs.getKeys() method. This will return a Set of keys. Now you can assign a List<String> keys = prefs.getKeys().where((k)=>k.startsWith('item_')) which will have the keys you want to get from the Storage.
2nd :
Iterate the filtered array and get the values you want by calling SharedPreferences, and save them to some variable.
Assuming that you have all the keys in a list, for example:
List<String> keys = ['item_001', 'item_103', 'item_007', 'item_059', 'other_key', 'blablabla'];
Now, you could iterate through all of them and checking the ones that starts with "item_", like this:
var itemKeys = [];
for(var i=0;i<keys.length;i++){
if (keys[i].startsWith('item_')) {
itemKeys.add(keys[i]);
}
}
print(itemKeys); // [item_001, item_103, item_007, item_059]
In the above example, itemKeys contains all the needed keys for you. What you could also do is to add the proper logic to fetch values from the shared preferences inside the if statement in the loop:
var result = [];
for(var i=0;i<keys.length;i++){
if (keys[i].startsWith('item_')) {
result.add(prefs.getString(keys[i]) ?? '');
}
}
result should contain what are you looking for.

Get value from Instance in Flutter

I am making a search request on the List with the Provider pattern.
List<Device> _devices = [
Device(one: 'Apple', two: 'iphone'),
Device(one: 'Samsung', two: 'Galaxy')
];
And Query is like this
List<Device> queryQuery(String value) {
return _devices
.where((device) => device.one.toLowerCase().contains(value.toLowerCase()))
.toList();
the result I expect to get is iphone when I passed the value Apple.
But the result on the screen that I got is [instance of ‘Device’]
when I code like this
child: Text('${deviceData.getDevice('Apple')}'
I do know I should be using some kind of key using two... but I have no idea :-(
You serialized the wrong object.
What you did end-up being similar to:
Text(Device(one: 'Apple', two: 'iphone').toString());
But you don't want to do Device.toString(). What you want instead is to pass Device.two to your Text.
As such your end result is:
Text('${chordData.chordExpand('Apple').two}')
By the look of [Instance of 'Device'], it seems the function is returning a list so it is a good idea to check if the list is empty or not. if it is not empty, one of the elements is still needed to be selected. I guess it should be Text('${chordData.chordExpand('Apple')[0].two}') in case the list is not empty.
To summarize, use something like this to handle the case when list is empty
// Inside your build method before returning the widget
var l = chordData.chordExpand('Apple'); // Returns a list of devices
String textToWrite; // Here we will store the text that needs to be written
if(l.isEmpty) textToWrite = 'No results'; // If the filter resulted in an empty list
else textToWrite = l[0].two; // l[0] is an instance of a device which has a property called two. You can select any instance from the list provided it exists
return <Your Widget>(
.....
Text(textToWrite),
.....
);

Specman: Error in on-the-fly generating of list of lists with all different values

I try to generate on-the-fly list of list of uint (my_list_of_list) with all different values (I have a variable num_of_ms_in_each_g : list of uint, that keeps lengths of every list inside my_list_of_list):
var my_list_of_list : list of list of uint;
gen my_list_of_list keeping {
for each (g) using index (g_idx) in it {
g.size() == num_of_ms_in_each_g[g_idx];
for each (m) using index (m_idx) in g {
// Error in the next line:
m not in it[0..g_idx-1][0..num_of_ms_in_each_g[g_idx]-1];
m not in it[g_idx][0..max(0, m_idx-1)];
};
};
Explanation for the code algorithm: generate m (the value) that was not yet in any list of uint (g) before, and does not appear in current list for previous indexes.
I get compilation error:
*** Error: 'm' is of type 'uint', while expecting type 'list of uint' or
'list of list of uint'.
Do you have any idea how to solve the compilation error? (it[0..g_idx-1][0..num_of_ms_in_each_g[g_idx]-1] is uint..) Or maybe another way to generate on-the-fly list of list of uint with all different values?
Thank you for your help.
I would reduce the complexity of this constraint by using a sort of a unified list that contains all the items, and then
Break this list into the desired list of list ( as It is easier to generate a single unique list).
Also, in general, it is best to keep all non-generative operations outside of the constraints since it could be done procedurally
Afterwards which will improve the overall performance of generating such a field set.
I would do this using the following code:
var unified_list:list of uint;
var my_list_of_list : list of list of uint;
gen unified_list keeping {
it.size()==num_of_ms_in_each_g.sum(it);
it.all_different(it);
};
for each in num_of_ms_in_each_g {
var temp_list:list of uint;
for i from 0 to it-1 {
temp_list.add(unified_list.pop0());
};
my_list_of_list.add(temp_list);
};
thanks
Actually, the expression it[0..g_idx-1][0..num_of_ms_in_each_g[g_idx]-1] is of type list of list of uint. The operator list[from..to] produces a sub list. In your code you apply it twice to it which first produces a sublist and then produces a sublist of the sublist.
The second such constraint in your code works, because it[g_idx] does not produce a sublist, but rather accesses a list item, which is of type list of uint and then produces a sublist.
To produce an all different list of list I would do something like:
var my_list_of_list : list of list of uint;
for each (sz) in num_of_ms_in_each_g {
var l : list of uint;
gen l keeping {
it.size() == sz;
it.all_different(it);
// not it.has(it in my_list_of_list.flatten());
// for better performance
for each (itm) in it {
itm not in my_list_of_list.flatten();
};
};
my_list_of_list.add(l);
};

Coffeescript isn't empty object [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
is object empty?
update: (id, data) ->
toUpdate = #find(id)
if toUpdate isnt {}
console.log "hi mom"
console.log toUpdate
toUpdate.setProperty(key, value) for own key, value of data
return toUpdate
find:(id) ->
result = record for record in #storage when record.id is id
return result or {}
Given the following Mocha tests
describe '#update', ->
it 'should return an updated record from a given id and data when the record exists', ->
boogie = createData()
archive = new Archive("Dog")
dog = archive.create(boogie)
result = archive.update(1, {name:"Chompie", age:1})
result.name.should.eql "Chompie"
result.age.should.eql 1
result.emotion.should.eql dog.emotion
it 'should return an updated record from a given id and data when the record does not exist', ->
boogie = createData()
archive = new Archive("Dog")
dog = archive.create(boogie)
result = archive.update(50, {name:"Chompie", age:1})
result.should.not.exist
The result is
Archive #update should return an updated record from a given id and data when the record exists: hi mom
{ id: 1,
validationStrategies: {},
name: 'Boogie',
age: 2,
emotion: 'happy' }
✓ Archive #update should return an updated record from a given id and data when the record exists: 1ms
Archive #update should return empty when the record does not exist: hi mom
{}
✖ 1 of 13 tests failed:
1) Archive #update should return empty when the record does not exist:
TypeError: Object #<Object> has no method 'setProperty'
...surprising, isnt it?
CoffeeScript's is (AKA ==) is just JavaScript's === and isnt (AKA !=) is just JavaScript's !==. So your condition:
if toUpdate isnt {}
will always be true since toUpdate and the object literal {} will never be the same object.
However, if #find could return a known "empty" object that was available in a constant, then you could use isnt:
EMPTY = {}
find: ->
# ...
EMPTY
and later:
if toUpdate isnt EMPTY
#...
For example, consider this simple code:
a = { }
b = { }
console.log("a is b: #{a is b}")
console.log("a isnt b: #{a isnt b}")
That will give you this in your console:
a is b: false
a isnt b: true
But this:
class C
EMPTY = { }
find: -> EMPTY
check: -> console.log("#find() == EMPTY: #{#find() == EMPTY}")
(new C).check()
will say:
#find() == EMPTY: true
Demo: http://jsfiddle.net/ambiguous/7JGdq/
So you need another way to check if toUpdate isn't empty. You could count the properties in toUpdate:
if (k for own k of toUpdate).length isnt 0
or you could use the special EMTPY constant approach outlined above. There are various other ways to check for an empty object, Ricardo Tomasi​ has suggested a few:
Underscore offers _.isEmpty which is basically the for loop approach with some special case handling and a short circuit.
Underscore also offers _.values so you could look at _(toUpdate).values().length. This calls map internally and that will be the native map function if available.
You could even go through JSON using JSON.stringify(toUpdate) is '{}', this seems a bit fragile to me and rather round about.
You could use Object.keys instead of the for loop: Object.keys(toUpdate).length isnt 0. keys isn't supported everywhere though but it will work with Node, up-to-date non-IE browsers, and IE9+.
Sugar also has Object.isEmpty and jQuery has $.isEmptyObject.
A short-circuiting for loop appears to be the quickest way to check emptiness:
(obj) ->
for k of toUpdate
return true
false
That assumes that you don't need own to avoid iterating over the wrong things. But given that this is just a test suite and that an emptiness test almost certainly won't be a bottle neck in your code, I'd go with whichever of Underscore, Sugar, or jQuery you have (if you need portability and have to deal with the usual browser nonsense), Object.keys(x).length if you know it will be available, and (k for own k of toUpdate).length if you don't have the libraries and have to deal with browser nonsense and aren't certain that toUpdate will be a simple object.