I have some problem with guava funnel , I read this article https://code.google.com/p/guava-libraries/wiki/HashingExplained and others , but I don't know how I can use funnel when my class contains not only primitive types.
Funnel<Person> personFunnel = new Funnel<Person>() {
#Override
public void funnel(Person person, PrimitiveSink into) {
into
.putInt(person.id)
.putString(person.firstName, Charsets.UTF_8)
.putString(person.lastName, Charsets.UTF_8)
.putInt(birthYear)
//.putObject(myObject,myObjectFunnel);I want to do something like this
}
};
after I need to do like this
HashFunction hf = Hashing.md5();
HashCode hc = hf.newHasher()
.putObject(person, personFunnel)
.hash();
PrimitiveSink class hasn't putObject method , only Hasher class has it.
I can transform myObject to byte array and use putBytes method , but probably somebody knows better approach.
You're right: at the moment, it's not possible to do it following the API chained methods only.
But I see that you have a myObjectFunnel. So why not use it?
What about:
Funnel<Person> personFunnel = new Funnel<Person>() {
#Override
public void funnel(Person person, PrimitiveSink into) {
into
.putInt(person.id)
.putString(person.firstName, Charsets.UTF_8)
.putString(person.lastName, Charsets.UTF_8)
.putInt(birthYear);
myObjectFunnel.funnel(myObject, into);
}
};
Related
I need some help to understand everything correctly.
I want to check a pointer to a abstract class if it is instance of a specific child class.
I have one abstract class "kunde" and two child classes "firmenkunde" and "privatkunde" who inherit the methods of kunde.
In order to search by "int knr" (int customer number) I use as return type a pointer to "kunde".
Within the database class I get back the "kdstatus" and use
kunde * kd = new privatkunde(0);
if the status is PK or new firmenkunde(0) if it would be FK.
The abstract class kunde doesn't have any attribute I could use to save the status.
This way I did hope to be able to ask, if the returned pointer would be an instance of the class privatkunde or firmenkunde. But I did not found any method to do this.
MessageBox::Show(marshal_as<String^>(typeid(kd).name()));
I did ask the typeid name but this only returns "class kunde *" and is not what I want to know.
Is there a way to work around this problem?
You can use typeid as you mentioned. Using the polymorphism, you can write:
kunde * kd = new privatkunde(0);
if(typeid(kd) == typeid(privatkunde))
{
// This is a privatkunde objet
}
See here to have more explanation.
The problem you encounter is that your kunde class is not polymorphic. As commented by #George, see how the virtual methods work.
I hope it can help.
Generally you can use dynamic_cast for this.
An example:
class Parent
{
public:
virtual ~Parent();
virtual void do_thing()= 0;
};
class Child1: public Parent
{
public:
void do_thing() override
{
//...
}
};
class Child2: public Parent
{
public:
void do_thing() override
{
//...
}
};
void use_parent(Parent* p)
{
auto c1_ptr = dynamic_cast<Child1*>(p);
if(c1_ptr != nullptr)
{
// p is a Child1
do_thing_with_child1(c1_ptr);
}
auto c2_ptr = dynamic_cast<Child2*>(p);
if(c2_ptr != nullptr)
{
// p is a Child2
do_thing_with_child2(c2_ptr);
}
}
While this works, it becomes difficult to maintain if you have multiple child classes. You have to remember to add a case for each new child class you define.
A better way to structure something like this would be to use the "Tell, don't ask" concept when designing your object-oriented systems. A great write-up on this concept can be found here.
I can't really understand when to use flatmap instead of map, nor do I find a good example.
Can you come up with a good scenrio to choose flat map over map?
Thanks.
For example, we want to do 2 requests, A and B, over web. However, request B must be requested after request A finishes because request B needs some result of request A. This is a good scenrio of flatMap. The example codes are as follow:
interface Movie {
}
interface UserInfo {
List<Long> getFavoriteMovies();
}
public Observable<UserInfo> requestUserInfo(long userId) {
// ...
}
public Observable<List<Movie>> requestMovieList(List<Long> movieIds) {
// ...
}
public Observable<List<Movie>> requestUserMovieList(long userId) {
return requestUserInfo(userId).flatMap(new Func1<UserInfo, Observable<List<Movie>>>() {
#Override
public Observable<List<Movie>> call(UserInfo user) {
return requestMovieList(user.getFavoriteMovies());
}
});
}
In addition, Ben Christensen's slide has some good examples of RxJava: https://speakerdeck.com/benjchristensen/rxjava-goto-aarhus-2013
I have to implement a Chat module to enable privacy chatting b/w users. I have to do this in Play framework using Scala, Akka and java.net.*
I had got several examples over the net which are demonstrating the use of WebSockets but I didn't got any which can help me implementing Chat module using WebSockets. I have the idea of what i have to do but i am totally confused about what should be the structure of the objects, classes and how Should I start.
Please, if anyone can help me for this or refer me a good article, paper which can help me all the way through the implementation. Thankyou.
I did it in Java. This is what I modified from the exemple :
public class ChatRoom extends UntypedActor {
//Added hashmap to keep references to actors (rooms).
// (might be put in another class)
public static HashMap<String,ActorRef> openedChats=new HashMap<String,ActorRef>();
//Added unique identifier to know which room join
final String chatId;
public ChatRoom(String chatId) {
this.chatId = chatId;
}
public static void join(final User user, final String chatId , WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) throws Exception{
final ActorRef chatRoom;
//Find the good room to bind to in the hashmap
if(openedChats.containsKey(chatId)){
chatRoom = openedChats.get(chatId);
//Or create it and add it to the hashmap
}else{
chatRoom = Akka.system().actorOf(new Props().withCreator(new UntypedActorFactory() {
public UntypedActor create() {
return new ChatRoom(chatId);
}
})
);
openedChats.put(chatId,chatRoom);
}
// Send the Join message to the room
String result = (String)Await.result(ask(chatRoom,new Join(user.getId()+"", out), 10000), Duration.create(10, SECONDS));
// ..... Nothing to do in the rest
It's only the main modifications, you also have to adapt javascript and route file
Feel free to ask questions.
Have a look at the official sample in playframework
https://github.com/playframework/playframework/tree/master/samples/scala/websocket-chat
I read this article from Eclipse wiki (http://wiki.eclipse.org/JDT/FAQ#From_an_IJavaElement_to_its_declaring_ASTNode) but I still can not convert from a IMethod to its corresponding MethodDeclaration.
I have an extension point which adds a popup menu to IMethod objects. Possessing this IMethod object, I want to visit it with an ASTVisitor.
Here is how I'm trying to convert from IMethod to MethodDeclaration
public static MethodDeclaration convertToAstNode(final IMethod method) throws JavaModelException
{
final ICompilationUnit compilationUnit = method.getCompilationUnit();
final ASTParser astParser = ASTParser.newParser( AST.JLS4 );
astParser.setSource( compilationUnit );
astParser.setKind( ASTParser.K_COMPILATION_UNIT );
astParser.setResolveBindings( true );
astParser.setBindingsRecovery( true );
final ASTNode rootNode = astParser.createAST( null );
final CompilationUnit compilationUnitNode = (CompilationUnit) rootNode;
final String key = method.getKey();
final ASTNode javaElement = compilationUnitNode.findDeclaringNode( key );
final MethodDeclaration methodDeclarationNode = (MethodDeclaration) javaElement;
return methodDeclarationNode;
}
What am I missing?
I realize this question is quite old now, but I want to post this solution in case future Googlers happen to stumble upon it :)
The workaround EijiAdachi posted in the comments should work, but there's a more "proper" way to do this that I discovered while searching for a solution.
In order for the ASTNode to correctly resolve the bindings, the contents of the page need to be fully parsed first. This is done via the (somewhat oddly named IMHO) ASTNode.accept(ASTVisitor) method. So if you subclass ASTVisitor, you can override the visit methods for all of the ASTNode types you care about and add them to data structures obtainable after the AST has been fully parsed.
This example will make accessible all of the MethodDeclaration nodes in your CompilationUnit root node (see OP for how to get that via the ASTParser class):
public class MethodVisitor extends ASTVisitor {
private final List <MethodDeclaration> methods = new ArrayList <> ();
#Override
public boolean visit (final MethodDeclaration method) {
methods.add (method);
return super.visit (method);
}
/**
* #return an immutable list view of the methods discovered by this visitor
*/
public List <MethodDeclaration> getMethods () {
return Collections.unmodifiableList (methods);
}
}
Any of the other ASTNode subtypes can be rounded up using the exact same process (you could make separate visitor types or put it all in one).
If anyone is interested, you can look for a more complete example in this tutorial article.
In my API, I'd like to have routes like GET /api/v1/widgets/1,2,3 and GET /api/v1/widgets/best-widget,major-widget,bob-the-widget
public class WidgetsController : MyApiController
{
public ActionResult Show(IEnumerable<int> ids)
{
}
public ActionResult Show(IEnumerable<string> names)
{
}
}
I've got routes set up to get me to the action, but I can't figure out how to turn 1,2,3 into new List<int>(){1, 2, 3} and so on. Of course, I could just take a string and parse it in my action, but I'd like to avoid going that route.
One thing that came to mind was to put something in the OnActionExecuting method, but then I wasn't sure exactly what to put in there (I could hack something together, obviously, but I'm trying to write something reusable.)
The main questions I have are how to know whether I need to do anything at all (sometimes the ValueProviders upstream will have figured everything out), and how to handle figuring out the type to cast to (e.g., how do I know that in this case I need to go to a collection of ints, or a collection of strings, and then how do I do that?)
By the way, I had the idea of implementing a ValueProvider as well, but got lost on similar questions.
I can't figure out how to turn 1,2,3 into new List(){1, 2, 3} and so on.
To avoid polluting each controller action that needs to receive this parameter I would recommend a custom model binder:
public class IdsModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var result = base.BindModel(controllerContext, bindingContext);
var ids = bindingContext.ValueProvider.GetValue("ids");
if (ids != null)
{
return ids.AttemptedValue
.Split(',')
.Select(id => int.Parse(id))
.ToList();
}
return result;
}
}
and then register the model binder in Application_Start:
ModelBinders.Binders.Add(typeof(IEnumerable<int>), new IdsModelBinder());
and finally your controller action might look like this (and from what I can see in your question it already does look like this :-)):
public ActionResult Show(IEnumerable<int> ids)
{
...
}
and the custom model binder will take care for parsing the ids route token to the corresponding IEnumerable<int> value.
You could do the same with the IEnumerable<string> where you would simply remove the .Select clause in the corresponding model binder.
if your URL was
/api/v1/widgets/Show?names=best-widget&names=major-widget&names=bob-the-widget
This would bind neatly by itself :)
No need to override modelbinders in this case.
The querystring-variable names will bind to your Show-method_
public ActionResult Show(IEnumerable<string> names)
Hope this helps!
I'm relatively new to ASP.Net MVC and so I'm not sure if there is an easier way of doing this or not, however my approach would be to do something like the following:
public class WidgetsController : MyApiController
{
public ActionResult Show(string ids)
{
List<int> parsedIds = new List<int>();
foreach (var id in ids.Split(','))
{
parsedIds.Add(int.Parse(id));
}
return Show(parsedIds);
}
private ActionResult Show(List<int> ids);
}
You might also want to add some more sophisticated error handling for cases where the IDs entered can't be parsed, but thats the general approach I would use.