问:
Laravel scout search in relationships
I can't seem to figure out how to search in 2 tables within 1 query in Laravel scout. For specific reasons that are not important right now, I don't want to just run raw queries. Right now I have this to search:

My relationship:

```<code>namespace App;
use Laravel\Scout\Searchable;
class Users extends Model
{
    use Searchable;
   public function searchableAs(){
      return 'users_index';
   }
   public function toSearchableArray(){
      return $this->toArray();
   }
   public function originalUser(){
      return $this->belongsTo(OriginalUser::class);
   }
}
</code>```

And this is the controller:

```<code>use App\OriginalUser;
use App\Users;
use App\Groups;

class SomeController extends Controller{

   public function index(){
     $group = Group::where('group_id',1)->first();
     return Users::search('something')->where('group_id',$group->id)->get();
   }
}
</code>```

Now this returns the user that has 'something' in one of the columns, which is good like this:

```<code>   [
      {
        "id": "1",
        "original_user_id": "1",
        "username": "something"
        "original_user": {
          "id": "1",
          "username":"test"
        }
      }
    ]
</code>```

But I need my code to also return this record:

```<code>   [
      {
        "id": "2",
        "original_user_id": "2",
        "username": "nope"
        "original_user": {
          "id": "2",
          "username": "something"
        }
      }
    ]
</code>```

So when it matches in the relationship of the result, I want that record to be returned as well. I've tried to make the OriginalUser model searchable as well, but I'm just stuck at this point.

The documentation isn't clear enough for me to find out how to actually get the results where the relationship columns would match the search value as well. The only thing I've found that says anything about relationships in the model in the official documentation, is:

```<code>// You may also add records via relationships...
$user->orders()->searchable();
</code>```

I've tried this but it doesn't show me the other record.(Of course I changed orders to originalUser() in my code)

Does anyone know how to search in multiple models within 1 "search" with laravel scout?

EDIT:
I am not using Algolia, but mysql.

答:
Unfortunately, this doesn't seem to be possible using Scout and the MySQL driver at the moment.

Hunting around myself today for a solution to the exact same problem, I found some suggestions that adding relationships via the toSearchableArray method on the models you want to search might do it: https://laracasts.com/discuss/channels/laravel/scout-how-to-search-in-relations-and-counts?page=1#reply=329201

But this didn't work for me, as toSearchableArray handles placing potential search results in an index like Algolia, and the MySql driver doesn't do this. After a few hours, I found an issue from 2016 on the repo on the topic, which suggests they haven't got around to implementing this yet: https://github.com/yabhq/laravel-scout-mysql-driver/issues/5

Title: Laravel scout search in relationships

Body:
I can't seem to figure out how to search in 2 tables within 1 query in Laravel scout. For specific reasons that are not important right now, I don't want to just run raw queries. Right now I have this to search:

My relationship:

namespace App;
use Laravel\Scout\Searchable;
class Users extends Model
{
    use Searchable;
   public function searchableAs(){
      return 'users_index';
   }
   public function toSearchableArray(){
      return $this->toArray();
   }
   public function originalUser(){
      return $this->belongsTo(OriginalUser::class);
   }
}

And this is the controller:

use App\OriginalUser;
use App\Users;
use App\Groups;

class SomeController extends Controller{

   public function index(){
     $group = Group::where('group_id',1)->first();
     return Users::search('something')->where('group_id',$group->id)->get();
   }
}

Now this returns the user that has 'something' in one of the columns, which is good like this:

   [
      {
        "id": "1",
        "original_user_id": "1",
        "username": "something"
        "original_user": {
          "id": "1",
          "username":"test"
        }
      }
    ]

But I need my code to also return this record:

   [
      {
        "id": "2",
        "original_user_id": "2",
        "username": "nope"
        "original_user": {
          "id": "2",
          "username": "something"
        }
      }
    ]

So when it matches in the relationship of the result, I want that record to be returned as well. I've tried to make the OriginalUser model searchable as well, but I'm just stuck at this point.

The documentation isn't clear enough for me to find out how to actually get the results where the relationship columns would match the search value as well. The only thing I've found that says anything about relationships in the model in the official documentation, is:

// You may also add records via relationships...
$user->orders()->searchable();

I've tried this but it doesn't show me the other record.(Of course I changed orders to originalUser() in my code)

Does anyone know how to search in multiple models within 1 "search" with laravel scout?

EDIT:
I am not using Algolia, but mysql.


来源: stackexchange

问:
JAXB EclipseLink Moxy: cycle is detected in the object graph
I experience a strange behavior while marshalling an object graph with bi-directional relationships.

The error message is:

Exception [EclipseLink-25037] (Eclipse Persistence Services -
  2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.XMLMarshalException

Exception Description: A cycle is detected in the object graph.  This
  will cause an infinite loop:
  com.moxytest.Cycle$Doc@27f723 ->
  com.moxytest.Cycle$Pub@670b40af -> com.moxytest.Cycle$Agree@4923ab24
  -> com.moxytest.Cycle$Agen@44c8afef -> com.moxytest.Cycle$Acc@7b69c6ba ->
  com.moxytest.Cycle$Med@46daef40 ->
  com.moxytest.Cycle$Pag@12f41634 -> com.moxytest.Cycle$Doc@27f723

The object graph in the exception message seems not in the order of processing. Debugging XPathObjectBuilder shows that on the cycleDetectionStack the objects are pushed in the following order:

```<code>com.moxytest.Cycle$Doc
com.moxytest.Cycle$Pag
com.moxytest.Cycle$Med
com.moxytest.Cycle$Acc
com.moxytest.Cycle$Agen
com.moxytest.Cycle$Agree
com.moxytest.Cycle$Pub
</code>```

I do not understand why the exception is being thrown because I thought I would be fine with @XmlInverseReference. The problem only occurs with a more complex object graph. Here is the code:

```<code>import java.io.StringReader;
import java.io.StringWriter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.eclipse.persistence.jaxb.JAXBContext;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.oxm.MediaType;
import org.eclipse.persistence.oxm.annotations.XmlInverseReference;

public final class Cycle {

    private static JAXBContext JAXB_CONTEXT;

    static {
        try {
            JAXB_CONTEXT = (JAXBContext) JAXBContext.newInstance(Doc.class);
        } catch (JAXBException ex) {
            ex.printStackTrace();
        }
    }

    @XmlTransient
    @XmlAccessorType(XmlAccessType.PROPERTY)
    public static abstract class Entity {

        private String id;

        @XmlElement
        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

    }

    @XmlRootElement
    public static class Doc extends Entity {

        private Pag pag;

        private Pub pub;

        @XmlElement
        @XmlInverseReference(mappedBy = "doc")
        public Pag getPag() {
            return pag;
        }

        public void setPag(Pag pag) {
            this.pag = pag;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "docs")
        public Pub getPub() {
            return pub;
        }

        public void setPub(Pub pub) {
            this.pub = pub;
        }

    }

    @XmlRootElement
    public static class Acc extends Entity {

        private Agen agen;

        @XmlElement
        public Agen getAgen() {
            return agen;
        }

        public void setAgen(Agen agen) {
            this.agen = agen;
        }

    }

    @XmlRootElement
    public static class Med extends Entity {

        private Pag pag;

        private Acc acc;

        @XmlElement
        @XmlInverseReference(mappedBy = "meds")
        public Pag getPag() {
            return pag;
        }

        public void setPag(Pag pag) {
            this.pag = pag;
        }

        @XmlElement
        public Acc getAcc() {
            return acc;
        }

        public void setAcc(Acc acc) {
            this.acc = acc;
        }

    }

    @XmlRootElement
    public static class Pag extends Entity {

        private Doc doc;

        private List<Med> meds = new ArrayList<>();

        public void setDoc(Doc doc) {
            this.doc = doc;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pag")
        public Doc getDoc() {
            return doc;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pag")
        public List<Med> getMeds() {
            return meds;
        }

        public void setMeds(List<Med> meds) {
            this.meds = meds;
        }

    }

    @XmlRootElement
    public static class Pub extends Entity {

        private List<Doc> docs;

        private Agree agree;

        public List<Doc> getDocs() {
            return docs;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pub")
        public void setDocs(List<Doc> docs) {
            this.docs = docs;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pub")
        public Agree getAgree() {
            return agree;
        }

        public void setAgree(Agree agree) {
            this.agree = agree;
        }

    }

    @XmlRootElement
    public static class Agree extends Entity {

        private Pub pub;

        private Agen agen;

        @XmlElement
        @XmlInverseReference(mappedBy = "agree")
        public Pub getPub() {
            return pub;
        }

        public void setPub(Pub pub) {
            this.pub = pub;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "agrees")
        public Agen getAgen() {
            return agen;
        }

        public void setAgen(Agen agen) {
            this.agen = agen;
        }

    }

    @XmlRootElement
    public static class Agen extends Entity {

        private List<Agree> agrees;

        @XmlElement
        @XmlInverseReference(mappedBy = "agen")
        public List<Agree> getAgrees() {
            return agrees;
        }

        public void setAgrees(List<Agree> agrees) {
            this.agrees = agrees;
        }

    }

    public static void main(String[] args) throws JAXBException {
        Pag pag = new Pag();

        Med med = new Med();
        med.setPag(pag);
        pag.getMeds().add(med);

        Doc doc = new Doc();
        pag.setDoc(doc);
        doc.setPag(pag);

        Pub pub = new Pub();
        pub.setDocs(Arrays.asList(doc));
        doc.setPub(pub);

        Agree agree = new Agree();
        agree.setPub(pub);
        pub.setAgree(agree);

        Agen agen = new Agen();
        agen.setAgrees(Arrays.asList(agree));
        agree.setAgen(agen);

        Acc acc = new Acc();
        acc.setAgen(agen);
        med.setAcc(acc);

        String marshal = marshal(doc);
        System.err.println(marshal);
        Doc ud = unmarshal(Doc.class, marshal);
        String marshal2 = marshal(ud);
        System.err.println("\n\n" + marshal2);
        System.err.println("Equals? " + marshal.equals(marshal2));
    }

    public static String marshal(Object toMarshal) throws JAXBException {
        Marshaller marshaller = JAXB_CONTEXT.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
        StringWriter sw = new StringWriter();
        marshaller.marshal(toMarshal, sw);
        return sw.toString();
    }

    @SuppressWarnings("unchecked")
    public static <T> T unmarshal(Class<T> unmarshallingClass, String str) throws JAXBException {
        Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
//        unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML);
        unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
        return (T) unmarshaller.unmarshal(new StringReader(str));
    }

}
</code>```

If I remove @XMLElement at setDocs() in class Pub it works. But then I loose the docs objects when marshalling Pub.

Can you help?

=============== UPDATE

EclipseLink's implementation of XMLInverseReference does not take transitive cycles into account. During marshalling it creates a cycleDetectionStack where it puts all marshalled objects. If it encounters XMLInverseReference it tries to find the owner by getting the object from the cycleDetectionStack - 2. This works for direct cycles between objects but not for transitive cycles like A --> B --> C --> A.

Looking into the source code I found a trivial way to make it work for transitive cycles. All I had to do was iterating over the complete cycleDetectionStack:

XMLCompositeCollectionMappingNodeValue:

```<code>if ((isInverseReference || xmlCompositeCollectionMapping.getInverseReferenceMapping() != null) && size >= 2) {
    //Object owner = marshalRecord.getCycleDetectionStack().get(size - 2);
    // Bugfix InverseRef has no effect on "transitive" references within object graph
    CycleDetectionStack cycleDetectionStack = marshalRecord.getCycleDetectionStack();
    for (Object stackedObj : cycleDetectionStack) {
        try {
            if (cp.contains(stackedObj, collection, session)) {
                return false;
            }
        } catch (ClassCastException e) {
            // For Bug #416875
        }
    }
}
</code>```

The second class was XMLCompositeObjectMappingNodeValue with the exact same solution:

```<code>if ((isInverseReference || xmlCompositeObjectMapping.getInverseReferenceMapping() != null) && objectValue != null && size >= 2) {
    //Object owner = marshalRecord.getCycleDetectionStack().get(size - 2);
    // Bugfix InverseRef has no effect on "transitive" references within object graph
    CycleDetectionStack cycleDetectionStack = marshalRecord.getCycleDetectionStack();
    for (Object stackedObj : cycleDetectionStack) {
        if (objectValue.equals(stackedObj)) {
            return false;
        }
    }
}
</code>```

Maybe the developer had good reasons for just looking at the owner. As for me I could not find out why I should live with this shortcoming. We have a large domain model where all entities are transcoded via json. We have not got any error since.

答:
In a JPA model layer, it is not very uncommon to have cyclic references and foreign key references that may turn a JSON serialisation into cyclic structure. This is called JSOG, where you have cycles in your JSON structure and EclipseLinks's default Moxy Json Provider is unable to serialize such POJOs.

You need Jackson Json Provider rather than modifying your model Pojo classes.

I assume you are using JaxRs REST api trying to serialize the Pojos. In that case you can use Jackson packages from maven quite easily. Simply create the providers for the jaxb provider and object mapper. More details can be found here:

https://stackoverflow.com/a/60319306/5076414

You need JSOG library along with the providers: https://github.com/jsog/jsog-jackson

ContentLicense: CC BY-SA 3.0

Body:
I experience a strange behavior while marshalling an object graph with bi-directional relationships.

The error message is:

Exception [EclipseLink-25037] (Eclipse Persistence Services -
  2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.XMLMarshalException

Exception Description: A cycle is detected in the object graph.  This
  will cause an infinite loop:
  com.moxytest.Cycle$Doc@27f723 ->
  com.moxytest.Cycle$Pub@670b40af -> com.moxytest.Cycle$Agree@4923ab24
  -> com.moxytest.Cycle$Agen@44c8afef -> com.moxytest.Cycle$Acc@7b69c6ba ->
  com.moxytest.Cycle$Med@46daef40 ->
  com.moxytest.Cycle$Pag@12f41634 -> com.moxytest.Cycle$Doc@27f723

The object graph in the exception message seems not in the order of processing. Debugging XPathObjectBuilder shows that on the cycleDetectionStack the objects are pushed in the following order:

com.moxytest.Cycle$Doc
com.moxytest.Cycle$Pag
com.moxytest.Cycle$Med
com.moxytest.Cycle$Acc
com.moxytest.Cycle$Agen
com.moxytest.Cycle$Agree
com.moxytest.Cycle$Pub

I do not understand why the exception is being thrown because I thought I would be fine with @XmlInverseReference. The problem only occurs with a more complex object graph. Here is the code:

import java.io.StringReader;
import java.io.StringWriter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.eclipse.persistence.jaxb.JAXBContext;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.oxm.MediaType;
import org.eclipse.persistence.oxm.annotations.XmlInverseReference;

public final class Cycle {

    private static JAXBContext JAXB_CONTEXT;

    static {
        try {
            JAXB_CONTEXT = (JAXBContext) JAXBContext.newInstance(Doc.class);
        } catch (JAXBException ex) {
            ex.printStackTrace();
        }
    }

    @XmlTransient
    @XmlAccessorType(XmlAccessType.PROPERTY)
    public static abstract class Entity {

        private String id;

        @XmlElement
        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

    }

    @XmlRootElement
    public static class Doc extends Entity {

        private Pag pag;

        private Pub pub;

        @XmlElement
        @XmlInverseReference(mappedBy = "doc")
        public Pag getPag() {
            return pag;
        }

        public void setPag(Pag pag) {
            this.pag = pag;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "docs")
        public Pub getPub() {
            return pub;
        }

        public void setPub(Pub pub) {
            this.pub = pub;
        }

    }

    @XmlRootElement
    public static class Acc extends Entity {

        private Agen agen;

        @XmlElement
        public Agen getAgen() {
            return agen;
        }

        public void setAgen(Agen agen) {
            this.agen = agen;
        }

    }

    @XmlRootElement
    public static class Med extends Entity {

        private Pag pag;

        private Acc acc;

        @XmlElement
        @XmlInverseReference(mappedBy = "meds")
        public Pag getPag() {
            return pag;
        }

        public void setPag(Pag pag) {
            this.pag = pag;
        }

        @XmlElement
        public Acc getAcc() {
            return acc;
        }

        public void setAcc(Acc acc) {
            this.acc = acc;
        }

    }

    @XmlRootElement
    public static class Pag extends Entity {

        private Doc doc;

        private List<Med> meds = new ArrayList<>();

        public void setDoc(Doc doc) {
            this.doc = doc;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pag")
        public Doc getDoc() {
            return doc;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pag")
        public List<Med> getMeds() {
            return meds;
        }

        public void setMeds(List<Med> meds) {
            this.meds = meds;
        }

    }

    @XmlRootElement
    public static class Pub extends Entity {

        private List<Doc> docs;

        private Agree agree;

        public List<Doc> getDocs() {
            return docs;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pub")
        public void setDocs(List<Doc> docs) {
            this.docs = docs;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pub")
        public Agree getAgree() {
            return agree;
        }

        public void setAgree(Agree agree) {
            this.agree = agree;
        }

    }

    @XmlRootElement
    public static class Agree extends Entity {

        private Pub pub;

        private Agen agen;

        @XmlElement
        @XmlInverseReference(mappedBy = "agree")
        public Pub getPub() {
            return pub;
        }

        public void setPub(Pub pub) {
            this.pub = pub;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "agrees")
        public Agen getAgen() {
            return agen;
        }

        public void setAgen(Agen agen) {
            this.agen = agen;
        }

    }

    @XmlRootElement
    public static class Agen extends Entity {

        private List<Agree> agrees;

        @XmlElement
        @XmlInverseReference(mappedBy = "agen")
        public List<Agree> getAgrees() {
            return agrees;
        }

        public void setAgrees(List<Agree> agrees) {
            this.agrees = agrees;
        }

    }

    public static void main(String[] args) throws JAXBException {
        Pag pag = new Pag();

        Med med = new Med();
        med.setPag(pag);
        pag.getMeds().add(med);

        Doc doc = new Doc();
        pag.setDoc(doc);
        doc.setPag(pag);

        Pub pub = new Pub();
        pub.setDocs(Arrays.asList(doc));
        doc.setPub(pub);

        Agree agree = new Agree();
        agree.setPub(pub);
        pub.setAgree(agree);

        Agen agen = new Agen();
        agen.setAgrees(Arrays.asList(agree));
        agree.setAgen(agen);

        Acc acc = new Acc();
        acc.setAgen(agen);
        med.setAcc(acc);

        String marshal = marshal(doc);
        System.err.println(marshal);
        Doc ud = unmarshal(Doc.class, marshal);
        String marshal2 = marshal(ud);
        System.err.println("\n\n" + marshal2);
        System.err.println("Equals? " + marshal.equals(marshal2));
    }

    public static String marshal(Object toMarshal) throws JAXBException {
        Marshaller marshaller = JAXB_CONTEXT.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
        StringWriter sw = new StringWriter();
        marshaller.marshal(toMarshal, sw);
        return sw.toString();
    }

    @SuppressWarnings("unchecked")
    public static <T> T unmarshal(Class<T> unmarshallingClass, String str) throws JAXBException {
        Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
//        unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML);
        unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
        return (T) unmarshaller.unmarshal(new StringReader(str));
    }

}

If I remove @XMLElement at setDocs() in class Pub it works. But then I loose the docs objects when marshalling Pub.

Can you help?

=============== UPDATE

EclipseLink's implementation of XMLInverseReference does not take transitive cycles into account. During marshalling it creates a cycleDetectionStack where it puts all marshalled objects. If it encounters XMLInverseReference it tries to find the owner by getting the object from the cycleDetectionStack - 2. This works for direct cycles between objects but not for transitive cycles like A --> B --> C --> A.

Looking into the source code I found a trivial way to make it work for transitive cycles. All I had to do was iterating over the complete cycleDetectionStack:

XMLCompositeCollectionMappingNodeValue:

if ((isInverseReference || xmlCompositeCollectionMapping.getInverseReferenceMapping() != null) && size >= 2) {
    //Object owner = marshalRecord.getCycleDetectionStack().get(size - 2);
    // Bugfix InverseRef has no effect on "transitive" references within object graph
    CycleDetectionStack cycleDetectionStack = marshalRecord.getCycleDetectionStack();
    for (Object stackedObj : cycleDetectionStack) {
        try {
            if (cp.contains(stackedObj, collection, session)) {
                return false;
            }
        } catch (ClassCastException e) {
            // For Bug #416875
        }
    }
}

The second class was XMLCompositeObjectMappingNodeValue with the exact same solution:

if ((isInverseReference || xmlCompositeObjectMapping.getInverseReferenceMapping() != null) && objectValue != null && size >= 2) {
    //Object owner = marshalRecord.getCycleDetectionStack().get(size - 2);
    // Bugfix InverseRef has no effect on "transitive" references within object graph
    CycleDetectionStack cycleDetectionStack = marshalRecord.getCycleDetectionStack();
    for (Object stackedObj : cycleDetectionStack) {
        if (objectValue.equals(stackedObj)) {
            return false;
        }
    }
}

Maybe the developer had good reasons for just looking at the owner. As for me I could not find out why I should live with this shortcoming. We have a large domain model where all entities are transcoded via json. We have not got any error since.

ContentLicense: CC BY-SA 4.0


问:
How could we use a formula in query Google sheet
I am unable to figure out how could we use formula within query results. I did not find any solution yet.

Like:

```<code>=query(sheet1!A1:Z,"Select A,B,Vlookup(D,sheet1!A1:A,1,false)");
</code>```

答:
you can't. you need to do:

```<code>=ARRAYFORMULA({sheet1!A:B, IFNA(VLOOKUP(D:D, sheet1!A:A, 1, 0))})
</code>```

and then you can play with query:

```<code>=ARRAYFORMULA(QUERY({sheet1!A:B, IFNA(VLOOKUP(D:D, sheet1!A:A, 1, 0))}, "select Col1,Col2,Col3", 0)
</code>```

Body:
I am unable to figure out how could we use formula within query results. I did not find any solution yet.

Like:

=query(sheet1!A1:Z,"Select A,B,Vlookup(D,sheet1!A1:A,1,false)");

Body:
you can't. you need to do:

=ARRAYFORMULA({sheet1!A:B, IFNA(VLOOKUP(D:D, sheet1!A:A, 1, 0))})

and then you can play with query:

=ARRAYFORMULA(QUERY({sheet1!A:B, IFNA(VLOOKUP(D:D, sheet1!A:A, 1, 0))}, "select Col1,Col2,Col3", 0)


问:
How to initialize a const std vector in old c++?
My C++ compiler identification is GNU 4.4.1

I think since c++ 11 you can initialize a vector this way:

```<code>const std::vector<int> myVector = {1, 2, 3};
const std::vector<int> myVector2{1, 2, 3};
</code>```

Unfortunately, I am not using c++ 11 so myVector can just be initilized by constructor.
I need to create a vector that will never be modified. It has to be shared by differents functions within a class so it may be static as well, or even a class member.
Is there a way to make my vector be initiliazed when it gets defined in c++98, as the examples from above, or something equivalent?

答:
You can return the vector from a function:

```<code>std::vector<int> f();
const std::vector<int> myVector = f();
</code>```

Alternatively, use boost::assign::list_of.

Body:
My C++ compiler identification is GNU 4.4.1

I think since c++ 11 you can initialize a vector this way:

const std::vector<int> myVector = {1, 2, 3};
const std::vector<int> myVector2{1, 2, 3};

Unfortunately, I am not using c++ 11 so myVector can just be initilized by constructor.
I need to create a vector that will never be modified. It has to be shared by differents functions within a class so it may be static as well, or even a class member.
Is there a way to make my vector be initiliazed when it gets defined in c++98, as the examples from above, or something equivalent?

Body:
You can return the vector from a function:

std::vector<int> f();
const std::vector<int> myVector = f();

Alternatively, use boost::assign::list_of.


问:
How would I remove non-duplicates from a CSV file in Python?
I have a CSV file with the following format:

```<code>User1, User2
1,2
1,3
2,1
</code>```

I am trying to remove the non-duplicated reverse values, so in this instance I would like to remove 1,3 as it doesn't have a reverse duplicate of 3,1

I currently have this script which removes the duplicate values:

```<code>import csv

reader=csv.reader(open('facebook-friendships.csv', 'r'), delimiter=',')
writer=csv.writer(open('facebook-friendships-write.csv', 'w'), delimiter=',')

entries = set()

for row in reader:
   key = (row[0], row[1])
   key = tuple(key)
   if key in entries and key[::-1] in entries:
       writer.writerow(row)
       entries.add(key)
</code>```

How would I edit this script to remove the non-duplicated reverse values? So that I am only left with

```<code>1,2
2,1
</code>```

Thanks

答:
```<code>reader = [
    [1, 2],
    [1, 3],
    [2, 1],
    [4, 5],
    [5, 4],
    ]

entries_dict = {}

for row in reader:
    sorted_row = tuple(sorted(row))
    if sorted_row not in entries_dict:
        entries_dict[sorted_row] = [row]
    else:
        entries_dict[sorted_row] += [row]

for duplic_rows in [rows_item for rows_item in entries_dict.values() if len(rows_item) > 1]:
    for row in duplic_rows:
        print(row) # writer.writerow(row)
</code>```

Or you can use groupby:

```<code>from itertools import groupby

reader = [
    [1, 2],
    [1, 3],
    [2, 1],
    [4, 5],
    [5, 4],
    ]

def get_key_from_row(row):
    return tuple(sorted(row))

sorted_rows = sorted(reader, key=get_key_from_row)
grouped_rows = [list(it) for k, it in groupby(sorted_rows, get_key_from_row)]

for duplic_rows in [rows for rows in grouped_rows if len(rows) > 1]:
    for row in duplic_rows:
        print(row) # writer.writerow(row)
</code>```

Body:
I have a CSV file with the following format:

User1, User2
1,2
1,3
2,1

I am trying to remove the non-duplicated reverse values, so in this instance I would like to remove 1,3 as it doesn't have a reverse duplicate of 3,1

I currently have this script which removes the duplicate values:

import csv

reader=csv.reader(open('facebook-friendships.csv', 'r'), delimiter=',')
writer=csv.writer(open('facebook-friendships-write.csv', 'w'), delimiter=',')

entries = set()

for row in reader:
   key = (row[0], row[1])
   key = tuple(key)
   if key in entries and key[::-1] in entries:
       writer.writerow(row)
       entries.add(key)

How would I edit this script to remove the non-duplicated reverse values? So that I am only left with

1,2
2,1

Thanks

Body:
reader = [
    [1, 2],
    [1, 3],
    [2, 1],
    [4, 5],
    [5, 4],
    ]

entries_dict = {}

for row in reader:
    sorted_row = tuple(sorted(row))
    if sorted_row not in entries_dict:
        entries_dict[sorted_row] = [row]
    else:
        entries_dict[sorted_row] += [row]

for duplic_rows in [rows_item for rows_item in entries_dict.values() if len(rows_item) > 1]:
    for row in duplic_rows:
        print(row) # writer.writerow(row)

Or you can use groupby:

from itertools import groupby

reader = [
    [1, 2],
    [1, 3],
    [2, 1],
    [4, 5],
    [5, 4],
    ]

def get_key_from_row(row):
    return tuple(sorted(row))

sorted_rows = sorted(reader, key=get_key_from_row)
grouped_rows = [list(it) for k, it in groupby(sorted_rows, get_key_from_row)]

for duplic_rows in [rows for rows in grouped_rows if len(rows) > 1]:
    for row in duplic_rows:
        print(row) # writer.writerow(row)


问:
Entity framework ASP.NET MVC (sometimes) problems with DbContext.Set and elsewhere
I've got a weird problem using ASP.NET in combination with Entity Framework and Unity Container.

This problem only occurs after the application has been running from a few hours to a few days. And after this happens it's temporally fixed (again for the same period) by restarting IIS.

Sometimes the problem gives an exception on trying to inject (using unity-container) a Controller.

Example:

```<code>public class PersonController
{
     private readonly ICrudService<Person> personCrudservice;

     public PersonController(ICrudService<Person> personCrudservice)
     {
         this.personCrudservice = personCrudservice;
     }
}
</code>```

The exception here is: An error occurred when trying to create a controller of type 'PersonController'. Make sure that the controller has a parameterless public constructor.

Of course the controller doesn't have a parameterless constructor, but using unity-container the personCrudservice is injected.  However, this doesn't happen since the dbContext.Set<Person>() method gives the following exception: An item with the same key has already been added. which leads to the exception shown above.

Another example is an exception when trying to load data from the database. Which gives a NullReference exception.  (Again, not all of the time and the data exists in the database)

Can you guys help me tackle the issue?

DataContext.cs:

```<code>public class DataContext : IUnitOfWork, IRepositoryFactory, ICrudServiceFactory
{
    private const string CONNECTIONSTRING = "Constring";
    private static readonly MedicijnverstrekkingDbContext dbContext = new MedicijnverstrekkingDbContext(CONNECTIONSTRING);
    public DbContext DbContext => dbContext;

    public static volatile Dictionary<string, object> repositories = new Dictionary<string, object>();

    public DataContext()
    {
        dbContext.Configuration.EnsureTransactionsForFunctionsAndCommands = false;
    }

    public void SaveChanges()
    {
        dbContext.SaveChanges();
    }

    public void Dispose()
    {
        dbContext.Dispose();
    }

    public IRepository<T> CreateRepositoryFor<T>() where T : class, IEntity
    {
        var naam = typeof(T).FullName;
        var repos = default(IRepository<T>);

        if(repositories.ContainsKey(naam))
        {
            repos = repositories[naam] as IRepository<T>;
        }
        if(repos == null)
        {
            repos = new Repository<T>(dbContext.Set<T>());

            repositories[naam] = repos;
        }
        return repos;
    }

    ICrudService<T> ICrudServiceFactory.GenerateCrudServiceFor<T>(IUnityContainer unityContainer)
    {
        var icrudServiceType = typeof(ICrudService<T>);

        var tService = icrudServiceType.Assembly.GetTypes().Where(t => icrudServiceType.IsAssignableFrom(t)).FirstOrDefault();

        //If predefined crud service exists, create an instance, otherwise create a generic crud service.
        if (tService != null)
        {
            return (ICrudService<T>)Activator.CreateInstance(tService, new object[] { unityContainer.Resolve<IUnitOfWork>(), unityContainer.Resolve<IRepository<T>>() });
        }
        else
        {
            return new GenericCrudService<T>(unityContainer.Resolve<IUnitOfWork>(), unityContainer.Resolve<IRepository<T>>());
        }
    }
}
</code>```

UnityConfig.cs

```<code>public class UnityConfig
{
    private static readonly Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    public static IUnityContainer Container => container.Value;

    public static void RegisterTypes(IUnityContainer container)
    {
        RegisterDependencies(container);

        System.Web.Mvc.DependencyResolver.SetResolver(new UnityDependencyResolverAdapter(container));
        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }

    private static void RegisterDependencies(IUnityContainer unityContainer)
    {
        RegisterDataContextAndUnitOfWork(unityContainer);
        RegisterRepositories(unityContainer);
        RegisterAuthenticationDependencies(unityContainer);
    }

    private static void RegisterDataContextAndUnitOfWork(IUnityContainer container)
    {
        container.RegisterType<IUnitOfWork, DataContext>(HttpContextLifetimeManager.FromType<DataContext>());
        container.RegisterType<IRepositoryFactory, DataContext>(HttpContextLifetimeManager.FromType<DataContext>());
        container.RegisterType<ICrudServiceFactory, DataContext>(HttpContextLifetimeManager.FromType<DataContext>());

    }

    private static void RegisterAuthenticationDependencies(IUnityContainer container)
    {
        container.RegisterType<IUserStore<GebruikerModel>, UserStore>(HttpContextLifetimeManager.FromType<UserStore>());
        container.RegisterType<IRoleStore<RoleModel, string>, RoleStore>(HttpContextLifetimeManager.FromType<RoleStore>());

        container.RegisterFactory<UserManager<GebruikerModel>>(unityContainer =>
        {
            var userStore = unityContainer.Resolve<IUserStore<GebruikerModel>>();
            var manager = new UserManager<GebruikerModel>(userStore)
            {
                PasswordHasher = new BcryptPasswordHasher()
            };
            manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<GebruikerModel>
            {
                MessageFormat = "Uw inlogcode is {0}."
            });
            manager.SmsService = new SmsService();
            return manager;
        });

        container.RegisterType<ICurrentUserProvider, CurrentHttpUserProvider>();
    }

    private static void RegisterRepositories(IUnityContainer container)
    {
        var registerRepositoryMethodName = MemberNameHelper.GetActionName(() => RegisterRepository<IEntity>(container));
        var registerCrudserviceName = MemberNameHelper.GetActionName(() => RegisterCrudService<IEntity>(container));
        var registerRepositoryMethodInfo = typeof(UnityConfig).GetMethod(registerRepositoryMethodName, BindingFlags.NonPublic | BindingFlags.Static);
        var registerCrudserviceMethodInfo = typeof(UnityConfig).GetMethod(registerCrudserviceName, BindingFlags.NonPublic | BindingFlags.Static);

        foreach (var entityType in typeof(IEntity).Assembly.GetTypes().Where(t => typeof(IEntity).IsAssignableFrom(t)))
        {
            var registerRepositoryMethod = registerRepositoryMethodInfo.MakeGenericMethod(entityType);
            registerRepositoryMethod.Invoke(null, new object[] { container });

            var registerCrudserviceMethod = registerCrudserviceMethodInfo.MakeGenericMethod(entityType);
            registerCrudserviceMethod.Invoke(null, new object[] { container });
        }
    }

    private static void RegisterRepository<T>(IUnityContainer unityContainer) where T : class, IEntity
    {
        unityContainer.RegisterFactory<IRepository<T>>(
            factory => factory.Resolve<IRepositoryFactory>().CreateRepositoryFor<T>(),
            HttpContextFactoryLifetimeManager.ForRepository<T>()
        );
    }

    private static void RegisterCrudService<T>(IUnityContainer unityContainer) where T : class, IEntity
    {
        unityContainer.RegisterFactory<ICrudService<T>>(
            factory => factory.Resolve<ICrudServiceFactory>().GenerateCrudServiceFor<T>(factory),
            HttpContextFactoryLifetimeManager.ForCrudService<T>()
            );
    }
}
</code>```

I've been having this problem for weeks now and trying different LifeTimeManagers and also downgrading Unity-Container / Entity Framework didn't help.

Stacktrace: An item with the same key has already been added.

```<code>   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Data.Entity.Internal.InternalContext.Set[TEntity]()
   at System.Data.Entity.DbContext.Set[TEntity]()
   at Multitask.COMPANYNAME.DataAccess.EntityFramework.DataContext.CreateRepositoryFor[T]() in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\DataAccess\DataContext.cs:line 50
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Multitask.COMPANYNAME.WebApplication.Unity.HttpContextFactoryLifetimeManager.GetValue(ILifetimeContainer container) in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\WebApplication\Unity\HttpContextFactoryLifetimeManager.cs:line 60
   at Unity.Strategies.LifetimeStrategy.PreBuildUp(BuilderContext& context)
   at Unity.UnityContainer.<>c.<.ctor>b__73_1(BuilderContext& context)
   at Unity.UnityContainer.Unity.IUnityContainer.Resolve(Type type, String name, ResolverOverride[] overrides)
   at Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
   at Multitask.COMPANYNAME.DataAccess.EntityFramework.DataContext.Multitask.COMPANYNAME.Service.DataAccess.ICrudServiceFactory.GenerateCrudServiceFor[T](IUnityContainer unityContainer) in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\DataAccess\DataContext.cs:line 131
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Multitask.COMPANYNAME.WebApplication.Unity.HttpContextFactoryLifetimeManager.GetValue(ILifetimeContainer container) in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\WebApplication\Unity\HttpContextFactoryLifetimeManager.cs:line 70
   at Unity.Strategies.LifetimeStrategy.PreBuildUp(BuilderContext& context)
   at Unity.UnityContainer.<>c.<.ctor>b__73_2(BuilderStrategy[] chain, BuilderContext& context)
   at Unity.Builder.BuilderContext.Resolve(Type type, String name, InternalRegistration registration)
   at Unity.Builder.BuilderContext.Resolve(Type type, String name)
   at Unity.Builder.BuilderContext.Resolve(ParameterInfo parameter, Object value)
   at Unity.Processors.ConstructorProcessor.<>c__DisplayClass16_0.<GetResolverDelegate>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Strategies.BuildPlanStrategy.PreBuildUp(BuilderContext& context)
   at Unity.UnityContainer.<>c.<.ctor>b__73_2(BuilderStrategy[] chain, BuilderContext& context)
   at Unity.Builder.BuilderContext.Resolve(Type type, String name, InternalRegistration registration)
   at Unity.Builder.BuilderContext.Resolve(Type type, String name)
   at Unity.Builder.BuilderContext.Resolve(ParameterInfo parameter, Object value)
   at Unity.Processors.ConstructorProcessor.<>c__DisplayClass16_0.<GetResolverDelegate>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Strategies.BuildPlanStrategy.PreBuildUp(BuilderContext& context)
   at Unity.UnityContainer.<>c.<.ctor>b__73_1(BuilderContext& context)
   at Unity.UnityContainer.Unity.IUnityContainer.Resolve(Type type, String name, ResolverOverride[] overrides)
   at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType)
   --- End of inner exception stack trace ---
   at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType)
   at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)````
```

答:
Add an Empty constructor like;</p>

```<code>public PersonController() {};
//before

public PersonController(ICrudService<Person> personCrudservice)
{
  this.personCrudservice = personCrudservice;
};
</code>```

Body:
I've got a weird problem using ASP.NET in combination with Entity Framework and Unity Container.

This problem only occurs after the application has been running from a few hours to a few days. And after this happens it's temporally fixed (again for the same period) by restarting IIS.

Sometimes the problem gives an exception on trying to inject (using unity-container) a Controller.

Example:

public class PersonController
{
     private readonly ICrudService<Person> personCrudservice;

     public PersonController(ICrudService<Person> personCrudservice)
     {
         this.personCrudservice = personCrudservice;
     }
}

The exception here is: An error occurred when trying to create a controller of type 'PersonController'. Make sure that the controller has a parameterless public constructor.

Of course the controller doesn't have a parameterless constructor, but using unity-container the personCrudservice is injected.  However, this doesn't happen since the dbContext.Set<Person>() method gives the following exception: An item with the same key has already been added. which leads to the exception shown above.

Another example is an exception when trying to load data from the database. Which gives a NullReference exception.  (Again, not all of the time and the data exists in the database)

Can you guys help me tackle the issue?

DataContext.cs:

public class DataContext : IUnitOfWork, IRepositoryFactory, ICrudServiceFactory
{
    private const string CONNECTIONSTRING = "Constring";
    private static readonly MedicijnverstrekkingDbContext dbContext = new MedicijnverstrekkingDbContext(CONNECTIONSTRING);
    public DbContext DbContext => dbContext;

    public static volatile Dictionary<string, object> repositories = new Dictionary<string, object>();

    public DataContext()
    {
        dbContext.Configuration.EnsureTransactionsForFunctionsAndCommands = false;
    }

    public void SaveChanges()
    {
        dbContext.SaveChanges();
    }

    public void Dispose()
    {
        dbContext.Dispose();
    }

    public IRepository<T> CreateRepositoryFor<T>() where T : class, IEntity
    {
        var naam = typeof(T).FullName;
        var repos = default(IRepository<T>);

        if(repositories.ContainsKey(naam))
        {
            repos = repositories[naam] as IRepository<T>;
        }
        if(repos == null)
        {
            repos = new Repository<T>(dbContext.Set<T>());

            repositories[naam] = repos;
        }
        return repos;
    }

    ICrudService<T> ICrudServiceFactory.GenerateCrudServiceFor<T>(IUnityContainer unityContainer)
    {
        var icrudServiceType = typeof(ICrudService<T>);

        var tService = icrudServiceType.Assembly.GetTypes().Where(t => icrudServiceType.IsAssignableFrom(t)).FirstOrDefault();

        //If predefined crud service exists, create an instance, otherwise create a generic crud service.
        if (tService != null)
        {
            return (ICrudService<T>)Activator.CreateInstance(tService, new object[] { unityContainer.Resolve<IUnitOfWork>(), unityContainer.Resolve<IRepository<T>>() });
        }
        else
        {
            return new GenericCrudService<T>(unityContainer.Resolve<IUnitOfWork>(), unityContainer.Resolve<IRepository<T>>());
        }
    }
}

UnityConfig.cs

public class UnityConfig
{
    private static readonly Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    public static IUnityContainer Container => container.Value;

    public static void RegisterTypes(IUnityContainer container)
    {
        RegisterDependencies(container);

        System.Web.Mvc.DependencyResolver.SetResolver(new UnityDependencyResolverAdapter(container));
        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }

    private static void RegisterDependencies(IUnityContainer unityContainer)
    {
        RegisterDataContextAndUnitOfWork(unityContainer);
        RegisterRepositories(unityContainer);
        RegisterAuthenticationDependencies(unityContainer);
    }

    private static void RegisterDataContextAndUnitOfWork(IUnityContainer container)
    {
        container.RegisterType<IUnitOfWork, DataContext>(HttpContextLifetimeManager.FromType<DataContext>());
        container.RegisterType<IRepositoryFactory, DataContext>(HttpContextLifetimeManager.FromType<DataContext>());
        container.RegisterType<ICrudServiceFactory, DataContext>(HttpContextLifetimeManager.FromType<DataContext>());

    }

    private static void RegisterAuthenticationDependencies(IUnityContainer container)
    {
        container.RegisterType<IUserStore<GebruikerModel>, UserStore>(HttpContextLifetimeManager.FromType<UserStore>());
        container.RegisterType<IRoleStore<RoleModel, string>, RoleStore>(HttpContextLifetimeManager.FromType<RoleStore>());

        container.RegisterFactory<UserManager<GebruikerModel>>(unityContainer =>
        {
            var userStore = unityContainer.Resolve<IUserStore<GebruikerModel>>();
            var manager = new UserManager<GebruikerModel>(userStore)
            {
                PasswordHasher = new BcryptPasswordHasher()
            };
            manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<GebruikerModel>
            {
                MessageFormat = "Uw inlogcode is {0}."
            });
            manager.SmsService = new SmsService();
            return manager;
        });

        container.RegisterType<ICurrentUserProvider, CurrentHttpUserProvider>();
    }

    private static void RegisterRepositories(IUnityContainer container)
    {
        var registerRepositoryMethodName = MemberNameHelper.GetActionName(() => RegisterRepository<IEntity>(container));
        var registerCrudserviceName = MemberNameHelper.GetActionName(() => RegisterCrudService<IEntity>(container));
        var registerRepositoryMethodInfo = typeof(UnityConfig).GetMethod(registerRepositoryMethodName, BindingFlags.NonPublic | BindingFlags.Static);
        var registerCrudserviceMethodInfo = typeof(UnityConfig).GetMethod(registerCrudserviceName, BindingFlags.NonPublic | BindingFlags.Static);

        foreach (var entityType in typeof(IEntity).Assembly.GetTypes().Where(t => typeof(IEntity).IsAssignableFrom(t)))
        {
            var registerRepositoryMethod = registerRepositoryMethodInfo.MakeGenericMethod(entityType);
            registerRepositoryMethod.Invoke(null, new object[] { container });

            var registerCrudserviceMethod = registerCrudserviceMethodInfo.MakeGenericMethod(entityType);
            registerCrudserviceMethod.Invoke(null, new object[] { container });
        }
    }

    private static void RegisterRepository<T>(IUnityContainer unityContainer) where T : class, IEntity
    {
        unityContainer.RegisterFactory<IRepository<T>>(
            factory => factory.Resolve<IRepositoryFactory>().CreateRepositoryFor<T>(),
            HttpContextFactoryLifetimeManager.ForRepository<T>()
        );
    }

    private static void RegisterCrudService<T>(IUnityContainer unityContainer) where T : class, IEntity
    {
        unityContainer.RegisterFactory<ICrudService<T>>(
            factory => factory.Resolve<ICrudServiceFactory>().GenerateCrudServiceFor<T>(factory),
            HttpContextFactoryLifetimeManager.ForCrudService<T>()
            );
    }
}

I've been having this problem for weeks now and trying different LifeTimeManagers and also downgrading Unity-Container / Entity Framework didn't help.

Stacktrace: An item with the same key has already been added.

   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Data.Entity.Internal.InternalContext.Set[TEntity]()
   at System.Data.Entity.DbContext.Set[TEntity]()
   at Multitask.COMPANYNAME.DataAccess.EntityFramework.DataContext.CreateRepositoryFor[T]() in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\DataAccess\DataContext.cs:line 50
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Multitask.COMPANYNAME.WebApplication.Unity.HttpContextFactoryLifetimeManager.GetValue(ILifetimeContainer container) in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\WebApplication\Unity\HttpContextFactoryLifetimeManager.cs:line 60
   at Unity.Strategies.LifetimeStrategy.PreBuildUp(BuilderContext& context)
   at Unity.UnityContainer.<>c.<.ctor>b__73_1(BuilderContext& context)
   at Unity.UnityContainer.Unity.IUnityContainer.Resolve(Type type, String name, ResolverOverride[] overrides)
   at Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
   at Multitask.COMPANYNAME.DataAccess.EntityFramework.DataContext.Multitask.COMPANYNAME.Service.DataAccess.ICrudServiceFactory.GenerateCrudServiceFor[T](IUnityContainer unityContainer) in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\DataAccess\DataContext.cs:line 131
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Multitask.COMPANYNAME.WebApplication.Unity.HttpContextFactoryLifetimeManager.GetValue(ILifetimeContainer container) in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\WebApplication\Unity\HttpContextFactoryLifetimeManager.cs:line 70
   at Unity.Strategies.LifetimeStrategy.PreBuildUp(BuilderContext& context)
   at Unity.UnityContainer.<>c.<.ctor>b__73_2(BuilderStrategy[] chain, BuilderContext& context)
   at Unity.Builder.BuilderContext.Resolve(Type type, String name, InternalRegistration registration)
   at Unity.Builder.BuilderContext.Resolve(Type type, String name)
   at Unity.Builder.BuilderContext.Resolve(ParameterInfo parameter, Object value)
   at Unity.Processors.ConstructorProcessor.<>c__DisplayClass16_0.<GetResolverDelegate>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Strategies.BuildPlanStrategy.PreBuildUp(BuilderContext& context)
   at Unity.UnityContainer.<>c.<.ctor>b__73_2(BuilderStrategy[] chain, BuilderContext& context)
   at Unity.Builder.BuilderContext.Resolve(Type type, String name, InternalRegistration registration)
   at Unity.Builder.BuilderContext.Resolve(Type type, String name)
   at Unity.Builder.BuilderContext.Resolve(ParameterInfo parameter, Object value)
   at Unity.Processors.ConstructorProcessor.<>c__DisplayClass16_0.<GetResolverDelegate>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Processors.MemberProcessor`2.<>c__DisplayClass8_0.<GetResolver>b__0(BuilderContext& c)
   at Unity.Strategies.BuildPlanStrategy.PreBuildUp(BuilderContext& context)
   at Unity.UnityContainer.<>c.<.ctor>b__73_1(BuilderContext& context)
   at Unity.UnityContainer.Unity.IUnityContainer.Resolve(Type type, String name, ResolverOverride[] overrides)
   at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType)
   --- End of inner exception stack trace ---
   at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType)
   at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)````

Body:
Add an Empty constructor like;

public PersonController() {};
//before

public PersonController(ICrudService<Person> personCrudservice)
{
  this.personCrudservice = personCrudservice;
};


问:
Xamarin.Forms: Disabled entry has white TextColor when Dark Mode is enabled on iOS
I seem to have some troubles with the TextColor of my Entry on iOS when Dark Mode is enabled.
Whenever I set the Entry's Enabled state to false, the TextColor turns white and it's not possible to change.
I used the following simple code to reproduce this.

```<code>Page.xaml

    <Entry x:Name="TestEntry" />
</code>```

```<code>Page.xaml.cs

    public OnboardingPage()
    {
        InitializeComponent();

        TestEntry.Text = "Testo";
        TestEntry.TextColor = Color.Blue;
        TestEntry.IsEnabled = false;
    }
</code>```

I am currently using the latest version of Xamarin.Forms. (4.4.0.991640)

Does anybody have an idea what's going wrong here? I don't think this is expected behavior..

Thanks in advance!

答:
The reason that is happening because of how iOS works with the dark mode for you to handle this you have to add the following in your Info.Plist

```<code><key>UIUserInterfaceStyle</key>
<string>Light</string>
</code>```

What this will do is stop your app from changing anything when Dark mode is turned on i.e. it is sort of an opt-out

Goodluck

Feel free to get back if you have questions

Body:
I seem to have some troubles with the TextColor of my Entry on iOS when Dark Mode is enabled.
Whenever I set the Entry's Enabled state to false, the TextColor turns white and it's not possible to change.
I used the following simple code to reproduce this.

Page.xaml

    <Entry x:Name="TestEntry" />

Page.xaml.cs

    public OnboardingPage()
    {
        InitializeComponent();

        TestEntry.Text = "Testo";
        TestEntry.TextColor = Color.Blue;
        TestEntry.IsEnabled = false;
    }

I am currently using the latest version of Xamarin.Forms. (4.4.0.991640)

Does anybody have an idea what's going wrong here? I don't think this is expected behavior..

Thanks in advance!

Body:
The reason that is happening because of how iOS works with the dark mode for you to handle this you have to add the following in your Info.Plist

<key>UIUserInterfaceStyle</key>
<string>Light</string>

What this will do is stop your app from changing anything when Dark mode is turned on i.e. it is sort of an opt-out

Goodluck

Feel free to get back if you have questions


问:
Button and input elements doesn't get applied css style : background
I want to bring output similar to one shown in the figure. I build the table in table2() and build buttons using ButtonDOM().

I want to get the layout shown in figure, so I make the button elements move to right by some pixels.
I have a basic question in css,

To make elements move left, right, top, bottom I have to set position
  property to relative or absolute but when I resize the window, I see
  elements are rearranged incorrect way. I want to move elements left,
  right, top, bottom as well on window resize element to show in correct
  manner. How to achieve this?

I have applied background color to whole div but I see the buttons and date input element appear outside the div, though all these elements are within this div.

Note :  I had to position the input date and button elements relative and absolute and the div #buttonsdiv relative just to position elements where I needed

function maintest () {

   table2();
   ButtonDOM();
   addClasses();
  }

function table2 () {
    let h = $("
").html("Borrowable Features:").prop("class","underline").appendTo("#BorrowableTable");
    let h1 = $("
").html("Features:").prop("class","underline").appendTo("#BorrowableTable");
    let $table = $('
').attr({"id" : "borrowable"}).css({"width":"50%"});
    let $row1 = $('
').appendTo($table);
    $('').appendTo($row1);
    let header = $('').text("Feature").appendTo($row1);
    let $row2 = $('
').prop("id","autocompleterow").appendTo($table);
    let $cell0 = $('').appendTo($row2);

        let $cell1 = $('').appendTo($row2);
        let $autocomplete1 = $("<input>").attr({"id" : "selector0","class":"creamcolorInput"}).appendTo($cell1);

        $("#BorrowableTable").append($table);
        autocomplete2 = $("#selector0").autocomplete( {"source": ['c++','java','javascript']}, {select: function(event, ui) {
            selectedObj = ui.item.value;

        } });

}

function addClasses () {
    let tableRows = $('tr').addClass('tableRows');
    let tableDefn = $('td').attr({"class":"tableDefn"});
    let tableHeader = $('th').attr({"class":"tableHeader"});
    let tbodyDOM = $('tbody').attr({"class" : "tbodyDOM"});
}

function ButtonDOM() {
  let buttonsdiv =  $("

").attr({"id":"buttonsdiv"}).css({"width":"50%"}).appendTo($("#BorrowableTable"));
  let returnDate = $("<input>").attr({"id":"returnDate"}).appendTo($('#buttonsdiv'));
   $( "#returnDate" ).datepicker({ dateFormat: 'yy-mm-dd' }).attr({"class":"creamcolorInput"});

   $("").html("Return Date").insertBefore(returnDate).css({"position":"relative","left":"350px","display":"inline"});
    $("<button>Borrow</button>").attr({"value":"Save","id":"borrowButton"}).appendTo(buttonsdiv)

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#buttonsdiv {
     height: unset !important;
     width:50%;
     position: relative;
     left :50px !important;
     bottom :0px !important;
     background-color: papayawhip !important;
  }

  #BorrowableTable {
    display: flex !important;
    flex-direction: column;
    height:fit-content !important;

  }

  #borrowable {
      display: unset !important;
      border-collapse: collapse;
      border-spacing :unset !important;
      margin-left:100px;
  }

  #BorrowableTable,.creamcolorInput,#buttonsdiv {
    background-color: papayawhip;

  }

  #borrowButton {
    position: absolute;
    left: 325px;
    top: 50px;
    height: 36px;
    width: 205px;
    cursor: pointer;
    border: solid 1px;
    background-color:whitesmoke;
    font-family: ffunit;
    font-size: 14px;
    margin-top: 35px;
    margin-left: 2px;
}

     #returnDate {
      position: absolute;
      left : 330px !important;
      top:25px;
      height:36px;
      width:200px;
  }
   .tableRows, .tableDefn, .tableHeader { /*added from addClasses() */

      padding: 0;
      margin: 0;
      font-family: ffunit;
      font-size: 14px;
      font-weight: bold;
      padding-right: 50px !important;
    }

   button {
      height:36px;
      width:205px;
      cursor: pointer;
      border: solid 1px;
      background-color:whitesmoke;
      font-family: ffunit;
      font-size: 14px;
      margin-top:35px;
      margin-left: 2px;
  }

  input {
    height: 30px;
    width: 250px;
    font-size: 20px;
    text-indent: 6px;
  }

 .tbodyDOM {
   float:  left !important;
  }

   .images {
      position: relative !important;
      cursor: pointer !important;
      width:35px !important;
      height:35px !important;
      left: 35px !important;

  }

   .underline {
     text-decoration: underline;
  }</code>```

```

答:
I have done changes in javascript and css please check and update

function maintest () {

   table2();
   ButtonDOM();
   addClasses();
  }

function table2 () {
    let h = $("
").html("Borrowable Features:").prop("class","underline").appendTo("#BorrowableTable");
    let h1 = $("
").html("Features:").prop("class","underline").appendTo("#BorrowableTable");
    let $table = $('
').attr({"id" : "borrowable"}).css({"width":"50%"});
    let $row1 = $('
').appendTo($table);
    $('').appendTo($row1);
    let header = $('').text("Feature").appendTo($row1);
    let $row2 = $('
').prop("id","autocompleterow").appendTo($table);
    let $cell0 = $('').appendTo($row2);

        let $cell1 = $('').appendTo($row2);
        let $autocomplete1 = $("<input>").attr({"id" : "selector0","class":"creamcolorInput"}).appendTo($cell1);

        $("#BorrowableTable").append($table);
        autocomplete2 = $("#selector0").autocomplete( {"source": ['c++','java','javascript']}, {select: function(event, ui) {
            selectedObj = ui.item.value;

        } });

}
function addClasses () {
    let tableRows = $('tr').addClass('tableRows');
    let tableDefn = $('td').attr({"class":"tableDefn"});
    let tableHeader = $('th').attr({"class":"tableHeader"});
    let tbodyDOM = $('tbody').attr({"class" : "tbodyDOM"});
}

function ButtonDOM() {
  let buttonsdiv =  $("

").attr({"id":"buttonsdiv"}).css({"width":"50%"}).appendTo($("#BorrowableTable"));
  let returnDate = $("<input>").attr({"id":"returnDate"}).appendTo($('#buttonsdiv'));
   $( "#returnDate" ).datepicker({ dateFormat: 'yy-mm-dd' }).attr({"class":"creamcolorInput"});

   $("").html("Return Date").insertBefore(returnDate).css({});
    $("<button>Borrow</button>").attr({"value":"Save","id":"borrowButton"}).appendTo(buttonsdiv)

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    #buttonsdiv {
         height: unset !important;
         width:50%;
         position: relative;
         left :50px !important;
         bottom :0px !important;
                  background-color: papayawhip !important;

      }

      #BorrowableTable {
        display: flex !important;
        flex-direction: column;
        height:fit-content !important;

      }

      #borrowable {
          display: unset !important;
          border-collapse: collapse;
          border-spacing :unset !important;
          margin-left:100px;
      }

      #BorrowableTable,.creamcolorInput,#buttonsdiv {
        background-color: papayawhip;

      }

      #borrowButton {
        cursor: pointer;
        border: solid 1px;
        background-color:whitesmoke;
        font-family: ffunit;
        font-size: 14px;
        margin-top: 35px;
        margin-left: 2px;
    }

         #returnDate {

          height:36px;
          width:200px;
      }
       .tableRows, .tableDefn, .tableHeader { /*added from addClasses() */

          padding: 0;
          margin: 0;
          font-family: ffunit;
          font-size: 14px;
          font-weight: bold;
          padding-right: 50px !important;
        }

       button {
          height:36px;
          width:205px;
          cursor: pointer;
          border: solid 1px;
          background-color:whitesmoke;
          font-family: ffunit;
          font-size: 14px;
          margin-top:35px;
          margin-left: 2px;
      }

      input {
        height: 30px;
        width: 250px;
        font-size: 20px;
        text-indent: 6px;
      }

     .tbodyDOM {
       float:  left !important;
      }

       .images {
          position: relative !important;
          cursor: pointer !important;
          width:35px !important;
          height:35px !important;
          left: 35px !important;

      }

       .underline {
         text-decoration: underline;
      }</code>```

```

Body:
I want to bring output similar to one shown in the figure. I build the table in table2() and build buttons using ButtonDOM().

I want to get the layout shown in figure, so I make the button elements move to right by some pixels.
I have a basic question in css,

To make elements move left, right, top, bottom I have to set position
  property to relative or absolute but when I resize the window, I see
  elements are rearranged incorrect way. I want to move elements left,
  right, top, bottom as well on window resize element to show in correct
  manner. How to achieve this?

I have applied background color to whole div but I see the buttons and date input element appear outside the div, though all these elements are within this div.

Note :  I had to position the input date and button elements relative and absolute and the div #buttonsdiv relative just to position elements where I needed

function maintest () {

   table2();
   ButtonDOM();
   addClasses();
  }

function table2 () {
    let h = $("
").html("Borrowable Features:").prop("class","underline").appendTo("#BorrowableTable");
    let h1 = $("
").html("Features:").prop("class","underline").appendTo("#BorrowableTable");
    let $table = $('
').attr({"id" : "borrowable"}).css({"width":"50%"});
    let $row1 = $('
').appendTo($table);
    $('').appendTo($row1);
    let header = $('').text("Feature").appendTo($row1);
    let $row2 = $('
').prop("id","autocompleterow").appendTo($table);
    let $cell0 = $('').appendTo($row2);

        let $cell1 = $('').appendTo($row2);
        let $autocomplete1 = $("<input>").attr({"id" : "selector0","class":"creamcolorInput"}).appendTo($cell1);

        $("#BorrowableTable").append($table);
        autocomplete2 = $("#selector0").autocomplete( {"source": ['c++','java','javascript']}, {select: function(event, ui) {
            selectedObj = ui.item.value;

        } });

}

function addClasses () {
    let tableRows = $('tr').addClass('tableRows');
    let tableDefn = $('td').attr({"class":"tableDefn"});
    let tableHeader = $('th').attr({"class":"tableHeader"});
    let tbodyDOM = $('tbody').attr({"class" : "tbodyDOM"});
}

function ButtonDOM() {
  let buttonsdiv =  $("

").attr({"id":"buttonsdiv"}).css({"width":"50%"}).appendTo($("#BorrowableTable"));
  let returnDate = $("<input>").attr({"id":"returnDate"}).appendTo($('#buttonsdiv'));
   $( "#returnDate" ).datepicker({ dateFormat: 'yy-mm-dd' }).attr({"class":"creamcolorInput"});

   $("").html("Return Date").insertBefore(returnDate).css({"position":"relative","left":"350px","display":"inline"});
    $("<button>Borrow</button>").attr({"value":"Save","id":"borrowButton"}).appendTo(buttonsdiv)

}

#buttonsdiv {
     height: unset !important;
     width:50%;
     position: relative;
     left :50px !important;
     bottom :0px !important;
     background-color: papayawhip !important;
  }

  #BorrowableTable {
    display: flex !important;
    flex-direction: column;
    height:fit-content !important;

  }

  #borrowable {
      display: unset !important;
      border-collapse: collapse;
      border-spacing :unset !important;
      margin-left:100px;
  }

  #BorrowableTable,.creamcolorInput,#buttonsdiv {
    background-color: papayawhip;

  }

  #borrowButton {
    position: absolute;
    left: 325px;
    top: 50px;
    height: 36px;
    width: 205px;
    cursor: pointer;
    border: solid 1px;
    background-color:whitesmoke;
    font-family: ffunit;
    font-size: 14px;
    margin-top: 35px;
    margin-left: 2px;
}

     #returnDate {
      position: absolute;
      left : 330px !important;
      top:25px;
      height:36px;
      width:200px;
  }
   .tableRows, .tableDefn, .tableHeader { /*added from addClasses() */

      padding: 0;
      margin: 0;
      font-family: ffunit;
      font-size: 14px;
      font-weight: bold;
      padding-right: 50px !important;
    }

   button {
      height:36px;
      width:205px;
      cursor: pointer;
      border: solid 1px;
      background-color:whitesmoke;
      font-family: ffunit;
      font-size: 14px;
      margin-top:35px;
      margin-left: 2px;
  }

  input {
    height: 30px;
    width: 250px;
    font-size: 20px;
    text-indent: 6px;
  }

 .tbodyDOM {
   float:  left !important;
  }

   .images {
      position: relative !important;
      cursor: pointer !important;
      width:35px !important;
      height:35px !important;
      left: 35px !important;

  }

   .underline {
     text-decoration: underline;
  }

Body:
I have done changes in javascript and css please check and update

function maintest () {

   table2();
   ButtonDOM();
   addClasses();
  }

function table2 () {
    let h = $("<h3>").html("Borrowable Features:").prop("class","underline").appendTo("#BorrowableTable");
    let h1 = $("<h3>").html("Features:").prop("class","underline").appendTo("#BorrowableTable");
    let $table = $('<table>').attr({"id" : "borrowable"}).css({"width":"50%"});
    let $row1 = $('<tr>').appendTo($table);
    $('<td>').appendTo($row1);
    let header = $('<td>').text("Feature").appendTo($row1);
    let $row2 = $('<tr>').prop("id","autocompleterow").appendTo($table);
    let $cell0 = $('<td>').appendTo($row2);

        let $cell1 = $('<td>').appendTo($row2);
        let $autocomplete1 = $("<input>").attr({"id" : "selector0","class":"creamcolorInput"}).appendTo($cell1);

        $("#BorrowableTable").append($table);
        autocomplete2 = $("#selector0").autocomplete( {"source": ['c++','java','javascript']}, {select: function(event, ui) {
            selectedObj = ui.item.value;

        } });

}
function addClasses () {
    let tableRows = $('tr').addClass('tableRows');
    let tableDefn = $('td').attr({"class":"tableDefn"});
    let tableHeader = $('th').attr({"class":"tableHeader"});
    let tbodyDOM = $('tbody').attr({"class" : "tbodyDOM"});
}

function ButtonDOM() {
  let buttonsdiv =  $("<div></div>").attr({"id":"buttonsdiv"}).css({"width":"50%"}).appendTo($("#BorrowableTable"));
  let returnDate = $("<input>").attr({"id":"returnDate"}).appendTo($('#buttonsdiv'));
   $( "#returnDate" ).datepicker({ dateFormat: 'yy-mm-dd' }).attr({"class":"creamcolorInput"});

   $("<td>").html("Return Date").insertBefore(returnDate).css({});
    $("<button>Borrow</button>").attr({"value":"Save","id":"borrowButton"}).appendTo(buttonsdiv)

}

    #buttonsdiv {
         height: unset !important;
         width:50%;
         position: relative;
         left :50px !important;
         bottom :0px !important;
                  background-color: papayawhip !important;

      }

      #BorrowableTable {
        display: flex !important;
        flex-direction: column;
        height:fit-content !important;

      }

      #borrowable {
          display: unset !important;
          border-collapse: collapse;
          border-spacing :unset !important;
          margin-left:100px;
      }

      #BorrowableTable,.creamcolorInput,#buttonsdiv {
        background-color: papayawhip;

      }

      #borrowButton {
        cursor: pointer;
        border: solid 1px;
        background-color:whitesmoke;
        font-family: ffunit;
        font-size: 14px;
        margin-top: 35px;
        margin-left: 2px;
    }

         #returnDate {

          height:36px;
          width:200px;
      }
       .tableRows, .tableDefn, .tableHeader { /*added from addClasses() */

          padding: 0;
          margin: 0;
          font-family: ffunit;
          font-size: 14px;
          font-weight: bold;
          padding-right: 50px !important;
        }

       button {
          height:36px;
          width:205px;
          cursor: pointer;
          border: solid 1px;
          background-color:whitesmoke;
          font-family: ffunit;
          font-size: 14px;
          margin-top:35px;
          margin-left: 2px;
      }

      input {
        height: 30px;
        width: 250px;
        font-size: 20px;
        text-indent: 6px;
      }

     .tbodyDOM {
       float:  left !important;
      }

       .images {
          position: relative !important;
          cursor: pointer !important;
          width:35px !important;
          height:35px !important;
          left: 35px !important;

      }

       .underline {
         text-decoration: underline;
      }

<!-- begin snippet: js hide: false console: true babel: null -->


问:
Angular 8: unable to set headers
I want to call a service from my component:

```<code>getToken() {
  const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", httpOptions);
}
</code>```

The call not showing the Authorization, check the image below:

答:
try this</p>

```<code>getToken() {
    const httpOptions = {
        headers: new HttpHeaders({
            'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==',
        })
    };
    const Url = this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password";
    return this.http.post(Url,null, httpOptions)
}
</code>```

Title: Angular 8: unable to set headers

Body:
I want to call a service from my component:

getToken() {
  const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", httpOptions);
}

The call not showing the Authorization, check the image below:

Body:
try this

getToken() {
    const httpOptions = {
        headers: new HttpHeaders({
            'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==',
        })
    };
    const Url = this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password";
    return this.http.post(Url,null, httpOptions)
}


问:
Why must I import my delegate header files?
I am always finding that if I create a delegate and then assign a class to conform to it I have to explicitly import the delegate .h file into that class otherwise I get an error stating the protocol cannot be found?

Am I missing a global setting somewhere that allows my project to find my delegate?

Thanks

答: You can add it into your MyApp_Prefix.pch file if you want it to be added to every class's header. This obviously has some build performance issues, but other than that, shouldn't be a problem.</p>