List<dynamic>.Find and List<dynamic>.FindAll - dynamic

I am trying to do this but unable to find a workaround.
I have a list of dynamic objects and its like ObjectList : List<dynamic>
its filled with objects that have a dynamic property LastName.
i am trying to find all elements that have a matching string in the Name property.
var result = mylist.FindAll(e => e.LastName.StartsWith("Mc"));
But when i do so, it says "Expression cannot contain lambda expressions".

you cannot use it like lambda if it dynamic try using it in different style
var result = mylist.FindAll(e => e.LastName.StartsWith("Mc"));
something like this should help
var result=(from c in mylist where c.LastName.StartsWith("Mc") select c).ToList();

Related

HotChocolate: Dynamic schemas and how to update filters accordingly

NOTE: If you do know that the below is not possible, this information is just as valuable.
Im checking out HotChocolate and Ive looked into the dynamic schemas
I have taken the code in your Github-example This works ok. I have extended our Product-type like so:
//Same json as in your Github-sample, new properties are "color" and some more
foreach (var field in type.GetProperty("fields").EnumerateArray())
{
string name = field.GetString();
typeDefinition.Fields.Add(new ObjectFieldDefinition(field.GetString()!, type: TypeReference.Parse("String"), pureResolver: ctx =>
{
var product = ctx.Parent<Product>();
return product.SubTypeSpecific.ContainsKey(name) ? product.SubTypeSpecific[name] : null;
}));
}
now I have "moved out" dynamic properties from a Dictionary (That is a sub-object in my documentDb) to own properties. Works well.
BUT:
How can I extend my ProductFilter in the same fashion?
I would like to extend my current Product-filter so its possible to search on the new dynamic property "color"
getProducts(where : color : {eq :"blue" }}) {...}
I can create new FilterInputDefinition, but not extend existing filter (because there is no FilterInputTypeExtensions.CreateUnsafe()
If I manage to create the new filter, is there any way to update the IQueryable-generation so that the inputed color ("blue")
So the query to my CosmosDb will be created automatically?
Many thanks in advance.

Apache Ignite : Ignite Repository query with "IN" clause, returns no records

I am using Apache Ignite as the back-end data store in a SpringBoot Application.
I have a requirement where I need to get all the entities whose name matches one of the names from a set of names.
Hence i am trying to get it implemented using a #Query configuration and a method named findAllByName(Iterable<String> names)as below:
Here on the Query, I am trying to use the 'IN' clause and want to pass an array of names as an input to the 'IN' clause.
#RepositoryConfig(cacheName = "Category")
public interface CategoryRepository extends IgniteRepository<Category, Long>
{
List<Category> findByName(String name);
#Query("SELECT * FROM Category WHERE name IN ( ? )")
Iterable<Category> findAllByName(Iterable<String> names); // this method always returns empty list .
}
In this the method findAllByName always returns empty list, even when ignite has Categories for which the name field matches the data passed in the query.
I am unable to figure out if there is a problem with the Syntax or the query of the method signature or the parameters.
Please try using String[] names instead for supplying parameters.
UPDATE: I have just checked the source, and we don't have tests for such scenario. It means that you're on uncharted territory even if it is somehow possible to get to work.
Otherwise looks unsupported currently.
I know your question is more specific to Spring Data Ignite feature. However, as an alternate, you can achieve it using the SqlQuery abstraction of Ignite.
You will form your query like this. I have pasted the sample below with custom sql function inSet that you will write. Also, the below tells how this is used in your sql.
IgniteCache<String, MyRecord> cache = this.ignite
.cache(this.environment.getProperty(Cache.CACHE_NAME));
String sql = "from “my-ignite-cache”.MyRecord WHERE
MyRecord.city=? AND inSet(?, MyRecord.flight)"
SqlQuery<String, MyRecord> sqlQuery = new SqlQuery<>(MyRecord.class,
sql);
sqlQuery.setArgs(MyCity, [Flight1, Flight2 ] );
QueryCursor<Entry<String, MyRecord>> resultCursor = cache.query(sqlQuery);
You can iterate the result cursor to do something meaningful from the extracted data.
resultCursor.forEach(e -> {
MyRecord record = e.getValue();
// do something with result
});
Below is the Ignite Custom Sql function which is used in the above Query - this will help in replicating the IN clause feature.
#QuerySqlFunction
public static boolean inSet(List<String> filterParamArgIds, String id) {
return filterParamArgIds.contains(id);
}
And finally, as a reference MyRecord referred above can be defined something like this.
public class MyRecord implements Serializable {
#QuerySqlField(name = "city", index = true)
private String city;
#QuerySqlField(name = "flight", index = true)
private String flight;
}

How to filter text in Scala SQL context data frame based on a list of keywords

I have been trying to filter tweets from a SQL dataframe based on selected hashtags. My code (given below) works when I try to filter tweets for a selected hashtag.
dfs.select(dfs("text"))
.map(r => r.getString(0))
.filter(_.contains("#tweet_of_interest"))
.foreach(println)
However, when I extend my code to filter tweets based on hashtags stored in a list, I get the following error.
dfs.select(dfs("text"))
.map(r => r.getString(0))
.filter(hashtag_list.exists(_.contains))
.foreach(println)
error: missing arguments for method contains in class String; follow
this method with `_' if you want to treat it as a partially applied
function
dfs.select(dfs("text"))
.map(r => r.getString(0))
.filter(konykeywords.exists(_.contains))
.foreach(println)
Can you try this code:
dfs.select(dfs("text")).map(r => r.getString(0)).filter(line => {
hashtag_list.exists(line.contains)
}).foreach(println)
The code you wrote doesn't work like this:
hashtag_list.exists(_.contains) // gives the error: missing arguments for method contains in class String; follow this method with '_' if you want to treat it as a partially applied function.
You have to pass some argument in contains method:
hashtag_list.exists(_.contains("somevalue"))
You can also work directly on your DataFrame, using UDF (User Defined Functions) that work on a whole column.
The first step, is to define a function of type (String => Boolean), that receives a tweet and returns true if it should be included in the final DataFrame:
def myFunc: (String => Boolean) = { t => hashtag_list.exists(t.contains) }
import org.apache.spark.sql.functions._
val myUDF = udf(myFunc)
Then, you can call it directly on the filter method of your DataFrame:
val filteredDF = dfs.filter(myUDF(col("tweets")))
For more information about UDFs, here's a nice article:
http://www.sparktutorials.net/using-sparksql-udfs-to-create-date-times-in-spark-1.5

Get property names present in a breeze entity

After I execute breeze query as shown below:
var breezeQuery = function(){
var query = EntityQuery.from('TableA')
.inlineCount();
function querySuceeded(data) {
//data.results[0] contains the entity
}
manager.executeQuery(query)
.then(querySuceeded)
}
I get the entity in data.results[0] which contains properties as well as other information like entityAspect etc.
How can I get the property names present in a breeze entity ?
Use the MetadataStore. Something like this:
var tableAType = manager.metadataStore.getEntityType("TableA");
var dataProperties = tableAType.dataProperties;
var navigationProperties = tableAType.navigationProperties;
or from an instance of a entity ( not a projection), since every entity will have an 'entityType' property you can also do this:
var tableAType = tableAInstance.entityType;
var dataProperties = tableAType.dataProperties;
var navigationProperties = tableAType.navigationProperties;
Also see: http://www.breezejs.com/sites/all/apidocs/classes/EntityType.html
Object.keys(data.result[0]) is the vanilla JavaScript way to get all properties of the data.result[0] object. Just saying.
Jay's way of course winnows those down to the properties monitored by Breeze, the persisted properties in particular. That's probably what you meant :-)

Using dynamic types with expresso

I would like to use a dynamic value as a parameter.
E.g.
dynamic dyn = new ExpandoObject();
dyn.Foo = "bar";
var bar = new Interpreter().Eval("d.Foo", new Parameter("d", dyn));
Assert.AreEqual("bar", bar.ToString());
But I get an error saying "No property or field 'Foo' exists in type 'ExpandoObject'" ?
Is this supposed to be possible?
Regards, Niels
Unfortunately for now dynamics (ExpandoObject) are not supported. I will consider this feature for the next release.
A possible workaround is to use anonymous objects:
dynamic dyn = new ExpandoObject();
dyn.Foo = "bar";
var bar = new Interpreter().Eval("d.Foo", new Parameter("d", new { Foo = dyn.Foo }));
Consider that in this case the property is evaluated when you create the parameter.
You can also convert a dynamic into an anonymous type (see Cast ExpandoObject to anonymous type) but the result is not very different.
Disclaimer: I'm the creator of Dynamic Expresso library.
Expression Evaluator supports dynamics (ExpandoObject). It supports method calls, property and index accessors, get and set. If you do encounter an error with dynamics please let me know as dynamics is relatively newly supported.