问:
C++ Designing a event handler class
I've been working on designing a library. One of the aspect is going to be a EventManager.

So far the design go like this:

```<code>Client client
client.on(string, function);
</code>```

Where string is a std::string and function is a std::function<void()>
client.on is defined as such:

```<code>void Client::on(const std::string& name, const std::function<void()>& function) {
    _eventManager->add(string, function);
}
</code>```

And _eventManager->add(string, function) only objective is to create a struct called Event and store the name and function in it and then push the new strut to a vector.

Now I can do something similar to this:
_eventManager->emit("test");
It will then loop the vector array and find any event.name that is equal to the name you use when you called emit and run the function within that struct.

This all work and is pretty great and awesome and all, however it isn't exactly what I need and will not work because I need to send a second argument with _eventManager->emit(). The second argument is going be unknown, well not unknown but it can be a multiple data type based on the string you enter in the first argument.

Example usage:

```<code>Client client();

client.on("ready", [](User user) {
    user.test();
});

User user;
_eventManager->emit("ready", user); //I know this does not exists but it is nearly an example.

client.on("message_created", [](Message message) {
    std::cout << message << std::endl; //Operator overload here
}

Message message("Something to print");

_eventManager->emit("message_created", message));
</code>```

I thought about using boost::variant to allow the multiple types to be allow being passed, however you would have to retrieve them by doing something like so within the function.

```<code>client.on("ready", [](boost::variant<User, Message> args){
    User user = boost::get<User>(args);
});
</code>```

And it is suppose to be simple too, I rather not have the person using the library forced to use boost::get within all the events to retrieve the class that get passed.

That's being said, with all the wonderful information above, what would be another alternative for what I want to do? Any suggestions on why I should or shouldn't do what I am doing?

This took me a long time to write so thank you in advanced and I hope all of this make sense.

答:
I have a solution which uses variable templates (C++14), but it looks like a horrible hack. One disadvantage of it is that variable templates can only be static. Assuming you can live with it (though it's already bad)...

For each type of message (here type = list of parameters passed to the handler), you are going to have a separate list of handlers. This can be implemented like this:

```<code>template<typename F> static map<string, vector<F>> list;
</code>```

Here an example for F is void(int) - a function that receives one int argument. Another example is void(int, int) - a function that receives two int arguments. The data structure I use here stores a vector of handlers for each message name. I could alternatively use multimap.

When "registering" an event handler, just add it to the list of handlers:

```<code>template<typename F> static void add_handler(string s, F f)
{
    list<F>[s].push_back(f);
}
</code>```

When looking up the event handlers, you should specify their type explicitly. This is a crucial part, which implements type safety - it will lookup only in the data structure that corresponds to the type of the called handler.

```<code>template<typename F, typename... A> static void call_handlers(string s, A... args)
{
    for (F f: list<F>[s])
        f(args...);
}
</code>```

Usage:

```<code>// Define event handlers
// Their type SHOULD be explicit (not lambda), because we will reference it further
function<void(int)> action1 = [](int k){cout << "notify user " << k << '\n';};
function<void(int)> action2 = [](int k){cout << "alert user " << k << '\n';};
function<void(int, int)> action3 = [](int a, int b){cout << "give $" << a << " to user " << b << '\n';};

// Register the handlers
add_handler("good_event", action1);
add_handler("good_event", action2);
add_handler("bad_event", action2);
add_handler("money_event", action3);

// Generate events, which will call the handlers
call_handlers<function<void(int)>>("good_event", 7);
call_handlers<function<void(int)>>("bad_event", 8);
call_handlers<function<void(int, int)>>("money_event", 100, 9);

// Wrong call, but no compilation error - the handler is just not found
call_handlers<function<void(int)>>("money_event", 99);
</code>```

Title: C++ Designing a event handler class

Body:
I've been working on designing a library. One of the aspect is going to be a EventManager.

So far the design go like this:

Client client
client.on(string, function);

Where string is a std::string and function is a std::function<void()>
client.on is defined as such:

void Client::on(const std::string& name, const std::function<void()>& function) {
    _eventManager->add(string, function);
}

And _eventManager->add(string, function) only objective is to create a struct called Event and store the name and function in it and then push the new strut to a vector.

Now I can do something similar to this:
_eventManager->emit("test");
It will then loop the vector array and find any event.name that is equal to the name you use when you called emit and run the function within that struct.

This all work and is pretty great and awesome and all, however it isn't exactly what I need and will not work because I need to send a second argument with _eventManager->emit(). The second argument is going be unknown, well not unknown but it can be a multiple data type based on the string you enter in the first argument.

Example usage:

Client client();

client.on("ready", [](User user) {
    user.test();
});

User user;
_eventManager->emit("ready", user); //I know this does not exists but it is nearly an example.

client.on("message_created", [](Message message) {
    std::cout << message << std::endl; //Operator overload here
}

Message message("Something to print");

_eventManager->emit("message_created", message));

I thought about using boost::variant to allow the multiple types to be allow being passed, however you would have to retrieve them by doing something like so within the function.

client.on("ready", [](boost::variant<User, Message> args){
    User user = boost::get<User>(args);
});

And it is suppose to be simple too, I rather not have the person using the library forced to use boost::get within all the events to retrieve the class that get passed.

That's being said, with all the wonderful information above, what would be another alternative for what I want to do? Any suggestions on why I should or shouldn't do what I am doing?

This took me a long time to write so thank you in advanced and I hope all of this make sense.

Body:
I have a solution which uses variable templates (C++14), but it looks like a horrible hack. One disadvantage of it is that variable templates can only be static. Assuming you can live with it (though it's already bad)...

For each type of message (here type = list of parameters passed to the handler), you are going to have a separate list of handlers. This can be implemented like this:

template<typename F> static map<string, vector<F>> list;

Here an example for F is void(int) - a function that receives one int argument. Another example is void(int, int) - a function that receives two int arguments. The data structure I use here stores a vector of handlers for each message name. I could alternatively use multimap.

When "registering" an event handler, just add it to the list of handlers:

template<typename F> static void add_handler(string s, F f)
{
    list<F>[s].push_back(f);
}

When looking up the event handlers, you should specify their type explicitly. This is a crucial part, which implements type safety - it will lookup only in the data structure that corresponds to the type of the called handler.

template<typename F, typename... A> static void call_handlers(string s, A... args)
{
    for (F f: list<F>[s])
        f(args...);
}

Usage:

// Define event handlers
// Their type SHOULD be explicit (not lambda), because we will reference it further
function<void(int)> action1 = [](int k){cout << "notify user " << k << '\n';};
function<void(int)> action2 = [](int k){cout << "alert user " << k << '\n';};
function<void(int, int)> action3 = [](int a, int b){cout << "give $" << a << " to user " << b << '\n';};

// Register the handlers
add_handler("good_event", action1);
add_handler("good_event", action2);
add_handler("bad_event", action2);
add_handler("money_event", action3);

// Generate events, which will call the handlers
call_handlers<function<void(int)>>("good_event", 7);
call_handlers<function<void(int)>>("bad_event", 8);
call_handlers<function<void(int, int)>>("money_event", 100, 9);

// Wrong call, but no compilation error - the handler is just not found
call_handlers<function<void(int)>>("money_event", 99);


来源: stackexchange

问:
Matlab plot: remove connecting line between disconnected regions?
Assume you have 1000 indexed datapoints, with two labels grouped into region1 and region2. Here is an example of how to generate such random data

```<code>indices = 1:1000;
data = zeros(size(indices));

% some regions of data
region1 = [50:100 200:340 450:500 670:980];
region2 = setdiff(indices, region1);

% generating random data
data(region1) = rand(size(region1)) + 1;
data(region2) = rand(size(region2));
</code>```

Now, if I plot these two regions I get a plot shown below

The code to generate the plot

```<code>% plotting
figure(1);
cla(gca);
hold on;
plot(region1, data(region1));
plot(region2, data(region2));
hold off;
</code>```

Now the question: Is there an elegant way of removing the connecting lines between the disconnected data regions, without doing much data manipulation? I still want to use the solid line linestyle, or have a look similar to that.

答:
If you make the x or y values into NaN then they wont be plotted. Since you have two complimentary regions, you can use them to set values to NaN...

```<code>% Two vectors which each cover ALL elements in "data", but with NaN where
% the other region is to be plotted. As per example, indices=1:1000;
r1 = 1:1000; r1(region2) = NaN;
r2 = 1:1000; r2(region1) = NaN;
% Plot all data for both lines, but NaNs wont show.
figure(1); clf;
hold on;
plot(r1, data);
plot(r2, data);
hold off;
</code>```

Output:

ContentLicense: CC BY-SA 3.0

Body:
Assume you have 1000 indexed datapoints, with two labels grouped into region1 and region2. Here is an example of how to generate such random data

indices = 1:1000;
data = zeros(size(indices));

% some regions of data
region1 = [50:100 200:340 450:500 670:980];
region2 = setdiff(indices, region1);

% generating random data
data(region1) = rand(size(region1)) + 1;
data(region2) = rand(size(region2));

Now, if I plot these two regions I get a plot shown below

The code to generate the plot

% plotting
figure(1);
cla(gca);
hold on;
plot(region1, data(region1));
plot(region2, data(region2));
hold off;

Now the question: Is there an elegant way of removing the connecting lines between the disconnected data regions, without doing much data manipulation? I still want to use the solid line linestyle, or have a look similar to that.

Body:
If you make the x or y values into NaN then they wont be plotted. Since you have two complimentary regions, you can use them to set values to NaN...

% Two vectors which each cover ALL elements in "data", but with NaN where
% the other region is to be plotted. As per example, indices=1:1000;
r1 = 1:1000; r1(region2) = NaN;
r2 = 1:1000; r2(region1) = NaN;
% Plot all data for both lines, but NaNs wont show.
figure(1); clf;
hold on;
plot(r1, data);
plot(r2, data);
hold off;

Output:


问:
OpenCL Kernel for Canny
I'm trying to achieve Canny Edge Detection with OpenCL kernel in very simplified and easy way.

I'm using original SobelFilter kernel to do steps like non-maximum suppression and thresholding.

But I'm lost about reaching the pixels and doing the math calculations on them with:

```<code>__kernel void sobel_filter(__global uchar4* inputImage, __global uchar4* outputImage)
</code>```

Could you give me ideas or show me simple examples to achieve this? It will be highly appreciated.
Regards.

答:
Sobel filter is inhrently separable into X and Y dimensions in kernel execution. So one can scan only on X or only on Y dimensions or both of them in same kernel loop to achieve edge feature detection.

Using user azer89's soution here: Image Processing - Implementing Sobel Filter

I prepared this kernel:

```<code>__kernel void postProcess(__global uchar * input, __global uchar * output)
{
    int resultImgSize=1024;
    int pixelX=get_global_id(0)%resultImgSize; // 1-D id list to 2D workitems(each process a single pixel)
    int pixelY=get_global_id(0)/resultImgSize;
    int imgW=resultImgSize;
    int imgH=resultImgSize;

    float kernelx[3][3] = {{-1, 0, 1},
                           {-2, 0, 2},
                           {-1, 0, 1}};
    float kernely[3][3] = {{-1, -2, -1},
                           {0,  0,  0},
                           {1,  2,  1}};

    // also colors are separable
    int magXr=0,magYr=0; // red
    int magXg=0,magYg=0;
    int magXb=0,magYb=0;

    // Sobel filter
    // this conditional leaves 10-pixel-wide edges out of processing
    if( (pixelX<imgW-10) && (pixelY<imgH-10) && (pixelX>10) && (pixelY>10) )
    {
        for(int a = 0; a < 3; a++)
        {
            for(int b = 0; b < 3; b++)
            {
                int xn = pixelX + a - 1;
                int yn = pixelY + b - 1;

                int index = xn + yn * resultImgSize;
                magXr += input[index*4] * kernelx[a][b];
                magXg += input[index*4+1] * kernelx[a][b];
                magXb += input[index*4+2] * kernelx[a][b];
                magYr += input[index*4] * kernely[a][b];
                magYg += input[index*4+1] * kernely[a][b];
                magYb += input[index*4+2] * kernely[a][b];
            }
         }
    }

    // magnitude of x+y vector
    output[(pixelX+pixelY*resultImgSize)*4]  =sqrt((float)(magXr*magXr + magYr*magYr)) ;
    output[(pixelX+pixelY*resultImgSize)*4+1]=sqrt((float)(magXg*magXg + magYg*magYg)) ;
    output[(pixelX+pixelY*resultImgSize)*4+2]=sqrt((float)(magXb*magXb + magYb*magYb)) ;
    output[(pixelX+pixelY*resultImgSize)*4+3]=255;

}
</code>```

Indices were multipled with 4 here because they were interpreted as uchar  array as kernel parameters. uchar is a single byte in OpenCL(at least for my system).

Here is a video of this:

Sobel Filter Example

if it works for you too, you should accept azer89's solution. But this is not very optimized and may take 1-2 milliseconds for a low end GPU and even more with only a CPU for 1024x1024 image. The image data is sent to an OpenCL buffer(not image buffer) using a byte array(of C# language) and kernel launch options are:

Global range = 1024*1024 (1 thread per pixel processing)

Local range = 256 (this is not important)

Buffer copy size 1024*1024*4 (bytes for rgba format)

also kernelx and kernely 2D arrays here were float so making them char could make it faster. Also you may check results(clamp, divide, ...) if result looks a lot more colorful than its expected. Host side representation/interpretation is also important to handle underflow and overlow of colors.

Title: OpenCL Kernel for Canny

Body:
I'm trying to achieve Canny Edge Detection with OpenCL kernel in very simplified and easy way.

I'm using original SobelFilter kernel to do steps like non-maximum suppression and thresholding.

But I'm lost about reaching the pixels and doing the math calculations on them with:

__kernel void sobel_filter(__global uchar4* inputImage, __global uchar4* outputImage)

Could you give me ideas or show me simple examples to achieve this? It will be highly appreciated.
Regards.

Body:
Sobel filter is inhrently separable into X and Y dimensions in kernel execution. So one can scan only on X or only on Y dimensions or both of them in same kernel loop to achieve edge feature detection.

Using user azer89's soution here: Image Processing - Implementing Sobel Filter

I prepared this kernel:

__kernel void postProcess(__global uchar * input, __global uchar * output)
{
    int resultImgSize=1024;
    int pixelX=get_global_id(0)%resultImgSize; // 1-D id list to 2D workitems(each process a single pixel)
    int pixelY=get_global_id(0)/resultImgSize;
    int imgW=resultImgSize;
    int imgH=resultImgSize;

    float kernelx[3][3] = {{-1, 0, 1},
                           {-2, 0, 2},
                           {-1, 0, 1}};
    float kernely[3][3] = {{-1, -2, -1},
                           {0,  0,  0},
                           {1,  2,  1}};

    // also colors are separable
    int magXr=0,magYr=0; // red
    int magXg=0,magYg=0;
    int magXb=0,magYb=0;

    // Sobel filter
    // this conditional leaves 10-pixel-wide edges out of processing
    if( (pixelX<imgW-10) && (pixelY<imgH-10) && (pixelX>10) && (pixelY>10) )
    {
        for(int a = 0; a < 3; a++)
        {
            for(int b = 0; b < 3; b++)
            {
                int xn = pixelX + a - 1;
                int yn = pixelY + b - 1;

                int index = xn + yn * resultImgSize;
                magXr += input[index*4] * kernelx[a][b];
                magXg += input[index*4+1] * kernelx[a][b];
                magXb += input[index*4+2] * kernelx[a][b];
                magYr += input[index*4] * kernely[a][b];
                magYg += input[index*4+1] * kernely[a][b];
                magYb += input[index*4+2] * kernely[a][b];
            }
         }
    }

    // magnitude of x+y vector
    output[(pixelX+pixelY*resultImgSize)*4]  =sqrt((float)(magXr*magXr + magYr*magYr)) ;
    output[(pixelX+pixelY*resultImgSize)*4+1]=sqrt((float)(magXg*magXg + magYg*magYg)) ;
    output[(pixelX+pixelY*resultImgSize)*4+2]=sqrt((float)(magXb*magXb + magYb*magYb)) ;
    output[(pixelX+pixelY*resultImgSize)*4+3]=255;

}

Indices were multipled with 4 here because they were interpreted as uchar  array as kernel parameters. uchar is a single byte in OpenCL(at least for my system).

Here is a video of this:

Sobel Filter Example

if it works for you too, you should accept azer89's solution. But this is not very optimized and may take 1-2 milliseconds for a low end GPU and even more with only a CPU for 1024x1024 image. The image data is sent to an OpenCL buffer(not image buffer) using a byte array(of C# language) and kernel launch options are:

Global range = 1024*1024 (1 thread per pixel processing)

Local range = 256 (this is not important)

Buffer copy size 1024*1024*4 (bytes for rgba format)

also kernelx and kernely 2D arrays here were float so making them char could make it faster. Also you may check results(clamp, divide, ...) if result looks a lot more colorful than its expected. Host side representation/interpretation is also important to handle underflow and overlow of colors.


问:
How to get a button element made in the DOM, run a function
I created a button element using javascript, and now would like to know how to find that element or select it and get it to call this function:</p>

```<code>    function test() {
      alert("it works!");
    }
</code>```

答:
Your button is an object once you created it dynamically. This means that you and easily assign properties and functions to it using the dot syntax. So, for example, if you want to give the dynamic button onclick functionality, you could do this:</p>

```<code>btn.onclick = function() {
  // add the JS function you want on the dynamic button here
 };
</code>```

Body:
I created a button element using javascript, and now would like to know how to find that element or select it and get it to call this function:

    function test() {
      alert("it works!");
    }

Body:
Your button is an object once you created it dynamically. This means that you and easily assign properties and functions to it using the dot syntax. So, for example, if you want to give the dynamic button onclick functionality, you could do this:

btn.onclick = function() {
  // add the JS function you want on the dynamic button here
 };


问:
When I import the yaml from swagger the authorizer does not work, after removing and re-adding it , it works
I use custom authorizer and api gateway to athorize the user before calling my services. First I manually create all the resources and methods then I create the authorizer and attach the services to authorizer in method execution.
when I deploy my api gateway everything works fine and when I export the yaml file with api gateway extention I have the following yaml file

```<code>---
swagger: "2.0"
info:
 version: "2017-06-02T19:36:38Z"
 title: "test"
 host: "t8ksrbnwce.execute-api.us-east-1.amazonaws.com"
 basePath: "/rrr"
 schemes:
  - "https"
 paths:
   /stories/{storyid}:
   get:
  produces:
  - "application/json"
  parameters:
  - name: "storyid"
    in: "path"
    required: true
    type: "string"
  responses:
    200:
      description: "200 response"
      schema:
        $ref: "#/definitions/Empty"
      headers:
        Access-Control-Allow-Origin:
          type: "string"
  security:
  - userAthenticationCheck: []
  x-amazon-apigateway-integration:
    responses:
      default:
        statusCode: "200"
        responseParameters:
          method.response.header.Access-Control-Allow-Origin: "'*'"
    requestParameters:
      integration.request.path.id: "method.request.path.storyid"
    uri: "https://jsonplaceholder.typicode.com/posts/{id}"
    passthroughBehavior: "when_no_match"
    httpMethod: "GET"
    type: "http"
options:
  consumes:
  - "application/json"
  produces:
  - "application/json"
  responses:
    200:
      description: "200 response"
      schema:
        $ref: "#/definitions/Empty"
      headers:
        Access-Control-Allow-Origin:
          type: "string"
        Access-Control-Allow-Methods:
          type: "string"
        Access-Control-Allow-Headers:
          type: "string"
  x-amazon-apigateway-integration:
    responses:
      default:
        statusCode: "200"
        responseParameters:
          method.response.header.Access-Control-Allow-Methods:
   "'GET,OPTIONS'"
          method.response.header.Access-Control-Allow-Headers: "'Content-
         Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,Access-Control-
  Allow-Headers,Origin,X-Requested-With,Accept,authorizationToken'"
          method.response.header.Access-Control-Allow-Origin: "'*'"
    requestTemplates:
      application/json: "{\"statusCode\": 200}"
    passthroughBehavior: "when_no_match"
    type: "mock"
    securityDefinitions:
    userAthenticationCheck:
     type: "apiKey"
     name: "authorizationToken"
    in: "header"
   x-amazon-apigateway-authtype: "custom"
    x-amazon-apigateway-authorizer:
  authorizerUri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-
   31/functions/arn:aws:lambda:us-east-
 1:048947288163:function:Authorizer/invocations"
  authorizerResultTtlInSeconds: 0
  type: "token"
  definitions:
  Empty:
    type: "object"
    title: "Empty Schema"
</code>```

Now that I have the yaml file I want to import it anytime I need it.
However when I import the yaml file again, when I use postman to try the imported API gateway I get cors 500 error. Then when I delete the authorizer in  the authorizer section of api gateway and create it again with the same name, then it starts working again. But the problem is I need to automate this process and I do not want to manually remove and add the authorizer again. Can anyone help how to fix this? is it a bug in aws? Or am I missing sth?

答:
apologies you are facing this issue.

There is a bug right now that is causing references to existing authorizers to be broken on imports. I'm not sure exactly if it affects all use cases or a subset, but clearly it's affecting you. We are working on getting this fix out as soon as possible.

Thanks,
Jack

Body:
I use custom authorizer and api gateway to athorize the user before calling my services. First I manually create all the resources and methods then I create the authorizer and attach the services to authorizer in method execution.
when I deploy my api gateway everything works fine and when I export the yaml file with api gateway extention I have the following yaml file

---
swagger: "2.0"
info:
 version: "2017-06-02T19:36:38Z"
 title: "test"
 host: "t8ksrbnwce.execute-api.us-east-1.amazonaws.com"
 basePath: "/rrr"
 schemes:
  - "https"
 paths:
   /stories/{storyid}:
   get:
  produces:
  - "application/json"
  parameters:
  - name: "storyid"
    in: "path"
    required: true
    type: "string"
  responses:
    200:
      description: "200 response"
      schema:
        $ref: "#/definitions/Empty"
      headers:
        Access-Control-Allow-Origin:
          type: "string"
  security:
  - userAthenticationCheck: []
  x-amazon-apigateway-integration:
    responses:
      default:
        statusCode: "200"
        responseParameters:
          method.response.header.Access-Control-Allow-Origin: "'*'"
    requestParameters:
      integration.request.path.id: "method.request.path.storyid"
    uri: "https://jsonplaceholder.typicode.com/posts/{id}"
    passthroughBehavior: "when_no_match"
    httpMethod: "GET"
    type: "http"
options:
  consumes:
  - "application/json"
  produces:
  - "application/json"
  responses:
    200:
      description: "200 response"
      schema:
        $ref: "#/definitions/Empty"
      headers:
        Access-Control-Allow-Origin:
          type: "string"
        Access-Control-Allow-Methods:
          type: "string"
        Access-Control-Allow-Headers:
          type: "string"
  x-amazon-apigateway-integration:
    responses:
      default:
        statusCode: "200"
        responseParameters:
          method.response.header.Access-Control-Allow-Methods:
   "'GET,OPTIONS'"
          method.response.header.Access-Control-Allow-Headers: "'Content-
         Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,Access-Control-
  Allow-Headers,Origin,X-Requested-With,Accept,authorizationToken'"
          method.response.header.Access-Control-Allow-Origin: "'*'"
    requestTemplates:
      application/json: "{\"statusCode\": 200}"
    passthroughBehavior: "when_no_match"
    type: "mock"
    securityDefinitions:
    userAthenticationCheck:
     type: "apiKey"
     name: "authorizationToken"
    in: "header"
   x-amazon-apigateway-authtype: "custom"
    x-amazon-apigateway-authorizer:
  authorizerUri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-
   31/functions/arn:aws:lambda:us-east-
 1:048947288163:function:Authorizer/invocations"
  authorizerResultTtlInSeconds: 0
  type: "token"
  definitions:
  Empty:
    type: "object"
    title: "Empty Schema"

Now that I have the yaml file I want to import it anytime I need it.
However when I import the yaml file again, when I use postman to try the imported API gateway I get cors 500 error. Then when I delete the authorizer in  the authorizer section of api gateway and create it again with the same name, then it starts working again. But the problem is I need to automate this process and I do not want to manually remove and add the authorizer again. Can anyone help how to fix this? is it a bug in aws? Or am I missing sth?


问:
How to put the res files from the project to the jar in the same folder?
I have problem with gradle.
I need the res folder had exactly the same location as in the project in order that would be executable file addressed to the resource in the same way as in the "unbuild" project.
my project file tree:

```<code>Project
+--src
   +--main
      |--kotlin
      +--res
</code>```

In the project resource usage I address in the following way:

```<code>var serviceAccount =  FileInputStream("src/main/res/my_resource_file.json")
</code>```

And I need when assembled the project location of the resource file saved in the jar file

my build.gradle file:

```<code>group 'Bot'
version '1.0'

buildscript {
    ext.kotlin_version = '1.1.2'

    repositories {
        mavenCentral()
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'kotlin'

repositories {
    mavenCentral()
}

ext {
    jsoup = "1.10.2"
    //...
    firebase_admin = "5.0.0"
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    //...
    compile "com.google.firebase:firebase-admin:$firebase_admin"
}

sourceSets {
    main.java.srcDirs += 'src/main/kotlin/'
    test.java.srcDirs += 'src/test/kotlin/'
    main {
        resources {
            srcDirs = ["src/main/res"]
        }
    }
}

jar {
    manifest {
        attributes 'Main-Class': 'com.my.bot.MainKt'
    }
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}
</code>```

I suspect that you need to configure this section jar{//...}, but i don't know what did is in gradle

答:
Normally you would reference such as resource from: src/main/resources as the source folder which then is copied auto copied into your JAR by Gradle.  You then use the Classloader to read the resources as a stream.

If I placed a file at src/main/resources/my_resource_file.json it would be loaded via:

```<code>// relative to the current class package location
val input  = javaClass.getResourceAsStream("/my_resource_file.json")

// or use system classloader
val input = ClassLoader.getSystemClassLoader().getResourceAsStream("my_resource_file.json")
</code>```

You are instead doing it in a non standard way by using res as the directory name instead of resources and by trying to access it as a file instead of a classpath resource.  In Gradle docs (similarly for Maven) they explain the file layout: Gradle Java Project Layout

Body:
I have problem with gradle.
I need the res folder had exactly the same location as in the project in order that would be executable file addressed to the resource in the same way as in the "unbuild" project.
my project file tree:

Project
+--src
   +--main
      |--kotlin
      +--res

In the project resource usage I address in the following way:

var serviceAccount =  FileInputStream("src/main/res/my_resource_file.json")

And I need when assembled the project location of the resource file saved in the jar file

my build.gradle file:

group 'Bot'
version '1.0'

buildscript {
    ext.kotlin_version = '1.1.2'

    repositories {
        mavenCentral()
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'kotlin'

repositories {
    mavenCentral()
}

ext {
    jsoup = "1.10.2"
    //...
    firebase_admin = "5.0.0"
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    //...
    compile "com.google.firebase:firebase-admin:$firebase_admin"
}

sourceSets {
    main.java.srcDirs += 'src/main/kotlin/'
    test.java.srcDirs += 'src/test/kotlin/'
    main {
        resources {
            srcDirs = ["src/main/res"]
        }
    }
}

jar {
    manifest {
        attributes 'Main-Class': 'com.my.bot.MainKt'
    }
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}

I suspect that you need to configure this section jar{//...}, but i don't know what did is in gradle

Body:
Normally you would reference such as resource from: src/main/resources as the source folder which then is copied auto copied into your JAR by Gradle.  You then use the Classloader to read the resources as a stream.

If I placed a file at src/main/resources/my_resource_file.json it would be loaded via:

// relative to the current class package location
val input  = javaClass.getResourceAsStream("/my_resource_file.json")

// or use system classloader
val input = ClassLoader.getSystemClassLoader().getResourceAsStream("my_resource_file.json")

You are instead doing it in a non standard way by using res as the directory name instead of resources and by trying to access it as a file instead of a classpath resource.  In Gradle docs (similarly for Maven) they explain the file layout: Gradle Java Project Layout


问:
Running the same query causing error the second time
I have a Data-table with all the mandatory fields which is required by select query in it. Now i am fetching data from 1st row of the data-table and running a select query (as given below). For the first time its working fine.
Now I am taking the 2nd row and giving all the mandatory fields (as i did for the first) and running the select query its giving error "insufficient permissions". When i am running both the select query (which are actually same but with different parameter) manually in Oracle SQL Developer its working fine.

```<code>Query1: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'
Query2: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'
</code>```

To fetch data from database

```<code>public OracleDataReader ExecuteReader(string SelectQuery, string conString)
        {
        try
        {
            OpenDbConnection(conString);

            OracleCommand cmd = new OracleCommand();
            cmd.Connection = con;
            cmd.CommandText = SelectQuery;
            cmd.CommandType = System.Data.CommandType.Text;
            OracleDataReader ora_dataReader = cmd.ExecuteReader();

            return ora_dataReader;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
        }
    }
</code>```

EDIT:
Forgot to mention that i am calling this funtion in another function as given below

```<code>public DataTable GetDataFromDB(string SelectQuery, string conString)
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Load(ExecuteReader(SelectQuery,conString));

                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                CloseDbConnection();
            }
        }
</code>```

答:
You need to ensure you're closing both the Connection and DataReader objects.

Try using the CommandBehavior argument in ExecuteReader, as it will close the connection automatically once you close the DataReader.

```<code>cmd.ExecuteReader(CommandBehavior.CloseConnection)
</code>```

Body:
I have a Data-table with all the mandatory fields which is required by select query in it. Now i am fetching data from 1st row of the data-table and running a select query (as given below). For the first time its working fine.
Now I am taking the 2nd row and giving all the mandatory fields (as i did for the first) and running the select query its giving error "insufficient permissions". When i am running both the select query (which are actually same but with different parameter) manually in Oracle SQL Developer its working fine.

Query1: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'
Query2: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'

To fetch data from database

public OracleDataReader ExecuteReader(string SelectQuery, string conString)
        {
        try
        {
            OpenDbConnection(conString);

            OracleCommand cmd = new OracleCommand();
            cmd.Connection = con;
            cmd.CommandText = SelectQuery;
            cmd.CommandType = System.Data.CommandType.Text;
            OracleDataReader ora_dataReader = cmd.ExecuteReader();

            return ora_dataReader;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
        }
    }

EDIT:
Forgot to mention that i am calling this funtion in another function as given below

public DataTable GetDataFromDB(string SelectQuery, string conString)
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Load(ExecuteReader(SelectQuery,conString));

                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                CloseDbConnection();
            }
        }

Body:
You need to ensure you're closing both the Connection and DataReader objects.

Try using the CommandBehavior argument in ExecuteReader, as it will close the connection automatically once you close the DataReader.

cmd.ExecuteReader(CommandBehavior.CloseConnection)


问:
Laravel Accessing Foreign Key Using Eloquent Where Clause
I have two models called Item and Sale where

```<code>class Item extends Model
{
    public function sale()
    {
        return $this->hasMany('App\Sale', 'sale_id');
    }
}
</code>```

and

```<code>class Sale extends Model
{
    public function item()
    {
        return $this->belongsTo('App\Sale', 'item_id');
    }
}
</code>```

This is my migration files for Items

```<code>public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('code');
            $table->string('name');
            $table->string('location');
            $table->double('buy_price');
            $table->double('sell_price');
            $table->integer('quantity');
            $table->timestamps();
        });
    }
</code>```

And Sales

```<code>public function up()
    {
        Schema::create('sales', function (Blueprint $table) {
            $table->increments('id');
            $table->date('date');
            $table->integer('quantity');
            $table->double('sell_price');
            $table->double('subtotal');
            $table->integer('item_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('sales', function (Blueprint $table) {
            $table->foreign('item_id')->references('id')->on('items')
                  ->onDelete('cascade')->onUpdate('cascade');
        });
    }
</code>```

I recorded the daily sales data to see what are the items sold that day. Therefore I wanted to view the sales daily. And this is what I have done in my controller.

```<code>class SaleController extends Controller
{
    public function show($date)
    {
        $sales = Sale::where('date', $date)->get();
        return view('sale.detail', compact('sales'));
    }
}
</code>```

And finally in my blade, I did this to call the information of the items

```<code>@foreach($sales as $sale)
    <tr>
        <td>{{ $sale->item->code }}</td>
        <td>{{ $sale->item->name }}</td>
        <td>{{ $sale->sell_price }}</td>
        <td>{{ $sale->quantity }}</td>
    </tr>
@endforeach
</code>```

In the end I got Trying to get property of non-object
Can someone enlighten me what is wrong with my code?
I am relatively new in Laravel but I'm keen on trying different things to see what this framework can do.

Thanks a lot

答:
Just noticed that your relationship is defined wrong. Change App\Sale to App\Item in your item relationship. Guess a minor slip up.

```<code>class Sale extends Model
{
    public function item()
    {
        return $this->belongsTo('App\Item', 'item_id');
    }
}
</code>```

Body:
I have two models called Item and Sale where

class Item extends Model
{
    public function sale()
    {
        return $this->hasMany('App\Sale', 'sale_id');
    }
}

and

class Sale extends Model
{
    public function item()
    {
        return $this->belongsTo('App\Sale', 'item_id');
    }
}

This is my migration files for Items

public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('code');
            $table->string('name');
            $table->string('location');
            $table->double('buy_price');
            $table->double('sell_price');
            $table->integer('quantity');
            $table->timestamps();
        });
    }

And Sales

public function up()
    {
        Schema::create('sales', function (Blueprint $table) {
            $table->increments('id');
            $table->date('date');
            $table->integer('quantity');
            $table->double('sell_price');
            $table->double('subtotal');
            $table->integer('item_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('sales', function (Blueprint $table) {
            $table->foreign('item_id')->references('id')->on('items')
                  ->onDelete('cascade')->onUpdate('cascade');
        });
    }

I recorded the daily sales data to see what are the items sold that day. Therefore I wanted to view the sales daily. And this is what I have done in my controller.

class SaleController extends Controller
{
    public function show($date)
    {
        $sales = Sale::where('date', $date)->get();
        return view('sale.detail', compact('sales'));
    }
}

And finally in my blade, I did this to call the information of the items

@foreach($sales as $sale)

        {{ $sale->item->code }}
        {{ $sale->item->name }}
        {{ $sale->sell_price }}
        {{ $sale->quantity }}

@endforeach

In the end I got Trying to get property of non-object
Can someone enlighten me what is wrong with my code?
I am relatively new in Laravel but I'm keen on trying different things to see what this framework can do.

Thanks a lot

Body:
Just noticed that your relationship is defined wrong. Change App\Sale to App\Item in your item relationship. Guess a minor slip up.

class Sale extends Model
{
    public function item()
    {
        return $this->belongsTo('App\Item', 'item_id');
    }
}


问:
Java: Long result = -1: cannot convert from int to long
I'm using eclipse java ee to perform java programming.

I had the following line of code in one of my functions:

```<code>Long result = -1;
</code>```

I got the following error:

Type mismatch: cannot convert from int to Long

I can't quite understand why when i add a number to the variable it provides this error.

How can this issue be resolved and why did it happen in the first place?

答:
-1 can be auto-boxed to an Integer.

Thus:

```<code>Integer result = -1;
</code>```

works and is equivalent to:

```<code>Integer result = Integer.valueOf(-1);
</code>```

However, an Integer can't be assigned to a Long, so the overall conversion in the question fails.

```<code>Long result = Integer.valueOf(-1);
</code>```

won't work either.

If you do:

```<code>Long result = -1L;
</code>```

it's equivalent (again because of auto-boxing) to:

```<code>Long result = Long.valueOf(-1L);
</code>```

Note that the L makes it a long literal.

Body:
I'm using eclipse java ee to perform java programming.

I had the following line of code in one of my functions:

Long result = -1;

I got the following error:

Type mismatch: cannot convert from int to Long

I can't quite understand why when i add a number to the variable it provides this error.

How can this issue be resolved and why did it happen in the first place?

Body:
-1 can be auto-boxed to an Integer.

Thus:

Integer result = -1;

works and is equivalent to:

Integer result = Integer.valueOf(-1);

However, an Integer can't be assigned to a Long, so the overall conversion in the question fails.

Long result = Integer.valueOf(-1);

won't work either.

If you do:

Long result = -1L;

it's equivalent (again because of auto-boxing) to:

Long result = Long.valueOf(-1L);

Note that the L makes it a long literal.

ContentLicense: CC BY-SA 2.5


答:
This way maybe.

$("body").append("<button>Button</button>");

$("button").click(function(){
  alert("it works!");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script></code>```

Title: How to get a button element made in the DOM, run a function

Body:
This way maybe.

$("body").append("<button>Button</button>");

$("button").click(function(){
  alert("it works!");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>


问:
Convert LUIS Datetime V2 to JS Date
Is there a builtin helper method in LUIS Sdk or Bot Sdk to convert the LUIS DatetimeV2 entities to JS Date objects? I have seen some have been using Chronic Parser for C# but I couldn't find anything that works for Nodejs.</p>

```<code>const dt = builder.EntityRecognizer.findEntity(args.intent.entities, 'datetimeV2');
if (dt) {
    // this is just the matching intent, I believe.
    // example intents; today, yesterday, 2/28, 31/5, ...
    // How do I convert this to a valid Date is where I am stuck.
}
</code>```

答:
To extract datetimeV2 entities in NodeJS, it is more specific in that you'll need to run:

```<code>const dt = builder.EntityRecognizer.findEntity(args.intent.entities,
    'builtin.datetimeV2.date');

const dt_daterange = builder.EntityRecognizer.findEntity(args.intent.entities,
    'builtin.datetimeV2.daterange');
</code>```

To create a Date object you can look it up here at MDN.

Here's a blogpost on datetimeV2 that shows the entity's structure in the LUIS response object.

To create a Date object, you can take dt.resolution.values[i]['value'] and place it into a constructor like so:

```<code>const dt_obj = new Date(dt.resolution.values[i]['value']);
</code>```

Title: Convert LUIS Datetime V2 to JS Date

Body:
Is there a builtin helper method in LUIS Sdk or Bot Sdk to convert the LUIS DatetimeV2 entities to JS Date objects? I have seen some have been using Chronic Parser for C# but I couldn't find anything that works for Nodejs.

const dt = builder.EntityRecognizer.findEntity(args.intent.entities, 'datetimeV2');
if (dt) {
    // this is just the matching intent, I believe.
    // example intents; today, yesterday, 2/28, 31/5, ...
    // How do I convert this to a valid Date is where I am stuck.
}

Body:
To extract datetimeV2 entities in NodeJS, it is more specific in that you'll need to run:

const dt = builder.EntityRecognizer.findEntity(args.intent.entities,
    'builtin.datetimeV2.date');

const dt_daterange = builder.EntityRecognizer.findEntity(args.intent.entities,
    'builtin.datetimeV2.daterange');

To create a Date object you can look it up here at MDN.

Here's a blogpost on datetimeV2 that shows the entity's structure in the LUIS response object.

To create a Date object, you can take dt.resolution.values[i]['value'] and place it into a constructor like so:

const dt_obj = new Date(dt.resolution.values[i]['value']);


问:
firebase messaging when Notification clicked to open my Activity
The firebase is working fine  , pushing the notification on the status bar but my challange is when the notification is clicked , I want it to take me to my Custom Activity not the default launcher , How do I go about it?

```<code>public class CustomActivity extends AppCompatActivity {

private static final String TAG = "CustomActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView mymessage = (TextView) findViewById(R.id.mymessage);

    // If a notification message is tapped, any data accompanying the notification
    // message is available in the intent extras. In this sample the launcher
    // intent is fired when the notification is tapped, so any accompanying data would
    // be handled here. If you want a different intent fired, set the click_action
    // field of the notification message to the desired intent. The launcher intent
    // is used when no click_action is specified.
    //
    // Handle possible data accompanying notification message.
    // [START handle_data_extras]
    if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            String value = String.valueOf(getIntent().getExtras().get(key));
            Log.d(TAG, "Key: " + key + " Value: " + value);
            //
            Toast.makeText(getApplicationContext() , value , Toast.LENGTH_SHORT).show();

        }

        //Toast.makeText(getApplicationContext() , String.valueOf(getIntent().getExtras().get("message")) , Toast.LENGTH_SHORT).show();

    }
    // [END handle_data_extras]

    Button subscribeButton = (Button) findViewById(R.id.subscribeButton);
    subscribeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // [START subscribe_topics]
            FirebaseMessaging.getInstance().subscribeToTopic("news");
            // [END subscribe_topics]

            // Log and toast
            String msg = getString(R.string.msg_subscribed);
            Log.d(TAG, msg);
            Toast.makeText(CustomActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

    Button logTokenButton = (Button) findViewById(R.id.logTokenButton);
    logTokenButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Get token
            String token = FirebaseInstanceId.getInstance().getToken();

            // Log and toast
            String msg = getString(R.string.msg_token_fmt, token);
            Log.d(TAG, msg);
            Toast.makeText(CustomActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });
}
</code>```

This is my Custom activity that I want to open when the notification is clocked . The Notification is from Firebase cloud messaging.

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

/**
 * Called when message is received.
 *
 * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
 */
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // [START_EXCLUDE]
    // There are two types of messages data messages and notification messages. Data messages are handled
    // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
    // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
    // is in the foreground. When the app is in the background an automatically generated notification is displayed.
    // When the user taps on the notification they are returned to the app. Messages containing both notification
    // and data payloads are treated as notification messages. The Firebase console always sends notification

    // [END_EXCLUDE]

    // TODO(developer): Handle FCM messages here.
    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        System.out.print("Message data payload :" + remoteMessage.getData());

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        System.out.print("Message Notification Body :" + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.

}
// [END receive_message]

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, CustomActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_ic_notification)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
</code>```

}

This is the service listening to the Notifications from the firebase.

答:
Inside your FirebaseMessagingService...

```<code>@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    NotificationPublisher.getInstance().showNotification(this, remoteMessage);

 }
</code>```

Then in your NotificationPublisher...

```<code>public static final String EXTRA_CHAT_NOTIFICATION = "com.myProject.chat_notification";
 public void showNotification(Context context, RemoteMessage remoteMessage) {
    Intent intent = new Intent();

    if (remoteMessage.getData().get("notification_type") != null) {
        Intent i = new Intent("broadCastName");
        i.putExtra("type", remoteMessage.getData().get("notification_type"));
        i.putExtra("trip_id", remoteMessage.getData().get("trip_id"));
        i.putExtra("status", remoteMessage.getData().get("status"));
        context.sendBroadcast(i);
        return;
    }

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent = new Intent(context, MainActivity.class);
    HashMap<String, String> dataHash = new HashMap<>(remoteMessage.getData());
    intent.putExtra(EXTRA_CHAT_NOTIFICATION, dataHash);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_noti)
            .setLargeIcon(R.drawable.ic_noti)
            .setColor(ContextCompat.getColor(context, R.color.white))
            .setContentTitle(remoteMessage.getData().get("title"))
            .setContentText(remoteMessage.getData().get("content"))
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setDefaults(Notification.DEFAULT_VIBRATE)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, notificationBuilder.build());
}
}
</code>```

And finally in your MainActivity onCreate() handle the incoming data...

```<code>// Handle possible data accompanying notification message.
    // [START handle_data_extras]
    if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            Object value = getIntent().getExtras().get(key);
            Log.d(TAG, "Key: " + key + " Value: " + value);
            if(key.equals(NotificationPublisher.EXTRA_CHAT_NOTIFICATION)) {
                // TODO: Start myCustomActivity
            }
        }
    }
</code>```

Body:
The firebase is working fine  , pushing the notification on the status bar but my challange is when the notification is clicked , I want it to take me to my Custom Activity not the default launcher , How do I go about it?

public class CustomActivity extends AppCompatActivity {

private static final String TAG = "CustomActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView mymessage = (TextView) findViewById(R.id.mymessage);

    // If a notification message is tapped, any data accompanying the notification
    // message is available in the intent extras. In this sample the launcher
    // intent is fired when the notification is tapped, so any accompanying data would
    // be handled here. If you want a different intent fired, set the click_action
    // field of the notification message to the desired intent. The launcher intent
    // is used when no click_action is specified.
    //
    // Handle possible data accompanying notification message.
    // [START handle_data_extras]
    if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            String value = String.valueOf(getIntent().getExtras().get(key));
            Log.d(TAG, "Key: " + key + " Value: " + value);
            //
            Toast.makeText(getApplicationContext() , value , Toast.LENGTH_SHORT).show();

        }

        //Toast.makeText(getApplicationContext() , String.valueOf(getIntent().getExtras().get("message")) , Toast.LENGTH_SHORT).show();

    }
    // [END handle_data_extras]

    Button subscribeButton = (Button) findViewById(R.id.subscribeButton);
    subscribeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // [START subscribe_topics]
            FirebaseMessaging.getInstance().subscribeToTopic("news");
            // [END subscribe_topics]

            // Log and toast
            String msg = getString(R.string.msg_subscribed);
            Log.d(TAG, msg);
            Toast.makeText(CustomActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

    Button logTokenButton = (Button) findViewById(R.id.logTokenButton);
    logTokenButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Get token
            String token = FirebaseInstanceId.getInstance().getToken();

            // Log and toast
            String msg = getString(R.string.msg_token_fmt, token);
            Log.d(TAG, msg);
            Toast.makeText(CustomActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });
}

This is my Custom activity that I want to open when the notification is clocked . The Notification is from Firebase cloud messaging.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

/**
 * Called when message is received.
 *
 * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
 */
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // [START_EXCLUDE]
    // There are two types of messages data messages and notification messages. Data messages are handled
    // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
    // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
    // is in the foreground. When the app is in the background an automatically generated notification is displayed.
    // When the user taps on the notification they are returned to the app. Messages containing both notification
    // and data payloads are treated as notification messages. The Firebase console always sends notification

    // [END_EXCLUDE]

    // TODO(developer): Handle FCM messages here.
    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        System.out.print("Message data payload :" + remoteMessage.getData());

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        System.out.print("Message Notification Body :" + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.

}
// [END receive_message]

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, CustomActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_ic_notification)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

}

This is the service listening to the Notifications from the firebase.

Body:
Inside your FirebaseMessagingService...

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    NotificationPublisher.getInstance().showNotification(this, remoteMessage);

 }

Then in your NotificationPublisher...

public static final String EXTRA_CHAT_NOTIFICATION = "com.myProject.chat_notification";
 public void showNotification(Context context, RemoteMessage remoteMessage) {
    Intent intent = new Intent();

    if (remoteMessage.getData().get("notification_type") != null) {
        Intent i = new Intent("broadCastName");
        i.putExtra("type", remoteMessage.getData().get("notification_type"));
        i.putExtra("trip_id", remoteMessage.getData().get("trip_id"));
        i.putExtra("status", remoteMessage.getData().get("status"));
        context.sendBroadcast(i);
        return;
    }

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent = new Intent(context, MainActivity.class);
    HashMap<String, String> dataHash = new HashMap<>(remoteMessage.getData());
    intent.putExtra(EXTRA_CHAT_NOTIFICATION, dataHash);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_noti)
            .setLargeIcon(R.drawable.ic_noti)
            .setColor(ContextCompat.getColor(context, R.color.white))
            .setContentTitle(remoteMessage.getData().get("title"))
            .setContentText(remoteMessage.getData().get("content"))
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setDefaults(Notification.DEFAULT_VIBRATE)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, notificationBuilder.build());
}
}

And finally in your MainActivity onCreate() handle the incoming data...

// Handle possible data accompanying notification message.
    // [START handle_data_extras]
    if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            Object value = getIntent().getExtras().get(key);
            Log.d(TAG, "Key: " + key + " Value: " + value);
            if(key.equals(NotificationPublisher.EXTRA_CHAT_NOTIFICATION)) {
                // TODO: Start myCustomActivity
            }
        }
    }


问:
Cookies in the new browser when using HyperlinkButton in Silverlight
When you use the HyperlinkButton control in silverlight in IE to open a link in a new window using TargetName="_blank", does the new window have the same cookies as the original IE window.  If not, how do you make it have the same cookies?</p>

答:
Well windows don't have cookies, the HTTP Request will have cookies.  The cookies included in the request will be determined by the cookies in the browsers cookie cache and the URL being requested.

Hence in a typical case where you have application cookies set by responses from an ASP.NET application and they you open a new window to display another url in the same application the request for that url will carry those cookies previously set.


问:
error: member reference base type 'uint32_t'(aka 'unsigned int') is not a structure or union
Hey Stackoverflow Community,
right now i have have the following problem: I want to compile c++ with mac osx.10.11. But every time i want to make the code it gives me an errorcode. I already googled that, but i found nothing.

```<code>hashGenesisBlock = uint256("0x01");
if (true && genesis.GetHash() != hashGenesisBlock)
        {
            Logprintf("recalculating params for mainnet.\n");
            Logprintf("old mainnet genesis nonce: %s\n", genesis.nNonce.ToString().c_str());
            Logprintf("old mainnet genesis hash:  %s\n", hashGenesisBlock.ToString().c_str());
            // deliberately empty for loop finds nonce value.
            for(genesis.nNonce == 0; genesis.GetHash() > bnProofOfWorkLimit; genesis.nNonce++){ }
            Logprintf("new mainnet genesis merkle root: %s\n", genesis.hashMerkleRoot.ToString().c_str());
            Logprintf("new mainnet genesis nonce: %s\n", genesis.nNonce.ToString().c_str());
            Logprintf("new mainnet genesis hash: %s\n", genesis.GetHash().ToString().c_str());
        }
</code>```

The error message:

```<code>Making all in src
  CXX      libgamebit_common_a-chainparams.o
chainparams.cpp:143:13: error: use of undeclared identifier 'Logprintf'
            Logprintf("recalculating params for mainnet.\n");
            ^
chainparams.cpp:144:72: error: member reference base type 'uint32_t'
      (aka 'unsigned int') is not a structure or union
  ...Logprintf("old mainnet genesis nonce: %s\n", genesis.nNonce.ToString().c...
</code>```

Do you have any ideas why im getting this kind of error?
Actually im trying to compile bitcoind.

I hope you can help me.
Thanks!

答:
You should concentrate on the first compiler error:

```<code>error: use of undeclared identifier 'Logprintf'
</code>```

That is, you are using this identifier Logprintf, probably a function, but it is not defined. Likely, you are missing a #include that defines it.

The next error:

```<code>error: member reference base type 'uint32_t'
</code>```

if you look at line 144, column 72, it is this one:

```<code>Logprintf("old mainnet genesis nonce: %s\n", genesis.nNonce.ToString()
                                                           ^
                                                  column 72|
</code>```

So your nNonce is of type uint32_t and you are trying to call member function ToString() on it. But basic types in C++ do not have member functions, only structures (ie, classes) and unions have.

<s>I suspect that you are trying to compile some C++/CLI code with a pure C++ compiler. I'm afraid some translation will be needed.</s>

This last error, you can fix, once you have the proper definition of Logprintf, by writing:

```<code>Logprintf("old mainnet genesis nonce: %u\n", (unsigned)genesis.nNonce);
</code>```

Body:
Hey Stackoverflow Community,
right now i have have the following problem: I want to compile c++ with mac osx.10.11. But every time i want to make the code it gives me an errorcode. I already googled that, but i found nothing.

hashGenesisBlock = uint256("0x01");
if (true && genesis.GetHash() != hashGenesisBlock)
        {
            Logprintf("recalculating params for mainnet.\n");
            Logprintf("old mainnet genesis nonce: %s\n", genesis.nNonce.ToString().c_str());
            Logprintf("old mainnet genesis hash:  %s\n", hashGenesisBlock.ToString().c_str());
            // deliberately empty for loop finds nonce value.
            for(genesis.nNonce == 0; genesis.GetHash() > bnProofOfWorkLimit; genesis.nNonce++){ }
            Logprintf("new mainnet genesis merkle root: %s\n", genesis.hashMerkleRoot.ToString().c_str());
            Logprintf("new mainnet genesis nonce: %s\n", genesis.nNonce.ToString().c_str());
            Logprintf("new mainnet genesis hash: %s\n", genesis.GetHash().ToString().c_str());
        }

The error message:

Making all in src
  CXX      libgamebit_common_a-chainparams.o
chainparams.cpp:143:13: error: use of undeclared identifier 'Logprintf'
            Logprintf("recalculating params for mainnet.\n");
            ^
chainparams.cpp:144:72: error: member reference base type 'uint32_t'
      (aka 'unsigned int') is not a structure or union
  ...Logprintf("old mainnet genesis nonce: %s\n", genesis.nNonce.ToString().c...

Do you have any ideas why im getting this kind of error?
Actually im trying to compile bitcoind.

I hope you can help me.
Thanks!

Body:
You should concentrate on the first compiler error:

error: use of undeclared identifier 'Logprintf'

That is, you are using this identifier Logprintf, probably a function, but it is not defined. Likely, you are missing a #include that defines it.

The next error:

error: member reference base type 'uint32_t'

if you look at line 144, column 72, it is this one:

Logprintf("old mainnet genesis nonce: %s\n", genesis.nNonce.ToString()
                                                           ^
                                                  column 72|

So your nNonce is of type uint32_t and you are trying to call member function ToString() on it. But basic types in C++ do not have member functions, only structures (ie, classes) and unions have.

<s>I suspect that you are trying to compile some C++/CLI code with a pure C++ compiler. I'm afraid some translation will be needed.</s>

This last error, you can fix, once you have the proper definition of Logprintf, by writing:

Logprintf("old mainnet genesis nonce: %u\n", (unsigned)genesis.nNonce);


问:
shell script to create libre office Impress with images
I've some image files generated by an analysis. Every time I do analysis, the file names are same. And I've to create a presentation, and I'm using Libre Office Impress.
Let us say, I've three images image1.png, image2.png, and image3.png, and I should put these images say in page no 3, page no 5, and page no 8

Now, I'm inserting images manually. I know very basic shell scripting. So I was wondering what would be the bash shell script to automatically create an libre office impress file with images automatically inserted at pages mentioned as above.

答:
If the main part of the .odp file doesn't change, it is possible to make a template in flat openDocument format, where the names of the 3 images are updated by script.
A flat document is a uncompressed xml document that can be open with a text editor to change some part manually with caution. Usually the name of such a document is rather with the .fodp You must save this template in flat format, with links to the images rather than incorporate them.

So.
Let us say :

the template is at /path/to/the/template.fodp beside the images im1.png, img2.png, img3.png of the example.

the name of the first image is image1.png, the second image2.png, and the third : image3.png.

the images to be imported are in the same directory /path/to/the/document where will be the final document.

Let us write a script insertImages.sh

```<code>myTpl="$1" # will contains '/path/to/the/template.fodp'
myDir="$2" # will contains '/path/to/the/document'
img1="$3"  # will contains the name of the first image in myDir
img2="$4"  # will contains the name of the second image in myDir
img3="$5"  # will contains the name of the third image in myDir

[[ -f "$1" ]] && cp "$1" "$2/document.fodp" || exit 1 # checks if the template exists and copy it
[[ -f "$3" ]] && sed "$2/document.fodp" "s/img1.png/$3/" || exit 1 # overwrite the name of the first image
[[ -f "$4" ]] && sed "$2/document.fodp" "s/img2.png/$4/" || exit 1 # overwrite the name of the second image
[[ -f "$5" ]] && sed "$2/document.fodp" "s/img3.png/$5/" || exit 1 # overwrite the name of the third image
</code>```

This script should be invoked this way :

insertImages.sh "/path/to/the/template.fodp" "/path/to/the/document" "image1.png" "image2.png" "image3.png"

I'm not a big programmer. So there is probably some mistakes in those lines. But the principle is there.

They are some constaints :

a flat document

relative pathes to the images.

Body:
If the main part of the .odp file doesn't change, it is possible to make a template in flat openDocument format, where the names of the 3 images are updated by script.
A flat document is a uncompressed xml document that can be open with a text editor to change some part manually with caution. Usually the name of such a document is rather with the .fodp You must save this template in flat format, with links to the images rather than incorporate them.

So.
Let us say :

the template is at /path/to/the/template.fodp beside the images im1.png, img2.png, img3.png of the example.

the name of the first image is image1.png, the second image2.png, and the third : image3.png.

the images to be imported are in the same directory /path/to/the/document where will be the final document.

Let us write a script insertImages.sh

myTpl="$1" # will contains '/path/to/the/template.fodp'
myDir="$2" # will contains '/path/to/the/document'
img1="$3"  # will contains the name of the first image in myDir
img2="$4"  # will contains the name of the second image in myDir
img3="$5"  # will contains the name of the third image in myDir

[[ -f "$1" ]] && cp "$1" "$2/document.fodp" || exit 1 # checks if the template exists and copy it
[[ -f "$3" ]] && sed "$2/document.fodp" "s/img1.png/$3/" || exit 1 # overwrite the name of the first image
[[ -f "$4" ]] && sed "$2/document.fodp" "s/img2.png/$4/" || exit 1 # overwrite the name of the second image
[[ -f "$5" ]] && sed "$2/document.fodp" "s/img3.png/$5/" || exit 1 # overwrite the name of the third image

This script should be invoked this way :

insertImages.sh "/path/to/the/template.fodp" "/path/to/the/document" "image1.png" "image2.png" "image3.png"

I'm not a big programmer. So there is probably some mistakes in those lines. But the principle is there.

They are some constaints :

a flat document

relative pathes to the images.


问:
Issue in launching spyder that was installed using pip install on Python 3.6.1
I have windows-7 64 bit machine and Python3.6.1(32-bit) installed on it. I wanted to try spyder as IDE for python. I don't have Anaconda or anything like that. So, I installed spyder from command line (cmd.exe) and it did install successfully and prompt returned.

I think it is installed because

I can see spyder3.exe under C:\Users\UserName\AppData\Local\Programs\Python\Python36-32\Scripts

From cmd.exe when I enter spyder3 it doesn't throw any error and a rotating circle appears which indicates something is processing. But nothing is launched.

After running spyder3 from cmd.exe though nothing gets launched except the rotating circle for couple of seconds, I see spyder.lock folder under C:\Users\UserName\.spyder-py3

When I delete spyder.lock folder under C:\Users\UserName\.spyder-py3 and run spyder3 again in cmd.exe the folder is created again.

Question: How can I make spyder launch? Did I do something wrong while installing spyder or am I trying to launch it with an incorrect method?

答: I had to install PyQt5. It is a requirement for spyder on windows and I was missing it. After I installed it I can launch spyder3 from cmd.exe</p>


问:
How to wait for Function to finish before continuing
In my current project I want to be able to display the users current position on a map.
I have implemented this functionality via the requestLocation method provided by Apple, but the problem is that my code continues without waiting for the requestLocation Function to finish.

The flow is this: First I call the positionController.setPositionViaLocationData() function, which handles the setup and execution of the requestLocation method. In the end this receives the coordinates and stores them in the userPosition member of the PositionController.
In the next line of code I want to access the userPosition via the PositionController but here comes my problem:

The line ...

```<code>var userPosition = positionController.getPosition()
</code>```

... is executed before positionController.setPositionViaLocationData() is finished, thus it takes the default values stored in userPosition.

How can I make my code wait for positionController.setPositionViaLocationData() before executing
var userPosition = positionController.getPosition()?
I already read stuff about Closures and CompletionManagers but I don't get that stuff to work for me.

Heres the code of both classes, first the ViewController who calls the functions:

```<code>import UIKit
import GoogleMaps
import CoreLocation

class MapViewController: UIViewController, CLLocationManagerDelegate {

    let positionController = PositionController()

    override func viewDidLoad() {
        super.viewDidLoad()

        positionController.setPositionViaLocationData()
        var userPosition = positionController.getPosition()
        setUserPositionMarkerOnMapAndShowMap(userPositionLatitude: userPosition.userLatitude, userPositionLongitude: userPosition.userLongitude)

    }

    func setUserPositionMarkerOnMapAndShowMap(userPositionLatitude: Double, userPositionLongitude: Double){
        let camera = GMSCameraPosition.camera(withLatitude: userPositionLatitude,
                                              longitude: userPositionLongitude, zoom:3)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera:camera)
        let marker = GMSMarker()

        self.view = mapView
        marker.snippet = "Munich"
        marker.appearAnimation = GMSMarkerAnimation.pop
        marker.map = mapView

        self.view = mapView
    }

}
</code>```

And now my PositionController class:

```<code>import Foundation
import CoreLocation

class PositionController: CLLocationManager, CLLocationManagerDelegate {

    let locationManager: CLLocationManager
    var userPosition = Position(longitude: 0,latitude: 0)

    override init() {
        self.locationManager = CLLocationManager()
        print("---------------Init---------------------------")
    }

    func setPositionViaLocationData(){

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
        locationManager.requestLocation()
    }

    func setPosition(longitude: Double, latitude: Double){
        userPosition.longitude = longitude
        userPosition.latitude = latitude
    }

    func getPosition() -> (userLongitude: Double, userLatitude: Double){
        return (userPosition.longitude, userPosition.latitude)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
        userPosition.latitude = locValue.latitude
        userPosition.longitude = locValue.longitude
    }
}
</code>```

答:
You can use a delegate to notify MapViewController that the user position has been updated.

You can add the next protocol above the PositionController class definition

```<code>protocol PositionControllerDelegate: class {
  func didUpdatePosition(_ newPosition: Position)
}
</code>```

Then add a new optional property to PositionController

weak var delegate: PositionControllerDelegate?

And then call the delegate method:

```<code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let locValue: CLLocationCoordinate2D = manager.location!.coordinate
    print("locations = \(locValue.latitude) \(locValue.longitude)")
    userPosition.latitude = locValue.latitude
    userPosition.longitude = locValue.longitude
    delegate?.didUpdatePosition(userPosition)
}
</code>```

On the MapViewController side, you only must implement the protocol and assign self to the delegate of PositionController.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    positionController.setPositionViaLocationData()
    positionController.delegate = self
    var userPosition = positionController.getPosition()
    setUserPositionMarkerOnMapAndShowMap(userPositionLatitude: userPosition.userLatitude, userPositionLongitude: userPosition.userLongitude)
}

extension MapViewController: PositionControllerDelegate {
  func didUpdatePosition(_ newPosition: Position) {
    //Do whatever you want with the position
  }
}
</code>```

Body:
In my current project I want to be able to display the users current position on a map.
I have implemented this functionality via the requestLocation method provided by Apple, but the problem is that my code continues without waiting for the requestLocation Function to finish.

The flow is this: First I call the positionController.setPositionViaLocationData() function, which handles the setup and execution of the requestLocation method. In the end this receives the coordinates and stores them in the userPosition member of the PositionController.
In the next line of code I want to access the userPosition via the PositionController but here comes my problem:

The line ...

var userPosition = positionController.getPosition()

... is executed before positionController.setPositionViaLocationData() is finished, thus it takes the default values stored in userPosition.

How can I make my code wait for positionController.setPositionViaLocationData() before executing
var userPosition = positionController.getPosition()?
I already read stuff about Closures and CompletionManagers but I don't get that stuff to work for me.

Heres the code of both classes, first the ViewController who calls the functions:

import UIKit
import GoogleMaps
import CoreLocation

class MapViewController: UIViewController, CLLocationManagerDelegate {

    let positionController = PositionController()

    override func viewDidLoad() {
        super.viewDidLoad()

        positionController.setPositionViaLocationData()
        var userPosition = positionController.getPosition()
        setUserPositionMarkerOnMapAndShowMap(userPositionLatitude: userPosition.userLatitude, userPositionLongitude: userPosition.userLongitude)

    }

    func setUserPositionMarkerOnMapAndShowMap(userPositionLatitude: Double, userPositionLongitude: Double){
        let camera = GMSCameraPosition.camera(withLatitude: userPositionLatitude,
                                              longitude: userPositionLongitude, zoom:3)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera:camera)
        let marker = GMSMarker()

        self.view = mapView
        marker.snippet = "Munich"
        marker.appearAnimation = GMSMarkerAnimation.pop
        marker.map = mapView

        self.view = mapView
    }

}

And now my PositionController class:

import Foundation
import CoreLocation

class PositionController: CLLocationManager, CLLocationManagerDelegate {

    let locationManager: CLLocationManager
    var userPosition = Position(longitude: 0,latitude: 0)

    override init() {
        self.locationManager = CLLocationManager()
        print("---------------Init---------------------------")
    }

    func setPositionViaLocationData(){

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
        locationManager.requestLocation()
    }

    func setPosition(longitude: Double, latitude: Double){
        userPosition.longitude = longitude
        userPosition.latitude = latitude
    }

    func getPosition() -> (userLongitude: Double, userLatitude: Double){
        return (userPosition.longitude, userPosition.latitude)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
        userPosition.latitude = locValue.latitude
        userPosition.longitude = locValue.longitude
    }
}

Body:
You can use a delegate to notify MapViewController that the user position has been updated.

You can add the next protocol above the PositionController class definition

protocol PositionControllerDelegate: class {
  func didUpdatePosition(_ newPosition: Position)
}

Then add a new optional property to PositionController

weak var delegate: PositionControllerDelegate?

And then call the delegate method:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let locValue: CLLocationCoordinate2D = manager.location!.coordinate
    print("locations = \(locValue.latitude) \(locValue.longitude)")
    userPosition.latitude = locValue.latitude
    userPosition.longitude = locValue.longitude
    delegate?.didUpdatePosition(userPosition)
}

On the MapViewController side, you only must implement the protocol and assign self to the delegate of PositionController.

override func viewDidLoad() {
    super.viewDidLoad()

    positionController.setPositionViaLocationData()
    positionController.delegate = self
    var userPosition = positionController.getPosition()
    setUserPositionMarkerOnMapAndShowMap(userPositionLatitude: userPosition.userLatitude, userPositionLongitude: userPosition.userLongitude)
}

extension MapViewController: PositionControllerDelegate {
  func didUpdatePosition(_ newPosition: Position) {
    //Do whatever you want with the position
  }
}


问:
At least one non-null i..... as a @Bean when using @EnableWebSecurity. Hint try extending WebSecurityConfigurerAdapter
Here is what I could not figure out after spending hours try to solve it. I am studying about spring security with java configuration. I came up with the following exception but has no clue what I am supposed to do.

```<code>  Oct 22, 2015 6:00:57 AM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalStateException: At least one non-null instance of WebSecurityConfigurer must be exposed as a @Bean when using @EnableWebSecurity. Hint try extending WebSecurityConfigurerAdapter

Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalStateException: At least one non-null instance of WebSecurityConfigurer must be exposed as a @Bean when using @EnableWebSecurity. Hint try extending WebSecurityConfigurerAdapter
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 33 more

Caused by: java.lang.IllegalStateException: At least one non-null instance of WebSecurityConfigurer must be exposed as a @Bean when using @EnableWebSecurity. Hint try extending WebSecurityConfigurerAdapter
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:90)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$1c09b217.CGLIB$springSecurityFilterChain$1(<generated>)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$1c09b217$$FastClassBySpringCGLIB$$7b0370bc.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
</code>```

The security configuration is

```<code>@Configuration
@EnableWebSecurity
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/allmessages*").hasAnyRole("USER", "ANONYMOUS")
                .antMatchers("/postmessages*").hasRole("USER")
                .antMatchers("/deletemessages*").hasRole("ADMIM")
            .and()
                .httpBasic();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("tadtdab").password("tadtab").authorities("ROLE_ADMIN","ROLE_USER")
                .and().withUser("tadi").password("tadi").authorities("ROLE_USER");
    }
}
</code>```

答:
I had the same issue, and just after reading this post i found the answer : it's in the stacktrace : if you go to the end of the message, you can find this :

```<code>Hint try extending WebSecurityConfigurerAdapter
</code>```

So i just found my webSecurityConfig class and added

```<code>extends WebSecurityConfigurerAdapter
</code>```

And my server started correctly

Body:
Here is what I could not figure out after spending hours try to solve it. I am studying about spring security with java configuration. I came up with the following exception but has no clue what I am supposed to do.

  Oct 22, 2015 6:00:57 AM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalStateException: At least one non-null instance of WebSecurityConfigurer must be exposed as a @Bean when using @EnableWebSecurity. Hint try extending WebSecurityConfigurerAdapter

Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalStateException: At least one non-null instance of WebSecurityConfigurer must be exposed as a @Bean when using @EnableWebSecurity. Hint try extending WebSecurityConfigurerAdapter
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 33 more

Caused by: java.lang.IllegalStateException: At least one non-null instance of WebSecurityConfigurer must be exposed as a @Bean when using @EnableWebSecurity. Hint try extending WebSecurityConfigurerAdapter
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:90)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$1c09b217.CGLIB$springSecurityFilterChain$1(<generated>)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$1c09b217$$FastClassBySpringCGLIB$$7b0370bc.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)

The security configuration is

@Configuration
@EnableWebSecurity
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/allmessages*").hasAnyRole("USER", "ANONYMOUS")
                .antMatchers("/postmessages*").hasRole("USER")
                .antMatchers("/deletemessages*").hasRole("ADMIM")
            .and()
                .httpBasic();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("tadtdab").password("tadtab").authorities("ROLE_ADMIN","ROLE_USER")
                .and().withUser("tadi").password("tadi").authorities("ROLE_USER");
    }
}

Body:
I had the same issue, and just after reading this post i found the answer : it's in the stacktrace : if you go to the end of the message, you can find this :

Hint try extending WebSecurityConfigurerAdapter

So i just found my webSecurityConfig class and added

extends WebSecurityConfigurerAdapter

And my server started correctly


问:
Kivy: How to check for the existence of a child widget
In my .py file I have a screen that looks something like:

```<code>class ExampleScreen(Screen):
    def create_layout(self):
        box = BoxLayout(orientation='vertical')
        # other layout stuff in here
        self.add_widget(box)
</code>```

In my .kv file, I have a button which, when pressed, calls this function and displays this layout on <ExampleScreen>. However, I would like to be able to press this button and first check if this layout already exists, and if so, remove it before adding a new one. I anticipate modifying create_layout() to something like:

```<code>def create_layout(self):
    if (box layout child has already been added):
        self.remove_widget(box layout child)
    box = BoxLayout(orientation='vertical')
    # other layout stuff in here
    self.add_widget(box)
</code>```

Does anyone know how to do this? Using id somehow?

答:
Each widget has a children property so you may want to use it.

```<code>for c in list(self.children):
    if isinstance(c, BoxLayout): self.remove(c)
</code>```

You can also assign it to the widget: (as mentioned in Edvardas Dlugauskas anwser)

```<code>def __init__(self, **kw):
    self.box = None
    ...

def create_layout(self):
    if self.box: self.remove(self.box)
    self.box = BoxLayout(orientation='vertical')
    self.add_widget(box)
</code>```

Body:
In my .py file I have a screen that looks something like:

class ExampleScreen(Screen):
    def create_layout(self):
        box = BoxLayout(orientation='vertical')
        # other layout stuff in here
        self.add_widget(box)

In my .kv file, I have a button which, when pressed, calls this function and displays this layout on <ExampleScreen>. However, I would like to be able to press this button and first check if this layout already exists, and if so, remove it before adding a new one. I anticipate modifying create_layout() to something like:

def create_layout(self):
    if (box layout child has already been added):
        self.remove_widget(box layout child)
    box = BoxLayout(orientation='vertical')
    # other layout stuff in here
    self.add_widget(box)

Does anyone know how to do this? Using id somehow?

Body:
Each widget has a children property so you may want to use it.

for c in list(self.children):
    if isinstance(c, BoxLayout): self.remove(c)

You can also assign it to the widget: (as mentioned in Edvardas Dlugauskas anwser)

def __init__(self, **kw):
    self.box = None
    ...

def create_layout(self):
    if self.box: self.remove(self.box)
    self.box = BoxLayout(orientation='vertical')
    self.add_widget(box)