get an element index in ocl collection ? [ocl_Eclipse] - eclipse

i'm working on the following domain :
my domain diagram
i want to express the folowing constraint :
" a succession of two actions of Type Rotate is not allowed "
i tried this declaration but eclipse is not recognizing indexOf(element ) :
class Choreography
{
property actions : Action[+|1] { ordered composes };
attribute name : String[?];
/*Succession of two actions of Type is not permitted */
invariant rotate_succ:
self.actions->asSequence()->forAll(a1:Action,a2:Action
|
a1.oclIsTypeOf(Rotate) and (indexOf(a1)=indexOf(a2)+1) implies
not a2.oclIsTypeOf(Rotate)
)
;
Does anyone have an idea about how to work with the index of a random element from an ocl colletion ?

The
OrderedCollection(T):indexOf(obj : OclAny[?]) : Integer[1]
operation requires an OrderedCollection (Sequence/OrderedSet) as its source and an OclAny as its argument. You have not identified a source so OCL will consider first an implicit iterator leading to an
a1.indexOf(a1)
a2.indexOf(a1)
ambiguity which would be an error if an Action had an indexOf operation. Then it considers an implicit self which also fails since there is no Choreography.indexOf() operation.
I presume you meant
self.actions->indexOf(a1)
etc etc, or more readably put self.actions in a let-variable for multi-use.
(Use of oclIsTypeOf is very rarely right. Use oclIsKindOf unless you have a specific intent.)
(self.actions is already an OrderedCollection so there is no need for the asSequence()).
Your use of indexOf will lead to quadratic performance. Better to use indexes - something like:
let theActions = self.actions in
Sequence{1..theActions->size()-1}->forAll(index |
theActions->at(index).oclIsKindOf(Rotate)
implies not theActions->at(index+1).oclIsKindOf(Rotate))

Related

AnyLogic inject agents from existing population with characteristics

I created a population with objects from a database with individual characteristics.
I am trying that the objects with a specific value are injected into a source for process-modelling.
("ankunftszeit" means "arrival time")
for (mp_lkw l : pop_mp_lkw){
if (l.ankunftszeit == getTime()){
source_mp_lkw.inject(mp_lkw l, 1, false, false);
}
}
But somehow an Error occurs and I cannot find any solution...
It says taht the inject() only accepts integers
The method inject(int) in the type Source<mp_lkw> is not applicable for the arguments (mp_lkw, int, boolean, boolean)
Syntax error on token "l", delete this token
Where is my mistake and how can it be corrected?
Not sure I understand your issue, but if the agents already exist, you shouldn't use a source, instead use an enter block, and then change your code to (even though this code seems like a terrible idea... instead you should use dynamic events but I'm not sure your purpose)
for (mp_lkw l : pop_mp_lkw){
if (l.ankunftszeit == getTime()){
enter.take(l);
}
}

Drools : how to assign value to variable "from" predefined method when using PackageDescr to generate rule?

How can I generate something like this in my rule using PackageDescr ?
$var: Number (doubleValue > 100 ) from myPredefinedFunction()
I tried the following :
PatternDescr pt = new PatternDescr("Number","$var");
RelationalExprDescr ex = new RelationalExprDescr(">", false, null, new ExprConstraintDescr("myPredefinedFunction()"), new ExprConstraintDescr("100"));
pt.addConstraint(ex);
but this is what I get :
$var : Number( myPredefinedFunction() > 100 )
You're trying to set the myPredefinedFuntion() as a constraint. Constraints are the part of the drools declaration between the parentheses, eg. MyObject( foo == "bar" ) ... the foo == "bar" is a constraint.
Instead you need to set the source using the setSource method. This is the 'from' part of the declaration. This method takes a instance of a PatternSourceDescr subclass -- likely a FromDescr for this particular scenario.
(Alternatively, you might need setResource instead of setSource. The problem with using internal-only APIs is that they're not documented and subject to change without notice. I strongly suggest not going down this route.)

How to create a newtype operation in Q#?

I am working with Q# on a generic grover search implementation and I wanted to define a custom Oracle type
newtype ModelOracle = ((Qubit[], Qubit[], Int[], Qubit) => Unit);
// ...
function GroverMaxMatchingOracle(search_set: (Int,Int)[], vertices: Int[], marked_pts: Bool[]): ModelOracle {
return ModelOracle(ApplyMaxMatchingOracle(_,_,_,_,search_set, vertices, marked_pts));
}
that will fit into my model. But when I try to use it (kind of in the same way as they use StateOracle in the DatabaseSearch sample), I get an error saying that the new type ModelOracle is not a valid operation
fail: Microsoft.Quantum.IQSharp.Workspace[0]
QS5021: The type of the expression must be a function or operation type. The given expression is of type OracleHelper.ModelOracle.
What am I getting wrong about the types here?
It looks like you have defined things ok, so it might be that you have to unwrap the user defined type first with the ! operator.
So where you are using it you may have to do something like GroverMaxMatchingOracle!(...)
Another approach could be to name the tuple in your UDT:
newtype ModelOracle = (Apply: (Qubit[], Qubit[], Int[], Qubit) => Unit);
Then wherever you want to use it you can directly used the named item Apply like this: GroverMaxMatchingOracle::Apply(...)
If its helpful, there is a section on user defined types (8.2) in the book #cgranade and I are working on, Learn Quantum Computing with Python and Q#

Getting list of types that are effected by an extension method in cqlinq

How to get the list of types that are extended by a extension method in ndepend cqlinq? Using reflection to code this seems a bit of donkey work where ndepend is already there.
NDepend code model doesn't have a straight way to resolve the method parameter type. So we can come up with a satisfying answer with code query relying on string formatting extended type name, extracted from the method name. But this query is overly complex and there are edge cases where it won't work properly (explained below).
Here is the code query, it runs fast even on large code base thanks to the use of a dictionary:
//
// First let build dicoExtensionMethods
let dicoExtensionMethods =
(from m in Application.Methods
where m.IsExtensionMethod
// extract extended type simple name (with generic parameters like "IEnumerable<String>")
let beginIndex = m.Name.IndexOf("(") + 1
let endIndex = m.Name.IndexOf(',', beginIndex) > 0 ? m.Name.IndexOf(',', beginIndex) : m.Name.IndexOf(")", beginIndex)
let extendedTypeSimpleName1 = m.Name.Substring(beginIndex, endIndex - beginIndex)
// Take care of generic type first char, like "IEnumerable<"
let extendedTypeSimpleName2 = extendedTypeSimpleName1.IndexOf('<') == -1 ? extendedTypeSimpleName1 :
extendedTypeSimpleName1.Substring(0, extendedTypeSimpleName1.IndexOf('<') + 1 )
select new { m, extendedTypeSimpleName2 })
.ToLookup(pair => pair.extendedTypeSimpleName2)
.ToDictionary(g => g.Key, g=> g.Select(p =>p.m))
//
// Second for each type get extension methods from dicoExtensionMethods
from t in Types
// Format type name like "IEnumerable<"
let typeName = !t.IsGeneric ? t.SimpleName : t.Name.Substring(0, t.Name.IndexOf('<') + 1 )
where dicoExtensionMethods.ContainsKey(typeName)
let methods = dicoExtensionMethods[typeName]
select new { t, methods }
As written it is a complex query because of type name formatting, and it works fine most of the time.
However when it comes to extending generic types, it says for example that IEnumerable<T> is extended by both methods that extend IEnumerable<String> and IEnumerable<Int32>. This is acceptable, but it is not 100% correct.
Also if you extend several types with same name but various generic arity (like Func<T1,T2> and Func<T1,T2,T3>), then this code query won't work properly.
The same if you extend several types with same name, declared in different assemblies or namespace (which is a code smell anyway).
Hope this helps!

Populating the list in g.select

I need to programmatically load a list.
Instead of:
<g:select
name="cars"
from="${Car.list()}"
value="${person?.cars*.id}"
optionKey="id"
multiple="true" />
I would like to do it this because, the list is not always coming from the same source
g.select(name : searchfield.fieldName,
class : "fillWidth searchfield",
multiple : "true",
from : ${ searchfield.fieldFrom },
optionKey : searchfield.fieldKey,
optionValue : searchfield.fieldValue)
The from does not load. with the list, I get an error message:
No signature of method: sample.SearchTagLib.$() is applicable for argument types: (sample.SearchTagLib$_getSelectField_closure5) values: [sample.SearchTagLib$_getSelectField_closure5#1187b50] Possible solutions: is(java.lang.Object), any(), use([Ljava.lang.Object;), any(groovy.lang.Closure), wait(), grep()
You don't need the ${} in the from option
g.select(name : searchfield.fieldName,
class : "fillWidth searchfield",
multiple : "true",
from : searchfield.fieldFrom,
optionKey : searchfield.fieldKey,
optionValue : searchfield.fieldValue)
In Groovy code ${} is a way to put Groovy expressions inside double quoted GStrings, if you're not in a GString you can just use the expression directly without wrapping it in ${}.
Edit from your comment
The fieldFrom at this point is a string which would get its value from a database. So the value in the DB is "Car.list()" which in the prototype I need to convert to a bound able or execute-able line of code.
It's not generally recommended to allow your app to execute arbitrary snippets of Groovy code provided by users (for obvious security reasons). As long as the code snippets come from a secure source such as a trusted admin user then fair enough, it is possible using GroovyShell
def from = new GroovyShell().evaluate(searchfield.fieldFrom)
but this is likely to be rather inefficient, creating a new classloader and parsing and compiling a whole Groovy script class every time. If the fieldFrom values are intended to always be pulling something from the database (i.e. they'll always be something like Car.list() or Vehicle.findAllByNumberOfWheelsGreaterThan(2), rather than arbitrary Groovy like [1,2,3]) then it might be better to store HQL expressions in fieldFrom and run them using executeQuery
def from = AnyDomainClass.executeQuery(searchfield.fieldFrom)
(executeQuery is a static GORM method, you need to call it on a specific domain class but it can return results of any type). The HQL equivalent of Car.list() would be "from Car", the equivalent of Vehicle.findAllByNumberOfWheelsGreaterThan(2) would be "from Vehicle where numberOfWheels > 2", etc.
I think you need to use strings as the attribute name:
g.select('name' : searchfield.fieldName,
'class' : "fillWidth searchfield",
'multiple' : "true",
'from' : ${ searchfield.fieldFrom },
'optionKey' : searchfield.fieldKey,
'optionValue' : searchfield.fieldValue)