OclInEcore: operation return type issue - eclipse

I want to write the following operation in the oclInEcore editor in the context of the "Comp" class, which is supposed to collect the parents of a Comp object to a Set.
operation parents(): Set(Comp)
{
body: self.superComp->union(self.parents());
}
The problem is, that ocl doesn't accept Set(Comp) as return type. However, it accepts Comp[*], but this will end up in an invalid call (Because of the incompatible return types, I suppose...)

The Set(Comp) is indeed invalid. In OCLInEcore the syntax for specifying the return type is different. The thing is that the model structure definitions (classes, features, operations) have nothing to do with OCL itself. It only comes later when you define the actual logic for your invariants, derived features or operation bodies.
The correct way of doing this is following:
operation parents() : Comp[*] { <properties> derived }
The Comp is the return type and the [*] sets the upperBound to -1.
The <properties> is a list of the operation return type properties that will precisely specify wich of the collection class should be used.
Here are the options:
!unique ordered --> Sequence(Comp)
!unique !ordered --> Bag(Comp)
unique !ordered --> Set(Comp)
unique ordered --> OrderedSet(Comp)
For example:
operation parents() : Comp[*] { unique !ordered derived }
will result in the Set(Comp).

I don't know the oclInEcore, but in base ecore you can define an EDataType and set its "Instance Type Name" to the Java return type you want and then use that Data Type on your EOperation. HTH.

Related

NDepend: Find fields that are either a given type or use a given type in their generic parameters

How would I go about using NDepend to not only identify JustMyCode.Fields that are exactly a given type, but also indirectly, i.e. fields like IList<MyType>, IDictionary<int, MyType>, Lazy<T> and all those "nice" generic variants/usages?
Is there any helper method similar to .UsedBy(...) available by any chance that provides such a functionality?
Here is a query to get field typed with String or Int32:
let types = Types.WithFullNameIn(
"System.String",
"System.Int32").ToArray()
from f in Application.Fields
where !f.ParentType.IsEnumeration &&
f.FieldType != null &&
types.Contains(f.FieldType)
select new { f, type =f.FieldType }
For now you cannot detect when a type is used in a generic parameter.

How to enumerate over columns with tokio-postgres when the field types are unknown at compile-time?

I would like a generic function that converts the result of a SQL query to JSON. I would like to build a JSON string manually (or use an external library). For that to happen, I need to be able to enumerate the columns in a row dynamically.
let rows = client
.query("select * from ExampleTable;")
.await?;
// This is how you read a string if you know the first column is a string type.
let thisValue: &str = rows[0].get(0);
Dynamic types are possible with Rust, but not with the tokio-postgres library API.
The row.get function of tokio-postgres is designed to require generic inference according to the source code
Without the right API, how can I enumerate rows and columns?
You need to enumerate the rows and columns, doing so you can get the column reference while enumerating, and from that get the postgresql-type. With the type information it's possible to have conditional logic to choose different sub-functions to both: i) get the strongly typed variable; and, ii) convert to a JSON value.
for (rowIndex, row) in rows.iter().enumerate() {
for (colIndex, column) in row.columns().iter().enumerate() {
let colType: string = col.type_().to_string();
if colType == "int4" { //i32
let value: i32 = row.get(colIndex);
return value.to_string();
}
else if colType == "text" {
let value: &str = row.get(colIndex);
return value; //TODO: escape characters
}
//TODO: more type support
else {
//TODO: raise error
}
}
}
Bonus tips for tokio-postgres code maintainers
Ideally, tokio-postgres would include a direct API that returns a dyn any type. The internals of row.rs already use the database column type information to confirm that the supplied generic type is valid. Ideally a new API uses would use the internal column information quite directly with improved FromSQL API, but a simpler middle-ground exists:-
It would be possible for an extra function layer in row.rs that uses the same column type conditional logic used in this answer to then leverage the existing get function. If a user such as myself needs to handle this kind of conditional logic, I also need to maintain this code when new types are handled by tokio-postgresql, therefore, this kind of logic should be included inside the library where such functionality can be better maintained.

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#

get an element index in ocl collection ? [ocl_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))

Supporting "recursive objects" in lua

I'm fairly new to lua and have the following problem with an assignment from a class:
We currently extend lua to support objects and inheritance. The Syntax for that is
Class{'MyClass',
attribute1 = String,
attribute2 = Number
}
Class{'MySubClass', MyClass,
attribute3 = Number
}
This works perfectly fine. The real problem lies within the next task: We should support "recursive types", that means a call like
Class{'MyClass', attribute = MyClass}
should result in an class with a field of the same type as the class. When this "class-constructor" is called the variable MyClass is nil, thats why the parameter table doesnt't have an entry attribute. How is it possible to access this attribute?
My first thought was using some kind of nil-table which gets returned every time the global __index is called with an unset key. This nil-table should behave like the normal nil, but can be checked for in the "class-constructor". The problem with this approach are comparisons like nil == unknown. This should return true, but as the __eq meta method of the nil-table is never called we cannot return true.
Is there another approach I'm currently just ignoring? Any hint is greatly appreciated.
Thanks in advance.
Edit:
Here the relevant part of the "testfile". The test by which the code is rated in class is another one and gets published later.
three = 3
print( three == 3 , "Should be true")
print( unknown == nil , "Should be true" )
Class{'AClass', name = String, ref = AClass}
function AClass:write()
print("AClass:write(), name of AClass:", self.name)
end
aclass = AClass:create("A. Class")
aclass:write()
Since MyClass is just a lookup in the global table (_G), you could mess with its metatable's __index to return a newly-defined MyClass object (which you would later need to fill with the details).
However, while feasible, such an implementation is
wildly unsafe, as you could end up with an undefined class (or worse, you may end up inadvertantly creating an infinite lookup loop. Trust me, I've been there)
very hard to debug, as every _G lookup for a non-existing variable will now return a newly created class object instead of nil (this problem could somewhat be reduced by requiring that class names start with an uppercase character)
If you go that route, be sure to also override __newindex.
How about providing the argument in string form?
Class{'MyClass', attribute = 'MyClass'}
Detect strings inside the implementation of Class and process them with _G[string] after creating the class
Or alternatively, use a function to delay the lookup:
Class{'MyClass', attribute = function() return MyClass end}