问:
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize Spring JPA
I have a couple one to many relationships in spring between my classes. And when i try to login I get the error, it is like infinite recursion, here is the whole error message.

```<code>at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:689) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:149) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:112) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:689) ~[jackson-databind-2.8.10.jar:2.8.10]
</code>```

I have 5 classes that are connected with each other.
Here they are:

```<code>@Entity
public class AppUser implements UserDetails {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @Column(unique = true)
    private String username;

    private String password;

    @ElementCollection(fetch = FetchType.EAGER)
    private List<String> roles = new ArrayList<>();

    @ManyToOne
    @JoinColumn(name = "apartmen_id")
    @JsonIgnoreProperties(value = {"apartmen_tenats"}, allowSetters=true)
    private Apartmen apartmen; // apartmen in which he lives

    @ManyToOne
    @JoinColumn(name = "institution_id")
    @JsonIgnoreProperties(value = {"workers"}, allowSetters=true)
    private Institution institution; // institution in which he works

    @OneToMany(mappedBy = "worker")
    @JsonIgnoreProperties(value = {"worker"}, allowSetters = true)
    private Set<Failure> failures; // Kvarovi na kojima je radio
}
</code>```

The second class:

```<code>@Entity
public class Failure implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String description; // Opis kvara

    @Temporal(TemporalType.TIMESTAMP)
    private Date dateCreated; // Datum i vreme kada je kvar kreiran

    @Temporal(TemporalType.TIMESTAMP)
    private Date dateSolved; // Datum i vreme kada je kvar popravljen

    private boolean solved; // Da li je kvar popravljen

    @ManyToOne
    @JoinColumn(name = "app_user_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private AppUser worker; // Radnik koji je zaduzen za kvar

    @ManyToOne
    @JoinColumn(name = "institution_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private Institution institution; // Institucija kojoj je kvar prijavljen

    @ManyToOne
    @JoinColumn(name = "building_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private Building building; // Zgrada u kojoj je kvar nastao
}
</code>```

The third class:

```<code>@Entity
public class Building implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String location;
    private String owner; // Vlasnik zgrade
    private int numberOfApartments;
    private int numberOfAparartmentsWithTenats; // Broj stanova koji su naseljeni
    private boolean hasPresident; // Oznacava da li zgrada ima predsednika skupstine stanara

    @OneToMany(mappedBy = "apartmenBuilding")
    @JsonIgnoreProperties(value = {"apartmenBuilding"}, allowSetters = true)
    private Set<Apartmen> apartments; // stanovi u zgradi

    @ManyToMany(mappedBy = "buildings")
    @JsonIgnoreProperties(value = {"buildings"}, allowSetters = true)
    private Set<Institution> institutions;

    @OneToMany(mappedBy = "building", fetch = FetchType.EAGER)
    @JsonIgnoreProperties(value = {"building"}, allowSetters = true)
    private List<Failure> failures; // Kvarovi koji su nastali u zgradi
}
</code>```

The fourth class:

```<code>@Entity
public class Institution {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String location;
    private String director;
    private String email;
    private String contactPhone;
    private String webSiteUrl;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
    @JoinTable(name = "institution_building",
        joinColumns = @JoinColumn(name = "institution_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "building_id", referencedColumnName = "id"))
    @JsonIgnoreProperties(value = {"institutions"}, allowSetters=true)
    private Set<Building> buildings; // Buildings which this institution is maintaining

    @OneToMany(mappedBy = "institution")
    @JsonIgnoreProperties(value = {"institution"}, allowSetters = true)
    private Set<AppUser> workers;

    @OneToMany(mappedBy = "institution", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JsonIgnoreProperties(value = {"institution"}, allowSetters = true)
    private Set<Failure> failures; // Kvarovi na kojima je radila institucija
}
</code>```

And the last class is:

```<code>@Entity
public class Apartmen implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String location;
    private String owner;
    private int numberOfTenats;
    private boolean hasApartmentBuilding;
    private boolean hasOwner;

    @ManyToOne
    @JoinColumn(name = "building_id")
    @JsonIgnoreProperties(value = {"apartments"}, allowSetters=true)
    private Building apartmenBuilding;

    @OneToMany(mappedBy = "apartmen")
    @JsonIgnoreProperties(value = {"apartmen"}, allowSetters = true)
    private Set<AppUser> apartmen_tenats;
}
</code>```

I don't know why it happens, but maybe it is because of the relationship with the class Failure. I think that may be the case because that class has a relationship with every other class in my code. If that is the case, than can you please show me why is it happening and how to do it properly.

Thank you in advance.

答:
@JsonIgnoreProperties is a class level annotation and it expects the exact field names in the class to ignore.

The best way is to replace all your @JsonIgnoreProperties with simply

```<code>@JsonIgnore.
</code>```

i.e.

```<code>@ManyToOne
@JoinColumn(name = "apartmen_id")
@JsonIgnoreProperties(value = {"apartmen_tenats"}, allowSetters=true)
private Apartmen apartmen;
</code>```

Change this to

```<code>@ManyToOne
@JoinColumn(name = "apartmen_id")
@JsonIgnore
private Apartmen apartmen;
</code>```

Make similar changes for all such occurrences of @JsonIgnoreProperties.
This should work.

Body:
I have a couple one to many relationships in spring between my classes. And when i try to login I get the error, it is like infinite recursion, here is the whole error message.

at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:689) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:149) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:112) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.10.jar:2.8.10]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:689) ~[jackson-databind-2.8.10.jar:2.8.10]

I have 5 classes that are connected with each other.
Here they are:

@Entity
public class AppUser implements UserDetails {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @Column(unique = true)
    private String username;

    private String password;

    @ElementCollection(fetch = FetchType.EAGER)
    private List<String> roles = new ArrayList<>();

    @ManyToOne
    @JoinColumn(name = "apartmen_id")
    @JsonIgnoreProperties(value = {"apartmen_tenats"}, allowSetters=true)
    private Apartmen apartmen; // apartmen in which he lives

    @ManyToOne
    @JoinColumn(name = "institution_id")
    @JsonIgnoreProperties(value = {"workers"}, allowSetters=true)
    private Institution institution; // institution in which he works

    @OneToMany(mappedBy = "worker")
    @JsonIgnoreProperties(value = {"worker"}, allowSetters = true)
    private Set<Failure> failures; // Kvarovi na kojima je radio
}

The second class:

@Entity
public class Failure implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String description; // Opis kvara

    @Temporal(TemporalType.TIMESTAMP)
    private Date dateCreated; // Datum i vreme kada je kvar kreiran

    @Temporal(TemporalType.TIMESTAMP)
    private Date dateSolved; // Datum i vreme kada je kvar popravljen

    private boolean solved; // Da li je kvar popravljen

    @ManyToOne
    @JoinColumn(name = "app_user_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private AppUser worker; // Radnik koji je zaduzen za kvar

    @ManyToOne
    @JoinColumn(name = "institution_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private Institution institution; // Institucija kojoj je kvar prijavljen

    @ManyToOne
    @JoinColumn(name = "building_id")
    @JsonIgnoreProperties(value = {"failures"}, allowSetters=true)
    private Building building; // Zgrada u kojoj je kvar nastao
}

The third class:

@Entity
public class Building implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String location;
    private String owner; // Vlasnik zgrade
    private int numberOfApartments;
    private int numberOfAparartmentsWithTenats; // Broj stanova koji su naseljeni
    private boolean hasPresident; // Oznacava da li zgrada ima predsednika skupstine stanara

    @OneToMany(mappedBy = "apartmenBuilding")
    @JsonIgnoreProperties(value = {"apartmenBuilding"}, allowSetters = true)
    private Set<Apartmen> apartments; // stanovi u zgradi

    @ManyToMany(mappedBy = "buildings")
    @JsonIgnoreProperties(value = {"buildings"}, allowSetters = true)
    private Set<Institution> institutions;

    @OneToMany(mappedBy = "building", fetch = FetchType.EAGER)
    @JsonIgnoreProperties(value = {"building"}, allowSetters = true)
    private List<Failure> failures; // Kvarovi koji su nastali u zgradi
}

The fourth class:

@Entity
public class Institution {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String location;
    private String director;
    private String email;
    private String contactPhone;
    private String webSiteUrl;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
    @JoinTable(name = "institution_building",
        joinColumns = @JoinColumn(name = "institution_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "building_id", referencedColumnName = "id"))
    @JsonIgnoreProperties(value = {"institutions"}, allowSetters=true)
    private Set<Building> buildings; // Buildings which this institution is maintaining

    @OneToMany(mappedBy = "institution")
    @JsonIgnoreProperties(value = {"institution"}, allowSetters = true)
    private Set<AppUser> workers;

    @OneToMany(mappedBy = "institution", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JsonIgnoreProperties(value = {"institution"}, allowSetters = true)
    private Set<Failure> failures; // Kvarovi na kojima je radila institucija
}

And the last class is:

@Entity
public class Apartmen implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String location;
    private String owner;
    private int numberOfTenats;
    private boolean hasApartmentBuilding;
    private boolean hasOwner;

    @ManyToOne
    @JoinColumn(name = "building_id")
    @JsonIgnoreProperties(value = {"apartments"}, allowSetters=true)
    private Building apartmenBuilding;

    @OneToMany(mappedBy = "apartmen")
    @JsonIgnoreProperties(value = {"apartmen"}, allowSetters = true)
    private Set<AppUser> apartmen_tenats;
}

I don't know why it happens, but maybe it is because of the relationship with the class Failure. I think that may be the case because that class has a relationship with every other class in my code. If that is the case, than can you please show me why is it happening and how to do it properly.

Thank you in advance.

Body:
@JsonIgnoreProperties is a class level annotation and it expects the exact field names in the class to ignore.

The best way is to replace all your @JsonIgnoreProperties with simply

@JsonIgnore.

i.e.

@ManyToOne
@JoinColumn(name = "apartmen_id")
@JsonIgnoreProperties(value = {"apartmen_tenats"}, allowSetters=true)
private Apartmen apartmen;

Change this to

@ManyToOne
@JoinColumn(name = "apartmen_id")
@JsonIgnore
private Apartmen apartmen;

Make similar changes for all such occurrences of @JsonIgnoreProperties.
This should work.


来源: stackexchange

问:
Can't able to read the binary file
```<code>         // STRUCTURE FOR ADD NEW DRIVER'S RECORD
        struct driver
       {
        int long reg;
        string name;
        string fhname;
        string peraddress;
        string pesentaddress;
        string dob;
        string cnic;
        string qualification;
        string occupation;
        string phone;
        string mobile;
        string licnum;
        string email;
        string city;
        string gender;
        string province;
        string lictype;
        string vitype;

    }e[100];

     // FUNCTION FOR ADD NEW RECORD OF DRIVER

      void add_driver_record()
      {
       system("CLS");
       char option;

       fstream driverTextFile, addrecord;
       addrecord.open("rcd.data", ios::out | ios::app | ios::binary);

       cout << "Do you Want to Enter New Record (Y/N) ";
       option = _getch();

       system("cls");

       if (option == 'Y' || option == 'y')
        {
          for (int i = 1; i == 1; i++)
           {
              while (option != 'N')
               {
                  cout << "\t\t Driver Information " << endl;
                  cout << "\t\t++++++++++++++++++++" << endl;

                  cout << "\t\tEnter Token No             :";
                  cin >> e[i].reg;

                  cout << "\t\tEnter License Number       :";
                  cin.ignore();
                  getline(cin, e[i].licnum);

                  cout << "\t\tEnter Full Name            :";
                  getline(cin, e[i].name);

                  cout << "\t\tEnter Father/Husband Name  :";
                  getline(cin, e[i].fhname);

                  cout << "\t\tEnter Permanent Address    :";
                  getline(cin, e[i].peraddress);

                  cout << "\t\tEnter Present Address      :";
                  getline(cin, e[i].pesentaddress);

                  cout << "\t\tEnter Date of Birth        :";
                  getline(cin, e[i].dob);

                  cout << "\t\tEnter CNI                  :";
                  getline(cin, e[i].cnic);

                  cout << "\t\tEnter city                 :";
                  getline(cin, e[i].city);

                  cout << "\t\tEnter Province             :";
                  getline(cin, e[i].province);

                  cout << "\t\tEnter Gender               :";
                  cin >> e[i].gender;

                  cout << "\t\tEnter Occupation           :";
                  cin >> e[i].occupation;

                  cout << "\t\tEnter Qaulification        :";
                  cin.ignore();
                  getline(cin, e[i].qualification);

                  cout << "\t\tEnter E-mail               :";
                  cin.ignore();
                  getline(cin, e[i].email);

                  cout << "\t\tEnter Phone No             :";
                  cin >> e[i].phone;

                  cout << "\t\tEnter Mobile No            :";
                  cin >> e[i].mobile;

                  cout << "\t\tEnter License Type         :";
                  cin.ignore();
                  getline(cin, e[i].lictype);

                  cout << "\t\tEnter Vehicle Type         :";
                  cin.ignore();
                  getline(cin, e[i].vitype);

                  addrecord.write((char *)&e, sizeof(driver));

                  driverTextFile <<                                                                                "========================================================\n";
                  driverTextFile << "\t\t   Driver Information  " << endl;
                  driverTextFile << "\t\t+++++++++++++++++++++++" << endl;
                  driverTextFile << "\t\t Token No              :" << e[i].reg << endl;
                  driverTextFile << "\t\t License Number        :" << e[i].licnum << endl;
                  driverTextFile << "\t\t Full Name             :" << e[i].name << endl;
                  driverTextFile << "\t\t Father/Husband Name   :" << e[i].fhname << endl;
                  driverTextFile << "\t\t Permanent Address     :" << e[i].peraddress << endl;
                  driverTextFile << "\t\t Present Address       :" << e[i].pesentaddress << endl;
                  driverTextFile << "\t\t Date of Birth         :" << e[i].dob << endl;
                  driverTextFile << "\t\t CNIC                  :" << e[i].cnic << endl;
                  driverTextFile << "\t\t City                  :" << e[i].city << endl;
                  driverTextFile << "\t\t Province              :" << e[i].province << endl;
                  driverTextFile << "\t\t Gender                :" << e[i].gender << endl;
                  driverTextFile << "\t\t Occupation            :" << e[i].occupation << endl;
                  driverTextFile << "\t\t Qaulification         :" << e[i].qualification << endl;
                  driverTextFile << "\t\t E-mail                :" << e[i].email << endl;
                  driverTextFile << "\t\t Phone No              :" << e[i].phone << endl;
                  driverTextFile << "\t\t Mobile No             :" << e[i].mobile << endl;
                  driverTextFile << "\t\t Enter License Type    :" << e[i].lictype << endl;
                  driverTextFile << "\t\t Enter Vehicle Type    :" << e[i].vitype << endl;
                  driverTextFile << "========================================================\n";

                  addrecord.close();

                  cout << "Do you Want to Enter New Record (Y/N) ";
                  cin >> option;

                  switch (option) {
                  case 'Y':
                  case 'y':
                   add_driver_record();
                   break;
                  case 'N':
                  case 'n':
                   exit(1);
                   break;
                  default:
                   printf("Please select suitable option \n");
                   add_driver_record();
                   break;
               }
              } // while Loop ends
             }// for loop ends
            } // if condition ends

           else if (option == 'N' || option == 'n')
           {
             printf("Please Select Suitable Option \n");
           }
        }

        // FUNCTION FOR DISPLAY ALL RECORDS OF DRIVER'S
         void display_all_driver()
         {

            system("CLS");
            system("color f5");

            fstream myfile, driverTextFile;
            myfile.open("rcd.data", ios::in | ios::out | ios::binary);

            int idx = 1;
            while (idx == 1)
             {

                myfile.read((char*)&e[idx].reg, sizeof(e[idx].reg));
                myfile.read((char*)&e[idx].licnum, sizeof(e[idx].licnum));
                myfile.read((char*)&e[idx].name, sizeof(e[idx].name));
                myfile.read((char*)&e[idx].fhname, sizeof(e[idx].fhname));
                myfile.read((char*)&e[idx].peraddress,              sizeof(e[idx].peraddress));
                myfile.read((char*)&e[idx].pesentaddress, sizeof(e[idx].pesentaddress));
                myfile.read((char*)&e[idx].dob, sizeof(e[idx].dob));
                myfile.read((char*)&e[idx].cnic, sizeof(e[idx].cnic));
                myfile.read((char*)&e[idx].city, sizeof(e[idx].city));
                myfile.read((char*)&e[idx].province, sizeof(e[idx].province));
                myfile.read((char*)&e[idx].gender, sizeof(e[idx].gender));
                myfile.read((char*)&e[idx].occupation, sizeof(e[idx].occupation));
                myfile.read((char*)&e[idx].qualification, sizeof(e[idx].qualification));
                myfile.read((char*)&e[idx].email, sizeof(e[idx].email));
                myfile.read((char*)&e[idx].phone, sizeof(e[idx].phone));
                myfile.read((char*)&e[idx].mobile, sizeof(e[idx].mobile));
                myfile.read((char*)&e[idx].lictype, sizeof(e[idx].lictype));
                myfile.read((char*)&e[idx].vitype, sizeof(e[idx].vitype));

                        cout << "========================================================\n";
                         cout << "\t\t   Driver Information  " << endl;
                         cout << "\t\t+++++++++++++++++++++++" << endl;
                         cout << "\t\t Token No              :" << e[idx].reg << endl;
                         cout << "\t\t License Number        :" << e[idx].licnum << endl;
                         cout << "\t\t Full Name             :" << e[idx].name << endl;
                         cout << "\t\t Father/Husband Name   :" << e[idx].fhname << endl;
                         cout << "\t\t Permanent Address     :" << e[idx].peraddress << endl;
                         cout << "\t\t Present Address       :" << e[idx].pesentaddress << endl;
                         cout << "\t\t Date of Birth         :" << e[idx].dob << endl;
                         cout << "\t\t CNIC                  :" << e[idx].cnic << endl;
                         cout << "\t\t City                  :" << e[idx].city << endl;
                         cout << "\t\t Province              :" << e[idx].province << endl;
                         cout << "\t\t Gender                :" << e[idx].gender << endl;
                         cout << "\t\t Occupation            :" << e[idx].occupation << endl;
                         cout << "\t\t Qaulification         :" << e[idx].qualification << endl;
                         cout << "\t\t E-mail                :" << e[idx].email << endl;
                         cout << "\t\t Phone No              :" << e[idx].phone << endl;
                         cout << "\t\t Mobile No             :" << e[idx].mobile << endl;
                         cout << "\t\t Enter License Type    :" << e[idx].lictype << endl;
                         cout << "\t\t Enter Vehicle Type    :" << e[idx].vitype << endl;
                         cout << "========================================================\n";

                         idx++;
                        }

                          myfile.close();

           }
</code>```

I am so sorry if somebody else had already asked this question. But I am unable to rectify the problem that I "can not" read the binary file on console. Let me tell what my code is doing. I took structure with bunch of attribute and taking the input in that and saving that data in Binary file. And i want to read that in second method. But I am completely unable to read the data. This is my code please provide me solution. I have already tried several ways but I am still unable. Your help will save me semester project.

答:
Your struct driver consists of std::strings, which internally represent the actual content trough a pointer to dynamically allocated memory. When you write such a struct (or an array of such structs) as plain bytes to a file, you actually write out "memory addresses" and not the actual content of the strings. So you will loose the actual content, and reading in the file will give you plain garbage.

Try the following program illustrating this:

```<code>struct TestStruct {
    string testString;
};

int main(){
    TestStruct ts;
    cout << "sizeof ts with empty string: " << sizeof(ts) << endl;
    ts.testString = "Will not get larger, right?";
    cout << "sizeof ts with string set to some content: " << sizeof(ts) << endl;
}
</code>```

Output:

```<code>sizeof ts with empty string: 24
sizeof ts with string set to some content: 24
</code>```

ContentLicense: CC BY-SA 3.0

Title: Can't able to read the binary file

Body:
         // STRUCTURE FOR ADD NEW DRIVER'S RECORD
        struct driver
       {
        int long reg;
        string name;
        string fhname;
        string peraddress;
        string pesentaddress;
        string dob;
        string cnic;
        string qualification;
        string occupation;
        string phone;
        string mobile;
        string licnum;
        string email;
        string city;
        string gender;
        string province;
        string lictype;
        string vitype;

    }e[100];

     // FUNCTION FOR ADD NEW RECORD OF DRIVER

      void add_driver_record()
      {
       system("CLS");
       char option;

       fstream driverTextFile, addrecord;
       addrecord.open("rcd.data", ios::out | ios::app | ios::binary);

       cout << "Do you Want to Enter New Record (Y/N) ";
       option = _getch();

       system("cls");

       if (option == 'Y' || option == 'y')
        {
          for (int i = 1; i == 1; i++)
           {
              while (option != 'N')
               {
                  cout << "\t\t Driver Information " << endl;
                  cout << "\t\t++++++++++++++++++++" << endl;

                  cout << "\t\tEnter Token No             :";
                  cin >> e[i].reg;

                  cout << "\t\tEnter License Number       :";
                  cin.ignore();
                  getline(cin, e[i].licnum);

                  cout << "\t\tEnter Full Name            :";
                  getline(cin, e[i].name);

                  cout << "\t\tEnter Father/Husband Name  :";
                  getline(cin, e[i].fhname);

                  cout << "\t\tEnter Permanent Address    :";
                  getline(cin, e[i].peraddress);

                  cout << "\t\tEnter Present Address      :";
                  getline(cin, e[i].pesentaddress);

                  cout << "\t\tEnter Date of Birth        :";
                  getline(cin, e[i].dob);

                  cout << "\t\tEnter CNI                  :";
                  getline(cin, e[i].cnic);

                  cout << "\t\tEnter city                 :";
                  getline(cin, e[i].city);

                  cout << "\t\tEnter Province             :";
                  getline(cin, e[i].province);

                  cout << "\t\tEnter Gender               :";
                  cin >> e[i].gender;

                  cout << "\t\tEnter Occupation           :";
                  cin >> e[i].occupation;

                  cout << "\t\tEnter Qaulification        :";
                  cin.ignore();
                  getline(cin, e[i].qualification);

                  cout << "\t\tEnter E-mail               :";
                  cin.ignore();
                  getline(cin, e[i].email);

                  cout << "\t\tEnter Phone No             :";
                  cin >> e[i].phone;

                  cout << "\t\tEnter Mobile No            :";
                  cin >> e[i].mobile;

                  cout << "\t\tEnter License Type         :";
                  cin.ignore();
                  getline(cin, e[i].lictype);

                  cout << "\t\tEnter Vehicle Type         :";
                  cin.ignore();
                  getline(cin, e[i].vitype);

                  addrecord.write((char *)&e, sizeof(driver));

                  driverTextFile <<                                                                                "========================================================\n";
                  driverTextFile << "\t\t   Driver Information  " << endl;
                  driverTextFile << "\t\t+++++++++++++++++++++++" << endl;
                  driverTextFile << "\t\t Token No              :" << e[i].reg << endl;
                  driverTextFile << "\t\t License Number        :" << e[i].licnum << endl;
                  driverTextFile << "\t\t Full Name             :" << e[i].name << endl;
                  driverTextFile << "\t\t Father/Husband Name   :" << e[i].fhname << endl;
                  driverTextFile << "\t\t Permanent Address     :" << e[i].peraddress << endl;
                  driverTextFile << "\t\t Present Address       :" << e[i].pesentaddress << endl;
                  driverTextFile << "\t\t Date of Birth         :" << e[i].dob << endl;
                  driverTextFile << "\t\t CNIC                  :" << e[i].cnic << endl;
                  driverTextFile << "\t\t City                  :" << e[i].city << endl;
                  driverTextFile << "\t\t Province              :" << e[i].province << endl;
                  driverTextFile << "\t\t Gender                :" << e[i].gender << endl;
                  driverTextFile << "\t\t Occupation            :" << e[i].occupation << endl;
                  driverTextFile << "\t\t Qaulification         :" << e[i].qualification << endl;
                  driverTextFile << "\t\t E-mail                :" << e[i].email << endl;
                  driverTextFile << "\t\t Phone No              :" << e[i].phone << endl;
                  driverTextFile << "\t\t Mobile No             :" << e[i].mobile << endl;
                  driverTextFile << "\t\t Enter License Type    :" << e[i].lictype << endl;
                  driverTextFile << "\t\t Enter Vehicle Type    :" << e[i].vitype << endl;
                  driverTextFile << "========================================================\n";

                  addrecord.close();

                  cout << "Do you Want to Enter New Record (Y/N) ";
                  cin >> option;

                  switch (option) {
                  case 'Y':
                  case 'y':
                   add_driver_record();
                   break;
                  case 'N':
                  case 'n':
                   exit(1);
                   break;
                  default:
                   printf("Please select suitable option \n");
                   add_driver_record();
                   break;
               }
              } // while Loop ends
             }// for loop ends
            } // if condition ends

           else if (option == 'N' || option == 'n')
           {
             printf("Please Select Suitable Option \n");
           }
        }

        // FUNCTION FOR DISPLAY ALL RECORDS OF DRIVER'S
         void display_all_driver()
         {

            system("CLS");
            system("color f5");

            fstream myfile, driverTextFile;
            myfile.open("rcd.data", ios::in | ios::out | ios::binary);

            int idx = 1;
            while (idx == 1)
             {

                myfile.read((char*)&e[idx].reg, sizeof(e[idx].reg));
                myfile.read((char*)&e[idx].licnum, sizeof(e[idx].licnum));
                myfile.read((char*)&e[idx].name, sizeof(e[idx].name));
                myfile.read((char*)&e[idx].fhname, sizeof(e[idx].fhname));
                myfile.read((char*)&e[idx].peraddress,              sizeof(e[idx].peraddress));
                myfile.read((char*)&e[idx].pesentaddress, sizeof(e[idx].pesentaddress));
                myfile.read((char*)&e[idx].dob, sizeof(e[idx].dob));
                myfile.read((char*)&e[idx].cnic, sizeof(e[idx].cnic));
                myfile.read((char*)&e[idx].city, sizeof(e[idx].city));
                myfile.read((char*)&e[idx].province, sizeof(e[idx].province));
                myfile.read((char*)&e[idx].gender, sizeof(e[idx].gender));
                myfile.read((char*)&e[idx].occupation, sizeof(e[idx].occupation));
                myfile.read((char*)&e[idx].qualification, sizeof(e[idx].qualification));
                myfile.read((char*)&e[idx].email, sizeof(e[idx].email));
                myfile.read((char*)&e[idx].phone, sizeof(e[idx].phone));
                myfile.read((char*)&e[idx].mobile, sizeof(e[idx].mobile));
                myfile.read((char*)&e[idx].lictype, sizeof(e[idx].lictype));
                myfile.read((char*)&e[idx].vitype, sizeof(e[idx].vitype));

                        cout << "========================================================\n";
                         cout << "\t\t   Driver Information  " << endl;
                         cout << "\t\t+++++++++++++++++++++++" << endl;
                         cout << "\t\t Token No              :" << e[idx].reg << endl;
                         cout << "\t\t License Number        :" << e[idx].licnum << endl;
                         cout << "\t\t Full Name             :" << e[idx].name << endl;
                         cout << "\t\t Father/Husband Name   :" << e[idx].fhname << endl;
                         cout << "\t\t Permanent Address     :" << e[idx].peraddress << endl;
                         cout << "\t\t Present Address       :" << e[idx].pesentaddress << endl;
                         cout << "\t\t Date of Birth         :" << e[idx].dob << endl;
                         cout << "\t\t CNIC                  :" << e[idx].cnic << endl;
                         cout << "\t\t City                  :" << e[idx].city << endl;
                         cout << "\t\t Province              :" << e[idx].province << endl;
                         cout << "\t\t Gender                :" << e[idx].gender << endl;
                         cout << "\t\t Occupation            :" << e[idx].occupation << endl;
                         cout << "\t\t Qaulification         :" << e[idx].qualification << endl;
                         cout << "\t\t E-mail                :" << e[idx].email << endl;
                         cout << "\t\t Phone No              :" << e[idx].phone << endl;
                         cout << "\t\t Mobile No             :" << e[idx].mobile << endl;
                         cout << "\t\t Enter License Type    :" << e[idx].lictype << endl;
                         cout << "\t\t Enter Vehicle Type    :" << e[idx].vitype << endl;
                         cout << "========================================================\n";

                         idx++;
                        }

                          myfile.close();

           }

I am so sorry if somebody else had already asked this question. But I am unable to rectify the problem that I "can not" read the binary file on console. Let me tell what my code is doing. I took structure with bunch of attribute and taking the input in that and saving that data in Binary file. And i want to read that in second method. But I am completely unable to read the data. This is my code please provide me solution. I have already tried several ways but I am still unable. Your help will save me semester project.

Body:
Your struct driver consists of std::strings, which internally represent the actual content trough a pointer to dynamically allocated memory. When you write such a struct (or an array of such structs) as plain bytes to a file, you actually write out "memory addresses" and not the actual content of the strings. So you will loose the actual content, and reading in the file will give you plain garbage.

Try the following program illustrating this:

struct TestStruct {
    string testString;
};

int main(){
    TestStruct ts;
    cout << "sizeof ts with empty string: " << sizeof(ts) << endl;
    ts.testString = "Will not get larger, right?";
    cout << "sizeof ts with string set to some content: " << sizeof(ts) << endl;
}

Output:

sizeof ts with empty string: 24
sizeof ts with string set to some content: 24


问:
INFO: No Spring WebApplicationInitializer types detected on classpath
I have a spring project that runs fine on my tomcat7 server when I deploy from eclipse: Run As >> Run on server.
In the eclipse tab "Servers" I see:

```<code>Servers
 Tomcat v7.0 Server at localhost [Started, Synchronized]
   my_project [Synchronized]
     spring-web-3.2.4-RELEASE.jar
</code>```

My project:

does not use web.xml, I use javaconf @ annotations.

does not use maven, I use a User Library

I see that the project is in:

```<code>/srv/applications/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
</code>```

And, I also see the folders: conf,logs,temp,webapps,work,wtpwebapps

I confirm that all runs fine on my tomcat7 server when I deploy from eclipse!

In eclipse console I get:

```<code>Apr 08, 2014 3:26:59 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:my_project' did not find a matching property.
Apr 08, 2014 3:27:00 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8888"]
Apr 08, 2014 3:27:00 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8843"]
Apr 08, 2014 3:27:01 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 3215 ms
Apr 08, 2014 3:27:01 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Apr 08, 2014 3:27:01 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.26
Apr 08, 2014 3:27:11 PM org.apache.catalina.core.ApplicationContext log
INFO: Spring WebApplicationInitializers detected on classpath: [my_project.web.context.WebApplicationInitializer@3599e94c]
Apr 08, 2014 3:27:12 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Apr 08, 2014 3:27:24 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Apr 08, 2014 3:27:24 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8888"]
Apr 08, 2014 3:27:24 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8843"]
Apr 08, 2014 3:27:24 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 23821 ms
</code>```

Now: The problem
It is when I deploy the same app (using a file .war) in the same tomcat7 server /var/lib/tomcat7/webapps

I can open the my initial page web BUT without data,

I see in the log:

```<code>INFO: No Spring WebApplicationInitializer types detected on classpath
</code>```

When I restart tomcat7 I get in the log file:

```<code>INFO: Destroying ProtocolHandler ["http-bio-8843"]
Apr 8, 2014 3:25:30 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:my_project' did not find a matching property.
Apr 8, 2014 3:25:30 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8888"]
Apr 8, 2014 3:25:31 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8843"]
Apr 8, 2014 3:25:31 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1664 ms
Apr 8, 2014 3:25:31 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Apr 8, 2014 3:25:31 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.26
Apr 8, 2014 3:25:38 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8888"]
Apr 8, 2014 3:25:38 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8843"]
Apr 8, 2014 3:25:38 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 7576 ms
</code>```

答:
I had similar problem with Tomcat 8 embedded in java7 application.

When I launched Tomcat in my application, it worked. But when I launched it through Maven for integration test purpose, I got this error : "No Spring WebApplicationInitializer types detected on classpath".

I fixed it by upgrading org.apache.tomcat.embed:tomcat-embed-* dependencies from version 8.0.29 to 8.0.47.

Body:
I have a spring project that runs fine on my tomcat7 server when I deploy from eclipse: Run As >> Run on server.
In the eclipse tab "Servers" I see:

Servers
 Tomcat v7.0 Server at localhost [Started, Synchronized]
   my_project [Synchronized]
     spring-web-3.2.4-RELEASE.jar

My project:

does not use web.xml, I use javaconf @ annotations.

does not use maven, I use a User Library

I see that the project is in:

/srv/applications/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0

And, I also see the folders: conf,logs,temp,webapps,work,wtpwebapps

I confirm that all runs fine on my tomcat7 server when I deploy from eclipse!

In eclipse console I get:

Apr 08, 2014 3:26:59 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:my_project' did not find a matching property.
Apr 08, 2014 3:27:00 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8888"]
Apr 08, 2014 3:27:00 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8843"]
Apr 08, 2014 3:27:01 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 3215 ms
Apr 08, 2014 3:27:01 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Apr 08, 2014 3:27:01 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.26
Apr 08, 2014 3:27:11 PM org.apache.catalina.core.ApplicationContext log
INFO: Spring WebApplicationInitializers detected on classpath: [my_project.web.context.WebApplicationInitializer@3599e94c]
Apr 08, 2014 3:27:12 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Apr 08, 2014 3:27:24 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Apr 08, 2014 3:27:24 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8888"]
Apr 08, 2014 3:27:24 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8843"]
Apr 08, 2014 3:27:24 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 23821 ms

Now: The problem
It is when I deploy the same app (using a file .war) in the same tomcat7 server /var/lib/tomcat7/webapps

I can open the my initial page web BUT without data,

I see in the log:

INFO: No Spring WebApplicationInitializer types detected on classpath

When I restart tomcat7 I get in the log file:

INFO: Destroying ProtocolHandler ["http-bio-8843"]
Apr 8, 2014 3:25:30 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:my_project' did not find a matching property.
Apr 8, 2014 3:25:30 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8888"]
Apr 8, 2014 3:25:31 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8843"]
Apr 8, 2014 3:25:31 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1664 ms
Apr 8, 2014 3:25:31 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Apr 8, 2014 3:25:31 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.26
Apr 8, 2014 3:25:38 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8888"]
Apr 8, 2014 3:25:38 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8843"]
Apr 8, 2014 3:25:38 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 7576 ms


问:
Using geocode API in twitter search
My code works perfectly fine. It has a form where users have to enter a keyword and it will give them a Twitter search results for that keyword.
How can I add the user's IP address or location in the results using geocode?

This is my code:

```<code><?php
include "twitteroauth.php";?>
<?php
$consumer = "...";
$consumersecret = "...";
$accesstoken = "...";
$accesstokensecret = "...";

$twitter = new TwitterOAuth($consumer, $consumersecret, $accesstoken, $accesstokensecret);

?>
<html>

<head>
<meta charset="UTF-8" />
<title>twitter search</title>
</head>

<body>
<form action="" method="post">
    <label> Search: <input type="text" name ="keyword"/></label>
</form>

<?php
  if (isset($_POST['keyword'])){
      $tweets = $twitter->get('https://api.twitter.com/1.1/search/tweets.json?q='.$_POST['keyword'].'&result_type=recent&count=50');
      foreach($tweets as $tweet){
           foreach($tweet as $t){
              echo '<p> <img src="'.$t->user->profile_image_url.'"/><p>Tweet:&nbsp'.$t->text.'<br>';
          }
      }
  }

?>
</body>

</html>
</code>```

答:
Here is what has worked for me (the assumption here is that your included file is the same)</p>

```<code>require_once 'lib/twitteroauth.php';

define('CONSUMER_KEY', 'your_consumer_key');
define('CONSUMER_SECRET', 'your_consumer_secret');
define('ACCESS_TOKEN', 'your_access_token');
define('ACCESS_TOKEN_SECRET', 'your_access_token_secret');

function search(array $query)
{
  $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
  return $toa->get('search/tweets', $query);
}

$query = array(
  "q" => "hipster",
  "count" => 20,
  "geocode" => "37.781157,-122.398720,1mi" // San Fran, Cali, USA
);
$results = search($query);

foreach ($results->statuses as $result) {
  echo $result->user->screen_name . ": " . $result->text . "\n";
}
</code>```

Title: Using geocode API in twitter search

Body:
My code works perfectly fine. It has a form where users have to enter a keyword and it will give them a Twitter search results for that keyword.
How can I add the user's IP address or location in the results using geocode?

This is my code:

<?php
include "twitteroauth.php";?>
<?php
$consumer = "...";
$consumersecret = "...";
$accesstoken = "...";
$accesstokensecret = "...";

$twitter = new TwitterOAuth($consumer, $consumersecret, $accesstoken, $accesstokensecret);

?>

<meta charset="UTF-8" />
<title>twitter search</title>

<form action="" method="post">
     Search: <input type="text" name ="keyword"/>
</form>

<?php
  if (isset($_POST['keyword'])){
      $tweets = $twitter->get('https://api.twitter.com/1.1/search/tweets.json?q='.$_POST['keyword'].'&result_type=recent&count=50');
      foreach($tweets as $tweet){
           foreach($tweet as $t){
              echo '
 user->profile_image_url.'"/>
Tweet:&nbsp'.$t->text.'
';
          }
      }
  }

?>

Body:
Here is what has worked for me (the assumption here is that your included file is the same)

require_once 'lib/twitteroauth.php';

define('CONSUMER_KEY', 'your_consumer_key');
define('CONSUMER_SECRET', 'your_consumer_secret');
define('ACCESS_TOKEN', 'your_access_token');
define('ACCESS_TOKEN_SECRET', 'your_access_token_secret');

function search(array $query)
{
  $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
  return $toa->get('search/tweets', $query);
}

$query = array(
  "q" => "hipster",
  "count" => 20,
  "geocode" => "37.781157,-122.398720,1mi" // San Fran, Cali, USA
);
$results = search($query);

foreach ($results->statuses as $result) {
  echo $result->user->screen_name . ": " . $result->text . "\n";
}


问:
In Django Rest Framework how to update FK in serializer
I'm trying to add a vote functionality to the code found in tutorial of Django Rest Framework. On top of Snippet model, I added a Vote model:

```<code>class Vote(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    voter = models.ForeignKey(User, on_delete=models.CASCADE)
    snippet = models.ForeignKey(Snippet, related_name='votes', on_delete=models.CASCADE)

    class Meta:
        ordering = ('created',)
</code>```

After posting and validating a user vote to a snippet, I now want to update the number of votes received by the snippet (I added to the Snippet model a number_of_votes field).

I'm doing it in the create method of my VoteSerializer like that:

```<code>class VoteSerializer(serializers.HyperlinkedModelSerializer):
    voter = serializers.ReadOnlyField(source='voter.username',validators=[UniqueValidator(queryset=VoteUp.objects.all(), message=already_voted)])
    snippet = serializers.PrimaryKeyRelatedField(queryset=Snippet.objects.all())

    def validate(self, data):
        # ... my validation function

    def create(self, validated_data):
        obj = Vote.objects.create(**validated_data)
        obj.snippet.number_of_votes += 1
        obj.snippet.save()
        return obj
</code>```

It works well but I'm not sure if it's the good way or not to do it. Is there a better way?

答:
Couple of possible "better" ways to try:

Overwrite Save Method

```<code>class Vote(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    voter = models.ForeignKey(User, on_delete=models.CASCADE)
    snippet = models.ForeignKey(Snippet, related_name='votes', on_delete=models.CASCADE)

  class Meta:
    ordering = ('created',)

  def save(self, *args, **kwargs):
    # ensure model is being created and not just modified:
    if not self.pk:
      # increment snippet vote counter
      self.snippet.number_of_votes += 1
      self.snippet.save()

    # call base save method to ensure proper handling
    super().save(*args, **kwargs)
</code>```

Use a Post Save signal

Once you have signals setup for your Django project following the documentation you can create a signal that will look something like this:

```<code>from django.dispatch import receiver
from django.db.models.signals import post_save
# make sure you import Vote here. I'm not sure of your project
# setup so I can't write the import for you.

@receiver(post_save, sender=Vote)
def update(sender, instance, created, **kwargs):
  # only increment on model creation
  if created:
    instance.snippet.number_of_votes += 1
    instance.snippet.save()
</code>```

Although in all honesty I'm pretty sure snippet.vote_set.count() is a pretty fast call and shouldn't interfere with your run time any if you wanted to start by using that instead of a counter. Because remember if you increment the counter you're going to have to decrement it too or your count will be off if someone deletes a record.

Body:
I'm trying to add a vote functionality to the code found in tutorial of Django Rest Framework. On top of Snippet model, I added a Vote model:

class Vote(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    voter = models.ForeignKey(User, on_delete=models.CASCADE)
    snippet = models.ForeignKey(Snippet, related_name='votes', on_delete=models.CASCADE)

    class Meta:
        ordering = ('created',)

After posting and validating a user vote to a snippet, I now want to update the number of votes received by the snippet (I added to the Snippet model a number_of_votes field).

I'm doing it in the create method of my VoteSerializer like that:

class VoteSerializer(serializers.HyperlinkedModelSerializer):
    voter = serializers.ReadOnlyField(source='voter.username',validators=[UniqueValidator(queryset=VoteUp.objects.all(), message=already_voted)])
    snippet = serializers.PrimaryKeyRelatedField(queryset=Snippet.objects.all())

    def validate(self, data):
        # ... my validation function

    def create(self, validated_data):
        obj = Vote.objects.create(**validated_data)
        obj.snippet.number_of_votes += 1
        obj.snippet.save()
        return obj

It works well but I'm not sure if it's the good way or not to do it. Is there a better way?

Body:
Couple of possible "better" ways to try:

Overwrite Save Method

class Vote(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    voter = models.ForeignKey(User, on_delete=models.CASCADE)
    snippet = models.ForeignKey(Snippet, related_name='votes', on_delete=models.CASCADE)

  class Meta:
    ordering = ('created',)

  def save(self, *args, **kwargs):
    # ensure model is being created and not just modified:
    if not self.pk:
      # increment snippet vote counter
      self.snippet.number_of_votes += 1
      self.snippet.save()

    # call base save method to ensure proper handling
    super().save(*args, **kwargs)

Use a Post Save signal

Once you have signals setup for your Django project following the documentation you can create a signal that will look something like this:

from django.dispatch import receiver
from django.db.models.signals import post_save
# make sure you import Vote here. I'm not sure of your project
# setup so I can't write the import for you.

@receiver(post_save, sender=Vote)
def update(sender, instance, created, **kwargs):
  # only increment on model creation
  if created:
    instance.snippet.number_of_votes += 1
    instance.snippet.save()

Although in all honesty I'm pretty sure snippet.vote_set.count() is a pretty fast call and shouldn't interfere with your run time any if you wanted to start by using that instead of a counter. Because remember if you increment the counter you're going to have to decrement it too or your count will be off if someone deletes a record.


问:
Import data tier application is failing
I'm getting the following error while restoring the database backup (.bacpac file) into my on premise SQL Server 2016 instance.

TITLE: Microsoft SQL Server Management Studio

Could not import package.

Warning SQL72012: The object [Azure_Data] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.

Warning SQL72012: The object [Azure_Log] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.

Error SQL72014: .Net SqlClient Data Provider:

Msg 33161, Level 15, State 1, Line 1

  Database master keys without password are not supported in this version of SQL Server.

Error SQL72045: Script execution error. The executed script: CREATE MASTER KEY;

答:
This is due to a difference between SQL Azure and SQL Server 2016. Having a master key without a password is an Azure-only feature. There are two ways to address this issue.

1) open the .bacpac and remove the master key object as well as the credential object. (Rename the .bacpac to .zip, unzip and then look through the xml files, make necessary changes, zip back up and rename back to .bacpac)

or

2) add password encryption to the master key before you export the database to a .bacpac using the following:
ALTER MASTER KEY ADD ENCRYPTION BY PASSWORD = '<PasswordHere>';

Title: Import data tier application is failing


问:
JMOCK Dependency Issue
I am trying to get through my very first JMOCK tutorial http://www.jmock.org/getting-started.html, and it didn't go well.

The problem I encountered is below:

```
<code>
java.lang.SecurityException: class "org.hamcrest.TypeSafeMatcher"'s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(Unknown Source)
    at java.lang.ClassLoader.preDefineClass(Unknown Source)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at org.jmock.internal.InvocationExpectationBuilder.createExpectationFrom(InvocationExpectationBuilder.java:86)
    at org.jmock.internal.InvocationToExpectationTranslator.invoke(InvocationToExpectationTranslator.java:19)
    at org.jmock.internal.FakeObjectMethods.invoke(FakeObjectMethods.java:38)
    at org.jmock.lib.JavaReflectionImposteriser$1.invoke(JavaReflectionImposteriser.java:33)
    at $Proxy8.receive(Unknown Source)
    at PublisherTest$1.(PublisherTest.java:35)
    at PublisherTest.oneSubscriberReceivesAMessage(PublisherTest.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
    at org.jmock.integration.junit4.JMock$1.invoke(JMock.java:37)
    at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:105)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMethod(JUnit4ClassRunner.java:96)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:59)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:52)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:50)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
</code>
```

I've found a solution on the internet. Please see below:

The solution is to ensure that any dependencies on JMock JARs occur
before dependencies on JUnit in every plug-in. That way, Hamcrest is
loaded from JMock, not from JUnit.

My understanding of the solution is: make the test class use the hamcrest jar from JMock instead of the one from Junit? Am I right? What should I do in Eclipse to make it happen?

Thanks,

Sarah

答: You could use junit-dep.jar (rather than junit.jar) which doesn't include the hamcrest types. Then the hamcrest references in jmock won't clash.

ContentLicense: CC BY-SA 2.5

Title: JMOCK Dependency Issue

Body:
I am trying to get through my very first JMOCK tutorial http://www.jmock.org/getting-started.html, and it didn't go well.

The problem I encountered is below:

java.lang.SecurityException: class "org.hamcrest.TypeSafeMatcher"'s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(Unknown Source)
    at java.lang.ClassLoader.preDefineClass(Unknown Source)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at org.jmock.internal.InvocationExpectationBuilder.createExpectationFrom(InvocationExpectationBuilder.java:86)
    at org.jmock.internal.InvocationToExpectationTranslator.invoke(InvocationToExpectationTranslator.java:19)
    at org.jmock.internal.FakeObjectMethods.invoke(FakeObjectMethods.java:38)
    at org.jmock.lib.JavaReflectionImposteriser$1.invoke(JavaReflectionImposteriser.java:33)
    at $Proxy8.receive(Unknown Source)
    at PublisherTest$1.(PublisherTest.java:35)
    at PublisherTest.oneSubscriberReceivesAMessage(PublisherTest.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
    at org.jmock.integration.junit4.JMock$1.invoke(JMock.java:37)
    at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:105)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMethod(JUnit4ClassRunner.java:96)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:59)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:52)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:50)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

I've found a solution on the internet. Please see below:

The solution is to ensure that any dependencies on JMock JARs occur
before dependencies on JUnit in every plug-in. That way, Hamcrest is
loaded from JMock, not from JUnit.

My understanding of the solution is: make the test class use the hamcrest jar from JMock instead of the one from Junit? Am I right? What should I do in Eclipse to make it happen?

Thanks,

Sarah


问:
How to get a substring from starting character to end character in unix korn shell
I'm trying to see if there's an easier way to get a substring from starting character to an end character to identify "date format" that it has, I have a solution that is working but I'm looking if there's a way much easier to do it.

```<code>EXAMPLE:
file_name=file_test_<yyyymmdd>_format.xls

SUBSTRING FROM "<" to ">"
<yyyymmdd>
</code>```

this is what I have and is working:

```<code>file_name="test_file_<mmddyyyy>_test"
format_date=""
Char_Found=0
index=0
while [ $index -lt ${#file_name} ]; do
   letter=$(echo $file_name | cut -c$(( $index + 1 )))
   if [ $letter == "<" ]; then
     Char_Found=1
   fi

   if [ $letter == ">" ]; then
      format_date=${format_date}">"
      break
   fi

   if (( ${Char_Found} )); then
      format_date=${format_date}"${letter}"
   fi

   index=$(( $index + 1 ))
done

echo "Format string: ${format_date}"

#OUTPUT: <mmddyyyy>
</code>```

答:
The posted implementation is not only lengthy,
it's very inefficient, due to calling cut in a loop,
for every character.

A simpler, far more efficient solution is possible with what is called parameter expansion in Bash,
which seems to work just fine in ksh too:

```<code>file_name="test_file_<mmddyyyy>_test"
format_date=$file_name
format_date="<${format_date#*<}"    # chop off the beginning until <
format_date="${format_date%%>*}>"   # chop off the end from >
echo "Format string: ${format_date}"
</code>```

Outputs:

```<code>Format string: <mmddyyyy>
</code>```

Body:
I'm trying to see if there's an easier way to get a substring from starting character to an end character to identify "date format" that it has, I have a solution that is working but I'm looking if there's a way much easier to do it.

EXAMPLE:
file_name=file_test_<yyyymmdd>_format.xls

SUBSTRING FROM "<" to ">"
<yyyymmdd>

this is what I have and is working:

file_name="test_file_<mmddyyyy>_test"
format_date=""
Char_Found=0
index=0
while [ $index -lt ${#file_name} ]; do
   letter=$(echo $file_name | cut -c$(( $index + 1 )))
   if [ $letter == "<" ]; then
     Char_Found=1
   fi

   if [ $letter == ">" ]; then
      format_date=${format_date}">"
      break
   fi

   if (( ${Char_Found} )); then
      format_date=${format_date}"${letter}"
   fi

   index=$(( $index + 1 ))
done

echo "Format string: ${format_date}"

#OUTPUT: <mmddyyyy>

Body:
The posted implementation is not only lengthy,
it's very inefficient, due to calling cut in a loop,
for every character.

A simpler, far more efficient solution is possible with what is called parameter expansion in Bash,
which seems to work just fine in ksh too:

file_name="test_file_<mmddyyyy>_test"
format_date=$file_name
format_date="<${format_date#*<}"    # chop off the beginning until <
format_date="${format_date%%>*}>"   # chop off the end from >
echo "Format string: ${format_date}"

Outputs:

Format string: <mmddyyyy>


问:
Should I use multiple databases for single project
I am working on a site which provides coupons for online shopping sites.
It provides discount coupons for shopping sites in India.
But now the client wants to provide coupons for USA stores also.
But offers available for Indian users are not useful for the USA users and vice versa.

Therefore there will be two versions of the site. One is for the Indian users and other is for the USA users.

But if a user from India searches for an offer which is not available in India but is available in the USA. Then it should appear in search results.

Now I am thinking of creating a new database for the USA users with exact same schema as that of the database for current users(Indian users).

But I would like to get advice from an expert.

答:
Creating a separate database or a separate table (by adding _usa to table name) for that matter does not make sense.. because the same can be achieved by creating a mapping table which maps offers/coupons to the country/countries for which it is valid and is more scalable as well.

Here is what I suggest:

countries: id, name

coupons: id, name, discount

coupon_country_mapping: id, country_id, coupon_id, is_active


问:
SQL string before and after certain characters
```<code>SELECT NAME
FROM SERVERS
</code>```

returns:

```<code>SDACR.hello.com
SDACR
SDACR\AIR
SDACR.hello.com\WATER
</code>```

I need the SELECT query for below result:

```<code>SDACR
SDACR
SDACR\AIR
SDACR\WATER
</code>```

Kindly help ! I tried using LEFT and RIGHT functions as below, but not able to get combined output correctly:

```<code> SELECT
     LEFT(Name, CHARINDEX('.', Name) - 1)
 FROM
     SERVERS

SELECT
    RIGHT(Name, LEN(Name) - CHARINDEX('\', Name))
FROM
    SERVERS
</code>```

答:
Throwing my hat in.... Showing how to use Values and APPLY for cleaner code.

```<code>-- sample data in an easily consumable format
declare @yourdata table (txt varchar(100));
insert @yourdata values
('SDACR.hello.com'),
('SDACR'),
('SDACR\AIR'),
('SDACR.hello.com\WATER');

-- solution
select
  txt,
  newTxt =
  case
    when loc.dot = 0 then txt
    when loc.dot > 0 and loc.slash = 0 then substring(txt, 1, loc.dot-1)
    else substring(txt, 1, loc.dot-1) + substring(txt, loc.slash, 100)
  end
from @yourdata
cross apply (values (charindex('.',txt), (charindex('\',txt)))) loc(dot,slash);
</code>```

Results

```<code>txt                            newTxt
------------------------------ --------------------
SDACR.hello.com                SDACR
SDACR                          SDACR
SDACR\AIR                      SDACR\AIR
SDACR.hello.com\WATER          SDACR\WATER
</code>```

Body:
SELECT NAME
FROM SERVERS

returns:

SDACR.hello.com
SDACR
SDACR\AIR
SDACR.hello.com\WATER

I need the SELECT query for below result:

SDACR
SDACR
SDACR\AIR
SDACR\WATER

Kindly help ! I tried using LEFT and RIGHT functions as below, but not able to get combined output correctly:

 SELECT
     LEFT(Name, CHARINDEX('.', Name) - 1)
 FROM
     SERVERS

SELECT
    RIGHT(Name, LEN(Name) - CHARINDEX('\', Name))
FROM
    SERVERS

Body:
Throwing my hat in.... Showing how to use Values and APPLY for cleaner code.

-- sample data in an easily consumable format
declare @yourdata table (txt varchar(100));
insert @yourdata values
('SDACR.hello.com'),
('SDACR'),
('SDACR\AIR'),
('SDACR.hello.com\WATER');

-- solution
select
  txt,
  newTxt =
  case
    when loc.dot = 0 then txt
    when loc.dot > 0 and loc.slash = 0 then substring(txt, 1, loc.dot-1)
    else substring(txt, 1, loc.dot-1) + substring(txt, loc.slash, 100)
  end
from @yourdata
cross apply (values (charindex('.',txt), (charindex('\',txt)))) loc(dot,slash);

Results

txt                            newTxt
------------------------------ --------------------
SDACR.hello.com                SDACR
SDACR                          SDACR
SDACR\AIR                      SDACR\AIR
SDACR.hello.com\WATER          SDACR\WATER


问:
Moving an an entire row from one position to another
I have 5 rows from my query results and i want to know if its even possible to move an entire row from one position to another. For example the third row to the first row.

Below is my sql code:

```<code>DECLARE @ClientID int = 1041
DECLARE @ProfileID int =2520
DECLARE @PageType tinyint = 2
BEGIN
WITH SortedList
    AS (
        SELECT PageID, PageName, PageTitle, PageUrl, ParentID,
            CAST((PageName) AS VARCHAR(1000)) AS "Path"
            FROM Pagelist p
            WHERE p.ParentId IS NULL and p.PageType=@PageType
        UNION ALL
        SELECT p.PageID, p.PageName, p.PageTitle, p.PageUrl, p.ParentID,
            CAST((a.path + '/' + p.PageName) AS VARCHAR(1000)) AS "Path"
            FROM Pagelist AS p
                JOIN SortedList AS a
                ON p.ParentID = a.PageID
            WHERE  p.PageType=@PageType
       )
        SELECT a.PageID,a.PageTitle,a.ParentID,ua.Access,a.Path,a.PageName
        FROM SortedList as a,ProfilePageAccess ua,UserProfile up
        WHERE ua.ClientID=@ClientID and ua.PageID=a.PageID
            and up.ProfileID=ua.ProfileID and up.ProfileID=@ProfileID
        ORDER BY a.Path
</code>```

END

I want to be able to move the third row to first row.

This is my current results

```<code>PAGEID  PAGETITLE       PARENTID ACCESS  PATH                     PAGENAME
</code>```

```<code>001R    Administration   801       2     HRAdmin                   HrAdmin
002R    Performance      802       2     HRAdmin/AdminPer          AdminPer
003R    Overall Ratings  803       2     HRAdmin/AdminPerformance  Perform
004R    Score Ratings    804       2     HRAdmin/AdminPerformance  Perform
005R    Template Setup   805       2     HRAdmin/AdminPerformance  Perform
</code>```

答:
One way is to change your ORDER BY to something more complex. For example, in Postgres you could change your query from

SELECT a.PageID,a.PageTitle,a.ParentID,ua.Access,a.Path,a.PageName

to

SELECT a.PageID,a.PageTitle,a.ParentID,ua.Access,a.Path,a.PageName, a.PageID == '003R' as priority_column

and change

ORDER BY a.Path

to

ORDER BY priority_column DESC, a.Path

Then it will sort results such that all rows where priority_column is true are above all rows where priority_column is false.

EDIT: Zorkolot's answer is cleaner than this; probably go with that one.

Body:
I have 5 rows from my query results and i want to know if its even possible to move an entire row from one position to another. For example the third row to the first row.

Below is my sql code:

DECLARE @ClientID int = 1041
DECLARE @ProfileID int =2520
DECLARE @PageType tinyint = 2
BEGIN
WITH SortedList
    AS (
        SELECT PageID, PageName, PageTitle, PageUrl, ParentID,
            CAST((PageName) AS VARCHAR(1000)) AS "Path"
            FROM Pagelist p
            WHERE p.ParentId IS NULL and p.PageType=@PageType
        UNION ALL
        SELECT p.PageID, p.PageName, p.PageTitle, p.PageUrl, p.ParentID,
            CAST((a.path + '/' + p.PageName) AS VARCHAR(1000)) AS "Path"
            FROM Pagelist AS p
                JOIN SortedList AS a
                ON p.ParentID = a.PageID
            WHERE  p.PageType=@PageType
       )
        SELECT a.PageID,a.PageTitle,a.ParentID,ua.Access,a.Path,a.PageName
        FROM SortedList as a,ProfilePageAccess ua,UserProfile up
        WHERE ua.ClientID=@ClientID and ua.PageID=a.PageID
            and up.ProfileID=ua.ProfileID and up.ProfileID=@ProfileID
        ORDER BY a.Path

END

I want to be able to move the third row to first row.

This is my current results

PAGEID  PAGETITLE       PARENTID ACCESS  PATH                     PAGENAME

001R    Administration   801       2     HRAdmin                   HrAdmin
002R    Performance      802       2     HRAdmin/AdminPer          AdminPer
003R    Overall Ratings  803       2     HRAdmin/AdminPerformance  Perform
004R    Score Ratings    804       2     HRAdmin/AdminPerformance  Perform
005R    Template Setup   805       2     HRAdmin/AdminPerformance  Perform


问:
Socket closed exception when trying to transfer a file
I am trying to transfer a file from server to client using Java and TCP, however on the client-side I am getting a socket closed exception, whereas the server has no errors when attempting to transfer the file. I am confused about this error because I did not close the socket before trying to read from it. The server accepts the connection and sends the file, but the client gets that error. Any suggestion?

The error is:

java.net.SocketException: Socket closed

Server thread's run function:

```<code>public void run() {
    System.out.println("Service thread running for client at " + socket.getInetAddress() + " on port " + socket.getPort());
    try {
        File file = new File("hank.txt");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream os = socket.getOutputStream();

        byte[] contents;
        long fileLength = file.length();
        long current = 0;

        long start = System.nanoTime();
        while(current!=fileLength) {
            int size = 1000;
            if(fileLength - current >= size) {
                current += size;
            }
            else {
                size = (int)(fileLength - current);
                current = fileLength;
            }
            contents = new byte[size];
            bis.read(contents,0,size);
            os.write(contents);
            System.out.println("sending file..." + (current*100)/fileLength+"% complete!");
        }
        os.flush();
        this.socket.close();
    }catch(Exception e) {
        e.printStackTrace();
    }
}
</code>```

Client receiving the file code:

```<code>    System.out.println("Going to get the file...");
    socket = new Socket(response.getIP().substring(1), response.getPort());

    byte[] contents = new byte[10000];
    FileOutputStream fos = new FileOutputStream("hank.txt");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    InputStream in = socket.getInputStream();

    int bytesRead = 0;
    System.out.println("Starting to read file...");
    while((bytesRead = is.read(contents))!=-1) { //the error points to this lin
        bos.write(contents,0,bytesRead);
    }

    bos.flush();
    bos.close();
    in.close();

    //
    socket.close();
</code>```

答:
Input stream for this socket is available in variable in

```<code>InputStream in = socket.getInputStream();
</code>```

So

```<code> Change is.read(contents)) to in.read(contents))
</code>```

Body:
I am trying to transfer a file from server to client using Java and TCP, however on the client-side I am getting a socket closed exception, whereas the server has no errors when attempting to transfer the file. I am confused about this error because I did not close the socket before trying to read from it. The server accepts the connection and sends the file, but the client gets that error. Any suggestion?

The error is:

java.net.SocketException: Socket closed

Server thread's run function:

public void run() {
    System.out.println("Service thread running for client at " + socket.getInetAddress() + " on port " + socket.getPort());
    try {
        File file = new File("hank.txt");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream os = socket.getOutputStream();

        byte[] contents;
        long fileLength = file.length();
        long current = 0;

        long start = System.nanoTime();
        while(current!=fileLength) {
            int size = 1000;
            if(fileLength - current >= size) {
                current += size;
            }
            else {
                size = (int)(fileLength - current);
                current = fileLength;
            }
            contents = new byte[size];
            bis.read(contents,0,size);
            os.write(contents);
            System.out.println("sending file..." + (current*100)/fileLength+"% complete!");
        }
        os.flush();
        this.socket.close();
    }catch(Exception e) {
        e.printStackTrace();
    }
}

Client receiving the file code:

    System.out.println("Going to get the file...");
    socket = new Socket(response.getIP().substring(1), response.getPort());

    byte[] contents = new byte[10000];
    FileOutputStream fos = new FileOutputStream("hank.txt");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    InputStream in = socket.getInputStream();

    int bytesRead = 0;
    System.out.println("Starting to read file...");
    while((bytesRead = is.read(contents))!=-1) { //the error points to this lin
        bos.write(contents,0,bytesRead);
    }

    bos.flush();
    bos.close();
    in.close();

    //
    socket.close();

Body:
Input stream for this socket is available in variable in

InputStream in = socket.getInputStream();

So

 Change is.read(contents)) to in.read(contents))


问:
how do I get the line number which is causing segmentation fault?
I want to know how can I get to know which line is causing segmentation fault in c language in unix terminal</p>

答:
Rebuild with debugging symbols (add -g flag when compiling).

Run through gdb.

gdb <binary name>

(In gdb) run <binary name> <args>

On crash, use backtrace command to see stack trace.  The offending line will be at the top of the stack, but you may need to look further down in case the segfault is in some library code.


问:
How to loop a Console.ReadLine?
I cannot figure out how to read user-input in a loop (with Console.ReadLine). I'm trying to create a note that lets me store what ever the user inputs, and exits if he types exit.

```<code> using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {

            Note myNote = new Note();
            Note otherNote = new Note();
            myNote.addText("Hi there");
            Console.WriteLine(myNote.display());
            otherNote.addText(Console.ReadLine());
            Console.WriteLine(otherNote.display());
            if (otherNote = "exit")
            {

            }

        }
    }

}

    class Note
{
    private string text = "";
    private DateTime timeStamp = DateTime.Now;
    private DateTime modifiedStamp = DateTime.Now;
    int maxLength = 10;

    public void addText(string sometext)
    {
        if (text.Length + sometext.Length < maxLength)
        {
            text += sometext;
            modifiedStamp = DateTime.Now;
        }

    }

    public string display()
    {
        return "Created: " + timeStamp.ToString() + "\n" +
            "Modified: " + modifiedStamp.ToString() + "\n" +
            "Content: " + text;
    }
}
</code>```

答:
One way to do it is this:

```<code>List<string> simpleList = new List<string> { "Alpha", "Bravo", "Charlie", "Delta", "Echo" }; //Dummy data source
Console.WriteLine("Enter a call sign to find in the list. Press X to exit: "); //Prompt

string callSign;
string exitKey = "x";

while ((callSign = Console.ReadLine().ToLower()) != exitKey)
{ //This is where the "Magic" happens
    if (simpleList.Contains(callSign))
    {
        Console.WriteLine($"\"{callSign}\" exists in our simple list");//Output should the list contain our entry
        Console.WriteLine(""); //Not really relevant, just needed to added spacing between input and output
    }
    else
    {
        Console.WriteLine($"\"{callSign}\" does not exist in our simple list"); //Output should the list not contain our entry
    }
    Console.WriteLine("");
    Console.WriteLine("Enter a call sign to find in the list. Press X to exit: ");//Prompt
}
</code>```

The line:

```<code>while ((callSign = Console.ReadLine().ToLower()) != exitKey) {
      ...
</code>```

is where the loop happens. If the entry does not equal the exitKey, the steps are repeated.

Title: How to loop a Console.ReadLine?

Body:
I cannot figure out how to read user-input in a loop (with Console.ReadLine). I'm trying to create a note that lets me store what ever the user inputs, and exits if he types exit.

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {

            Note myNote = new Note();
            Note otherNote = new Note();
            myNote.addText("Hi there");
            Console.WriteLine(myNote.display());
            otherNote.addText(Console.ReadLine());
            Console.WriteLine(otherNote.display());
            if (otherNote = "exit")
            {

            }

        }
    }

}

    class Note
{
    private string text = "";
    private DateTime timeStamp = DateTime.Now;
    private DateTime modifiedStamp = DateTime.Now;
    int maxLength = 10;

    public void addText(string sometext)
    {
        if (text.Length + sometext.Length < maxLength)
        {
            text += sometext;
            modifiedStamp = DateTime.Now;
        }

    }

    public string display()
    {
        return "Created: " + timeStamp.ToString() + "\n" +
            "Modified: " + modifiedStamp.ToString() + "\n" +
            "Content: " + text;
    }
}

Body:
One way to do it is this:

List<string> simpleList = new List<string> { "Alpha", "Bravo", "Charlie", "Delta", "Echo" }; //Dummy data source
Console.WriteLine("Enter a call sign to find in the list. Press X to exit: "); //Prompt

string callSign;
string exitKey = "x";

while ((callSign = Console.ReadLine().ToLower()) != exitKey)
{ //This is where the "Magic" happens
    if (simpleList.Contains(callSign))
    {
        Console.WriteLine($"\"{callSign}\" exists in our simple list");//Output should the list contain our entry
        Console.WriteLine(""); //Not really relevant, just needed to added spacing between input and output
    }
    else
    {
        Console.WriteLine($"\"{callSign}\" does not exist in our simple list"); //Output should the list not contain our entry
    }
    Console.WriteLine("");
    Console.WriteLine("Enter a call sign to find in the list. Press X to exit: ");//Prompt
}

The line:

while ((callSign = Console.ReadLine().ToLower()) != exitKey) {
      ...

is where the loop happens. If the entry does not equal the exitKey, the steps are repeated.

ContentLicense: CC BY-SA 4.0


问:
vlookup for most common row
I am trying to populate ColumnA in Table1 with the most common value of ColumnB in Table2, where ColumnC in Table2 matches ColumnC in Table1.

Something like:

Table1.ColumnA = Max(if(Table1.ColumnC = Table2.ColumnC, Table2.ColumnB))

I have tried a vlookup with no success. I have also created a pivot table to show the aggregated values but don't know how to query it from TableA.ColumnA

Thank you in advance,
Kevin.

答:
Use this array formula:

```<code>=INDEX(Table2[B],MODE(IF(Table2[C]=[@C],MATCH(Table2[B],Table2[B],0))))
</code>```

Being an array formula it needs to be confirmed with Ctrl-Shift-enter instead of Enter when exiting edit mode.

Using an intermediary pivot table.

Create the pivot table with the name column as the rows and the one to count as the columns and data.

Then you can use this long formula:

```<code>=INDEX($B$16:$D$16,AGGREGATE(15,6,(COLUMN(INDEX($B$17:$D$19,MATCH([@C],$A$17:$A$19,0),0))-MIN(COLUMN(INDEX($B$17:$D$19,MATCH([@C],$A$17:$A$19,0),0)))+1)/(MAX(INDEX($B$17:$D$19,MATCH([@C],$A$17:$A$19,0),0))=INDEX($B$17:$D$19,MATCH([@C],$A$17:$A$19,0),0)),1))
</code>```

Title: vlookup for most common row

Body:
Use this array formula:

=INDEX(Table2[B],MODE(IF(Table2[C]=[@C],MATCH(Table2[B],Table2[B],0))))

Being an array formula it needs to be confirmed with Ctrl-Shift-enter instead of Enter when exiting edit mode.

Using an intermediary pivot table.

Create the pivot table with the name column as the rows and the one to count as the columns and data.

Then you can use this long formula:

=INDEX($B$16:$D$16,AGGREGATE(15,6,(COLUMN(INDEX($B$17:$D$19,MATCH([@C],$A$17:$A$19,0),0))-MIN(COLUMN(INDEX($B$17:$D$19,MATCH([@C],$A$17:$A$19,0),0)))+1)/(MAX(INDEX($B$17:$D$19,MATCH([@C],$A$17:$A$19,0),0))=INDEX($B$17:$D$19,MATCH([@C],$A$17:$A$19,0),0)),1))


问:
Dictionary to a txt file
I am trying  to write a dictionary to a .txt file. I haven't found an efficient way to add multiple values for keys to a text doc.

```<code>players = {}
def save_roster(players):
    with open("Team Roster.txt", "wt") as out_file:
        for k, v in players.items():
            out_file.write(str(k) + ', ' + str(v) + '\n\n')
    display_menu()
</code>```

I have a dictionary that has multiple values for the key. This part of the program leave me with:

```<code>Bryce, <__main__.Roster object at 0x00000167D6DB6550>
</code>```

Where the out put i am aiming for is:

```<code>Bryce, 23, third, 23
</code>```

答:
Python doesn't inherently understand how to print an object. You need to define the __str__ method in order to tell python how to represent your object as a string; otherwise it will default to the representation you're getting. In your case, I might go with something like

```<code>def __str__(self):
   return str(self.position)+", "+str(self.jersey)
</code>```

or whichever attributes you want to print.

And to read the data back in from the text file:

```<code>with open("Team Roster.txt", "r") as in_file:
   for line in in_file:
      player = Roster(*(line.split(", "))
      #do something with player, like store it in a list
</code>```

Assuming Roster.__init__() is set up appropriately, i.e. a Roster object is initialized by passing in the parameters in each line of the file in order.

Title: Dictionary to a txt file

Body:
I am trying  to write a dictionary to a .txt file. I haven't found an efficient way to add multiple values for keys to a text doc.

players = {}
def save_roster(players):
    with open("Team Roster.txt", "wt") as out_file:
        for k, v in players.items():
            out_file.write(str(k) + ', ' + str(v) + '\n\n')
    display_menu()

I have a dictionary that has multiple values for the key. This part of the program leave me with:

Bryce, <__main__.Roster object at 0x00000167D6DB6550>

Where the out put i am aiming for is:

Bryce, 23, third, 23

Body:
Python doesn't inherently understand how to print an object. You need to define the __str__ method in order to tell python how to represent your object as a string; otherwise it will default to the representation you're getting. In your case, I might go with something like

def __str__(self):
   return str(self.position)+", "+str(self.jersey)

or whichever attributes you want to print.

And to read the data back in from the text file:

with open("Team Roster.txt", "r") as in_file:
   for line in in_file:
      player = Roster(*(line.split(", "))
      #do something with player, like store it in a list

Assuming Roster.__init__() is set up appropriately, i.e. a Roster object is initialized by passing in the parameters in each line of the file in order.


问:
Oozie Copy files from one hdfs location to another
I am using oozie fs move option to copy data from one hdfs folder to another. However if the target exists the fs command places source as a child of the target directory as expected. Is there a way to avoid this and copy only avro files from source to target.

答:
if you have to overwrite a directory you can use -f example : hdfs dfs -cp -f /sourcepath /Destination path You can reflect the same way in oozie.

If you want to only copy the Avro files pick the common extension for the avro files and use the wild care, something like this hdfs dfs -cp -f sourcepath/*.avro /Destnation_path

There is no straight way to override the folder from oozie fs, you should delete the folder first and move that way you will not have the child directories

```<code><workflow-app name="[WF-DEF-NAME]" xmlns="uri:oozie:workflow:0.1">
...
<action name="[NODE-NAME]">
    <fs>
        <delete path='[PATH]'/>
        ...
        <mkdir path='[PATH]'/>
        ...
        <move source='[SOURCE-PATH]' target='[TARGET-PATH]'/>
        ...
        <chmod path='[PATH]' permissions='[PERMISSIONS]' dir-files='false' />
        ...
    </fs>
    <ok to="[NODE-NAME]"/>
    <error to="[NODE-NAME]"/>
</action>
...
</code>```

Please refer the oozie documentation for more info on that.

Hope this help, comment on the answer if you have any questions.

Body:
if you have to overwrite a directory you can use -f example : hdfs dfs -cp -f /sourcepath /Destination path You can reflect the same way in oozie.

If you want to only copy the Avro files pick the common extension for the avro files and use the wild care, something like this hdfs dfs -cp -f sourcepath/*.avro /Destnation_path

There is no straight way to override the folder from oozie fs, you should delete the folder first and move that way you will not have the child directories

<workflow-app name="[WF-DEF-NAME]" xmlns="uri:oozie:workflow:0.1">
...
<action name="[NODE-NAME]">
    <fs>
        <delete path='[PATH]'/>
        ...
        <mkdir path='[PATH]'/>
        ...
        <move source='[SOURCE-PATH]' target='[TARGET-PATH]'/>
        ...
        <chmod path='[PATH]' permissions='[PERMISSIONS]' dir-files='false' />
        ...
    </fs>
    <ok to="[NODE-NAME]"/>
    <error to="[NODE-NAME]"/>
</action>
...

Please refer the oozie documentation for more info on that.

Hope this help, comment on the answer if you have any questions.