mongodb: IndexKeysBuilder for Array elements without string constants? - indexing

I am trying to eliminate hardcoded property names in my code and stuck with indexes for nested Arrays.
string version looks pretty simple:
DocumentCaollection.EnsureIndex("ChangesList._id");
but i have no idea how to write this with IndexKeysBuilder:
new IndexKeysBuilder<TransactionEntity>().Ascending(x => x.ChangesList. ???? )
For example, this code compiles but fails on runtime:
new IndexKeysBuilder<TransactionEntity>().Ascending(x => x.ChangesList.Select(y => y.Id))
with following exception:
Unable to determine the serialization information for the expression: (TransactionEntity x) => Enumerable.Select(x.ChangesList, (TransactionItem y) => y.Id)

Related

Filter within ErgoScript using Coll

I'd like to use the filter function in Coll. However I'm getting an error that says that there's something wrong with parsing:
Code:
val isNftInDataInputBox: Boolean =
dataInputBox.tokens
.filter(token => token._1 == outProfileBox.R5[Coll[Byte]].get)
.nonEmpty
Error:
Invalid declaration of lambda Ident(token,NoType) => Some(EQ(Select(Ident(token,NoType),_1,None),Select(ApplyTypes(Select(Ident(outProfileBox,NoType),R5,None),Vector(Coll[SByte$])),get,None)))
sigmastate.lang.syntax.ParserException:
line 61: .filter(token => token._1 == outProfileBox.R5[Coll[Byte]].get)
Is Filter allowed in ErgoScript?
Is this the correct documentation for Colls?
https://github.com/ScorexFoundation/sigmastate-interpreter/blob/fada073b82a16a928c457693b888da4c0310aca6/library/src/main/scala/special/collection/impl/CollsImpl.scala
I was able to filter it this way:
val filteredNFTToken: Coll[(Coll[Byte], Long)] = dataInputBox.tokens
.filter{
(token: (Coll[Byte], Long)) => token._1 == outProfileBox.R5[Coll[Byte]].get
}
val isNftInDataInputBox: Boolean = filteredNFTToken.size == 1
However, when I try
filteredNFTToken.NonEmpty
it fails with
Cannot find method 'nonEmpty' in in the object Ident(filteredNFTToken,NoType) of Product type with methods List(SMethod(sigmastate.SCollection$#25a5c8e,size,(Coll[IV]) => SInt$,1,FixedCost(14),MethodIRInfo(None,None,None),Some(OperationInfo(Some(SizeOf$(177)),The size of the collection in elements.,ArrayBuffer(ArgInfo(this,this instance)))),None), SMethod(sigmastate.SCollection$#25a5c8e,getOrElse,[IV](Coll[IV],SInt$,IV) => IV,2,FixedCost(30),MethodIRInfo(Some(<function1>),None,None),Some(OperationInfo(Some(ByIndex$(178)),Return the element of collection if \lst{index} is in range \lst{0 .. size-1},ArrayBuffer(ArgInfo(this,this instance), ArgInfo(index,index of the element of this collection), ArgInfo(default,value to return when \lst{index} is out of range)))),None), SMethod(sigmastate.SCollection$#25a5c8e,map,[IV,OV](Coll[IV],(IV) => OV) => Coll[OV],3,PerItemCost(20,1,10),MethodIRInfo(None,None,None),Some(OperationInfo(Some(MapCollection$(173)), Builds a new collection by applying a function to all elements of this collection.
Returns a new collection of type \lst{Coll[B]} resulting from applying the given function
\lst{f} to each element of this collection and collecting the results.
The documentation for available methods is 1.
The NonEmpty of nonEmpty methods are not available on Coll type.
Note, the names are case sensitive.
So, your solution is the right way to go.

LINQ Does not contain a definition for 'union'

what is wrong with this linq query that show me the error of Does not contain a definition for 'union'
(from rev in db.vM29s
where Years.Contains(rev.FinancialYear) && rev.Exclude=="No"
group rev by new { rev.RevenueCode, rev.FinancialYear } into g
select new
{
Revenuecode = g.Key.RevenueCode,
totalRevenue = g.Sum(x => x.RevenueAmount),
RevenueEnglish = (from a in db.RevenueCodes where a._RevenueCode == g.Key.RevenueCode select a.RevenueEng).FirstOrDefault(),
// MinorCode = (from a in db.MinorCodes where a._MinorCode == g.Key.MinorCode select a.MinorEng),
RevenueDari = (from a in db.RevenueCodes where a._RevenueCode == g.Key.RevenueCode select a.RevenueDari).FirstOrDefault(),
Yearss = g.Key.FinancialYear
}
)
.Union
(from u in db.rtastable
where Years.Contains(u.Year)
group u by new { u.objectcode, u.Year } into g
select new
{
Revenuecode = g.Key.objectcode,
totalRevenue = g.Sum(x => x.amount),
RevenueEnglish = (from a in db.RevenueCodes where a._RevenueCode == g.Key.objectcode select a.RevenueEng).FirstOrDefault(),
// MinorCode = (from a in db.MinorCodes where a._MinorCode == g.Key.MinorCode select a.MinorEng),
RevenueDari = (from a in db.RevenueCodes where a._RevenueCode == g.Key.objectcode select a.RevenueDari).FirstOrDefault(),
Yearss = g.Key.Year
}
)
.ToList();
If you included using System.Linq; and both Anonymous Types have exactly the same property names + property types, then what you did should work.
Yet it does not work. The solution is to check your Anonymous Types for subtle property name differences and/or subtle property type differences.
E.g. even an int vs a smallint or double or decimal will cause this build error:
'System.Collections.Generic.IEnumerable<AnonymousType#1>' does not contain a definition for 'Union' and the best extension method overload 'System.Linq.Queryable.Union(System.Linq.IQueryable, System.Collections.Generic.IEnumerable)' has some invalid arguments
Switching to .Concat() will not fix this: it has the same (obvious) restriction that the types on both sides must be compatible.
After you fix the naming or typing problem, I would recommend that you consider switching to .Concat(). The reason: .Union() will call .Equals() on all objects to eliminate duplicates, but that is pointless because no two Anonymous Objects that were created independently will ever be the same object (even if their contents would be the same).
If it was your specific intention to eliminate duplicates, then you need to create a class that holds your data and that implements .Equals() in a way that makes sense.
You should use Concat or using addRange if the data is allready in memory.

ErrorException [ Notice ]: Undefined variable on an existing variable dynamically built

First of all thanks for your time on my issue.
Second sorry if this is a duplicate, I legit searched for 3 days on and off and didn't find answer to my particular situation.
Visual on the error obtained
This first line transforms an array's values into a string of index(es)
$path = self::extract_path($path);
After extraction $path becomes a string with a format similar to['key1']['key2']
Here I test if one valuable element (ondemand) is found within that Keys string, so far so good.
if( $path !== FALSE && strpos($path, $element) !== FALSE){
$var_dim_str = 'coupon' . $path . '[recurrence]';
As a self-proofing, I hard-coded one of my specific scenario element and it does exist so my issue is not really non-initialization of my variable as most other topic were suggesting.
var_dump($coupon['item']['ondemand']['recurrence']);
My issue lies here, I get "ErrorException [ Notice ]: Undefined variable: coupon[item][ondemand][recurrence]"
$recurrence = $$var_dim_str;
[...]
Here are my var_dump output:
These are my indexes as an array they get extracted to reconstruct the variable's string', I have some variable-dimension arrays that gets called so the dimension depth might not always be of fixed value, hence why I have to dynamically test this.
1- $path, before being extracted
[...]\modules\payment\classes\Helper\Payment.php:290:
array (size=2)
0 => string 'item' (length=4)
1 => string 'ondemand' (length=8)
2- We see here that (['item']['ondemand']['recurrence'] => 3) exists
[...]\modules\payment\classes\Payment\Cart.php:266:
array (size=1)
'item' =>
array (size=3)
'ondemand' =>
array (size=14)
[...]
'recurrence' => string '3' (length=1)
[...]
3- My var_dump above is outputting it properly.
[...]\modules\payment\classes\Payment\Cart.php:270:string '3' (length=1)
**So, my conclusion is that PHP doesn't really appreciate my 'built' variable but there has to be some way to make this logic work... any pointers on this would be really appreciated. **
The issue does lie with $$var_dim_str. What the $$ does is resolve $$variableName to be the variable name contained in $variableName. It basically holds a reference to another variable based on the variable's name. From the PHP site:
A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.
So ...
// some variables
$name = 'Ellan' ;
$site = 'Stack Exchange' ;
$tags = 'PHP-7, Variables' ;
// we want $site
$variableName = 'site' ;
echo $$variableName ;
// we want $tags
$variableName = 'tags' ;
echo $$variableName ;
The code above will produce:
Stack Exchange
PHP-7, Variables
When you assign a value to $var_dim_str:
$var_dim_str = 'coupon' . $path . '[recurrence]';
$var_dim_str does not hold the name of a variable. It contains the a string.
Are you sure you want to use $$ in this instance? Maybe you really want to use:
$recurrence = $var_dim_str;

What return value to use to match two different kinds of Types

I'm using LINQ towards my MSSQL database. I have the TypeOfMetaData-table, the UserMetaData-table and the MetaDataHasType-table that has foreign-keys from the TypeOfMetaData- and the UserMetaData-table. What I need to do a method to get all MetaData and Types and return them. The problem is that I don't know what kind of return value I should use to be able to match the correct rows together.
Thanks for the help,
wardh
You could use an Anonymous Type (var) to store the result:
var result =
yourDataContext
.UserMetaData_Table
.Select(
userMetaData =>
new
{
UserMetaData = userMetaData,
Types = userMetaData.MetaDataHasTypes.Select(types => types.TypeOfMetaData),
})
.ToArray();
If this isn't what you want, could you update you question to with an example of the data context and the classes you have and what you have tried so far.

How do I use Rhino.Mocks.RhinoMocksExtensions.VoidType with lambda Expect?

I get the following error on this line:
session.Expect(s => s.Add("string", null)).IgnoreArguments().Return(SaveMockUser());
cannot convert from 'void' to 'Rhino.Mocks.RhinoMocksExtensions.VoidType'
SaveMockUser is defined as follows
private void SaveMockUser()
{
}
What am I doing wrong?
It's not possible to return a void type. Probably what you want to do is have another expectation that expects that SaveMockUser() is actually called or actually perform the action via a callback - i.e., when you see this function called, then do this.
session.Expect( s => s.Add("string", null) )
.IgnoreArguments()
.WhenCalled( x => SaveMockUser() );
or even better - use the new inline constraints
session.Expect( s => s.Add( Arg<string>.Is.Equal( "string" ), Arg<string>.Is.Anything ) )
.WhenCalled( x => SaveMockUser() );