问:
Overload -> arrow operator in shared_ptr<interface> instance with no pure virtual destructor in interface
I'm trying to overload the -> operator to eventually execute something along the lines:

```<code>MyInterface *myInstance = (MyInterface *)(new A());
myInstance->Toggle(); //this works wonderfully

std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);

//the next line doesn't compile, I would like to achieve something like this, but even
//sharedPtrWrapper.get()->Toggle();
//would be nice to achieve, is this possible?
sharedPtrWrapper->Toggle();

//this works:
sharedPtrWrapper->operator->()->Toggle();
</code>```

Note: I have no control over MyInterface, cannot implement the pure virtual destructor.

Here is what I tried (the below code runs):

```<code>#import <memory>
#import <iostream>

struct MyInterface {
    virtual bool Toggle() = 0;
};

class A : public MyInterface {
public:
    bool Toggle() {
        stateEnabled = !stateEnabled;
        std::cout<<"current state " << stateEnabled << std::endl;
        return true;
    }
private:
    bool stateEnabled = false;
};

template <typename T>
class Wrapper {
private:
    T *unsafePointer = nullptr;
public:
    Wrapper<T>()
    { }

    T *operator->() const {
        return unsafePointer;
    }
    T *getInner() {
        return unsafePointer;
    }
    Wrapper<T>(T *stuff) {
        unsafePointer = stuff;
    }

    ~Wrapper<T>() {}
};

int main(int argc, const char * argv[]) {
    MyInterface *myInstance = (MyInterface *)(new A());
    myInstance->Toggle();

    Wrapper<MyInterface> wrapperS(myInstance);
    wrapperS->Toggle();

    std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);
    sharedPtrWrapper->operator->()->Toggle();
    sharedPtrWrapper.operator->()->operator->()->Toggle();

    sharedPtrWrapper.get()->operator->()->Toggle();

    (*sharedPtrWrapper).operator->()->Toggle();

    return 0;
}
</code>```

Output:

```<code>current state 1
current state 0
current state 1
current state 0
current state 1
current state 0
Program ended with exit code: 0
</code>```

To reiterate:
This code doesn't compile:

```<code>sharedPtrWrapper->Toggle();
</code>```

How to make it compile?

Edit : I'm using a wrapper because I have no control over the MyInterface, I get it from a library, also shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>(myInstance); doesn't compile, because of the missing pure virtual destructor from the above mentioned interface.

Edit2: Example library usage in pseudocode:

```<code>void firstcallbackFromLib(Framework *framework) {
    MyInterface *myInstance = framework->getInstance();

    {
        Wrapper<MyInterface> wrapperS(myInstance);
        std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(wrapperS);
        //assign sharedPtrWrapper and framework to static instances
    }
}
void myFunction() {
    sharedPtrWrapper->Toggle(); //this doesn't work, this is what i'm trying to achieve
    sharedPtrWrapper->operator->()->Toggle(); //this ugly thing works

}
void lastUninitCallbackFromLibrary() {
    MyInterface *p = sharedPtrWrapper.get()->getInner();
    framework->releaseInterface(p);
    //etc
}
</code>```

答:
sharedPtrWrapper->Toggle(); doesn't compile because of operator-> chaining rules explained well in this answer. In principle: if your object is NOT a pointer, operator-> is called recursively, if it is a pointer, member access is performed. Now std::shared_ptr has overloaded operator-> to access the raw Wrapper<MyInterface>* pointer kept inside and when it is applied on it, it tries to access Toggle, which does not exist.

For clarity note that this code also will not compile:

```<code>Wrapper<MyInterface>* wrapper = new Wrapper<MyInterface>(myInstance);
wrapper->Toggle();
</code>```

You can do this however:

(*sharedPtrWrapper)->Toggle();

Body:
I'm trying to overload the -> operator to eventually execute something along the lines:

MyInterface *myInstance = (MyInterface *)(new A());
myInstance->Toggle(); //this works wonderfully

std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);

//the next line doesn't compile, I would like to achieve something like this, but even
//sharedPtrWrapper.get()->Toggle();
//would be nice to achieve, is this possible?
sharedPtrWrapper->Toggle();

//this works:
sharedPtrWrapper->operator->()->Toggle();

Note: I have no control over MyInterface, cannot implement the pure virtual destructor.

Here is what I tried (the below code runs):

#import <memory>
#import <iostream>

struct MyInterface {
    virtual bool Toggle() = 0;
};

class A : public MyInterface {
public:
    bool Toggle() {
        stateEnabled = !stateEnabled;
        std::cout<<"current state " << stateEnabled << std::endl;
        return true;
    }
private:
    bool stateEnabled = false;
};

template <typename T>
class Wrapper {
private:
    T *unsafePointer = nullptr;
public:
    Wrapper<T>()
    { }

    T *operator->() const {
        return unsafePointer;
    }
    T *getInner() {
        return unsafePointer;
    }
    Wrapper<T>(T *stuff) {
        unsafePointer = stuff;
    }

    ~Wrapper<T>() {}
};

int main(int argc, const char * argv[]) {
    MyInterface *myInstance = (MyInterface *)(new A());
    myInstance->Toggle();

    Wrapper<MyInterface> wrapperS(myInstance);
    wrapperS->Toggle();

    std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);
    sharedPtrWrapper->operator->()->Toggle();
    sharedPtrWrapper.operator->()->operator->()->Toggle();

    sharedPtrWrapper.get()->operator->()->Toggle();

    (*sharedPtrWrapper).operator->()->Toggle();

    return 0;
}

Output:

current state 1
current state 0
current state 1
current state 0
current state 1
current state 0
Program ended with exit code: 0

To reiterate:
This code doesn't compile:

sharedPtrWrapper->Toggle();

How to make it compile?

Edit : I'm using a wrapper because I have no control over the MyInterface, I get it from a library, also shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>(myInstance); doesn't compile, because of the missing pure virtual destructor from the above mentioned interface.

Edit2: Example library usage in pseudocode:

void firstcallbackFromLib(Framework *framework) {
    MyInterface *myInstance = framework->getInstance();

    {
        Wrapper<MyInterface> wrapperS(myInstance);
        std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(wrapperS);
        //assign sharedPtrWrapper and framework to static instances
    }
}
void myFunction() {
    sharedPtrWrapper->Toggle(); //this doesn't work, this is what i'm trying to achieve
    sharedPtrWrapper->operator->()->Toggle(); //this ugly thing works

}
void lastUninitCallbackFromLibrary() {
    MyInterface *p = sharedPtrWrapper.get()->getInner();
    framework->releaseInterface(p);
    //etc
}

Body:
sharedPtrWrapper->Toggle(); doesn't compile because of operator-> chaining rules explained well in this answer. In principle: if your object is NOT a pointer, operator-> is called recursively, if it is a pointer, member access is performed. Now std::shared_ptr has overloaded operator-> to access the raw Wrapper<MyInterface>* pointer kept inside and when it is applied on it, it tries to access Toggle, which does not exist.

For clarity note that this code also will not compile:

Wrapper<MyInterface>* wrapper = new Wrapper<MyInterface>(myInstance);
wrapper->Toggle();

You can do this however:

(*sharedPtrWrapper)->Toggle();


来源: stackexchange

问:
Error when trying to load Excel information
I have C# WinForms application that gets information from Excel sheet and stores it to my database, my code works fine on my PC but when I changed it an Error

System.InvalidOperationException: 'The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.'

display. I solved this problem by changing the project platform from x86 to x64 but when I launch the project with x64 I can't charge many files so I have to run it on x86. Guys any solutions?

Rq: My code:

```<code>String name = "Feuil1";
            String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                            textBox_path.Text +
                            ";Extended Properties='Excel 12.0 XML;HDR=YES;';";

            OleDbConnection con = new OleDbConnection(constr);
            OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
            con.Open();

            OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
            DataTable data = new DataTable();
            sda.Fill(data);
            dataview1.DataSource = data;
            using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["UR2k_CS.Properties.Settings.StoreConnectionString"].ConnectionString))
            {
                String query = "INSERT INTO dbo.Stock (RFID,name,refrence,prix,Stockdate) VALUES (@RFID,@name,@refrence,@prix,@Stockdate)";
                connection.Open();
                        for (int i=0;i<dataview1.Rows.Count-1;i++)
                        {

                            using (SqlCommand command = new SqlCommand(query, connection))
                            {
                                    if ((dataview1.Rows[i].Cells[0].Value.ToString()!=null)&&((!checkifexist(dataview1.Rows[i].Cells[0].Value.ToString()))) &&(dataview1.Rows[i].Cells[0].Value.ToString()!=""))
                                    {

                                        command.Parameters.AddWithValue("@RFID", dataview1.Rows[i].Cells[0].Value.ToString());
                                        command.Parameters.AddWithValue("@name", dataview1.Rows[i].Cells[1].Value.ToString());
                                        command.Parameters.AddWithValue("@refrence", dataview1.Rows[i].Cells[2].Value.ToString());
                                        command.Parameters.AddWithValue("@prix", dataview1.Rows[i].Cells[3].Value.ToString());

                                        command.Parameters.AddWithValue("@Stockdate", DateTime.Now);

                                        command.ExecuteNonQuery();
                                    }

                            }
                        }
                connection.Close();
            }
</code>```

答:
You need to download the 32 bit driver from here microsoft downloads (I think this is the correct one) but the difficulty you may run into is that a machine cannot have both the 64bit and 32bit versions installed side by side.

Using EPPlus is a more modern approach.

ContentLicense: CC BY-SA 4.0

Body:
I have C# WinForms application that gets information from Excel sheet and stores it to my database, my code works fine on my PC but when I changed it an Error

System.InvalidOperationException: 'The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.'

display. I solved this problem by changing the project platform from x86 to x64 but when I launch the project with x64 I can't charge many files so I have to run it on x86. Guys any solutions?

Rq: My code:

String name = "Feuil1";
            String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                            textBox_path.Text +
                            ";Extended Properties='Excel 12.0 XML;HDR=YES;';";

            OleDbConnection con = new OleDbConnection(constr);
            OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
            con.Open();

            OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
            DataTable data = new DataTable();
            sda.Fill(data);
            dataview1.DataSource = data;
            using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["UR2k_CS.Properties.Settings.StoreConnectionString"].ConnectionString))
            {
                String query = "INSERT INTO dbo.Stock (RFID,name,refrence,prix,Stockdate) VALUES (@RFID,@name,@refrence,@prix,@Stockdate)";
                connection.Open();
                        for (int i=0;i<dataview1.Rows.Count-1;i++)
                        {

                            using (SqlCommand command = new SqlCommand(query, connection))
                            {
                                    if ((dataview1.Rows[i].Cells[0].Value.ToString()!=null)&&((!checkifexist(dataview1.Rows[i].Cells[0].Value.ToString()))) &&(dataview1.Rows[i].Cells[0].Value.ToString()!=""))
                                    {

                                        command.Parameters.AddWithValue("@RFID", dataview1.Rows[i].Cells[0].Value.ToString());
                                        command.Parameters.AddWithValue("@name", dataview1.Rows[i].Cells[1].Value.ToString());
                                        command.Parameters.AddWithValue("@refrence", dataview1.Rows[i].Cells[2].Value.ToString());
                                        command.Parameters.AddWithValue("@prix", dataview1.Rows[i].Cells[3].Value.ToString());

                                        command.Parameters.AddWithValue("@Stockdate", DateTime.Now);

                                        command.ExecuteNonQuery();
                                    }

                            }
                        }
                connection.Close();
            }


问:
How to manage time in seconds in text format?
I’m reporting on one of the older telecom applications which exports the data in a text format.

I can convert the text to time.

Issue: The issue surfaces when I get a time in this format

-   :00,

-   :22,

The data is changing from :22 to 00:22:00 which changes 22 seconds to 22 minutes.

```<code>Sub FixTime()
    For Each cell In Range("A1:A10")
        cell.Value = "00" & cell.Value
    Next
End Sub
</code>```

This does not happen if I have 00:22:00 (minutes) and 01:22:00 (Hour).

答:
Welcome to SO Maciej. I'm hoping that I used some valid examples and this code will get you started!

```<code>Sub FixTime()
    Dim cell As Range

    For Each cell In Range("A1:A10")
        Select Case Len(cell.Value)
            Case 3 'seconds
                cell.Offset(0, 1).Value = TimeSerial(0, 0, Right(cell.Value, 2))
            Case 6 'minutes
                cell.Offset(0, 1).Value = TimeSerial(0, Mid(cell.Value, 2, 2), Right(cell.Value, 2))
            Case 8 'full time
                cell.Offset(0, 1).Value = TimeSerial(Left(cell.Value, 2), Mid(cell.Value, 4, 2), Right(cell.Value, 2))
        End Select
    Next
End Sub
</code>```

(the code has been adjusted using TimeSerial as per @Pᴇʜ's comment)

I'm converting values from column A and dropping the results into column B (feel free to skip the Offset(0,1) part to simply replace the existing values):

Body:
I’m reporting on one of the older telecom applications which exports the data in a text format.

I can convert the text to time.

Issue: The issue surfaces when I get a time in this format

-   :00,

-   :22,

The data is changing from :22 to 00:22:00 which changes 22 seconds to 22 minutes.

Sub FixTime()
    For Each cell In Range("A1:A10")
        cell.Value = "00" & cell.Value
    Next
End Sub

This does not happen if I have 00:22:00 (minutes) and 01:22:00 (Hour).

Body:
Welcome to SO Maciej. I'm hoping that I used some valid examples and this code will get you started!

Sub FixTime()
    Dim cell As Range

    For Each cell In Range("A1:A10")
        Select Case Len(cell.Value)
            Case 3 'seconds
                cell.Offset(0, 1).Value = TimeSerial(0, 0, Right(cell.Value, 2))
            Case 6 'minutes
                cell.Offset(0, 1).Value = TimeSerial(0, Mid(cell.Value, 2, 2), Right(cell.Value, 2))
            Case 8 'full time
                cell.Offset(0, 1).Value = TimeSerial(Left(cell.Value, 2), Mid(cell.Value, 4, 2), Right(cell.Value, 2))
        End Select
    Next
End Sub

(the code has been adjusted using TimeSerial as per @Pᴇʜ's comment)

I'm converting values from column A and dropping the results into column B (feel free to skip the Offset(0,1) part to simply replace the existing values):


问:
jQuery click events firing multiple times
I'm attempting to write a video poker game in Javascript as a way of getting the basics of it down, and I've run into a problem where the jQuery click event handlers are firing multiple times.

They're attached to buttons for placing a bet, and it works fine for placing a bet on the first hand during a game (firing only once); but in betting for the second hand, it fires the click event twice each time a bet or place bet button is pressed (so twice the correct amount is bet for each press).  Overall, it follows this pattern for number of times the click event is fired when pressing a bet button once--where the ith term of the sequence is for the betting of the ith hand from the beginning of the game: 1, 2, 4, 7, 11, 16, 22, 29, 37, 46, which appears to be n(n+1)/2 + 1 for whatever that's worth--and I wasn't smart enough to figure that out, I used OEIS. :)

Here's the function with the click event handlers that are acting up; hopefully it's easy to understand (let me know if not, I want to get better at that as well):

```<code>/** The following function keeps track of bet buttons that are pressed, until place button is pressed to place bet. **/
function pushingBetButtons() {
    $("#money").text("Money left: $" + player.money); // displays money player has left

    $(".bet").click(function() {
        var amount = 0; // holds the amount of money the player bet on this click
        if($(this).attr("id") == "bet1") { // the player just bet $1
            amount = 1;
        } else if($(this).attr("id") == "bet5") { // etc.
            amount = 5;
        } else if($(this).attr("id") == "bet25") {
            amount = 25;
        } else if($(this).attr("id") == "bet100") {
            amount = 100;
        } else if($(this).attr("id") == "bet500") {
            amount = 500;
        } else if($(this).attr("id") == "bet1000") {
            amount = 1000;
        }
        if(player.money >= amount) { // check whether the player has this much to bet
            player.bet += amount; // add what was just bet by clicking that button to the total bet on this hand
            player.money -= amount; // and, of course, subtract it from player's current pot
            $("#money").text("Money left: $" + player.money); // then redisplay what the player has left
        } else {
            alert("You don't have $" + amount + " to bet.");
        }
    });

    $("#place").click(function() {
        if(player.bet == 0) { // player didn't bet anything on this hand
            alert("Please place a bet first.");
        } else {
            $("#card_para").css("display", "block"); // now show the cards
            $(".card").bind("click", cardClicked); // and set up the event handler for the cards
            $("#bet_buttons_para").css("display", "none"); // hide the bet buttons and place bet button
            $("#redraw").css("display", "block"); // and reshow the button for redrawing the hand
            player.bet = 0; // reset the bet for betting on the next hand
            drawNewHand(); // draw the cards
        }
    });
}
</code>```

Please let me know if you have any ideas or suggestions, or if the solution to my problem is similar to a solution to another problem on here (I've looked at many similarly titled threads and had no luck in finding a solution that could work for me).

答:
In case this works fine</p>

```<code>$( "#ok" ).bind( "click", function() {
    console.log("click");
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm attempting to write a video poker game in Javascript as a way of getting the basics of it down, and I've run into a problem where the jQuery click event handlers are firing multiple times.

They're attached to buttons for placing a bet, and it works fine for placing a bet on the first hand during a game (firing only once); but in betting for the second hand, it fires the click event twice each time a bet or place bet button is pressed (so twice the correct amount is bet for each press).  Overall, it follows this pattern for number of times the click event is fired when pressing a bet button once--where the ith term of the sequence is for the betting of the ith hand from the beginning of the game: 1, 2, 4, 7, 11, 16, 22, 29, 37, 46, which appears to be n(n+1)/2 + 1 for whatever that's worth--and I wasn't smart enough to figure that out, I used OEIS. :)

Here's the function with the click event handlers that are acting up; hopefully it's easy to understand (let me know if not, I want to get better at that as well):

/** The following function keeps track of bet buttons that are pressed, until place button is pressed to place bet. **/
function pushingBetButtons() {
    $("#money").text("Money left: $" + player.money); // displays money player has left

    $(".bet").click(function() {
        var amount = 0; // holds the amount of money the player bet on this click
        if($(this).attr("id") == "bet1") { // the player just bet $1
            amount = 1;
        } else if($(this).attr("id") == "bet5") { // etc.
            amount = 5;
        } else if($(this).attr("id") == "bet25") {
            amount = 25;
        } else if($(this).attr("id") == "bet100") {
            amount = 100;
        } else if($(this).attr("id") == "bet500") {
            amount = 500;
        } else if($(this).attr("id") == "bet1000") {
            amount = 1000;
        }
        if(player.money >= amount) { // check whether the player has this much to bet
            player.bet += amount; // add what was just bet by clicking that button to the total bet on this hand
            player.money -= amount; // and, of course, subtract it from player's current pot
            $("#money").text("Money left: $" + player.money); // then redisplay what the player has left
        } else {
            alert("You don't have $" + amount + " to bet.");
        }
    });

    $("#place").click(function() {
        if(player.bet == 0) { // player didn't bet anything on this hand
            alert("Please place a bet first.");
        } else {
            $("#card_para").css("display", "block"); // now show the cards
            $(".card").bind("click", cardClicked); // and set up the event handler for the cards
            $("#bet_buttons_para").css("display", "none"); // hide the bet buttons and place bet button
            $("#redraw").css("display", "block"); // and reshow the button for redrawing the hand
            player.bet = 0; // reset the bet for betting on the next hand
            drawNewHand(); // draw the cards
        }
    });
}

Please let me know if you have any ideas or suggestions, or if the solution to my problem is similar to a solution to another problem on here (I've looked at many similarly titled threads and had no luck in finding a solution that could work for me).

Body:
In case this works fine

$( "#ok" ).bind( "click", function() {
    console.log("click");
});


问:
Dark Theme through out the app in flutter
I am making an app where i want to have dark theme for app on switch.I have written the code and is working fine but just for one page.When i go back and open that page again it shows "BAD STATE ERROR". when i searched on stackoverflow, many of them suggested to use shared preferences.But i am unable to implement it.

CODE

```<code>    class Settings extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    // TODO: implement build
    return StreamBuilder(

      stream: bloc.darkThemeEnabled,
      initialData: false,
      builder: (context,snapshot) => MaterialApp(
        debugShowCheckedModeBanner: false ,
        theme: snapshot.data?ThemeData.dark():ThemeData.light(),
        home: HomePage(snapshot.data),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
 final bool darkThemeEnabled;

  HomePage(this.darkThemeEnabled);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(

        title: Text('Settings'),
      ),
      body: ListView(
        children: <Widget>[
          ListTile(
              title: Text("Dark Theme",style:
              TextStyle(
                  fontSize: 20.0
              ),),
              trailing: Switch(
                value: darkThemeEnabled,
                onChanged:bloc.changeTheme,
              )
          )],
      ),
    );
  }
}

class Bloc{
  final _themecontroller = StreamController<bool>();
  get changeTheme => _themecontroller.sink.add;
  get darkThemeEnabled => _themecontroller.stream;

}

final bloc = Bloc();
</code>```

答:
Exampe on DartPad</p>

```<code>class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  ThemeMode _themeMode = ThemeMode.light;

  _handleThemeModeChanged(ThemeMode mode) {
    setState(() {
      _themeMode = mode;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light(),
      darkTheme: ThemeData.dark(),
      themeMode: _themeMode,
      debugShowCheckedModeBanner: false,
      home: HomePage(
          themeMode: _themeMode, onThemeModeChanged: _handleThemeModeChanged),
    );
  }
}

</code>```

```<code>class HomePage extends StatelessWidget {
  const HomePage({Key key, this.themeMode, this.onThemeModeChanged})
      : super(key: key);

  final ThemeMode themeMode;
  final ThemeModeChanged onThemeModeChanged;

  onSwitch(bool value) {
    final newThemeMode = value ? ThemeMode.dark : ThemeMode.light;

    onThemeModeChanged(newThemeMode);
  }

  @override
  Widget build(BuildContext context) {
    final isDarkMode = themeMode == ThemeMode.dark;

    return Scaffold(
      appBar: AppBar(
        title: Text('Settings'),
      ),
      body: ListView(
        children: <Widget>[
          ListTile(
              title: Text(
                "Dark Theme",
                style: TextStyle(fontSize: 20.0),
              ),
              trailing: Switch(value: isDarkMode, onChanged: onSwitch))
        ],
      ),
    );
  }
}

</code>```

Body:
I am making an app where i want to have dark theme for app on switch.I have written the code and is working fine but just for one page.When i go back and open that page again it shows "BAD STATE ERROR". when i searched on stackoverflow, many of them suggested to use shared preferences.But i am unable to implement it.

CODE

    class Settings extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    // TODO: implement build
    return StreamBuilder(

      stream: bloc.darkThemeEnabled,
      initialData: false,
      builder: (context,snapshot) => MaterialApp(
        debugShowCheckedModeBanner: false ,
        theme: snapshot.data?ThemeData.dark():ThemeData.light(),
        home: HomePage(snapshot.data),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
 final bool darkThemeEnabled;

  HomePage(this.darkThemeEnabled);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(

        title: Text('Settings'),
      ),
      body: ListView(
        children: <Widget>[
          ListTile(
              title: Text("Dark Theme",style:
              TextStyle(
                  fontSize: 20.0
              ),),
              trailing: Switch(
                value: darkThemeEnabled,
                onChanged:bloc.changeTheme,
              )
          )],
      ),
    );
  }
}

class Bloc{
  final _themecontroller = StreamController<bool>();
  get changeTheme => _themecontroller.sink.add;
  get darkThemeEnabled => _themecontroller.stream;

}

final bloc = Bloc();

Body:
Exampe on DartPad

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  ThemeMode _themeMode = ThemeMode.light;

  _handleThemeModeChanged(ThemeMode mode) {
    setState(() {
      _themeMode = mode;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light(),
      darkTheme: ThemeData.dark(),
      themeMode: _themeMode,
      debugShowCheckedModeBanner: false,
      home: HomePage(
          themeMode: _themeMode, onThemeModeChanged: _handleThemeModeChanged),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key key, this.themeMode, this.onThemeModeChanged})
      : super(key: key);

  final ThemeMode themeMode;
  final ThemeModeChanged onThemeModeChanged;

  onSwitch(bool value) {
    final newThemeMode = value ? ThemeMode.dark : ThemeMode.light;

    onThemeModeChanged(newThemeMode);
  }

  @override
  Widget build(BuildContext context) {
    final isDarkMode = themeMode == ThemeMode.dark;

    return Scaffold(
      appBar: AppBar(
        title: Text('Settings'),
      ),
      body: ListView(
        children: <Widget>[
          ListTile(
              title: Text(
                "Dark Theme",
                style: TextStyle(fontSize: 20.0),
              ),
              trailing: Switch(value: isDarkMode, onChanged: onSwitch))
        ],
      ),
    );
  }
}


问:
Using sed to replace <? with <?php
I'm trying to programmatically replace <? with <?php in a bunch of file, but my sed regex isn't behaving like I expected. Can you tell me what's wrong with it?

I'm testing it on the command line here:

```<code>$ sed -e 's/<\?/<\?php/g'
<?
<?php?<?php
d
<?phpd<?php
</code>```

答:
I don't think you need the escapes on the ?:</p>

```<code>sed -e 's/<?/<?php/g'
</code>```

Title: Using sed to replace <? with <?php

Body:
I'm trying to programmatically replace <? with <?php in a bunch of file, but my sed regex isn't behaving like I expected. Can you tell me what's wrong with it?

I'm testing it on the command line here:

$ sed -e 's/<\?/<\?php/g'
<?
<?php?<?php
d
<?phpd<?php

Body:
I don't think you need the escapes on the ?:

sed -e 's/<?/<?php/g'


问:
Send two parameters from controller to Ajax | Asp.Net
I have a question is it possible to send two parameters from controller to Ajax for view?

I have two variables that store data

I need an optimal solution

I tried:

Controller:

```<code> [HttpGet]
        public async Task<ActionResult> GetDepartmentAndManager(string userId)
        {

            var danePracownika = _uzytkownicyContext.Uzytkownicy
                                                    .Where(x => x.Id == IntIdCzlowieka)
                                                    .Select(s => new
                                                    {
                                                        UserDepartament = s.Departament,
                                                        UserManager = s.ManagerLogin

                                                    });

            var userDetailsAU = _ecpContext.AC_Merge_V
                                           .Where(x => x.Id == IntIdCzlowieka)
                                           .Select(s => new
                                           {
                                               WymiarEtatu = s.WymiarEtatu,
                                               NormaDzienna = s.NormaDzienna

                                           });

            return Json(danePracownika, userDetailsAU);
        }

</code>```

Ajax | javascript / View:

```<code>  $.ajax({

            url: "@Url.Action("GetDepartmentAndManager", "Uzytkownicy")",
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {"userId": JSON.stringify(userId)},
            cache: false,
            success: function (data, user) {
                $("#Id_department")
                    .dxTextBox("instance")
                    .option("value", data[0].UserDepartament);
                $("#Id_manager")
                    .dxTextBox("instance")
                   .option("value", data[0].UserManager);
            }

        });
</code>```

答:
Return those values as properties on an object:

```<code>return Json(new { data = danePracownika, user = userDetailsAU });
</code>```

Then in the response they will be properties on the result:

```<code>success: function (result) {
    $("#Id_department")
        .dxTextBox("instance")
        .option("value", result.data[0].UserDepartament);
    $("#Id_manager")
        .dxTextBox("instance")
        .option("value", result.data[0].UserManager);
    // I assume you also want to use result.user somewhere...
}
</code>```

Body:
I have a question is it possible to send two parameters from controller to Ajax for view?

I have two variables that store data

I need an optimal solution

I tried:

Controller:

 [HttpGet]
        public async Task<ActionResult> GetDepartmentAndManager(string userId)
        {

            var danePracownika = _uzytkownicyContext.Uzytkownicy
                                                    .Where(x => x.Id == IntIdCzlowieka)
                                                    .Select(s => new
                                                    {
                                                        UserDepartament = s.Departament,
                                                        UserManager = s.ManagerLogin

                                                    });

            var userDetailsAU = _ecpContext.AC_Merge_V
                                           .Where(x => x.Id == IntIdCzlowieka)
                                           .Select(s => new
                                           {
                                               WymiarEtatu = s.WymiarEtatu,
                                               NormaDzienna = s.NormaDzienna

                                           });

            return Json(danePracownika, userDetailsAU);
        }

Ajax | javascript / View:

  $.ajax({

            url: "@Url.Action("GetDepartmentAndManager", "Uzytkownicy")",
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {"userId": JSON.stringify(userId)},
            cache: false,
            success: function (data, user) {
                $("#Id_department")
                    .dxTextBox("instance")
                    .option("value", data[0].UserDepartament);
                $("#Id_manager")
                    .dxTextBox("instance")
                   .option("value", data[0].UserManager);
            }

        });

Body:
Return those values as properties on an object:

return Json(new { data = danePracownika, user = userDetailsAU });

Then in the response they will be properties on the result:

success: function (result) {
    $("#Id_department")
        .dxTextBox("instance")
        .option("value", result.data[0].UserDepartament);
    $("#Id_manager")
        .dxTextBox("instance")
        .option("value", result.data[0].UserManager);
    // I assume you also want to use result.user somewhere...
}


问:
i want operating multiple services with multiple domain and sub-domain
i have one linux VM instance in google cloud platform.

and i have multiple domin. example aaa.com, bbb.com

and i want multiple service and set sub-domains

```<code>service    port    subdomain
apache1    80      aa.aaa.com
apache2    81      bb.aaa.com
tomcat1    8080    cc.aaa.com
tomcat2    8081    dd.aaa.com
nodejs1    8000    ee.aaa.com
nodejs2    8001    ff.aaa.com
rshiny1    3838    aa.bbb.com
rshiny2    3839    bb.bbb.com
ftp1       21      cc.bbb.com
ftp2       20      dd.bbb.com
mariadb1   3306    ee.bbb.com
mariadb2   3307    ff.bbb.com
oracle1    1521    gg.bbb.com
oracle2    1522    hh.bbb.com
</code>```

if i use only apache web server, i can setting sub-domain in virtual host.

but this is many services. how can i setting all sub-domains?

in apache? node.js? dns?
please reply to my question.

thank you!

答:
This is what a reverse proxy is for. And it is fairly straightforward to configure Apache to do it.

Run a single Apache for the main front-end and have it serve the default http/https porst (80/443). Then use it to proxy vhost requests to individual services as follows:

```<code><VirtualHost *:80>
    ProxyRequests off
    ProxyPreserveHost On

    ServerName bb.aaa.com

    <Location />
        ProxyPass http://127.0.0.1:81/
        ProxyPassReverse http://127.0.0.1:81/
        Order allow,deny
        Allow from all
    </Location>
</VirtualHost>

<VirtualHost *:80>
    ProxyRequests off
    ProxyPreserveHost On

    ServerName cc.aaa.com

    <Location />
        ProxyPass http://127.0.0.1:8080/
        ProxyPassReverse http://127.0.0.1:8080/
        Order allow,deny
        Allow from all
    </Location>
</VirtualHost>

# ...
</code>```

Create one for each service. This way your server will route depending on the domain name in the request instead of the TCP port number.

Of course, if you do this you cannot use the default ports (80/443) for your internal services as your front-end Apache needs it. But you can also use the Apache running the service on the default ports as your proxy server.

Basically you will end up with this kind of setup:

```<code>                                         ┌────────────┐
                                    ┌┄┄┄┄┤ apache2:81 │
                                    ┆    └────────────┘
                                    ┆    ┌──────────────┐
                                    ├┄┄┄┄┤ tomcat1:8080 │
           ┌───────────────────┐    ┆    └──────────────┘
internet┄┄┄┤front-end apache:80├┄┄┄┄┤    ┌──────────────┐
           └───────────────────┘    ├┄┄┄┄┤ tomcat2:8081 │
                                    ┆    └──────────────┘
                                    ┆
                                    .
                                    .
</code>```

This type of setup is very flexible allowing you to implement things like load-balancing and routing services based on <Location> instead of domain name or port number. Before CORS, this was the standard way to implement microservices by using a single Apache or Nginx to route by location/url path.

Body:
i have one linux VM instance in google cloud platform.

and i have multiple domin. example aaa.com, bbb.com

and i want multiple service and set sub-domains

service    port    subdomain
apache1    80      aa.aaa.com
apache2    81      bb.aaa.com
tomcat1    8080    cc.aaa.com
tomcat2    8081    dd.aaa.com
nodejs1    8000    ee.aaa.com
nodejs2    8001    ff.aaa.com
rshiny1    3838    aa.bbb.com
rshiny2    3839    bb.bbb.com
ftp1       21      cc.bbb.com
ftp2       20      dd.bbb.com
mariadb1   3306    ee.bbb.com
mariadb2   3307    ff.bbb.com
oracle1    1521    gg.bbb.com
oracle2    1522    hh.bbb.com

if i use only apache web server, i can setting sub-domain in virtual host.

but this is many services. how can i setting all sub-domains?

in apache? node.js? dns?
please reply to my question.

thank you!

Body:
This is what a reverse proxy is for. And it is fairly straightforward to configure Apache to do it.

Run a single Apache for the main front-end and have it serve the default http/https porst (80/443). Then use it to proxy vhost requests to individual services as follows:

<VirtualHost *:80>
    ProxyRequests off
    ProxyPreserveHost On

    ServerName bb.aaa.com

    <Location />
        ProxyPass http://127.0.0.1:81/
        ProxyPassReverse http://127.0.0.1:81/
        Order allow,deny
        Allow from all
    </Location>
</VirtualHost>

<VirtualHost *:80>
    ProxyRequests off
    ProxyPreserveHost On

    ServerName cc.aaa.com

    <Location />
        ProxyPass http://127.0.0.1:8080/
        ProxyPassReverse http://127.0.0.1:8080/
        Order allow,deny
        Allow from all
    </Location>
</VirtualHost>

# ...

Create one for each service. This way your server will route depending on the domain name in the request instead of the TCP port number.

Of course, if you do this you cannot use the default ports (80/443) for your internal services as your front-end Apache needs it. But you can also use the Apache running the service on the default ports as your proxy server.

Basically you will end up with this kind of setup:

                                         ┌────────────┐
                                    ┌┄┄┄┄┤ apache2:81 │
                                    ┆    └────────────┘
                                    ┆    ┌──────────────┐
                                    ├┄┄┄┄┤ tomcat1:8080 │
           ┌───────────────────┐    ┆    └──────────────┘
internet┄┄┄┤front-end apache:80├┄┄┄┄┤    ┌──────────────┐
           └───────────────────┘    ├┄┄┄┄┤ tomcat2:8081 │
                                    ┆    └──────────────┘
                                    ┆
                                    .
                                    .

This type of setup is very flexible allowing you to implement things like load-balancing and routing services based on <Location> instead of domain name or port number. Before CORS, this was the standard way to implement microservices by using a single Apache or Nginx to route by location/url path.


问:
How to pass or condition in Web Service Endpoints - Acumatica
I Have a requirement to pull the orders based on the Order Type conditions.I'm able to get the data  by passing one order type,but i need to get the orders of  two order types,couldn't find Or condition to Implement.

Here the code.

```<code>private static SalesOrder SOStokItem(DateTimeSearch whereCondition, StringSearch Condition, int rowCount)
    {
        SalesOrder item = new SalesOrder()
        {
            RowNumber = new LongSearch { Condition = LongCondition.IsLessThan, Value = rowCount },
            ReturnBehavior = ReturnBehavior.OnlySpecified,
            OrderType = new StringReturn(),
            OrderNbr = new StringReturn(),
        };
        if (whereCondition != null)
            item.LastModified = whereCondition;
         if (Condition != null)
        {
             //item.OrderType = new StringSearch() { Condition = StringCondition.or, Value = "RC" };
            //item.OrderType = new StringSearch() { Value = "RW" };
        }
        return item;
    }
</code>```

答:
The SOAP API doesn't include or filter conditions on string fields.
You need to issue two SOAP requests to filter the sales orders with an or condition.

Body:
I Have a requirement to pull the orders based on the Order Type conditions.I'm able to get the data  by passing one order type,but i need to get the orders of  two order types,couldn't find Or condition to Implement.

Here the code.

private static SalesOrder SOStokItem(DateTimeSearch whereCondition, StringSearch Condition, int rowCount)
    {
        SalesOrder item = new SalesOrder()
        {
            RowNumber = new LongSearch { Condition = LongCondition.IsLessThan, Value = rowCount },
            ReturnBehavior = ReturnBehavior.OnlySpecified,
            OrderType = new StringReturn(),
            OrderNbr = new StringReturn(),
        };
        if (whereCondition != null)
            item.LastModified = whereCondition;
         if (Condition != null)
        {
             //item.OrderType = new StringSearch() { Condition = StringCondition.or, Value = "RC" };
            //item.OrderType = new StringSearch() { Value = "RW" };
        }
        return item;
    }


问:
Implementing a Dynamic Plugin Manager
I'm trying to create a plugin manager for c++ that checks a directory for shared libraries (dll,so,dylib) and checks if there is a plugin interface available to store the plugin and retrieve it later with.

I'm using boost::dll to import the dll, but I don't know how to set up the template better.

How do I use templates or some other method to add plugin interfaces to the plugin manager so it will check the shared libraries for the export alias name and store the shared library handle?

PluginInterface.hpp

class PluginInterface {
public:
  virtual void testPlugin() = 0;
};
```

<p>plugin.hpp source for "plugins_directory/plugin.dll"</p>

<pre class="lang-cpp prettyprint-override"><code>#include <boost/config.hpp> // for BOOST_SYMBOL_EXPORT
#include "pluginInterface.hpp"

namespace PluginNamespace {
class PluginClass : public PluginInterface {
  void testPlugin(){
    printf("Hello World!");
  }
}

extern "C" BOOST_SYMBOL_EXPORT PluginClass pluginName;
PluginClass pluginName;
}
</code>```

PluginManager.hpp

class InterfaceMethodsBase {
public:
  std::string pluginName;
  InterfaceMethodsBase(std::string s) { pluginName = s; }
  ~InterfaceMethodsBase() {}
  virtual void addPath(std::filesystem::path p) = 0;
};

template <class T> class InterfaceMethods : public InterfaceMethodsBase {
public:
  InterfaceMethods(std::string s) : InterfaceMethodsBase(s) {}
  ~InterfaceMethods() {}
  std::vector<boost::shared_ptr<T>> pluginPtrs;
  void addPath(std::filesystem::path p) {
    boost::filesystem::path lib_path(p.string().c_str());
    std::cout << "PLUGIN: Loading " << p << "\n";
    boost::shared_ptr<T> plugin;
    try {
      plugin = boost::dll::import<T>(lib_path, pluginName,
                                     boost::dll::load_mode::default_mode);
    } catch (...) {
      std::cout << "PLUGIN: Loading FAILED " << p << "\n";
    }
    if (plugin) {
      std::cout << "PLUGIN: Loading SUCCESS " << p << "\n";
      pluginPtrs.push_back(plugin);
    }
  }
};

class PluginManager {
private:
  std::unordered_map<std::string, InterfaceMethodsBase *> interfaceMap;

public:
  template <class T> void addPluginInterface(std::string pluginName) {
    InterfaceMethods<T> *interface = new InterfaceMethods<T>(pluginName);
    InterfaceMethodsBase *interfaceBase = (InterfaceMethodsBase *)interface;
    interfaceMap.insert({pluginName, interface});
  }

  void loadPlugins(std::string directoryPathStr) {
    for (auto &p :
         std::filesystem::recursive_directory_iterator(directoryPathStr)) {
      std::cout << "PLUGIN: File Found " << p.path() << "\n";
      if (p.is_regular_file() &&
          (p.path().extension() == ".dll" || p.path().extension() == ".dylib" ||
           p.path().extension() == ".so")) {
        for (auto pairs : interfaceMap) {
          pairs.second->addPath(p.path());
        }
      }
    }
  }

  template <class T> boost::shared_ptr<T> getPlugin(std::string pluginName) {
    InterfaceMethods<T> *interface =
        dynamic_cast<InterfaceMethods<T> *>(interfaceMap.at(pluginName));
    if (interface->pluginPtrs.empty()) {
      return nullptr;
    }
    return interface->pluginPtrs.front();
  }
};
```

<p>main.cpp</p>

<pre class="lang-cpp prettyprint-override"><code>#include "PluginManager.hpp"
#include "PluginInterface.hpp"

int main(){
  PluginManager pluginManagerObj;
  pluginManagerObj.addPluginInterface<PluginInterface>("pluginName");
  pluginManagerObj.loadPlugins("plugins_directory");
  boost::shared_ptr<PluginInterface> plugin = pluginManagerObj.getPlugin<PluginInterface>("pluginName");
  plugin->testPlugin();
}
</code>```

EDIT: I'm using MinGW compiler on windows

答:
My original intent was to find some way for the method loadPlugins() to intelligently find and load all plugins in a directory and store their handles for later use.

After asking the initial question and messing around with possible solutions, I found out I could use templates to create class InterfaceMethods that inherits InterfaceMethodsBase that would handle the recognition of a single interface type and store all the class instances in a hash table of type InterfaceMethodsBase. After calling loadPlugins(), I could retrieve the discovered plugins from the hash table.

I edited the working code back into the original post. I hope someone can benefit from this solution in the future.

Title: Implementing a Dynamic Plugin Manager

Body:
I'm trying to create a plugin manager for c++ that checks a directory for shared libraries (dll,so,dylib) and checks if there is a plugin interface available to store the plugin and retrieve it later with.

I'm using boost::dll to import the dll, but I don't know how to set up the template better.

How do I use templates or some other method to add plugin interfaces to the plugin manager so it will check the shared libraries for the export alias name and store the shared library handle?

PluginInterface.hpp

class PluginInterface {
public:
  virtual void testPlugin() = 0;
};

plugin.hpp source for "plugins_directory/plugin.dll"

#include <boost/config.hpp> // for BOOST_SYMBOL_EXPORT
#include "pluginInterface.hpp"

namespace PluginNamespace {
class PluginClass : public PluginInterface {
  void testPlugin(){
    printf("Hello World!");
  }
}

extern "C" BOOST_SYMBOL_EXPORT PluginClass pluginName;
PluginClass pluginName;
}

PluginManager.hpp

class InterfaceMethodsBase {
public:
  std::string pluginName;
  InterfaceMethodsBase(std::string s) { pluginName = s; }
  ~InterfaceMethodsBase() {}
  virtual void addPath(std::filesystem::path p) = 0;
};

template <class T> class InterfaceMethods : public InterfaceMethodsBase {
public:
  InterfaceMethods(std::string s) : InterfaceMethodsBase(s) {}
  ~InterfaceMethods() {}
  std::vector<boost::shared_ptr<T>> pluginPtrs;
  void addPath(std::filesystem::path p) {
    boost::filesystem::path lib_path(p.string().c_str());
    std::cout << "PLUGIN: Loading " << p << "\n";
    boost::shared_ptr<T> plugin;
    try {
      plugin = boost::dll::import<T>(lib_path, pluginName,
                                     boost::dll::load_mode::default_mode);
    } catch (...) {
      std::cout << "PLUGIN: Loading FAILED " << p << "\n";
    }
    if (plugin) {
      std::cout << "PLUGIN: Loading SUCCESS " << p << "\n";
      pluginPtrs.push_back(plugin);
    }
  }
};

class PluginManager {
private:
  std::unordered_map<std::string, InterfaceMethodsBase *> interfaceMap;

public:
  template <class T> void addPluginInterface(std::string pluginName) {
    InterfaceMethods<T> *interface = new InterfaceMethods<T>(pluginName);
    InterfaceMethodsBase *interfaceBase = (InterfaceMethodsBase *)interface;
    interfaceMap.insert({pluginName, interface});
  }

  void loadPlugins(std::string directoryPathStr) {
    for (auto &p :
         std::filesystem::recursive_directory_iterator(directoryPathStr)) {
      std::cout << "PLUGIN: File Found " << p.path() << "\n";
      if (p.is_regular_file() &&
          (p.path().extension() == ".dll" || p.path().extension() == ".dylib" ||
           p.path().extension() == ".so")) {
        for (auto pairs : interfaceMap) {
          pairs.second->addPath(p.path());
        }
      }
    }
  }

  template <class T> boost::shared_ptr<T> getPlugin(std::string pluginName) {
    InterfaceMethods<T> *interface =
        dynamic_cast<InterfaceMethods<T> *>(interfaceMap.at(pluginName));
    if (interface->pluginPtrs.empty()) {
      return nullptr;
    }
    return interface->pluginPtrs.front();
  }
};

main.cpp

#include "PluginManager.hpp"
#include "PluginInterface.hpp"

int main(){
  PluginManager pluginManagerObj;
  pluginManagerObj.addPluginInterface<PluginInterface>("pluginName");
  pluginManagerObj.loadPlugins("plugins_directory");
  boost::shared_ptr<PluginInterface> plugin = pluginManagerObj.getPlugin<PluginInterface>("pluginName");
  plugin->testPlugin();
}

EDIT: I'm using MinGW compiler on windows


问:
How to change the color of all Labels in a UIView in Swift?
I found a similar question here. But the problem is it is in OBJ-C. I do not know the code and am working in SWIFT so please can anyone explain and translate this code in swift.
I am still new to swift so please help me.

Regards

答:
with an extension. Maybe its not the perfect solution but once you applied it to all needed labels, then it applies to all labels when you make a change. Create a new swift file and put the following code in:

```<code>    import UIKit

extension UILabel {
    func labelColor() {
        self.textColor = UIColor.red //or whichever color you want
    }
}
</code>```

And in the viewDidLoad or viewWillLoad you can do:

```<code>yourLabel.labelColor()
</code>```

Body:
with an extension. Maybe its not the perfect solution but once you applied it to all needed labels, then it applies to all labels when you make a change. Create a new swift file and put the following code in:

    import UIKit

extension UILabel {
    func labelColor() {
        self.textColor = UIColor.red //or whichever color you want
    }
}

And in the viewDidLoad or viewWillLoad you can do:

yourLabel.labelColor()


问:
reading JSON element using JS
I am receiving a JSON object from a PHP get request. It looks like this:

```<code>data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}
</code>```

I need to access the items within emp_type_id ("11" and "10" in this case).

I am able to access user_id just fine using data["user_id"] but can't figure out how to get the other items. I tried variations of:

```<code>eti=data["emp_type_id"];
var myVar = eti[0];
</code>```

I'll want to loop through all items in emp_type_id eventually and add them to a JS array.

答:
use a for in loop

```<code>var data = {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]};
var eti = data["emp_type_id"];
var myVar = eti[0];
for(var entry in myVar){
  alert(entry + ":\t" + myVar[entry] );
}
</code>```

Running JSBIN Example

Title: reading JSON element using JS

Body:
I am receiving a JSON object from a PHP get request. It looks like this:

data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}

I need to access the items within emp_type_id ("11" and "10" in this case).

I am able to access user_id just fine using data["user_id"] but can't figure out how to get the other items. I tried variations of:

eti=data["emp_type_id"];
var myVar = eti[0];

I'll want to loop through all items in emp_type_id eventually and add them to a JS array.

Body:
use a for in loop

var data = {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]};
var eti = data["emp_type_id"];
var myVar = eti[0];
for(var entry in myVar){
  alert(entry + ":\t" + myVar[entry] );
}

Running JSBIN Example


问:
NumPy get index inside multidimensional array
I have a Python NumPy array like this:

```<code>array([[[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0, 125, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]]], dtype=uint8)
</code>```

And I'm trying to get the index of 125 inside the array with 2 numbers in it. At first I had only 3 values, instead of 4, and this worked to get the indexed position:

```<code>p = np.unravel_index(tiles[tileindex].argmax(), tiles[tileindex].shape)
</code>```

Can't seem to find what I need to use now instead of argmax();
the value 125, can be 255 as well, so I'd like to make my selection based on the number of non-zero values in the nested arrays instead of the value itself.

So basically, how to find the line with two values, and then get the position of 125 in this example.

Any help much appreciated.

答:
I'm not sure to totally understand the question, but you say you want to select on the number of non-zeros, so you can use np.count_nonzero

Let say that we call A the matrix you set in your question. A first option, not optimal but more readable is the following

```<code>for a in A:
    print( np.count_nonzero(a,axis=1) # print just for example here, you can stock it
</code>```

And you will have, as a result, for each submatrix of your array A a vector with number of nonzero by lines. You can see that for the fourth matrix, you have two non-zeros values on the first line

[1 1 1 1 1 1 1 1]

[1 1 1 1 1 1 1 1]

[2 1 1 1 1 1 1 1] -> two non-zeros values on the first line

[1 1 1 1 1 1 1 1]

You can do it in a shorter way like this

```<code>np.count_nonzero(A,axis=2)
</code>```

Body:
I have a Python NumPy array like this:

array([[[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0, 125, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]]], dtype=uint8)

And I'm trying to get the index of 125 inside the array with 2 numbers in it. At first I had only 3 values, instead of 4, and this worked to get the indexed position:

p = np.unravel_index(tiles[tileindex].argmax(), tiles[tileindex].shape)

Can't seem to find what I need to use now instead of argmax();
the value 125, can be 255 as well, so I'd like to make my selection based on the number of non-zero values in the nested arrays instead of the value itself.

So basically, how to find the line with two values, and then get the position of 125 in this example.

Any help much appreciated.

Body:
I'm not sure to totally understand the question, but you say you want to select on the number of non-zeros, so you can use np.count_nonzero

Let say that we call A the matrix you set in your question. A first option, not optimal but more readable is the following

for a in A:
    print( np.count_nonzero(a,axis=1) # print just for example here, you can stock it

And you will have, as a result, for each submatrix of your array A a vector with number of nonzero by lines. You can see that for the fourth matrix, you have two non-zeros values on the first line

[1 1 1 1 1 1 1 1]

[1 1 1 1 1 1 1 1]

[2 1 1 1 1 1 1 1] -> two non-zeros values on the first line

[1 1 1 1 1 1 1 1]

You can do it in a shorter way like this

np.count_nonzero(A,axis=2)


问:
django rest framework update method
should i use is_valid() function for validating my user data in put() function in drf?
because when i use it ,is_valid.errors says that model with this username and email is already exists!i can't understand the errors meaning,because i think should be something saved before i want to update

serializers.py

```<code>class UserCreateSerializers(ModelSerializer):
class Meta:
    model = User
    fields = ('name','email','family',"username","password","profile_pic")

def update(self, instance, validated_data):
    print("from update try")

    #more dry
    for i in validated_data.keys():
        if hasattr(instance,str(i)) and str(i) !="password":
            setattr(instance,str(i),validated_data.get(str(i)))

        elif hasattr(instance,str(i)) and str(i) =="password":
            instance.set_password(validated_data.get('password'))

    setattr(instance,"username",validated_data.get('new_username'))
    instance.save()
</code>```

views.py

```<code>    def put(self,request):

    username = request.data['username']
    user = User.objects.get(username = username)
    serialized = UserCreateSerializers(data = request.data)

    if serialized.is_valid():
        serialized.update(user,serialized.validated_data)
        return Response(data ={"status":"api_user_update_ok"} , status = status.HTTP_201_CREATED)

    else:
        print(serialized.errors)
        return Response(data = {"status":"api_user_update_failed","error":serialized.errors.get('email')[0]},status = status.HTTP_400_BAD_REQUEST)
</code>```

client data with put method :

```<code>name:user
family:useri
username:user2
password:1234
new_username:user22
email:user@gmail.com
</code>```

error is :

{'email': [ErrorDetail(string='user with this email already exists.',
  code='unique')], 'username': [ErrorDetail(string='user with this
  username already exists.', code='unique')]} Bad Request:
  /api/v0/registration/signup

and the server response is :

```<code>{
    "status": "api_user_update_failed",
    "error": "user with this email already exists."
}
</code>```

thanks for your help.

答:
Short answer: yes you should use is_valid() before try to save received data into DB. You see this error because DRF add uniqueness validator to unique fields by default. This behavior described in the doc.

To tell django that you are updating object and don't need uniqueness validator you have to provide instance to serializer:

```<code>serialized = UserCreateSerializers(user, data=request.data)
</code>```

Title: django rest framework update method

Body:
should i use is_valid() function for validating my user data in put() function in drf?
because when i use it ,is_valid.errors says that model with this username and email is already exists!i can't understand the errors meaning,because i think should be something saved before i want to update

serializers.py

class UserCreateSerializers(ModelSerializer):
class Meta:
    model = User
    fields = ('name','email','family',"username","password","profile_pic")

def update(self, instance, validated_data):
    print("from update try")

    #more dry
    for i in validated_data.keys():
        if hasattr(instance,str(i)) and str(i) !="password":
            setattr(instance,str(i),validated_data.get(str(i)))

        elif hasattr(instance,str(i)) and str(i) =="password":
            instance.set_password(validated_data.get('password'))

    setattr(instance,"username",validated_data.get('new_username'))
    instance.save()

views.py

    def put(self,request):

    username = request.data['username']
    user = User.objects.get(username = username)
    serialized = UserCreateSerializers(data = request.data)

    if serialized.is_valid():
        serialized.update(user,serialized.validated_data)
        return Response(data ={"status":"api_user_update_ok"} , status = status.HTTP_201_CREATED)

    else:
        print(serialized.errors)
        return Response(data = {"status":"api_user_update_failed","error":serialized.errors.get('email')[0]},status = status.HTTP_400_BAD_REQUEST)

client data with put method :

name:user
family:useri
username:user2
password:1234
new_username:user22
email:user@gmail.com

error is :

{'email': [ErrorDetail(string='user with this email already exists.',
  code='unique')], 'username': [ErrorDetail(string='user with this
  username already exists.', code='unique')]} Bad Request:
  /api/v0/registration/signup

and the server response is :

{
    "status": "api_user_update_failed",
    "error": "user with this email already exists."
}

thanks for your help.

Body:
Short answer: yes you should use is_valid() before try to save received data into DB. You see this error because DRF add uniqueness validator to unique fields by default. This behavior described in the doc.

To tell django that you are updating object and don't need uniqueness validator you have to provide instance to serializer:

serialized = UserCreateSerializers(user, data=request.data)


问:
How to automate the renaming of a txt file using python
I am trying to find a way to automate the renaming of a file using python.

So the text files need to be renamed everyday to include yesterday's date (T-1).

For example: FileName_20200121.txt needs to be renamed to FileName_20200120.txt.

How do I go about this?

Thanks for the help in advance.

答:
I think what you're looking for is os.rename

but the files need to exist and you must know their complete path and name

make sure to run os.path.exists(filename) first just to prevent any errors from coming

for changing the dates you can use the datetime module

and you can configure Windows settings to have the script run everyday by

pressing Windows+R, then type shell:startup.

and adding the file in the startup folder (or make a batch file that runs the python script)

or you can go to scheduled tasks to do that.


问:
Java: How to print the String value of a Map element?
Could someone tell me how to get or print the String value of a map element?
The below code results in "The method values() is undefined for the type String."
I also tried .getValue() but the outcome is the same.

Thanks in advance!

```<code>Map<Integer, String> mapName = new HashMap<>();
mapName.put(0, "description_0");
mapName.put(1, "description_1");

for (Integer i : mapName.keySet()){
     System.out.println(mapName.get(i).values());
}

</code>```

答:
If you want to use stream:

```<code>mapName.entrySet().stream().forEach(elem-> System.out.println(elem));
</code>```

This will allow you to use all the features of stream such as filtering,collecting , reducing etc.
https://www.geeksforgeeks.org/stream-map-java-examples/

Body:
Could someone tell me how to get or print the String value of a map element?
The below code results in "The method values() is undefined for the type String."
I also tried .getValue() but the outcome is the same.

Thanks in advance!

Map<Integer, String> mapName = new HashMap<>();
mapName.put(0, "description_0");
mapName.put(1, "description_1");

for (Integer i : mapName.keySet()){
     System.out.println(mapName.get(i).values());
}

Body:
If you want to use stream:

mapName.entrySet().stream().forEach(elem-> System.out.println(elem));

This will allow you to use all the features of stream such as filtering,collecting , reducing etc.
https://www.geeksforgeeks.org/stream-map-java-examples/


问:
Python: Removing list element while iterating over list
I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

```<code>for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list
</code>```

What should I use in place of remove_element?
I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

答:
You can still use filter, moving to an outside function the element modification (iterating just once)</p>

```<code>def do_the_magic(x):
    do_action(x)
    return check(x)

# you can get a different filtered list
filter(do_the_magic,yourList)

# or have it modified in place (as suggested by Steven Rumbalski, see comment)
yourList[:] = itertools.ifilter(do_the_magic, yourList)
</code>```

Body:
I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list

What should I use in place of remove_element?
I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

Body:
You can still use filter, moving to an outside function the element modification (iterating just once)

def do_the_magic(x):
    do_action(x)
    return check(x)

# you can get a different filtered list
filter(do_the_magic,yourList)

# or have it modified in place (as suggested by Steven Rumbalski, see comment)
yourList[:] = itertools.ifilter(do_the_magic, yourList)


问:
Calculate percent change in a column within a group in Pandas
My dataframe has a Ticker column and a Price column.  There are 10 rows per Ticker (with the same Ticker value) but each row has a different Price.

My aim is to calculate the percent change within a Ticker group.

I tried the following but failed:

```<code>Test_preds_actual1['Target1_preds_pct_chng'] = 0
Test_preds_actual1.groupby('Ticker')['Target1_preds_pct_chng'] =\
Test_preds_actual1.groupby('Ticker')['Target1_preds'].pct_change()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-316-168796f850f9> in <module>
      1 Test_preds_actual1.groupby('Ticker')['Target1_preds_pct_chng'] =\
----> 2 Test_preds_actual1.groupby('Ticker')['Target1_preds'].pct_change()

TypeError: 'DataFrameGroupBy' object does not support item assignment
</code>```

I am not sure I understand the error message.  How can I accomplish my objective?

答:
You can do assign </p>

```<code>Test_preds_actual1['Target1_preds_pct_chng']=Test_preds_actual1.groupby('Ticker')['Target1_preds'].pct_change()
</code>```

Body:
My dataframe has a Ticker column and a Price column.  There are 10 rows per Ticker (with the same Ticker value) but each row has a different Price.

My aim is to calculate the percent change within a Ticker group.

I tried the following but failed:

Test_preds_actual1['Target1_preds_pct_chng'] = 0
Test_preds_actual1.groupby('Ticker')['Target1_preds_pct_chng'] =\
Test_preds_actual1.groupby('Ticker')['Target1_preds'].pct_change()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-316-168796f850f9> in <module>
      1 Test_preds_actual1.groupby('Ticker')['Target1_preds_pct_chng'] =\
----> 2 Test_preds_actual1.groupby('Ticker')['Target1_preds'].pct_change()

TypeError: 'DataFrameGroupBy' object does not support item assignment

I am not sure I understand the error message.  How can I accomplish my objective?

Body:
You can do assign

Test_preds_actual1['Target1_preds_pct_chng']=Test_preds_actual1.groupby('Ticker')['Target1_preds'].pct_change()


答:
List comp:</p>

```<code>results = [x for x in (do_action(element) for element in somelist) if check(element)]
</code>```

Title: Python: Removing list element while iterating over list

Body:
List comp:

results = [x for x in (do_action(element) for element in somelist) if check(element)]


问:
sort from information from a text file Python 3
I'm currently trying to open text file with a 100 random numbers. Then reading them and sorting this numbers from lowest to highest.

I've created the file and written the 100 random numbers through this function.

```<code>def hundred_values():
    import random
    numbers_list = []
    for _ in range(100):
        numbers_list.append(random.randint(1, 100))
    with open('numbers.txt', 'w') as file:
        file.write(str(numbers_list))
</code>```

after this I'm trying to get Python to read the file, changing the string into int to then sorting them from lowest to highest. But I can't get it to work. Any input would be greatly appreciated

```<code>def find_smallest_number():
    lines = []
    with open('numbers.txt', 'r') as file:
        line = file.read().splitlines() # for processing
        lines.append(line) # storing everything in memory
        lines.sort(lines)
        print(lines)
</code>```

答:
You are writing the entire list in a single line, what you will see in the file is this: [8, 2, 4, ...], that's why you can't sort it. It's better to store each value in a single line if you don't want to use csv or json format. For example:

import random

def hundred_values():
    with open('numbers.txt', 'w') as file:
        for _ in range(100):
            print(random.randint(1, 100), file=file)

def find_smallest_number():
    with open('numbers.txt') as file:
        values = sorted([int(i) for i in file.readlines()])
        print(values)

hundred_values()
find_smallest_number()

>>> [1, 5, 5, 6, 7, 10, 10, 10, 10, 11, 11, 13, ... ]
```

Body:
I'm currently trying to open text file with a 100 random numbers. Then reading them and sorting this numbers from lowest to highest.

I've created the file and written the 100 random numbers through this function.

def hundred_values():
    import random
    numbers_list = []
    for _ in range(100):
        numbers_list.append(random.randint(1, 100))
    with open('numbers.txt', 'w') as file:
        file.write(str(numbers_list))

after this I'm trying to get Python to read the file, changing the string into int to then sorting them from lowest to highest. But I can't get it to work. Any input would be greatly appreciated

def find_smallest_number():
    lines = []
    with open('numbers.txt', 'r') as file:
        line = file.read().splitlines() # for processing
        lines.append(line) # storing everything in memory
        lines.sort(lines)
        print(lines)


问:
Why CSE formula doesn't work in NameManager, but works in cell?
I'm so confused.Please tell me why CSE array formula works in cell,but doesn't work in NameManager?

All cells in range A1:A10 contains formula which in this case throws "" in A9 and A10. That's why I can't use COUNTA(A1:A10) to count not blanks, but I'm using MIN(IF(A1:A10=""|ROW(A1:A10)))-1.

When I try to define this dynamic range as named, copy-pasting the formula in C1 into NameManager's "Refers to:" , troubles begin. Sorry for my english > I hope pictures can explain me better.

PS: I also tried to use =INDIRECT(C1) instead
 =OFFSET(A1|0|0|MIN(IF(A1:A10=""|ROW(A1:A10)))-1|1) ,but same result apears

答:
Try this formula:

```<code>=Sheet1!$A$1:INDEX(Sheet1!$A$1:$A$10,SUMPRODUCT(--(Sheet1!$A$1:$A$10<>"")))
</code>```

It'll skip the blanks which result is ""

Let me know if it works

Body:
Try this formula:

=Sheet1!$A$1:INDEX(Sheet1!$A$1:$A$10,SUMPRODUCT(--(Sheet1!$A$1:$A$10<>"")))

It'll skip the blanks which result is ""

Let me know if it works


问:
Count numbers that are lower by constant from current number
Imagine that I have a list of numbers (i.e. numbers column in data.table/data.frame).

```<code>1
5
5
10
11
12
</code>```

for each number in a list a want to count how many unique numbers are there which are lower than that particular number + 5.

The explanation for upper case, first number = 1, search range is 1+5 = 6, so three numbers are in range, less than or equal to: c(1,5,5), and then count unique is 2.
This is all by assuming we've got the additional condition, that the number must not only be lower than current_number + 5, but also its index in the list must be >= that of current_number.

The result in this case would be:

```<code>2
2
2
3
2
1
</code>```

Note: Is there a fast solution for huge dataset, in data.frame or data.table? My dataset is rather huge, 10+M rows.

Body:
Imagine that I have a list of numbers (i.e. numbers column in data.table/data.frame).

1
5
5
10
11
12

for each number in a list a want to count how many unique numbers are there which are lower than that particular number + 5.

The explanation for upper case, first number = 1, search range is 1+5 = 6, so three numbers are in range, less than or equal to: c(1,5,5), and then count unique is 2.
This is all by assuming we've got the additional condition, that the number must not only be lower than current_number + 5, but also its index in the list must be >= that of current_number.

The result in this case would be:

2
2
2
3
2
1

Note: Is there a fast solution for huge dataset, in data.frame or data.table? My dataset is rather huge, 10+M rows.

Body:
Try this:

x <- c(1,5,5,10,11,12)

sapply(seq_along(x), function(i)
  sum(unique(x[i:length(x)]) <= (x[i] + 5)))
# [1] 2 2 2 3 2 1


问:
How to set default values for shadow property
I have the following entity:

```<code>public class Person
{
    public Guid Id { get; set; }

    public string Name { get; set; }
}
</code>```

This is my DB context

```<code>public class PersonDbContext : DbContext
{
    private static readonly ILoggerFactory
        Logger = LoggerFactory.Create(x => x.AddConsole());

    public DbSet<Person> Persons { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseLoggerFactory(Logger)
            .UseSqlServer(
                "Server=(localdb)\\mssqllocaldb;Database=PersonDb;Trusted_Connection=True;MultipleActiveResultSets=true");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Person>()
            .Property<DateTime>("Created")
            .HasDefaultValueSql("GETUTCDATE()")
            .ValueGeneratedOnAdd();

        modelBuilder
            .Entity<Person>()
            .Property<DateTime>("Updated")
            .HasDefaultValueSql("GETUTCDATE()")
            .ValueGeneratedOnAddOrUpdate();
    }
}
</code>```

As can be seen from OnModelCreating override, I'm adding shadow properties Updated/Created to Person entity.

I set those properties to be populated with SQL default values

Created when value is added

Updated when value is added or updated

Below is client code

```<code>var personId = Guid.Parse("CF5EE27D-C694-408A-9F7B-080FF6315843");

using (var dbContext = new PersonDbContext())
{
    var person = new Person
    {
        Id = personId,
        Name = "New Person"
    };

    dbContext.Add(person);

    await dbContext.SaveChangesAsync();
}

using (var dbContext = new PersonDbContext())
{
    var person = dbContext.Persons.Find(personId);

    var personName = person.Name;

    person.Name = $"{personName} {DateTime.UtcNow}";

    dbContext.SaveChanges();
}
</code>```

I can confirm that both properties are set to UTC date when inserting a new person.
However, on update, Updated property is not being set.

This is the t-sql generated:

```<code>info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[@p1='?' (DbType = Guid), @p0='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      UPDATE [Persons] SET [Name] = @p0
      WHERE [Id] = @p1;
      SELECT [Updated]
      FROM [Persons]
      WHERE @@ROWCOUNT = 1 AND [Id] = @p1;
</code>```

Reading documentation on genereted value on add or update I see the following warning:

However, if you specify that a DateTime property is generated on add
  or update, then you must setup a way for the values to be generated.
  One way to do this, is to configure a default value of GETDATE() (see
  Default Values) to generate values for new rows. You could then use a
  database trigger to generate values during updates (such as the
  following example trigger).

I don't get what's the purpose of ValueGeneratedOnAddOrUpdate() then, if it behaves like ValueGeneratedOnAdd() and I have to manually intervene (creating a trigger) to set this property.

Indeed, if I change the definition of Updated shadow property to

```<code>modelBuilder
    .Entity<Person>()
    .Property<DateTime>("Updated")
    .HasDefaultValueSql("GETUTCDATE()")
    .ValueGeneratedOnAdd();
</code>```

And override SaveChanges on the PersonDbContext

```<code>public override int SaveChanges()
{
    ChangeTracker.DetectChanges();

    foreach (var entry in ChangeTracker.Entries().Where(entity => entity.State == EntityState.Modified))
    {
        entry.Property("Updated").CurrentValue = DateTime.UtcNow;
    }

    return base.SaveChanges();
}
</code>```

This does what is expected.

So the question is - what's the proper way to set default values for shadow properties in EF Core.

This is simplified example from my bigger project, so using HasData on the entities in OnModelCreating override is not a good option (due to many entities).

I'm using EF Core 3.1.1

```<code><PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1"/>
</code>```

答:
if you want to have reusable shadow properties follow these steps.

1- create a marker empty interface. IAuditableEntity.cs

    ///
    /// It's a marker interface, in order to make our entities audit-able.
    /// Every entity you mark with this interface, will save audit info to the database.
    ///
    public interface IAuditableEntity
    { }

```

<p>2- Create a static Class to write your Shadow Properties logic. <code>AuditableShadowProperties.cs</code></p>

<pre class="lang-cs prettyprint-override"><code>public static class AuditableShadowProperties {

    public static readonly Func<object, DateTimeOffset?> EfPropertyCreatedDateTime =
        entity => EF.Property<DateTimeOffset?> (entity, CreatedDateTime);

    public static readonly string CreatedDateTime = nameof (CreatedDateTime);

    public static readonly Func<object, DateTimeOffset?> EfPropertyModifiedDateTime =
        entity => EF.Property<DateTimeOffset?> (entity, ModifiedDateTime);

    public static readonly string ModifiedDateTime = nameof (ModifiedDateTime);

    public static void AddAuditableShadowProperties (this ModelBuilder modelBuilder) {
        foreach (var entityType in modelBuilder.Model
                .GetEntityTypes ()
                .Where (e => typeof (IAuditableEntity).IsAssignableFrom (e.ClrType))) {
            modelBuilder.Entity (entityType.ClrType)
                .Property<DateTimeOffset?> (CreatedDateTime);

            modelBuilder.Entity (entityType.ClrType)
                .Property<DateTimeOffset?> (ModifiedDateTime);

        }
    }

    public static void SetAuditableEntityPropertyValues (
        this ChangeTracker changeTracker) {
        var now = DateTimeOffset.UtcNow;

        var modifiedEntries = changeTracker.Entries<IAuditableEntity> ()
            .Where (x => x.State == EntityState.Modified);
        foreach (var modifiedEntry in modifiedEntries) {
            modifiedEntry.Property (ModifiedDateTime).CurrentValue = now;
        }

        var addedEntries = changeTracker.Entries<IAuditableEntity> ()
            .Where (x => x.State == EntityState.Added);
        foreach (var addedEntry in addedEntries) {
            addedEntry.Property (CreatedDateTime).CurrentValue = now;
        }
    }
}
</code>```

3- Add neccessery changes to your PersonDbContext to use your IAuditableEntity.

 // first we add our shadow properties to the database with next migration
 protected override void OnModelCreating(ModelBuilder builder)
{
...
  builder.AddAuditableShadowProperties();
}

// override saveChanges methods to use our shadow properties.
        public override int SaveChanges()
        {
            ChangeTracker.DetectChanges();

            BeforeSaveTriggers();

            ChangeTracker.AutoDetectChangesEnabled =
                false; // for performance reasons, to avoid calling DetectChanges() again.
            var result = base.SaveChanges();
            ChangeTracker.AutoDetectChangesEnabled = true;
            return result;
        }

     public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            ChangeTracker.DetectChanges();

            BeforeSaveTriggers();

            ChangeTracker.AutoDetectChangesEnabled =
                false; // for performance reasons, to avoid calling DetectChanges() again.
            var result = base.SaveChangesAsync(cancellationToken);
            ChangeTracker.AutoDetectChangesEnabled = true;
            return result;
        }

        public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess,
            CancellationToken cancellationToken = new CancellationToken())
        {
            ChangeTracker.DetectChanges();

            BeforeSaveTriggers();

            ChangeTracker.AutoDetectChangesEnabled =
                false; // for performance reasons, to avoid calling DetectChanges() again.
            var result = base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
            ChangeTracker.AutoDetectChangesEnabled = true;
            return result;
        }

        #region "ExtraMethods"

        public T GetShadowPropertyValue<T>(object entity, string propertyName) where T : IConvertible
        {
            var value = this.Entry(entity).Property(propertyName).CurrentValue;
            return value != null ?
                (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture) :
                default(T);
        }

        public object GetShadowPropertyValue(object entity, string propertyName)
        {
            return this.Entry(entity).Property(propertyName).CurrentValue;
        }

        private void BeforeSaveTriggers()
        {
            ValidateEntities();
            SetShadowProperties();
        }

        private void ValidateEntities()
        {
            var errors = this.GetValidationErrors();
            if (!string.IsNullOrWhiteSpace(errors))
            {
                // we can't use constructor injection anymore, because we are using the `AddDbContextPool<>`
                var loggerFactory = this.GetService<ILoggerFactory>();
                loggerFactory.CheckArgumentIsNull(nameof(loggerFactory));
                var logger = loggerFactory.CreateLogger<AppDbContext>();
                logger.LogError(errors);
                throw new InvalidOperationException(errors);
            }
        }

        private void SetShadowProperties()
        {
            ChangeTracker.SetAuditableEntityPropertyValues();
        }
        #endregio

```

<p><strong>usage:</strong></p>

<p>4- now you can add <code>IAuditableEntity</code> interface to any entity you want to have these shadow properties and you are done.</p>

<pre class="lang-cs prettyprint-override"><code>public class Person : IAuditableEntity
{
    public Guid Id { get; set; }

    public string Name { get; set; }
}
</code>```

I'm using IAuditableEntity with a lot of other properties such as BrowserName userIp ... but I removed those in this example to keep it as simple as possible. it's not easy to explain everything in this example but feel free to ask if you had any questions about this approach.

Body:
I have the following entity:

public class Person
{
    public Guid Id { get; set; }

    public string Name { get; set; }
}

This is my DB context

public class PersonDbContext : DbContext
{
    private static readonly ILoggerFactory
        Logger = LoggerFactory.Create(x => x.AddConsole());

    public DbSet<Person> Persons { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseLoggerFactory(Logger)
            .UseSqlServer(
                "Server=(localdb)\\mssqllocaldb;Database=PersonDb;Trusted_Connection=True;MultipleActiveResultSets=true");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Person>()
            .Property<DateTime>("Created")
            .HasDefaultValueSql("GETUTCDATE()")
            .ValueGeneratedOnAdd();

        modelBuilder
            .Entity<Person>()
            .Property<DateTime>("Updated")
            .HasDefaultValueSql("GETUTCDATE()")
            .ValueGeneratedOnAddOrUpdate();
    }
}

As can be seen from OnModelCreating override, I'm adding shadow properties Updated/Created to Person entity.

I set those properties to be populated with SQL default values

Created when value is added

Updated when value is added or updated

Below is client code

var personId = Guid.Parse("CF5EE27D-C694-408A-9F7B-080FF6315843");

using (var dbContext = new PersonDbContext())
{
    var person = new Person
    {
        Id = personId,
        Name = "New Person"
    };

    dbContext.Add(person);

    await dbContext.SaveChangesAsync();
}

using (var dbContext = new PersonDbContext())
{
    var person = dbContext.Persons.Find(personId);

    var personName = person.Name;

    person.Name = $"{personName} {DateTime.UtcNow}";

    dbContext.SaveChanges();
}

I can confirm that both properties are set to UTC date when inserting a new person.
However, on update, Updated property is not being set.

This is the t-sql generated:

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[@p1='?' (DbType = Guid), @p0='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      UPDATE [Persons] SET [Name] = @p0
      WHERE [Id] = @p1;
      SELECT [Updated]
      FROM [Persons]
      WHERE @@ROWCOUNT = 1 AND [Id] = @p1;

Reading documentation on genereted value on add or update I see the following warning:

However, if you specify that a DateTime property is generated on add
  or update, then you must setup a way for the values to be generated.
  One way to do this, is to configure a default value of GETDATE() (see
  Default Values) to generate values for new rows. You could then use a
  database trigger to generate values during updates (such as the
  following example trigger).

I don't get what's the purpose of ValueGeneratedOnAddOrUpdate() then, if it behaves like ValueGeneratedOnAdd() and I have to manually intervene (creating a trigger) to set this property.

Indeed, if I change the definition of Updated shadow property to

modelBuilder
    .Entity<Person>()
    .Property<DateTime>("Updated")
    .HasDefaultValueSql("GETUTCDATE()")
    .ValueGeneratedOnAdd();

And override SaveChanges on the PersonDbContext

public override int SaveChanges()
{
    ChangeTracker.DetectChanges();

    foreach (var entry in ChangeTracker.Entries().Where(entity => entity.State == EntityState.Modified))
    {
        entry.Property("Updated").CurrentValue = DateTime.UtcNow;
    }

    return base.SaveChanges();
}

This does what is expected.

So the question is - what's the proper way to set default values for shadow properties in EF Core.

This is simplified example from my bigger project, so using HasData on the entities in OnModelCreating override is not a good option (due to many entities).

I'm using EF Core 3.1.1

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1"/>

Body:
if you want to have reusable shadow properties follow these steps.

1- create a marker empty interface. IAuditableEntity.cs

    /// <summary>
    /// It's a marker interface, in order to make our entities audit-able.
    /// Every entity you mark with this interface, will save audit info to the database.
    /// </summary>
    public interface IAuditableEntity
    { }

2- Create a static Class to write your Shadow Properties logic. AuditableShadowProperties.cs

public static class AuditableShadowProperties {

    public static readonly Func<object, DateTimeOffset?> EfPropertyCreatedDateTime =
        entity => EF.Property<DateTimeOffset?> (entity, CreatedDateTime);

    public static readonly string CreatedDateTime = nameof (CreatedDateTime);

    public static readonly Func<object, DateTimeOffset?> EfPropertyModifiedDateTime =
        entity => EF.Property<DateTimeOffset?> (entity, ModifiedDateTime);

    public static readonly string ModifiedDateTime = nameof (ModifiedDateTime);

    public static void AddAuditableShadowProperties (this ModelBuilder modelBuilder) {
        foreach (var entityType in modelBuilder.Model
                .GetEntityTypes ()
                .Where (e => typeof (IAuditableEntity).IsAssignableFrom (e.ClrType))) {
            modelBuilder.Entity (entityType.ClrType)
                .Property<DateTimeOffset?> (CreatedDateTime);

            modelBuilder.Entity (entityType.ClrType)
                .Property<DateTimeOffset?> (ModifiedDateTime);

        }
    }

    public static void SetAuditableEntityPropertyValues (
        this ChangeTracker changeTracker) {
        var now = DateTimeOffset.UtcNow;

        var modifiedEntries = changeTracker.Entries<IAuditableEntity> ()
            .Where (x => x.State == EntityState.Modified);
        foreach (var modifiedEntry in modifiedEntries) {
            modifiedEntry.Property (ModifiedDateTime).CurrentValue = now;
        }

        var addedEntries = changeTracker.Entries<IAuditableEntity> ()
            .Where (x => x.State == EntityState.Added);
        foreach (var addedEntry in addedEntries) {
            addedEntry.Property (CreatedDateTime).CurrentValue = now;
        }
    }
}

3- Add neccessery changes to your PersonDbContext to use your IAuditableEntity.

 // first we add our shadow properties to the database with next migration
 protected override void OnModelCreating(ModelBuilder builder)
{
...
  builder.AddAuditableShadowProperties();
}

// override saveChanges methods to use our shadow properties.
        public override int SaveChanges()
        {
            ChangeTracker.DetectChanges();

            BeforeSaveTriggers();

            ChangeTracker.AutoDetectChangesEnabled =
                false; // for performance reasons, to avoid calling DetectChanges() again.
            var result = base.SaveChanges();
            ChangeTracker.AutoDetectChangesEnabled = true;
            return result;
        }

     public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            ChangeTracker.DetectChanges();

            BeforeSaveTriggers();

            ChangeTracker.AutoDetectChangesEnabled =
                false; // for performance reasons, to avoid calling DetectChanges() again.
            var result = base.SaveChangesAsync(cancellationToken);
            ChangeTracker.AutoDetectChangesEnabled = true;
            return result;
        }

        public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess,
            CancellationToken cancellationToken = new CancellationToken())
        {
            ChangeTracker.DetectChanges();

            BeforeSaveTriggers();

            ChangeTracker.AutoDetectChangesEnabled =
                false; // for performance reasons, to avoid calling DetectChanges() again.
            var result = base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
            ChangeTracker.AutoDetectChangesEnabled = true;
            return result;
        }

        #region "ExtraMethods"

        public T GetShadowPropertyValue<T>(object entity, string propertyName) where T : IConvertible
        {
            var value = this.Entry(entity).Property(propertyName).CurrentValue;
            return value != null ?
                (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture) :
                default(T);
        }

        public object GetShadowPropertyValue(object entity, string propertyName)
        {
            return this.Entry(entity).Property(propertyName).CurrentValue;
        }

        private void BeforeSaveTriggers()
        {
            ValidateEntities();
            SetShadowProperties();
        }

        private void ValidateEntities()
        {
            var errors = this.GetValidationErrors();
            if (!string.IsNullOrWhiteSpace(errors))
            {
                // we can't use constructor injection anymore, because we are using the `AddDbContextPool<>`
                var loggerFactory = this.GetService<ILoggerFactory>();
                loggerFactory.CheckArgumentIsNull(nameof(loggerFactory));
                var logger = loggerFactory.CreateLogger<AppDbContext>();
                logger.LogError(errors);
                throw new InvalidOperationException(errors);
            }
        }

        private void SetShadowProperties()
        {
            ChangeTracker.SetAuditableEntityPropertyValues();
        }
        #endregio

usage:

4- now you can add IAuditableEntity interface to any entity you want to have these shadow properties and you are done.

public class Person : IAuditableEntity
{
    public Guid Id { get; set; }

    public string Name { get; set; }
}

I'm using IAuditableEntity with a lot of other properties such as BrowserName userIp ... but I removed those in this example to keep it as simple as possible. it's not easy to explain everything in this example but feel free to ask if you had any questions about this approach.


问:
golang Chi router with query params not working
I am working on a restful service in golang using chi. I am trying to create a route as below

```<code>r.Mount("/api/dest", router.NewDestRouter(chi.NewRouter(), destSrv).InitRoutes())

func (dr *DestRouter) InitRoutes() http.Handler {
    dr.router.Post("/{number}/product?version={v}", handlers.HandleProduct(dr.dest))
    return dr.router
}
</code>```

But I try to hit this endpoint via post man I get a 404 not found

```<code>http://localhost:8345/api/dest/1235abc/product?version=1
</code>```

May I know the issue here?

答: As @mkopriva mentioned, simply use r.URL.Query().Get("version") to get the query parameter.

Body:
I am working on a restful service in golang using chi. I am trying to create a route as below

r.Mount("/api/dest", router.NewDestRouter(chi.NewRouter(), destSrv).InitRoutes())

func (dr *DestRouter) InitRoutes() http.Handler {
    dr.router.Post("/{number}/product?version={v}", handlers.HandleProduct(dr.dest))
    return dr.router
}

But I try to hit this endpoint via post man I get a 404 not found

http://localhost:8345/api/dest/1235abc/product?version=1

May I know the issue here?


问:
How to turn a dataframe of two columns, where each row represents a pair of friends id, into a data with id and all their friends in the one row?
Data example:

col1  col2

```<code>id1   id2
id2   id3
id1   id4
id3   id4
</code>```

Output:

col1 col2

```<code>id1  id2, id4
id2  id1, id3
id3  id2
id4  id1, id3
</code>```

答:
Another idea is to collect in a list and after apply an scala mkString
So the first query is</p>

```<code>select col1, collect_list(col2) as c from test group by col1
</code>```

Body:
Data example:

col1  col2

id1   id2
id2   id3
id1   id4
id3   id4

Output:

col1 col2

id1  id2, id4
id2  id1, id3
id3  id2
id4  id1, id3

Body:
Another idea is to collect in a list and after apply an scala mkString
So the first query is

select col1, collect_list(col2) as c from test group by col1