I have a lambda expression like below. What I want to ask is Is there any easy way or best practice for the casting the lambda parameter(x) to String?
Optional.ofNullable(result).isPresent( x-> {
String value = (String) x;
});
When I try to change input type like
String value = (String) x;
I am getting below error;
Inconvertible types; cannot cast the lambda parameter to java.lang.String
You could do a safe casting:
Optional.of(result)
.filter(String.class::isInstance) // verify that Object is a String
.map(String.class::cast) // safely cast to String
.ifPresent( input-> {
// now input is a String
});
Related
I have a reflect.Value type of data and I want to check if the value can be convert to uint or not.
this is just an example hope you guys get the idea
var myVal = new(reflect.Value)
if myVal.CanConvert(uint) { // this doesn't work
// do stuf...
}
I dont know what I have to pass as the argument of CanConvert()
The argument to the CanConvert method is a reflect.Type. Use the reflect.TypeOf function to get a reflect.Type from a value of the type.
if myVal.CanConvert(reflect.TypeOf(uint(0)) {
// do stuff...
}
I have the following enum declared which using a string as its underlying value:
enum IssueType : string {
STUDENT_LEAVING = "leaving",
STUDENT_CONFLICT = "conflict",
NEEDS_ARCHIVE = "archive",
OTHER = "other"
}
I want to be able to do the following:
string s = "conflict";
IssueType type = std.conv.to!IssueType(s);
Currently, it is only possible to convert from a string to the enum by providing a case-sensitive match for one of the enum value names, like in this case the string "STUDENT_CONFLICT" would be accepted, while I want "conflict" to be accepted.
Simply cast the string to the enum type.
IssueType type = cast(IssueType)s;
How to send message type as object in ProtoBuf - Proto3 Syntax?
I want to transfer object instead of string or number.
Example
{
name: 'One',
date: 'date',
some: 'some',
...
...
}
syntax = "proto3";
package db;
service Proxy
{
rpc myFunction(Request) returns (Response);
}
message Request
{
string name = 1;
}
message Response
{
object keyvalue = 1;
}
Here, I am getting error
throw Error("no such Type or Enum '" + path + "' in " + this);
^
Error: no such Type or Enum 'object' in Type
--
Workaround
I can convert it to string in server side, and then I can JSON.parse() at client.
But I want to know, if there any better way to do it.
protocol-buffer does not support the object data type!
But you can emulate your data as hierarchically by using protocol buffer message type itself.
syntax = "proto3";
package db;
service Proxy
{
rpc myFunction(Request) returns (Response);
}
message Request
{
string name = 1;
}
message Response
{
message obj {
string key1 = 1;
string key2 = 2
}
obj keyvalue = 1; // Here you have created your own type obj.
}
In the above example, you can see that the Response message now has "keyvalue" field of type obj(which is a custom type you have just built).
Now you will pass Object in a callback from the server instead of primitive type.
callback(null, { keyvalue: { key1: "value1", key2: "value2" } });
Let's say if keys are unknown to you but key/value pair data type is same and known to you then, in this case, you can use
map<type, type>
message Response
{
map<string, string> keyvalue = 1;
}
callback(null, { keyvalue: { "key1": "value1", "key5": "value2" } });
References:-
https://developers.google.com/protocol-buffers/docs/proto3#other
https://developers.google.com/protocol-buffers/docs/proto#scalar
https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Struct
Depending on what you're trying to accomplish, you can likely use one of three types.
The bytes type represents an arbitrary string of bytes. You can choose to encode your types in anyway you feel appropriate.
The any type represents an arbitrary protobuf message, allowing the client or server to encode non-predefined messages. This is a string of bytes, with a unique identifier per message type and language implementations will have ways to unpack the message.
You mention using Javascript. You could likely define a Javascript object message using a combination of oneof for the basic types and map for object types.
If all of the keys and values you want to send have the same type, you can use a map type. Your example shows string keys and string values, so that could use the type map<string, string>.
If you want to send arbitrary object data with similar structure to JSON objects, you can use the google.protobuf.Struct message type.
Currently I had integrate LUIS with Bot Framework v4.
When I search for result match with Intent,
the Bot return me with this Error:
Error : Unable to cast object of type ‘System.String’ to type ‘AuthBotES.ReturnIntents’.
My Source code as below:
if (stepContext.Result != null)
{
var result = (ReturnIntents)stepContext.Result;
var msg = $"{result}";
await stepContext.Context.SendActivityAsync(MessageFactory.Text(msg), cancellationToken);
}
and my ReturnIntents classes.
public class ReturnIntents
{
public string Intent { get; set; }
public double Score { get; set; }
public string Entities { get; set; }
}
A few issues here:
The first code block you posted looks to be for handling the result of a dialog, not for processing a LUIS result.
The cast from string to ReturnIntents will always fail.
Even if your cast of stepContext.Result to ReturnIntents did work, your msg variable would only contain namespace.to.class.ReturnIntents (the string representation of the object type, not the string representation of the objects properties.
Your msg variable is redundant.
I will address these in the order that they occur.
1 - Incorrect code block
This block of code looks suspiciously like code used to process a dialog and here e.g.:
var result = (bool)stepContext.Result;
Rather than the code for handling a LUIS result e.g.:
var dispatchResult = await cognitiveModels.DispatchService.RecognizeAsync(dc.Context, CancellationToken.None);
2 - Casting error
The error is telling you that it doesn't know how to convert a string object to a ReturnIntents object. To convert the string to your object you could use a couple of methods:
Use the NewtonSoft.Json NuGet package to allow you to turn the JSON string into your object as explained here.
2) A user defined type conversion as detailed in the official docs here and explained in this answer.
This error is a red herring in terms of your solution because I believe you're accidentally copied in the wrong block of code.
3 - Incorrect ToString behaviour
To get the string value of a ReturnIntents you will need to override the ToString method for the class and write your own custom implementation.
4 - Redundant cast
This:
// We know that this cast fails, and that stepContext.Result is a string
var result = (ReturnIntents)stepContext.Result;
// This will only return <namespace.path>.ReturnIntents (if the cast above works)
var msg = $"{result}";
// Passing in message msg isn't required, we can just pass in stepContext.Result
await stepContext.Context.SendActivityAsync(MessageFactory.Text(msg), cancellationToken);
Becomes:
var result = stepContext.Result;
await stepContext.Context.SendActivityAsync(MessageFactory.Text(result), cancellationToken);
So what I actually think you actually want is the following:
var dispatchResult = await cognitiveModels.DispatchService.RecognizeAsync<ReturnIntents>(dc.Context, CancellationToken.None);
Which will send the user's input off to LUIS, and deserialize the response into a ReturnIntents object.
Edit to provide solution to the OP
The ExecuteLuisQuery method called here, and defined here returns a ReturnIntents object.
This object is passed as an option to the ReturnIntentDialog here. Because this comes through as an instance of the object type you have a few options inside your FinalStepAsync method here to turn your options object into a ReturnIntents object.:
Casting
ReturnIntents returnIntents = null;
if (stepContext.Options is ReturnIntents)
{
returnIntents = (ReturnIntents)stepContext.Options;
}
Deserializing
using Newtonsoft.Json;
ReturnIntents returnIntents = null;
if (stepContext.Options is ReturnIntents)
{
returnIntents = JsonConvert.DeserializeObject<ReturnIntents>(JsonConvert.SerializeObject(stepContext.Options));
}
Currently I am using expression builder for dynamic query generation.
I have created dynamic expressions for int, date time, and string operators. Now I am stuck at one point .
I want to compare month part of datetime through expression.
We are passing property of datetime and want to create expression for month of that property.
Code:
public static Expression GetDynamicquery<TSource>(
string property, object value, ParameterExpression p)
{
var propertyReference = Expression.Property(p, property);
var constantReference = Expression.Constant(value);
var expression = Expression.Equal(propertyReference, constantReference);
MethodInfo method = null;
return Expression.LessThanOrEqual(propertyReference, constantReference);
}
Here property is name of property which I am passing into Tsource.
p is parameter expression of type Tsource.
I want result like all birthdate of this month.
You can use
Expression.PropertyOrField method for that.
Not sure it would work with entity framework query though.
http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.propertyorfield(v=vs.110).aspx
Update
For entity framework you can use SqlFunctions.DatePart method.
http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions(v=vs.110).aspx
You would need an Expression.Call to represent that as an expression.
http://msdn.microsoft.com/en-us/library/bb349020(v=vs.110).aspx
I got answer of my question. What I did is like....
Code:
public static Expression GetDynamicquery<TSource>(
string property, object value, ParameterExpression p)
{
var propertyReference = Expression.Property(p, property);
propertyReference = Expression.Property(propertyReference, "Year");
var constantReference = Expression.Constant(value);
return Expression.Equal(propertyReference, constantReference);
}
Here first property reference will give datetime expression.
And again using that expression we can go one step inside and can access year property.
Same thing we can do for month.