How to create a set containing different types - rascal

How can I create a set containing a loc, int and string?
In the example below it seems my map is converted to the container type ' value'. I would like to use the characteristics of a set;
Only one element should be contained in the set and the order does not matter .
In the example below the same elements are contained in what I was hoping to be a set.
rascal>mySet = ();
map[void, void]: ()
rascal>mySet += {<|project://Test/|, 1, "test"> };
value: {
(),
<|project://Test|,1,"test">
}
rascal>mySet += {<|project://Test/|, 1, "test"> };
value: {
<|project://Test|,1,"test">,
{
(),
<|project://Test|,1,"test">
}
}
Thank you again for advise :-)

Something weird is going on . First mySet is a map, and then you add a set to it and the variable mySet is suddenly a set that contains the previous map and the new element you added. It looks to me that += has a bug.
If you want to add several elements to a set, you should start with a set and add elements to it like so:
rascal>mySet = { |project://Test| ,1, "test" }; // simply create the set with 3 different elements in it
set[value]: { |project://Test| ,1, "test" }
Or you could start with an empty set and add elements:
rascal>mySet = {};
set[void]: {}
rascal>mySet += 1;
set[int]: {1}
rascal>mySet += |project://Test|;
set[value]: {1, |project://Test|}
rascal>mySet += "test";
set[value]: {1, |project://Test|, "test"}

Related

Check if element is the last value in fold function

I am using fold on an array which hasn't been assign to a variable and want to check whether the element is the last value. With a conventional for loop I can do this:
List<int> ints = [1, 2, 3];
int sum = 0;
for (int num in ints]) {
if (num != ints.last) {
sum = sum + num;
}
}
print(sum);
Is it possible to do this with fold instead?
int foldSum = [1, 2, 3].fold(0, (int prev, element) => prev + element);
print(foldSum);
I can't find any way of check when fold is at the last value. Note: this is a simplified example of my problem and the reason the list isn't assigned to a variable (allowing me to use .last) is because it is the result of a call to .map().
For completeness, below is the actual code (which won't obviously won't be runnable in isolation but will help illustrate my problem) I am trying to convert to use .map and .fold:
String get fieldsToSqlInsert {
String val = "";
for (Column column in columns) {
if (data.containsKey(column.name)) {
val = '$val "${data[column.name]}"';
} else {
val = "$val NULL";
}
if (column != columns.last) {
val = "$val,";
}
}
return val;
}
But it doesn't work because I don't know how to check when fold is at the final element:
String get fieldsToSqlInsert => columns
.map((column) =>
data.containsKey(column.name) ? data[column.name] : "NULL")
.fold("", (val, column) => column != columns.last ? "$val," : val);
If you simply want to exclude the last element from further calculation, you can just use take to do so:
String get fieldsToSqlInsert => columns.take(columns.length - 1)...

Map implementation with duplicate keys in Dart

I want to have a map with duplicate keys. Is there such a map in Dart or a utility library that has this functionality?
I'm using the following get a count of items:
myList.forEach(
(element) {
if (!myMap.containsKey(element)) {
myMap[element] = 1;
} else {
myMap[element] += 1;
}
},
);
then convert keys/values to lists: Need to switch key/values...
final keys = myMap.keys.toList();
final itemSpit = keys.map((e) => e.toString().split('§º')).toList();
final values = myMap.values.toList();
put it in a map
final map = Map();
for (var i = 0; i < values.length; i++) {
map[values[i]] = itemSpit[i];
}
Obviously the keys are overridden in the for loop.
then
iterate over map (Put keys/values in flutter widgets)
final cells = map.entries
.map((e) => ........
THe first method increases the value count if there's a duplicate value. So I have this. ... {breadwhitelarge: 3, cornyellowsmall:5 ..etc..}
I then have to split the strings and have output like this
5 bread white large
3 corn yellow small
Instead of defining a map which allows duplicated keys you can instead create a Map<K,List<V>> like this example:
void main() {
final map = <String, List<int>>{};
addValueToMap(map, 'Test 1', 1);
addValueToMap(map, 'Test 1', 2);
addValueToMap(map, 'Test 2', 3);
addValueToMap(map, 'Test 1', 4);
addValueToMap(map, 'Test 2', 5);
addValueToMap(map, 'Test 3', 6);
print(map); // {Test 1: [1, 2, 4], Test 2: [3, 5], Test 3: [6]}
}
void addValueToMap<K, V>(Map<K, List<V>> map, K key, V value) =>
map.update(key, (list) => list..add(value), ifAbsent: () => [value]);
You can then ask for a given key and get a list of all values connected to this key.
package:quiver provides a MultiMap class with List-based and Set-based implementations.
Could you just create the Flutter widgets directly from the first map?
var widgets = [for (var e in myMap.entries) MyWidget(
count: e.value,
strings: [... e.key.split("§º")])];
Building the intermediate map seems to be what is causing the trouble.
this is an example map has duplicate keys
withDuplicateKey() {
List<dynamic> demoList = [
{1},
{2},
{3},
{1}
];
var toRemove = {};
demoList.forEach((e) {
toRemove.putIfAbsent(e, () => e);
});
print(toRemove.keys.toList());
}
output is ( printed list of key )
[{1}, {2}, {3}, {1}]

Testing for identical objects in Dart

According to the documentation, the function identical checks whether two references are to the same object.
With that in mind, I don't understand why the following is the case:
int a = 1;
int b = 1;
print(identical(a, b)); // prints 'true'
Map c = { 1: 'y' };
Map d = { 1: 'y' };
print(identical(c, d)); // prints 'false'
I'd expect both calls to return 'false'.
identical compares references. a and b are references to a compile time literal 1. Thus they are identical.

JQuery : How can we filter int from variable

Is it possible to filter numbers from the variable.
I can show you one example here from the link http://jsfiddle.net/sweetmaanu/82r5v/6/
I need to get only numbers from the alert message
Simply replace the box string out of it.
DEMO
for (var i = 0; i < order.length; i++) {
order[i] = order[i].replace('box', '');
}
So instead of box1, box2, box3, box4 you want to see 1,2,3,4
You can use a regular expression like this:
var order = $("#boxes").sortable("toArray") + "";
alert(order.replace(/[^0-9,]/g, ''));
I also had to append an empty string to order because it wasn't being recognized as a string object even though the jQuery documentation says it should be when you call sortable("toArray").
change var order = $("#boxes").sortable("toArray");
to var order = $("#boxes").sortable("toArray").join(',').replace(/[a-zA-Z]/gi, "");
Demo: http://jsfiddle.net/82r5v/13/
// Remove all non-digits from the string
'box1'.replace(/\D/g, ''); // => '1'
// Same, but try to make the string a number
Number('box1'.replace(/\D/g, '')); // => 1
// Shorthand for making an object a number (+o is the same as Number(o))
+'box1'.replace(/\D/g, ''); // => 1
// parseInt(s) works if the number is at the beginning
parseInt('1box'); // => 1
// but not if it occurs later
parseInt('box1'); // => NaN
Maybe using regular expressions something like this:
`alert(order.join(',').match(/\d/g));`
To return the array as numbers.
(\d matches all digits, g signifies a global match wildcard)
One way to do it by using regular expressions - http://jsfiddle.net/holodoc/82r5v/14/
$(document).ready(function() {
var arrValuesForOrder = ["2", "1", "3", "4"];
var ul = $("#boxes"),
items = $("#boxes li.con");
for (var i = arrValuesForOrder[arrValuesForOrder.length - 1]; i >= 0; i--) {
// arrValuesForOrder[i] element to move
// i = index to move element at
ul.prepend(items.get(arrValuesForOrder[i] - 1));
}
$("#boxes").sortable({
handle : '.drag',
update: function() {
var order = $("#boxes").sortable("toArray");
var sorted = [];
$.each(order, function(index, value){
sorted.push(value.match(/box(\d+)/)[1]);
})
alert(sorted);
}
});
});

What grammar is this?

I have to parse a document containing groups of variable-value-pairs which is serialized to a string e.g. like this:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
Here are the different elements:
Group IDs:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
Length of string representation of each group:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
One of the groups:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14 ^VAR1^6^VALUE1^^
Variables:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
Length of string representation of the values:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
The values themselves:
4^26^VAR1^6^VALUE1^VAR2^4^VAL2^^1^14^VAR1^6^VALUE1^^
Variables consist only of alphanumeric characters.
No assumption is made about the values, i.e. they may contain any character, including ^.
Is there a name for this kind of grammar? Is there a parsing library that can handle this mess?
So far I am using my own parser, but due to the fact that I need to detect and handle corrupt serializations the code looks rather messy, thus my question for a parser library that could lift the burden.
The simplest way to approach it is to note that there are two nested levels that work the same way. The pattern is extremely simple:
id^length^content^
At the outer level, this produces a set of groups. Within each group, the content follows exactly the same pattern, only here the id is the variable name, and the content is the variable value.
So you only need to write that logic once and you can use it to parse both levels. Just write a function that breaks a string up into a list of id/content pairs. Call it once to get the groups, and then loop through them calling it again for each content to get the variables in that group.
Breaking it down into these steps, first we need a way to get "tokens" from the string. This function returns an object with three methods, to find out if we're at "end of file", and to grab the next delimited or counted substring:
var tokens = function(str) {
var pos = 0;
return {
eof: function() {
return pos == str.length;
},
delimited: function(d) {
var end = str.indexOf(d, pos);
if (end == -1) {
throw new Error('Expected delimiter');
}
var result = str.substr(pos, end - pos);
pos = end + d.length;
return result;
},
counted: function(c) {
var result = str.substr(pos, c);
pos += c;
return result;
}
};
};
Now we can conveniently write the reusable parse function:
var parse = function(str) {
var parts = {};
var t = tokens(str);
while (!t.eof()) {
var id = t.delimited('^');
var len = t.delimited('^');
var content = t.counted(parseInt(len, 10));
var end = t.counted(1);
if (end !== '^') {
throw new Error('Expected ^ after counted string, instead found: ' + end);
}
parts[id] = content;
}
return parts;
};
It builds an object where the keys are the IDs (or variable names). I'm asuming as they have names that the order isn't significant.
Then we can use that at both levels to create the function to do the whole job:
var parseGroups = function(str) {
var groups = parse(str);
Object.keys(groups).forEach(function(id) {
groups[id] = parse(groups[id]);
});
return groups;
}
For your example, it produces this object:
{
'1': {
VAR1: 'VALUE1'
},
'4': {
VAR1: 'VALUE1',
VAR2: 'VAL2'
}
}
I don't think it's a trivial task to create a grammar for this. But on the other hand, a simple straight forward approach is not that hard. You know the corresponding string length for every critical string. So you just chop your string according to those lengths apart..
where do you see problems?

Resources