问:
ServiceStack Utility to read from Custom Config Sections
Is there any ServiceStack utility that can read from custom config sections. ServiceStack has IAppSettings which makes it easy to read from appSettings in a config file. I am wondering if ServiceStack has a similar utility to read from Custom Config Sections.

Thanks
rudrvij

答:
No there isn't, we actively discourage usage of Config Sections which is XML encumbered, in-flexible, non-portable and non-substitutable.

Our preference (when needed) is instead to embed Complex Type configuration in a single AppSetting Text Value which is transparently supported using the human-friendly JSV Format, e.g:

```<code><appSettings>
    <add key="RedisConfig"
         value="{Host:localhost,Port:6379,Database:1,Timeout:10000}" />
</appSettings>
</code>```

Which is supported by every App Settings Provider and can be easily serialized into any POCO with:

```<code>RedisConfig redisConf = appSettings.Get<RedisConfig>("RedisConf");
</code>```

Body:
No there isn't, we actively discourage usage of Config Sections which is XML encumbered, in-flexible, non-portable and non-substitutable.

Our preference (when needed) is instead to embed Complex Type configuration in a single AppSetting Text Value which is transparently supported using the human-friendly JSV Format, e.g:

<appSettings>
    <add key="RedisConfig"
         value="{Host:localhost,Port:6379,Database:1,Timeout:10000}" />
</appSettings>

Which is supported by every App Settings Provider and can be easily serialized into any POCO with:

RedisConfig redisConf = appSettings.Get<RedisConfig>("RedisConf");


来源: stackexchange

问:
img tag not showing image
I created a text file using notepad with the following content, and save it with a html extension.  Then I open it in browser.  The image doesn't show. When I put the image URL in the browser the image shows up, so I know my link is correct.   What am I missing here?  Thanks in advance for your answer.</p>

```<code><!DOCTYPE html>
<html>
<body>

<p>Image doesn't show</p>

<img scr="https://www.findtaxpro.com/Content/img/logo.png" style="width:90px; height:90px;"/>

</body>
</html>
</code>```

答:
you've incorrectly typed the src attribute.

change this:

```<code><img scr="https://www.findtaxpro.com/Content/img/logo.png" style="width:90px; height:90px;"/>
</code>```

to this:

```<code><img src="https://www.findtaxpro.com/Content/img/logo.png" style="width:90px; height:90px;"/>
</code>```

<!DOCTYPE html>

See Image below

```

ContentLicense: CC BY-SA 3.0

Title: img tag not showing image

Body:
I created a text file using notepad with the following content, and save it with a html extension.  Then I open it in browser.  The image doesn't show. When I put the image URL in the browser the image shows up, so I know my link is correct.   What am I missing here?  Thanks in advance for your answer.

<!DOCTYPE html>

Image doesn't show

Body:
you've incorrectly typed the src attribute.

change this:

<img scr="https://www.findtaxpro.com/Content/img/logo.png" style="width:90px; height:90px;"/>

to this:

<img src="https://www.findtaxpro.com/Content/img/logo.png" style="width:90px; height:90px;"/>

<!DOCTYPE html>
<html>
  <body>

    <p>See Image below</p>

    <img src="//www.findtaxpro.com/Content/img/logo.png" style="width:90px; height:90px;"/>

  </body>
</html>


问:
C++ Overload operator - to subtract two objects of the same type
Just trying to follow the book on a self-paced learn C++.

What I have so far is a program that I have created that has an object of Date, which has four parameters. The three parameters that are filled out by the user are, "Month", "Day", and "Year". The fourth parameter is "Old", and that is to store how many days old it is. For that, I have written a function that calculates how many days old it is, and sets it as the forth parameter.

This part works. It calculates how many days old it is.

The book wants me to subtract two objects of type Date and find out the difference between how old they are. For that it specifically requests that I create an overloaded operator of (-), and subtract the two. This is where I am getting a little stuck. The part that I am having issues with is, I believe, the call that is used to access it. I continue to get the error of "ambiguous overload for "operator-' (operand types are 'Date' and 'Date').

It recognizes both objects as Date. Now I just need a little help for the last leg of this.

I have tried using several different things in the header, but perhaps I am implementing them incorrectly.

```<code>-friend Date operator - (Date &ob1, Date &ob2);
-Date &operator-();
-Date &operator-(Date);
-Date operator-(Date);
</code>```

If you can help out with this, it would be wonderful. I'm new, and I've spent over 12 hours on this on question.

Main.cpp

```<code>#include <iostream>
#include <time.h>
#include <ctime>
#include "Date.cpp" // Date class definition
using namespace std;

int main() {
    unsigned int birthMonth = 0;
    unsigned int birthDay = 0;
    unsigned int birthYear = 0;

    unsigned int dateToMonth = 0;
    unsigned int dateToDay = 0;
    unsigned int dateToYear = 0;

    cout << "Enter birth month (1-12): ";
    cin >> birthMonth;
    cout << "Enter birth day (1-31): ";
    cin >> birthDay;
    cout << "Enter birth year (1900 - 2000): ";
    cin >> birthYear;

    Date birthDate (birthMonth, birthDay, birthYear);
    Date tempDate (1, 1, 1, 1);

    cout << "To which date would you like to calculate to?\nEnter Day month (1-12): ";
    cin >> dateToMonth;
    cout << "Enter Day to calculate it to (1-31): ";
    cin >> dateToDay;
    cout << "Enter Year to calculate it to: ";
    cin >> dateToYear;

    Date dateTo (dateToMonth, dateToDay, dateToYear);

    pastDays(birthDate);
    pastDays(dateTo);

    cout << "\nHow many days ago is the birth date? " << birthDate.old << endl;
    cout << "How many days ago is the secondary date? " << dateTo.old << endl;

    // Here is where I get an error "ambiguous overload for "operator-' (operand types are 'Date' and 'Date')"
    cout << tempDate = birthDate - dateTo << endl;
    cout << tempDate.old;
}
</code>```

Date.h

```<code>#ifndef DATE_H
#define DATE_H
#include <array>
#include <iostream>

class Date
  {
    friend std::ostream &operator<<( std::ostream &, const Date & );
public:
    Date( int m = 1, int d = 1, int y = 1900, int o = 0 ); // default constructor
    void setDate( int, int, int, int ); // set month, day, year
//    friend Date operator - (Date &ob1, Date &ob2);
    Date &operator-(); // Modified Line for Assignment
    Date &operator-(Date); // Modified Line for Assignment
//    Date operator-(Date);
    void pastDays (Date);
    static bool leapYear( int ); // is date in a leap year?
    unsigned int month;
    unsigned int day;
    unsigned int year;
    int old;
    static const std::array< unsigned int, 13 > days; // days per month
}; // end class Date

#endif
</code>```

Date.cpp

```<code>#include <iostream>
#include <string>
#include "Date.h"
#include <time.h>
#include <ctime>
#include <conio.h>
#include "Date.h" // Date class definition
using namespace std;

   // initialize static member; one classwide copy
const array< unsigned int, 13 > Date::days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// Date constructor
Date::Date( int month, int day, int year, int old )
  {
    setDate( month, day, year, old );
  } // end Date constructor

// set month, day and year
void Date::setDate( int mm, int dd, int yy, int old )
  {
    if ( mm >= 1 && mm <= 12 )
        month = mm;
    else
        throw invalid_argument( "Month must be 1-12" );

    if ( yy >= 1900 && yy <= 2100 )
        year = yy;

    // test for a leap year
//        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
//            if (dd >= 1 || dd <= 31)
//            day == dd;
//        }
//        if (month == 4 || month == 6 || month == 9 || month == 11){
//            if (dd >= 1 || dd <= 30)
//            day == dd;
//        }
//        if (month == 2)
//            if ( year % 4 != 0 ) {
//                if (dd >= 1 || dd <= 29)
//                day == dd;
//            }
//        if (month == 2)
//            if ( year % 4 != 0 ) {
//                if (dd >= 1 || dd <= 28)
//                day == dd;
//            }
//        else {
//            throw invalid_argument(
//                "Day is out of range for current month and year" );
//        }

    if ( ( month == 2 && leapYear( year ) && dd >= 1 && dd <= 29 ) ||
        ( dd >= 1 && dd <= days[ month ] ) )
        day = dd;
    else
        throw invalid_argument(
            "Day is out of range for current month and year" );

} // end function setDate

void pastDays (Date &entryDay) {
    //Creating Today date object
    time_t t = time(0);
    struct tm * now = localtime(&t);
    int currentYear = now -> tm_year + 1900;
    int currentMonth = now -> tm_mon + 1;
    int currentDay = now -> tm_mday;

    int birthMonth = entryDay.month;
    int birthDay = entryDay.day;
    int birthYear = entryDay.year;

    //The variable that will be assigned to the old parameter, which can then be subtracted from another time.
    int daysAgo = 0;
    entryDay.old = 0;

    cout << endl;
    cout << "First" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Lowering days to 1, to make transition between years easier.
//    while (birthDay > 1){
//        birthDay--;
//        daysAgo--;
//    }

    daysAgo = daysAgo - birthDay;
    daysAgo++;
    birthDay = 1;

    cout << endl;
    cout << "Second" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Lowering months to 1, to make transition between years easier.
    while (birthMonth > 1){
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth--;
            daysAgo -= 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth--;
            daysAgo -= 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth--;
    daysAgo -= 29;
            }
        else {
            birthMonth--;
            daysAgo -= 28;
        }
    }

    cout << endl;
    cout << "Third" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Incrementing year to current year
    while (birthYear < currentYear){
        if ( currentYear % 400 == 0 ||
        ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
            daysAgo = daysAgo + 366;
            birthYear++;
        }
        else {
            daysAgo = daysAgo + 365;
            birthYear++;
        }
    }

    cout << endl;
    cout << "Fourth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    // Incrementing to current month
    while (birthMonth < currentMonth) {
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth++;
            daysAgo += 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth++;
            daysAgo += 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth++;
    daysAgo += 29;
            }
        else {
            birthMonth++;
            daysAgo += 28;
        }
    }

    cout << endl;
    cout << "Fifth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Incrementing to current day, and adding the days to the daysAgo
    while (birthDay < currentDay){
        birthDay++;
        daysAgo++;
    }

    cout << endl;
    cout << "Sixth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Assigning DaysAgo to input parameter.old
    entryDay.old = daysAgo;
}

    Date operator  - (Date &date1, Date &date2)
    {

    Date temp;
    temp.old   = date1.old   - date2.old;
    if(temp.old < 0)
    {
        temp.old = temp.old * -1;
    }
    return(temp);
    }

//Date operator-(Date birthDate)
////friend Distance operator - (Date &birthDate, Date &today)
//    {
////    int birthMonth = birthDate.month;
////    int birthDay = birthDate.day;
////    int birthYear = birthDate.year;
////    int birthOld = 0;
////    Date temp (birthDate.month, birthDate.day, birthDate.year, birthDate.old);
//
////    pastDays(today);
////    pastDays(birthDate);
//
////    int currentMonth = today.month;
////    int currentDay = today.day;
////    int currentYear = today.year;
//
////    int date1 = pastDays(today);
////    int date2 = pastDays(birthDate);
//    Date temp (birthDate.month, birthDate.day, birthDate.year);
//
////    int month, int day, int year, int old
////    temp.month = this -> month;
////    temp.month = this -> day;
////    temp.month = this -> year;
////    Date temp = *this;
//    cout << temp.old;
//
//    temp.old = *this -> old - birthDate.old;
//        //Here I get "Error: Invalid use of 'this' in non-member function;
//
//    return(temp);
//}

bool Date::leapYear( int testYear )
{
    if ( testYear % 400 == 0 ||
      ( testYear % 100 != 0 && testYear % 4 == 0 ) )
        return true; // a leap year
    else
        return false; // not a leap year
} // end function leapYear

// overloaded output operator
ostream &operator<<( ostream &output, const Date &d )
{
  static string monthName[ 13 ] = { "", "January", "February",
        "March", "April", "May", "June", "July", "August",
        "September", "October", "November", "December" };
  output << monthName[ d.month ] << ' ' << d.day << ", " << d.year;
  return output; // enables cascading
} // end function operator<<
</code>```

答:
main.cpp

```<code>#include <iostream>
#include <time.h>
#include <ctime>
#include "Date.cpp" // Date class definition
using namespace std;

int main() {
    unsigned int birthMonth = 0;
    unsigned int birthDay = 0;
    unsigned int birthYear = 0;

    unsigned int dateToMonth = 0;
    unsigned int dateToDay = 0;
    unsigned int dateToYear = 0;

    cout << "Enter birth month (1-12): ";
    cin >> birthMonth;
    cout << "Enter birth day (1-31): ";
    cin >> birthDay;
    cout << "Enter birth year (1900 - 2000): ";
    cin >> birthYear;

    Date birthDate (birthMonth, birthDay, birthYear);
    Date tempDate (1, 1, 1, 1);

    cout << "To which date would you like to calculate to?\nEnter Day month (1-12): ";
    cin >> dateToMonth;
    cout << "Enter Day to calculate it to (1-31): ";
    cin >> dateToDay;
    cout << "Enter Year to calculate it to: ";
    cin >> dateToYear;

    Date dateTo (dateToMonth, dateToDay, dateToYear);

    pastDays(birthDate);
    pastDays(dateTo);

    cout << "\nHow many days ago is the birth date? " << birthDate.old << endl;
    cout << "How many days ago is the secondary date? " << dateTo.old << endl;

    tempDate = birthDate - dateTo;
    cout << tempDate.old;
}
</code>```

Date.h

```<code>#ifndef DATE_H
#define DATE_H
#include <array>
#include <iostream>

class Date
  {
    friend std::ostream &operator<<( std::ostream &, const Date & );
//  friend Date operator-(Date, Date);
public:
    Date( int m = 1, int d = 1, int y = 1900, int o = 0 ); // default constructor
    void setDate( int, int, int, int ); // set month, day, year
//  friend Date operator-(Date, Date);
    Date operator-(); // Modified Line for Assignment
    Date operator-(Date); // Modified Line for Assignment
//    Date operator-(Date);
    void pastDays (Date);
    static bool leapYear( int ); // is date in a leap year?
    unsigned int month;
    unsigned int day;
    unsigned int year;
    int old;
    static const std::array< unsigned int, 13 > days; // days per month
}; // end class Date

#endif
</code>```

Date.cpp

```<code>#include <iostream>
#include <string>
#include "Date.h"
#include <time.h>
#include <ctime>
#include <conio.h>
#include "Date.h" // Date class definition
using namespace std;

   // initialize static member; one classwide copy
const array< unsigned int, 13 > Date::days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// Date constructor
Date::Date( int month, int day, int year, int old )
  {
    setDate( month, day, year, old );
  } // end Date constructor

// set month, day and year
void Date::setDate( int mm, int dd, int yy, int old )
  {
    if ( mm >= 1 && mm <= 12 )
        month = mm;
    else
        throw invalid_argument( "Month must be 1-12" );

    if ( yy >= 1900 && yy <= 2100 )
        year = yy;

    if ( ( month == 2 && leapYear( year ) && dd >= 1 && dd <= 29 ) ||
        ( dd >= 1 && dd <= days[ month ] ) )
        day = dd;
    else
        throw invalid_argument(
            "Day is out of range for current month and year" );

} // end function setDate

void pastDays (Date &entryDay) {
    //Creating Today date object
    time_t t = time(0);
    struct tm * now = localtime(&t);
    int currentYear = now -> tm_year + 1900;
    int currentMonth = now -> tm_mon + 1;
    int currentDay = now -> tm_mday;

    int birthMonth = entryDay.month;
    int birthDay = entryDay.day;
    int birthYear = entryDay.year;

    //The variable that will be assigned to the old parameter, which can then be subtracted from another time.
    int daysAgo = 0;
    entryDay.old = 0;

    cout << endl;
    cout << "First" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Lowering days to 1, to make transition between years easier.
//    while (birthDay > 1){
//        birthDay--;
//        daysAgo--;
//    }

    daysAgo = daysAgo - birthDay;
    daysAgo++;
    birthDay = 1;

    cout << endl;
    cout << "Second" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Lowering months to 1, to make transition between years easier.
    while (birthMonth > 1){
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth--;
            daysAgo -= 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth--;
            daysAgo -= 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth--;
    daysAgo -= 29;
            }
        else {
            birthMonth--;
            daysAgo -= 28;
        }
    }

    cout << endl;
    cout << "Third" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Incrementing year to current year
    while (birthYear < currentYear){
        if ( currentYear % 400 == 0 ||
        ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
            daysAgo = daysAgo + 366;
            birthYear++;
        }
        else {
            daysAgo = daysAgo + 365;
            birthYear++;
        }
    }

    cout << endl;
    cout << "Fourth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    // Incrementing to current month
    while (birthMonth < currentMonth) {
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth++;
            daysAgo += 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth++;
            daysAgo += 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth++;
    daysAgo += 29;
            }
        else {
            birthMonth++;
            daysAgo += 28;
        }
    }

    cout << endl;
    cout << "Fifth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Incrementing to current day, and adding the days to the daysAgo
    while (birthDay < currentDay){
        birthDay++;
        daysAgo++;
    }

    cout << endl;
    cout << "Sixth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Assigning DaysAgo to input parameter.old
    entryDay.old = daysAgo;
}

bool Date::leapYear( int testYear )
{
    if ( testYear % 400 == 0 ||
      ( testYear % 100 != 0 && testYear % 4 == 0 ) )
        return true; // a leap year
    else
        return false; // not a leap year
} // end function leapYear

// overloaded output operator
ostream &operator<<( ostream &output, const Date &d )
{
  static string monthName[ 13 ] = { "", "January", "February",
        "March", "April", "May", "June", "July", "August",
        "September", "October", "November", "December" };
  output << monthName[ d.month ] << ' ' << d.day << ", " << d.year;
  return output; // enables cascading
} // end function operator<<

Date Date::operator-(Date rhs) {
  //lhs -= rhs; // use compound assignment
  //return lhs; // return the result by value
  Date n = *this;
  n.old -= rhs.old;
  return n;
}
</code>```

Body:
Just trying to follow the book on a self-paced learn C++.

What I have so far is a program that I have created that has an object of Date, which has four parameters. The three parameters that are filled out by the user are, "Month", "Day", and "Year". The fourth parameter is "Old", and that is to store how many days old it is. For that, I have written a function that calculates how many days old it is, and sets it as the forth parameter.

This part works. It calculates how many days old it is.

The book wants me to subtract two objects of type Date and find out the difference between how old they are. For that it specifically requests that I create an overloaded operator of (-), and subtract the two. This is where I am getting a little stuck. The part that I am having issues with is, I believe, the call that is used to access it. I continue to get the error of "ambiguous overload for "operator-' (operand types are 'Date' and 'Date').

It recognizes both objects as Date. Now I just need a little help for the last leg of this.

I have tried using several different things in the header, but perhaps I am implementing them incorrectly.

-friend Date operator - (Date &ob1, Date &ob2);
-Date &operator-();
-Date &operator-(Date);
-Date operator-(Date);

If you can help out with this, it would be wonderful. I'm new, and I've spent over 12 hours on this on question.

Main.cpp

#include <iostream>
#include <time.h>
#include <ctime>
#include "Date.cpp" // Date class definition
using namespace std;

int main() {
    unsigned int birthMonth = 0;
    unsigned int birthDay = 0;
    unsigned int birthYear = 0;

    unsigned int dateToMonth = 0;
    unsigned int dateToDay = 0;
    unsigned int dateToYear = 0;

    cout << "Enter birth month (1-12): ";
    cin >> birthMonth;
    cout << "Enter birth day (1-31): ";
    cin >> birthDay;
    cout << "Enter birth year (1900 - 2000): ";
    cin >> birthYear;

    Date birthDate (birthMonth, birthDay, birthYear);
    Date tempDate (1, 1, 1, 1);

    cout << "To which date would you like to calculate to?\nEnter Day month (1-12): ";
    cin >> dateToMonth;
    cout << "Enter Day to calculate it to (1-31): ";
    cin >> dateToDay;
    cout << "Enter Year to calculate it to: ";
    cin >> dateToYear;

    Date dateTo (dateToMonth, dateToDay, dateToYear);

    pastDays(birthDate);
    pastDays(dateTo);

    cout << "\nHow many days ago is the birth date? " << birthDate.old << endl;
    cout << "How many days ago is the secondary date? " << dateTo.old << endl;

    // Here is where I get an error "ambiguous overload for "operator-' (operand types are 'Date' and 'Date')"
    cout << tempDate = birthDate - dateTo << endl;
    cout << tempDate.old;
}

Date.h

#ifndef DATE_H
#define DATE_H
#include <array>
#include <iostream>

class Date
  {
    friend std::ostream &operator<<( std::ostream &, const Date & );
public:
    Date( int m = 1, int d = 1, int y = 1900, int o = 0 ); // default constructor
    void setDate( int, int, int, int ); // set month, day, year
//    friend Date operator - (Date &ob1, Date &ob2);
    Date &operator-(); // Modified Line for Assignment
    Date &operator-(Date); // Modified Line for Assignment
//    Date operator-(Date);
    void pastDays (Date);
    static bool leapYear( int ); // is date in a leap year?
    unsigned int month;
    unsigned int day;
    unsigned int year;
    int old;
    static const std::array< unsigned int, 13 > days; // days per month
}; // end class Date

#endif

Date.cpp

#include <iostream>
#include <string>
#include "Date.h"
#include <time.h>
#include <ctime>
#include <conio.h>
#include "Date.h" // Date class definition
using namespace std;

   // initialize static member; one classwide copy
const array< unsigned int, 13 > Date::days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// Date constructor
Date::Date( int month, int day, int year, int old )
  {
    setDate( month, day, year, old );
  } // end Date constructor

// set month, day and year
void Date::setDate( int mm, int dd, int yy, int old )
  {
    if ( mm >= 1 && mm <= 12 )
        month = mm;
    else
        throw invalid_argument( "Month must be 1-12" );

    if ( yy >= 1900 && yy <= 2100 )
        year = yy;

    // test for a leap year
//        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
//            if (dd >= 1 || dd <= 31)
//            day == dd;
//        }
//        if (month == 4 || month == 6 || month == 9 || month == 11){
//            if (dd >= 1 || dd <= 30)
//            day == dd;
//        }
//        if (month == 2)
//            if ( year % 4 != 0 ) {
//                if (dd >= 1 || dd <= 29)
//                day == dd;
//            }
//        if (month == 2)
//            if ( year % 4 != 0 ) {
//                if (dd >= 1 || dd <= 28)
//                day == dd;
//            }
//        else {
//            throw invalid_argument(
//                "Day is out of range for current month and year" );
//        }

    if ( ( month == 2 && leapYear( year ) && dd >= 1 && dd <= 29 ) ||
        ( dd >= 1 && dd <= days[ month ] ) )
        day = dd;
    else
        throw invalid_argument(
            "Day is out of range for current month and year" );

} // end function setDate

void pastDays (Date &entryDay) {
    //Creating Today date object
    time_t t = time(0);
    struct tm * now = localtime(&t);
    int currentYear = now -> tm_year + 1900;
    int currentMonth = now -> tm_mon + 1;
    int currentDay = now -> tm_mday;

    int birthMonth = entryDay.month;
    int birthDay = entryDay.day;
    int birthYear = entryDay.year;

    //The variable that will be assigned to the old parameter, which can then be subtracted from another time.
    int daysAgo = 0;
    entryDay.old = 0;

    cout << endl;
    cout << "First" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Lowering days to 1, to make transition between years easier.
//    while (birthDay > 1){
//        birthDay--;
//        daysAgo--;
//    }

    daysAgo = daysAgo - birthDay;
    daysAgo++;
    birthDay = 1;

    cout << endl;
    cout << "Second" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Lowering months to 1, to make transition between years easier.
    while (birthMonth > 1){
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth--;
            daysAgo -= 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth--;
            daysAgo -= 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth--;
    daysAgo -= 29;
            }
        else {
            birthMonth--;
            daysAgo -= 28;
        }
    }

    cout << endl;
    cout << "Third" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Incrementing year to current year
    while (birthYear < currentYear){
        if ( currentYear % 400 == 0 ||
        ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
            daysAgo = daysAgo + 366;
            birthYear++;
        }
        else {
            daysAgo = daysAgo + 365;
            birthYear++;
        }
    }

    cout << endl;
    cout << "Fourth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    // Incrementing to current month
    while (birthMonth < currentMonth) {
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth++;
            daysAgo += 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth++;
            daysAgo += 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth++;
    daysAgo += 29;
            }
        else {
            birthMonth++;
            daysAgo += 28;
        }
    }

    cout << endl;
    cout << "Fifth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Incrementing to current day, and adding the days to the daysAgo
    while (birthDay < currentDay){
        birthDay++;
        daysAgo++;
    }

    cout << endl;
    cout << "Sixth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Assigning DaysAgo to input parameter.old
    entryDay.old = daysAgo;
}

    Date operator  - (Date &date1, Date &date2)
    {

    Date temp;
    temp.old   = date1.old   - date2.old;
    if(temp.old < 0)
    {
        temp.old = temp.old * -1;
    }
    return(temp);
    }

//Date operator-(Date birthDate)
////friend Distance operator - (Date &birthDate, Date &today)
//    {
////    int birthMonth = birthDate.month;
////    int birthDay = birthDate.day;
////    int birthYear = birthDate.year;
////    int birthOld = 0;
////    Date temp (birthDate.month, birthDate.day, birthDate.year, birthDate.old);
//
////    pastDays(today);
////    pastDays(birthDate);
//
////    int currentMonth = today.month;
////    int currentDay = today.day;
////    int currentYear = today.year;
//
////    int date1 = pastDays(today);
////    int date2 = pastDays(birthDate);
//    Date temp (birthDate.month, birthDate.day, birthDate.year);
//
////    int month, int day, int year, int old
////    temp.month = this -> month;
////    temp.month = this -> day;
////    temp.month = this -> year;
////    Date temp = *this;
//    cout << temp.old;
//
//    temp.old = *this -> old - birthDate.old;
//        //Here I get "Error: Invalid use of 'this' in non-member function;
//
//    return(temp);
//}

bool Date::leapYear( int testYear )
{
    if ( testYear % 400 == 0 ||
      ( testYear % 100 != 0 && testYear % 4 == 0 ) )
        return true; // a leap year
    else
        return false; // not a leap year
} // end function leapYear

// overloaded output operator
ostream &operator<<( ostream &output, const Date &d )
{
  static string monthName[ 13 ] = { "", "January", "February",
        "March", "April", "May", "June", "July", "August",
        "September", "October", "November", "December" };
  output << monthName[ d.month ] << ' ' << d.day << ", " << d.year;
  return output; // enables cascading
} // end function operator<<

Body:
main.cpp

#include <iostream>
#include <time.h>
#include <ctime>
#include "Date.cpp" // Date class definition
using namespace std;

int main() {
    unsigned int birthMonth = 0;
    unsigned int birthDay = 0;
    unsigned int birthYear = 0;

    unsigned int dateToMonth = 0;
    unsigned int dateToDay = 0;
    unsigned int dateToYear = 0;

    cout << "Enter birth month (1-12): ";
    cin >> birthMonth;
    cout << "Enter birth day (1-31): ";
    cin >> birthDay;
    cout << "Enter birth year (1900 - 2000): ";
    cin >> birthYear;

    Date birthDate (birthMonth, birthDay, birthYear);
    Date tempDate (1, 1, 1, 1);

    cout << "To which date would you like to calculate to?\nEnter Day month (1-12): ";
    cin >> dateToMonth;
    cout << "Enter Day to calculate it to (1-31): ";
    cin >> dateToDay;
    cout << "Enter Year to calculate it to: ";
    cin >> dateToYear;

    Date dateTo (dateToMonth, dateToDay, dateToYear);

    pastDays(birthDate);
    pastDays(dateTo);

    cout << "\nHow many days ago is the birth date? " << birthDate.old << endl;
    cout << "How many days ago is the secondary date? " << dateTo.old << endl;

    tempDate = birthDate - dateTo;
    cout << tempDate.old;
}

Date.h

#ifndef DATE_H
#define DATE_H
#include <array>
#include <iostream>

class Date
  {
    friend std::ostream &operator<<( std::ostream &, const Date & );
//  friend Date operator-(Date, Date);
public:
    Date( int m = 1, int d = 1, int y = 1900, int o = 0 ); // default constructor
    void setDate( int, int, int, int ); // set month, day, year
//  friend Date operator-(Date, Date);
    Date operator-(); // Modified Line for Assignment
    Date operator-(Date); // Modified Line for Assignment
//    Date operator-(Date);
    void pastDays (Date);
    static bool leapYear( int ); // is date in a leap year?
    unsigned int month;
    unsigned int day;
    unsigned int year;
    int old;
    static const std::array< unsigned int, 13 > days; // days per month
}; // end class Date

#endif

Date.cpp

#include <iostream>
#include <string>
#include "Date.h"
#include <time.h>
#include <ctime>
#include <conio.h>
#include "Date.h" // Date class definition
using namespace std;

   // initialize static member; one classwide copy
const array< unsigned int, 13 > Date::days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// Date constructor
Date::Date( int month, int day, int year, int old )
  {
    setDate( month, day, year, old );
  } // end Date constructor

// set month, day and year
void Date::setDate( int mm, int dd, int yy, int old )
  {
    if ( mm >= 1 && mm <= 12 )
        month = mm;
    else
        throw invalid_argument( "Month must be 1-12" );

    if ( yy >= 1900 && yy <= 2100 )
        year = yy;

    if ( ( month == 2 && leapYear( year ) && dd >= 1 && dd <= 29 ) ||
        ( dd >= 1 && dd <= days[ month ] ) )
        day = dd;
    else
        throw invalid_argument(
            "Day is out of range for current month and year" );

} // end function setDate

void pastDays (Date &entryDay) {
    //Creating Today date object
    time_t t = time(0);
    struct tm * now = localtime(&t);
    int currentYear = now -> tm_year + 1900;
    int currentMonth = now -> tm_mon + 1;
    int currentDay = now -> tm_mday;

    int birthMonth = entryDay.month;
    int birthDay = entryDay.day;
    int birthYear = entryDay.year;

    //The variable that will be assigned to the old parameter, which can then be subtracted from another time.
    int daysAgo = 0;
    entryDay.old = 0;

    cout << endl;
    cout << "First" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Lowering days to 1, to make transition between years easier.
//    while (birthDay > 1){
//        birthDay--;
//        daysAgo--;
//    }

    daysAgo = daysAgo - birthDay;
    daysAgo++;
    birthDay = 1;

    cout << endl;
    cout << "Second" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Lowering months to 1, to make transition between years easier.
    while (birthMonth > 1){
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth--;
            daysAgo -= 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth--;
            daysAgo -= 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth--;
    daysAgo -= 29;
            }
        else {
            birthMonth--;
            daysAgo -= 28;
        }
    }

    cout << endl;
    cout << "Third" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Incrementing year to current year
    while (birthYear < currentYear){
        if ( currentYear % 400 == 0 ||
        ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
            daysAgo = daysAgo + 366;
            birthYear++;
        }
        else {
            daysAgo = daysAgo + 365;
            birthYear++;
        }
    }

    cout << endl;
    cout << "Fourth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    // Incrementing to current month
    while (birthMonth < currentMonth) {
        if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
            birthMonth++;
            daysAgo += 31;
        }
        if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
            birthMonth++;
            daysAgo += 30;
        }
        if (birthMonth == 2)
            if ( currentYear % 400 == 0 ||
            ( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
    birthMonth++;
    daysAgo += 29;
            }
        else {
            birthMonth++;
            daysAgo += 28;
        }
    }

    cout << endl;
    cout << "Fifth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Incrementing to current day, and adding the days to the daysAgo
    while (birthDay < currentDay){
        birthDay++;
        daysAgo++;
    }

    cout << endl;
    cout << "Sixth" << daysAgo << endl;
    cout << "BirthMonth: " << birthMonth << endl;
    cout << "BirthDay: " << birthDay << endl;
    cout << "BirthYear: " << birthYear << endl;

    //Assigning DaysAgo to input parameter.old
    entryDay.old = daysAgo;
}

bool Date::leapYear( int testYear )
{
    if ( testYear % 400 == 0 ||
      ( testYear % 100 != 0 && testYear % 4 == 0 ) )
        return true; // a leap year
    else
        return false; // not a leap year
} // end function leapYear

// overloaded output operator
ostream &operator<<( ostream &output, const Date &d )
{
  static string monthName[ 13 ] = { "", "January", "February",
        "March", "April", "May", "June", "July", "August",
        "September", "October", "November", "December" };
  output << monthName[ d.month ] << ' ' << d.day << ", " << d.year;
  return output; // enables cascading
} // end function operator<<

Date Date::operator-(Date rhs) {
  //lhs -= rhs; // use compound assignment
  //return lhs; // return the result by value
  Date n = *this;
  n.old -= rhs.old;
  return n;
}


问:
Pseudo Random Number Generator using LFSR in VHDL
I'm having a bit of trouble creating a prng using the lfsr method. Here is my code:

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity pseudorng is
Port ( clock : in STD_LOGIC;
       reset : in STD_LOGIC;
       Q : out STD_LOGIC_VECTOR (7 downto 0);
       check: out STD_LOGIC);

       constant seed: STD_LOGIC_VECTOR(7 downto 0) := "00000001";
end pseudorng;

architecture Behavioral of pseudorng is

signal temp: STD_LOGIC;
signal Qt: STD_LOGIC_VECTOR(7 downto 0);

begin

PROCESS(clock)
BEGIN

IF rising_edge(clock) THEN
IF (reset='1') THEN Qt <= "00000000";
ELSE Qt <= seed;
END IF;
temp <= Qt(4) XOR Qt(3) XOR Qt(2) XOR Qt(0);
--Qt <= temp & Qt(7 downto 1);

END IF;
END PROCESS;

check <= temp;
Q <= Qt;

end Behavioral;
</code>```

Here is the simulation I have ran:
prng sim

Firstly, the check output is just there so I can monitor the output of the temp signal. Secondly, the line that is commented out is what is causing the problem.

As can be seen from the simulation, on the first rising edge of the clock, the Qt signal reads the seed. However, and this is my question, for some reason the temp signal only XORs the bits of the Qt signal on the second rising edge of the clock. It remains undefined on the first clock pulse. Why is that? If it operated on the first rising edge right after the Qt signal reads the seed, then I could uncomment the line that shifts the bits and it would solve my problem. Any help would be much appreciated!

Here is the test bench if anyone cares:

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity tb_pseudorng is
end tb_pseudorng;

architecture bench of tb_pseudorng is

COMPONENT pseudorng
      Port ( clock : in STD_LOGIC;
      reset : in STD_LOGIC;
      Q : out STD_LOGIC_VECTOR (7 downto 0);
      check: out STD_LOGIC);
END COMPONENT;

signal clock1: STD_LOGIC;
signal reset1: STD_LOGIC;
signal Q1: STD_LOGIC_VECTOR(7 downto 0);
signal check1: STD_LOGIC;

begin

mapping: pseudorng PORT MAP(
clock => clock1,
reset => reset1,
Q => Q1,
check => check1);

clock: PROCESS
BEGIN
clock1<='0'; wait for 50ns;
clock1<='1'; wait for 50ns;
END PROCESS;

reset: PROCESS
BEGIN
reset1<='0'; wait for 900ns;
END PROCESS;

end bench;
</code>```

答:
I made some slight modifications to what you had (you are pretty much there though); I don't think the LFSR would step properly otherwise. I added an enable signal to the LFSR so you can effectively control when you want it to step. Resulting sim is here.

Just as a sidenote, you could also include a load and seed inputs if you wanted to seed the LFSR with a different value (instead of making it const).

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity pseudorng is
Port ( clock : in STD_LOGIC;
       reset : in STD_LOGIC;
       en : in STD_LOGIC;
       Q : out STD_LOGIC_VECTOR (7 downto 0);
       check: out STD_LOGIC);

--       constant seed: STD_LOGIC_VECTOR(7 downto 0) := "00000001";
end pseudorng;

architecture Behavioral of pseudorng is

--signal temp: STD_LOGIC;
signal Qt: STD_LOGIC_VECTOR(7 downto 0) := x"01";

begin

PROCESS(clock)
variable tmp : STD_LOGIC := '0';
BEGIN

IF rising_edge(clock) THEN
   IF (reset='1') THEN
   -- credit to QuantumRipple for pointing out that this should not
   -- be reset to all 0's, as you will enter an invalid state
      Qt <= x"01";
   --ELSE Qt <= seed;
   ELSIF en = '1' THEN
      tmp := Qt(4) XOR Qt(3) XOR Qt(2) XOR Qt(0);
      Qt <= tmp & Qt(7 downto 1);
   END IF;

END IF;
END PROCESS;
-- check <= temp;
check <= Qt(7);
Q <= Qt;

end Behavioral;
</code>```

And tb:

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity tb_pseudorng is
end tb_pseudorng;

architecture bench of tb_pseudorng is

COMPONENT pseudorng
      Port ( clock : in STD_LOGIC;
      reset : in STD_LOGIC;
      en : in STD_LOGIC;
      Q : out STD_LOGIC_VECTOR (7 downto 0);
      check: out STD_LOGIC);
END COMPONENT;

signal clock1: STD_LOGIC;
signal reset1: STD_LOGIC;
signal Q1: STD_LOGIC_VECTOR(7 downto 0);
signal check1: STD_LOGIC;
signal en : STD_LOGIC;

begin

mapping: pseudorng PORT MAP(
clock => clock1,
reset => reset1,
en => en,
Q => Q1,
check => check1);

clock: PROCESS
BEGIN
   clock1 <= '0'; wait for 50 ns;
   clock1 <= '1'; wait for 50 ns;
END PROCESS;

reset: PROCESS
BEGIN
   reset1 <= '0';
   en <= '1';
   wait for 900 ns;
END PROCESS;

end bench;
</code>```

Body:
I'm having a bit of trouble creating a prng using the lfsr method. Here is my code:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity pseudorng is
Port ( clock : in STD_LOGIC;
       reset : in STD_LOGIC;
       Q : out STD_LOGIC_VECTOR (7 downto 0);
       check: out STD_LOGIC);

       constant seed: STD_LOGIC_VECTOR(7 downto 0) := "00000001";
end pseudorng;

architecture Behavioral of pseudorng is

signal temp: STD_LOGIC;
signal Qt: STD_LOGIC_VECTOR(7 downto 0);

begin

PROCESS(clock)
BEGIN

IF rising_edge(clock) THEN
IF (reset='1') THEN Qt <= "00000000";
ELSE Qt <= seed;
END IF;
temp <= Qt(4) XOR Qt(3) XOR Qt(2) XOR Qt(0);
--Qt <= temp & Qt(7 downto 1);

END IF;
END PROCESS;

check <= temp;
Q <= Qt;

end Behavioral;

Here is the simulation I have ran:
prng sim

Firstly, the check output is just there so I can monitor the output of the temp signal. Secondly, the line that is commented out is what is causing the problem.

As can be seen from the simulation, on the first rising edge of the clock, the Qt signal reads the seed. However, and this is my question, for some reason the temp signal only XORs the bits of the Qt signal on the second rising edge of the clock. It remains undefined on the first clock pulse. Why is that? If it operated on the first rising edge right after the Qt signal reads the seed, then I could uncomment the line that shifts the bits and it would solve my problem. Any help would be much appreciated!

Here is the test bench if anyone cares:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity tb_pseudorng is
end tb_pseudorng;

architecture bench of tb_pseudorng is

COMPONENT pseudorng
      Port ( clock : in STD_LOGIC;
      reset : in STD_LOGIC;
      Q : out STD_LOGIC_VECTOR (7 downto 0);
      check: out STD_LOGIC);
END COMPONENT;

signal clock1: STD_LOGIC;
signal reset1: STD_LOGIC;
signal Q1: STD_LOGIC_VECTOR(7 downto 0);
signal check1: STD_LOGIC;

begin

mapping: pseudorng PORT MAP(
clock => clock1,
reset => reset1,
Q => Q1,
check => check1);

clock: PROCESS
BEGIN
clock1<='0'; wait for 50ns;
clock1<='1'; wait for 50ns;
END PROCESS;

reset: PROCESS
BEGIN
reset1<='0'; wait for 900ns;
END PROCESS;

end bench;

Body:
I made some slight modifications to what you had (you are pretty much there though); I don't think the LFSR would step properly otherwise. I added an enable signal to the LFSR so you can effectively control when you want it to step. Resulting sim is here.

Just as a sidenote, you could also include a load and seed inputs if you wanted to seed the LFSR with a different value (instead of making it const).

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity pseudorng is
Port ( clock : in STD_LOGIC;
       reset : in STD_LOGIC;
       en : in STD_LOGIC;
       Q : out STD_LOGIC_VECTOR (7 downto 0);
       check: out STD_LOGIC);

--       constant seed: STD_LOGIC_VECTOR(7 downto 0) := "00000001";
end pseudorng;

architecture Behavioral of pseudorng is

--signal temp: STD_LOGIC;
signal Qt: STD_LOGIC_VECTOR(7 downto 0) := x"01";

begin

PROCESS(clock)
variable tmp : STD_LOGIC := '0';
BEGIN

IF rising_edge(clock) THEN
   IF (reset='1') THEN
   -- credit to QuantumRipple for pointing out that this should not
   -- be reset to all 0's, as you will enter an invalid state
      Qt <= x"01";
   --ELSE Qt <= seed;
   ELSIF en = '1' THEN
      tmp := Qt(4) XOR Qt(3) XOR Qt(2) XOR Qt(0);
      Qt <= tmp & Qt(7 downto 1);
   END IF;

END IF;
END PROCESS;
-- check <= temp;
check <= Qt(7);
Q <= Qt;

end Behavioral;

And tb:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity tb_pseudorng is
end tb_pseudorng;

architecture bench of tb_pseudorng is

COMPONENT pseudorng
      Port ( clock : in STD_LOGIC;
      reset : in STD_LOGIC;
      en : in STD_LOGIC;
      Q : out STD_LOGIC_VECTOR (7 downto 0);
      check: out STD_LOGIC);
END COMPONENT;

signal clock1: STD_LOGIC;
signal reset1: STD_LOGIC;
signal Q1: STD_LOGIC_VECTOR(7 downto 0);
signal check1: STD_LOGIC;
signal en : STD_LOGIC;

begin

mapping: pseudorng PORT MAP(
clock => clock1,
reset => reset1,
en => en,
Q => Q1,
check => check1);

clock: PROCESS
BEGIN
   clock1 <= '0'; wait for 50 ns;
   clock1 <= '1'; wait for 50 ns;
END PROCESS;

reset: PROCESS
BEGIN
   reset1 <= '0';
   en <= '1';
   wait for 900 ns;
END PROCESS;

end bench;


问:
How to map a domain to another domain's subfolder?
I have a very fast web server (IIS6, ASP.NET) that I want to use for several sites. Now, I already have a domain that maps directly to the IP address of the server, but how can I get another domain to map to a subfolder (i.e., a separate ASP.NET application) on that same computer? Is it theoretically possible? (note: only port 80 is open, I cannot open other ones.)

Accepted answer: shown below. I actually followed the tutorial and got it working. Hooray! Thanks, everyone! :)

答:
Does it have to be a subfolder? You can setup a different site in iis and use host headers to direct each domain to the relevant site, all using one ip.

You can't do this if you need ssl though; you really need multiple ips for that.

If it has to be a subdir you can create another site as above and set it to redirect to somewhere else.

OwnerDisplayName: Dmitri Nesteruk

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Dmitri Nesteruk

OwnerDisplayName: Steve Robbins


问:
SQL Server 2008 - why is performance WORSE with xml index?
It's crazy, but query performance is about 50% WORSE after I add a primary XML index to my xml field.

Here's what I'm doing.

I have a table containing an XML field ActivityStepLog (contains LogData, XML)

I generate sample data to insert into this table by running the following

INSERT INTO dbo.ActivityStepLog (

 LogGUID

 ,LogContextID

 ,LogTypeID

 ,LogSourceName

 ,LogContent

 ,LogDate

 ,CreateDate

 ,CreatedBy

)

select

 LogGUID         = newid()

 ,LogContextID   = newid()

 ,LogTypeID      = 2

 ,LogSourceName  = 'test test test'

 ,LogContent     = (SELECT top 1 * FROM  ##SampleData SampleData1 where DecisionLogID = SampleData.DecisionLogID FOR XML AUTO, ELEMENTS, ROOT('BusinessRule') )

 ,LogDate        = current_timestamp

 ,CreateDate     = current_timestamp

 ,CreatedBy      = 'test create by'

from ##SampleData SampleData

SampleData has 100,000 rows, I run it in a loop 5 times so end up with 500,000 rows.

The LogContent field will end up having data such as the following:

   -2147483643
   0569281A-D1A3-49E3-9E68-BCAC62E2C1C3
   1016
   2
   0
   -2147483495
   1
   2009-05-18T11:47:00
   none

(sorry, not sure if this will be formatted properly - it's just basically a short set of elements).

And then I just run a very simple sql  -

```<code>SELECT *
FROM ActivityStepLog
WHERE LogContent.value('(/BusinessRuleDecisionLog/SampleData1/DecisionLogID)[1]', 'int') = -2147483535
</code>```

Before creating the primary xml index on LogContent, it takes 8 seconds, after, it takes about 12 seconds.  I've cleaned out cache, etc (DROPCLEANBUFFERS and FREEPROCCACHE ),  it doesn't seem to affect the proportions though it does affect the overall time.

Here's my statistics:

WITH xml index
Table 'xml_index_nodes_325576198_256000'. Scan count 1000000, logical reads 3517272, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'ActivityStepLog'. Scan count 1, logical reads 71694, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

With OUT xml index

(5 row(s) affected)
Table 'ActivityStepLog'. Scan count 1, logical reads 71694, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

So, the logical reads are much less withOUT the xml index.  I tried adding ALL the available secondary indexes, that didn't improve performance over having a primary xml index.

I'll be doing some more research on this, but I would really appreciate any pointers or  comments.

thanks,
Sylvia

答:
From doing more research on this - it appears that for UNTYPED xml fields, at least in my test case, the xml indexes degrade performance.  This appears to be different for typed xml, though I didn't look into it much.

One thing that DID improve performance tremendously (thank you for the idea to wBob on the msdn sql xml forum!) was to create a full text index on the xml field.  I got subsecond performance at that point.  I also included an xml filter as well for accuracy.

```<code>SELECT *
FROM dbo.ActivityStepLog
WHERE
   CONTAINS (LogContent, '-2147483535')
   and LogContent.value('(/BusinessRuleDecisionLog/SampleData1/DecisionLogID)[1]', 'int') = -2147483535
</code>```

I sill need to research whether this fits all my filtering needs, but so far it looks good.

Sylvia

Body:
It's crazy, but query performance is about 50% WORSE after I add a primary XML index to my xml field.

Here's what I'm doing.

I have a table containing an XML field ActivityStepLog (contains LogData, XML)

I generate sample data to insert into this table by running the following

INSERT INTO dbo.ActivityStepLog (

 LogGUID

 ,LogContextID

 ,LogTypeID

 ,LogSourceName

 ,LogContent

 ,LogDate

 ,CreateDate

 ,CreatedBy

)

select

 LogGUID         = newid()

 ,LogContextID   = newid()

 ,LogTypeID      = 2

 ,LogSourceName  = 'test test test'

 ,LogContent     = (SELECT top 1 * FROM  ##SampleData SampleData1 where DecisionLogID = SampleData.DecisionLogID FOR XML AUTO, ELEMENTS, ROOT('BusinessRule') )

 ,LogDate        = current_timestamp

 ,CreateDate     = current_timestamp

 ,CreatedBy      = 'test create by'

from ##SampleData SampleData

SampleData has 100,000 rows, I run it in a loop 5 times so end up with 500,000 rows.

The LogContent field will end up having data such as the following:

   -2147483643
   0569281A-D1A3-49E3-9E68-BCAC62E2C1C3
   1016
   2
   0
   -2147483495
   1
   2009-05-18T11:47:00
   none

(sorry, not sure if this will be formatted properly - it's just basically a short set of elements).

And then I just run a very simple sql  -

SELECT *
FROM ActivityStepLog
WHERE LogContent.value('(/BusinessRuleDecisionLog/SampleData1/DecisionLogID)[1]', 'int') = -2147483535

Before creating the primary xml index on LogContent, it takes 8 seconds, after, it takes about 12 seconds.  I've cleaned out cache, etc (DROPCLEANBUFFERS and FREEPROCCACHE ),  it doesn't seem to affect the proportions though it does affect the overall time.

Here's my statistics:

WITH xml index
Table 'xml_index_nodes_325576198_256000'. Scan count 1000000, logical reads 3517272, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'ActivityStepLog'. Scan count 1, logical reads 71694, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

With OUT xml index

(5 row(s) affected)
Table 'ActivityStepLog'. Scan count 1, logical reads 71694, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

So, the logical reads are much less withOUT the xml index.  I tried adding ALL the available secondary indexes, that didn't improve performance over having a primary xml index.

I'll be doing some more research on this, but I would really appreciate any pointers or  comments.

thanks,
Sylvia

Body:
From doing more research on this - it appears that for UNTYPED xml fields, at least in my test case, the xml indexes degrade performance.  This appears to be different for typed xml, though I didn't look into it much.

One thing that DID improve performance tremendously (thank you for the idea to wBob on the msdn sql xml forum!) was to create a full text index on the xml field.  I got subsecond performance at that point.  I also included an xml filter as well for accuracy.

SELECT *
FROM dbo.ActivityStepLog
WHERE
   CONTAINS (LogContent, '-2147483535')
   and LogContent.value('(/BusinessRuleDecisionLog/SampleData1/DecisionLogID)[1]', 'int') = -2147483535

I sill need to research whether this fits all my filtering needs, but so far it looks good.

Sylvia


问:
Delete SharedPreferences File
I am allowing the user to create multiple SharedPreferences files, but I also would like the option for them to delete these files. I know I could use internal storage, but that is not my question.

My question is: "How can I delete in code or manually (not just clear) a SharedPreferences file?"

答:
```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    context.deleteSharedPreferences(preferencesKey);
} else {
    try {
        org.apache.commons.io.FileUtils.cleanDirectory(new File(context.getCacheDir().getParent() + "/shared_prefs/"));
    } catch (IOException e) {
        Log.e(TAG, "Cannot delete files in shared pref directory", e);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Delete SharedPreferences File


问:
ggplot2::geom_segment. How to set multiple sizes, say c(10,12)?
I'm plotting with ggplot a data frame of different actions (A,B) not mutually exclusive and have multiple Ids.
The activities often overlap within an Id, which might cause that some are not visible.

The data

```<code>df <- data.frame(id = c("id1", "id1", "id2", "id2"), x1 = c(10, 9, 12, 12 ), x2 = c(16, 17, 15, 19), type = c("A", "B", "A", "B"))
</code>```

The codes

```<code>library("ggplot2")
</code>```

This works:

```<code>ggplot2::ggplot() +
  geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = 10)
</code>```

Result: overlapping B and A. How to specify different geom_segment size?

Does not work:

```<code>ggplot2::ggplot() +
  geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = c(10,12,10,12))
</code>```

Error: Aesthetics must be either length 1 or the same as the data (2):
  size

答:
I think the placement of a ')' before size is what the issue was. It should be part of aes.

```<code>ggplot2::ggplot() +
geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id,
yend = id, size = c(10,12,10,12)))
</code>```

@aelwan raised a valid point. I have an edit using the position parameter.

```<code> ggplot(df) +
 geom_segment(aes(x = x1, xend = x2,
 y = id, yend = id, colour = type),size =10, position = position_dodge(width =
 .5))
</code>```

Body:
I'm plotting with ggplot a data frame of different actions (A,B) not mutually exclusive and have multiple Ids.
The activities often overlap within an Id, which might cause that some are not visible.

The data

df <- data.frame(id = c("id1", "id1", "id2", "id2"), x1 = c(10, 9, 12, 12 ), x2 = c(16, 17, 15, 19), type = c("A", "B", "A", "B"))

The codes

library("ggplot2")

This works:

ggplot2::ggplot() +
  geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = 10)

Result: overlapping B and A. How to specify different geom_segment size?

Does not work:

ggplot2::ggplot() +
  geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = c(10,12,10,12))

Error: Aesthetics must be either length 1 or the same as the data (2):
  size

Body:
I think the placement of a ')' before size is what the issue was. It should be part of aes.

ggplot2::ggplot() +
geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id,
yend = id, size = c(10,12,10,12)))

@aelwan raised a valid point. I have an edit using the position parameter.

 ggplot(df) +
 geom_segment(aes(x = x1, xend = x2,
 y = id, yend = id, colour = type),size =10, position = position_dodge(width =
 .5))


答:
It looks like your sizes map to activity types. In that case you can just put size=type in the aesthetic mapping like any other part of your graph, and then specify how the different sizes will work using scale_size_discrete:

```<code># Put all data and aesthetics that apply to the whole plot in the original
#   ggplot() call
ggplot2::ggplot(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id, size=type)) +
    geom_segment() +
    # A is drawn first so make it bigger
    scale_size_discrete(range=c(12, 8))
</code>```

Result:

Title: ggplot2::geom_segment. How to set multiple sizes, say c(10,12)?

Body:
It looks like your sizes map to activity types. In that case you can just put size=type in the aesthetic mapping like any other part of your graph, and then specify how the different sizes will work using scale_size_discrete:

# Put all data and aesthetics that apply to the whole plot in the original
#   ggplot() call
ggplot2::ggplot(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id, size=type)) +
    geom_segment() +
    # A is drawn first so make it bigger
    scale_size_discrete(range=c(12, 8))

Result:


问:
How to get ODATA to serialize NotMapped property
I have a WebAPI backend that provides inventory information, etc. to various clients, using ODATA v3 (I cannot use v4 due to a restriction in a component that we use).  The inventory database is quite large (100K+ records) and ODATA is great for server-side filtering, pagination, etc. and keeping the data transfers lean.

The inventory records have some properties that are not mapped, but rather calculated and populated on the fly as the queries are made.  For example:

```<code>[NotMapped]
public decimal RebateAmount { get; set; }
</code>```

The problem is that ODATA ignores any NotMapped properties, so they never get sent back to the clients.

I know this has been asked before, but that was a while ago now so I was hoping that support for this has been added by now or that somebody has a simple workaround (short of letting EF create these fields in the DB).

I have tried this ugly workaround, but it did not work (RebateAmount still does not get included by ODATA):

```<code>private decimal _rebateAmount;
public decimal RebateAmount { get {return _rebateAmount; } }

public void SetRebateAmount(decimal amount)
{
   _rebateAmount = amount;
}
</code>```

Is there a (preferably simple) way to include non-DB properties in ODATA result sets?

Edit 1/7/2017
For this to be useful in my scenario, ODATA needs to also include the calculated fields in its metadata, otherwise the auto-generated (client-side) proxy classes will not include them.

答:
I know this is an old post but in the WebApiConfig file just add the following and it will expose the "NotMapped" property.

```<code>builder.StructuralTypes.First(t => t.ClrType == typeof(YourModel)).AddProperty(typeof(YourModel).GetProperty("RebateAmount"));
</code>```

Where "builder" is your IEdmModel. Most likely in your "GetEdmModel" method.

Body:
I have a WebAPI backend that provides inventory information, etc. to various clients, using ODATA v3 (I cannot use v4 due to a restriction in a component that we use).  The inventory database is quite large (100K+ records) and ODATA is great for server-side filtering, pagination, etc. and keeping the data transfers lean.

The inventory records have some properties that are not mapped, but rather calculated and populated on the fly as the queries are made.  For example:

[NotMapped]
public decimal RebateAmount { get; set; }

The problem is that ODATA ignores any NotMapped properties, so they never get sent back to the clients.

I know this has been asked before, but that was a while ago now so I was hoping that support for this has been added by now or that somebody has a simple workaround (short of letting EF create these fields in the DB).

I have tried this ugly workaround, but it did not work (RebateAmount still does not get included by ODATA):

private decimal _rebateAmount;
public decimal RebateAmount { get {return _rebateAmount; } }

public void SetRebateAmount(decimal amount)
{
   _rebateAmount = amount;
}

Is there a (preferably simple) way to include non-DB properties in ODATA result sets?

Edit 1/7/2017
For this to be useful in my scenario, ODATA needs to also include the calculated fields in its metadata, otherwise the auto-generated (client-side) proxy classes will not include them.

Body:
I know this is an old post but in the WebApiConfig file just add the following and it will expose the "NotMapped" property.

builder.StructuralTypes.First(t => t.ClrType == typeof(YourModel)).AddProperty(typeof(YourModel).GetProperty("RebateAmount"));

Where "builder" is your IEdmModel. Most likely in your "GetEdmModel" method.


问:
Do I need to impliment UnitOfWork for EF Core and if so is there a standard pattern somewhere?
I have read in some places that EF already implements it's own UnitOfWork and transactions.

I am looking at the following solutions:
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

I don't really like this because I don't want to have to manually add in every type of repo I have as that goes against the reason for the GenericRepository which I've already put in a lot of work to making generic already.

Also looking at the UnitOfWork Attribute solution described here but backing away because of the reasons discussed by the author himself:
Entity Framework Core 1.0 unit of work with Asp.Net Core middleware or Mvc filter

But let me try to lay out my question in the discussion below.

I have a Generic Repo and a Generic Service.  They are registered in my Startup like this:

```<code>services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddScoped(typeof(IGenericService<>), typeof(GenericService<>));
</code>```

My Generic Repo looks like this (leaving out Interfaces for brevity):

```<code>public enum FilteredSource
{
    All,
    GetAllIncluding,
}

public class GenericRepository<T> : IGenericRepository<T>
    where T: BaseEntity
{
    protected readonly ApplicationDbContext _context;
    protected DbSet<T> _dbSet;

    public GenericRepository(ApplicationDbContext context)
    {
        _context = context;
        _dbSet = context.Set<T>();
    }

    // no eager loading
    private IQueryable<T> All => _dbSet.Cast<T>();

    // eager loading
    private IQueryable<T> GetAllIncluding(
        params Expression<Func<T, object>>[] includeProperties) =>
         includeProperties.Aggregate(All, (currentEntity, includeProperty) => currentEntity.Include(includeProperty));

    // eager loading
    public async Task<T> GetSingleIncludingAsync(
        long id, params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> entities = GetAllIncluding(includeProperties);
        //return await Filter<long>(entities, x => x.Id, id).FirstOrDefaultAsync();
        return await entities.SingleOrDefaultAsync(e => e.Id == id);
    }

    // no eager loading
    public async Task<T> GetSingleIncludingAsync(long id)
    {
        return await _dbSet.SingleOrDefaultAsync(e => e.Id == id);
    }

    /// <summary>
    /// Takes in a lambda selector and let's you filter results from GetAllIncluding or All.
    /// </summary>
    /// <param name="selector">labmda expression to filter results by.</param>
    /// <param name="getFilteredSource">All or GetAllIncluding as the method to get results from.</param>
    /// <param name="includeProperties">array of eager load lamda expressions.</param>
    /// <returns></returns>
    public async Task<IEnumerable<T>> GetFiltered(
        Expression<Func<T, bool>> selector, FilteredSource filteredSource,
        Expression<Func<T, object>>[] includeProperties = null)
    {
        var results = default(IEnumerable<T>);
        switch (filteredSource)
        {
            case FilteredSource.All:
                results = All.Where(selector);
                break;
            case FilteredSource.GetAllIncluding:
                results = GetAllIncluding(includeProperties).Where(selector);
                break;
        }
        return await results.AsQueryable().ToListAsync();
    }

    public async Task<IEnumerable<T>> GetUnFiltered(
        FilteredSource filteredSource,
        Expression<Func<T, object>>[] includeProperties = null)
    {
        var results = default(IEnumerable<T>);
        switch (filteredSource)
        {
            case FilteredSource.All:
                results = All;
                break;
            case FilteredSource.GetAllIncluding:
                results = GetAllIncluding(includeProperties);
                break;
        }
        return await results.AsQueryable().ToListAsync();
    }

    public async Task<T> InsertAsync(T entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException($"No {nameof(T)}  Entity was provided for Insert");
        }
        await _dbSet.AddAsync(entity);
        return entity;
    }

    public async Task<T> UpdateAsync(T entity)
    {
        T entityToUpdate = await
            _dbSet.AsNoTracking().SingleOrDefaultAsync(e => e.Id == entity.Id);
        if (entityToUpdate == null)
        {
            //return null;
            throw new ArgumentNullException($"No {nameof(T)}  Entity was provided for Update");
        }

        _dbSet.Update(entity);
        return entity;
    }

    public async Task<T> DeleteAsync(T entity)
    {
        _dbSet.Remove(entity);
        return await Task.FromResult(entity);
    }

    public Task SaveAsync() => _context.SaveChangesAsync();
</code>```

}

Service Layer looks like this:

```<code>public class GenericService<T> : IGenericService<T>
    where T : BaseEntity
{
    private IGenericRepository<T> _genericRepo;

    public GenericService(IGenericRepository<T> genericRepo)
    {
        _genericRepo = genericRepo;
    }

    public async Task<IEnumerable<T>> GetFiltered(
        Expression<Func<T, bool>> selector, FilteredSource filteredSource,
        Expression<Func<T, object>>[] includeProperties = null)
    {
        return await _genericRepo.GetFiltered(selector, filteredSource,
            includeProperties);
    }

    public async Task<IEnumerable<T>> GetUnFiltered(
        FilteredSource filteredSource,
        Expression<Func<T, object>>[] includeProperties = null)
    {
        return await _genericRepo.GetUnFiltered(filteredSource,
            includeProperties);
    }

    // no eager loading
    public async Task<T> GetSingleIncludingAsync(long id)
    {
        return await _genericRepo.GetSingleIncludingAsync(id);
    }
    // eager loading
    public async Task<T> GetSingleIncludingAsync(long id, params Expression<Func<T, object>>[] includeProperties)
    {
        T entity = await _genericRepo.GetSingleIncludingAsync(id, includeProperties);
        //return await Filter<long>(entities, x => x.Id, id).FirstOrDefaultAsync();
        return entity;
    }

    public async Task<T> InsertAsync(T entity)
    {
        var result = await _genericRepo.InsertAsync(entity);
        await _genericRepo.SaveAsync();
        return entity;
    }

    public async Task<T> UpdateAsync(T entity)
    {
        var result = await _genericRepo.UpdateAsync(entity);
        if (result != null)
        {
            await _genericRepo.SaveAsync();
        }
        return result;
    }

    public async Task<T> DeleteAsync(T entity)
    {
        throw new NotImplementedException();
    }
}
</code>```

An example of a MVC Core Web API controller that uses the service looks like this:

```<code>[Route("api/[controller]")]
public class EmployeesController : Controller
{
    private IGenericService<Employee> _genericService;

    public EmployeesController(IGenericService<Employee> genericService)
    {
        _genericService = genericService;
    }

    // GET: api/employees
    [HttpGet]
    public async Task<IEnumerable<Employee>> GetEmployeesAsync(
            string firstName = null, string lastName = null)
    {
        return await _genericService.GetFiltered(
                e => (string.IsNullOrEmpty(firstName) || e.FirstName.Contains(firstName))
                && (string.IsNullOrEmpty(lastName) || e.LastName.Contains(lastName)),
                FilteredSource.GetAllIncluding,
                new Expression<Func<Employee, object>>[] { a => a.Organization,
                b => b.PayPlan,
                c => c.GradeRank,
                d => d.PositionTitle,
                e => e.Series,
                f => f.BargainingUnit }
            );
    }

    // GET api/employees/5
    [HttpGet("{id}", Name = "GetEmployeeById")]
    public async Task<IActionResult> GetEmployeeByIdAsync(long id)
    {
        var employee = await _genericService.GetSingleIncludingAsync(id,
            a => a.Organization,
            b => b.PayPlan,
            c => c.GradeRank,
            d => d.PositionTitle,
            e => e.Series,
            f => f.BargainingUnit);

        if (employee == null)
        {
            return NotFound();
        }
        else
        {
            return new ObjectResult(employee);
        }
    }

    // PUT api/employees/id
    [HttpPut("{id}")]
    public async Task<IActionResult> PutEmployeeAsync([FromBody] Employee emp)
    {
        var employee = await _genericService.UpdateAsync(emp);
        if (employee == null)
        {
            return NotFound();
        }

        return new ObjectResult(employee);
    }
}
</code>```

So here are my questions:
The way I understand it, UnitOfWork is used in case you bring in two repositories into a service or controller.  If you manipulate data in repo 1 and it passes, and then manipulate data in repo 2 and it fails (or visa versa) you want to roll everything back.

So far I am not using two repos. But if this situation occurs, it will be because I am bringing  in two GenericServices to a controller, which will in turn bring in two GenericRepos.

Now lets talk about scope.
I have to bring in my GenericRepo as Scoped. Not Singleton.  Because if I query an object on one request, and then try to update that object on the next request, I will get an error that the object cannot be updated because it is already being tracked by the Singleton Repo from the previous request.
So I bring it in Scoped as shown in the StartUp segment:

```<code>services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddScoped(typeof(IGenericService<>), typeof(GenericService<>));
</code>```

I also bring in the service as scoped.  Pretty much guessing I should bring it in as scoped also.

Now, if I bring in a GenericService of Type Employee -> which gets a GenericRepository of Type Employee into a controller and I also bring in GenericService of Type Case -> which gets a GenericRepository of Type Case, are these two different GenericRepos?  Or are they the same Repo?
Will they be treated as the same transaction and all pass or fail together?

Or do I need to manually implement UnitOfWork?

Another factor I think that goes into this is whether the following baked into Core DI line is Singleton or Scoped:

```<code>services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConn")));
</code>```

答:
You are right to use Scoped but see below: it's your ApplicationDbContext that must be scoped, the services and repos can be transient.

Since IGenericRepo<Employee> is a different type to IGenericRepo<Case> yes you will get two different GenericRepo<T>'s (and the same logic applies to the services).

But about the UnitOfWork pattern in the article you link, I don't get your comment that "I don't really like this because I don't want to have to manually add in every type of repo ..."

You could change the UoW code in the article to a GenericUnitOfWork<T1,T2> ?

Or you could take the view that for each controller which needs to write to 2 repos, you write a UoW class specifically for it. Note that you can strip out the lazy getter code that the article uses in its UoW class, because your repos are already created for you anyway by the services container, so the UoW reduces to only a few lines of mostly-boiler code anyway.

```<code>public class UnitOfWork<T1,T2> : IDisposable
{
    ApplicationDbContext context;
    GenericRepo<T1> Repo1 {get; private set;}
    GenericRepo<T2> Repo2 {get; private set;}

    public UnitOfWork(ApplicationDbContext context)
    {
      this.context=context;
      Repo1 =new GenericRepo<T1>(context)
      Repo2 =new GenericRepo<T2>(context)
    }

    public void Save()
    {
        context.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
</code>```

But here's the important thing: the UoW pattern as presented in the article depends crucially on both repos using the same DbContext (otherwise it would be a distributed transaction and requires more code)

So it's important that your ApplicationDbContext is scoped:

```<code>services.AddScoped(typeof(ApplicationDbContext), typeof(ApplicationDbContext));
</code>```

However, you do have to be sure that every controller in your application can happily accept this constraint that it should only need one underlying ApplicationDbContext. For must cases, it should be fine.

Finally, you might as well be explicit that the real dependency is the DbContext:

```<code>public class EmployeesController : Controller
{
  UnitofWork<T1,T2> uow;

  public EmployeesController(ApplicationDbContext dbContext)
  {
    this.uow= new UnitofWork<Employee,Case>(dbContext)
  }
//...
</code>```

Body:
I have read in some places that EF already implements it's own UnitOfWork and transactions.

I am looking at the following solutions:
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

I don't really like this because I don't want to have to manually add in every type of repo I have as that goes against the reason for the GenericRepository which I've already put in a lot of work to making generic already.

Also looking at the UnitOfWork Attribute solution described here but backing away because of the reasons discussed by the author himself:
Entity Framework Core 1.0 unit of work with Asp.Net Core middleware or Mvc filter

But let me try to lay out my question in the discussion below.

I have a Generic Repo and a Generic Service.  They are registered in my Startup like this:

services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddScoped(typeof(IGenericService<>), typeof(GenericService<>));

My Generic Repo looks like this (leaving out Interfaces for brevity):

public enum FilteredSource
{
    All,
    GetAllIncluding,
}

public class GenericRepository<T> : IGenericRepository<T>
    where T: BaseEntity
{
    protected readonly ApplicationDbContext _context;
    protected DbSet<T> _dbSet;

    public GenericRepository(ApplicationDbContext context)
    {
        _context = context;
        _dbSet = context.Set<T>();
    }

    // no eager loading
    private IQueryable<T> All => _dbSet.Cast<T>();

    // eager loading
    private IQueryable<T> GetAllIncluding(
        params Expression<Func<T, object>>[] includeProperties) =>
         includeProperties.Aggregate(All, (currentEntity, includeProperty) => currentEntity.Include(includeProperty));

    // eager loading
    public async Task<T> GetSingleIncludingAsync(
        long id, params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> entities = GetAllIncluding(includeProperties);
        //return await Filter<long>(entities, x => x.Id, id).FirstOrDefaultAsync();
        return await entities.SingleOrDefaultAsync(e => e.Id == id);
    }

    // no eager loading
    public async Task<T> GetSingleIncludingAsync(long id)
    {
        return await _dbSet.SingleOrDefaultAsync(e => e.Id == id);
    }

    ///
    /// Takes in a lambda selector and let's you filter results from GetAllIncluding or All.
    ///
    /// <param name="selector">labmda expression to filter results by.</param>
    /// <param name="getFilteredSource">All or GetAllIncluding as the method to get results from.</param>
    /// <param name="includeProperties">array of eager load lamda expressions.</param>
    /// <returns></returns>
    public async Task<IEnumerable<T>> GetFiltered(
        Expression<Func<T, bool>> selector, FilteredSource filteredSource,
        Expression<Func<T, object>>[] includeProperties = null)
    {
        var results = default(IEnumerable<T>);
        switch (filteredSource)
        {
            case FilteredSource.All:
                results = All.Where(selector);
                break;
            case FilteredSource.GetAllIncluding:
                results = GetAllIncluding(includeProperties).Where(selector);
                break;
        }
        return await results.AsQueryable().ToListAsync();
    }

    public async Task<IEnumerable<T>> GetUnFiltered(
        FilteredSource filteredSource,
        Expression<Func<T, object>>[] includeProperties = null)
    {
        var results = default(IEnumerable<T>);
        switch (filteredSource)
        {
            case FilteredSource.All:
                results = All;
                break;
            case FilteredSource.GetAllIncluding:
                results = GetAllIncluding(includeProperties);
                break;
        }
        return await results.AsQueryable().ToListAsync();
    }

    public async Task<T> InsertAsync(T entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException($"No {nameof(T)}  Entity was provided for Insert");
        }
        await _dbSet.AddAsync(entity);
        return entity;
    }

    public async Task<T> UpdateAsync(T entity)
    {
        T entityToUpdate = await
            _dbSet.AsNoTracking().SingleOrDefaultAsync(e => e.Id == entity.Id);
        if (entityToUpdate == null)
        {
            //return null;
            throw new ArgumentNullException($"No {nameof(T)}  Entity was provided for Update");
        }

        _dbSet.Update(entity);
        return entity;
    }

    public async Task<T> DeleteAsync(T entity)
    {
        _dbSet.Remove(entity);
        return await Task.FromResult(entity);
    }

    public Task SaveAsync() => _context.SaveChangesAsync();

}

Service Layer looks like this:

public class GenericService<T> : IGenericService<T>
    where T : BaseEntity
{
    private IGenericRepository<T> _genericRepo;

    public GenericService(IGenericRepository<T> genericRepo)
    {
        _genericRepo = genericRepo;
    }

    public async Task<IEnumerable<T>> GetFiltered(
        Expression<Func<T, bool>> selector, FilteredSource filteredSource,
        Expression<Func<T, object>>[] includeProperties = null)
    {
        return await _genericRepo.GetFiltered(selector, filteredSource,
            includeProperties);
    }

    public async Task<IEnumerable<T>> GetUnFiltered(
        FilteredSource filteredSource,
        Expression<Func<T, object>>[] includeProperties = null)
    {
        return await _genericRepo.GetUnFiltered(filteredSource,
            includeProperties);
    }

    // no eager loading
    public async Task<T> GetSingleIncludingAsync(long id)
    {
        return await _genericRepo.GetSingleIncludingAsync(id);
    }
    // eager loading
    public async Task<T> GetSingleIncludingAsync(long id, params Expression<Func<T, object>>[] includeProperties)
    {
        T entity = await _genericRepo.GetSingleIncludingAsync(id, includeProperties);
        //return await Filter<long>(entities, x => x.Id, id).FirstOrDefaultAsync();
        return entity;
    }

    public async Task<T> InsertAsync(T entity)
    {
        var result = await _genericRepo.InsertAsync(entity);
        await _genericRepo.SaveAsync();
        return entity;
    }

    public async Task<T> UpdateAsync(T entity)
    {
        var result = await _genericRepo.UpdateAsync(entity);
        if (result != null)
        {
            await _genericRepo.SaveAsync();
        }
        return result;
    }

    public async Task<T> DeleteAsync(T entity)
    {
        throw new NotImplementedException();
    }
}

An example of a MVC Core Web API controller that uses the service looks like this:

[Route("api/[controller]")]
public class EmployeesController : Controller
{
    private IGenericService<Employee> _genericService;

    public EmployeesController(IGenericService<Employee> genericService)
    {
        _genericService = genericService;
    }

    // GET: api/employees
    [HttpGet]
    public async Task<IEnumerable<Employee>> GetEmployeesAsync(
            string firstName = null, string lastName = null)
    {
        return await _genericService.GetFiltered(
                e => (string.IsNullOrEmpty(firstName) || e.FirstName.Contains(firstName))
                && (string.IsNullOrEmpty(lastName) || e.LastName.Contains(lastName)),
                FilteredSource.GetAllIncluding,
                new Expression<Func<Employee, object>>[] { a => a.Organization,
                b => b.PayPlan,
                c => c.GradeRank,
                d => d.PositionTitle,
                e => e.Series,
                f => f.BargainingUnit }
            );
    }

    // GET api/employees/5
    [HttpGet("{id}", Name = "GetEmployeeById")]
    public async Task<IActionResult> GetEmployeeByIdAsync(long id)
    {
        var employee = await _genericService.GetSingleIncludingAsync(id,
            a => a.Organization,
            b => b.PayPlan,
            c => c.GradeRank,
            d => d.PositionTitle,
            e => e.Series,
            f => f.BargainingUnit);

        if (employee == null)
        {
            return NotFound();
        }
        else
        {
            return new ObjectResult(employee);
        }
    }

    // PUT api/employees/id
    [HttpPut("{id}")]
    public async Task<IActionResult> PutEmployeeAsync([FromBody] Employee emp)
    {
        var employee = await _genericService.UpdateAsync(emp);
        if (employee == null)
        {
            return NotFound();
        }

        return new ObjectResult(employee);
    }
}

So here are my questions:
The way I understand it, UnitOfWork is used in case you bring in two repositories into a service or controller.  If you manipulate data in repo 1 and it passes, and then manipulate data in repo 2 and it fails (or visa versa) you want to roll everything back.

So far I am not using two repos. But if this situation occurs, it will be because I am bringing  in two GenericServices to a controller, which will in turn bring in two GenericRepos.

Now lets talk about scope.
I have to bring in my GenericRepo as Scoped. Not Singleton.  Because if I query an object on one request, and then try to update that object on the next request, I will get an error that the object cannot be updated because it is already being tracked by the Singleton Repo from the previous request.
So I bring it in Scoped as shown in the StartUp segment:

services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddScoped(typeof(IGenericService<>), typeof(GenericService<>));

I also bring in the service as scoped.  Pretty much guessing I should bring it in as scoped also.

Now, if I bring in a GenericService of Type Employee -> which gets a GenericRepository of Type Employee into a controller and I also bring in GenericService of Type Case -> which gets a GenericRepository of Type Case, are these two different GenericRepos?  Or are they the same Repo?
Will they be treated as the same transaction and all pass or fail together?

Or do I need to manually implement UnitOfWork?

Another factor I think that goes into this is whether the following baked into Core DI line is Singleton or Scoped:

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConn")));

Body:
You are right to use Scoped but see below: it's your ApplicationDbContext that must be scoped, the services and repos can be transient.

Since IGenericRepo<Employee> is a different type to IGenericRepo<Case> yes you will get two different GenericRepo<T>'s (and the same logic applies to the services).

But about the UnitOfWork pattern in the article you link, I don't get your comment that "I don't really like this because I don't want to have to manually add in every type of repo ..."

You could change the UoW code in the article to a GenericUnitOfWork<T1,T2> ?

Or you could take the view that for each controller which needs to write to 2 repos, you write a UoW class specifically for it. Note that you can strip out the lazy getter code that the article uses in its UoW class, because your repos are already created for you anyway by the services container, so the UoW reduces to only a few lines of mostly-boiler code anyway.

public class UnitOfWork<T1,T2> : IDisposable
{
    ApplicationDbContext context;
    GenericRepo<T1> Repo1 {get; private set;}
    GenericRepo<T2> Repo2 {get; private set;}

    public UnitOfWork(ApplicationDbContext context)
    {
      this.context=context;
      Repo1 =new GenericRepo<T1>(context)
      Repo2 =new GenericRepo<T2>(context)
    }

    public void Save()
    {
        context.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

But here's the important thing: the UoW pattern as presented in the article depends crucially on both repos using the same DbContext (otherwise it would be a distributed transaction and requires more code)

So it's important that your ApplicationDbContext is scoped:

services.AddScoped(typeof(ApplicationDbContext), typeof(ApplicationDbContext));

However, you do have to be sure that every controller in your application can happily accept this constraint that it should only need one underlying ApplicationDbContext. For must cases, it should be fine.

Finally, you might as well be explicit that the real dependency is the DbContext:

public class EmployeesController : Controller
{
  UnitofWork<T1,T2> uow;

  public EmployeesController(ApplicationDbContext dbContext)
  {
    this.uow= new UnitofWork<Employee,Case>(dbContext)
  }
//...


问:
Business Logic in a multi sites application (front-end, back-end 2, back-end3,back-end)
Suppose I have an application for courses management.

BACK-END STUDENT:

the student can view the courses, subscribe course, rate course...

BACK-END SCHOOL:

ths school can insert course, subscrive student to a cuorse....
upload fies for a course

BACK-END TEACHER:

the teacher can upload files to a cuorse....

.

As you can see some function is shared accros the applications.

Where i have to put the Business Logic?

I's possibile to wirite a "core business logic" and share it?
Or is better to create 3 completly different business logic?

答:
Are you familiar with the following principles?

Common Closure Principle CCP

Common Reuse Principle CRP

The short answer is (probably) that you want to have all your BL in one place, but orgainised in such a way that you follow CCP and CRP.

Yes it is possible to share and reuse the BL, but this will depend on how you architect the rest of the solution.

What these principles basically say (in your case) is that as your Teacher, Student and School objects are obviosuly part of the same domain they should probably go together.

Read this, it should help if you're new to the whole architecture thing: 5-Layer Architecture  (P.S - although it's ASP.NET centric there's still lots of basics that apply more widely).


问:
REST Best practice for sync log data in reverse order
Consider a backend system that stores logs of this form:

```<code>{"id": 541, "timestamp": 123, "status": "ok"}
{"id": 681, "timestamp": 124, "status": "waiting"}
...
</code>```

Assuming that there are MANY logs, a client (e.g. an Android app) wants to sync the log data stored at a server to the client's device for presentation. Since the most recent logs are of more interest to a user, the GET request should be paged and start with the most recent logs and walk its way towards the oldest ones.

What is a proper design for this situation? What about the following design?

Let the server response in reverse order, add parameters lastReceivedIdand size to the request and add a field more=true/false in the response that indicates whether there are more old logs available before the oldest log send in the current request. On the first request set lastRecivedId=-1 indicating that the server should answer with the most recent logs.

答:
Ship 'em all, let the server sort them out. The endpoint simply doesn't care what order they show up in, the server will handle that detail for presentation.

On the client, the client can choose to send the latest logs first, but that's simply coincidence. There's no requirement one way or the other.

There's also no need to send them in any particular order. If the client has a thousand log entries (in chronological order), it can send back batches of 100 starting at 900-1000, then 800-899, etc. The server will figure it out in the end.

Body:
Consider a backend system that stores logs of this form:

{"id": 541, "timestamp": 123, "status": "ok"}
{"id": 681, "timestamp": 124, "status": "waiting"}
...

Assuming that there are MANY logs, a client (e.g. an Android app) wants to sync the log data stored at a server to the client's device for presentation. Since the most recent logs are of more interest to a user, the GET request should be paged and start with the most recent logs and walk its way towards the oldest ones.

What is a proper design for this situation? What about the following design?

Let the server response in reverse order, add parameters lastReceivedIdand size to the request and add a field more=true/false in the response that indicates whether there are more old logs available before the oldest log send in the current request. On the first request set lastRecivedId=-1 indicating that the server should answer with the most recent logs.