Using predicates in Alloy - function

I am trying to use two predicates (say, methodsWiThSameParameters and methodsWiThSameReturn) from another one (i.e. checkOverriding) but i receive the following error: "There are no commands to execute". Any clues?
I also tried to use functions but with no success, either due to syntax or to functions do not return boolean values.
They are part of a java metamodel specified in Alloy, as i commented in some earlier questions.
pred checkOverriding[]{
//check accessibility of methods involved in overriding
no c1, c2: Class {
c1=c2.^extend
some m1, m2:Method |
m1 in c1.methods && m2 in c2.methods && m1.id = m2.id
&& methodsWiThSameParameters[m1, m2] && methodsWiThSameReturn[m1, m2] &&
( (m1.acc = protected && (m2.acc = private_ || #(m2.acc) = 0 )) ||
(m1.acc = public && (m2.acc != public || #(m2.acc) = 0 )) ||
(#(m1.acc) = 0 && m2.acc != private_ )
)
}
}
pred methodsWiThSameParameters [first,second:Method]{
m1.param=m2.param || (#(m1.param)=0 && #(m2.param)=0)
}
pred methodsWiThSameReturn [first, second:Method]{
m1.return=m2.return || (#(m1.return)=0 && #(m2.return)=0)
}
Thank you for your response, mr C. M. Sperberg-McQueen, but i think i was not clear enough in my question.
My predicate, say checkOverriding, is being called from a fact like this:
fact chackJavaWellFormednessRules{
checkOverriding[]
}
Thus, i continue not understanding the error: "There are no commands to execute" .

You've defined predicates; they have a purely declarative semantics and they will be true in some subset of instances of the model and false in the complementary subset.
If you want the Analyzer to do anything, you need to give it an instruction; the instruction to search for an instance of a predicate is run. So you'll want to say something like
run methodsWithSameParameters for 3
or
run methodsWithSameParameters for 5
run methodsWithSameReturn for 5
Note that you can have more than one instruction in an Alloy model; the Analyzer lets you tell it which to execute.
[Addendum]
The Alloy Analyzer regards the keywords run and check (and only them) as 'commands'. From your description, it sounds very much as if you don't have any occurrences of those keywords in the model.
If all you want to do is to see some instances of the Alloy model (to verify that the model is not self-contradictory), then the simplest way is to add something like the following to the model:
pred show {}
run show for 3
Or, if you already have a named predicate, you could simply add a run command for that predicate:
run checkOverriding
But without a clause in the model that begins with either run or check, you do not have a 'command' in the model.
You say that you have defined a predicate (checkOverriding) and then specified in a fact that that predicate is always satisfied. This amounts to saying that the predicate checkOverriding is always true (and might just as well be done by making checkOverriding a fact instead of a predicate), but it has a purely declarative meaning, and it does not count as a "command". If you want Alloy to find instances of a predicate, you must use the run command; if you want Alloy to find counter-examples for an assertion, you must use the check command.

Related

What is the technical term for a programming language's operator evaluation order?

Several procedures such as array destructuring in JavaScript or collection manipulation in Python have prompted me to evaluate an object's property or method to check if it even exists before proceeding, often resulting in the following pattern:
var value = collection.length
if value != null {
if value == targetValue {
/* do something */
}
}
In an attempt to make "cleaner" code I want to do something like:
if value != null && value == targetValue {
/* do something */
}
or with a ternary operator:
var value = collection.length != null ? collection.length : 0
However, I'm never sure if the compiler will stop evaluating as soon as it resolves the first comparison to null, or if it'll keep going and produce an error. I can of course do small unit tests to find out but I'd prefer if I knew the right term to look up in any language's documentation. What is this term, or is it perhaps the same in all languages?
This is known as Short Circuit Evaluation . It's quite consistent between languages.
In most languages, && will only evaluate the second argument if the first was true, and || will only evaluate its second if the first was false.

While Iterator in groovy

I'm trying to create a loop to read, for example, 4200 users from 1000 to 1000 but I can't get it to cut when it reaches the end. I tried it with if, for and I couldn't do it.
I have programmed in JAVA but with Groovy I see that the structure is different.
urlUsers = urlUsers.concat("/1/1000");
List<UserConnectorObject> usersList = null;
while({
gesdenResponse = GesdenUtils.sendHttpRequest(urlUsers, "LOOKUP", null,
request.getMetaData()?.getLogin(), request.getMetaData()?.getPassword());
log.info("Users data in JSON: "+gesdenResponse.getOutput())
usersList = GesdenUtils.fromJSON(gesdenResponse.getOutput(), GesdenConstants.USER_IDENTITY_KEY);
usersList.size() == 10;
log.info("List size in JSON "+usersList.size());
}()) continue
Groovy has lots of loop structures, but it is crucial to separate the regular ones (lang built-ins) and the api functions which take closure as an argument
take closure - no plain way to escape
If you want to iterate from A to B users, you can use, for instance,
(10..20).each { userNo -> // Here you will have all 10 iterations
if ( userNo == 5) {
return
}
}
If something outrageous happens in the loop body and you cannot use return to escape, as loop boddy is a closure (separate function) and this resurn just exits this closure. Next iteration will happen just after.
use regular lang built-in loop structures - make use of break/continue
for (int userNo in 1..10) { // Here you will have only 5 iterations
if (userNo == 5) {
break
}
}
It looks like your closure always return falsy because there is no explicit return, and the last statement evaluated is the call to log.info(String) which returns void.
Use an explicit return or move/delete the log statement.

Rails class method scope makes an extra query

I have a relation between two objects. Let's say it like this: Model1 has_many Model2 (That doesn't really matter)
And say, I want to filter-out some of the results:
a = Model1.find(123)
b = a.model2
And now, for example, I want to select only EVEN records (by ID)
If I do following: b.select {|x| x.id % 2 == 0} then it returns all even records as expected. And NO additional database queries created.
But if I define a class method in the Model2:
def self.even_records
select {|x| x.id % 2 == 0}
end
Then, for some magic reason it makes an additional query to database, that looks like it re-instantiated the "b" variable (re-loads the relation):
Model2 Load (0.4ms) SELECT `model2`.* FROM `model2` WHERE `model2`.`model1_id` = 123
Why it behaves so ? Is there any way I can fix it ?
P.S I have no fishy callbacks, like after_find or whatsoever defined in any of models.
ActiveRecord scopes are evaluated lazily, i.e. scope is evaluated when its result is necessary. When you try this code in console, inspect method are called implicitly on every evaluated object, including ActiveRecord::Relation instance returned from
b = a.model2
call. After calling inspect on ActiveRecord::Relation, scope is evaluated and DB query is created since it's necessary to show inspect return value properly.
On the contrary, when you run your code outside rails console,
b = a.model2
won't produce DB query, thus there will probably be only one database query.
The Basic difference between these two is that when you call select method on b which is an array, than it calls the enumerable method select.
b.select {|x| x.id % 2 == 0}
and when you write in a method, it calls the select method of activerecord query interface.
def self.even_records
select {|x| x.id % 2 == 0}
end
BTW Ruby have methods like even? and odd?, so you can directly call them :
even_records = b.select{|x| x.id.even?}
odd_records = b.select{|x| x.id.odd? }
Edit: I found a simple solution for you, you can define a scope in your model Model2 like below,
scope :even_records, -> { where ('id % 2 == 0') }
and now if you will call :
Model2.even_records
you will have your even_records.
Thanks

Creating complex XPQuery - LINQ to SQL with nested lists

any hint on what's wrong with the below query?
return new ItemPricesViewModel()
{
Source = (from o in XpoSession.Query<PRICE>()
select new ItemPriceViewModel()
{
ID = o.ITEM_ID.ITEM_ID,
ItemCod = o.ITEM_ID.ITEM_COD,
ItemModifier = o.ITEM_MODIFIER_ID.ITEM_MODIFIER_COD,
ItemName = o.ITEM_ID.ITEM_COD,
ItemID = o.ITEM_ID.ITEM_ID,
ItemModifierID = o.ITEM_MODIFIER_ID.ITEM_MODIFIER_ID,
ItemPrices = (from d in o
where d.ITEM_ID.ITEM_ID == o.ITEM_ID.ITEM_ID && d.ITEM_MODIFIER_ID.ITEM_MODIFIER_ID == o.ITEM_MODIFIER_ID.ITEM_MODIFIER_ID
select new Price()
{
ID = o.PRICE_ID,
PriceList = o.PRICELIST_ID.PRICELIST_,
Price = o.PRICE_
}).ToList()
}).ToList()
};
o in subquery is in read and I got the message "Could not find an implementation of the query pattern for source type . 'Where' not found."
I would like to have distinct ItemID, ItemModifier: should I create a custom IEqualityComparer to do it?
Thank you!
It seems like XPO it's not able to respond to this scenario. For reference this is what you could do with DbContext.
It sounds like maybe you want a GroupBy. Try something like this.
var result = dbContext.Prices
.GroupBy(p => new {p.ItemName, p.ItemTypeName)
.Select(g => new Item
{
ItemName = g.Key.ItemName,
ItemTypeName = g.Key.ItemTypeName,
Prices = g.Select(p => new Price
{
Price = p.Price
}
).ToList()
})
.Skip(x)
.Take(y)
.ToList();
Probable cause
In general, XPO does not support "free joins" in most of the cases. It was explicitelly written somewhere in their knowledgebase or Q/A site. If I hit that article again, I'll include a link to it.
In your original code example, you were trying to perform a "free join" in the INNER query. The 'WHERE' clause was doing a join-by-key, probably navigational, but also it contained an extra filter by "modifier" which probably is not a part of the definition of the relation.
Moreover, the query tried to reuse the IQueryable<PRICE> o in the inner query - what actually seems somewhat supported by XPO - but if you ever add any prefiltering ('where') to the toplevel 'o', it would have high odds of breaking again.
The docs state that XPO supports only navigational joins, along paths formed by properties and/or xpcollections defined in your XPObjects. This applies to XPO as whole, so XPQuery too. All other kinds of joins are called "free joins" and either:
are silently emulated by XPO by fetching related objects, extracting key values from them and rewriting the query into a multiple roundtrips with a series of partial queries that fetch full objects with WHERE-id-IN-(#p0,#p1,#p2,...) - but this happens only in the some simpliest cases
or are "not fully supported", meaning they throw exceptions and require you to manually split the query or rephrase it
Possible direct solution schemes
If ITEM_ID is a relation and XPCollection in PRICE class, then you could rewrite your query so that it fetches a PRICE object then builds up a result object and initializes its fields with PRICE object's properties. Something like:
return new ItemPricesViewModel()
{
Source = (from o in XpoSession.Query<PRICE>().AsEnumerable()
select new ItemPriceViewModel()
{
ID = o.ITEM_ID.ITEM_ID,
ItemCod = o.ITEM_ID.ITEM_COD,
....
ItemModifierID = o.ITEM_MODIFIER_ID.ITEM_MODIFIER_ID,
ItemPrices = (from d in o
where d.ITEM_ID.ITEM_ID == ....
select new Price()
.... .... ....
};
Note the 'AsEnumerable' that breaks the query and ensures that PRICE objects are first fetched instead of just trying to translate the query. Very probable that this would "just work".
Also, splitting the query into explicit stages sometimes help the XPO to analyze it:
return new ItemPricesViewModel()
{
Source = (from o in XpoSession.Query<PRICE>()
select new
{
id = o.ITEM_ID.ITEM_ID,
itemcod = o.ITEM_ID.ITEM_COD,
....
}
).AsEnumerable()
.Select(temp =>
select new ItemPriceViewModel()
{
ID = temp.id
ItemCod = temp.itemcod,
....
ItemPrices = (from d in XpoSession.Query<PRICE>()
where d.ITEM_ID.ITEM_ID == ....
select new Price()
.... .... ....
};
Here, note that I first fetch the item-data from server, and then conctruct the item on the 'client', and then build the required groupings. Note that I could not refer to the variable o anymore. In these precise case and examples, unsuprisingly, the second one (splitted) would be probably even slower than the first one, since it would fetch all PRICEs and then refetch the groupings through additional queries, while the first one would just fetch all PRICEs and then would calculate the groups in-memory basing on the PRICEs already fetched. This is not an a sideeffect of my laziness, but it is a common pitfall when rewriting the LINQ queries, so I included it as a warning :)
Both of these code examples are NOT RECOMMENDED for your case, as they would probably have very poor performace, especially if you have many PRICEs in the table, which is highly likely. I included them to present as only an example of how you could rewrite the query to siplify its structure so the XPO can eat it without choking. However, you have to be really careful and pay attention to little details, as you can very easily spoil the performance.
observations and real solution
However, it is worth noting that they are not that much worse than your original query. It was itself quite poor, since it tried to perform something near O(N^2) row-fetches from the table just to perform to group te rows by "ITEM_ID" and then formatting the results as separate objects. Properly done, it would be something like O(N lg N)+O(N), so regardless of being supported or not, your alternate attempt with GroupBy is surely a much better approach, and I'm really glad you found it yourself.
Very often when you are trying to split/simplify the XPQuery expressions as I did above, you implicitely rethink the problem and find an easier and simplier way to express the query that was initially not-supported or just were crashing.
Unfortunatelly, your query was in fact quite simple. For a really complex queries that cannot be "just rephrased", splitting into stages and making some of the join-filter work at 'client' is unavoidable.. But again, doing them on XPCollections or XPViews with CritieriaOperators is impossible too, so either we have to bear with it or use plain direct handcrafted SQL..
Sidenote:
Whole XPO has problems with "free joins", they are "not fully supported" not only in XPQuery, but also there's not much for them in XPCollection, XPView, CriteriaOperators, etc, too. But, it is worth noting that at least in "my version" of DX11, the XPQuery has very poor LINQ support at all.
I've hit many cases where a proper LINQ query was:
throwing "NotSupportedException", mostly in FreeJoins, but also very often with complex GroupBy or Select-with-Projection, GroupJoin, and many others - sometimes even Distinct(!) seemed to malfunction
throwing "NullReferenceExceptions" at some proper type conversions (XPO tried to interprete a column that held INT/NULL as an object..), often I had to write some completely odd and artificial expressions like foo!=null && foo.bar!=123 instead of foo = 123 despite the 'foo' being an public int Foo {get;set;}, all because the DX could not cope properly with NULLs in the database (because XPO created nullable-INT column for this property.. but that's another story)
throwing other random ArgumentException/InvalidOperation exceptions from other constructs
or even analyzing the query structure improperly, for example this one is usually valid:
session.Query<ABC>()
.Where( abc => abc.foo == "somefilter" )
.Select( abc => new { first = abc, b = abc } )
.ToArray();
but things like this one usually throws:
session.Query<ABC>()
.Select( abc => new { first = abc, b = abc } )
.Where ( temp => temp.first.foo == "somefilter" )
.ToArray();
but this one is valid:
session.Query<ABC>()
.Select( abc => new { first = abc, b = abc } )
.ToArray()
.Where ( temp => temp.first.foo == "somefilter" )
.ToArray();
The middle code example usually throws with an error that reveals that XPO layer were trying to find ".first.foo" path inside the ABC class, which is obviously wrong since at that point the element type isn't ABC anymore but instead a' anonymous class.
disclaimer
I've already noted that, but let me repeat: these observations are related to DX11 and most probably also earlier. I do not know what of that was fixed in DX12 and above (if anything at all was!).

Using variable within a literal

In my code I need to declare notationArr1 but I'm getting this error: Error #1010: A term is undefined and has no properties.
if ((notationArr[1].length == 2) && ((notationArr[1].charCodeAt(0) >= 97) && notationArr[1].charCodeAt(0) <= 104) && ((notationArr[1].charCodeAt(1) >= 49) && notationArr[1].charCodeAt(1) <= 56)) {
if (pieces.d3.man == "") {
pieces.notationArr[1].man.y = pieces.d4.y;
}
}
Here, pieces is an object.
Edit: More code: http://sudrap.org/paste/text/44915/
One of the many variables in your little code piece was not properly declared and/or initialized. You can only access properties or methods (every time you write something.something, that's the part after the .) on existing Objects, but not if the variable you are trying to access contains null.
EDIT
Having read your longer code piece, there could be several null variables, but your problem is probably what #AsTheWormTurns mentioned in his comment above:
pieces.notationArr[1].man
will try to access an array called notationArr that is a member of pieces, instead of using an evaluation of the content of notationArr[1] to find out which member of pieces to access. It should be:
pieces[notationArr[1]].man