EzDevInfo.com

dispatch

Dispatch is a PHP 5.4+ micro-framework.

An internal error occurred during: "JDI Event Dispatch" java.lang.NullPointerException

I have my java applet codee,I am trying to debug using eclipse Indigo EE. I am trying to debug on remote using debug configuration and port. When I try to execute the application, it gives always an error message,

An internal error occurred during: "JDI Event Dispatch" java.lang.NullPointerException.

and control is not stopping in the break point.

Please help.

Regards, KSAT


Source: (StackOverflow)

How to properly add and use D3 Events?

I'm having trouble understanding using D3 events and dispatch functions. I have a chart example that I've been working on called: "Vertical Bar Charts With Legends."

Drawing the charts and the legends was easy enough but I'd like to add the ability to highlight each bar as I mouseover its correlating text legend, located to the right of the chart.

I've read through all of the event documentation and even looked at a number of examples, most of which are pretty complicated, but I seem to be missing something. Would anyone know how to best accomplish the text legend mouseover functionality that dispatches events to automatically change colors of the corresponding vertical bars?


Source: (StackOverflow)

Advertisements

CLR implementation of virtual method calls to interface members

Out of curiosity: how does the CLR dispatch virtual method calls to interface members to the correct implementation?

I know about the VTable that the CLR maintains for each type with method slots for each method, and the fact that for each interface it has an additional list of method slots that point to the associated interface method implementations. But I don't understand the following: how does the CLR efficiently determine which interface method slot list to pick from the type's VTable?

The article How the CLR Creates Runtime Objects talks about a process-level mapping table IVMap indexed by interface ID. Does this mean that all types in the same process have the same pointer to the same IVMap?

It also states that:

If MyInterface1 is implemented by two classes, there will be two entries in the IVMap table. The entry will point back to the beginning of the sub-table embedded within the MyClass method table.

How does the CLR know which entry to pick? Does it do a linear search to find the entry that matches the current type? Or a binary search? Or some kind of direct indexing and have a map with possibly many empty entries in it?

I've also read the chapter on Interfaces in CLR via C# 3rd edition but it does not talk about this. Therefore, the answers to this other question do not answer my question.


Source: (StackOverflow)

dispatching S4 methods with an expression as argument

I'm trying to convince an S4 method to use an expression as an argument, but I always get an error returned. A trivial example that illustrates a bit what I'm trying to do here :

setGeneric('myfun',function(x,y)standardGeneric('myfun'))

setMethod('myfun',c('data.frame','expression'),
          function(x,y) transform(x,y) )

If I now try :

> myfun(iris,NewVar=Petal.Width*Petal.Length)
Error in myfun(iris, NewVar = Petal.Width * Petal.Length) : 
  unused argument(s) (NewVar = Petal.Width * Petal.Length)

> myfun(iris,{NewVar=Petal.Width*Petal.Length})
Error in myfun(iris, list(NewVar = Petal.Width * Petal.Length)) : 
 error in evaluating the argument 'y' in selecting a method for 
 function 'myfun': Error: object 'Petal.Width' not found

It seems the arguments are evaluated in the generic already if I understand it right. So passing expressions down to methods seems at least tricky. Is there a possibility to use S4 dispatching methods using expressions?


edit : changed to transform, as it is a better example.


Source: (StackOverflow)

Why virtual function call is faster than dynamic_cast?

I wrote a simple example, which estimates average time of calling virtual function, using base class interface and dynamic_cast and call of non-virtual function. Here is it:

#include <iostream>
#include <numeric>
#include <list>
#include <time.h>

#define CALL_COUNTER (3000)

__forceinline int someFunction()
{
  return 5;
}

struct Base
{
  virtual int virtualCall() = 0;
  virtual ~Base(){};
};

struct Derived : public Base
{
  Derived(){};
  virtual ~Derived(){};
  virtual int virtualCall(){ return someFunction(); };
  int notVirtualCall(){ return someFunction(); };
};


struct Derived2 : public Base
{
  Derived2(){};
  virtual ~Derived2(){};
  virtual int virtualCall(){ return someFunction(); };
  int notVirtualCall(){ return someFunction(); };
};

typedef std::list<double> Timings;

Base* createObject(int i)
{
  if(i % 2 > 0)
    return new Derived(); 
  else 
    return new Derived2(); 
}

void callDynamiccast(Timings& stat)
{
  for(unsigned i = 0; i < CALL_COUNTER; ++i)
  {
    Base* ptr = createObject(i);

    clock_t startTime = clock();

    for(int j = 0; j < CALL_COUNTER; ++j)
    {
      Derived* x = (dynamic_cast<Derived*>(ptr));
      if(x) x->notVirtualCall();
    }

    clock_t endTime = clock();
    double callTime = (double)(endTime - startTime) / CLOCKS_PER_SEC;
    stat.push_back(callTime);

    delete ptr;
  }
}

void callVirtual(Timings& stat)
{
  for(unsigned i = 0; i < CALL_COUNTER; ++i)
  {
    Base* ptr = createObject(i);

    clock_t startTime = clock();

    for(int j = 0; j < CALL_COUNTER; ++j)
      ptr->virtualCall();


    clock_t endTime = clock();
    double callTime = (double)(endTime - startTime) / CLOCKS_PER_SEC;
    stat.push_back(callTime);

     delete ptr;
  }
}

int main()
{
  double averageTime = 0;
  Timings timings;


  timings.clear();
  callDynamiccast(timings);
  averageTime = (double) std::accumulate<Timings::iterator, double>(timings.begin(), timings.end(), 0);
  averageTime /= timings.size();
  std::cout << "time for callDynamiccast: " << averageTime << std::endl;

  timings.clear();
  callVirtual(timings);
  averageTime = (double) std::accumulate<Timings::iterator, double>(timings.begin(), timings.end(), 0);
  averageTime /= timings.size();
  std::cout << "time for callVirtual: " << averageTime << std::endl;

  return 0;
}

It looks like callDynamiccast takes almost two times more.

time for callDynamiccast: 0.000240333

time for callVirtual: 0.0001401

Any ideas why does it?

EDITED: object creation is made in separete function now, so the compler does not know it real type. Almost the same result.

EDITED2: create two different types of a derived objects.


Source: (StackOverflow)

How to convert dispatch_data_t to NSData?

Is this the right way?

// convert
const void *buffer = NULL;
size_t size = 0;
dispatch_data_t new_data_file = dispatch_data_create_map(data, &buffer, &size);
if(new_data_file){ /* to avoid warning really - since dispatch_data_create_map demands we care about the return arg */}

NSData *nsdata = [[NSData alloc] initWithBytes:buffer length:size];

// use the nsdata... code removed for general purpose

// clean up
[nsdata release];
free(buffer); // warning: passing const void * to parameter of type void *

It is working fine. My main concern is memory leaks. Leaking data buffers is not fun. So is the NSData, the buffer and the dispatch_data_t new_data_file all fine?

From what I can read on http://opensource.apple.com/source/libdispatch/libdispatch-187.7/dispatch/data.c it seems the buffer is DISPATCH_DATA_DESTRUCTOR_FREE. Does that mean it is my responsibility to free the buffer?


Source: (StackOverflow)

c# Generic overloaded method dispatching ambiguous

I just hit a situation where a method dispatch was ambiguous and wondered if anyone could explain on what basis the compiler (.NET 4.0.30319) chooses what overload to call

interface IfaceA
{

}

interface IfaceB<T>
{
    void Add(IfaceA a);
    T Add(T t);
}

class ConcreteA : IfaceA
{

}

class abstract BaseClassB<T> : IfaceB<T>
{
    public virtual T Add(T t) { ... }
    public virtual void Add(IfaceA a) { ... }
}

class ConcreteB : BaseClassB<IfaceA>
{
    // does not override one of the relevant methods
}

void code()  
{
    var concreteB = new ConcreteB();

    // it will call void Add(IfaceA a)
    concreteB.Add(new ConcreteA());
}

In any case, why does the compiler not warn me or even why does it compile? Thank you very much for any answers.


Source: (StackOverflow)

AS3 - Event listener that only fires once

I'm looking for a way to add an EventListener which will automatically removes itself after the first time it fires, but I can't figure a way of doing this the way I want to.

I found this function (here) :

public class EventUtil
{
    public static function addOnceEventListener(dispatcher:IEventDispatcher,eventType:String,listener:Function):void
    {
         var f:Function = function(e:Event):void
         {
              dispatcher.removeEventListener(eventType,f);
              listener(e);
          }
          dispatcher.addEventListener(eventType,f);
    }
}


But instead of having to write :

EventUtil.addOnceEventListener( dispatcher, eventType, listener );

I would like to use it the usual way :

dispatcher.addOnceEventListener( eventType, listener );


Has anybody got an idea of how this could be done?
Any help would be greatly apprecitated.


(I know that Robert Penner's Signals can do this, but I can't use them since it would mean a lot of code rewriting that I can't afford for my current project)


Source: (StackOverflow)

How do I dispatch to a method based on a parameter's runtime type in C# < 4?

I have an object o which guaranteed at runtime to be one of three types A, B, or C, all of which implement a common interface I. I can control I, but not A, B, or C. (Thus I could use an empty marker interface, or somehow take advantage of the similarities in the types by using the interface, but I can't add new methods or change existing ones in the types.)

I also have a series of methods MethodA, MethodB, and MethodC. The runtime type of o is looked up and is then used as a parameter to these methods.

public void MethodA(A a) { ... }
public void MethodB(B b) { ... }
public void MethodC(C c) { ... }

Using this strategy, right now a check has to be performed on the type of o to determine which method should be invoked. Instead, I would like to simply have three overloaded methods:

public void Method(A a) { ... } // these are all overloads of each other
public void Method(B b) { ... }
public void Method(C c) { ... }

Now I'm letting C# do the dispatch instead of doing it manually myself. Can this be done? The naive straightforward approach doesn't work, of course:

Cannot resolve method 'Method(object)'. Candidates are:

  • void Method(A)
  • void Method(B)
  • void Method(C)

Source: (StackOverflow)

How can I implement a dynamic dispatch table in C

First of all, I understand how to implement a dispatch table using function pointers and a string or other lookup, that's not the challenge.

What I'm looking for is some way to dynamically add entries to this table at compile time.

The type of code structure I'd hope for is something like:

Strategy.h - contains function definition for the dispatcher and dispatch table definition Strategy.c - contains code for dispatcher

MyFirstStrategy.c - includes Strategy.h and provides one implementation of the strategy MyOtherStrategy.c - includes Strategy.h and provides a second implementation of the stratgy

The idea is that the code to insert function pointers and strategy names into the dispatch table should not live in Strategy.c but should be in the individual strategy implementation files and the lookup table should be somehow dynamically constructed at compile time.

For a fixed size dispatch table, this could be managed as below but I want a dynamically sized table, I don't want the Strategy.c implementation to have to include all of the header files for the implementations and I'd like the dispatch table to be constructed at compile time, not run time.

Fixed Size Example

Strategy.h

typedef void strategy_fn_t(int);
typedef struct {
    char           *strategyName;
    strategy_fn_t  *implementation;
} dispatchTableEntry_t;

MyFirstStrategy.h

#include "Strategy.h"

void firstStrategy( int param );

MyOtherStrategy.h

#include "Strategy.h"

void otherStrategy( int param );

Strategy.c

#include "Strategy.h"
#include "MyFirstStrategy.h"
#include "MyOtherStrategy.h"

dispatchTableEntry_t dispatchTable[] = {
    { "First Strategy", firstStrategy },
    { "Other Strategy", otherStrategy }
};
int numStrategies = sizeof( dispatchTable ) / sizeof(dispatchTable[0] );

What I really want is some preprocessor magic which I can insert into the strategy implementation files to handle this automatically e.g.

MyFirstStrategy.c

#include "Strategy.h"

void firstStrategy( int param );

ADD_TO_DISPATCH_TABLE( "First Strategy", firstStrategy );

Any thoughts ?


Source: (StackOverflow)

Is this design using dynamic okay?

I've got a list of different jobs to process in my application. I'm toying with a design which uses different types to represent different types of job - this is natural because they have different properties and so on. For processing I was thinking about using the dynamic keyword in C# as per the code below.

abstract class Animal {}    
class Cat : Animal {} 
class Dog : Animal {}

class AnimalProcessor
{
    public void Process(Cat cat)
    {
        System.Diagnostics.Debug.WriteLine("Do Cat thing");
    }

    public void Process(Dog dog)
    {
        System.Diagnostics.Debug.WriteLine("Do Dog thing");
    }

    public void Process(Animal animal)
    {
        throw new NotSupportedException(String.Format("'{0}' is type '{1}' which isn't supported.",
            animal,
            animal.GetType()));
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        List<Animal> animals = new List<Animal>
        {
            new Cat(),
            new Cat(),
            new Dog(),
            new Cat()
        };

        AnimalProcessor animalProcessor = new AnimalProcessor();
        foreach (dynamic animal in animals)
        {
            animalProcessor.Process(animal);
        }

        //Do stuff all Animals need.
    }
}

The code works as expected, but, I have a nagging feeling that I'm missing something blindingly obvious and that there's a much better (or better known) pattern to do this.

Is there any better or equally good but more accepted pattern to use to process my Animals? Or, is this fine? And, please explain why any alternatives are better.


Source: (StackOverflow)

Get current dispatch queue?

I have a method which should support being called from any queue, and should expect to. It runs some code in a background thread itself, and then uses dispatch_get_main_queue when it returns a value to it's block argument. I don't want it to force it onto the main queue if it wasn't when it entered the method. Is there a way to get a pointer to the current dispatch queue?


Source: (StackOverflow)

How do we dispatch Google Analytics events when iOS app goes to the background?

My iOS app has links to Apple's App Store in it and I am trying to track those as events.

The problem is that we can't get my app to properly dispatch the GA events before it goes into the background. We are using iOS SDK v2beta4.

Here is an overview of the code we are using. You can see we've put in a lot of what I call "insurance policy" code because what we think is the correct way is not working. But even the insurance policy code does not always dispatch the events before my app goes into the background. It only works about 50% of the time and the rest of the time I have to return to the app to get the events to dispatch.

We believe the correct way is to dispatch the event in "applicationDidEnterBackground" and to ask the iOS for extra time to do this via "beginBackgroundTaskWithExpirationHandler". We've tried this code on its own without my "insurance policy" code. At least I believe we commented out every line of insurance code correctly.

Note that we set the global variable UIBackgroundTaskIdentifier bgTask; in the AppDelegate.h header file with the code

UIBackgroundTaskIdentifier  bgTask;

Here is the code that we think is the correct way to do this:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UIApplication *app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        [[GAI sharedInstance] dispatch];

        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}

The above code is what we think should work but does not. Note: The App Store is not a usual app, but a website inside an app if that makes a difference.

As an insurance policy we've done a few other things which dispatch the event about 50% of the time:

The first [[GAI sharedInstance] dispatch] is called immediately in the function where tracking has been set

Source code:

- (IBAction)goToAppStore:(id)sender
{    
    ...
    // Tracking
    // Using events (pressing on buttons)

    id <GAITracker> tracker = [[GAI sharedInstance] defaultTracker];

    [tracker sendEventWithCategory:@"App Checkout"
                        withAction:@"Checkout Button Pressed"
                        withLabel:nameApp.text
                        withValue:nil];

    [[GAI sharedInstance] dispatch];
    ...
}

We also put it in "applicationWillResignActive"

- (void)applicationWillResignActive:(UIApplication *)application
{
    ...  
    [[GAI sharedInstance] dispatch];
}

And finally when you completely close the app another GA dispatch is called

- (void)applicationWillTerminate:(UIApplication *)application
{
    [[GAI sharedInstance] dispatch];
}

None of this works 100% of the time. Only about 50% of the time. So we did this: When you re-enter the app (it doesn't matter if from the background or the app has been completely closed) we send a dispatch

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [[GAI sharedInstance] dispatch];
}

With this last bit the events are dispatched but only if a user returns to my app. Although I am not 100% sure if it is this code that is dispatching the events when I return to the app or a GA default dispatch when I go back to the app.


Source: (StackOverflow)

jQuery dispatch event? How to

how can i dispatch an event on my window ready? For example in my code i've got:

$("#info").click(function(){
// do stuff
});

I need to call this function the first time without have a click on #info, in the way // do stuff.


Source: (StackOverflow)

Android WindowManager error : DispatchAttachedToWindow is not called

My app interface as facebook chathead so i used overlay button. I used with intent service in my main activity. I create chathead ui in my FloatBitchService. UI create with WindowManager. Add float_view layout to WindowManager. In float_view layout, all of the controls are visible gone except butHead. butHead is overlay button. I want to show ovelay button click show other controls. I used with overlay button onTouchevent for overlay button click. My Error occur in input textbox control. Debug Device is Samsung Galaxy Note 2.

(FloatBitchService.java)

public class FloatBitchService extends Service {
@Override
public void onCreate() {
    windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
    LayoutInflater inflater = LayoutInflater.from(this);        
    viewFloat = inflater.inflate(R.layout.float_view, null);
    butHead = (Button)viewFloat.findViewById(R.id.butHead);
    ...........................
    parameters = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT, // Width
            WindowManager.LayoutParams.WRAP_CONTENT, // Height
            WindowManager.LayoutParams.TYPE_PHONE, // Type
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,// Flag             
            PixelFormat.TRANSLUCENT // Format)
            );      
    parameters.x = 0;
    parameters.y = 0;
    parameters.gravity = Gravity.TOP | Gravity.LEFT;        
    windowManager.addView(viewFloat, parameters);
    butHead.setOnTouchListener(new OnTouchListener() {

        int initialX, initialY;
        float initialTouchX, initialTouchY;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub

            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                // Get current time in nano seconds.
                initialX = parameters.x;
                initialY = parameters.y;
                initialTouchX = event.getRawX();
                initialTouchY = event.getRawY();
                startClickTime = Calendar.getInstance().getTimeInMillis();
                Toast.makeText(getApplication(), "Here to Remove", Toast.LENGTH_SHORT).show();
                break;
            case MotionEvent.ACTION_UP:
                // Check Single Click
                long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
                if (clickDuration < MAX_CLICK_DURATION){
                    if (layout1.getVisibility() == View.VISIBLE) {  
                        // isMove flag for chat head movement
                        isMove = true;
                        chatHeadClose();
                    }else {
                        // isMove flag for chat head movement
                        isMove = false;
                        chatHeadOpen();
                    }
                }

                Display display = windowManager.getDefaultDisplay();
                Point point = new Point();
                display.getSize(point);
                screenWidth = point.x;
                screenHeight = point.y;

                // Dictionary Panel size set to fix screen size
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)layout1.getLayoutParams();
                params.width = screenWidth;
                params.height = (int)(screenHeight * 0.68);

                // Calculate for Delete Space [ * ]
                int screenWidthHalf = screenWidth / 2;
                int rightValue = screenWidthHalf + 100;
                int leftValue = screenWidthHalf - 100;
                int headwidth = butHead.getWidth() / 2;

                // float item close when arrive screen bottom                   
                if (parameters.y > (screenHeight - 450) && (parameters.x + headwidth) > leftValue && (parameters.x + headwidth) < rightValue) {
                    viewFloat.setVisibility(View.GONE);
                    Toast.makeText(getApplication(), "Removed!",Toast.LENGTH_SHORT).show();
                    stopSelf();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (isMove) {
                    // chathead movement
                    parameters.x = initialX + (int) (event.getRawX() - initialTouchX);
                    parameters.y = initialY + (int) (event.getRawY() - initialTouchY);                      
                    windowManager.updateViewLayout(viewFloat, parameters);
                }
                break;

            }

            return false;
        }
    });
}
private void chatHeadOpen()
{
    parameters = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT, // Width
            WindowManager.LayoutParams.WRAP_CONTENT, // Height
            WindowManager.LayoutParams.TYPE_PHONE, // Type
            WindowManager.LayoutParams.FLAG_BLUR_BEHIND,// Flag             
            PixelFormat.TRANSLUCENT // Format)
            );

    parameters.x = 0;
    parameters.y = 0;
    parameters.gravity = Gravity.TOP | Gravity.LEFT;
    windowManager.removeView(viewFloat);
    windowManager.addView(viewFloat, parameters);                           
    layout1.setVisibility(View.VISIBLE);
}

private void chatHeadClose(){
    parameters = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT, // Width
            WindowManager.LayoutParams.WRAP_CONTENT, // Height
            WindowManager.LayoutParams.TYPE_PHONE, // Type
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,// Flag             
            PixelFormat.TRANSLUCENT // Format)
            );

    parameters.x = 0;
    parameters.y = 0;
    parameters.gravity = Gravity.TOP | Gravity.LEFT;
    windowManager.removeView(viewFloat);
    windowManager.addView(viewFloat, parameters);
    layout1.setVisibility(View.GONE);
}}

Error Screen Shot


Source: (StackOverflow)