问:
Angular 5 click bind to anchor tag
I need to bind a click event on an anchor in my template:

My html looks like this:

```<code><a (click)="deleteUser(user)">
    <i class="la la-trash"></i>
</a>
</code>```

user is a variable from a previous *ngFor="let user of users"

The deleteUser() function is declared on my users.component.ts file:

```<code>import { Component, OnInit, ViewEncapsulation, AfterViewInit } from '@angular/core';
import { Helpers } from '../../../../helpers';
import { ScriptLoaderService } from '../../../../_services/script-loader.service';

import { User } from '../../../../models/user';
import { UsersService } from '../../../../_services/users.service';

import swal from 'sweetalert';

@Component({
    selector: ".m-grid__item.m-grid__item--fluid.m-wrapper",
    templateUrl: "./users.component.html",
    styleUrls: ["./users.component.scss"],
    encapsulation: ViewEncapsulation.None,
})
export class UsersComponent implements OnInit, AfterViewInit {

    users: User[];

    constructor(
        private _script: ScriptLoaderService,
        private usersService: UsersService
    ) { }

    ngOnInit() {
        this.getUsers();
    }

    getUsers(): void {
        this.usersService.getUsers()
            .subscribe(users => this.users = users)
    }

    ngAfterViewInit() {
        this._script.load('.m-grid__item.m-grid__item--fluid.m-wrapper',
            'assets/app/js/users.js');
    }

    deleteUser(user: User): void {
        swal({
            title: `Eliminar usuario ${user.name}`,
            text: "Una vez eliminado, toda su información será eliminada!",
            icon: "warning",
            dangerMode: true,
          })
          .then((willDelete) => {
            if (willDelete) {
                this.usersService.deleteUser(user.id)
                    .subscribe(() => {
                        swal("Usuario eliminado", {
                            icon: "success",
                        });
                    });
            }
          });
    }

}
</code>```

However that click event is never triggered. It simply doesn't do anything. No errors, nothing.
I've tried a lot of variations to try to make it work:

routerLink=""

[routerLink]=""

href=""

href="#"

href="#!"

href="!#"

Change  tag for
, ,
, <button> but none worked

I've tried this another question but I think it didn't work because it is Angular2 (I'm using Angular 5).

The template I'm using is Metronic (just in case is relevant)

答:
I faced same issue where click event on  tag was not working.

Work around for that is to wrap  tag and put click event on that tag like below

```<code><a href="javascript: void(0)" >
<i class="la la-trash" (click)="deleteUser(user)"></i>
</a>
</code>```

With this way click event started working but still i had question in my mind why it was not working on  tag after some investigation i found it was not working because of below style applied on  tag

```<code>pointer-events: none;
</code>```

To fix that issue either remove above style or add below style

```<code>pointer-events: all;
</code>```

Hope this will help if same problem is in your case

Apart from this as a best practice always add href="javascript: void(0)" in  tag  to avoid it to navigating to home page and style cursor: pointer; if default style of  tag is getting over-ridden by some style in your appliction

Title: Angular 5 click bind to anchor tag

Body:
I need to bind a click event on an anchor in my template:

My html looks like this:

user is a variable from a previous *ngFor="let user of users"

The deleteUser() function is declared on my users.component.ts file:

import { Component, OnInit, ViewEncapsulation, AfterViewInit } from '@angular/core';
import { Helpers } from '../../../../helpers';
import { ScriptLoaderService } from '../../../../_services/script-loader.service';

import { User } from '../../../../models/user';
import { UsersService } from '../../../../_services/users.service';

import swal from 'sweetalert';

@Component({
    selector: ".m-grid__item.m-grid__item--fluid.m-wrapper",
    templateUrl: "./users.component.html",
    styleUrls: ["./users.component.scss"],
    encapsulation: ViewEncapsulation.None,
})
export class UsersComponent implements OnInit, AfterViewInit {

    users: User[];

    constructor(
        private _script: ScriptLoaderService,
        private usersService: UsersService
    ) { }

    ngOnInit() {
        this.getUsers();
    }

    getUsers(): void {
        this.usersService.getUsers()
            .subscribe(users => this.users = users)
    }

    ngAfterViewInit() {
        this._script.load('.m-grid__item.m-grid__item--fluid.m-wrapper',
            'assets/app/js/users.js');
    }

    deleteUser(user: User): void {
        swal({
            title: `Eliminar usuario ${user.name}`,
            text: "Una vez eliminado, toda su información será eliminada!",
            icon: "warning",
            dangerMode: true,
          })
          .then((willDelete) => {
            if (willDelete) {
                this.usersService.deleteUser(user.id)
                    .subscribe(() => {
                        swal("Usuario eliminado", {
                            icon: "success",
                        });
                    });
            }
          });
    }

}

However that click event is never triggered. It simply doesn't do anything. No errors, nothing.
I've tried a lot of variations to try to make it work:

routerLink=""

[routerLink]=""

href=""

href="#"

href="#!"

href="!#"

Change  tag for
, ,
, <button> but none worked

I've tried this another question but I think it didn't work because it is Angular2 (I'm using Angular 5).

The template I'm using is Metronic (just in case is relevant)

Body:
I faced same issue where click event on < a > tag was not working.

Work around for that is to wrap < i > tag and put click event on that tag like below

<a href="javascript: void(0)" >
<i class="la la-trash" (click)="deleteUser(user)"></i>
</a>

With this way click event started working but still i had question in my mind why it was not working on < a > tag after some investigation i found it was not working because of below style applied on < a > tag

pointer-events: none;

To fix that issue either remove above style or add below style

pointer-events: all;

Hope this will help if same problem is in your case

Apart from this as a best practice always add href="javascript: void(0)" in < a > tag  to avoid it to navigating to home page and style cursor: pointer; if default style of < a > tag is getting over-ridden by some style in your appliction


来源: stackexchange

问:
How to communicate information between a python script and an iPhone app
I have a python script running on a Raspberry Pi, and this script gathers real-time information about the Raspberry Pi, storing the information into variables. I would like to use an iPhone app that I am creating to retrieve this information and display it on screen each time a button is pressed.

I have found solutions online involving REST APIs as well as software like ZeroMQ; however, I am very unfamiliar with these types of things and am unsure which approach to use. What is the simplest approach that you would suggest, and how might I go about implementing it?

答:
Here's a few ways I thought of doing it:

Use SMPT email protocol to send yourself an email which you can access on your iphone.

Pay for an SMS service to send SMS messages to your iphone.

Push to https://jsonstorage.net/ on your Rasberry Pi, then access the storage bin on your iphone.

If it's running Windows or Linux. You can download Dropbox Desktop. This will give you a folder that is automatically updated on changes which you can check from anywhere.

Further details:

How to update a json bin with python

```<code>headers = {'Content-Type': "application/json; charset=utf-8",'dataType': "json"}
data = json.dumps(json_data_you_want_to_upload)
url = https://jsonstorage.net/api/items/your-bin-id
resp = requests.put(url, headers=headers, data=data)
if resp.status_code == 200 or 201:
    print(f'Data successfull uploaded: {resp.json()})')
else:
    print(f'Error! Could not upload to the database: {resp.json()}')

</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here's a few ways I thought of doing it:

Use SMPT email protocol to send yourself an email which you can access on your iphone.

Pay for an SMS service to send SMS messages to your iphone.

Push to https://jsonstorage.net/ on your Rasberry Pi, then access the storage bin on your iphone.

If it's running Windows or Linux. You can download Dropbox Desktop. This will give you a folder that is automatically updated on changes which you can check from anywhere.

Further details:

How to update a json bin with python

headers = {'Content-Type': "application/json; charset=utf-8",'dataType': "json"}
data = json.dumps(json_data_you_want_to_upload)
url = https://jsonstorage.net/api/items/your-bin-id
resp = requests.put(url, headers=headers, data=data)
if resp.status_code == 200 or 201:
    print(f'Data successfull uploaded: {resp.json()})')
else:
    print(f'Error! Could not upload to the database: {resp.json()}')


问:
How can I force UI updated in Swift?
I am using swift to develop a chess game.  When the computer is playing itself, the display does not get updated when a move completed until it is out of the loop (in this case the game is ended).

I have tried to dispatch it in a background queue to generate a move and dispatch it back to main queue to make the move and update the display.  While it seems to help updating the display, but I have no way to predict the completion of each background queue.  That messes up the order of the moves.

Is there a better way to make computer playing itself and properly update the display after each move is completed?

```<code>while chessGame.checkmate != true {
    DispatchQueue.global(qos: .background).async {
        let bestMove = chessAI.findBestMove(depth : chessGame.searchDepth)
        if bestMove != nil {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
                chessMove.makeMove(m : bestMove!)
                self.boardView.setNeedsDisplay()
            }
        } else {
            print("CheckMate!")
            chessGame.checkmate = true
        }
    }
}
</code>```

答:
You can force display immediately (by calling displayIfNeeded), but it won't help.

The problem is that the while loop does not pause between iterations: it just keeps looping at top speed. Thus the while loop is a poor strategy.

Instead, use recursion. This puts control of when to do the next iteration in your hands, namely, you recurse after a delay. That is a loop where you get to pause between iterations.

Pseudocode:

```<code>func nextMove() {
    DispatchQueue.global(qos: .background).async {
        let bestMove = chessAI.findBestMove(depth : chessGame.searchDepth)
        if bestMove != nil {
            DispatchQueue.main.asyncAfter(deadline: .now() + 3) { // or whatever
                chessMove.makeMove(m : bestMove!)
                self.boardView.setNeedsDisplay()
                if chessGame.checkmate != true {
                    nextMove()
                } else {
                    print("checkmate")
                }
            }
        }
    }
}
</code>```

Title: How can I force UI updated in Swift?

Body:
I am using swift to develop a chess game.  When the computer is playing itself, the display does not get updated when a move completed until it is out of the loop (in this case the game is ended).

I have tried to dispatch it in a background queue to generate a move and dispatch it back to main queue to make the move and update the display.  While it seems to help updating the display, but I have no way to predict the completion of each background queue.  That messes up the order of the moves.

Is there a better way to make computer playing itself and properly update the display after each move is completed?

while chessGame.checkmate != true {
    DispatchQueue.global(qos: .background).async {
        let bestMove = chessAI.findBestMove(depth : chessGame.searchDepth)
        if bestMove != nil {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
                chessMove.makeMove(m : bestMove!)
                self.boardView.setNeedsDisplay()
            }
        } else {
            print("CheckMate!")
            chessGame.checkmate = true
        }
    }
}

Body:
You can force display immediately (by calling displayIfNeeded), but it won't help.

The problem is that the while loop does not pause between iterations: it just keeps looping at top speed. Thus the while loop is a poor strategy.

Instead, use recursion. This puts control of when to do the next iteration in your hands, namely, you recurse after a delay. That is a loop where you get to pause between iterations.

Pseudocode:

func nextMove() {
    DispatchQueue.global(qos: .background).async {
        let bestMove = chessAI.findBestMove(depth : chessGame.searchDepth)
        if bestMove != nil {
            DispatchQueue.main.asyncAfter(deadline: .now() + 3) { // or whatever
                chessMove.makeMove(m : bestMove!)
                self.boardView.setNeedsDisplay()
                if chessGame.checkmate != true {
                    nextMove()
                } else {
                    print("checkmate")
                }
            }
        }
    }
}


问:
Azure functions host.json somehow being ignored
I have a V2 Azure function. I have configured this function to run only one function in parallel. This is my host.json file:

{
  "version": "2.0",
  "extensions": {
    "queues": {
      "batchSize": 1,
      "newBatchThreshold": 0
    }
  }
}

When I start the function on my local development machine it shows the following output:

[27-5-2019 12:43:06] Starting Rpc Initialization Service.

[27-5-2019 12:43:06] Initializing RpcServer

[27-5-2019 12:43:06] Building host: startup suppressed:False, configuration
  suppressed: False

[27-5-2019 12:43:07] Initializing Host.

[27-5-2019 12:43:07] Host initialization: ConsecutiveErrors=0, StartupCount=1

...

[27-5-2019 12:43:07] QueuesOptions

[27-5-2019 12:43:07] {

[27-5-2019 12:43:07]   "BatchSize": 16,

[27-5-2019 12:43:07]   "NewBatchThreshold": 8,

[27-5-2019 12:43:07]   "MaxPollingInterval": "00:00:02",

[27-5-2019 12:43:07]   "MaxDequeueCount": 5,**

[27-5-2019 12:43:07]   "VisibilityTimeout": "00:00:00"

Following this output it seems to not have registered these settings. The behaviour also shows this as the function runs in parallel instead of one at a time. What am I doing wrong?

Any help is appreciated.

Reference to MS host.json specification

答:
Seems like an open issue reported here, Functions Startup ignored host.json

If you have [assembly: WebJobsStartup(typeof(Startup))] in your code, removing that should recognized host.json correctly.


问:
Show ContextMenu on Left Click using only XAML
The default behavior of a WPF ContextMenu is to display it when the user right-clicks.  I want the ContextMenu to show when the user left-clicks.  It seems like this should be a simple property on ContextMenu, but it is not.

I rigged it, so that I handle the LeftMouseButtonDown event in the code-behind and then display the context menu.

I'm using MVVM in my project which means I'm using DataTemplates for the items that have the context menus. It would be much more elegant to get rid of the code-behind and find a way to display the context menu using triggers or properties in the XAML.

Any ideas or solutions to this issue?

答:
What I would suggest doing is making a new static class with attached DependencyProperty.  Call the class LeftClickContextMenu and the property Enabled (just ideas).  When your registering the DependencyProperty add an on changed callback.  Then in the property changed callback if Enabled is set to true then add a handler to the LeftMouseButtonDown event and do your stuff there.  If Enabled is set to false remove the handler.  This sould allow you to set it like a property on anything by simply using the following in your xaml.

```<code><Border namespace:LeftClickContextMenu.Enabled="True" />
</code>```

This technique is called an attached behavior and you can read more about it in this code project article: http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

OwnerDisplayName: timothymcgrath

ContentLicense: CC BY-SA 3.0

Body:
What I would suggest doing is making a new static class with attached DependencyProperty.  Call the class LeftClickContextMenu and the property Enabled (just ideas).  When your registering the DependencyProperty add an on changed callback.  Then in the property changed callback if Enabled is set to true then add a handler to the LeftMouseButtonDown event and do your stuff there.  If Enabled is set to false remove the handler.  This sould allow you to set it like a property on anything by simply using the following in your xaml.

<Border namespace:LeftClickContextMenu.Enabled="True" />

This technique is called an attached behavior and you can read more about it in this code project article: http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

OwnerDisplayName: Caleb Vear

ContentLicense: CC BY-SA 2.5


问:
Hide keyboard when user touches uiview
I have a UIView with multiple text boxes. Now i have used delegates to change the responder from from text field to another. In this case my key board goes away when the user comes to last text field.

but now i want to hide my key board when the user touches UIView(touches any where on screen apart from text boxes). Can some one help me with this.

Thanks

答:
SO I agonized over this and I figured it out..

you don't need the other button or anything.

All you need to do is select "Files owner", in the inspector drag from its textField outlet (or whatever you named it) to your actual textfield (via whatever you named it) This will be in addition to whatever inputs you already had wired up.

and ofcourse in addition to the Control outlet (UIview changed to UIControl via inspector) to files owner via backgroundtouched...the first thing we all tried

Title: Hide keyboard when user touches uiview


问:
Response 400 on Microsoft Graph - Create calendar event: Property emailAddress in payload has a value that does not match schema
I'm creating a new calendar event through Microsoft Graph. I'm trying to insert organizer information on a Graph Calendar Event

```<code>if organizer.get('email'):
    log('email: ')
    log(organizer.get('email', ''))

eventJson["organizer"] = {
    "emailAddress": {
        "address":str(organizer.get('email', ''))
    }
}
</code>```

log:

```<code>2019-05-17T17:05:45.421475+00:00 app[web.1]: ERROR
2019-05-17T17:05:45.421493+00:00 app[web.1]: <Response [400]>
2019-05-17T17:05:45.421501+00:00 app[web.1]:
{
  "error": {
    "code": "BadRequest",
    "message": "Property emailAddress in payload has a value that does not match schema.",
    "innerError": {
      "request-id": "xxxxxxxxxxxx",
      "date": "2019-05-17T17:05:45"
    }
  }
}
</code>```

I have already checked organizer.get('email') content. Also, in some other events, the same structure worked well. I don't know what the schema expects.

This is the example I have found on the documentation

```<code>"organizer": {
    "emailAddress": {
        "name": "Megan Bowen",
        "address": "MeganB@contoso.OnMicrosoft.com"
    }
}
</code>```

答:
You can't set the organizer in the POST body.

If you are using /me/calendars/{id}/events the user logged in is the organizer (me).

If you use /users/{id | userPrincipalName}/calendars/{id}/events you set the organizer with the {id | userPrincipalName} (for example with application permisions app)

Example: /users/Guilherme@mail.com/calendars/{id}/events. Organizer:Guilherme@mail.com

In the link you provided Graph docs for Create Event you have the request example (not response)

Body:
I'm creating a new calendar event through Microsoft Graph. I'm trying to insert organizer information on a Graph Calendar Event

if organizer.get('email'):
    log('email: ')
    log(organizer.get('email', ''))

eventJson["organizer"] = {
    "emailAddress": {
        "address":str(organizer.get('email', ''))
    }
}

log:

2019-05-17T17:05:45.421475+00:00 app[web.1]: ERROR
2019-05-17T17:05:45.421493+00:00 app[web.1]: <Response [400]>
2019-05-17T17:05:45.421501+00:00 app[web.1]:
{
  "error": {
    "code": "BadRequest",
    "message": "Property emailAddress in payload has a value that does not match schema.",
    "innerError": {
      "request-id": "xxxxxxxxxxxx",
      "date": "2019-05-17T17:05:45"
    }
  }
}

I have already checked organizer.get('email') content. Also, in some other events, the same structure worked well. I don't know what the schema expects.

This is the example I have found on the documentation

"organizer": {
    "emailAddress": {
        "name": "Megan Bowen",
        "address": "MeganB@contoso.OnMicrosoft.com"
    }
}


问:
jQuery each function not working need to replace each attribute
I have this html

```<code><form method="POST" action="" id="order" class="forms">
    <div>
        <span class="col1">Ref.</span>
        <span class="col2">Number</span>
        <span class="col3">Color</span>
        <span class="col4">Remarks</span>
        <span class="col5">Prijs</span>
    </div>
    <div class="order">
        <input type="text" name="ref-1" class="col1" />
        <input type="text" name="num-1" class="col2" />
        <input type="text" name="color-1" class="col3" />
        <input type="text" name="remark-1" class="col4" />
        <input type="text" name="price-1" class="col5" />
    </div>
    <a id="add" href="#">+</a>
</form>
</code>```

And this jquery

```<code>$("#add").click(function() {
    $("#order").children(":eq(1)").clone().each(function() {
            var index = $("#order").children().length - 1;
            alert(index);

        $(this).children().find(":input").each(function() {

                alert(index);

                    $(this).attr("[name]", function(i, v) {

                        return v.substr(0, v.lastIndexOf("-") + 1) + index;

                    }).val("");

                });
    }).insertBefore("#add");
});
</code>```

I need to replace the -1 part of each input name to the incremented value.
But the js never gets to the $(this).attr() function
When I run this code it doesn't show the second alert box when I click #add

答: Remove .find(":input") and pass ":input" as argument to .children(). children() can retrieve child elements even by filtering the elements.</p>

Body:
I have this html

<form method="POST" action="" id="order" class="forms">

        Ref.
        Number
        Color
        Remarks
        Prijs

        <input type="text" name="ref-1" class="col1" />
        <input type="text" name="num-1" class="col2" />
        <input type="text" name="color-1" class="col3" />
        <input type="text" name="remark-1" class="col4" />
        <input type="text" name="price-1" class="col5" />

    +
</form>

And this jquery

$("#add").click(function() {
    $("#order").children(":eq(1)").clone().each(function() {
            var index = $("#order").children().length - 1;
            alert(index);

        $(this).children().find(":input").each(function() {

                alert(index);

                    $(this).attr("[name]", function(i, v) {

                        return v.substr(0, v.lastIndexOf("-") + 1) + index;

                    }).val("");

                });
    }).insertBefore("#add");
});

I need to replace the -1 part of each input name to the incremented value.
But the js never gets to the $(this).attr() function
When I run this code it doesn't show the second alert box when I click #add


问:
Java Codemodel - Annotate a method or class
I am using CodeModel to programmatically generate .java files. This is a snippet of code to create a method:

```<code>JCodeModel jCodeModel = new JCodeModel();
JDefinedClass definedClass = jCodeModel._class("Foo");

//To generate method
JMethod method = definedClass.method(3, String.class, "getCustomerInfo()");
</code>```

When I run (assume all other necessary codes are there);

```<code>public String getCustomerInfo() { }
</code>```

But I want to annotate above method like this:

```<code>@GET
@Path("/getCustomerInfo")
public String getCustomerInfo() { }
</code>```

For which I tried below methods:
method.annotate(...) and method.annotate2(...)

But those methods accept only Class files as a arguments (ie like in the form SomeClass.class), but I want to be able to String as an argument and that class will be available dynamically at run time.

Say I should be able to do like this: method.annotate("Path").

Can anyone help me?

答:
```<code>public void setControllerMapping(Pagemaster pagemaster)  throws Exception
        {
            // Instantiate a new JCodeModel
            JCodeModel codeModel = new JCodeModel();

            // Create a new class

            JDefinedClass mappingController = codeModel._class("com.discom.springmvc.controllerTemp.ViewUrlController"+pagemaster.getUrl());
            mappingController.annotate(codeModel.ref("org.springframework.stereotype.Controller"));
            mappingController.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/");
            mappingController.annotate(codeModel.ref("org.springframework.web.bind.annotation.SessionAttributes")).param("value", "roles");

            JFieldVar jSearchDao = mappingController.field(JMod.NONE, SearchDao.class, "searchDao");
            jSearchDao.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
            JFieldVar jAddService = mappingController.field(JMod.NONE, AddService.class, "addService");
            jAddService.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
            JFieldVar httpSession = mappingController.field(JMod.PRIVATE, HttpSession.class, "httpSession");
            httpSession.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
            JFieldVar listService = mappingController.field(JMod.PRIVATE, ListService.class, "listService");
            listService.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
            /*codeModel.directClass("java.util.Date");
            codeModel.directClass("java.sql.Timestamp");
            codeModel.directClass("org.springframework.http.HttpStatus");
            codeModel.directClass("org.springframework.security.core.context.SecurityContextHolder");
            codeModel.directClass("org.springframework.security.core.userdetails.UserDetails");
            codeModel.directClass("com.fasterxml.jackson.databind.ObjectMapper");
            codeModel.directClass("java.util.List");*/
            JFieldVar saveDate = mappingController.field(JMod.NONE, Date.class, "saveDatee");
            JFieldVar timeStampDate = mappingController.field(JMod.NONE, Timestamp.class, "timeStampDatee");
            JFieldVar httpStatus = mappingController.field(JMod.NONE, HttpStatus.class, "httpStatuss");
            JFieldVar securityContextHolder = mappingController.field(JMod.NONE, SecurityContextHolder.class, "securityContextHolder");
            JFieldVar userDetails = mappingController.field(JMod.NONE, UserDetails.class, "userDetails");
            JFieldVar objectMapper = mappingController.field(JMod.NONE, ObjectMapper.class, "objectMapperr");
            JFieldVar listt = mappingController.field(JMod.NONE, List.class, "listt");

            // Add Mapping method
            JMethod mappingMethod = mappingController.method(JMod.PUBLIC, String.class, pagemaster.getUrl()+"URL");
            JVar model = mappingMethod.param(ModelMap.class, "model");
            mappingMethod.body().invoke(model, "addAttribute").arg("pagemaster").arg(jSearchDao.invoke("findPagemasterByUrl").arg(pagemaster.getUrl()));
            mappingMethod.body().invoke(model, "addAttribute").arg("submenu").arg(jSearchDao.invoke("findSubMenuById").arg(jSearchDao.invoke("findPagemasterByUrl").arg(pagemaster.getUrl()).invoke("getSubmenuId").invoke("toString")));
            mappingMethod.body().invoke(model, "addAttribute").arg("fieldsList").arg(jSearchDao.invoke("getTemplateFieldsList").arg(jSearchDao.invoke("findPagemasterByUrl").arg(pagemaster.getUrl()).invoke("getTemplateId").invoke("toString")));
            mappingMethod.body()._return(JExpr.ref("\""+pagemaster.getUrl()+"Def\""));
            mappingMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/"+pagemaster.getUrl()).param("method", RequestMethod.GET);

            // Add Save method
            JMethod saveMethod = mappingController.method(JMod.PUBLIC, codeModel.ref(ResponseEntity.class).narrow(String.class), "save"+pagemaster.getPageTitle().replace(" ", ""));
            List<TemplateFields> reqFields = searchDao.getTemplateFieldsList(pagemaster.getTemplateId().toString());
            for(TemplateFields tf:reqFields)
            {
                if(!tf.getFieldName().equals("id") && !tf.getFieldName().contains("created") && !tf.getFieldName().contains("updated"))
                {
                    JVar reqParam = saveMethod.param(getDataType(tf.getFieldType()), tf.getFieldName());
                    if(tf.getIsNull()==false)
                        reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName());
                    else
                        reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName()).param("required", false);
                }
            }
            Template template = reqFields.get(0).getTemplateId();
            JFieldVar templateTableName = mappingController.field(JMod.NONE, codeModel.ref("com.discom.springmvc.pojo."+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)), template.getTablename()+"Obj");
            saveMethod.body().directStatement("Date saveDate = new Date();");
            saveMethod.body().directStatement("Timestamp timeStampDate = new Timestamp(saveDate.getTime());");
            saveMethod.body().directStatement(template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" "+template.getTablename()+" = new "+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"();");
            for(TemplateFields tf:reqFields)
            {
                if(tf.getFieldName().equals("id"))
                {
                    saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(null);");
                }
                else if(tf.getFieldName().equals("createdBy") || tf.getFieldName().equals("updatedBy"))
                {
                    saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(getPrincipal());");
                }
                else if(tf.getFieldName().equals("createdOn") || tf.getFieldName().equals("updatedOn"))
                {
                    saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(timeStampDate);");
                }
                else
                {
                    saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"("+tf.getFieldName()+");");
                }
            }
            saveMethod.body().directStatement("boolean sts = false;");
            saveMethod.body().directStatement("// create save method first");
            saveMethod.body().directStatement("//sts = addService.save"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"("+template.getTablename()+");");
            saveMethod.body().directStatement("if(sts==false){");
            saveMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" not saved.\",HttpStatus.BAD_REQUEST);");
            saveMethod.body().directStatement("}");
            saveMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" Successfully saved.\",HttpStatus.OK);");
            saveMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/save"+pagemaster.getPageTitle().replace(" ", "")).param("method", RequestMethod.POST);

            // Add Update method
            JMethod updateMethod = mappingController.method(JMod.PUBLIC, codeModel.ref(ResponseEntity.class).narrow(String.class), "update"+pagemaster.getPageTitle().replace(" ", ""));
            for(TemplateFields tf:reqFields)
            {
                if(!tf.getFieldName().contains("created") && !tf.getFieldName().contains("updated"))
                {
                    JVar reqParam = updateMethod.param(getDataType(tf.getFieldType()), tf.getFieldName());
                    if(tf.getIsNull()==false)
                        reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName());
                    else
                        reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName()).param("required", false);
                }
            }
            updateMethod.body().directStatement("Date saveDate = new Date();");
            updateMethod.body().directStatement("Timestamp timeStampDate = new Timestamp(saveDate.getTime());");
            updateMethod.body().directStatement(template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" "+template.getTablename()+" = null; // create search methods //searchDao.find"+template.getTablename().substring(0, 1).toUpperCase()+template.getTablename().substring(1)+"ById(id.toString());");
            for(TemplateFields tf:reqFields)
            {
                if(tf.getFieldName().equals("id"))
                {

                }
                else if(tf.getFieldName().equals("updatedBy"))
                {
                    updateMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(getPrincipal());");
                }
                else if(tf.getFieldName().equals("updatedOn"))
                {
                    updateMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(timeStampDate);");
                }
                else if(tf.getFieldName().equals("createdBy"))
                {

                }
                else if(tf.getFieldName().equals("createdOn"))
                {

                }
                else
                {
                    updateMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"("+tf.getFieldName()+");");
                }
            }
            updateMethod.body().directStatement("boolean sts = false;");
            updateMethod.body().directStatement("// create update method first");
            updateMethod.body().directStatement("//sts = addService.update"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"("+template.getTablename()+");");
            updateMethod.body().directStatement("if(sts==false){");
            updateMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" not updated.\",HttpStatus.BAD_REQUEST);");
            updateMethod.body().directStatement("}");
            updateMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" Successfully updated.\",HttpStatus.OK);");
            updateMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/update"+pagemaster.getPageTitle().replace(" ", "")).param("method", RequestMethod.POST);

            // Add DataTable List method
            JMethod dtMethod = mappingController.method(JMod.PUBLIC, (codeModel.ref(String.class)), "list"+pagemaster.getPageTitle().replace(" ", ""));
            dtMethod._throws(Exception.class);
            JVar startReqParam = dtMethod.param(int.class, "start");
            startReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam"));
            JVar lengthReqParam = dtMethod.param(int.class, "length");
            lengthReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam"));
            JVar searchReqParam = dtMethod.param(String.class, "search");
            searchReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", "search[value]");
            List<String> filAssN = new ArrayList<String>();
            List<String> filAssV = new ArrayList<String>();
            String printS = "";
            int fSize = 0;
            for(TemplateFields tf:reqFields)
            {
                if(!tf.getFieldName().equals("id") && !tf.getFieldName().contains("created") && !tf.getFieldName().contains("updated"))
                {
                    JVar reqParam = dtMethod.param(String.class, tf.getFieldName());
                    reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName());
                    filAssN.add("list["+fSize+"]=null;");
                    filAssV.add("if("+tf.getFieldName()+"!=null && !"+tf.getFieldName()+".equals(\"\"))");
                    filAssV.add("list["+fSize+"]="+tf.getFieldName()+";");
                    if(fSize==0)
                        printS += "\""+tf.getFieldName()+" :\"+"+tf.getFieldName()+"";
                    else
                        printS += "+\" "+tf.getFieldName()+" :\"+"+tf.getFieldName()+"";
                    fSize++;
                }
            }
            JVar datatReqParam = dtMethod.param(String.class, "datat");
            datatReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", "datat");
            dtMethod.body().directStatement("String list[]=new String["+fSize+"];");
            for(String s:filAssN)
            {
                dtMethod.body().directStatement(s);
            }
            dtMethod.body().directStatement("System.out.println("+ printS +"+\" datat: \"+datat);");
            for(String s:filAssV)
            {
                dtMethod.body().directStatement(s);
            }
            dtMethod.body().directStatement("DataTablesTO<"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"> dt = new DataTablesTO<"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+">();");
            dtMethod.body().directStatement("String sessid=(String) httpSession.getId();");
            dtMethod.body().directStatement(template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" "+template.getTablename()+" = null; // create search methods //searchDao.find"+template.getTablename().substring(0, 1).toUpperCase()+template.getTablename().substring(1)+"ById(id.toString());");
            dtMethod.body().directStatement("if(sessid!=null) {");
            dtMethod.body().directStatement("String token= (String)httpSession.getAttribute(\"token\");");
            dtMethod.body().directStatement("if(token.equals(datat)) {");
            dtMethod.body().directStatement("List<"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"> accts = null; //create list method // listService.getAll"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"List(start,length, search, list);");
            dtMethod.body().directStatement("int count = 0; //create list count method // listService.getAll"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"ListCount(search, list);");
            dtMethod.body().directStatement("System.out.println(\"accts___ \"+accts.size()+\" count: \"+count);");
            dtMethod.body().directStatement("dt.setAaData(accts);");
            dtMethod.body().directStatement("dt.setiTotalDisplayRecords(count);");
            dtMethod.body().directStatement("dt.setiTotalRecords(count);");
            dtMethod.body().directStatement("dt.setsEcho(0);");
            dtMethod.body().directStatement("}");
            dtMethod.body().directStatement("}");
            dtMethod.body().directStatement("System.out.println(\"toJson(dt)___ \"+toJson(dt));");
            dtMethod.body().directStatement("return toJson(dt);");
            dtMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/list"+pagemaster.getPageTitle().replace(" ", ""));

            // getPrincipal Mapping method
            JMethod principalMethod = mappingController.method(JMod.PRIVATE, String.class, "getPrincipal");
            principalMethod.body().directStatement("String userName = null;");
            principalMethod.body().directStatement("Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();");
            principalMethod.body().directStatement("if (principal instanceof UserDetails) {");
            principalMethod.body().directStatement("userName = ((UserDetails)principal).getUsername();");
            principalMethod.body().directStatement("} else {");
            principalMethod.body().directStatement("userName = principal.toString();");
            principalMethod.body().directStatement("}");
            principalMethod.body().directStatement("return userName;");

            // getJson Mapping method
            JMethod jsonMethod = mappingController.method(JMod.PRIVATE, String.class, "toJson");
            //codeModel.ref(DataTablesTO.class).narrow(String.class)
            jsonMethod.param(codeModel.ref(DataTablesTO.class).narrow(codeModel.ref(Object.class).wildcard()), "dt");
            jsonMethod.body().directStatement("ObjectMapper mapper = new ObjectMapper();");
            jsonMethod.body().directStatement("try {");
            jsonMethod.body().directStatement("return mapper.writeValueAsString(dt);");
            jsonMethod.body().directStatement("} catch (Exception e) {");
            jsonMethod.body().directStatement("e.printStackTrace();");
            jsonMethod.body().directStatement("return null;");
            jsonMethod.body().directStatement("}");

            // Generate the code
            //JFormatter f = new JFormatter(codeModel.);
            codeModel.build(new File("F:/UISOFT/uisoft/DISCOM/src/main/java/"));
            //codeModel.build(new File(getPath()+"src/main/java/"));
        }
</code>```

Body:
I am using CodeModel to programmatically generate .java files. This is a snippet of code to create a method:

JCodeModel jCodeModel = new JCodeModel();
JDefinedClass definedClass = jCodeModel._class("Foo");

//To generate method
JMethod method = definedClass.method(3, String.class, "getCustomerInfo()");

When I run (assume all other necessary codes are there);

public String getCustomerInfo() { }

But I want to annotate above method like this:

@GET
@Path("/getCustomerInfo")
public String getCustomerInfo() { }

For which I tried below methods:
method.annotate(...) and method.annotate2(...)

But those methods accept only Class files as a arguments (ie like in the form SomeClass.class), but I want to be able to String as an argument and that class will be available dynamically at run time.

Say I should be able to do like this: method.annotate("Path").

Can anyone help me?


问:
Laravel where query for getting record if the difference of two fields is not 0
I need to get record only if subtraction of two fields is not zero.

```<code>$list = InspectionCertificate::where('amount' - 'billed_amount' != 0)
</code>```

Thanks in advance.

答:
Using Not Equal operator, you can able to do.

Sample query:

```<code>SELECT *
FROM TableName
WHERE (ColumnName1 - ColumnName2) != 0
</code>```

Body:
I need to get record only if subtraction of two fields is not zero.

$list = InspectionCertificate::where('amount' - 'billed_amount' != 0)

Thanks in advance.

Body:
Using Not Equal operator, you can able to do.

Sample query:

SELECT *
FROM TableName
WHERE (ColumnName1 - ColumnName2) != 0


问:
Limited range when copying from excel VBA to word
I am developing a macro that transfers a range of cells from excel to word bookmark. The problem I am having is that not the whole of the range I selected is transfered. Not sure if there is a limit to how big the range can be? Also want the transfered content to autofit to the word documents margins?

The code I have so far is:

```<code>'Name of the existing Word doc.
Const stWordReport As String = "Exporting a Table to a Word Document 2.docx"

'Word objects.
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdbmRange As Word.Range

'Excel objects.
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnReport As Range
'Dim Table1 As Range

Dim coluna As Integer
coluna = Worksheets("Planilha1").Cells(1, Worksheets("Planilha1").Columns.Count).End(xlToLeft).Column
Table1 = Worksheets("Planilha1").Range(Cells(4, 4), Cells(16, coluna))

'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Planilha1")
Set rnReport = wsSheet.Range("Table1")

'Initialize the Word objects.
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport)
Set wdbmRange = wdDoc.Bookmarks("Report").Range

'Turn off screen updating.
Application.ScreenUpdating = False

'Copy the report to the clipboard.
rnReport.Copy

'Select the range defined by the "Report" bookmark and paste in the report from clipboard.
With wdbmRange
    .Select
    .PasteSpecial Link:=False, _
                  DataType:=wdPasteMetafilePicture, _
                  Placement:=wdInLine, _
                  DisplayAsIcon:=False
End With

'Save and close the Word doc.
With wdDoc
    .Save
    .Close
End With

'Quit Word.
wdApp.Quit

'Null out your variables.
Set wdbmRange = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing

'Clear out the clipboard, and turn screen updating back on.
With Application
    .CutCopyMode = False
    .ScreenUpdating = True
End With

MsgBox "The report has successfully been " & vbNewLine & _
       "transferred to " & stWordReport, vbInformation
</code>```

I expect the content on the word document to have the same formatting as the excel one and to be fitted to the page.

答:
Word's maximum column count is 63; there is no set row limit. In any event, since you are pasting what you've copied as a picture, the table limits aren't relevant. I suspect the real issue is with how you're determining coluna. Try:</p>

```<code>'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Planilha1")
Set rnReport = wsSheet.Range("Table1")

coluna = wsSheet.UsedRange.Cells.SpecialCells(xlCellTypeLastCell).Column
Table1 = wsSheet.Range(Cells(4, 4), Cells(16, coluna))
</code>```

Body:
I am developing a macro that transfers a range of cells from excel to word bookmark. The problem I am having is that not the whole of the range I selected is transfered. Not sure if there is a limit to how big the range can be? Also want the transfered content to autofit to the word documents margins?

The code I have so far is:

'Name of the existing Word doc.
Const stWordReport As String = "Exporting a Table to a Word Document 2.docx"

'Word objects.
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdbmRange As Word.Range

'Excel objects.
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnReport As Range
'Dim Table1 As Range

Dim coluna As Integer
coluna = Worksheets("Planilha1").Cells(1, Worksheets("Planilha1").Columns.Count).End(xlToLeft).Column
Table1 = Worksheets("Planilha1").Range(Cells(4, 4), Cells(16, coluna))

'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Planilha1")
Set rnReport = wsSheet.Range("Table1")

'Initialize the Word objects.
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport)
Set wdbmRange = wdDoc.Bookmarks("Report").Range

'Turn off screen updating.
Application.ScreenUpdating = False

'Copy the report to the clipboard.
rnReport.Copy

'Select the range defined by the "Report" bookmark and paste in the report from clipboard.
With wdbmRange
    .Select
    .PasteSpecial Link:=False, _
                  DataType:=wdPasteMetafilePicture, _
                  Placement:=wdInLine, _
                  DisplayAsIcon:=False
End With

'Save and close the Word doc.
With wdDoc
    .Save
    .Close
End With

'Quit Word.
wdApp.Quit

'Null out your variables.
Set wdbmRange = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing

'Clear out the clipboard, and turn screen updating back on.
With Application
    .CutCopyMode = False
    .ScreenUpdating = True
End With

MsgBox "The report has successfully been " & vbNewLine & _
       "transferred to " & stWordReport, vbInformation

I expect the content on the word document to have the same formatting as the excel one and to be fitted to the page.

Body:
Word's maximum column count is 63; there is no set row limit. In any event, since you are pasting what you've copied as a picture, the table limits aren't relevant. I suspect the real issue is with how you're determining coluna. Try:

'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Planilha1")
Set rnReport = wsSheet.Range("Table1")

coluna = wsSheet.UsedRange.Cells.SpecialCells(xlCellTypeLastCell).Column
Table1 = wsSheet.Range(Cells(4, 4), Cells(16, coluna))


问:
Cannot iterate of a collection of Anonymous Types created from a LINQ Query in VB.NET
Ok everyone, I must be missing something here.

Every LINQ example I have seen for VB.NET anonymous types claims I can do something like this:

```<code>Dim Info As EnumerableRowCollection = pDataSet.Tables(0).AsEnumerable
Dim Infos = From a In Info _
            Select New With {
                             .Prop1 = a("Prop1"),
                             .Prop2 = a("Prop2"),
                             .Prop3 = a("Prop3") }
</code>```

Now when I go to iterate through the collection (see example below), I get an error that says "Name "x" is not declared.

```<code>For Each x in Infos
 ...
Next
</code>```

It's like VB.NET doesn't understand that Infos is a collection of anonymous types created by LINQ and wants me to declare "x" as some type. (Wouldn't this defeat the purpose of an anonymous type?)  I have added the references to System.Data.Linq and System.Data.DataSetExtensions to my project. Here is what I am importing with the class:

```<code>Imports System.Linq
Imports System.Linq.Enumerable
Imports System.Linq.Queryable
Imports System.Data.Linq
</code>```

Any ideas?

答:
I was upgrading from vs 20005 to vs 2008 to vs 2010 the Option Infer Off was turned off, when i turned it on everything worked just fine..

I it is by default turned on on vs 2010 and 2008, but in vs2005 it is not an option!! S

Body:
Ok everyone, I must be missing something here.

Every LINQ example I have seen for VB.NET anonymous types claims I can do something like this:

Dim Info As EnumerableRowCollection = pDataSet.Tables(0).AsEnumerable
Dim Infos = From a In Info _
            Select New With {
                             .Prop1 = a("Prop1"),
                             .Prop2 = a("Prop2"),
                             .Prop3 = a("Prop3") }

Now when I go to iterate through the collection (see example below), I get an error that says "Name "x" is not declared.

For Each x in Infos
 ...
Next

It's like VB.NET doesn't understand that Infos is a collection of anonymous types created by LINQ and wants me to declare "x" as some type. (Wouldn't this defeat the purpose of an anonymous type?)  I have added the references to System.Data.Linq and System.Data.DataSetExtensions to my project. Here is what I am importing with the class:

Imports System.Linq
Imports System.Linq.Enumerable
Imports System.Linq.Queryable
Imports System.Data.Linq

Any ideas?


问:
How to fix Warning: `getFieldDecorator` will override `value`,so please don't set `value and v-model` directly and use `setFieldsValue` to set it.?
I'm coding a custom validation form component using ant-design-vue

I have changed my code nearly same as the example showed on the official website, but still got warning, the only difference is the example use template to define child component, but I use single vue file

```<code>//parent component
...some other code
<a-form-item
    label="account"
>
  <ReceiverAccount
      v-decorator="[
       'receiverAccount',
        {
          initialValue: step.receiverAccount,
          rules: [
           {
              required: true,
              message: 'need account',

           }
          ]
        }
      ]"
  />
</a-form-item>
...some other code
</code>```

```<code>//child component
<template>
    <a-input-group compact>
        <a-select
            :value="type"
            @change="handleTypeChange"
        >
            <a-select-option value="alipay">alipay</a-select-option>
            <a-select-option value="bank">bank</a-select-option>
        </a-select>
        <a-input
            :value="number"
            @change="handleNumberChange"
        />
    </a-input-group>
</template>

<script>
export default {
    props: {
        value: {
            type: Object,
            default: () => {}
        }
    },
    data() {
        const { type, number } = this.value
        return {
            type: type || 'alipay',
            number: number || ''
        }
    },
    watch: {
        value(val = {}) {
            this.type = val.type || 'alipay'
            this.number = val.number || ''
        }
    },
    methods: {
        handleTypeChange(val) {
            this.triggerChange({ val })
        },
        handleNumberChange(e) {
            const number = parseInt(e.target.value || 0, 10)
            if (isNaN(number)) {
                return
            }
            this.triggerChange({ number })
        },
        triggerChange(changedValue) {
            this.$emit('change', Object.assign({}, this.$data, changedValue))
        }
    }
}
</script>
</code>```

I expect everything is fine, but the actual is I got 'Warning: getFieldDecorator will override value, so please don't set value and v-model directly and use setFieldsValue to set it.'

How can I fix it? Thanks in advance

答:
because I am new of ant-design-vue, after one day research, solution is change :value to v-model and remove value props in the child component</p>

```<code><template>
    <a-input-group compact>
        <a-select
            v-model="type"
            @change="handleTypeChange"
        >
            <a-select-option value="alipay">alipay</a-select-option>
            <a-select-option value="bank">bank</a-select-option>
        </a-select>
        <a-input
            v-model="number"
            @change="handleNumberChange"
        />
    </a-input-group>
</template>
</code>```

Body:
I'm coding a custom validation form component using ant-design-vue

I have changed my code nearly same as the example showed on the official website, but still got warning, the only difference is the example use template to define child component, but I use single vue file

//parent component
...some other code

  <ReceiverAccount
      v-decorator="[
       'receiverAccount',
        {
          initialValue: step.receiverAccount,
          rules: [
           {
              required: true,
              message: 'need account',

           }
          ]
        }
      ]"
  />

...some other code

//child component
<template>

            alipay
            bank

</template>

I expect everything is fine, but the actual is I got 'Warning: getFieldDecorator will override value, so please don't set value and v-model directly and use setFieldsValue to set it.'

How can I fix it? Thanks in advance

Body:
because I am new of ant-design-vue, after one day research, solution is change :value to v-model and remove value props in the child component

<template>
    <a-input-group compact>
        <a-select
            v-model="type"
            @change="handleTypeChange"
        >
            <a-select-option value="alipay">alipay</a-select-option>
            <a-select-option value="bank">bank</a-select-option>
        </a-select>
        <a-input
            v-model="number"
            @change="handleNumberChange"
        />
    </a-input-group>
</template>


问:
Unchecked Cast warning: cast Object to Generic
I'm trying to implement a DoublyLinkedList with genenerics.
According to Java Docs, the argument of remove() method must be an Object.

If I try to cast Object o to T data, I will get the warning: Unchecked Cast: 'Java.lang.Object' to 'T'.

```<code>public boolean remove(Object o) {
        T data = (T) o; // warning here
...
}
</code>```

To avoid this, I have to suppress the warning by "@SuppressWarning("Unchecked")"

```<code>@SuppressWarnings("unchecked")
public boolean remove(Object o) {
        T data = (T) o;
...
}
</code>```

My understanding is every T is an Object but not every Object is a T. That's why it shows the warning.

But what if when I use my DoublyLinkedList class, I'm 100% sure the Object argument is a T, is there a way to avoid the warning or @suppresswarning is the only choice here?

If my assumption is not correct, what is the correct way to cast an Object to a T?
Thank you.

答:
As Silvio and Andreas mentioned in the comments.

No need to cast Object to T, instead, we just need to use .equals() for comparison.

My initial implementation is to use == operator to compare the object. This is wrong because == is used to compare the reference not the content.

Body:
I'm trying to implement a DoublyLinkedList with genenerics.
According to Java Docs, the argument of remove() method must be an Object.

If I try to cast Object o to T data, I will get the warning: Unchecked Cast: 'Java.lang.Object' to 'T'.

public boolean remove(Object o) {
        T data = (T) o; // warning here
...
}

To avoid this, I have to suppress the warning by "@SuppressWarning("Unchecked")"

@SuppressWarnings("unchecked")
public boolean remove(Object o) {
        T data = (T) o;
...
}

My understanding is every T is an Object but not every Object is a T. That's why it shows the warning.

But what if when I use my DoublyLinkedList class, I'm 100% sure the Object argument is a T, is there a way to avoid the warning or @suppresswarning is the only choice here?

If my assumption is not correct, what is the correct way to cast an Object to a T?
Thank you.


问:
Android: how to make keyboard enter button say "Search" and handle its click?
I can't figure this out. Some apps have an EditText (textbox) with the help of which, when you touch it and it brings up the on-screen keyboard, the keyboard has a "Search" button instead of an enter key.

I want to implement this. How can I implement that Search button and detect the press of the Search button?

Edit: found how to implement the Search button; in XML, android:imeOptions="actionSearch" or in Java, EditTextSample.setImeOptions(EditorInfo.IME_ACTION_SEARCH);. But how do I handle the user pressing that Search button? Does it have something to do with android:imeActionId?

答:
This answer is for TextInputEditText :

In the layout XML file set your input method options to your required type. for example done.

```<code><com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="actionGo"/>
</code>```

</com.google.android.material.textfield.TextInputLayout>

Similarly, you can also set imeOptions to actionSubmit, actionSearch, etc

In the java add the editor action listener.

```<code>TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);

textInputLayout.getEditText().setOnEditorActionListener(new

    TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_GO) {
                performYourAction();
                return true;
            }
            return false;
        }
    });
</code>```

If you're using kotlin :

```<code>textInputLayout.editText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_GO) {
        performYourAction()
    }
    true
}
</code>```

Body:
This answer is for TextInputEditText :

In the layout XML file set your input method options to your required type. for example done.

<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="actionGo"/>

</com.google.android.material.textfield.TextInputLayout>

Similarly, you can also set imeOptions to actionSubmit, actionSearch, etc

In the java add the editor action listener.

TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);

textInputLayout.getEditText().setOnEditorActionListener(new

    TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_GO) {
                performYourAction();
                return true;
            }
            return false;
        }
    });

If you're using kotlin :

textInputLayout.editText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_GO) {
        performYourAction()
    }
    true
}


问:
Plot graph from the selected excel sheet
There are lot of csv excel sheets in a folder. All excel sheet contains data only in first 3 columns. I will select corresponding csv sheet from a lot of csv sheets and then plot it.Here is the code

```<code>import os
path = "F:\\Users\\Desktop\\Data\\Summary"
files = []
folder_data = os.listdir(path)
folder_data = [i+"\\" for i in folder_data]

# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.csv' in file:
            files.append(file)
for i, f in enumerate(files):
    print(( i,f))
    print('\n'.join(f'{i}-{v}' for i,v in enumerate(files)))
    csv_code = str(int(input("Enter corresponding code to plot: ")))
    csv_path = path + "\\" + folder_data[csv_code]

    df = pd.read_csv(csv_path, header=None)
    df1 = df.iloc[:,0:2]
    plt.plot(df1[0], df1[1])
</code>```

Currently only 1 csv sheet is displayed when i run code so When i run the code i want the Output to be displayed as follows (i mean i want all csv files from the folder to be displayed so that i can select what i want):

```<code>0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc

</code>```

so that i select the corresponding code like 1 or 2 or 3 to plot.This is the error i am getting

```<code>    csv_path = path + "\\" + folder_data[csv_code]

TypeError: list indices must be integers or slices, not str
</code>```

答:
Your input call shouldn't be inside the for loop, because you want to print out all the items first. You can fix it as follows:

```<code>print('\n'.join(f'{i}-{v}' for i,v in enumerate(files))) # a shorter version of the loop

csv_code = int(input("Enter corresponding code to plot: "))
csv_path = os.path.join(path, files[csv_code])

df = pd.read_csv(csv_path, header=None)
df1 = df[0:2]
df1 = df.iloc[:,0:2]
plt.plot(df1[0], df1[1])
</code>```

Update:

In your new code, you are casting csv_code to string for some reason. Firstly, input() will return a string, so there is no need to do str(int(input())), and secondly, you require it to be a list index. So remove the str cast and leave it at int(input()) as before.

Body:
There are lot of csv excel sheets in a folder. All excel sheet contains data only in first 3 columns. I will select corresponding csv sheet from a lot of csv sheets and then plot it.Here is the code

import os
path = "F:\\Users\\Desktop\\Data\\Summary"
files = []
folder_data = os.listdir(path)
folder_data = [i+"\\" for i in folder_data]

# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.csv' in file:
            files.append(file)
for i, f in enumerate(files):
    print(( i,f))
    print('\n'.join(f'{i}-{v}' for i,v in enumerate(files)))
    csv_code = str(int(input("Enter corresponding code to plot: ")))
    csv_path = path + "\\" + folder_data[csv_code]

    df = pd.read_csv(csv_path, header=None)
    df1 = df.iloc[:,0:2]
    plt.plot(df1[0], df1[1])

Currently only 1 csv sheet is displayed when i run code so When i run the code i want the Output to be displayed as follows (i mean i want all csv files from the folder to be displayed so that i can select what i want):

0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc

so that i select the corresponding code like 1 or 2 or 3 to plot.This is the error i am getting

    csv_path = path + "\\" + folder_data[csv_code]

TypeError: list indices must be integers or slices, not str

Body:
Your input call shouldn't be inside the for loop, because you want to print out all the items first. You can fix it as follows:

print('\n'.join(f'{i}-{v}' for i,v in enumerate(files))) # a shorter version of the loop

csv_code = int(input("Enter corresponding code to plot: "))
csv_path = os.path.join(path, files[csv_code])

df = pd.read_csv(csv_path, header=None)
df1 = df[0:2]
df1 = df.iloc[:,0:2]
plt.plot(df1[0], df1[1])

Update:

In your new code, you are casting csv_code to string for some reason. Firstly, input() will return a string, so there is no need to do str(int(input())), and secondly, you require it to be a list index. So remove the str cast and leave it at int(input()) as before.


问:
How to set margins to two div inside another div?
I want to set different margins to two divs, inside another div. The first div should appear top of the second div.

```<code><div style="position:relative">
 <div style="position: absolute;margin-top:24px">
   This should be appar top of the second div.
 </div>
 <div style="margin-top:24px">
   second div
 </div>
</div
</code>```

I used above mention code, but first div also getting margin 50, not margin 24.

How to resolve this issue?

Cannot use position:absoulte to the second div.

答:
enter this code  inside div

margin: 5px auto;
```

Body:
I want to set different margins to two divs, inside another div. The first div should appear top of the second div.

   This should be appar top of the second div.

   second div

</div

I used above mention code, but first div also getting margin 50, not margin 24.

How to resolve this issue?

Cannot use position:absoulte to the second div.


问:
How can I update a source file (with classes) in interactive python
Simple python question.

When in interactive mode, I'm test an imported file, let's say I use:

```<code>from foo import foo
</code>```

But in the same time I edit the code. How can I update the script which is once loaded into interactive python? When I try to reimport it, nothing happens and I'm still on my old files.

Thanks for any help.

EDIT:
Ok, as I understand reload(modulename) works fine, but... What if I'm trying to reload a class with its methods? As it's written in documentation:

If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

But there's no word how to update a class methods. Any idea?

The answer's here
How to reload the code of a method of class object in Python?

No more question as everything works fine now :)

答:
Did you take a look at this question?
Reloading a changed python file in emacs python shell

Libraries in your python path can be easily updated with reload(modulename).

Body:
Simple python question.

When in interactive mode, I'm test an imported file, let's say I use:

from foo import foo

But in the same time I edit the code. How can I update the script which is once loaded into interactive python? When I try to reimport it, nothing happens and I'm still on my old files.

Thanks for any help.

EDIT:
Ok, as I understand reload(modulename) works fine, but... What if I'm trying to reload a class with its methods? As it's written in documentation:

If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

But there's no word how to update a class methods. Any idea?

The answer's here
How to reload the code of a method of class object in Python?

No more question as everything works fine now :)


问:
Android ViewPager - Show preview of page on left and right
I'm using Android's ViewPager. What I want to do is to show a preview of the page on both the left and the right. I've seen where I can use a negative pageMargin to show a preview of the right side.

```<code>setPageMargin(-100);
</code>```

Is there anyway that I can show a preview of the left side aswell? Its basically something similar to the gallery widget that I am looking for.

答:
You can do this in xml file, just use below code:

```<code> android:clipToPadding="false"
 android:paddingLeft="XX"
 android:paddingRight="XX"
</code>```

For example:

```<code><androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingLeft="30dp"
        android:paddingRight="30dp" />
</code>```

Note: If you need space between pages, set padding/margin to child fragments

Body:
I'm using Android's ViewPager. What I want to do is to show a preview of the page on both the left and the right. I've seen where I can use a negative pageMargin to show a preview of the right side.

setPageMargin(-100);

Is there anyway that I can show a preview of the left side aswell? Its basically something similar to the gallery widget that I am looking for.

Body:
You can do this in xml file, just use below code:

 android:clipToPadding="false"
 android:paddingLeft="XX"
 android:paddingRight="XX"

For example:

<androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingLeft="30dp"
        android:paddingRight="30dp" />

Note: If you need space between pages, set padding/margin to child fragments


问:
Change strings with different format to dates with the same format in a dataframe
I have a dataframe which looks like this (it has thounds of date rows like this, ranging from years 18xx until 2019)

```<code>                date
1   25 February 1987
2     20 August 1974
3     9 October 1984
4          16-Oct-63
5         13-11-1961
6           03/23/87
7         01.01.1995
8      February 1988
9               1988
10 20050101-20051231
</code>```

I need to change the date column to one date-format (eg.: YYYY-MM-DD, or any other).
Since there are just some Year values as for ID 9, I also have to autofill them. This should always lead to the last day of the particular year. If it ist like ID 8 a month and a year, it should always fill the last day of the particular month (and check if it was a leap year, like it was in 1988 and return in this case something like 1988-02-29). If it is a timeframe like in the last row, it should always cut off the first part and change it to the 31st of December of the given year.
How can I do this?

I thought about using the lubridate package or the anytime package. With lubridate and parse_date or parse_date_time. This even works, but it always fills the missing values for days to the first day of a month and not the last.

```<code>library(lubridate)

date <- c("25 February 1987", "20 August 1974", "9 October 1984", "16-Oct-63", "13-11-1961", "03/23/87", "01.01.1995",
          "February 1988", "1988", "20050101-20051231")

df <- as.data.frame(date)

parse_date(df$date)

parse_date_time(x = df$date,
                orders = c("d m y", "d B Y", "d/m/Y","B Y", "Y", "m/d/y",
                           "Ymd-Ymd"),
                locale = "eng")
</code>```

My actual results

```<code>(parse_date(df$date)):

 [1] "1987-02-25 UTC" "1974-08-20 UTC" "1984-10-09 UTC" "2019-10-16 UTC" "2019-11-13 UTC" "1987-03-23 UTC" "1995-01-01 UTC"
 [8] "1988-02-01 UTC" "1988-01-01 UTC" "2005-12-31 UTC"
</code>```

For the parse_date_time I acutally get an error, due to the last orders "Ymd-Ymd" (If I just test: parse_date("20050101-20051231") it results in "2005-12-31 UTC", which I really want to have!)

Body:
I have a dataframe which looks like this (it has thounds of date rows like this, ranging from years 18xx until 2019)

                date
1   25 February 1987
2     20 August 1974
3     9 October 1984
4          16-Oct-63
5         13-11-1961
6           03/23/87
7         01.01.1995
8      February 1988
9               1988
10 20050101-20051231

I need to change the date column to one date-format (eg.: YYYY-MM-DD, or any other).
Since there are just some Year values as for ID 9, I also have to autofill them. This should always lead to the last day of the particular year. If it ist like ID 8 a month and a year, it should always fill the last day of the particular month (and check if it was a leap year, like it was in 1988 and return in this case something like 1988-02-29). If it is a timeframe like in the last row, it should always cut off the first part and change it to the 31st of December of the given year.
How can I do this?

I thought about using the lubridate package or the anytime package. With lubridate and parse_date or parse_date_time. This even works, but it always fills the missing values for days to the first day of a month and not the last.

library(lubridate)

date <- c("25 February 1987", "20 August 1974", "9 October 1984", "16-Oct-63", "13-11-1961", "03/23/87", "01.01.1995",
          "February 1988", "1988", "20050101-20051231")

df <- as.data.frame(date)

parse_date(df$date)

parse_date_time(x = df$date,
                orders = c("d m y", "d B Y", "d/m/Y","B Y", "Y", "m/d/y",
                           "Ymd-Ymd"),
                locale = "eng")

My actual results

(parse_date(df$date)):

 [1] "1987-02-25 UTC" "1974-08-20 UTC" "1984-10-09 UTC" "2019-10-16 UTC" "2019-11-13 UTC" "1987-03-23 UTC" "1995-01-01 UTC"
 [8] "1988-02-01 UTC" "1988-01-01 UTC" "2005-12-31 UTC"

For the parse_date_time I acutally get an error, due to the last orders "Ymd-Ymd" (If I just test: parse_date("20050101-20051231") it results in "2005-12-31 UTC", which I really want to have!)

Body:
Thank you. This is very close. Unfortunately, it still gives me the wrong output dates for some entries.

               date    newdate   newdate2
1   25 February 1987 1987-02-25 1987-02-25
2     20 August 1974 1974-08-20 1974-08-20
3     9 October 1984 1984-10-09 1984-10-09
4          16-Oct-63 2063-10-16 1963-10-16
5         13-11-1961 1961-11-13 1961-11-13
6           03/23/87 1987-03-23 1987-03-23
7         01.01.1995 1995-01-01 1995-01-01
8      February 1988 1988-02-19 1988-02-19
9               1988 1988-01-01 1988-01-01
10 20050101-20051231       <NA> 2005-01-01

But I need it like this:

               date    newdate   newdate2
1   25 February 1987 1987-02-25 1987-02-25
2     20 August 1974 1974-08-20 1974-08-20
3     9 October 1984 1984-10-09 1984-10-09
4          16-Oct-63 2063-10-16 1963-10-16
5         13-11-1961 1961-11-13 1961-11-13
6           03/23/87 1987-03-23 1987-03-23
7         01.01.1995 1995-01-01 1995-01-01
8      February 1988 1988-02-19 **1988-02-29**
9               1988 1988-01-01 **1988-12-31**
10 20050101-20051231       <NA> **2005-12-31**

This means: If I only have year and month: I need to enter the last day of the particular month and for February to consider leap years, like in the example row 8. If I just have a year, I need to change it to 31st of December of the given year. And if the entry looks like in row 10, I need to cut of the first part and just keep the 31st of December of the given year, but for this case, I already adjusted the part of your code:

is.na(newdate) ~ paste0(substr(x=date, start = 10, stop = 13), "-",
                            substr(x=date, start = 14, stop = 15), "-",
                            substr(x=date, start = 16, stop = 17) )


答:
Sharing more info you will get a better answer, but here is a way using the query builder:</p>

```<code>\DB::table('table_name')
    ->havingRaw('(column1 - column2) != 0')
    ->get();
</code>```

Title: Laravel where query for getting record if the difference of two fields is not 0

Body:
I need to get record only if subtraction of two fields is not zero.

$list = InspectionCertificate::where('amount' - 'billed_amount' != 0)

Thanks in advance.

Body:
Sharing more info you will get a better answer, but here is a way using the query builder:

\DB::table('table_name')
    ->havingRaw('(column1 - column2) != 0')
    ->get();


问:
How much disk space needed for Bitcoin SV testnet node implementation?
I want to create Bitcoin SV node but not sure how much disk space it needed.

please someone answer me as soon as possible

答:
I do not know the actoal SV-testnet blockchain size. But, if see to mainnet -
because of this is relative fresh fork of Bitcoin, blockchain size is close to Bitcoin's one, i.e. 200G.
Please, be careful:

BitcoinSV runs as a daemon on a Linux only, and there is not exists a GUI wallet.

It uses directory $HOME/.bitcoin to hold
blockchain and wallet.dat. As result, if you use Bitcoin on same
Linux server/account, then BitcoinSV will hurt your Bitcoins wallet.dat and
blockchain. I recommend backup or rename your .bitcoin before run SV.

Config command "zapwallettxes" does not work correctly. In my case,
it clears balance from wallet.dat, I restored it from backup.


问:
Secure react routing with spring security
I introduced in my projects log in/out via spring security and jwt auth. At the moment I would like to prevent unauthorized user to enter the routs like /admin. Should I make a call before making history.push("/admin") and check the response to determine if user should see it or not?

How to prevent the accessing routes? I do not mean making api calls...

Regards

答:
Store the login status of the user in react state or global state if you are using redux.

Then you can make a private route in react and check the user roles

```<code>const PrivateRoute = (props)=>(
  <Route {...props.routeProps} render={() => (
    props.logged_in===true ? (
        <div>{props.children}</div>
        ) : (
        <Redirect to={{
            pathname: '/',
            state: { from: props.location }
        }} /> )
    )} />
)
</code>```

and you can use this component like

```<code><PrivateRoute path = {"/admin/"} ><Dashboard /></PrivateRoute>
</code>```

Body:
Store the login status of the user in react state or global state if you are using redux.

Then you can make a private route in react and check the user roles

const PrivateRoute = (props)=>(
  <Route {...props.routeProps} render={() => (
    props.logged_in===true ? (
        <div>{props.children}</div>
        ) : (
        <Redirect to={{
            pathname: '/',
            state: { from: props.location }
        }} /> )
    )} />
)

and you can use this component like

<PrivateRoute path = {"/admin/"} ><Dashboard /></PrivateRoute>


问:
How to use the where clause in entity framework?
I'm trying to query my EF Code First database so it will return all bookings that where made by the currently logged in user. I'm not quite getting the syntax correct somewhere, and I'm hoping someone can point me in the correct direction.

The two different ways I've tried to achieve this:

List<Booking> bookings = new List<Booking>();
string userid = User.Identity.GetUserId();
foreach(var b in db.Bookings.Where(b => b.Customer.Id == userid))
{
    bookings.Add(b);
}
```

<pre class="lang-cs prettyprint-override"><code>string userid = User.Identity.GetUserId();
var bookings = db.Bookings.Include(b => b.Customer).Include(b => b.Invoice).Include(b => b.Payment).Include(b => b.Vehicle).Where(b => b.Customer.Id == userid);
return View(bookings.ToList());
</code>```

None of these ways have returned any of the bookings in the database, so I'm sure my logic is wrong here somewhere. Any help would be appreciated.

答:
In your first query, you forgot to include Customer navigation property, so the customer always fails and no bookings will return.

Although in your 2nd query, you have included customer, invoice and etc! In that case, only returns customers if they have a booking which their booking got an invoice, payment and etc.

This query should work with you:

```<code>string userid = User.Identity.GetUserId();
var bookings = db.Bookings
                 .Include(b => b.Customer)
                 .Where(b => b.Customer.Id == userid)
                 .ToList();

return View(bookings);
</code>```

It seems you are using EF with EagerMode enabled, so you need to Include customer or any related fields in your where criteria.

My off-topic recommendation:

Please don't return entities that fetched directly from ORM. First, convert them into a DTO (with AutoMapper or any other object mappers).

Body:
I'm trying to query my EF Code First database so it will return all bookings that where made by the currently logged in user. I'm not quite getting the syntax correct somewhere, and I'm hoping someone can point me in the correct direction.

The two different ways I've tried to achieve this:

List<Booking> bookings = new List<Booking>();
string userid = User.Identity.GetUserId();
foreach(var b in db.Bookings.Where(b => b.Customer.Id == userid))
{
    bookings.Add(b);
}

string userid = User.Identity.GetUserId();
var bookings = db.Bookings.Include(b => b.Customer).Include(b => b.Invoice).Include(b => b.Payment).Include(b => b.Vehicle).Where(b => b.Customer.Id == userid);
return View(bookings.ToList());

None of these ways have returned any of the bookings in the database, so I'm sure my logic is wrong here somewhere. Any help would be appreciated.

Body:
In your first query, you forgot to include Customer navigation property, so the customer always fails and no bookings will return.

Although in your 2nd query, you have included customer, invoice and etc! In that case, only returns customers if they have a booking which their booking got an invoice, payment and etc.

This query should work with you:

string userid = User.Identity.GetUserId();
var bookings = db.Bookings
                 .Include(b => b.Customer)
                 .Where(b => b.Customer.Id == userid)
                 .ToList();

return View(bookings);

It seems you are using EF with EagerMode enabled, so you need to Include customer or any related fields in your where criteria.

My off-topic recommendation:

Please don't return entities that fetched directly from ORM. First, convert them into a DTO (with AutoMapper or any other object mappers).


问:
In Facebook PHP Sdk, how can I add a footer link just below Like and Comment?
I've seen this thing in a lot of applications.
http://img708.imageshack.us/img708/2284/99528077.png</p>

答:
I hope this is not to late [but I just had the same problem], you need to use actions key. Here is an example from facebook graph api:

curl -F 'access_token=...' \

     -F 'message=Check out this funny article' \

     -F 'link=http://www.example.com/article.html' \

     -F 'picture=http://www.example.com/article-thumbnail.jpg' \

     -F 'name=Article Title' \

     -F 'caption=Caption for the link' \

     -F 'description=Longer description of the link' \

     -F 'actions={"name": "View on Zombo", "link": "http://www.zombo.com"}' \

     -F 'privacy={"value": "ALL_FRIENDS"}' \

     -F 'targeting= {"countries":"US","regions":"6,53","locales":"6"}' \

     https://graph.facebook.com/me/feed

Cheers...


答:
You have some Syntax issue in your code like converting STRING to INT. Can you please try with replace you last column in selection with this below code-</p>

```<code>   CAST
   (
        REPLACE
        (
            CAST
            (
                LEFT
                (
                    CASE
                        WHEN(ISNULL(TotalHrs, '00:00:00') > '10:00:00')
                            THEN CONVERT(TIME, DATEADD(ms, DATEDIFF(ss, '10:00:00', ISNULL(TotalHrs, '00:00:00')) * 1000, 0), 114)
                        --Your code had: * 1 000
                        --Changed to: * 1000
                        ELSE NULL
                    END
                    , 5
                ) AS VARCHAR(7)
            )
            , ':'
            , '.'
        ) AS FLOAT --Changed from INT to FLOAT
    )
</code>```

Title: I want to sum time and then multiply with salary using sql

Body:
I am trying to calculate overtime hour ,then based on overtime hour calculate with per day overtime salary.

emp_reader_id   in_time                 out_time                TotalHrs            OT
         1002   2019-05-14 08:09:42.000 2019-05-14 23:28:43.000 08:30:00.0000000    14:58:43.0000000    04.58
         1003   2019-05-14 08:18:47.000 2019-05-14 21:59:12.000 08:30:00.0000000    13:29:12.0000000    03.29
         1004   NULL    NULL    08:30:00.0000000    NULL    NULL
         1005   2019-05-14 08:24:29.000 2019-05-14 21:58:46.000 08:30:00.0000000    13:28:46.0000000    03.28
         1006   2019-05-14 08:05:30.000 2019-05-14 23:29:14.000 08:30:00.0000000    14:59:14.0000000    04.59

 select in_time,out_time,shifthrs,TotalHrs,cast( replace(cast(left(case
 when  (isnull(TotalHrs,'00:00:00')>'10:00:00') then
 convert(time,dateadd(ms,datediff(ss,'10:00:00',
 isnull(TotalHrs,'00:00:00'))*1
 000,0),114)
 else NULL end,5) as varchar(7)),':','.') as int) from
 table order by att_date desc

I want another column to calculate ot with salary ot amt per day

E.G: 1.25 overtime * 5.3 per day ot salary

= result

Body:
You have some Syntax issue in your code like converting STRING to INT. Can you please try with replace you last column in selection with this below code-

   CAST
   (
        REPLACE
        (
            CAST
            (
                LEFT
                (
                    CASE
                        WHEN(ISNULL(TotalHrs, '00:00:00') > '10:00:00')
                            THEN CONVERT(TIME, DATEADD(ms, DATEDIFF(ss, '10:00:00', ISNULL(TotalHrs, '00:00:00')) * 1000, 0), 114)
                        --Your code had: * 1 000
                        --Changed to: * 1000
                        ELSE NULL
                    END
                    , 5
                ) AS VARCHAR(7)
            )
            , ':'
            , '.'
        ) AS FLOAT --Changed from INT to FLOAT
    )


问:
Not getting location updates when App is removed from background also
"I am trying to get the location in the background but it is showing this error. I am unable to get the location anyway. Notification not working. How should my doMystuff() function look like in the main activity? Can someone please provide how can I register the broadcast receiver in manifest and how to implement the code with onButton Click."
UPDATE[2]: "Here I have just written the run-time permission to be accessed. Now on button click "startButton" in the doStuff function should I write startService or startForegroundService?"
    "MAIN ACTIVITY"</p>

```<code>package com.example.locationrunandall;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private Button butt1, butt2;
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textview);
        butt1 = findViewById(R.id.butt1);
        butt2 = findViewById(R.id.butt2);

    }

    public void startButton(View view) {
        fetchCode();
    }

    private void fetchCode() {
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Permission is not granted
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                // Show an explanation to the user *asynchronously* -- don't block
                new AlertDialog.Builder(this)
                        .setTitle("Required Location")
                        .setMessage("You have to get this permission to access the feature.")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(MainActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);
                            }
                        })
                        .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            } else {
                // No explanation needed; request the permission
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);

            }
        } else {
            // Permission has already been granted
            doMyStuff();
        }
    }

    private void doMyStuff() {
        Toast.makeText(this, "Working", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this,ForeService.class);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            startForegroundService(intent);
        }else{
            startService(intent);
        }
    }
    public void stopButton(View view) {
        Intent intent = new Intent(this,ForeService.class);
        stopService(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            if(requestCode==MY_PERMISSIONS_REQUEST_LOCATION){
                if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    Intent gpsOptionsIntent = new Intent(
                            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(gpsOptionsIntent);
                }else
                {
                }
            }
    }
}
</code>```

答:
You should use ForegroundService instead of Service. Call startForegroundService() when you want to start it.

Next in this new ForegroundService in onCreate method call startForeground(). With startForeground you have to pass a notification to inform the user that service is running.

Moreover I've found that some devices like HUAWEI have a feature called “power-intensive app monitor“. It kills every app that runs in the background for a long time unless user gives special permissions to it. The path to do this: Settings -> Security & privacy -> Location services -> recent location requests: YOUR APP NAME -> Battery -> uncheck Power-intensive prompt, App launch: Manage manually: check all three positions: Auto-launch, secondary launch, run in background.

I don’t know is there a way to do this programmatically. I think the best way is to create a sort of help activity and explain the user what to do if application won’t work.

Body:
"I am trying to get the location in the background but it is showing this error. I am unable to get the location anyway. Notification not working. How should my doMystuff() function look like in the main activity? Can someone please provide how can I register the broadcast receiver in manifest and how to implement the code with onButton Click."
UPDATE[2]: "Here I have just written the run-time permission to be accessed. Now on button click "startButton" in the doStuff function should I write startService or startForegroundService?"
    "MAIN ACTIVITY"

package com.example.locationrunandall;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private Button butt1, butt2;
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textview);
        butt1 = findViewById(R.id.butt1);
        butt2 = findViewById(R.id.butt2);

    }

    public void startButton(View view) {
        fetchCode();
    }

    private void fetchCode() {
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Permission is not granted
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                // Show an explanation to the user *asynchronously* -- don't block
                new AlertDialog.Builder(this)
                        .setTitle("Required Location")
                        .setMessage("You have to get this permission to access the feature.")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(MainActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);
                            }
                        })
                        .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            } else {
                // No explanation needed; request the permission
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);

            }
        } else {
            // Permission has already been granted
            doMyStuff();
        }
    }

    private void doMyStuff() {
        Toast.makeText(this, "Working", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this,ForeService.class);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            startForegroundService(intent);
        }else{
            startService(intent);
        }
    }
    public void stopButton(View view) {
        Intent intent = new Intent(this,ForeService.class);
        stopService(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            if(requestCode==MY_PERMISSIONS_REQUEST_LOCATION){
                if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    Intent gpsOptionsIntent = new Intent(
                            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(gpsOptionsIntent);
                }else
                {
                }
            }
    }
}