问:
Play Framework Compile Error: '(' expected but ')' found
When I attempting to compile my Play Framework 2. project, I receive this error: '(' expected but ')' found.
What I'm trying to do is : 'After a failed login attempt, user should get feedback. If the login attempt fails server side, show error messages on page after the failed request. Could someone please help me out.

I added the string that I want to display on the form after a failed login attempt as below:

```<code>if (response.hasErrors()) {
return ok(create.render(createViewModelForm, "invalid username or password"));
</code>```

And on the create.scala.html

```<code>@if (!@errorMessage.isEmpty()) {
  <div>@errorMessage</div>
  }
</code>```

This is the SessionsController.java   > ui\controllers\SessionsController

```<code>package femr.ui.controllers;

import com.google.inject.Inject;
import femr.business.services.core.ISessionService;
import femr.business.services.core.IUserService;
import femr.common.dtos.CurrentUser;
import femr.common.dtos.ServiceResponse;
import femr.data.models.core.IUser;
import femr.ui.models.sessions.CreateViewModel;
import femr.ui.views.html.sessions.create;
import femr.ui.views.html.sessions.editPassword;
import femr.util.calculations.dateUtils;
import femr.util.stringhelpers.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.Controller;
import play.mvc.Result;

import java.util.ArrayList;
import java.util.regex.Pattern;

public class SessionsController extends Controller {

    private final FormFactory formFactory;
    private final ISessionService sessionsService;
    private final IUserService userService;

    @Inject
    public SessionsController(FormFactory formFactory, ISessionService sessionsService, IUserService userService) {

        this.formFactory = formFactory;
        this.sessionsService = sessionsService;
        this.userService = userService;
    }

    public Result createGet() {
        CurrentUser currentUser = sessionsService.retrieveCurrentUserSession();

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);

        if (currentUser != null) {
            return redirect(routes.HomeController.index());
        }

        return ok(create.render(createViewModelForm));
    }

    public Result createPost() {

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);
        CreateViewModel viewModel = createViewModelForm.bindFromRequest().get();
        ServiceResponse<CurrentUser> response = sessionsService.createSession(viewModel.getEmail(), viewModel.getPassword(), request().remoteAddress());

        if (response.hasErrors()) {
            return ok(create.render(createViewModelForm));
        }else{
            IUser user = userService.retrieveById(response.getResponseObject().getId());
            user.setLastLogin(dateUtils.getCurrentDateTime());
            ServiceResponse<IUser> userResponse = userService.update(user, false);
            if (userResponse.hasErrors()){
                throw new RuntimeException();
            }

            DateTime start = new DateTime(user.getPasswordCreatedDate());
            DateTime stop = new DateTime(DateTime.now());
            int daysBetween = Days.daysBetween(start, stop).getDays();

            if(daysBetween > 60){
                user.setPasswordReset(true);
            }

            if (user.getPasswordReset() == true){
                return editPasswordGet(user);
            }
        }

        return redirect(routes.HomeController.index());

    }

    public Result editPasswordGet(IUser user){

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);

        return ok(editPassword.render(user.getFirstName(), user.getLastName(), createViewModelForm, new ArrayList<String>()));
    }

    public Result editPasswordPost(){

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);
        CreateViewModel viewModel = createViewModelForm.bindFromRequest().get();
        CurrentUser currentUser = sessionsService.retrieveCurrentUserSession();
        IUser user = userService.retrieveById(currentUser.getId());
        Boolean isNewPassword = false;

        Pattern hasUppercase = Pattern.compile("[A-Z]");
        Pattern hasNumber = Pattern.compile("\\d");
        ArrayList<String> messages = new ArrayList<>();
        if (StringUtils.isNullOrWhiteSpace(viewModel.getNewPassword()))
            messages.add("password is a required field");
        else
        {
            if(viewModel.getNewPassword().length() < 6)        //AJ Saclayan Password Constraints
                messages.add("password is less than 6 characters");
            if (!hasUppercase.matcher(viewModel.getNewPassword()).find())
                    messages.add("password must have an uppercase");
            if (!hasNumber.matcher(viewModel.getNewPassword()).find())
                    messages.add("password must have a number");
            if(!viewModel.getNewPassword().equals(viewModel.getNewPasswordVerify()))
                messages.add("passwords do not match");
            //check if new password is equal to the old password
            if(userService.checkOldPassword(viewModel.getNewPassword(),userService.retrieveById(currentUser.getId()).getPassword()))
                messages.add("password must not be the same one used before reset");

        }

        if(!messages.isEmpty())
            return ok(editPassword.render(user.getFirstName(), user.getLastName(), createViewModelForm, messages));
        else
        {
            user.setPassword(viewModel.getNewPassword());
            user.setPasswordCreatedDate(DateTime.now());
            user.setPasswordReset(false);
            isNewPassword = true;
        }

        ServiceResponse<IUser> userResponse = userService.update(user, isNewPassword);
        if (userResponse.hasErrors()){
            throw new RuntimeException();
        }
        return redirect(routes.HomeController.index());
    }

    public Result delete() {
        sessionsService.invalidateCurrentUserSession();

        return redirect(routes.HomeController.index());
    }
}
</code>```

This is the createForm in ui\views\sessions

```<code>@(gcreateForm: Form[femr.ui.models.sessions.CreateViewModel], errorMessage: java.lang.String)

@import femr.ui.views.html.layouts.main
@import femr.ui.controllers.routes.SessionsController
    @styles = {
        <link rel="stylesheet" href="@routes.Assets.versioned("css/login.css")">
    }
@main("Login", styles = styles) {

    @helper.form(action = SessionsController.createPost(), 'class -> "form-signin") {
        <div id="login">
            <h1>Please sign in</h1>
            @if (!@errorMessage.isEmpty()) {
                <div>@errorMessage</div>
            }
            <input type="text" name="email" placeholder="Email" />
            <input type="password" name="password" placeholder="Password" />
            <input type="submit" value="Log in" />
            <img src="@routes.Assets.versioned("img/logo_color_sm.png")" />
        </div>
    }
}
</code>```

HomeController.java

```<code>package femr.ui.controllers;

import com.google.inject.Inject;
import femr.common.dtos.CurrentUser;
import femr.business.services.core.ISessionService;
import femr.ui.views.html.home.index;
import femr.ui.views.html.sessions.create;
import play.mvc.Controller;
import play.mvc.Result;

public class HomeController extends Controller {

    private ISessionService sessionService;

    @Inject
    public HomeController(ISessionService sessionService) {
        this.sessionService = sessionService;
    }

    public Result index() {
        CurrentUser currentUser = sessionService.retrieveCurrentUserSession();

        if (null != currentUser) {
            return ok(index.render(currentUser));
        }
        return ok(create.render(null));
    }

}
</code>```

答:
1 - When you have an expression like this you don't need to add the @ on the variable because it is already inside a scala code block.

2 -  errorMessage: java.lang.String, Change your variable type to only String I guess it is better if you use Scala string there may be some differences for the template engine.

@if (!errorMessage.isEmpty()) {

@errorMessage

}

Body:
When I attempting to compile my Play Framework 2. project, I receive this error: '(' expected but ')' found.
What I'm trying to do is : 'After a failed login attempt, user should get feedback. If the login attempt fails server side, show error messages on page after the failed request. Could someone please help me out.

I added the string that I want to display on the form after a failed login attempt as below:

if (response.hasErrors()) {
return ok(create.render(createViewModelForm, "invalid username or password"));

And on the create.scala.html

@if (!@errorMessage.isEmpty()) {

@errorMessage

  }

This is the SessionsController.java   > ui\controllers\SessionsController

package femr.ui.controllers;

import com.google.inject.Inject;
import femr.business.services.core.ISessionService;
import femr.business.services.core.IUserService;
import femr.common.dtos.CurrentUser;
import femr.common.dtos.ServiceResponse;
import femr.data.models.core.IUser;
import femr.ui.models.sessions.CreateViewModel;
import femr.ui.views.html.sessions.create;
import femr.ui.views.html.sessions.editPassword;
import femr.util.calculations.dateUtils;
import femr.util.stringhelpers.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.Controller;
import play.mvc.Result;

import java.util.ArrayList;
import java.util.regex.Pattern;

public class SessionsController extends Controller {

    private final FormFactory formFactory;
    private final ISessionService sessionsService;
    private final IUserService userService;

    @Inject
    public SessionsController(FormFactory formFactory, ISessionService sessionsService, IUserService userService) {

        this.formFactory = formFactory;
        this.sessionsService = sessionsService;
        this.userService = userService;
    }

    public Result createGet() {
        CurrentUser currentUser = sessionsService.retrieveCurrentUserSession();

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);

        if (currentUser != null) {
            return redirect(routes.HomeController.index());
        }

        return ok(create.render(createViewModelForm));
    }

    public Result createPost() {

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);
        CreateViewModel viewModel = createViewModelForm.bindFromRequest().get();
        ServiceResponse<CurrentUser> response = sessionsService.createSession(viewModel.getEmail(), viewModel.getPassword(), request().remoteAddress());

        if (response.hasErrors()) {
            return ok(create.render(createViewModelForm));
        }else{
            IUser user = userService.retrieveById(response.getResponseObject().getId());
            user.setLastLogin(dateUtils.getCurrentDateTime());
            ServiceResponse<IUser> userResponse = userService.update(user, false);
            if (userResponse.hasErrors()){
                throw new RuntimeException();
            }

            DateTime start = new DateTime(user.getPasswordCreatedDate());
            DateTime stop = new DateTime(DateTime.now());
            int daysBetween = Days.daysBetween(start, stop).getDays();

            if(daysBetween > 60){
                user.setPasswordReset(true);
            }

            if (user.getPasswordReset() == true){
                return editPasswordGet(user);
            }
        }

        return redirect(routes.HomeController.index());

    }

    public Result editPasswordGet(IUser user){

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);

        return ok(editPassword.render(user.getFirstName(), user.getLastName(), createViewModelForm, new ArrayList<String>()));
    }

    public Result editPasswordPost(){

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);
        CreateViewModel viewModel = createViewModelForm.bindFromRequest().get();
        CurrentUser currentUser = sessionsService.retrieveCurrentUserSession();
        IUser user = userService.retrieveById(currentUser.getId());
        Boolean isNewPassword = false;

        Pattern hasUppercase = Pattern.compile("[A-Z]");
        Pattern hasNumber = Pattern.compile("\\d");
        ArrayList<String> messages = new ArrayList<>();
        if (StringUtils.isNullOrWhiteSpace(viewModel.getNewPassword()))
            messages.add("password is a required field");
        else
        {
            if(viewModel.getNewPassword().length() < 6)        //AJ Saclayan Password Constraints
                messages.add("password is less than 6 characters");
            if (!hasUppercase.matcher(viewModel.getNewPassword()).find())
                    messages.add("password must have an uppercase");
            if (!hasNumber.matcher(viewModel.getNewPassword()).find())
                    messages.add("password must have a number");
            if(!viewModel.getNewPassword().equals(viewModel.getNewPasswordVerify()))
                messages.add("passwords do not match");
            //check if new password is equal to the old password
            if(userService.checkOldPassword(viewModel.getNewPassword(),userService.retrieveById(currentUser.getId()).getPassword()))
                messages.add("password must not be the same one used before reset");

        }

        if(!messages.isEmpty())
            return ok(editPassword.render(user.getFirstName(), user.getLastName(), createViewModelForm, messages));
        else
        {
            user.setPassword(viewModel.getNewPassword());
            user.setPasswordCreatedDate(DateTime.now());
            user.setPasswordReset(false);
            isNewPassword = true;
        }

        ServiceResponse<IUser> userResponse = userService.update(user, isNewPassword);
        if (userResponse.hasErrors()){
            throw new RuntimeException();
        }
        return redirect(routes.HomeController.index());
    }

    public Result delete() {
        sessionsService.invalidateCurrentUserSession();

        return redirect(routes.HomeController.index());
    }
}

This is the createForm in ui\views\sessions

@(gcreateForm: Form[femr.ui.models.sessions.CreateViewModel], errorMessage: java.lang.String)

@import femr.ui.views.html.layouts.main
@import femr.ui.controllers.routes.SessionsController
    @styles = {
        <link rel="stylesheet" href="@routes.Assets.versioned("css/login.css")">
    }
@main("Login", styles = styles) {

    @helper.form(action = SessionsController.createPost(), 'class -> "form-signin") {

Please sign in

            @if (!@errorMessage.isEmpty()) {

@errorMessage

            }
            <input type="text" name="email" placeholder="Email" />
            <input type="password" name="password" placeholder="Password" />
            <input type="submit" value="Log in" />

    }
}

HomeController.java

package femr.ui.controllers;

import com.google.inject.Inject;
import femr.common.dtos.CurrentUser;
import femr.business.services.core.ISessionService;
import femr.ui.views.html.home.index;
import femr.ui.views.html.sessions.create;
import play.mvc.Controller;
import play.mvc.Result;

public class HomeController extends Controller {

    private ISessionService sessionService;

    @Inject
    public HomeController(ISessionService sessionService) {
        this.sessionService = sessionService;
    }

    public Result index() {
        CurrentUser currentUser = sessionService.retrieveCurrentUserSession();

        if (null != currentUser) {
            return ok(index.render(currentUser));
        }
        return ok(create.render(null));
    }

}

Body:
1 - When you have an expression like this you don't need to add the @ on the variable because it is already inside a scala code block.

2 -  errorMessage: java.lang.String, Change your variable type to only String I guess it is better if you use Scala string there may be some differences for the template engine.

@if (!errorMessage.isEmpty()) {
    <div>@errorMessage</div>
}


来源: stackexchange

问:
Java: queue isn't displaying all records
I am trying to add patient records into a queue and then display all the records on the screen but I am not getting them.. I guess the display method isn't working for me.. I probably made a mistake.. Here is my code for queue of the patients.</p>

```<code>public class Patient_Queue {

    private LinkedList list;

    public Patient_Queue()
    {
        // Create a new LinkedList.
        list= new LinkedList();
    }

    public boolean isEmpty()
    {
        return (list.size() == 0);
    }

    public void joinQueue(Object item)
    {
        list.add(item);
    }

    public Object Consultation()
    {
        Object item = list;
        list.remove(0);
        return item;
    }

    public void display() {
        for(int q=0;q<list.size();q++)
        {
            System.out.println(list.get(q));
        }
    }

    public int size(){
        return list.size();
    }

    public void clear()
    {
        list.clear();
    }
}
</code>```

答:
It seems to be a mistake here:

```<code>public Object Consultation()
{

    Object item = list;

    list.remove(0);

    return item;
}
</code>```

Corrected version:

```<code>public Object Consultation()
{

    Object item = list.get(0); // fix

    list.remove(0);

    return item;
}
</code>```

Note that LinkedList implements Queue interface and you can use its Queue methods directly.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to add patient records into a queue and then display all the records on the screen but I am not getting them.. I guess the display method isn't working for me.. I probably made a mistake.. Here is my code for queue of the patients.

public class Patient_Queue {

    private LinkedList list;

    public Patient_Queue()
    {
        // Create a new LinkedList.
        list= new LinkedList();
    }

    public boolean isEmpty()
    {
        return (list.size() == 0);
    }

    public void joinQueue(Object item)
    {
        list.add(item);
    }

    public Object Consultation()
    {
        Object item = list;
        list.remove(0);
        return item;
    }

    public void display() {
        for(int q=0;q<list.size();q++)
        {
            System.out.println(list.get(q));
        }
    }

    public int size(){
        return list.size();
    }

    public void clear()
    {
        list.clear();
    }
}

Body:
It seems to be a mistake here:

public Object Consultation()
{

    Object item = list;

    list.remove(0);

    return item;
}

Corrected version:

public Object Consultation()
{

    Object item = list.get(0); // fix

    list.remove(0);

    return item;
}

Note that LinkedList implements Queue interface and you can use its Queue methods directly.


问:
Understanding a JS conditional statement to resize an element and trouble shooting it
I have a section of code in a WP Plugin that is not working:

```<code>            //for compatibility with contact-form-7-signature-addon
 var cf7signature_resized = 0;

        if (cf7signature_resized == 0 && typeof signatures !== 'undefined' && signatures.constructor === Array && signatures.length > 0 ) {
            if (signatures[0].canvas.width == 0) {
                for (var i = 0; i < signatures.length; i++) {

                    jQuery(".wpcf7-form-control-signature-body>canvas").eq(0).attr('width', jQuery(".wpcf7-form-control-signature-wrap").width());
                    jQuery(".wpcf7-form-control-signature-body>canvas").eq(0).attr('height', jQuery(".wpcf7-form-control-signature-wrap").height());

                    cf7signature_resized = 1;
                }
            }
        }
</code>```

The html that it is supposed to be scouting for is something like this:

```<code>    <div class="wpcf7-form-control-signature-global-wrap" data-field-id="signature-386">
        <div class="wpcf7-form-control-signature-wrap" style="width:300px;height:200px;">
            <div class="wpcf7-form-control-signature-body">
                <canvas width="0" height="0" class="signature-386" id="wpcf7_signature-386_signature" style="touch-action: none;"></canvas>
            </div>
        </div>
    </div>
</code>```

What I think this is saying is look through the page and find all elements that are not undefined and where cf7signature_resized is equal to 0 then put them in an array.  For all those elements that have a canvas width property of 0, change the canvas width and height variables to be equal to the width and height properties of the signature wrapper. Then set the cf7signature_resized variable to 1. Am I reading this correctly?

If I am reading this correctly, this is what it should be doing but it is not. The resize is not taking place on the zero width. Essentially what it needs to do is find all the signature elements and resize them once.  I do not see any errors in the console.  What are some steps I can use to troubleshoot it?

What I do see is that the array in signatures is:

```<code> [{"signature":{"velocityFilterWeight":0.7,"minWidth":0.5,"maxWidth":2.5,"penColor":"black","backgroundColor":"rgba(0,0,0,0)","_canvas":{},"_ctx":{},"points":[],"_lastVelocity":0,"_lastWidth":1.5,"_isEmpty":true,"_mouseButtonDown":false},"input":{"jQuery112408345313077967815":28},"canvas":{},"options":[]},{"signature":{"velocityFilterWeight":0.7,"minWidth":0.5,"maxWidth":2.5,"penColor":"black","backgroundColor":"rgba(0,0,0,0)","_canvas":{},"_ctx":{},"points":[],"_lastVelocity":0,"_lastWidth":1.5,"_isEmpty":true,"_mouseButtonDown":false},"input":{"jQuery112408345313077967815":28},"canvas":{},"options":[]}]
</code>```

I am not sure that this is what is needed to complete the task.

When I extract the array another way I can see that it is pointing to the correct object:

```<code> Object
 canvas: canvas#wpcf7_signature-386_signature.signature-386
 input: input#wpcf7_input_signature-386
 options: Array[0]
 signature: b
 __proto__: Object
</code>```

This looks correct but I am not sure why it is not meeting the condition:

```<code> if (signatures[0].canvas.width == 0)
</code>```

答: Changed eq(0) to eq(i) and the loop does what it is supposed to.</p>

Body:
I have a section of code in a WP Plugin that is not working:

            //for compatibility with contact-form-7-signature-addon
 var cf7signature_resized = 0;

        if (cf7signature_resized == 0 && typeof signatures !== 'undefined' && signatures.constructor === Array && signatures.length > 0 ) {
            if (signatures[0].canvas.width == 0) {
                for (var i = 0; i < signatures.length; i++) {

                    jQuery(".wpcf7-form-control-signature-body>canvas").eq(0).attr('width', jQuery(".wpcf7-form-control-signature-wrap").width());
                    jQuery(".wpcf7-form-control-signature-body>canvas").eq(0).attr('height', jQuery(".wpcf7-form-control-signature-wrap").height());

                    cf7signature_resized = 1;
                }
            }
        }

The html that it is supposed to be scouting for is something like this:

                <canvas width="0" height="0" class="signature-386" id="wpcf7_signature-386_signature" style="touch-action: none;"></canvas>

What I think this is saying is look through the page and find all elements that are not undefined and where cf7signature_resized is equal to 0 then put them in an array.  For all those elements that have a canvas width property of 0, change the canvas width and height variables to be equal to the width and height properties of the signature wrapper. Then set the cf7signature_resized variable to 1. Am I reading this correctly?

If I am reading this correctly, this is what it should be doing but it is not. The resize is not taking place on the zero width. Essentially what it needs to do is find all the signature elements and resize them once.  I do not see any errors in the console.  What are some steps I can use to troubleshoot it?

What I do see is that the array in signatures is:

 [{"signature":{"velocityFilterWeight":0.7,"minWidth":0.5,"maxWidth":2.5,"penColor":"black","backgroundColor":"rgba(0,0,0,0)","_canvas":{},"_ctx":{},"points":[],"_lastVelocity":0,"_lastWidth":1.5,"_isEmpty":true,"_mouseButtonDown":false},"input":{"jQuery112408345313077967815":28},"canvas":{},"options":[]},{"signature":{"velocityFilterWeight":0.7,"minWidth":0.5,"maxWidth":2.5,"penColor":"black","backgroundColor":"rgba(0,0,0,0)","_canvas":{},"_ctx":{},"points":[],"_lastVelocity":0,"_lastWidth":1.5,"_isEmpty":true,"_mouseButtonDown":false},"input":{"jQuery112408345313077967815":28},"canvas":{},"options":[]}]

I am not sure that this is what is needed to complete the task.

When I extract the array another way I can see that it is pointing to the correct object:

 Object
 canvas: canvas#wpcf7_signature-386_signature.signature-386
 input: input#wpcf7_input_signature-386
 options: Array[0]
 signature: b
 __proto__: Object

This looks correct but I am not sure why it is not meeting the condition:

 if (signatures[0].canvas.width == 0)


问:
LINQ ICollection of a Model to a string with Name and Surname from within another model
I have a field which is a collection of a model ICollection "Parties", which is in another model "Matter". I want to extract the Name and Surname of each party and separate with a "/" using LINQ. I am putting these into a field called Investors, the second last item.

This is my query:

```<code>    var matterQuery = (from matter in context.Matters
  select new
  {
      matter.ID,
      matter.AttorneyRef,
      matter.Status,
      matter.ProductType,
      matter.IsDiscarded,
      matter.Base_CreatedDate,
      matter.Base_CreatedBy,
      matter.BranchID,
      matter.InstitutionID,
      matter.InvestmentTypeID,

      StatusName = matter.MatterStatu != null ? matter.MatterStatu.Name : string.Empty,
      ProductTypeName = matter.ProductType1 != null ? matter.ProductType1.Name : string.Empty,
      AccountNumber = matter.Account != null ? matter.Account.AccountNumber : string.Empty,
      CreatedBy = matter.Paralegal != null ? matter.Paralegal
      : matter.AspNetUser != null ? matter.AspNetUser.FirstName + " " + matter.AspNetUser.LastName
      : matter.User != null ? matter.User.Firstname + " " + matter.User.Surname
      : string.Empty,
      IntermediaryName = matter.IntermediaryBranch != null ? matter.IntermediaryBranch.Intermediary.Name
      : matter.Attorney != null ? matter.Attorney.AttorneyName
      : string.Empty,
      CloseRequested = matter.CloseAccounts.Where(x => x.Status == (int)CloseAccountStatusEnum.Authorised).Count() > 0,
      StatementRequested = matter.Account != null ? matter.Account.StatementRequested : false,
      RequestedDate = matter.RequestedDate.HasValue ? matter.RequestedDate.Value : matter.Base_CreatedDate,
      Investors = matter.Parties.Select(x => x.Name.ToString()).Concat(matter.Parties.Select(x => x.Surname.ToString())),
      SoftLock = matter.SoftLock,
  })
   .AsQueryable();
</code>```

I need this in 1 long string as I am doing a search on the results for a filter and the following line:

```<code>(x.Investors != null && x.Investors.ToLower().Contains(search))
</code>```

requires it be in a string format. I want to display the results as "Name1 Surname1 / Name2 Surname2 / ..."

How can I do this?

EDIT:

I have tried Join and Aggregate but I get the errors:

base {System.SystemException} = {System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
   at System.Da...

and...

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Aggregate[String](System.Collections.Generic.IEnumerable1[System.String], System.Func3[System.String,System.String,System.String])'

答:
Assuming that your search is working and the result of the search is IEnumerable<string>, you can do this to create the string that you want:

```<code>// IEnumerable<string> searchResult = ... this is your search statement
string result = String.Join(" / ", searchResult);
</code>```

Body:
I have a field which is a collection of a model ICollection "Parties", which is in another model "Matter". I want to extract the Name and Surname of each party and separate with a "/" using LINQ. I am putting these into a field called Investors, the second last item.

This is my query:

    var matterQuery = (from matter in context.Matters
  select new
  {
      matter.ID,
      matter.AttorneyRef,
      matter.Status,
      matter.ProductType,
      matter.IsDiscarded,
      matter.Base_CreatedDate,
      matter.Base_CreatedBy,
      matter.BranchID,
      matter.InstitutionID,
      matter.InvestmentTypeID,

      StatusName = matter.MatterStatu != null ? matter.MatterStatu.Name : string.Empty,
      ProductTypeName = matter.ProductType1 != null ? matter.ProductType1.Name : string.Empty,
      AccountNumber = matter.Account != null ? matter.Account.AccountNumber : string.Empty,
      CreatedBy = matter.Paralegal != null ? matter.Paralegal
      : matter.AspNetUser != null ? matter.AspNetUser.FirstName + " " + matter.AspNetUser.LastName
      : matter.User != null ? matter.User.Firstname + " " + matter.User.Surname
      : string.Empty,
      IntermediaryName = matter.IntermediaryBranch != null ? matter.IntermediaryBranch.Intermediary.Name
      : matter.Attorney != null ? matter.Attorney.AttorneyName
      : string.Empty,
      CloseRequested = matter.CloseAccounts.Where(x => x.Status == (int)CloseAccountStatusEnum.Authorised).Count() > 0,
      StatementRequested = matter.Account != null ? matter.Account.StatementRequested : false,
      RequestedDate = matter.RequestedDate.HasValue ? matter.RequestedDate.Value : matter.Base_CreatedDate,
      Investors = matter.Parties.Select(x => x.Name.ToString()).Concat(matter.Parties.Select(x => x.Surname.ToString())),
      SoftLock = matter.SoftLock,
  })
   .AsQueryable();

I need this in 1 long string as I am doing a search on the results for a filter and the following line:

(x.Investors != null && x.Investors.ToLower().Contains(search))

requires it be in a string format. I want to display the results as "Name1 Surname1 / Name2 Surname2 / ..."

How can I do this?

EDIT:

I have tried Join and Aggregate but I get the errors:

base {System.SystemException} = {System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
   at System.Da...

and...

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Aggregate[String](System.Collections.Generic.IEnumerable1[System.String], System.Func3[System.String,System.String,System.String])'

Body:
Assuming that your search is working and the result of the search is IEnumerable<string>, you can do this to create the string that you want:

// IEnumerable<string> searchResult = ... this is your search statement
string result = String.Join(" / ", searchResult);


问:
Accessing data in an array of object for a map in React
```<code>"data": {
 "offset": 0,
 "limit": 20,
 "total": 1,
 "count": 1,
 "results": [
   {
    "id": 1009144,
    "name": "A.I.M.",
    "modified": "2013-10-17T14:41:30-0400",
    "thumbnail": {
      "path": "i.annihil.us/u/prod/marvel/i/mg/6/20/52602f21f29ec",
      "extension": "jpg"
    },
    "resourceURI": "gateway.marvel.com/v1/public/characters/1009144",
    "comics": {
      "available": 33,
      "collectionURI": "gateway.marvel.com/v1/public/characters/1009144/comics",
      "items": [
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/36763",
          "name": "Ant-Man & the Wasp (2010) #3"
        },
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/17553",
          "name": "Avengers (1998) #67"
        }
     ]
   }
  }
]
}
</code>```

I  am using axios to fetch datas from an api inside a React component. I would like to access to the key items in my json response in order to setState but I can't.

```<code>export default class Hero extends React.Component {
constructor(props) {
super(props);
this.state = {
    details : [],
    comics :[]
};
}
componentDidMount() {
    axios.get(infoUrl).then((res) => {
    this.setState({details : res.data.data.results,
                    comics : res.data.data.results.results[6].items});
})
}
render() {

     (<div>
      </div>)
}
}
</code>```

I can access to my state details but not the comics one.

答:
Results array contains only one item, so you need to use index 0 instead of 6. Another thing is items is present inside comics, so first access comics then access items, use this:

```<code>componentDidMount() {
    axios.get(infoUrl).then((res) => {
    this.setState({
            details : res.data.data.results,
            comics : res.data.data.results[0].comics.items});
     })
}
</code>```

Run this snippet:

let data = {"data": {
 "offset": 0,
 "limit": 20,
 "total": 1,
 "count": 1,
 "results": [
   {
    "id": 1009144,
    "name": "A.I.M.",
    "modified": "2013-10-17T14:41:30-0400",
    "thumbnail": {
      "path": "i.annihil.us/u/prod/marvel/i/mg/6/20/52602f21f29ec",
      "extension": "jpg"
    },
    "resourceURI": "gateway.marvel.com/v1/public/characters/1009144",
    "comics": {
      "available": 33,
      "collectionURI": "gateway.marvel.com/v1/public/characters/1009144/comics",
      "items": [
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/36763",
          "name": "Ant-Man & the Wasp (2010) #3"
        },
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/17553",
          "name": "Avengers (1998) #67"
        }
     ]
   }
  }
 ]
 }
}
console.log('items', data.data.results[0].comics.items)```

Body:
"data": {
 "offset": 0,
 "limit": 20,
 "total": 1,
 "count": 1,
 "results": [
   {
    "id": 1009144,
    "name": "A.I.M.",
    "modified": "2013-10-17T14:41:30-0400",
    "thumbnail": {
      "path": "i.annihil.us/u/prod/marvel/i/mg/6/20/52602f21f29ec",
      "extension": "jpg"
    },
    "resourceURI": "gateway.marvel.com/v1/public/characters/1009144",
    "comics": {
      "available": 33,
      "collectionURI": "gateway.marvel.com/v1/public/characters/1009144/comics",
      "items": [
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/36763",
          "name": "Ant-Man & the Wasp (2010) #3"
        },
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/17553",
          "name": "Avengers (1998) #67"
        }
     ]
   }
  }
]
}

I  am using axios to fetch datas from an api inside a React component. I would like to access to the key items in my json response in order to setState but I can't.

export default class Hero extends React.Component {
constructor(props) {
super(props);
this.state = {
    details : [],
    comics :[]
};
}
componentDidMount() {
    axios.get(infoUrl).then((res) => {
    this.setState({details : res.data.data.results,
                    comics : res.data.data.results.results[6].items});
})
}
render() {

     (

)
}
}

I can access to my state details but not the comics one.

Body:
Results array contains only one item, so you need to use index 0 instead of 6. Another thing is items is present inside comics, so first access comics then access items, use this:

componentDidMount() {
    axios.get(infoUrl).then((res) => {
    this.setState({
            details : res.data.data.results,
            comics : res.data.data.results[0].comics.items});
     })
}

Run this snippet:

let data = {"data": {
 "offset": 0,
 "limit": 20,
 "total": 1,
 "count": 1,
 "results": [
   {
    "id": 1009144,
    "name": "A.I.M.",
    "modified": "2013-10-17T14:41:30-0400",
    "thumbnail": {
      "path": "i.annihil.us/u/prod/marvel/i/mg/6/20/52602f21f29ec",
      "extension": "jpg"
    },
    "resourceURI": "gateway.marvel.com/v1/public/characters/1009144",
    "comics": {
      "available": 33,
      "collectionURI": "gateway.marvel.com/v1/public/characters/1009144/comics",
      "items": [
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/36763",
          "name": "Ant-Man & the Wasp (2010) #3"
        },
        {
          "resourceURI": "gateway.marvel.com/v1/public/comics/17553",
          "name": "Avengers (1998) #67"
        }
     ]
   }
  }
 ]
 }
}
console.log('items', data.data.results[0].comics.items)


问:
Using Coldfusion in Atom
How do you use the text editor Atom to connect with Coldfusion 10? I am writing code but the Coldfusion is just coming out as pure text and not running.

When I open the same folder in Dreamweaver the CF code is actually running.

So basically the setup we have is a server that is running CF and our "work/files/folders". Then from my pc I open the file/folder that is on that server and run the code from my pc.

Dreamweaver works. Atom does not.

Is there something special you have to do to tell Atom to connect with the Coldfusion administrator or something?

答:
I haven't used Dreamweaver in years but I recall that it could be configured with different views. One of those views allowed you to have a "live" browser view and a text editor side-by-side. As you made changes to the code you could see them immediately within Dreamweaver itself. I assume this is the functionality you are after. They called it "live view" apparently. Here is an example that I found here.

A. Application bar B. Document toolbar C. Document window D. Workspace switcher E. Panels F. Code View G. Status bar H. Tag selector I. Live View J. Toolbar

One of the true powers of Atom comes from the packages that have been developed for it. Most likely if you are looking for some functionality someone has created it already.  That's what I have found with using it. The packages that I have installed to work on CFML are:

atom-beautify

autocomplete-cfml

language-cfml

While Atom can handle static HTML files directly, it does not know how to render CFML files. It would need a CFML engine to do that. I have not used this package myself but I believe the one that will help you is the browser-plus package. It allows you to run a browser within Atom. From that browser you can surf to your ColdFusion server and see the pages you are working on.

If you are running ColdFusion locally on your computer then just edit the webroot files directly. If you are running ColdFusion on a server, then just map a drive to the server's webroot and you can edit the files from that mapped drive. After saving any changes just refresh that browser.

I should mention that browser-plus is only one option for Atom that I found. There are others. Depending on what your needs are a different one may work better for you. Here are a few more for reference but definitely do some searching and see what works for you.

atom-webbrowser

open-in-browser

web-view

Title: Using Coldfusion in Atom

ContentLicense: CC BY-SA 4.0


问:
phpexcel download file and save in directory
i am using phpexcel with codeignitor.following code ask for download only. i want that it should also save file in following path

$filename= "kp.xlsx";
$filePath = FCPATH."files/application_download/".$filename;

```<code>if (file_exists($filePath)) {
             unlink($filePath);
            }
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $filename . '"');
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007');
          $objWriter->save('php://output');
</code>```

if i do this   $objWriter->save($filePath);  then this will save a blank file

答:
if you want to give name by yourself then you can specify as I have specified in $a

I want to use filename from where this function is being called so I have also concat that name to the excel file name  and also attached current date to the filename

LogReport is a folder where my files will be downloaded

```<code>self::$objPHPExcel = new PHPExcel();
$objWriter = PHPExcel_IOFactory::createWriter(self::$objPHPExcel, 'Excel2007');
        $a = 'Log' . self::$filename . date("Y-m-d") . '.xlsx';
        $objWriter->save(__DIR__ . '/LogReport/' . $a);
</code>```

Body:
i am using phpexcel with codeignitor.following code ask for download only. i want that it should also save file in following path

$filename= "kp.xlsx";
$filePath = FCPATH."files/application_download/".$filename;

if (file_exists($filePath)) {
             unlink($filePath);
            }
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $filename . '"');
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007');
          $objWriter->save('php://output');

if i do this   $objWriter->save($filePath);  then this will save a blank file

Body:
if you want to give name by yourself then you can specify as I have specified in $a

I want to use filename from where this function is being called so I have also concat that name to the excel file name  and also attached current date to the filename

LogReport is a folder where my files will be downloaded

self::$objPHPExcel = new PHPExcel();
$objWriter = PHPExcel_IOFactory::createWriter(self::$objPHPExcel, 'Excel2007');
        $a = 'Log' . self::$filename . date("Y-m-d") . '.xlsx';
        $objWriter->save(__DIR__ . '/LogReport/' . $a);


问:
Linq to NHibernate - select count problem
Given the classes A and B where

```<code>class A
{
 string Name;
 Ilist<B> BList;
}

class B
{
 string Name;
}
</code>```

With FluentNH mapping, relationship is many-to-many which is HasManyToMany(x => x.B) for A. B has no reference to A. NH version is 2.1.2.4000.

What should be the linq query to select the collection where each row contains B.Name and count of A's containing that B? Result must be the List of anonymous type who has 2 fields: Name and Count. Result also should include all B's, hence it should be outer join.

My intend is to get the result with minimum round-trips to database, possibly in one go.

答:
If you want to do it in Linq in one hit in code, you could do this...

```<code>var result = Session.Linq<A>()
    .SelectMany(a => a.BList, (a, b) => new { b.Name, A = a.Id })
    .ToList()
    .GroupBy(x => x.Name)
    .Select(x => new { Name = x.Key, Count = x.Count() })
    .ToList();
</code>```

NHibernate.Linq (2.1.2.4000) can't handle a GroupBy after a SelectMany it seems, so the first ToList pulls all the data into memory. This is inefficient -- a SQL count would be better.

Alternatively, you could add a lazy loaded collection to your B class that goes back to A. If you're using a many-to-many table in the middle, that should be easy.

```<code>public class B
{
    public virtual string Name { get; set; }
    public virtual IList<A> AList { get; private set; }
}
</code>```

Your query simply becomes...

```<code>var result = Session.Linq<B>()
    .Where(b => b.AList.Count > 0)
    .Select(b => new { b.Name, b.AList.Count }
    .ToList();
</code>```

Which produces very efficient SQL from Linq (using a count) and gives the same result.

ContentLicense: CC BY-SA 2.5

Body:
Given the classes A and B where

class A
{
 string Name;
 Ilist BList;
}

class B
{
 string Name;
}

With FluentNH mapping, relationship is many-to-many which is HasManyToMany(x => x.B) for A. B has no reference to A. NH version is 2.1.2.4000.

What should be the linq query to select the collection where each row contains B.Name and count of A's containing that B? Result must be the List of anonymous type who has 2 fields: Name and Count. Result also should include all B's, hence it should be outer join.

My intend is to get the result with minimum round-trips to database, possibly in one go.

Body:
If you want to do it in Linq in one hit in code, you could do this...

var result = Session.Linq<A>()
    .SelectMany(a => a.BList, (a, b) => new { b.Name, A = a.Id })
    .ToList()
    .GroupBy(x => x.Name)
    .Select(x => new { Name = x.Key, Count = x.Count() })
    .ToList();

NHibernate.Linq (2.1.2.4000) can't handle a GroupBy after a SelectMany it seems, so the first ToList pulls all the data into memory. This is inefficient -- a SQL count would be better.

Alternatively, you could add a lazy loaded collection to your B class that goes back to A. If you're using a many-to-many table in the middle, that should be easy.

public class B
{
    public virtual string Name { get; set; }
    public virtual IList<A> AList { get; private set; }
}

Your query simply becomes...

var result = Session.Linq<B>()
    .Where(b => b.AList.Count > 0)
    .Select(b => new { b.Name, b.AList.Count }
    .ToList();

Which produces very efficient SQL from Linq (using a count) and gives the same result.


问:
textIsSelectable not working with Edittext
I have seen many question like this here and lots of solution but nothing is working for me. below is my EditText xml

```<code>        <EditText
        android:id="@+id/summary_edittextview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="10dp"
        android:lines="15"
        android:maxLength="1000"
        android:textIsSelectable="true"
        android:textSize="16dp"
        android:backgroundTint="@color/colorPrimaryDark"/>
</code>```

I tried to do textIsSelectable=true which makes edittext disable and nothing happens, I tried using cursorVisible=true but that also does not solve my problem. Please help i want to allow user to copy text which is inside EditText

More Details:-
This EditText is under layout of fragment and I am using this style as app theme

```<code>  <style name="AppTheme.Dark" parent="Theme.AppCompat.Light.NoActionBar">
</code>```

even if i remove textIsSelectable=true it doesn't work. Please help me where i am doing mistake.

答:
Its style problem, change it to following to check it works or not?</p>

```<code>  <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</code>```

Body:
I have seen many question like this here and lots of solution but nothing is working for me. below is my EditText xml

        <EditText
        android:id="@+id/summary_edittextview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="10dp"
        android:lines="15"
        android:maxLength="1000"
        android:textIsSelectable="true"
        android:textSize="16dp"
        android:backgroundTint="@color/colorPrimaryDark"/>

I tried to do textIsSelectable=true which makes edittext disable and nothing happens, I tried using cursorVisible=true but that also does not solve my problem. Please help i want to allow user to copy text which is inside EditText

More Details:-
This EditText is under layout of fragment and I am using this style as app theme

Body:
Its style problem, change it to following to check it works or not?

  <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">


问:
posting formdata with ajax has csrf error in django
I'm new to ajax and django and I'm trying to send a file in a form using formdata and ajax but I'm getting csrf token missing error and I've searched alot but can't solve this problem.Should I use cookies?if so,how?.I really need help.My codes are here:

urls.py

...

```<code>url(r'^administration/library/add_ebook/ajax/$',upload_ebook_ajax, name='upload_ebook_ajax'),
</code>```

...

forms.py

```<code>class EbookForm(forms.ModelForm):
    class Meta:
        model = Ebook
        fields = ('ebook_title', 'ebook_publisher','ebook_publication_date','ebook_Type','ebook_keywords','ebook_preview','ebook_url','ebook_categories', )
</code>```

views.py

```<code>@transaction.atomic()
def upload_ebook_ajax(request):

if request.method == 'POST':
    form = EbookForm(request.POST, request.FILES)
    if form.is_valid():

        form.save()
        data['form_is_valid'] = True

    else:
        data['form_is_valid'] = False
else:
    form = EbookForm()

context = {'form': form}
data['html_form'] = render_to_string('upldebook.html',context,request=request)
return JsonResponse(data)
</code>```

upldebook.html

```<code>{% load crispy_forms_tags %}
{% crispy form %}
</code>```

add_ebook.html

```<code><div class="c">
                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
                    <script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script>
                    <script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script>
                    <script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script>
                <form method="post" enctype="multipart/form-data" action="{% url 'upload_ebook_ajax' %}" class="js-upload-ebook-form">
                    {% csrf_token %}

                    <div class="frmclass"></div>

                <script src="{% static 'uploadebook.js' %}"></script>

                    <button type="submit">Upload</button>
                    </form>
                </div>
</code>```

uploadebook.js

```<code>//for showing form
 $.ajax({
      url: '/administration/library/add_ebook/ajax',
      type: 'get',
      dataType: 'json',
      success: function (data) {
        $(".frmclass").html(data.html_form);
      }
    });
//for form submit
    $(".js-upload-ebook-form").submit( function (e) {
    e.preventDefault();
    var frmdt = new FormData($('form').get(0)); //I don't know what is 'form' :|
    frmdt.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    $.ajax({
    url: $(this).attr('action'),
    type: $(this).attr('method'),
    data: frmdt,
    cache: false,
    processData: false,
    contentType: false,
    dataType: 'json',
    success: function(data) {
        alert("SUCCESS1");
        window.location = "/"
    }

    });
    return false;
    });
</code>```

答:
I just needed this:

```<code>data:  new FormData(this)
</code>```

and now it works.

Thanks to this link:
http://phppot.com/php/php-ajax-image-upload/

Body:
I'm new to ajax and django and I'm trying to send a file in a form using formdata and ajax but I'm getting csrf token missing error and I've searched alot but can't solve this problem.Should I use cookies?if so,how?.I really need help.My codes are here:

urls.py

...

url(r'^administration/library/add_ebook/ajax/$',upload_ebook_ajax, name='upload_ebook_ajax'),

...

forms.py

class EbookForm(forms.ModelForm):
    class Meta:
        model = Ebook
        fields = ('ebook_title', 'ebook_publisher','ebook_publication_date','ebook_Type','ebook_keywords','ebook_preview','ebook_url','ebook_categories', )

views.py

@transaction.atomic()
def upload_ebook_ajax(request):

if request.method == 'POST':
    form = EbookForm(request.POST, request.FILES)
    if form.is_valid():

        form.save()
        data['form_is_valid'] = True

    else:
        data['form_is_valid'] = False
else:
    form = EbookForm()

context = {'form': form}
data['html_form'] = render_to_string('upldebook.html',context,request=request)
return JsonResponse(data)

upldebook.html

{% load crispy_forms_tags %}
{% crispy form %}

add_ebook.html

                <form method="post" enctype="multipart/form-data" action="{% url 'upload_ebook_ajax' %}" class="js-upload-ebook-form">
                    {% csrf_token %}

                    <button type="submit">Upload</button>
                    </form>

uploadebook.js

//for showing form
 $.ajax({
      url: '/administration/library/add_ebook/ajax',
      type: 'get',
      dataType: 'json',
      success: function (data) {
        $(".frmclass").html(data.html_form);
      }
    });
//for form submit
    $(".js-upload-ebook-form").submit( function (e) {
    e.preventDefault();
    var frmdt = new FormData($('form').get(0)); //I don't know what is 'form' :|
    frmdt.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    $.ajax({
    url: $(this).attr('action'),
    type: $(this).attr('method'),
    data: frmdt,
    cache: false,
    processData: false,
    contentType: false,
    dataType: 'json',
    success: function(data) {
        alert("SUCCESS1");
        window.location = "/"
    }

    });
    return false;
    });

Body:
I just needed this:

data:  new FormData(this)

and now it works.

Thanks to this link:
http://phppot.com/php/php-ajax-image-upload/


问:
How to disable the Formatter in Delphi 2010
The formatter in Delphi 2010 is really an annoying thing to me.
I prefer formatting my code manually.
I believe I do it better.

How can I disable it?

NOTE: Answers on why I don't use it in the first place will not be accepted. I need it switched OFF. Nothing more, nothing less.

答:
There is no need for downloading and installing an extension, not even for deleting a file!

In the Delphi 10 Options head to:

Formatting / Delphi / Profiles and Status
(the captions may differ slightly, I have translated them from German)

There is a Checkbox there, titled "Activate Formatting".

Possible downside: This Formatter feature is also deactivated in the Edit menu.


问:
Entity framework and inheritance: NotSupportedException
I'm getting

System.NotSupportedException: All
  objects in the EntitySet
  'Entities.Message' must have unique
  primary keys. However, an instance of
  type 'Model.Message' and an instance
  of type 'Model.Comment' both have the
  same primary key value

but I have no idea what this means.

Using EF4, I have a bunch of entities of type Message. Some of these messages are actually a subtype, Comment, inheritance by table-per-type. Just

```<code> DB.Message.First();
</code>```

will produce the exception. I have other instances of subtyping where I don't experience problems but I can't see any discrepencies. Sometimes, though, the problem goes away if I restart the development server, but not always.

Edit:
I've worked out (should have before) that the problem is a fault of the stored procedure fetching my Messages. The way this is currently set up as that all the fields pertaining to Message is fetched, the Comment table is ignored by the sproc. The context then proceeds to muck this up, probably by fetching those Messages that are also Comments again, as you suggested. How to do this properly is the central issue at hand. I've found some indications to a solution at http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/bb0bb421-ba8e-4b35-b7a7-950901adb602.

答:
As you infer, it looks like the Context is fetching a Comment as a Message (not knowing that it is a comment).  Later, you ask for the actual Comment, so the context fetches the Comment.  Now you have two object instances in the Context with the same ID - one is a Message and one is a Comment.

It seems that the exception is not being thrown until after both objects have been loaded (ie when you try to access the Message the second time).  If you can find a way to remove the Message from Context when the Comment is loaded, this may solve your problem.

Another option might be to use the Table-per-hierarchy model.  This results in a bad database design but at the end of the day you have to use what works.

You might be able to avoid the problem by ensuring that the objects are loaded as Comments first.  This way, when you ask for the Message, the Context already knows about it.

Also consider using Composition over Inheritance, such that a Message has 0..1 CommentDetails.

The final suggestion is to remove the dependency on the Entity Framework from your Control code, and create a Data Access Layer which references the EF and retrieves your objects.  The DAL can turn Entity Framework objects into a different set of Entity objects which are easier to use in code.  This approach will produce a lot of code overhead, but may be suitable if you cannot use the Entity Framework to produce an Entity model which represents your Entities in the way you want to work with them.

To summarize, unless MS fix this issue, there is no solution to your problem which does not involve a rethink of your approach.  Unfortunately the Entity Framework is not ideal, especially for complex Entity models - you might be better off creating your own DAL and bypassing the EF altogether.

Body:
I'm getting

System.NotSupportedException: All
  objects in the EntitySet
  'Entities.Message' must have unique
  primary keys. However, an instance of
  type 'Model.Message' and an instance
  of type 'Model.Comment' both have the
  same primary key value

but I have no idea what this means.

Using EF4, I have a bunch of entities of type Message. Some of these messages are actually a subtype, Comment, inheritance by table-per-type. Just

 DB.Message.First();

will produce the exception. I have other instances of subtyping where I don't experience problems but I can't see any discrepencies. Sometimes, though, the problem goes away if I restart the development server, but not always.

Edit:
I've worked out (should have before) that the problem is a fault of the stored procedure fetching my Messages. The way this is currently set up as that all the fields pertaining to Message is fetched, the Comment table is ignored by the sproc. The context then proceeds to muck this up, probably by fetching those Messages that are also Comments again, as you suggested. How to do this properly is the central issue at hand. I've found some indications to a solution at http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/bb0bb421-ba8e-4b35-b7a7-950901adb602.


问:
Using dates in oracle prepared statements from .net4
Given this table:

```<code>myTable
EMPID           NOT NULL CHAR(10)
DEFFECTIVE      NOT NULL DATE
SSCHEME                  CHAR(10)
</code>```

and this prepared statement:

```<code>update myTable set sScheme = :sScheme
where empID = :sEmpID
and dEffective= :dStart
</code>```

with these parameters:

```<code>OCmd.Parameters.Add("sEmpID", OracleDbType.Char).Value = sEmp_No        'string
OCmd.Parameters.Add("dStart", OracleDbType.Date).Value = dtStart        'System.DateTime
OCmd.Parameters.Add("sScheme", OracleDbType.Char).Value = sScheme       'string
</code>```

Why do I keep getting Oracle.DataAccess.Client.OracleException ORA-01858: a non-numeric character was found where a numeric was expected

I see lots of people suggesting to pass the date in as formatted string and then do a to_date in the query - but that just seems a horribly backward step.

Have tried using SetSessionInfo (from OracleGlobalization) to match the DateFormat as specified by Culture but to no avail.

Initially this app was running a .net2 using the MS oracle provider with no issues, but moving to .net4 and Oracle.DataAccess causes me this headache.

Using System.DateTime as the .net type for the date as per instructions here: http://docs.oracle.com/html/E15167_01/featTypes.htm

.net framework 4
Oracle.DataAccess (v4.112.3.0)

答:
I'd forgotten about Oracle.DataAccess defaulting to BindByName = false.

Solution:  OCmd.BindByName = True

Body:
Given this table:

myTable
EMPID           NOT NULL CHAR(10)
DEFFECTIVE      NOT NULL DATE
SSCHEME                  CHAR(10)

and this prepared statement:

update myTable set sScheme = :sScheme
where empID = :sEmpID
and dEffective= :dStart

with these parameters:

OCmd.Parameters.Add("sEmpID", OracleDbType.Char).Value = sEmp_No        'string
OCmd.Parameters.Add("dStart", OracleDbType.Date).Value = dtStart        'System.DateTime
OCmd.Parameters.Add("sScheme", OracleDbType.Char).Value = sScheme       'string

Why do I keep getting Oracle.DataAccess.Client.OracleException ORA-01858: a non-numeric character was found where a numeric was expected

I see lots of people suggesting to pass the date in as formatted string and then do a to_date in the query - but that just seems a horribly backward step.

Have tried using SetSessionInfo (from OracleGlobalization) to match the DateFormat as specified by Culture but to no avail.

Initially this app was running a .net2 using the MS oracle provider with no issues, but moving to .net4 and Oracle.DataAccess causes me this headache.

Using System.DateTime as the .net type for the date as per instructions here: http://docs.oracle.com/html/E15167_01/featTypes.htm

.net framework 4
Oracle.DataAccess (v4.112.3.0)


问:
FileOutputStream alternative for Java 1.6
I have to retrofit a piece of java code that must be compatible with Java 1.6 and I'm looking for an alternative for fileoutputstream in the following function. I am using apache.commons FTP package.</p>

```<code>import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

FTPClient ftp = null;

public FTPFetch(String host, int port, String username, String password) throws Exception
{

    ftp = new FTPClient();
    ftp.setConnectTimeout(5000);
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
    int reply;
    ftp.connect(host, port);
    reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply))
    {
        ftp.disconnect();
        throw new Exception("Exception in connecting to FTP Server");
    }
    if (ftp.login(username, password))
    {
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalActiveMode();
    } else
    {
        disconnect();
        errorLog.fatal("Remote FTP Login Failed. Username or Password is incorrect. Please update in configuration file.");
        System.exit(1);
    }
}

 try (FileOutputStream fos = new FileOutputStream(destination))
    {
        if (this.ftp.retrieveFile(source, fos))
        {
            return true;
        } else
        {
            return false;
        }
    } catch (IOException e)
    {
        return false;
    }
</code>```

答:
the code does not compile in Java 1.6 because you use try-with-resources

The try-with-resources Statement

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

...

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

the alternative is:

```<code>FileOutputStream fos = null;
try {
  fos = new FileOutputStream(destination);

  if(this.ftp.retrieveFile(source, fos)) {
    return true;
  } else {
    return false;
  }
} catch (IOException e) {
  return false;
} finally {
  if(fos != null)
    fos.close();
}
</code>```

Body:
I have to retrofit a piece of java code that must be compatible with Java 1.6 and I'm looking for an alternative for fileoutputstream in the following function. I am using apache.commons FTP package.

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

FTPClient ftp = null;

public FTPFetch(String host, int port, String username, String password) throws Exception
{

    ftp = new FTPClient();
    ftp.setConnectTimeout(5000);
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
    int reply;
    ftp.connect(host, port);
    reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply))
    {
        ftp.disconnect();
        throw new Exception("Exception in connecting to FTP Server");
    }
    if (ftp.login(username, password))
    {
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalActiveMode();
    } else
    {
        disconnect();
        errorLog.fatal("Remote FTP Login Failed. Username or Password is incorrect. Please update in configuration file.");
        System.exit(1);
    }
}

 try (FileOutputStream fos = new FileOutputStream(destination))
    {
        if (this.ftp.retrieveFile(source, fos))
        {
            return true;
        } else
        {
            return false;
        }
    } catch (IOException e)
    {
        return false;
    }

Body:
the code does not compile in Java 1.6 because you use try-with-resources

The try-with-resources Statement

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

...

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

the alternative is:

FileOutputStream fos = null;
try {
  fos = new FileOutputStream(destination);

  if(this.ftp.retrieveFile(source, fos)) {
    return true;
  } else {
    return false;
  }
} catch (IOException e) {
  return false;
} finally {
  if(fos != null)
    fos.close();
}


问:
Biggest and smallest of four integers (No arrays, no functions, fewest 'if' statements)
You see, I've self-taught myself C++ (not completely, I'm still procrastinating -_-). So, now I started university and they're teaching C and they made us do a program of inputting four integers and we have to tell the largest and smallest out of them. Simple, no?

The thing is, I already have good understanding of functions and arrays. Yes, I CAN program this in arrays, no problem. But since this was the first lab, we haven't 'learned' that yet, so I can't use any of those, it'd be very simple with that.

This is what I wrote there (it feels wrong somehow).

```<code>#include<stdio.h>

int main(void)
{
    int first, second, third, fourth;
    printf("Enter four integers (separated by space): ");
    scanf("%d %d %d %d", &first, &second, &third, &fourth);

    if((first>second) && (first>third) && (first>fourth))
        printf("\nFirst number is largest");
    else if((second>first) && (second>third) && (second>fourth))
        printf("\nSecond number is largest");
    else if((third>second) && (third>first) && (third>fourth))
        printf("\nThird number is largest");
    else if((fourth>second) && (fourth>third) && (fourth>first))
        printf("\nFourth number is largest");

    if((first<second) && (first<third) && (first<fourth))
        printf("\nFirst number is smallest");
    else if((second<first) && (second<third) && (second<fourth))
        printf("\nSecond number is smallest");
    else if((third<second) && (third<first) && (third<fourth))
        printf("\nThird number is smallest");
    else if((fourth<second) && (fourth<third) && (fourth<first))
        printf("\nFourth number is smallest");

    printf("\n");
    return 0;
}
</code>```

As you can see, it's too long and boring and complex. But seeing that all we've covered in class for now are loops and decision statements. Is there a more elegant way of doing this? One which uses fewer ifs? Not that there is something wrong with this, but it could be better.

P.S. This isn't exactly 'homework' or anything. I made a program, I just wanted to know what I could have done to make it better and to learn better programming practices.

答:
```<code>int max_of_four(int a, int b, int c, int d){
        int res=a;
        if(b/res)
            res=b;
        if(c/res)
            res=c;
        if(d/res)
            res=d;
        return res;
    }
int main() {
    int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = max_of_four(a, b, c, d);
    printf("%d", ans);

    return 0;
}
</code>```

Body:
You see, I've self-taught myself C++ (not completely, I'm still procrastinating -_-). So, now I started university and they're teaching C and they made us do a program of inputting four integers and we have to tell the largest and smallest out of them. Simple, no?

The thing is, I already have good understanding of functions and arrays. Yes, I CAN program this in arrays, no problem. But since this was the first lab, we haven't 'learned' that yet, so I can't use any of those, it'd be very simple with that.

This is what I wrote there (it feels wrong somehow).

#include<stdio.h>

int main(void)
{
    int first, second, third, fourth;
    printf("Enter four integers (separated by space): ");
    scanf("%d %d %d %d", &first, &second, &third, &fourth);

    if((first>second) && (first>third) && (first>fourth))
        printf("\nFirst number is largest");
    else if((second>first) && (second>third) && (second>fourth))
        printf("\nSecond number is largest");
    else if((third>second) && (third>first) && (third>fourth))
        printf("\nThird number is largest");
    else if((fourth>second) && (fourth>third) && (fourth>first))
        printf("\nFourth number is largest");

    if((first<second) && (first<third) && (first<fourth))
        printf("\nFirst number is smallest");
    else if((second<first) && (second<third) && (second<fourth))
        printf("\nSecond number is smallest");
    else if((third<second) && (third<first) && (third<fourth))
        printf("\nThird number is smallest");
    else if((fourth<second) && (fourth<third) && (fourth<first))
        printf("\nFourth number is smallest");

    printf("\n");
    return 0;
}

As you can see, it's too long and boring and complex. But seeing that all we've covered in class for now are loops and decision statements. Is there a more elegant way of doing this? One which uses fewer ifs? Not that there is something wrong with this, but it could be better.

P.S. This isn't exactly 'homework' or anything. I made a program, I just wanted to know what I could have done to make it better and to learn better programming practices.


问:
variable scope in woocommerce filter
My page need to display a different product name in the woocommerce email for the admin (new customer order email). To change the name i use the filter woocommerce_order_item_name.
But i must verify if it is an admin email or customer email. I use a gloab variable in this code and it works but it's not the proper way i guess. So is there a better solution to verify it's an admin email or customer email?

woocommerce/emails/email-order-items.php

```<code>global $is_admin_email;
if($show_sku) {
    $is_admin_email = True;
}
else {
    $is_admin_email = False;

// Product name
echo apply_filters( 'woocommerce_order_item_name', $item['name'], $item, false );
//Set to false again
$is_admin_email = False;
</code>```

functions.php

```<code>function filter_woocommerce_order_item_name( $item_name, $item, $false ) {
    global $is_admin_email;
    if( $is_admin_email ){
        $item_name = "Item name in admin email";
    }

    return $item_name;
};

// add the filter
add_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );
</code>```

答:
I would find a hook that shows up in the emails and includes the variable $sent_to_admin which is true when sent to an admin. This sounds like it would serve as the perfect conditional for your needs.

So, I would try the following:

```<code>add_action( 'woocommerce_email_before_order_table', 'so_43094965_order_item_names', 10, 4 );

function so_43094965_order_item_names( $order, $sent_to_admin, $plain_text, $email ){
    if( $sent_to_admin ){
        add_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );
    }
}
</code>```

This adds your filter, but only if your in an admin email.

And then:

```<code>add_action( 'woocommerce_email_after_order_table', 'so_43094965_remove_order_item_names', 10, 4 );

function so_43094965_remove_order_item_names( $order, $sent_to_admin, $plain_text, $email ){
    remove_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );
}
</code>```

This removes it so it doesn't appear in other places... I'm not sure if it is needed, but for completeness I'm throwing it out there.

This is untested, so your mileage may vary.

Title: variable scope in woocommerce filter

Body:
My page need to display a different product name in the woocommerce email for the admin (new customer order email). To change the name i use the filter woocommerce_order_item_name.
But i must verify if it is an admin email or customer email. I use a gloab variable in this code and it works but it's not the proper way i guess. So is there a better solution to verify it's an admin email or customer email?

woocommerce/emails/email-order-items.php

global $is_admin_email;
if($show_sku) {
    $is_admin_email = True;
}
else {
    $is_admin_email = False;

// Product name
echo apply_filters( 'woocommerce_order_item_name', $item['name'], $item, false );
//Set to false again
$is_admin_email = False;

functions.php

function filter_woocommerce_order_item_name( $item_name, $item, $false ) {
    global $is_admin_email;
    if( $is_admin_email ){
        $item_name = "Item name in admin email";
    }

    return $item_name;
};

// add the filter
add_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );

Body:
I would find a hook that shows up in the emails and includes the variable $sent_to_admin which is true when sent to an admin. This sounds like it would serve as the perfect conditional for your needs.

So, I would try the following:

add_action( 'woocommerce_email_before_order_table', 'so_43094965_order_item_names', 10, 4 );

function so_43094965_order_item_names( $order, $sent_to_admin, $plain_text, $email ){
    if( $sent_to_admin ){
        add_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );
    }
}

This adds your filter, but only if your in an admin email.

And then:

add_action( 'woocommerce_email_after_order_table', 'so_43094965_remove_order_item_names', 10, 4 );

function so_43094965_remove_order_item_names( $order, $sent_to_admin, $plain_text, $email ){
    remove_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );
}

This removes it so it doesn't appear in other places... I'm not sure if it is needed, but for completeness I'm throwing it out there.

This is untested, so your mileage may vary.


答:
Try-with-resources (try (AutoClosable ...)) was not available in Java 6. Omit that and you should be fine, e.g.:

```<code>FileOutputStream fos = null;
try {
  fos = new FileOutputStream(destination);
  return this.ftp.retrieveFile(source, fos);
} catch (IOException e) {
  return false;
} finally {
  if (fos != null)
    fos.close();
}
</code>```

Title: FileOutputStream alternative for Java 1.6

Body:
Try-with-resources (try (AutoClosable ...)) was not available in Java 6. Omit that and you should be fine, e.g.:

FileOutputStream fos = null;
try {
  fos = new FileOutputStream(destination);
  return this.ftp.retrieveFile(source, fos);
} catch (IOException e) {
  return false;
} finally {
  if (fos != null)
    fos.close();
}


问:
jQuery - ensure IDs are unique in inserted markup
I have the following markup:

```<code><div id="section">
    <input type="text" id="myInput">
</div>
</code>```

I am attempting to insert the html contents of this markup after itself, using the jQuery html() and after() methods:

```<code>var newSection = $('#section').html();
$('#section').after(newSection);
</code>```

So I'm ending up with something like this:

```<code><div id="section">
    <input type="text" id="myInput">
</div>
<input type="text" id="myInput">
</code>```

Is there a way I can ensure the IDs of my inputs are unique? I would prefer something like "myInput2" for the input that has been inserted. Thank you.

答:
Here's an approach that keeps your code the same but adds the new element with a unique ID, specifically "myInput2" for the second execution or "myInputN" for whichever number input is being added:

```<code>var newSection = $("#section").html();
//create new element with unique ID
newSection = $(newSection).attr('id', "myInput" + ($("input[id^=myInput").length + 1));
$("#section").after(newSection);
</code>```

To determine the next unique ID we simply query all the input tags that start with "myInput"

If you actually want new sections with inputs so the input fields appear one after the other (on top of each other) you can use the following approach which will create a new section with a unique ID and a containing input with a new ID:

```<code>//Create a new section by cloning the first section
var newSection = $("#section").clone();
//Set the new unique ID for the section
$(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
//Set the new unique ID for child input element
$(newSection).find("input").attr('id', "myInput" + ($("input[id^=myInput").length + 1));
//Add the new section last so each section appears in order by ID
$("div[id^=section").last().after(newSection);
</code>```

Body:
I have the following markup:

    <input type="text" id="myInput">

I am attempting to insert the html contents of this markup after itself, using the jQuery html() and after() methods:

var newSection = $('#section').html();
$('#section').after(newSection);

So I'm ending up with something like this:

    <input type="text" id="myInput">

<input type="text" id="myInput">

Is there a way I can ensure the IDs of my inputs are unique? I would prefer something like "myInput2" for the input that has been inserted. Thank you.

Body:
Here's an approach that keeps your code the same but adds the new element with a unique ID, specifically "myInput2" for the second execution or "myInputN" for whichever number input is being added:

var newSection = $("#section").html();
//create new element with unique ID
newSection = $(newSection).attr('id', "myInput" + ($("input[id^=myInput").length + 1));
$("#section").after(newSection);

To determine the next unique ID we simply query all the input tags that start with "myInput"

If you actually want new sections with inputs so the input fields appear one after the other (on top of each other) you can use the following approach which will create a new section with a unique ID and a containing input with a new ID:

//Create a new section by cloning the first section
var newSection = $("#section").clone();
//Set the new unique ID for the section
$(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
//Set the new unique ID for child input element
$(newSection).find("input").attr('id', "myInput" + ($("input[id^=myInput").length + 1));
//Add the new section last so each section appears in order by ID
$("div[id^=section").last().after(newSection);


问:
Multiple Implementations passed in a list
I am New to Spring.I have this question which has been bothering me for a while now. Any help would be appreciated.

There is an Interface which calls a getter method.

```<code>interface MessageHandler{

    public List GetMessageCheckerList();

}
</code>```

There is another Interface called MessageChecker which has multiple Implementations.
Say MessageChecker1, TestChecker, etc. (lets assume 2 for now )

Now how do i define this in the configuration xml file.

I actually have the bean created ,

here is the rest of the code

```<code><bean id="checkerList" class="java.util.ArrayList">
    <constructor-arg>
        <list>
            <ref bean="HL7Checker"/>
        </list>
    </constructor-arg>
</bean>

<bean id="HL7Checker" class="com.kahootz.messagereceiver.HL7CheckerImpl">
    <property name="messageExecutor" ref="Executor"/>
</bean>
</code>```

Please Advice

When I actually run the program using a main method, I get the handle of one of the beans, The HL7Checker should be passed in a list to the Bean with ID=messageHandler. But when i print out the list. It is empty.

Without using spring and only using getter and setter methods , i am able "set" a list and retrieve it using Get.

答:
Almost all of your names do not conform to the Java Naming Conventions. That makes it hard for others to understand your code.

The <ref> tag expects the name of an object, not the name of a class. So you need to define a <bean id="testChecker" class="com.test.TestChecker" /> before you can reference it.

Don't use the package name com.Test. First, it should contain only lowercase letters. Second, you should be the owner of that name.

Body:
I am New to Spring.I have this question which has been bothering me for a while now. Any help would be appreciated.

There is an Interface which calls a getter method.

interface MessageHandler{

    public List GetMessageCheckerList();

}

There is another Interface called MessageChecker which has multiple Implementations.
Say MessageChecker1, TestChecker, etc. (lets assume 2 for now )

Now how do i define this in the configuration xml file.

I actually have the bean created ,

here is the rest of the code

<bean id="checkerList" class="java.util.ArrayList">
    <constructor-arg>
        <list>
            <ref bean="HL7Checker"/>
        </list>
    </constructor-arg>
</bean>

<bean id="HL7Checker" class="com.kahootz.messagereceiver.HL7CheckerImpl">
    <property name="messageExecutor" ref="Executor"/>
</bean>

Please Advice

When I actually run the program using a main method, I get the handle of one of the beans, The HL7Checker should be passed in a list to the Bean with ID=messageHandler. But when i print out the list. It is empty.

Without using spring and only using getter and setter methods , i am able "set" a list and retrieve it using Get.


问:
Creating multiple of the same radio button group
I have a model with a list of inner class tripSeatPreference, I would like to create for each item in that list a new group of radio buttons. I have written my attempt below in the view, it does not work right now my index seems to be out of range in my for loop.

Model:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using MVC_COMP1562.Models;

namespace MVC_COMP1562.ViewModels
{
    public class SeatPreferencesShoppingCartViewModel
    {
        public ShoppingCart ShoppingCart { get; set; }
        public float Total { get; set; }
        public List<tripSeatPreference> Preferences { get; set; }

        public IEnumerable<string> SeatPreferenceOptions { get; set; }

        public class tripSeatPreference
        {
            public int Id { get; set; }
            [Required]
            public int? SeatPreferenceSelected { get; set; }
            public CartItem CartItem { get; set; }
        }
    }
}
</code>```

View:

```<code>@model MVC_COMP1562.ViewModels.SeatPreferencesShoppingCartViewModel

<table class="table">

    @for(int i=0;i<Model.SeatPreferenceOptions.Count();i++)
    {
        <tr>
            <td>@Html.DisplayFor(m=>Model.Preferences[i].CartItem.Trip.Title)</td>
        </tr>
        foreach (var radio in Model.SeatPreferenceOptions)
        {
            <tr>
                <td>@Html.RadioButtonFor(m => Model.Preferences[i].SeatPreferenceSelected, Model.Preferences[i].Id, new { id = Model.Preferences[i].Id })</td>
                <td><label for="@Model.Preferences[i].Id">@radio</label><td/>
            </tr>
        }
    }

</table>
</code>```

答:
You are looping on SeatPreferenceOptions while inside the loop you are trying to get item from SeatPreferences using index of SeatPreferenceOptions collection which will obviously fail, as there can be items more or less in one of them, so change the loop from:

```<code>@for(int i=0;i<Model.SeatPreferenceOptions.Count();i++)
</code>```

to:

```<code> @for(int i=0;i<Model.SeatPreferences.Count();i++)
</code>```

Body:
I have a model with a list of inner class tripSeatPreference, I would like to create for each item in that list a new group of radio buttons. I have written my attempt below in the view, it does not work right now my index seems to be out of range in my for loop.

Model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using MVC_COMP1562.Models;

namespace MVC_COMP1562.ViewModels
{
    public class SeatPreferencesShoppingCartViewModel
    {
        public ShoppingCart ShoppingCart { get; set; }
        public float Total { get; set; }
        public List<tripSeatPreference> Preferences { get; set; }

        public IEnumerable<string> SeatPreferenceOptions { get; set; }

        public class tripSeatPreference
        {
            public int Id { get; set; }
            [Required]
            public int? SeatPreferenceSelected { get; set; }
            public CartItem CartItem { get; set; }
        }
    }
}

View:

@model MVC_COMP1562.ViewModels.SeatPreferencesShoppingCartViewModel

    @for(int i=0;i<Model.SeatPreferenceOptions.Count();i++)
    {

            @Html.DisplayFor(m=>Model.Preferences[i].CartItem.Trip.Title)

        foreach (var radio in Model.SeatPreferenceOptions)
        {

                @Html.RadioButtonFor(m => Model.Preferences[i].SeatPreferenceSelected, Model.Preferences[i].Id, new { id = Model.Preferences[i].Id })
                @radio

        }
    }

Body:
You are looping on SeatPreferenceOptions while inside the loop you are trying to get item from SeatPreferences using index of SeatPreferenceOptions collection which will obviously fail, as there can be items more or less in one of them, so change the loop from:

@for(int i=0;i<Model.SeatPreferenceOptions.Count();i++)

to:

 @for(int i=0;i<Model.SeatPreferences.Count();i++)


问:
outlook view unique content emails having same subject
Is there any query to find distinct messages in mailbox with same subject and has different contents inside the mail body in outlook?
we can write queries in outlook to find mails but i need to know whether we have query to find distinct mails since it is available in SQL queries by using distinct keyword

Thanks in advance!!

答: No, your code would need to find messages by subject first, then decide what constitutes uniqueness and process the messages accordingly.  </p>


问:
Read and Split(Parse) data in java
I am trying to split some simple data from a .txt file. I have found some useful structures on the internet but it was not enough to split the data the way I wanted. I get a string like this:

```<code>{X:0.8940594 Y:0.6853521 Z:1.470214}
</code>```

And I want to transform it to like this;

```<code>0.8940594
0.6853521
1.470214
</code>```

And then put them in a matrix in order X=[], Y=[], Z=[]; (the data is the coordinate of an object)

Here is my code:

```<code>BufferedReader in = null; {
        try {
            in = new BufferedReader(new FileReader("file.txt"));
            String read = null;
            while ((read = in.readLine()) != null) {
                String[] splited = read.split("\\s+");
                for (String part : splited) {
                    System.out.println(part);
                }
            }
        } catch (IOException e) {
            System.out.println("There was a problem: " + e);
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }
</code>```

What do I need to add to my code to get the data the way I want?

Right now with this code I receive data like this:

```<code>{X:0.8940594
Y:0.6853521
Z:1.470214}
</code>```

答:
This code will solve your problem.

```<code>String input = "{X:0.8940594 Y:0.6853521 Z:1.470214} ";
        String[] parts = input.split("(?<= )");
        List<String> output = new ArrayList();

        for (int i = 0; i < parts.length; i++) {
            //System.out.println("*" + i);
            //System.out.println(parts[i]);
            String[] part = parts[i].split("(?<=:)");
            String[] temp = part[1].split("}");
            output.add(temp[0]);
        }

        System.out.println("This List contains numbers:" + output);
</code>```

Output->This List contains numbers:[0.8940594 , 0.6853521 , 1.470214]

Title: Read and Split(Parse) data in java

Body:
I am trying to split some simple data from a .txt file. I have found some useful structures on the internet but it was not enough to split the data the way I wanted. I get a string like this:

{X:0.8940594 Y:0.6853521 Z:1.470214}

And I want to transform it to like this;

0.8940594
0.6853521
1.470214

And then put them in a matrix in order X=[], Y=[], Z=[]; (the data is the coordinate of an object)

Here is my code:

BufferedReader in = null; {
        try {
            in = new BufferedReader(new FileReader("file.txt"));
            String read = null;
            while ((read = in.readLine()) != null) {
                String[] splited = read.split("\\s+");
                for (String part : splited) {
                    System.out.println(part);
                }
            }
        } catch (IOException e) {
            System.out.println("There was a problem: " + e);
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }

What do I need to add to my code to get the data the way I want?

Right now with this code I receive data like this:

{X:0.8940594
Y:0.6853521
Z:1.470214}

Body:
This code will solve your problem.

String input = "{X:0.8940594 Y:0.6853521 Z:1.470214} ";
        String[] parts = input.split("(?<= )");
        List<String> output = new ArrayList();

        for (int i = 0; i < parts.length; i++) {
            //System.out.println("*" + i);
            //System.out.println(parts[i]);
            String[] part = parts[i].split("(?<=:)");
            String[] temp = part[1].split("}");
            output.add(temp[0]);
        }

        System.out.println("This List contains numbers:" + output);

Output->This List contains numbers:[0.8940594 , 0.6853521 , 1.470214]


问:
extract only one part from xpath scrapy
I want to extract from a web page information with xpath, but I'm getting the wrong information. In this code below I want to get 100 :

```<code><div class="pricing">
 <p class="pricePerUnit">
  <p class="pricePerMeasure">
  £0.64
  <abbr title="per">/</abbr>
  100
</code>```

I want to only get 100, I tried this but it returns £0.64 100.  But,  I just want to retrieve the 100 :

```<code>`prices_mesure3 = `response.xpath('//p[@class="pricePerMeasure"]/text()').extract()`
</code>```

Any help please ?

答:
You can try below XPath expression to get "100" only

```<code>//p[@class="pricePerMeasure"]/text()[last()]
</code>```

P.S. I suppose there are only 2 text nodes ("£0.64" and "100") and you just missed closing tags...

Title: extract only one part from xpath scrapy

Body:
I want to extract from a web page information with xpath, but I'm getting the wrong information. In this code below I want to get 100 :

  £0.64
  /
  100

I want to only get 100, I tried this but it returns £0.64 100.  But,  I just want to retrieve the 100 :

`prices_mesure3 = `response.xpath('//p[@class="pricePerMeasure"]/text()').extract()`

Any help please ?

Body:
You can try below XPath expression to get "100" only

//p[@class="pricePerMeasure"]/text()[last()]

P.S. I suppose there are only 2 text nodes ("£0.64" and "100") and you just missed closing tags...


问:
Git SVN clone with complex structure
I need to clone an SVN repository to git. The SVN repository is structured as if it's a repository of repositories, like so:

```<code>SVNRepo
|____ProjectA
|    |___branches
|    |___tags
|    |___trunk
|            file
|____ProjectB
|    |___branches
|    |___tags
|    |___trunk
             file
</code>```

I need to clone the repository so that I end up with a single git repository, without the svn specific folders (branches, tags, trunk). I originally dumped then split the SVN repo into separate repos for each project and migrated to git using git svn clone with the --stdlayout command. This worked but came with it's own issues that have been vetoed by our team.

I tried the git svn clone with the --stdlayout command but that doesn't work. I end up with an empty git repo with 2 commits (out of hundreds) and no actual files. There were no errors so I'm not sure what happened.

Trying git svn clone without the --stdlayout sort of works, in that I get a single git repo with all files and history. However, I still have all of the branches, tags and trunk folders which I've like to remove.

I've considered dumping the SVN repo and using sed to edit the binary but that seems like a lot of work. I imagine someone else has encountered this and solved the problem but can't find anything that works.

答: You can set up multiple trunk, branches and tags locations in git svn's configuration. If they are being created from the same parents, git-svn will figure it out. https://git-scm.com/docs/git-svn</p>

Title: Git SVN clone with complex structure

Body:
I need to clone an SVN repository to git. The SVN repository is structured as if it's a repository of repositories, like so:

SVNRepo
|____ProjectA
|    |___branches
|    |___tags
|    |___trunk
|            file
|____ProjectB
|    |___branches
|    |___tags
|    |___trunk
             file

I need to clone the repository so that I end up with a single git repository, without the svn specific folders (branches, tags, trunk). I originally dumped then split the SVN repo into separate repos for each project and migrated to git using git svn clone with the --stdlayout command. This worked but came with it's own issues that have been vetoed by our team.

I tried the git svn clone with the --stdlayout command but that doesn't work. I end up with an empty git repo with 2 commits (out of hundreds) and no actual files. There were no errors so I'm not sure what happened.

Trying git svn clone without the --stdlayout sort of works, in that I get a single git repo with all files and history. However, I still have all of the branches, tags and trunk folders which I've like to remove.

I've considered dumping the SVN repo and using sed to edit the binary but that seems like a lot of work. I imagine someone else has encountered this and solved the problem but can't find anything that works.