问:
Use TextOut() in WM_COMMAND
I'm trying to print a text in the WM_COMMAND case, because I need a text to be printed after a button was pushed.

Here's the code I have:

```<code>switch(msg)
{
default:
    return DefWindowProc(hwnd, msg, wParam, lParam);
case WM_COMMAND:
    switch (LOWORD(wParam))
    {
    case 1:
        PAINTSTRUCT ps;
        HDC         hDC;
        hDC = BeginPaint(hwnd, &ps);
        {
            TextOut(hDC, 10, 50, "hello", 5);
        }
        EndPaint(hwnd, &ps);
        UpdateWindow(hwnd);
        break;
    }
    break;
}
</code>```

Sadly it doesn't print anything.

edit:

I can use TextOut() during WM_COMMAND that way:

```<code>HDC         hDC;
hDC = GetDC(hwnd);
TextOut(hDC, 10, ypos, "Warnings: ", 10);
UpdateWindow(hwnd);
</code>```

答:
It's best to structure your program so that all painting is performed in WM_PAINT.

so you could change it to be something like:

```<code>LRESULT CALLBACK WndProc(/*blah blah blah*/)
{
    static wchar_t my_text[] = L"hello";
    static BOOL show_btn_text = FALSE;
    HDC dc;
    PAINTSTRUCT ps;
    switch (msg) {
          case WM_COMMAND:
               switch (LOWORD(wParam)) {
                  case 1:
                       show_btn_text = !show_btn_text;
                       InvalidateRect(hwnd, NULL, TRUE); //tells windows that the whole client area needs to be repainted
                       break;
               }
               return 0;
           case WM_PAINT:
                dc = BeginPaint(hwnd, &ps);
                if (show_btn_text) {
                    TextOut(dc, 0, 0, my_text, wcslen(my_text));
                }
                EndPaint(hwnd, &ps);

            return 0;
            /*the rest of the window procedure
    }
}
</code>```

Title: Use TextOut() in WM_COMMAND

Body:
I'm trying to print a text in the WM_COMMAND case, because I need a text to be printed after a button was pushed.

Here's the code I have:

switch(msg)
{
default:
    return DefWindowProc(hwnd, msg, wParam, lParam);
case WM_COMMAND:
    switch (LOWORD(wParam))
    {
    case 1:
        PAINTSTRUCT ps;
        HDC         hDC;
        hDC = BeginPaint(hwnd, &ps);
        {
            TextOut(hDC, 10, 50, "hello", 5);
        }
        EndPaint(hwnd, &ps);
        UpdateWindow(hwnd);
        break;
    }
    break;
}

Sadly it doesn't print anything.

edit:

I can use TextOut() during WM_COMMAND that way:

HDC         hDC;
hDC = GetDC(hwnd);
TextOut(hDC, 10, ypos, "Warnings: ", 10);
UpdateWindow(hwnd);

Body:
It's best to structure your program so that all painting is performed in WM_PAINT.

so you could change it to be something like:

LRESULT CALLBACK WndProc(/*blah blah blah*/)
{
    static wchar_t my_text[] = L"hello";
    static BOOL show_btn_text = FALSE;
    HDC dc;
    PAINTSTRUCT ps;
    switch (msg) {
          case WM_COMMAND:
               switch (LOWORD(wParam)) {
                  case 1:
                       show_btn_text = !show_btn_text;
                       InvalidateRect(hwnd, NULL, TRUE); //tells windows that the whole client area needs to be repainted
                       break;
               }
               return 0;
           case WM_PAINT:
                dc = BeginPaint(hwnd, &ps);
                if (show_btn_text) {
                    TextOut(dc, 0, 0, my_text, wcslen(my_text));
                }
                EndPaint(hwnd, &ps);

            return 0;
            /*the rest of the window procedure
    }
}


来源: stackexchange

问:
Change key binding for German umlauts in VSCode
I like the use the German umlauts "ö", "Ö", "ä", and "Ä" on my keyboard for coding in VSCode, i.e., use these keys to type square and curly brackets. Here is what I tried in keybindings.json:

```<code>{ "key": "ö",           "command": "type", "args": { "text": "[" }, "when": "editorTextFocus" },
{ "key": "ä",           "command": "type", "args": { "text": "]" }, "when": "editorTextFocus" },
{ "key": "Shift+ö",     "command": "type", "args": { "text": "{" }, "when": "editorTextFocus" },
{ "key": "Shift+ä",     "command": "type", "args": { "text": "}" }, "when": "editorTextFocus" },
{ "key": "Alt-ö",       "command": "type", "args": { "text": "ö" }, "when": "editorTextFocus" },
{ "key": "Alt-ä",       "command": "type", "args": { "text": "ä" }, "when": "editorTextFocus" },
{ "key": "Alt-Shift+ö", "command": "type", "args": { "text": "Ö" }, "when": "editorTextFocus" },
{ "key": "Alt-Shift+ä", "command": "type", "args": { "text": "Ä" }, "when": "editorTextFocus" }
</code>```

VSCode complains:

You won't be able to produce this key combination under your current
  keyboard layout.

Is there an easy way to teach VSCode to allow bindings for any key instead of just the predefined ones?

答:
Thanks @Gama11 for the hint regarding the UI. I tried it and got the keys [Semicolon], [Quote], and [BracketLeft], for ö, ä, and ü for my German keyboard + layout.

Here is my working keybindings.json:

    { "key": "[Semicolon]",           "command": "type", "args": { "text": "[" }, "when": "editorTextFocus" },
    { "key": "[Quote]",               "command": "type", "args": { "text": "]" }, "when": "editorTextFocus" },
    { "key": "Shift+[Semicolon]",     "command": "type", "args": { "text": "{" }, "when": "editorTextFocus" },
    { "key": "Shift+[Quote]",         "command": "type", "args": { "text": "}" }, "when": "editorTextFocus" },
    { "key": "Alt+[Semicolon]",       "command": "type", "args": { "text": "ö" }, "when": "editorTextFocus" },
    { "key": "Alt+[Quote]",           "command": "type", "args": { "text": "ä" }, "when": "editorTextFocus" },
    { "key": "Shift+Alt+[Semicolon]", "command": "type", "args": { "text": "Ö" }, "when": "editorTextFocus" },
    { "key": "Shift+Alt+[Quote]",     "command": "type", "args": { "text": "Ä" }, "when": "editorTextFocus" }
```

It works perfectly for the mapped umlaut keys and does not interfere with the regular ; and " keys.

ContentLicense: CC BY-SA 4.0

Body:
I like the use the German umlauts "ö", "Ö", "ä", and "Ä" on my keyboard for coding in VSCode, i.e., use these keys to type square and curly brackets. Here is what I tried in keybindings.json:

{ "key": "ö",           "command": "type", "args": { "text": "[" }, "when": "editorTextFocus" },
{ "key": "ä",           "command": "type", "args": { "text": "]" }, "when": "editorTextFocus" },
{ "key": "Shift+ö",     "command": "type", "args": { "text": "{" }, "when": "editorTextFocus" },
{ "key": "Shift+ä",     "command": "type", "args": { "text": "}" }, "when": "editorTextFocus" },
{ "key": "Alt-ö",       "command": "type", "args": { "text": "ö" }, "when": "editorTextFocus" },
{ "key": "Alt-ä",       "command": "type", "args": { "text": "ä" }, "when": "editorTextFocus" },
{ "key": "Alt-Shift+ö", "command": "type", "args": { "text": "Ö" }, "when": "editorTextFocus" },
{ "key": "Alt-Shift+ä", "command": "type", "args": { "text": "Ä" }, "when": "editorTextFocus" }

VSCode complains:

You won't be able to produce this key combination under your current
  keyboard layout.

Is there an easy way to teach VSCode to allow bindings for any key instead of just the predefined ones?

Body:
Thanks @Gama11 for the hint regarding the UI. I tried it and got the keys [Semicolon], [Quote], and [BracketLeft], for ö, ä, and ü for my German keyboard + layout.

Here is my working keybindings.json:

    { "key": "[Semicolon]",           "command": "type", "args": { "text": "[" }, "when": "editorTextFocus" },
    { "key": "[Quote]",               "command": "type", "args": { "text": "]" }, "when": "editorTextFocus" },
    { "key": "Shift+[Semicolon]",     "command": "type", "args": { "text": "{" }, "when": "editorTextFocus" },
    { "key": "Shift+[Quote]",         "command": "type", "args": { "text": "}" }, "when": "editorTextFocus" },
    { "key": "Alt+[Semicolon]",       "command": "type", "args": { "text": "ö" }, "when": "editorTextFocus" },
    { "key": "Alt+[Quote]",           "command": "type", "args": { "text": "ä" }, "when": "editorTextFocus" },
    { "key": "Shift+Alt+[Semicolon]", "command": "type", "args": { "text": "Ö" }, "when": "editorTextFocus" },
    { "key": "Shift+Alt+[Quote]",     "command": "type", "args": { "text": "Ä" }, "when": "editorTextFocus" }

It works perfectly for the mapped umlaut keys and does not interfere with the regular ; and " keys.


问:
How to Select between two periode of month and year eg: january 2018 - january 2019?
SQL query problem</p>

```<code>select *
from app_contract_hd
where year(created_datetime) between 2018 and 2018 and MONTH(created_datetime)between 4 and 4
</code>```

答:
One possible way using CONCAT and checking with BETWEEN

```<code>SELECT *
FROM app_contract_hd
WHERE CONCAT(YEAR(created_datetime), MONTH (created_datetime)) BETWEEN 201801 AND 201901
</code>```

Body:
SQL query problem

select *
from app_contract_hd
where year(created_datetime) between 2018 and 2018 and MONTH(created_datetime)between 4 and 4

Body:
One possible way using CONCAT and checking with BETWEEN

SELECT *
FROM app_contract_hd
WHERE CONCAT(YEAR(created_datetime), MONTH (created_datetime)) BETWEEN 201801 AND 201901


问:
Timezones in SQL DATE vs java.sql.Date
I'm getting a bit confused by the behaviour of the SQL DATE data type vs. that of java.sql.Date. Take the following statement, for example:

select cast(? as date)           -- in most databases
select cast(? as date) from dual -- in Oracle
```

<p>Let's prepare and execute the statement with Java</p>

<pre class="lang-java prettyprint-override"><code>PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setDate(1, new java.sql.Date(0)); // GMT 1970-01-01 00:00:00
ResultSet rs = stmt.executeQuery();
rs.next();

// I live in Zurich, which is CET, not GMT. So the following prints -3600000,
// which is CET 1970-01-01 00:00:00
// ... or   GMT 1969-12-31 23:00:00
System.out.println(rs.getDate(1).getTime());
</code>```

In other words, the GMT timestamp I bind to the statement becomes the CET timestamp I get back. At what step is the timezone added and why?

Note:

I have observed this to be true for any of these databases:

DB2, Derby, H2, HSQLDB, Ingres, MySQL, Oracle, Postgres, SQL Server, Sybase ASE, Sybase SQL Anywhere

I have observed this to be false for SQLite (which doesn't really have true DATE data types)

All of this is irrelevant when using java.sql.Timestamp instead of java.sql.Date

This is a similar question, which doesn't answer this question, however: java.util.Date vs java.sql.Date

答:
JDBC 4.2 and java.time

```<code>PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setObject(1, LocalDate.EPOCH); // The epoch year LocalDate, '1970-01-01'.
ResultSet rs = stmt.executeQuery();
rs.next();

// It doesnt matter where you live or your JVM’s time zone setting
// since a LocalDate doesn’t have or use time zone
System.out.println(rs.getObject(1, LocalDate.class));
</code>```

I didn’t test, but unless there’s a bug in your JDBC driver, the output in all time zones is:

1970-01-01

LocalDate is a date without time of day and without time zone. So there is no millisecond value to get and no time of day to be confused about. LocalDate is part of java.time, the modern Java date and time API. JDBC 4.2 specifies that you can transfer java.time objects including LocalDate to and from your SQL database through the methods setObject and getObject I use in the snippet (so not setDate nor getDate).

I think that virtually all of us are using JDBC 4.2 drivers by now.

What went wrong in your code?

java.sql.Date is a hack trying (not very successfully) to disguise a java.util.Date as a date without time of day. I recommend that you don’t use that class.

From the documentation:

To conform with the definition of SQL DATE, the millisecond values
  wrapped by a java.sql.Date instance must be 'normalized' by setting
  the hours, minutes, seconds, and milliseconds to zero in the
  particular time zone with which the instance is associated.

“Associated” may be vague. What this means, I believe, is that the millisecond value must denote the start of day in your JVM’s default time zone (Europe/Zurich in your case, I suppose). So when you create new java.sql.Date(0) equal to GMT 1970-01-01 00:00:00, it’s really you creating an incorrect Date object, since this time is 01:00:00 in your time zone. JDBC is ignoring the time of day (we might have expected an error message, but don’t get any). So SQL is getting and returning a date of 1970-01-01. JDBC correctly translates this back to a Date containing CET 1970-01-01 00:00:00. Or a millisecond value of -3 600 000. Yes, it’s confusing. As I said, don’t use that class.

If you had been at a negative GMT offset (for example most time zones in the Americas), new java.sql.Date(0) would have been interpreted as 1969-12-31, so this would have been the date you had passed to and got back from SQL.

To make matters worse, think what happens when the JVM’s time zone setting is changed. Any part of your program and any other program running in the same JVM may do this at any time. This typically causes all java.sql.Date objects created before the change to become invalid and may sometimes shift their date by one day (in rare cases by two days).

Links

Oracle tutorial: Date Time explaining how to use java.time.

JSR-000221 JDBC™ API Specification 4.2 Maintenance Release 2

Documentation of java.sql.Date

ContentLicense: CC BY-SA 3.0

Title: Timezones in SQL DATE vs java.sql.Date

Body:
I'm getting a bit confused by the behaviour of the SQL DATE data type vs. that of java.sql.Date. Take the following statement, for example:

select cast(? as date)           -- in most databases
select cast(? as date) from dual -- in Oracle

Let's prepare and execute the statement with Java

PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setDate(1, new java.sql.Date(0)); // GMT 1970-01-01 00:00:00
ResultSet rs = stmt.executeQuery();
rs.next();

// I live in Zurich, which is CET, not GMT. So the following prints -3600000,
// which is CET 1970-01-01 00:00:00
// ... or   GMT 1969-12-31 23:00:00
System.out.println(rs.getDate(1).getTime());

In other words, the GMT timestamp I bind to the statement becomes the CET timestamp I get back. At what step is the timezone added and why?

Note:

I have observed this to be true for any of these databases:

DB2, Derby, H2, HSQLDB, Ingres, MySQL, Oracle, Postgres, SQL Server, Sybase ASE, Sybase SQL Anywhere

I have observed this to be false for SQLite (which doesn't really have true DATE data types)

All of this is irrelevant when using java.sql.Timestamp instead of java.sql.Date

This is a similar question, which doesn't answer this question, however: java.util.Date vs java.sql.Date

Body:
JDBC 4.2 and java.time

PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setObject(1, LocalDate.EPOCH); // The epoch year LocalDate, '1970-01-01'.
ResultSet rs = stmt.executeQuery();
rs.next();

// It doesnt matter where you live or your JVM’s time zone setting
// since a LocalDate doesn’t have or use time zone
System.out.println(rs.getObject(1, LocalDate.class));

I didn’t test, but unless there’s a bug in your JDBC driver, the output in all time zones is:

1970-01-01

LocalDate is a date without time of day and without time zone. So there is no millisecond value to get and no time of day to be confused about. LocalDate is part of java.time, the modern Java date and time API. JDBC 4.2 specifies that you can transfer java.time objects including LocalDate to and from your SQL database through the methods setObject and getObject I use in the snippet (so not setDate nor getDate).

I think that virtually all of us are using JDBC 4.2 drivers by now.

What went wrong in your code?

java.sql.Date is a hack trying (not very successfully) to disguise a java.util.Date as a date without time of day. I recommend that you don’t use that class.

From the documentation:

To conform with the definition of SQL DATE, the millisecond values
  wrapped by a java.sql.Date instance must be 'normalized' by setting
  the hours, minutes, seconds, and milliseconds to zero in the
  particular time zone with which the instance is associated.

“Associated” may be vague. What this means, I believe, is that the millisecond value must denote the start of day in your JVM’s default time zone (Europe/Zurich in your case, I suppose). So when you create new java.sql.Date(0) equal to GMT 1970-01-01 00:00:00, it’s really you creating an incorrect Date object, since this time is 01:00:00 in your time zone. JDBC is ignoring the time of day (we might have expected an error message, but don’t get any). So SQL is getting and returning a date of 1970-01-01. JDBC correctly translates this back to a Date containing CET 1970-01-01 00:00:00. Or a millisecond value of -3 600 000. Yes, it’s confusing. As I said, don’t use that class.

If you had been at a negative GMT offset (for example most time zones in the Americas), new java.sql.Date(0) would have been interpreted as 1969-12-31, so this would have been the date you had passed to and got back from SQL.

To make matters worse, think what happens when the JVM’s time zone setting is changed. Any part of your program and any other program running in the same JVM may do this at any time. This typically causes all java.sql.Date objects created before the change to become invalid and may sometimes shift their date by one day (in rare cases by two days).

Links

Oracle tutorial: Date Time explaining how to use java.time.

JSR-000221 JDBC™ API Specification 4.2 Maintenance Release 2

Documentation of java.sql.Date


问:
How can I fix the cannot convert type error?
I want to create a details page about a movie, but I´m getting this error and I´m kinda stuck. I'm getting a cant convert type error. I do understand the error, but I dont have any idea of how to fix it.

This is the Index the PAP Entities is the Database instance:

```<code>public class MoviesController : Controller
{

    PAPEntities db = new PAPEntities();

    public ActionResult Index()
    {

        MovieViewModel[] movies = db.MoviesData.Select(movie => new MovieViewModel
        {
            MovieID = movie.MovieID,
            MovieName = movie.MovieName,
            MovieDescription = movie.MovieDescription,
            MovieCategory = movie.MovieCategory,
            MovieYear = movie.MovieYear
        }).ToArray();

        return View(movies);

    }
</code>```

And this is my details class for now:

```<code>public ActionResult Details(int Id = 1)
    {
        MovieViewModel MovieVM = db.MoviesData.Find(Id);
        return View(MovieVM);
    }
</code>```

I keep getting the error on the "db.MoviesData.Find(Id);"

This is the MovieViewModel code:

```<code>public class MovieViewModel
{
    public int MovieID { get; set; }
    public string MovieName { get; set; }
    public string MovieDescription { get; set; }
    public string MovieCategory { get; set; }
    public string MovieYear { get; set; }
}
</code>```

This is the razor page:

```<code>@model WebApplication3.Models.MovieViewModel[]

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Movies</h2>

<p>
@Html.ActionLink("Create New", "Create")
</code>```

```<code><table class="table table-bordered table-responsive table-hover">
    <tr>
        <th><b>Movie Name </b></th>
        <th><b>Movie Category </b></th>
        <th><b>Movie Year </b></th>
        <th><b>Movie Description </b></th>
        <th></th>

    </tr>
    @foreach (var item in Model)
    {
    <tr>
        <td>@item.MovieID</td>
        <td>@item.MovieCategory</td>
        <td>@item.MovieYear</td>
        <td>@item.MovieDescription</td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
            @Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.MovieID })
        </td>
    </tr>
    }
</table>
</code>```

This is the error:

Cannot implicitly convert type 'WebApplication3.Models.MoviesData' to
  'WebApplication3.Models.MovieViewModel'

The MoviesData is the database's table

答:
In your ActionResult Details method db.MoviesData.Find(Id) returns object which type is WebApplication3.Models.MoviesData but your variable type is MovieViewModel. That's why you are getting exception.

You need to cast manually. So, You can code like this,

public ActionResult Details(int Id = 1)
{
    MoviesData movie = db.MoviesData.Find(Id);
    MovieViewModel MovieVM = new MovieViewModel{
        MovieID = movie.MovieID,
        MovieName = movie.MovieName,
        MovieDescription = movie.MovieDescription,
        MovieCategory = movie.MovieCategory,
        MovieYear = movie.MovieYear
    };

    return View(MovieVM);
}
```

Body:
I want to create a details page about a movie, but I´m getting this error and I´m kinda stuck. I'm getting a cant convert type error. I do understand the error, but I dont have any idea of how to fix it.

This is the Index the PAP Entities is the Database instance:

public class MoviesController : Controller
{

    PAPEntities db = new PAPEntities();

    public ActionResult Index()
    {

        MovieViewModel[] movies = db.MoviesData.Select(movie => new MovieViewModel
        {
            MovieID = movie.MovieID,
            MovieName = movie.MovieName,
            MovieDescription = movie.MovieDescription,
            MovieCategory = movie.MovieCategory,
            MovieYear = movie.MovieYear
        }).ToArray();

        return View(movies);

    }

And this is my details class for now:

public ActionResult Details(int Id = 1)
    {
        MovieViewModel MovieVM = db.MoviesData.Find(Id);
        return View(MovieVM);
    }

I keep getting the error on the "db.MoviesData.Find(Id);"

This is the MovieViewModel code:

public class MovieViewModel
{
    public int MovieID { get; set; }
    public string MovieName { get; set; }
    public string MovieDescription { get; set; }
    public string MovieCategory { get; set; }
    public string MovieYear { get; set; }
}

This is the razor page:

@model WebApplication3.Models.MovieViewModel[]

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

Movies

@Html.ActionLink("Create New", "Create")

        Movie Name
        Movie Category
        Movie Year
        Movie Description

    @foreach (var item in Model)
    {

        @item.MovieID
        @item.MovieCategory
        @item.MovieYear
        @item.MovieDescription

            @Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
            @Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.MovieID })

    }

This is the error:

Cannot implicitly convert type 'WebApplication3.Models.MoviesData' to
  'WebApplication3.Models.MovieViewModel'

The MoviesData is the database's table


问:
onClick post request and redirect to another page
I am new to react and I am learning fetch , but i stucked into post request .

I want to make something like , when the user click on button , a post request happens ,  where I get an ID from the request and redirect to fight/ID

My route is set in the index.js thats not the problem

This is my child component

```<code>function Fight(props){
     if(props.other === 3) {

        return(
            <div className="row">

                    <button className="btn btn-danger"> Fight</button>
                    <p><i>Your team is ready to fight </i></p>
            </div>
            )
    }
</code>```

答:
Thanks to your Router's history prop that wraps your components like this:

```<code>import React, { Component } from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';

class App extends Component {
    render () {
    return (
      <Router history={history}>
        <Switch>
          <Route exact path="/home" component={Home}/>
        </Switch>
      </Router>
    );
  }
}

export default App;
</code>```

In your Home component, you have for example a div with an onClick:
You just do this:

```<code>import React from 'react';
import { withRouter } from 'react-router-dom';

class Home extends React.Component {
  constructor(props) {
    super(props)
  }

  clickMe = () => {
      fetch("http://myapi.com/route")
       .then(function(response) {
          console.log("It worked, response is: ", response)
          this.props.history.push({
              pathname: '/nextcomponent'
          });
       }).catch(function() {
          console.log("error");
       });
  }

  render() {
    return(
      <div onClick={this.clickMe}>
        Click Me!
      </div>
    );
  }
}

export default withRouter(Home);
</code>```

Body:
I am new to react and I am learning fetch , but i stucked into post request .

I want to make something like , when the user click on button , a post request happens ,  where I get an ID from the request and redirect to fight/ID

My route is set in the index.js thats not the problem

This is my child component

function Fight(props){
     if(props.other === 3) {

        return(

                    <button className="btn btn-danger"> Fight</button>

Your team is ready to fight

            )
    }

Body:
Thanks to your Router's history prop that wraps your components like this:

import React, { Component } from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';

class App extends Component {
    render () {
    return (
      <Router history={history}>
        <Switch>
          <Route exact path="/home" component={Home}/>
        </Switch>
      </Router>
    );
  }
}

export default App;

In your Home component, you have for example a div with an onClick:
You just do this:

import React from 'react';
import { withRouter } from 'react-router-dom';

class Home extends React.Component {
  constructor(props) {
    super(props)
  }

  clickMe = () => {
      fetch("http://myapi.com/route")
       .then(function(response) {
          console.log("It worked, response is: ", response)
          this.props.history.push({
              pathname: '/nextcomponent'
          });
       }).catch(function() {
          console.log("error");
       });
  }

  render() {
    return(
      <div onClick={this.clickMe}>
        Click Me!
      </div>
    );
  }
}

export default withRouter(Home);


问:
Property 'tab' does not exist on type 'JQuery'
My Html Code is

```<code><nav class="nav-sidebar">
<ul class="nav tabs" id="myTab">
  <li class="active" ><a  href="#tab3" data-toggle="tab" >Tabl 1</a> </li>
  <li class="tab2"><a href="#tab2" data-toggle="tab">Tab 2</a></li>
  <li ><a href="#tab3" data-toggle="tab">Tab 3</a></li>
  <li ><a href="#tab4" data-toggle="tab">Tab 4</a></li>
  <li><a href="#tab5" data-toggle="tab">Tab 5</a></li>
</ul>
</code>```

And in My .ts

```<code>$('#myTab a').click(function(e) {
     e.preventDefault();
     $(this).tab('show');
   });
   $("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
     var id = $(e.target).attr("href").substr(1);
     window.location.hash = id;
   });
   var hash = window.location.hash;
   $('#myTab a[href="' + hash + '"]').tab('show');
</code>```

Tried so many from stackoverflow and other web sites but i ended up with 'tab' doesn't exist in jquery

答: You need to install @types/bootstrap.

Body:
My Html Code is

Tabl 1

Tab 2

Tab 3

Tab 4

Tab 5

And in My .ts

$('#myTab a').click(function(e) {
     e.preventDefault();
     $(this).tab('show');
   });
   $("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
     var id = $(e.target).attr("href").substr(1);
     window.location.hash = id;
   });
   var hash = window.location.hash;
   $('#myTab a[href="' + hash + '"]').tab('show');

Tried so many from stackoverflow and other web sites but i ended up with 'tab' doesn't exist in jquery

Body: You need to install @types/bootstrap.


问:
Refactoring problem from class to function with hooks
I am refactoring some code and now I am stuck.
The original code is from a tuto :
https://github.com/EricLondon/rails5-react-reactstrap-crud-example
All is fine there.
I try to use hooks new feature.
The new code I wrote just fail.

"Original code" is ok tested
"new code" fails

```<code>//"New code"
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

export default function Posts() {
  const [posts, setPosts] = useState([])
  const [isLoaded, setIsLoaded] = useState(false)
  const [error, setError] = useState(null)

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setIsLoaded(true)
          setPosts([])
          setError(data)
        } else {
          setIsLoaded(true)
          setPosts(data)
        }
      })
  })

  if (error) {

    return (
      <Alert color="danger">
          Error: {error}
      </Alert>
    )

  } else if (!isLoaded) {

    return (
      <Alert color="primary">
          Loading...
      </Alert>
    )

  } else {

    return (
      <Container>
        <Row>
          <Col>
            <PostsTable posts={posts}></PostsTable>
            <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
          </Col>
        </Row>
      </Container>
    )

  }
}

//"Original code"
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

class Posts extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: [],
      isLoaded: false,
      error: null
    }
  }

  componentDidMount() {
    Api.getPosts()
      .then(response => {
        const [error, data] = response
        if (error) {
          this.setState({
            isLoaded: true,
            posts: [],
            error: data
          })
        } else {
          this.setState({
            isLoaded: true,
            posts: data
          })
        }
      })
  }

  render() {
    const { error, isLoaded, posts } = this.state

    if (error) {

      return (
        <Alert color="danger">
          Error: {error}
        </Alert>
      )

    } else if (!isLoaded) {

      return (
        <Alert color="primary">
          Loading...
        </Alert>
      )

    } else {

      return (
        <Container>
          <Row>
            <Col>
              <PostsTable posts={posts}></PostsTable>
              <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
            </Col>
          </Row>
        </Container>
      )

    }

  }
}

export default Posts
</code>```

With "new code" my backend server is driving crazy:
....
Started GET "/api/posts" for 127.0.0.1 at 2019-05-26 20:45:39 +0200
Processing by Api::PostsController#index as HTML
  Post Load (1.3ms)  SELECT "posts".* FROM "posts"
  ↳ app/controllers/api/posts_controller.rb:5
Completed 200 OK in 6ms (Views: 4.4ms | ActiveRecord: 1.3ms)
....
etc.

答:
I think the problem is solved. Thx all.
In fact we wer facing 2 problems at the same time.
1/ [] in second argument was necessary,
2/ then as @olivier said there was some bad code in the child component: PostsTable.
"original code":

```<code>class PostsTable extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: props.posts
    }
  }

  render() {
    const posts = this.state.posts
    if (posts.length === 0) {
      return <div></div> ......
</code>```

I did this :
"New code":

```<code>class PostsTable extends Component {

  render() {
    const posts = this.props.posts
    if (posts.length === 0) {
      return <div></div> .....
</code>```

I just render PostsTable with props only. PostsTable is now stateless.
Nota: in the original code from Eric London I think PostsTable object was created efrom within the global set State.
Using useEffect and setIsLoaded(true); setPosts(data) is more tricky since as soon as setIsLoaded(true) is lauched PostsTable object is created and rendering without calling constructor again.

I ending refactoring like this :

```<code>export default function PostsTable(props)  {
  const posts = props.posts
  if (posts.length === 0) {
    return <div></div> ....
</code>```

thx @olivier

Body:
I am refactoring some code and now I am stuck.
The original code is from a tuto :
https://github.com/EricLondon/rails5-react-reactstrap-crud-example
All is fine there.
I try to use hooks new feature.
The new code I wrote just fail.

"Original code" is ok tested
"new code" fails

//"New code"
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

export default function Posts() {
  const [posts, setPosts] = useState([])
  const [isLoaded, setIsLoaded] = useState(false)
  const [error, setError] = useState(null)

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setIsLoaded(true)
          setPosts([])
          setError(data)
        } else {
          setIsLoaded(true)
          setPosts(data)
        }
      })
  })

  if (error) {

    return (
      <Alert color="danger">
          Error: {error}
      </Alert>
    )

  } else if (!isLoaded) {

    return (
      <Alert color="primary">
          Loading...
      </Alert>
    )

  } else {

    return (
      <Container>
        <Row>
          <Col>
            <PostsTable posts={posts}></PostsTable>
            <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
          </Col>
        </Row>
      </Container>
    )

  }
}

//"Original code"
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

class Posts extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: [],
      isLoaded: false,
      error: null
    }
  }

  componentDidMount() {
    Api.getPosts()
      .then(response => {
        const [error, data] = response
        if (error) {
          this.setState({
            isLoaded: true,
            posts: [],
            error: data
          })
        } else {
          this.setState({
            isLoaded: true,
            posts: data
          })
        }
      })
  }

  render() {
    const { error, isLoaded, posts } = this.state

    if (error) {

      return (
        <Alert color="danger">
          Error: {error}
        </Alert>
      )

    } else if (!isLoaded) {

      return (
        <Alert color="primary">
          Loading...
        </Alert>
      )

    } else {

      return (
        <Container>
          <Row>
            <Col>
              <PostsTable posts={posts}></PostsTable>
              <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
            </Col>
          </Row>
        </Container>
      )

    }

  }
}

export default Posts

With "new code" my backend server is driving crazy:
....
Started GET "/api/posts" for 127.0.0.1 at 2019-05-26 20:45:39 +0200
Processing by Api::PostsController#index as HTML
  Post Load (1.3ms)  SELECT "posts".* FROM "posts"
  ↳ app/controllers/api/posts_controller.rb:5
Completed 200 OK in 6ms (Views: 4.4ms | ActiveRecord: 1.3ms)
....
etc.

Body:
I think the problem is solved. Thx all.
In fact we wer facing 2 problems at the same time.
1/ [] in second argument was necessary,
2/ then as @olivier said there was some bad code in the child component: PostsTable.
"original code":

class PostsTable extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: props.posts
    }
  }

  render() {
    const posts = this.state.posts
    if (posts.length === 0) {
      return <div></div> ......

I did this :
"New code":

class PostsTable extends Component {

  render() {
    const posts = this.props.posts
    if (posts.length === 0) {
      return <div></div> .....

I just render PostsTable with props only. PostsTable is now stateless.
Nota: in the original code from Eric London I think PostsTable object was created efrom within the global set State.
Using useEffect and setIsLoaded(true); setPosts(data) is more tricky since as soon as setIsLoaded(true) is lauched PostsTable object is created and rendering without calling constructor again.

I ending refactoring like this :

export default function PostsTable(props)  {
  const posts = props.posts
  if (posts.length === 0) {
    return <div></div> ....

thx @olivier


问:
Can I assign an image gradient to a rectangle
I'm currently making Mario as a school graphics project.

I have most of the collisions done, but I just want the land and bricks to actually look like land and bricks instead of just colored rectangles. I have an ImageIcon for the "land" in my graphics project. The problem is that it is only 16x16 pixels large. In order to make enough land by just making each part of the land one 16x16 pixel, it would essentially be horribly inefficient.

I was wondering if I could get the ImageIcon or possibly buffered image and use it as the "color" for a rectangle to make the chunks of land easier. If that's not possible, can you offer other suggestions on how to go about this problem?

答:
Using a background of tiled images, a texture:

```<code>private BufferedImage image;

    URL url = getClass().getResource("/mytexture.png");
    assert url != null;
    image =  ImageIO.read(url);

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Rectangle rect = new Rectangle(0, 0, width, height);
    Rectangle textureRect = new Rectangle(0, 0, image.getWidth(), image.getHeight());
    TexturePaint paint = new TexturePaint(image, textureRect);
    g2.setPaint(paint);
    g2.fill(rect);
}
</code>```

In general create your own JPanel.

Gimp and other tools allow to create a tilable image by ensuring that a line running to a border will enter at the opposite border.

Body:
Using a background of tiled images, a texture:

private BufferedImage image;

    URL url = getClass().getResource("/mytexture.png");
    assert url != null;
    image =  ImageIO.read(url);

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Rectangle rect = new Rectangle(0, 0, width, height);
    Rectangle textureRect = new Rectangle(0, 0, image.getWidth(), image.getHeight());
    TexturePaint paint = new TexturePaint(image, textureRect);
    g2.setPaint(paint);
    g2.fill(rect);
}

In general create your own JPanel.

Gimp and other tools allow to create a tilable image by ensuring that a line running to a border will enter at the opposite border.


问:
force window open in internet explorer
I guess what I want to do is not possible.

I would like open a new window using javascript, this is easy:

```<code>popup = window.open('www.google.es', 'titlebar=no,toolbar=no,location=no,status=no,menubar=no,resizable=no, top=0, left=0, type=fullWindow,fullscreen,scrollbars=yes');
</code>```

but I want this new window opens in Internet Explorer whatever the parent was. So, I'm navigating in crhome, and opens the new window in IE.

Is it possible?

答:
You can do it the other way around, that is force to open a link in Edge from an IE page,
window.open("microsoft-edge:http://www.google.com");

but it seems that it's not possible to use a similar command to force a link to open in IE.
It can be achieved using javascript and ActiveX (if enabled) but I can't use this in an enterprise environment (too risky)

Title: force window open in internet explorer

Body:
I guess what I want to do is not possible.

I would like open a new window using javascript, this is easy:

popup = window.open('www.google.es', 'titlebar=no,toolbar=no,location=no,status=no,menubar=no,resizable=no, top=0, left=0, type=fullWindow,fullscreen,scrollbars=yes');

but I want this new window opens in Internet Explorer whatever the parent was. So, I'm navigating in crhome, and opens the new window in IE.

Is it possible?


问:
sed: How to join the lines of a record with an empty line delimiting records
I would like to use 'sed' to joins three lines that make up a record, with records separated by empty lines, and record fields separated by a space.

Here's a snip of data from the file:

```<code>KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'
</code>```

I need to combine the lines like this:

```<code>KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'
</code>```

I'm a novice with sed but pieced together this ugly line.

```<code>sed 'N;s/\n/ /' navlog.txt | sed 'N;s/\n/ /'
</code>```

yea - there is a better way...

答:
If you are looking for a single sed command without having to pipe, this one should work fine!

```<code>sed 'N;N;s/\n/ /g;N;s/\n/ /;s/ $//' navlog.txt
KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'
</code>```

or Alex Harvey suggestion:

```<code>sed '$!N;$!N;$!N;s/\n/ /g;s/ $//' navlog.txt
KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'
</code>```

Also if your file does end up with an empty line:

```<code>$ cat navlog.txt
KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'

^^^^^^^^^^^
</code>```

You can simplify the command into:

```<code>sed 'N;N;N;s/\n/ /g;s/ $//' navlog.txt
KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'
</code>```

Another great suggestion from potong is:

If empty lines are to be deleted then it is better to be explicit about it and as all other solutions do add a space at the end of the line, that need to be removed afterwards via (s/ $//), it is more direct to use:

```<code>sed '/\S/!d;N;N;s/\n/ /g'navlog.txt
KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'
</code>```

Body:
I would like to use 'sed' to joins three lines that make up a record, with records separated by empty lines, and record fields separated by a space.

Here's a snip of data from the file:

KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'

I need to combine the lines like this:

KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'

I'm a novice with sed but pieced together this ugly line.

sed 'N;s/\n/ /' navlog.txt | sed 'N;s/\n/ /'

yea - there is a better way...

Body:
If you are looking for a single sed command without having to pipe, this one should work fine!

sed 'N;N;s/\n/ /g;N;s/\n/ /;s/ $//' navlog.txt
KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'

or Alex Harvey suggestion:

sed '$!N;$!N;$!N;s/\n/ /g;s/ $//' navlog.txt
KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'

Also if your file does end up with an empty line:

$ cat navlog.txt
KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'

^^^^^^^^^^^

You can simplify the command into:

sed 'N;N;N;s/\n/ /g;s/ $//' navlog.txt
KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'

Another great suggestion from potong is:

If empty lines are to be deleted then it is better to be explicit about it and as all other solutions do add a space at the end of the line, that need to be removed afterwards via (s/ $//), it is more direct to use:

sed '/\S/!d;N;N;s/\n/ /g'navlog.txt
KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'


问:
Fixed div on the bottom of the scrollable div
I need a create 4 cards with non-changable height with buttons on the bottom, but there are different text amount in each card.

Position Fixed is connected to body element,
position absolute scrolls with content,
position sticky appears when content ends.

https://codepen.io/anatoli101/pen/NVzbGY Here is a basic exemple of my problem

```<code>.content{
  display:flex;
  width: 100%;
  justify-content: space-around;
}

.fixed-div{
  background-color: red;
  height: 400px;
  width: 300px;
  overflow-y: auto;
}

.button{
  position:sticky;
  bottom:0;
  background-color: grey;
  width: 100%;
  height: 30px;
}
</code>```

答:
```<code>.content{
  display:flex;
  width: 100%;
  justify-content: space-around;
}

.fixed-div{
    position: relative;
    background-color: green;
    height: 400px;
    width: 300px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.button{
  position:relative;
  background-color: grey;
  width: 100%;
  height: 30px;
  display: inline-table;
}
</code>```

Body:
I need a create 4 cards with non-changable height with buttons on the bottom, but there are different text amount in each card.

Position Fixed is connected to body element,
position absolute scrolls with content,
position sticky appears when content ends.

https://codepen.io/anatoli101/pen/NVzbGY Here is a basic exemple of my problem

.content{
  display:flex;
  width: 100%;
  justify-content: space-around;
}

.fixed-div{
  background-color: red;
  height: 400px;
  width: 300px;
  overflow-y: auto;
}

.button{
  position:sticky;
  bottom:0;
  background-color: grey;
  width: 100%;
  height: 30px;
}


问:
How to clone an element and insert it multiple times in one go?
How can I clone an element and insert it 5 times right after each other? This of course is the base statement:

```<code>$('.col').clone().insertAfter('.col');
</code>```

Here's what I need to get:

```<code><div class="col" id="original"> </div>
<div class="col"> </div>
<div class="col"> </div>
<div class="col"> </div>
<div class="col"> </div>
<div class="col"> </div>
</code>```

The selector doesn't need to be using an unique id, it can also be a class selector.

I could just repeat the base statement four times but there must be a more elegant way?

答:
You might want to clone fields when the document is ready against cloning any changes made by client. This is mostly active issue with inputs. Then you should:

Clone the element on document ready: var elementClone = $('#element').clone()

on click clone the cloned element again and add elementClone.clone().insertAfter(element)

Body:
How can I clone an element and insert it 5 times right after each other? This of course is the base statement:

$('.col').clone().insertAfter('.col');

Here's what I need to get:

The selector doesn't need to be using an unique id, it can also be a class selector.

I could just repeat the base statement four times but there must be a more elegant way?


问:
How to use mget to ftp files containing specific string?
I am using mget to retrieve files from a remote server to local directory in Windows.

```<code>lcd C:\E920_1\autopkg\saveE1logafterDir\serverlog
mget /slot/ems2576/appmgr/jdedwards/e920/6210/log/jde_*.log
</code>```

Now, I wish to add additional step to retrieve out of this list, only the files which contains the word "PACKAGE BUILD" inside it.

How do I accomplish it?

答:
It's not possible. FTP protocol does not have an API to find files by their contents.

See also Search Within Files On Remote FTP Site.

So any implementation you will use will have to download all log files and search their contents locally.

In a batch file, you can use findstr command for that:

Batch file to search a keyword in all files of a directory

You may have a different way of accessing the server files. For example, if you have a (SSH) shell access, you can search the files directly on the server. But that's a completely different topic.

Body:
I am using mget to retrieve files from a remote server to local directory in Windows.

lcd C:\E920_1\autopkg\saveE1logafterDir\serverlog
mget /slot/ems2576/appmgr/jdedwards/e920/6210/log/jde_*.log

Now, I wish to add additional step to retrieve out of this list, only the files which contains the word "PACKAGE BUILD" inside it.

How do I accomplish it?


问:
Is there a way to generate a type within a template class out of a template argument and a string
i want to improve my code by getting rid of some template arguments. I have an idea but struggling with the correct code. Its also possible that c++ does not have such an feature, which would be also fine.

The current code looks like this:

class ModelProperties{
public:
    string name;
};

class Model{
public:
    ModelProperties properties;
};

template <class TModel, class TModelProperties>
class ModelWrapper{
private:
    TModel m_model;
public:
ModelWrapper(TModel model){
    m_model = model;
}

TModelProperties getProperties(){
    return m_model.properties;
}
};
```

<p>I would like to have something like this:</p>

<pre class="lang-cpp prettyprint-override"><code>
template <class TModel>
class ModelWrapper{

private:
    TModel m_model;

public:
ModelWrapper(TModel model){
    m_model = model;
}

TModel + "Properties" getProperties(){
    return m_model.properties;
}

};
</code>```

答:
This question boils down to deducing the return type of ModelWrapper::getProperties. Given that you really want to return a copy and not a reference, there are these equivalent options:

```<code>auto getProperties() const { return m_model.properties; }

std::remove_reference_t<decltype(TModel::properties)> getProperties() const
{ return m_model.properties; }
</code>```

If you do not want to use the auto keyword in a signature (perhaps for the sake of documentation), rather declare a type alias for the properties for each Model:

```<code>class Model {
public:
    using properties_t = ModelProperties;
    properties_t properties;
};
</code>```

which you can substitute for auto like so:

```<code>typename TModel::properties_t getProperties() const { return m_model.properties; }
</code>```

Alternatively, if your Model classes were defined as templates like so:

```<code>template <typename TProperties>
class Model {
public:
    TProperties properties;
};
</code>```

you could do:

```<code>template <template <typename TProperties> class TModel>
class ModelWrapper {
    ...
    TProperties getProperties() const { return m_model.properties; }
};
</code>```

where TProperties is automatically deduced during the instantiation of ModelWrapper.

Body:
i want to improve my code by getting rid of some template arguments. I have an idea but struggling with the correct code. Its also possible that c++ does not have such an feature, which would be also fine.

The current code looks like this:

class ModelProperties{
public:
    string name;
};

class Model{
public:
    ModelProperties properties;
};

template <class TModel, class TModelProperties>
class ModelWrapper{
private:
    TModel m_model;
public:
ModelWrapper(TModel model){
    m_model = model;
}

TModelProperties getProperties(){
    return m_model.properties;
}
};

I would like to have something like this:

template <class TModel>
class ModelWrapper{

private:
    TModel m_model;

public:
ModelWrapper(TModel model){
    m_model = model;
}

TModel + "Properties" getProperties(){
    return m_model.properties;
}

};

Body:
This question boils down to deducing the return type of ModelWrapper::getProperties. Given that you really want to return a copy and not a reference, there are these equivalent options:

auto getProperties() const { return m_model.properties; }

std::remove_reference_t<decltype(TModel::properties)> getProperties() const
{ return m_model.properties; }

If you do not want to use the auto keyword in a signature (perhaps for the sake of documentation), rather declare a type alias for the properties for each Model:

class Model {
public:
    using properties_t = ModelProperties;
    properties_t properties;
};

which you can substitute for auto like so:

typename TModel::properties_t getProperties() const { return m_model.properties; }

Alternatively, if your Model classes were defined as templates like so:

template <typename TProperties>
class Model {
public:
    TProperties properties;
};

you could do:

template <template <typename TProperties> class TModel>
class ModelWrapper {
    ...
    TProperties getProperties() const { return m_model.properties; }
};

where TProperties is automatically deduced during the instantiation of ModelWrapper.


问:
Run a function onblur when only when none of 3 inputs have focus
I need to accept the start date of an event in an HTML form
Created 3 Separate select boxes for date, month, and time as follows

I want to run an onblur function on any of the boxes and should return false
if any other 2 boxes have focus

  <form name=event method=post action=xxx.asp>
    Start Date
    <Select id=startDD name=startDD style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "dddd")>
      <Option value="">DD</option>
      <Option value="1">1</option>
      <Option value="2">2</option>
      <Option value="3">3</option>
      <Option value="4">4</option>
      <Option value="5">5</option>
      <Option value="6">6</option>
      <Option value="7">7</option>
      <Option value="8">8</option>
      <Option value="9">9</option>
      <Option value="10">10</option>
      <Option value="11">11</option>
      <Option value="12">12</option>
      <Option value="13">13</option>
      <Option value="14">14</option>
      <Option value="15">15</option>
      <Option value="16">16</option>
      <Option value="17">17</option>
      <Option value="18">18</option>
      <Option value="19">19</option>
      <Option value="20">20</option>
      <Option value="21">21</option>
      <Option value="22">22</option>
      <Option value="23">23</option>
      <Option value="24">23</option>
      <Option value="25">25</option>
      <Option value="26">26</option>
      <Option value="27">27</option>
      <Option value="28">28</option>
      <Option value="29">29</option>
      <Option value="30">30</option>
      <Option value="31">31</option>
    </Select>
    <Select id=startMM name=startMM style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "mmmm")>
      <Option value="">MM</option>
      <Option value="0">Jan</option>
      <Option value="1">Feb</option>
      <Option value="2">Mar</option>
      <Option value="3">Apr</option>
      <Option value="4">May</option>
      <Option value="5">June</option>
      <Option value="6">Jul</option>
      <Option value="7">Aug</option>
      <Option value="8">Sep</option>
      <Option value="9">Oct</option>
      <Option value="10">Nov</option>
      <Option value="11">Dec</option>
    </Select>
    <Select id=startYY name=startYY style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "yyyy")>
      <Option value="">YYYY</option>
      <Option value="2019">2019</option>
      <Option value="2020">2020</option>
      <Option value="2021">2021</option>
      <Option value="2022">2022</option>
      <Option value="2023">2023</option>
      <Option value="2024">2024</option>
      <Option value="2025">2025</option>
    </Select>
    (Start Date in DD/MM/YYYY Format)

  </form>

```

I want the onblur event to validate the date only if focus is not on any of the 3 select boxes (not happening)

答:
For your second point to validate the date :

Create a date object by passing the iso string representation of your date

Create an iso string representation of your date

Ensure this two string are identical

```<code>new Date("2019-04-31T00:00:00.000Z").toJSON() // "2019-05-01T00:00:00.000Z"
</code>```

function validateDate(dd, mm, yyyy)
{
 dd = (dd < 10) ? "0"+dd : dd;
    mm = (mm < 10) ? "0"+mm : mm;
    yyyy = (yyyy < 100) ? "20"+yyyy : yyyy;

    var d_iso = new Date(yyyy+"-"+mm+"-"+dd+"T00:00:00.000Z").toJSON();
    var iso = yyyy+"-"+mm+"-"+dd+"T00:00:00.000Z";

    if(d_iso === iso)
       return true;
    else
       return false;
}

console.log(validateDate(4, 2, 19)); // true
console.log(validateDate(31, 2, 19)); // false
console.log(validateDate(31, 4, 2019)); // false
console.log(validateDate(31, 3, 2019)); // true```

Body:
I need to accept the start date of an event in an HTML form
Created 3 Separate select boxes for date, month, and time as follows

I want to run an onblur function on any of the boxes and should return false
if any other 2 boxes have focus

  <form name=event method=post action=xxx.asp>
    Start Date
    <Select id=startDD name=startDD style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "dddd")>
      <Option value="">DD</option>
      <Option value="1">1</option>
      <Option value="2">2</option>
      <Option value="3">3</option>
      <Option value="4">4</option>
      <Option value="5">5</option>
      <Option value="6">6</option>
      <Option value="7">7</option>
      <Option value="8">8</option>
      <Option value="9">9</option>
      <Option value="10">10</option>
      <Option value="11">11</option>
      <Option value="12">12</option>
      <Option value="13">13</option>
      <Option value="14">14</option>
      <Option value="15">15</option>
      <Option value="16">16</option>
      <Option value="17">17</option>
      <Option value="18">18</option>
      <Option value="19">19</option>
      <Option value="20">20</option>
      <Option value="21">21</option>
      <Option value="22">22</option>
      <Option value="23">23</option>
      <Option value="24">23</option>
      <Option value="25">25</option>
      <Option value="26">26</option>
      <Option value="27">27</option>
      <Option value="28">28</option>
      <Option value="29">29</option>
      <Option value="30">30</option>
      <Option value="31">31</option>
    </Select>
    <Select id=startMM name=startMM style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "mmmm")>
      <Option value="">MM</option>
      <Option value="0">Jan</option>
      <Option value="1">Feb</option>
      <Option value="2">Mar</option>
      <Option value="3">Apr</option>
      <Option value="4">May</option>
      <Option value="5">June</option>
      <Option value="6">Jul</option>
      <Option value="7">Aug</option>
      <Option value="8">Sep</option>
      <Option value="9">Oct</option>
      <Option value="10">Nov</option>
      <Option value="11">Dec</option>
    </Select>
    <Select id=startYY name=startYY style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "yyyy")>
      <Option value="">YYYY</option>
      <Option value="2019">2019</option>
      <Option value="2020">2020</option>
      <Option value="2021">2021</option>
      <Option value="2022">2022</option>
      <Option value="2023">2023</option>
      <Option value="2024">2024</option>
      <Option value="2025">2025</option>
    </Select>
    (Start Date in DD/MM/YYYY Format)

  </form>

I want the onblur event to validate the date only if focus is not on any of the 3 select boxes (not happening)

Body:
For your second point to validate the date :

Create a date object by passing the iso string representation of your date

Create an iso string representation of your date

Ensure this two string are identical

new Date("2019-04-31T00:00:00.000Z").toJSON() // "2019-05-01T00:00:00.000Z"

function validateDate(dd, mm, yyyy)
{
 dd = (dd < 10) ? "0"+dd : dd;
    mm = (mm < 10) ? "0"+mm : mm;
    yyyy = (yyyy < 100) ? "20"+yyyy : yyyy;

    var d_iso = new Date(yyyy+"-"+mm+"-"+dd+"T00:00:00.000Z").toJSON();
    var iso = yyyy+"-"+mm+"-"+dd+"T00:00:00.000Z";

    if(d_iso === iso)
       return true;
    else
       return false;
}

console.log(validateDate(4, 2, 19)); // true
console.log(validateDate(31, 2, 19)); // false
console.log(validateDate(31, 4, 2019)); // false
console.log(validateDate(31, 3, 2019)); // true


问:
How to write very small text in HTML
I would like to have a font smaller than an Arial 9px text.

I've tried to find other font name but I did not succeed to get a very small text. Is there a way to achieve this easily using css ?

EDIT :
I can't go under 9px using Arial
I have tried font-size, small, transform, scale, other fonts... everything as I am an experienced web developper.

答:
Set font-size to whatever you want - although you may find that any font less than 9px may be too small to read well. You could also do it with em's or rem's or percentages.

But you can set the font size as follows (for an example p element that you want to be 6px in size).

```<code> p {font-size: 6px}
</code>```

So note that you are not importing the smallest possible font - you are sizing the html elements to be a small font-size with CSS). Using this principle- you set the fontsize for all the elements you want to use it - eg: p, span, a, li, h etc.

But again - I must caution against this for accessibility purposes.

p {
 font-family: Arial;
 font-size: 6px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>This is a test with Arial font at 6px and is NOT recommended</p></code>```

Title: How to write very small text in HTML

Body:
Set font-size to whatever you want - although you may find that any font less than 9px may be too small to read well. You could also do it with em's or rem's or percentages.

But you can set the font size as follows (for an example p element that you want to be 6px in size).

 p {font-size: 6px}

So note that you are not importing the smallest possible font - you are sizing the html elements to be a small font-size with CSS). Using this principle- you set the fontsize for all the elements you want to use it - eg: p, span, a, li, h etc.

But again - I must caution against this for accessibility purposes.

p {
 font-family: Arial;
 font-size: 6px;
}

<p>This is a test with Arial font at 6px and is NOT recommended</p>


答:
You can use HTML  tag.
https://www.w3schools.com/tags/tag_small.asp

Title: How to write very small text in HTML

Body:
I would like to have a font smaller than an Arial 9px text.

I've tried to find other font name but I did not succeed to get a very small text. Is there a way to achieve this easily using css ?

EDIT :
I can't go under 9px using Arial
I have tried font-size, small, transform, scale, other fonts... everything as I am an experienced web developper.

Body:
You can use HTML <small> tag.
https://www.w3schools.com/tags/tag_small.asp


问:
Access main activity FloatingActionButton from Fragments
I have a an activity with 3 fragments. Each fragment has to have a FAB with different icon an action.
The FAB is defined on the main activity layout. Now I saw that I cannot access it from fragments. How can I do it?

Here's my code:
main_activity layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        tools:layout_editor_absoluteX="16dp">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabMode="fixed" />
    </android.support.v4.view.ViewPager>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="24dp"
        android:src="@android:drawable/ic_dialog_email"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

my fragment layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackgroundFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/contact_recycleview">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>
</code>```

inflating the fragment:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v= inflater.inflate(R.layout.filters_fragment,container,false);

    myrecyclerview = (RecyclerView) v.findViewById(R.id.contact_recycleview);
    recyclerAdapter = new RecyclerViewAdapterCall(getContext(), lstCall);
    myrecyclerview.setLayoutManager(new LinearLayoutManager((getActivity())));
    myrecyclerview.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    myrecyclerview.setAdapter(recyclerAdapter);

    return v;
}
</code>```

so here I'll like to change icon an action, how?

答:
Step 1 create interface

```<code>  public interface FabButtonClick {
         void onFabClicked();
         void onFabClickedTwo();
    }
</code>```

Step 2 : inside activity

```<code> FabButtonClick fabButtonClick ;

inside `oncreate()` of activity

    fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

switch(mViewPager.getCurrentItem()){
case 0:
fabButtonClick.onFabClicked()
break;
case 1:
fabButtonClick.onFabClickedTwo()
break;
etc
}

                }
            });
</code>```

Inside of activity only

```<code>private void setListener(FabButtonClick interface){
    fabButtonClick =interface;
}

fragment implement FabButtonClick
</code>```

Inside fragments onViewCreated

```<code>((YOUR_ACTIVITY_NAME)getActivity()).setListener(this)
</code>```

Overridden method from interface now let you handle fab clicks in Fragment

Body:
I have a an activity with 3 fragments. Each fragment has to have a FAB with different icon an action.
The FAB is defined on the main activity layout. Now I saw that I cannot access it from fragments. How can I do it?

Here's my code:
main_activity layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        tools:layout_editor_absoluteX="16dp">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabMode="fixed" />
    </android.support.v4.view.ViewPager>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="24dp"
        android:src="@android:drawable/ic_dialog_email"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

my fragment layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackgroundFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/contact_recycleview">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

inflating the fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v= inflater.inflate(R.layout.filters_fragment,container,false);

    myrecyclerview = (RecyclerView) v.findViewById(R.id.contact_recycleview);
    recyclerAdapter = new RecyclerViewAdapterCall(getContext(), lstCall);
    myrecyclerview.setLayoutManager(new LinearLayoutManager((getActivity())));
    myrecyclerview.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    myrecyclerview.setAdapter(recyclerAdapter);

    return v;
}

so here I'll like to change icon an action, how?

Body:
Step 1 create interface

  public interface FabButtonClick {
         void onFabClicked();
         void onFabClickedTwo();
    }

Step 2 : inside activity

 FabButtonClick fabButtonClick ;

inside `oncreate()` of activity

    fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

switch(mViewPager.getCurrentItem()){
case 0:
fabButtonClick.onFabClicked()
break;
case 1:
fabButtonClick.onFabClickedTwo()
break;
etc
}

                }
            });

Inside of activity only

private void setListener(FabButtonClick interface){
    fabButtonClick =interface;
}

fragment implement FabButtonClick

Inside fragments onViewCreated

((YOUR_ACTIVITY_NAME)getActivity()).setListener(this)

Overridden method from interface now let you handle fab clicks in Fragment


问:
How can I merge results to a single dataframe after exctracting columns from different excel sheets?
I am extracting columns from different excel files in a for loop and I want to merge the results to a single dataframe (concat).

```<code>result = pd.DataFrame()
for excel in excels :
excel_df = pd.read_excel(excel)
extracted_columns = excel_df[[‚min', original_name]]

result = pd.concat(result , extracted_columns)          #?
result.to_excel(‚summary.xlsx’)

result-liste in excel

extracted_columns
index   File1       (empty)                  File 2     (empty) .....
1    min values  original_name values     min values    original_name values
2    min values  origina_name values      min values    original_name values
</code>```

How can I add the columns like in the psydocode line marked with #? to get an excel like in the lower part(extracted_columns) is equal for every file.

It would also be nice to add the filename.

答:
You can append DataFrames to list and then concat:

```<code>result = []
for excel in excels:
    #filter columns by usecols parameter
    excel_df = pd.read_excel(excel, usecols=['min', 'original_name'])
    #filter columns by lists
    excel_df = pd.read_excel(excel)[['min', 'original_name']]
</code>```

Or:

```<code>result = [pd.read_excel(excel, usecols=['min', 'original_name']) for excel in excels]
result = [pd.read_excel(excel)[['min', 'original_name']] for excel in excels]
</code>```

```<code>result = pd.concat(result, ignore_index=True)
result.to_excel('summary.xlsx', index=False)
</code>```

Body:
I am extracting columns from different excel files in a for loop and I want to merge the results to a single dataframe (concat).

result = pd.DataFrame()
for excel in excels :
excel_df = pd.read_excel(excel)
extracted_columns = excel_df[[‚min', original_name]]

result = pd.concat(result , extracted_columns)          #?
result.to_excel(‚summary.xlsx’)

result-liste in excel

extracted_columns
index   File1       (empty)                  File 2     (empty) .....
1    min values  original_name values     min values    original_name values
2    min values  origina_name values      min values    original_name values

How can I add the columns like in the psydocode line marked with #? to get an excel like in the lower part(extracted_columns) is equal for every file.

It would also be nice to add the filename.

Body:
You can append DataFrames to list and then concat:

result = []
for excel in excels:
    #filter columns by usecols parameter
    excel_df = pd.read_excel(excel, usecols=['min', 'original_name'])
    #filter columns by lists
    excel_df = pd.read_excel(excel)[['min', 'original_name']]

Or:

result = [pd.read_excel(excel, usecols=['min', 'original_name']) for excel in excels]
result = [pd.read_excel(excel)[['min', 'original_name']] for excel in excels]

result = pd.concat(result, ignore_index=True)
result.to_excel('summary.xlsx', index=False)


问:
Postgresql. How to copy the value of a cell in a row and paste it into another cell of another row in the same table using python
I'm starting studying Python and PostgreSQL.

I'm trying to update the value of a cell in a row, based on the value of another cell in another row of the same table.

Let's made an example:
I've this table:

```<code>ID | name | age
1  | John |  20
2  | Jack |  30
3  | Mary |  40
</code>```

What I would like to do is to make a query that change the age of John based on the age of Jack (copy the age of Jack and paste it in the age of John)

and so this will be the result to be achieved:

```<code>ID | name | age
1  | John |  30
2  | Jack |  30
3  | Mary |  40
</code>```

Someone could help me? thanks

答:
One way is to use a subquery in the assignment in the SET clause.

```<code>UPDATE elbat
       SET age = (SELECT t.age
                         FROM elbat t
                         WHERE t.name = 'Jack')
       WHERE name = 'John';
</code>```

Body:
I'm starting studying Python and PostgreSQL.

I'm trying to update the value of a cell in a row, based on the value of another cell in another row of the same table.

Let's made an example:
I've this table:

ID | name | age
1  | John |  20
2  | Jack |  30
3  | Mary |  40

What I would like to do is to make a query that change the age of John based on the age of Jack (copy the age of Jack and paste it in the age of John)

and so this will be the result to be achieved:

ID | name | age
1  | John |  30
2  | Jack |  30
3  | Mary |  40

Someone could help me? thanks

Body:
One way is to use a subquery in the assignment in the SET clause.

UPDATE elbat
       SET age = (SELECT t.age
                         FROM elbat t
                         WHERE t.name = 'Jack')
       WHERE name = 'John';


问:
LINQ side effects
is it possible to substitute a foreach loop with a lambda expression in LINQ (.Select))?

```<code>List<int> l = {1, 2, 3, 4, 5};
foreach (int i in l)
    Console.WriteLine(i);
</code>```

To:

```<code>List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);
</code>```

答: Use List.ForEach instead.</p>

Title: LINQ side effects

Body:
is it possible to substitute a foreach loop with a lambda expression in LINQ (.Select))?

List<int> l = {1, 2, 3, 4, 5};
foreach (int i in l)
    Console.WriteLine(i);

To:

List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);

Body: Use List.ForEach instead.


问:
Sulu: Is it possible to limit Categories per webspace?
We have a sulu 1.6 multi site installation and are wondering if it is possible to limit the available categories per webspace?

Something like:

webspace 1:

cat 1 and children only

webspace 2:

cat 2 and children

cat 3 and children

Is that possible?

答:
Sorry, but this is not possible. The closest thing I can tell you about is our rootKey parameter of the category API. This query parameter would allow you to only return children of the category with the given key. The key is the second line in the contact form.

So if you send a request like this, you should get only a subtree of the categories:

/admin/api/categories?locale=en&flat=true&rootKey=category1

However, the bad news is that this query parameter is not used by the category_list field type. However, a PR would be highly appreciated, and probably get merged :-)


问:
Make all the elemant zero except max n element in each row in numpy 2d-array
Let's say I have a 2D numpy array like:

```<code>[[1, 8, 3, 4, 5],
 [10,13,13,12,15]]
</code>```

I want to convert all the elements to zero except the maximum or maximum 2 elements in each row. The output I'd like to get is:

```<code>[[0, 8, 0,0, 5],
 [0,13,13,0,15]]
</code>```

How can I do this?

答:
```<code>def func(x):
    x[np.argwhere(x != x.max())] = 0
    return x

arr = np.array([[1, 8, 3, 4, 5],
               [10,13,13,12,15]])

new_arr = np.apply_along_axis(func,  1, arr)
</code>```

You can modify the function "func" for largest 2 numbers. The above snippet replaces all the elements with 0 except the largest one in every row.

Update : For doing it with largest n elements you can use the following function in apply,

```<code>n = 2
def func(x):
    global n
    idx = (-x).argsort()[n:]
    x[idx] = 0
    return x

arr = np.array([[1, 8, 3, 4, 5],
               [10,13,13,12,15]])

new_arr = np.apply_along_axis(func,  1, arr)
</code>```

Body:
Let's say I have a 2D numpy array like:

[[1, 8, 3, 4, 5],
 [10,13,13,12,15]]

I want to convert all the elements to zero except the maximum or maximum 2 elements in each row. The output I'd like to get is:

[[0, 8, 0,0, 5],
 [0,13,13,0,15]]

How can I do this?

Body:
def func(x):
    x[np.argwhere(x != x.max())] = 0
    return x

arr = np.array([[1, 8, 3, 4, 5],
               [10,13,13,12,15]])

new_arr = np.apply_along_axis(func,  1, arr)

You can modify the function "func" for largest 2 numbers. The above snippet replaces all the elements with 0 except the largest one in every row.

Update : For doing it with largest n elements you can use the following function in apply,

n = 2
def func(x):
    global n
    idx = (-x).argsort()[n:]
    x[idx] = 0
    return x

arr = np.array([[1, 8, 3, 4, 5],
               [10,13,13,12,15]])

new_arr = np.apply_along_axis(func,  1, arr)


问:
How to send a ref to a function as a parameter in React Native?
I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like this.

```<code>render() {
  return (
    <View>
      <MyComponent ref={component => this.myComponent = component} />
    </View>
  )
}
</code>```

Then, I've created another function to access the state of my custom component. I wrote it like this.

```<code>myFunction = (ref) => {
  ref.setState({ myState: myValue })
}
</code>```

Then, I called that function like this.

```<code>this.myFunction(this.myComponent)
</code>```

But, it does not work. It gives me the following error.

null is not an object (evaluating 'ref.setState')

Actually what I need this myFunction to do is,

```<code>this.myComponent.setState({ myState: myValue })
</code>```

Can you please help me to solve this problem?

答:
ref is not your this object. it's dom for your componnet. For setState you need this of your component.

you can pass this as argument.

myFunction(this)

Now you will be able to do ref.setState in myFunction.

```<code>function myFunction(ref) {
    ref.setState({ myState: myValue })
}
</code>```

Body:
I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like this.

render() {
  return (
    <View>
      <MyComponent ref={component => this.myComponent = component} />
    </View>
  )
}

Then, I've created another function to access the state of my custom component. I wrote it like this.

myFunction = (ref) => {
  ref.setState({ myState: myValue })
}

Then, I called that function like this.

this.myFunction(this.myComponent)

But, it does not work. It gives me the following error.

null is not an object (evaluating 'ref.setState')

Actually what I need this myFunction to do is,

this.myComponent.setState({ myState: myValue })

Can you please help me to solve this problem?

Body:
ref is not your this object. it's dom for your componnet. For setState you need this of your component.

you can pass this as argument.

myFunction(this)

Now you will be able to do ref.setState in myFunction.

function myFunction(ref) {
    ref.setState({ myState: myValue })
}


问:
Implementing partial recursive function in C#
I am having trouble with somwhow implementing a partial recursive function (at least in my mind though).

for any given p and arbitrary maxsteps = 100, calculate L:

答:
You could pass the maxsteps down to the recursive function and subtract 1 on each step until you reach 0, with is the end condition:</p>

```<code>public double L(double p, int maxSteps)
{
    if (maxSteps == 0)
    {
        return 1 / (p + 1);
    }
    return 1 / (p + L(p, maxSteps - 1));
}
</code>```

Body:
You could pass the maxsteps down to the recursive function and subtract 1 on each step until you reach 0, with is the end condition:

public double L(double p, int maxSteps)
{
    if (maxSteps == 0)
    {
        return 1 / (p + 1);
    }
    return 1 / (p + L(p, maxSteps - 1));
}


问:
How to extract data from a dropdown menu using python beautifulsoup
I am trying to scrape data from a website that has a multilevel drop-down menu every time an item is selected it changes the sub items for sub drop-downs.
problem is that for every loop it extracts same sub items from the drop down items. the selection happens but it do not update the items on behalf of new selection from loop
can any one help me why I am not getting the desired results.
Perhaps this is because my drop-down list is in java Script or something.

for instance like this manue in the picture below:

i have gone this far:

```<code>enter code here

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import csv

//#from selenium.webdriver.support import Select
import time

print ("opening chorome....")
driver = webdriver.Chrome()
driver.get('https://www.wheelmax.com/')
time.sleep(10)

csvData = ['Year', 'Make', 'Model', 'Body', 'Submodel', 'Size']

//#variables
yeart = []
make= []
model=[]
body = []
submodel = []
size = []
Yindex = Mkindex = Mdindex = Bdindex = Smindex = Sindex = 0

print ("waiting for program to set variables....")
time.sleep(20)

print ("initializing and setting variables....")

//#initializing Year
Year = Select(driver.find_element_by_id("icm-years-select"))
Year.select_by_value('2020')
yr = driver.find_elements(By.XPATH, '//*[@id="icm-years-select"]')
time.sleep(15)

//#initializing Make
Make = Select(driver.find_element_by_id("icm-makes-select"))
Make.select_by_index(1)
mk = driver.find_elements(By.XPATH, '//*[@id="icm-makes-select"]')
time.sleep(15)

//#initializing Model
Model = Select(driver.find_element_by_id("icm-models-select"))
Model.select_by_index(1)
mdl = driver.find_elements(By.XPATH, '//*[@id="icm-models-select"]')
time.sleep(15)

//#initializing body
Body = Select(driver.find_element_by_id("icm-drivebodies-select"))
Body.select_by_index(1)
bdy = driver.find_elements(By.XPATH, '//*[@id="icm-drivebodies-select"]')
time.sleep(15)

//#initializing submodel
Submodel = Select(driver.find_element_by_id("icm-submodels-select"))
Submodel.select_by_index(1)
sbm = driver.find_elements(By.XPATH, '//*[@id="icm-submodels-select"]')
time.sleep(15)

//#initializing size
Size = Select(driver.find_element_by_id("icm-sizes-select"))
Size.select_by_index(0)
siz = driver.find_elements(By.XPATH, '//*[@id="icm-sizes-select"]')
time.sleep(5)

Cyr = Cmk = Cmd = Cbd = Csmd = Csz = ""

print ("fetching data from variables....")

for y in yr:
    obj1 = driver.find_element_by_id("icm-years-select")
    Year = Select(obj1)
    Year.select_by_index(++Yindex)
    obj1.click()
    #obj1.click()
    yeart.append(y.text)
    Cyr = y.text
    time.sleep(10)
    for m in mk:
        obj2 = driver.find_element_by_id("icm-makes-select")
        Make = Select(obj2)
        Make.select_by_index(++Mkindex)
        obj2.click()
        #obj2.click()
        make.append(m.text)
        Cmk = m.text
        time.sleep(10)
        for md in mdl:
            Mdindex =0
            obj3 = driver.find_element_by_id("icm-models-select")
            Model = Select(obj3)
            Model.select_by_index(++Mdindex)
            obj3.click()
            #obj3.click(clickobj)
            model.append(md.text)
            Cmd = md.text
            time.sleep(10)
            Bdindex = 0
            for bd in bdy:
                obj4 = driver.find_element_by_id("icm-drivebodies-select")
                Body = Select(obj4)
                Body.select_by_index(++Bdindex)
                obj4.click()
                #obj4.click(clickobj2)
                body.append(bd.text)
                Cbd = bd.text
                time.sleep(10)
                Smindex = 0
                for sm in sbm:
                    obj5 = driver.find_element_by_id("icm-submodels-select")
                    Submodel = Select(obj5)
                    obj5.click()
                    Submodel.select_by_index(++Smindex)
                    #obj5.click(clickobj5)
                    submodel.append(sm.text)
                    Csmd = sm.text
                    time.sleep(10)
                    Sindex = 0
                    for sz in siz:
                        Size = Select(driver.find_element_by_id("icm-sizes-select"))
                        Size.select_by_index(++Sindex)
                        size.append(sz.text)
                        Scz = sz.text
                        csvData += [Cyr, Cmk, Cmd, Cbd,Csmd, Csz]
</code>```

答:
How to extract data from a dropdown menu using python beautifulsoup

The page does a callback to populate with years. Simply mimic that.

If you actually need to change years and select from dependent drop downs, which becomes a different question, you need browser automation e.g. selenium, or to manually perform this and inspect network tab to see if there is an xhr request you can mimic to submit your choices.

```<code>import requests

r = requests.get('https://www.iconfigurators.com/json2/?returnType=json&bypass=true&id=13898&callback=yearObj').json()
years = [item['year'] for item in r['years']]
print(years)
</code>```

Body:
I am trying to scrape data from a website that has a multilevel drop-down menu every time an item is selected it changes the sub items for sub drop-downs.
problem is that for every loop it extracts same sub items from the drop down items. the selection happens but it do not update the items on behalf of new selection from loop
can any one help me why I am not getting the desired results.
Perhaps this is because my drop-down list is in java Script or something.

for instance like this manue in the picture below:

i have gone this far:

enter code here

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import csv

//#from selenium.webdriver.support import Select
import time

print ("opening chorome....")
driver = webdriver.Chrome()
driver.get('https://www.wheelmax.com/')
time.sleep(10)

csvData = ['Year', 'Make', 'Model', 'Body', 'Submodel', 'Size']

//#variables
yeart = []
make= []
model=[]
body = []
submodel = []
size = []
Yindex = Mkindex = Mdindex = Bdindex = Smindex = Sindex = 0

print ("waiting for program to set variables....")
time.sleep(20)

print ("initializing and setting variables....")

//#initializing Year
Year = Select(driver.find_element_by_id("icm-years-select"))
Year.select_by_value('2020')
yr = driver.find_elements(By.XPATH, '//*[@id="icm-years-select"]')
time.sleep(15)

//#initializing Make
Make = Select(driver.find_element_by_id("icm-makes-select"))
Make.select_by_index(1)
mk = driver.find_elements(By.XPATH, '//*[@id="icm-makes-select"]')
time.sleep(15)

//#initializing Model
Model = Select(driver.find_element_by_id("icm-models-select"))
Model.select_by_index(1)
mdl = driver.find_elements(By.XPATH, '//*[@id="icm-models-select"]')
time.sleep(15)

//#initializing body
Body = Select(driver.find_element_by_id("icm-drivebodies-select"))
Body.select_by_index(1)
bdy = driver.find_elements(By.XPATH, '//*[@id="icm-drivebodies-select"]')
time.sleep(15)

//#initializing submodel
Submodel = Select(driver.find_element_by_id("icm-submodels-select"))
Submodel.select_by_index(1)
sbm = driver.find_elements(By.XPATH, '//*[@id="icm-submodels-select"]')
time.sleep(15)

//#initializing size
Size = Select(driver.find_element_by_id("icm-sizes-select"))
Size.select_by_index(0)
siz = driver.find_elements(By.XPATH, '//*[@id="icm-sizes-select"]')
time.sleep(5)

Cyr = Cmk = Cmd = Cbd = Csmd = Csz = ""

print ("fetching data from variables....")

for y in yr:
    obj1 = driver.find_element_by_id("icm-years-select")
    Year = Select(obj1)
    Year.select_by_index(++Yindex)
    obj1.click()
    #obj1.click()
    yeart.append(y.text)
    Cyr = y.text
    time.sleep(10)
    for m in mk:
        obj2 = driver.find_element_by_id("icm-makes-select")
        Make = Select(obj2)
        Make.select_by_index(++Mkindex)
        obj2.click()
        #obj2.click()
        make.append(m.text)
        Cmk = m.text
        time.sleep(10)
        for md in mdl:
            Mdindex =0
            obj3 = driver.find_element_by_id("icm-models-select")
            Model = Select(obj3)
            Model.select_by_index(++Mdindex)
            obj3.click()
            #obj3.click(clickobj)
            model.append(md.text)
            Cmd = md.text
            time.sleep(10)
            Bdindex = 0
            for bd in bdy:
                obj4 = driver.find_element_by_id("icm-drivebodies-select")
                Body = Select(obj4)
                Body.select_by_index(++Bdindex)
                obj4.click()
                #obj4.click(clickobj2)
                body.append(bd.text)
                Cbd = bd.text
                time.sleep(10)
                Smindex = 0
                for sm in sbm:
                    obj5 = driver.find_element_by_id("icm-submodels-select")
                    Submodel = Select(obj5)
                    obj5.click()
                    Submodel.select_by_index(++Smindex)
                    #obj5.click(clickobj5)
                    submodel.append(sm.text)
                    Csmd = sm.text
                    time.sleep(10)
                    Sindex = 0
                    for sz in siz:
                        Size = Select(driver.find_element_by_id("icm-sizes-select"))
                        Size.select_by_index(++Sindex)
                        size.append(sz.text)
                        Scz = sz.text
                        csvData += [Cyr, Cmk, Cmd, Cbd,Csmd, Csz]

Body:
How to extract data from a dropdown menu using python beautifulsoup

The page does a callback to populate with years. Simply mimic that.

If you actually need to change years and select from dependent drop downs, which becomes a different question, you need browser automation e.g. selenium, or to manually perform this and inspect network tab to see if there is an xhr request you can mimic to submit your choices.

import requests

r = requests.get('https://www.iconfigurators.com/json2/?returnType=json&bypass=true&id=13898&callback=yearObj').json()
years = [item['year'] for item in r['years']]
print(years)


问:
Validator textarea does not work and always returns false
I am trying to use kendo UI validator over a textarea using validateinput but always returns false. This Dojo contains the script.

Thanks for your help.

https://dojo.telerik.com/ifIhEGIy

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Untitled</title>

  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.514/styles/kendo.common.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.514/styles/kendo.rtl.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.514/styles/kendo.default.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.514/styles/kendo.mobile.all.min.css">

<form id="hechoForm">

<textarea rows="10" cols="30" id="txtDescripcion" name="txtDescripcion"></textarea>

  <button onclick="validateFormHecho()">Click me</button>

</form>

```

答:
you use <textarea rows="10" cols="30" id="txtDescripcion" name="txtDescripcion"></textarea>.
But in your alert you are searching for an input elem. Textarea is not a classic HTML input, so you have to edit this part:

```<code>alert(validator.validateInput($("input[id=txtDescripcion]")));
</code>```

to

```<code>alert(validator.validateInput($("textarea[id=txtDescripcion]")));
</code>```

Or use $("#txtDescripcion") as the id selector

PS: you misspelled txtDescrip t ion ;)

Body:
you use <textarea rows="10" cols="30" id="txtDescripcion" name="txtDescripcion"></textarea>.
But in your alert you are searching for an input elem. Textarea is not a classic HTML input, so you have to edit this part:

alert(validator.validateInput($("input[id=txtDescripcion]")));

to

alert(validator.validateInput($("textarea[id=txtDescripcion]")));

Or use $("#txtDescripcion") as the id selector

PS: you misspelled txtDescrip t ion ;)


问:
How to align the flex items in three different ways?

So, I want to align items inside flex-box like in the above picture.

I have html as follows:

```<code><div class="flex-row">
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
</div>
</code>```

css as

```<code>   .flex-row {
      min-height: 400px;
      display: flex;
      align-items: flex-start;
   }

   .flex-item:nth-child(2) {
     align-items: center;
   }

   .flex-item:last-child {
      align-items: flex-end;
   }
</code>```

答:
NOTE!

to set height to column change the px here:flex: 0 1 50px; or remove it!

Using margin-right/left:auto as:

.flex-row {
  min-height: 400px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
}

.flex-item {
  flex: 0 1 50px;

}

.flex-item:nth-child(2) {
  margin-right: auto;
  margin-left: auto;
}
.flex-item:last-child {
  margin-left: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-row">
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
</div></code>```

2. using align-self

.flex-row {
  min-height: 400px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
}

.flex-item {
  flex: 0 1 50px;
  align-self: flex-start;
}

.flex-item:nth-child(2) {
  align-self: center;
}

.flex-item:last-child {
  align-self: flex-end;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-row">
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
</div></code>```

Body:
So, I want to align items inside flex-box like in the above picture.

I have html as follows:

css as

   .flex-row {
      min-height: 400px;
      display: flex;
      align-items: flex-start;
   }

   .flex-item:nth-child(2) {
     align-items: center;
   }

   .flex-item:last-child {
      align-items: flex-end;
   }

Body:
NOTE!

to set height to column change the px here:flex: 0 1 50px; or remove it!

Using margin-right/left:auto as:

.flex-row {
  min-height: 400px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
}

.flex-item {
  flex: 0 1 50px;

}

.flex-item:nth-child(2) {
  margin-right: auto;
  margin-left: auto;
}
.flex-item:last-child {
  margin-left: auto;
}

<div class="flex-row">
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
</div>

2. using align-self

.flex-row {
  min-height: 400px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
}

.flex-item {
  flex: 0 1 50px;
  align-self: flex-start;
}

.flex-item:nth-child(2) {
  align-self: center;
}

.flex-item:last-child {
  align-self: flex-end;
}

<div class="flex-row">
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
</div>


问:
3DES Key Size Matter in C#.Net

Below Code is Working Fine in c#.NET

```<code>byte[] key = Encoding.ASCII.GetByte("012345678901234567890123"); //24characters
byte[] plainText = Encoding.ASCII.GetBytes("lasaa");
TripleDES des = TripleDES.Create();
des.Key = key;
des.Mode = CipherMode.CBC;
ICryptoTransform ic = des.CreateEncryptor();
byte[] enc = ic.TransformFinalBlock(plainText, 0, plainText.Length);
MessageBox.Show(UTF8Encoding.UTF8.GetString(enc));
</code>```

My questions regarding above are...

How can I specify KeySize? if i use des.KeySize= 128 or 192 or 256 it gives

Specified key is not a valid size for this algorithm

If I change character length in key by adding more (ex:40 chars). It gives error

Specified key is not a valid size for this algorithm

I want to know why is this happen?

答: The key size for TripleDES is 168 bits. So you'll need 21 bytes. If you want to use a string for the key you really should hash it first. In which case you can use any length of characters (the more the better) and then trim the hashed output to your key size. E.g. if you use SHA-256 from which you'll get 32 bytes, use 21 of them.</p>

Title: 3DES Key Size Matter in C#.Net

Body:
Below Code is Working Fine in c#.NET

byte[] key = Encoding.ASCII.GetByte("012345678901234567890123"); //24characters
byte[] plainText = Encoding.ASCII.GetBytes("lasaa");
TripleDES des = TripleDES.Create();
des.Key = key;
des.Mode = CipherMode.CBC;
ICryptoTransform ic = des.CreateEncryptor();
byte[] enc = ic.TransformFinalBlock(plainText, 0, plainText.Length);
MessageBox.Show(UTF8Encoding.UTF8.GetString(enc));

My questions regarding above are...

How can I specify KeySize? if i use des.KeySize= 128 or 192 or 256 it gives

Specified key is not a valid size for this algorithm

If I change character length in key by adding more (ex:40 chars). It gives error

Specified key is not a valid size for this algorithm

I want to know why is this happen?