问:
How to update a table from a select query
i am creating a temp table using DB facade and then using select query i need to update some columns in temp table based on condition

```<code>DB::update('update table_temp_topcustomer
            set ordercount = aaa.ordercount
            from
            (select count(id) as ordercount,mobileno
             from order_hdrs
             group by mobileno
            ) as aaa
            where table_temp_topcustomer .mobileno = aaa.mobileno
          ');
</code>```

it gives this error

Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'from (select count(id) as ordercount,mobileno from order_hdrs group by mobileno ' at line 1 (SQL: update table_temp_topcustomer set ordercount = aaa.ordercount from (select count(id) as ordercount,mobileno from order_hdrs group by mobileno ) as aaa )

How can i achieve this?

答:
```<code>UPDATE table_temp_topcustomer JOIN
        ( SELECT order_hdrs count(*) as ordercount
              FROM order_hdrs
              GROUP BY mobileno
        ) AS aaa
           ON table_temp_topcustomer.mobileno = aaa.mobileno
        SET   table_temp_topcustomer.ordercount = aaa.ordercount
</code>```

Body:
i am creating a temp table using DB facade and then using select query i need to update some columns in temp table based on condition

DB::update('update table_temp_topcustomer
            set ordercount = aaa.ordercount
            from
            (select count(id) as ordercount,mobileno
             from order_hdrs
             group by mobileno
            ) as aaa
            where table_temp_topcustomer .mobileno = aaa.mobileno
          ');

it gives this error

Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'from (select count(id) as ordercount,mobileno from order_hdrs group by mobileno ' at line 1 (SQL: update table_temp_topcustomer set ordercount = aaa.ordercount from (select count(id) as ordercount,mobileno from order_hdrs group by mobileno ) as aaa )

How can i achieve this?


来源: stackexchange

问:
Event Bubbling from Parent to Child on Target Click
I'm trying to render a table in React and make rows clickable. Table rows may contain cells that have buttons or other clickable elements however and if a table cell contains a clickable element I don't want the row onClick function to be called when the cell element is clicked.

For some reason, the events are propagating in the reverse to what I would expect. From the parent (Row) to the child (Cell) so when I click a checkbox in a cell the order for onClick callbacks is Row -> Checkbox.

Because the more specific onClick handler is called after the row's onClick function I've been unable to cancel the event propagation as I initially intended to.

I've had a look into the docs from MDN & react on events but from what I can tell the event should order as follows Cell -> Row

I thought about using a ref to the row & comparing it to the target but would rather not have to store refs for each row visible...

The row code:

```<code><TableRow
    key={keyedItem.key}
    selected={this.isItemSelected(keyedItem.key)}
    hover={true}
    onClick={(event) => this.handleRowClicked(event, keyedItem)}
>
    {this.renderCheckBox(keyedItem.key)}
    {this.props.renderRowCells(keyedItem.item)}
</TableRow>
</code>```

The renderCheckbox(key) function from above

```<code>private renderCheckBox(key: string) {
        if (this.multiSelectionMode()) {
            return (
                <TableCell padding="checkbox">
                    <Checkbox
                        checked={this.isSelected(key)}
                        onChange={(event, checked: boolean) => { console.log(event.target); this.changeItemSelection(key, checked); }}
                   />
                </TableCell>
            );
        }
        return null;
    }
</code>```

Does anyone know what I might be doing wrong here? Or is this working as intended?

答:
One thing you can do to prevent this sort of event-bubbling is to define a switch-case. You can filter the target that is causing the event by its className then apply your logic for each case.

Here is a codesandbox for you to see it in action: https://codesandbox.io/s/sparkling-waterfall-u7b87

Parent

```<code>import React from "react";
import Child from "./Child";

class Parent extends React.Component {
  state = {
    cells: [
      { value: 1, selected: false },
      { value: 2, selected: false },
      { value: 3, selected: false }
    ]
  };
  handleClickEvents = event => {
    var target = event.target.className;
    switch (target) {
      case "parent":
        return console.log(target);
      case "child":
        return this.findCheckedInput(event);
      default:
        return;
    }
  };

  findCheckedInput = event => {
    const updatedCells = this.state.cells.map(cell => {
      if (cell.value == event.target.value) {
        return {
          ...cell,
          selected: !cell.selected
        };
      } else {
        return cell;
      }
    });

    this.setState(
      {
        cells: updatedCells
      },
      () => console.log(this.state)
    );
  };

  renderChildren = () => {
    const { cells } = this.state;
    return cells.map(item => {
      return (
        <Child
          key={item.value}
          handleClick={this.handleClickEvents}
          value={item.value}
          selected={item.selected}
        />
      );
    });
  };

  render() {
    return (
      <div
        className="parent"
        style={{ background: "green" }}
        onClick={this.handleClickEvents}
      >
        {this.renderChildren()}
      </div>
    );
  }
}

export default Parent;
</code>```

Child

```<code>import React from "react";

class Child extends React.Component {
  handleOnClick = () => {
    this.props.handleClick();
  };

  render() {
    return (
      <input
        className="child"
        onChange={this.handleOnClick}
        type="checkbox"
        checked={this.props.selected}
        value={this.props.value}
      />
    );
  }
}

export default Child;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to render a table in React and make rows clickable. Table rows may contain cells that have buttons or other clickable elements however and if a table cell contains a clickable element I don't want the row onClick function to be called when the cell element is clicked.

For some reason, the events are propagating in the reverse to what I would expect. From the parent (Row) to the child (Cell) so when I click a checkbox in a cell the order for onClick callbacks is Row -> Checkbox.

Because the more specific onClick handler is called after the row's onClick function I've been unable to cancel the event propagation as I initially intended to.

I've had a look into the docs from MDN & react on events but from what I can tell the event should order as follows Cell -> Row

I thought about using a ref to the row & comparing it to the target but would rather not have to store refs for each row visible...

The row code:

<TableRow
    key={keyedItem.key}
    selected={this.isItemSelected(keyedItem.key)}
    hover={true}
    onClick={(event) => this.handleRowClicked(event, keyedItem)}
>
    {this.renderCheckBox(keyedItem.key)}
    {this.props.renderRowCells(keyedItem.item)}
</TableRow>

The renderCheckbox(key) function from above

private renderCheckBox(key: string) {
        if (this.multiSelectionMode()) {
            return (
                <TableCell padding="checkbox">
                    <Checkbox
                        checked={this.isSelected(key)}
                        onChange={(event, checked: boolean) => { console.log(event.target); this.changeItemSelection(key, checked); }}
                   />
                </TableCell>
            );
        }
        return null;
    }

Does anyone know what I might be doing wrong here? Or is this working as intended?

Body:
One thing you can do to prevent this sort of event-bubbling is to define a switch-case. You can filter the target that is causing the event by its className then apply your logic for each case.

Here is a codesandbox for you to see it in action: https://codesandbox.io/s/sparkling-waterfall-u7b87

Parent

import React from "react";
import Child from "./Child";

class Parent extends React.Component {
  state = {
    cells: [
      { value: 1, selected: false },
      { value: 2, selected: false },
      { value: 3, selected: false }
    ]
  };
  handleClickEvents = event => {
    var target = event.target.className;
    switch (target) {
      case "parent":
        return console.log(target);
      case "child":
        return this.findCheckedInput(event);
      default:
        return;
    }
  };

  findCheckedInput = event => {
    const updatedCells = this.state.cells.map(cell => {
      if (cell.value == event.target.value) {
        return {
          ...cell,
          selected: !cell.selected
        };
      } else {
        return cell;
      }
    });

    this.setState(
      {
        cells: updatedCells
      },
      () => console.log(this.state)
    );
  };

  renderChildren = () => {
    const { cells } = this.state;
    return cells.map(item => {
      return (
        <Child
          key={item.value}
          handleClick={this.handleClickEvents}
          value={item.value}
          selected={item.selected}
        />
      );
    });
  };

  render() {
    return (
      <div
        className="parent"
        style={{ background: "green" }}
        onClick={this.handleClickEvents}
      >
        {this.renderChildren()}
      </div>
    );
  }
}

export default Parent;

Child

import React from "react";

class Child extends React.Component {
  handleOnClick = () => {
    this.props.handleClick();
  };

  render() {
    return (
      <input
        className="child"
        onChange={this.handleOnClick}
        type="checkbox"
        checked={this.props.selected}
        value={this.props.value}
      />
    );
  }
}

export default Child;


问:
Unable to get object data when used multiple-argument function
I am unable to get the data of an object

var a = {
  'ab':'cd',
  'ef':'gh',
  'ij':'kl'
}
function fun(...val){
  console.log(a.val[0])
}
fun('ab','ef')```

It should output 'cd' but it is giving out error in the console
any idea how do i fix this...

答:
Use bracket notation like so:

var a = {
  'ab':'cd',
  'ef':'gh',
  'ij':'kl'
}
function fun(...val){
  console.log(a[val[0]])
}
fun('ab','ef')```

Your code was trying to get the property named val in a (doesn't exist), then get the first character/item of that value (trying to do this to undefined causes the error).

Body:
I am unable to get the data of an object

var a = {
  'ab':'cd',
  'ef':'gh',
  'ij':'kl'
}
function fun(...val){
  console.log(a.val[0])
}
fun('ab','ef')

It should output 'cd' but it is giving out error in the console
any idea how do i fix this...

Body:
Use bracket notation like so:

var a = {
  'ab':'cd',
  'ef':'gh',
  'ij':'kl'
}
function fun(...val){
  console.log(a[val[0]])
}
fun('ab','ef')

Your code was trying to get the property named val in a (doesn't exist), then get the first character/item of that value (trying to do this to undefined causes the error).


问:
Django sending users to the wrong template location?
I'm working on Python Crash Course Chapter 19, where we are setting up a 'learning log' application. I'm stuck (on page 440) with a template reference error.

I have reworked this section of the book, in addition to taking all of the updates listed here: https://ehmatthes.github.io/pcc/chapter_19/README.html

but seem to keep getting what looks to be a template reference error. I noticed the template is referencing the 'learning_logs' directory when looking for the login.html, which is incorrect -- it should be looking in the 'learning_log' directory.

learning_log\users\urls.py

from django.contrib.auth import views as auth_views

from . import views

app_name = 'users'
urlpatterns = [
    # Login page.
    path('login/',
        auth_views.LoginView.as_view(template_name='users/login.html'),
        name='login'),
]
```

<p>learning_logs\urls.py</p>

<pre class="lang-py prettyprint-override"><code>"""learning_logs URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

"""Defines URL patterns for learning_logs."""

from django.urls import path

from . import views

app_name = 'learning_logs'
urlpatterns = [
    # Home page.
    path('', views.index, name='index'),

    #Show all topics.
    path('topics/', views.topics, name='topics'),

    #Detail page for a single topic.
    path('topics/<int:topic_id>/', views.topic, name='topic'),

    #Page for adding a new topic.
    path('new_topic/', views.new_topic, name='new_topic'),

    #Page for adding a new entry.
    path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),

    #Page for editing an entry.
    path('edit_entry/<int:entry_id>/', views.edit_entry, name='edit_entry'),
]
</code>```

learning_log\urls.py

"""learning_log URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('users.urls')),
    path('', include('learning_logs.urls')),
]
```

<p>Here is the browser error:</p>

<pre class="lang-py prettyprint-override"><code>TemplateDoesNotExist at /users/login/
users/login.html
Request Method:
GET
Request URL:
http://localhost:8000/users/login/
Django Version:
2.2.1
Exception Type:
TemplateDoesNotExist
Exception Value:
users/login.html
Exception Location:
C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py in select_template, line 47
Python Executable:
C:\Users\kevin\Documents\webapps\11_env\Scripts\python.exe
Python Version:
3.7.3
Python Path:
['C:\\Users\\kevin\\Documents\\webapps',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env\\lib\\site-packages']
Server time:
Sun, 26 May 2019 22:14:26 +0000
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\admin\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\auth\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\learning_logs\templates\users\login.html (Source does not exist)
</code>```

Here is the server error:

    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:27] "GET /users/login/ HTTP/1.1" 500 79384
    Not Found: /users/
    [26/May/2019 15:12:39] "GET /users/ HTTP/1.1" 404 3224
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:43] "GET /users/login/ HTTP/1.1" 500 79384
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html

```

答: Are you sure you haven't mistyped anything? I do that heaps and it always messes up my programs. Try checking where you've typed learning_logs or learning_log and see if you need to add or remove an s.</p>

Body:
I'm working on Python Crash Course Chapter 19, where we are setting up a 'learning log' application. I'm stuck (on page 440) with a template reference error.

I have reworked this section of the book, in addition to taking all of the updates listed here: https://ehmatthes.github.io/pcc/chapter_19/README.html

but seem to keep getting what looks to be a template reference error. I noticed the template is referencing the 'learning_logs' directory when looking for the login.html, which is incorrect -- it should be looking in the 'learning_log' directory.

learning_log\users\urls.py

from django.contrib.auth import views as auth_views

from . import views

app_name = 'users'
urlpatterns = [
    # Login page.
    path('login/',
        auth_views.LoginView.as_view(template_name='users/login.html'),
        name='login'),
]

learning_logs\urls.py

"""learning_logs URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

"""Defines URL patterns for learning_logs."""

from django.urls import path

from . import views

app_name = 'learning_logs'
urlpatterns = [
    # Home page.
    path('', views.index, name='index'),

    #Show all topics.
    path('topics/', views.topics, name='topics'),

    #Detail page for a single topic.
    path('topics/<int:topic_id>/', views.topic, name='topic'),

    #Page for adding a new topic.
    path('new_topic/', views.new_topic, name='new_topic'),

    #Page for adding a new entry.
    path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),

    #Page for editing an entry.
    path('edit_entry/<int:entry_id>/', views.edit_entry, name='edit_entry'),
]

learning_log\urls.py

"""learning_log URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('users.urls')),
    path('', include('learning_logs.urls')),
]

Here is the browser error:

TemplateDoesNotExist at /users/login/
users/login.html
Request Method:
GET
Request URL:
http://localhost:8000/users/login/
Django Version:
2.2.1
Exception Type:
TemplateDoesNotExist
Exception Value:
users/login.html
Exception Location:
C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py in select_template, line 47
Python Executable:
C:\Users\kevin\Documents\webapps\11_env\Scripts\python.exe
Python Version:
3.7.3
Python Path:
['C:\\Users\\kevin\\Documents\\webapps',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env\\lib\\site-packages']
Server time:
Sun, 26 May 2019 22:14:26 +0000
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\admin\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\auth\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\learning_logs\templates\users\login.html (Source does not exist)

Here is the server error:

    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:27] "GET /users/login/ HTTP/1.1" 500 79384
    Not Found: /users/
    [26/May/2019 15:12:39] "GET /users/ HTTP/1.1" 404 3224
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:43] "GET /users/login/ HTTP/1.1" 500 79384
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html


Title: Is there a work around for business days with multiple lines (molten data) in ggplot?

Body:
I am trying to plot multiple lines with molten data and I am using the library(bdscale) to correct the x scale for business days, however the x scales are not being placed correctly. I wonder if anyone out there have already faced the same issue and could help me out. Thanks!

I have already checked these two previous answers the question was with faceting and transform the date into factors, however unfortunately neither of them seem to be the solution I would like.

I have included a sample of my data.

dput(pred_final_price_melt)
structure(list(date_hist = structure(c(18017, 18018, 18019, 18022,
18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
18036, 18037, 18038, 18039, 18040, 18017, 18018, 18019, 18022,
18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
18036, 18037, 18038, 18039, 18040, 18017, 18018, 18019, 18022,
18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
18036, 18037, 18038, 18039, 18040, 18017, 18018, 18019, 18022,
18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
18036, 18037, 18038, 18039, 18040, 18017, 18018, 18019, 18022,
18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
18036, 18037, 18038, 18039, 18040, 18017, 18018, 18019, 18022,
18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
18036, 18037, 18038, 18039, 18040), class = "Date"), variable = c("Model_1",
"Model_1", "Model_1", "Model_1", "Model_1", "Model_1", "Model_1",
"Model_1", "Model_1", "Model_1", "Model_1", "Model_1", "Model_1",
"Model_1", "Model_1", "Model_1", "Model_1", "Model_1", "Model_2",
"Model_2", "Model_2", "Model_2", "Model_2", "Model_2", "Model_2",
"Model_2", "Model_2", "Model_2", "Model_2", "Model_2", "Model_2",
"Model_2", "Model_2", "Model_2", "Model_2", "Model_2", "Model_3",
"Model_3", "Model_3", "Model_3", "Model_3", "Model_3", "Model_3",
"Model_3", "Model_3", "Model_3", "Model_3", "Model_3", "Model_3",
"Model_3", "Model_3", "Model_3", "Model_3", "Model_3", "Model_4",
"Model_4", "Model_4", "Model_4", "Model_4", "Model_4", "Model_4",
"Model_4", "Model_4", "Model_4", "Model_4", "Model_4", "Model_4",
"Model_4", "Model_4", "Model_4", "Model_4", "Model_4", "BH",
"BH", "BH", "BH", "BH", "BH", "BH", "BH", "BH", "BH", "BH", "BH",
"BH", "BH", "BH", "BH", "BH", "BH", "BH_Intra", "BH_Intra", "BH_Intra",
"BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra",
"BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra",
"BH_Intra", "BH_Intra", "BH_Intra"), value = c(0.000884284992420437,
-0.00353937555302741, -0.000760649087221177, 0.000505816894284195,
0.00063035804336864, 0.0013869625520111, -0.00202045712842525,
-0.000629722921914322, 0.00264417023419794, -0.000627982918864567,
0.00226102248461246, 0.00213032581453632, 0.000250972518509252,
-0.00175702811244982, -0.00113150616042246, 0.00239144115796108,
0.00564759036144569, -0.000375187593796844, -0.000884284992420437,
-0.00353937555302741, 0.000760649087221177, 0.000505816894284195,
-0.00063035804336864, 0.0013869625520111, -0.00202045712842525,
0.000629722921914322, -0.00264417023419794, 0.000627982918864567,
-0.00226102248461246, -0.00213032581453632, 0.000250972518509252,
0.00175702811244982, 0.00113150616042246, 0.00239144115796108,
0.00564759036144569, -0.000375187593796844, -0.000884284992420437,
-0.00353937555302741, 0.000760649087221177, 0.000505816894284195,
-0.00063035804336864, 0.0013869625520111, -0.00202045712842525,
-0.000629722921914322, -0.00264417023419794, -0.000627982918864567,
0.00226102248461246, -0.00213032581453632, 0.000250972518509252,
0.00175702811244982, -0.00113150616042246, -0.00239144115796108,
-0.00564759036144569, 0.000375187593796844, 0.000884284992420437,
-0.00353937555302741, 0.000760649087221177, 0.000505816894284195,
0.00063035804336864, -0.0013869625520111, 0.00202045712842525,
0.000629722921914322, -0.00264417023419794, 0.000627982918864567,
-0.00226102248461246, 0.00213032581453632, 0.000250972518509252,
0.00175702811244982, 0.00113150616042246, 0.00239144115796108,
-0.00564759036144569, 0.000375187593796844, -0.000758054327226754,
-0.00328739410797829, 0.00139540783965497, 0.00228021281986313,
0.003159757330637, -0.00214186720423337, 0.00189393939393945,
0, 0.00352867044738492, -0.000753484867512255, 0.002764861128566,
-0.00200526381752097, 0.000502323245008096, -0.00163173088992097,
-0.00113150616042246, 0.00239144115796108, 0.00615268709191352,
-0.00249594409085241, -0.000884284992420437, -0.00353937555302741,
0.000760649087221177, 0.000505816894284195, 0.00063035804336864,
-0.0013869625520111, 0.00202045712842525, -0.000629722921914322,
0.00264417023419794, -0.000627982918864567, 0.00226102248461246,
-0.00213032581453632, -0.000250972518509252, -0.00175702811244982,
-0.00113150616042246, 0.00239144115796108, 0.00564759036144569,
-0.000375187593796844), ret_accum = c(0.993020566092887, 0.989505893377605,
0.988753226623007, 0.989253354709311, 0.989876938518382, 0.991249860763206,
0.989247082915976, 0.988624131352427, 0.991238221853359, 0.99061574118151,
0.992855545645932, 0.994970651444927, 0.995220361735163, 0.993471731581512,
0.992347612197022, 0.994720753119834, 1.00033852845748, 0.999963213852009,
0.993817657624321, 0.990300163702759, 0.991053434618354, 0.991554726188723,
0.990929691691629, 0.992304074065681, 0.99029916622567, 0.990922780310195,
0.98830261179011, 0.988923248948984, 0.986687271247554, 0.984585305882741,
0.984832409736645, 0.986562787966604, 0.987679089838832, 0.99004106626513,
0.995632412648405, 0.995258863719197, 1.00633565703449, 1.00277385721184,
1.00353661623102, 1.00404422200554, 1.0034113146543, 1.00480300857199,
1.00277284717066, 1.00214137812332, 0.999491545720829, 0.998863882102567,
1.00112233579907, 0.998989619043607, 0.999240337984263, 1.00099603134919,
0.999863398173165, 0.997472283690435, 0.991838968835255, 0.992211094511407,
1.02637315186551, 1.02274043182351, 1.02351837839944, 1.02403609128685,
1.02468160067369, 1.02326040566582, 1.02532785944668, 1.02597353190225,
1.02326068322812, 1.02390327345873, 1.02158820513538, 1.0237645208606,
1.02402145762076, 1.02582069210955, 1.02698141454216, 1.02943738016536,
1.02362353953943, 1.02400759039218, 1.04741093894848, 1.04396768639915,
1.0454244470931, 1.04780823731956, 1.05111905707853, 1.04886769964243,
1.05085419149781, 1.05085419149781, 1.05456230962786, 1.05376771288571,
1.05668123427361, 1.05456230962786, 1.0550920407893, 1.05337041451463,
1.0521785194014, 1.05469474241822, 1.06118394914581, 1.05853529333863,
1.0447374250804, 1.04103970697874, 1.04183157288161, 1.04235854889217,
1.04301560798754, 1.0415689843981, 1.04367342987737, 1.04301620479559,
1.04577411719809, 1.0451173889155, 1.0474804228309, 1.04524894824592,
1.04498661948491, 1.04315054861734, 1.04197021734533, 1.04446202780846,
1.05036072148961, 1.0499666391779), Month = c(5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5)), class = c("data.table",
"data.frame"), row.names = c(NA, -108L), .internal.selfref = <pointer: 0x0000000007a41ef0>)

My code:

library(ggplot2)
library(bdscale)

ggplot(pred_final_price_melt,aes(date_hist,ret_accum,colour=variable,shape=variable))+
  geom_line()+
  geom_point() +
  xlab("Date") +
  ylab("Accumulated return") +
  scale_x_bd(business.dates = pred_final_price_melt$date_hist,
             max.major.breaks = 10,
             labels = date_format("%y-%m-%d"))

Body:
I provide a response with the suggestion to use the ggplot2 and scales package.

library(ggplot2)
library(scales)

datas <- unique(pred_final_price_melt$date_hist)

ggplot(pred_final_price_melt,aes(date_hist,ret_accum,colour=variable))+
  geom_line()+
  geom_point(aes(shape = variable)) +
  xlab("Date") +
  ylab("Accumulated return") +
  scale_x_date(breaks = datas,
               labels = scales::date_format("%Y-%m-%d"),
               limits = range(datas)) +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 90))

df <- pred_final_price_melt %>%
  dplyr::mutate(date_hist = as.factor(date_hist))

library(lemon)

ggplot(df,
       aes(date_hist, ret_accum,
           shape = variable, col = variable, group = variable)) +
  lemon::geom_pointline() +
  xlab("Date") +
  ylab("Accumulated return") +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 90))

Dataset

pred_final_price_melt <- structure(list(date_hist = structure(c(18017, 18018, 18019, 18022,
                                       18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
                                       18036, 18037, 18038, 18039, 18040, 18017, 18018, 18019, 18022,
                                       18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
                                       18036, 18037, 18038, 18039, 18040, 18017, 18018, 18019, 18022,
                                       18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
                                       18036, 18037, 18038, 18039, 18040, 18017, 18018, 18019, 18022,
                                       18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
                                       18036, 18037, 18038, 18039, 18040, 18017, 18018, 18019, 18022,
                                       18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
                                       18036, 18037, 18038, 18039, 18040, 18017, 18018, 18019, 18022,
                                       18023, 18024, 18025, 18026, 18029, 18030, 18031, 18032, 18033,
                                       18036, 18037, 18038, 18039, 18040), class = "Date"), variable = c("Model_1",
                                                                                "Model_1", "Model_1", "Model_1", "Model_1", "Model_1", "Model_1",
                                                                                "Model_1", "Model_1", "Model_1", "Model_1", "Model_1", "Model_1",
                                                                                "Model_1", "Model_1", "Model_1", "Model_1", "Model_1", "Model_2",
                                                                                "Model_2", "Model_2", "Model_2", "Model_2", "Model_2", "Model_2",
                                                                                "Model_2", "Model_2", "Model_2", "Model_2", "Model_2", "Model_2",
                                                                                "Model_2", "Model_2", "Model_2", "Model_2", "Model_2", "Model_3",
                                                                                "Model_3", "Model_3", "Model_3", "Model_3", "Model_3", "Model_3",
                                                                                "Model_3", "Model_3", "Model_3", "Model_3", "Model_3", "Model_3",
                                                                                "Model_3", "Model_3", "Model_3", "Model_3", "Model_3", "Model_4",
                                                                                "Model_4", "Model_4", "Model_4", "Model_4", "Model_4", "Model_4",
                                                                                "Model_4", "Model_4", "Model_4", "Model_4", "Model_4", "Model_4",
                                                                                "Model_4", "Model_4", "Model_4", "Model_4", "Model_4", "BH",
                                                                                "BH", "BH", "BH", "BH", "BH", "BH", "BH", "BH", "BH", "BH", "BH",
                                                                                "BH", "BH", "BH", "BH", "BH", "BH", "BH_Intra", "BH_Intra", "BH_Intra",
                                                                                "BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra",
                                                                                "BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra", "BH_Intra",
                                                                                "BH_Intra", "BH_Intra", "BH_Intra"), value = c(0.000884284992420437,
                                                                                -0.00353937555302741, -0.000760649087221177, 0.000505816894284195,
                                                                                0.00063035804336864, 0.0013869625520111, -0.00202045712842525,
                                                                                -0.000629722921914322, 0.00264417023419794, -0.000627982918864567,
                                                                                0.00226102248461246, 0.00213032581453632, 0.000250972518509252,
                                                                                -0.00175702811244982, -0.00113150616042246, 0.00239144115796108,
                                                                                0.00564759036144569, -0.000375187593796844, -0.000884284992420437,
                                                                                -0.00353937555302741, 0.000760649087221177, 0.000505816894284195,
                                                                                -0.00063035804336864, 0.0013869625520111, -0.00202045712842525,
                                                                                0.000629722921914322, -0.00264417023419794, 0.000627982918864567,
                                                                                -0.00226102248461246, -0.00213032581453632, 0.000250972518509252,
                                                                                0.00175702811244982, 0.00113150616042246, 0.00239144115796108,
                                                                                0.00564759036144569, -0.000375187593796844, -0.000884284992420437,
                                                                                -0.00353937555302741, 0.000760649087221177, 0.000505816894284195,
                                                                                -0.00063035804336864, 0.0013869625520111, -0.00202045712842525,
                                                                                -0.000629722921914322, -0.00264417023419794, -0.000627982918864567,
                                                                                0.00226102248461246, -0.00213032581453632, 0.000250972518509252,
                                                                                0.00175702811244982, -0.00113150616042246, -0.00239144115796108,
                                                                                -0.00564759036144569, 0.000375187593796844, 0.000884284992420437,
                                                                                -0.00353937555302741, 0.000760649087221177, 0.000505816894284195,
                                                                                0.00063035804336864, -0.0013869625520111, 0.00202045712842525,
                                                                                0.000629722921914322, -0.00264417023419794, 0.000627982918864567,
                                                                                -0.00226102248461246, 0.00213032581453632, 0.000250972518509252,
                                                                                0.00175702811244982, 0.00113150616042246, 0.00239144115796108,
                                                                                -0.00564759036144569, 0.000375187593796844, -0.000758054327226754,
                                                                                -0.00328739410797829, 0.00139540783965497, 0.00228021281986313,
                                                                                0.003159757330637, -0.00214186720423337, 0.00189393939393945,
                                                                                0, 0.00352867044738492, -0.000753484867512255, 0.002764861128566,
                                                                                -0.00200526381752097, 0.000502323245008096, -0.00163173088992097,
                                                                                -0.00113150616042246, 0.00239144115796108, 0.00615268709191352,
                                                                                -0.00249594409085241, -0.000884284992420437, -0.00353937555302741,
                                                                                0.000760649087221177, 0.000505816894284195, 0.00063035804336864,
                                                                                -0.0013869625520111, 0.00202045712842525, -0.000629722921914322,
                                                                                0.00264417023419794, -0.000627982918864567, 0.00226102248461246,
                                                                                -0.00213032581453632, -0.000250972518509252, -0.00175702811244982,
                                                                                -0.00113150616042246, 0.00239144115796108, 0.00564759036144569,
                                                                                -0.000375187593796844), ret_accum = c(0.993020566092887, 0.989505893377605,
                                                                                0.988753226623007, 0.989253354709311, 0.989876938518382, 0.991249860763206,
                                                                                0.989247082915976, 0.988624131352427, 0.991238221853359, 0.99061574118151,
                                                                                0.992855545645932, 0.994970651444927, 0.995220361735163, 0.993471731581512,
                                                                                0.992347612197022, 0.994720753119834, 1.00033852845748, 0.999963213852009,
                                                                                0.993817657624321, 0.990300163702759, 0.991053434618354, 0.991554726188723,
                                                                                0.990929691691629, 0.992304074065681, 0.99029916622567, 0.990922780310195,
                                                                                0.98830261179011, 0.988923248948984, 0.986687271247554, 0.984585305882741,
                                                                                0.984832409736645, 0.986562787966604, 0.987679089838832, 0.99004106626513,
                                                                                0.995632412648405, 0.995258863719197, 1.00633565703449, 1.00277385721184,
                                                                                1.00353661623102, 1.00404422200554, 1.0034113146543, 1.00480300857199,
                                                                                1.00277284717066, 1.00214137812332, 0.999491545720829, 0.998863882102567,
                                                                                1.00112233579907, 0.998989619043607, 0.999240337984263, 1.00099603134919,
                                                                                0.999863398173165, 0.997472283690435, 0.991838968835255, 0.992211094511407,
                                                                                1.02637315186551, 1.02274043182351, 1.02351837839944, 1.02403609128685,
                                                                                1.02468160067369, 1.02326040566582, 1.02532785944668, 1.02597353190225,
                                                                                1.02326068322812, 1.02390327345873, 1.02158820513538, 1.0237645208606,
                                                                                1.02402145762076, 1.02582069210955, 1.02698141454216, 1.02943738016536,
                                                                                1.02362353953943, 1.02400759039218, 1.04741093894848, 1.04396768639915,
                                                                                1.0454244470931, 1.04780823731956, 1.05111905707853, 1.04886769964243,
                                                                                1.05085419149781, 1.05085419149781, 1.05456230962786, 1.05376771288571,
                                                                                1.05668123427361, 1.05456230962786, 1.0550920407893, 1.05337041451463,
                                                                                1.0521785194014, 1.05469474241822, 1.06118394914581, 1.05853529333863,
                                                                                1.0447374250804, 1.04103970697874, 1.04183157288161, 1.04235854889217,
                                                                                1.04301560798754, 1.0415689843981, 1.04367342987737, 1.04301620479559,
                                                                                1.04577411719809, 1.0451173889155, 1.0474804228309, 1.04524894824592,
                                                                                1.04498661948491, 1.04315054861734, 1.04197021734533, 1.04446202780846,
                                                                                1.05036072148961, 1.0499666391779), Month = c(5, 5, 5, 5, 5,
                                                                                5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
                                                                                5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
                                                                                5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
                                                                                5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
                                                                                5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5)), class = c("data.table",
                                                                                "data.frame"), row.names = c(NA, -108L))


问:
How to get exit code when using Python subprocess communicate method?
How do I retrieve the exit code when using Python's subprocess module and the communicate() method?

Relevant code:

```<code>import subprocess as sp
data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]
</code>```

Should I be doing this another way?

答:
Popen.communicate will set the returncode attribute when it's done(*). Here's the relevant documentation section:

```<code>Popen.returncode
  The child return code, set by poll() and wait() (and indirectly by communicate()).
  A None value indicates that the process hasn’t terminated yet.

  A negative value -N indicates that the child was terminated by signal N (Unix only).
</code>```

So you can just do (I didn't test it but it should work):

```<code>import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode
</code>```

(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls wait.

ContentLicense: CC BY-SA 3.0

Body:
How do I retrieve the exit code when using Python's subprocess module and the communicate() method?

Relevant code:

import subprocess as sp
data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]

Should I be doing this another way?

Body:
Popen.communicate will set the returncode attribute when it's done(*). Here's the relevant documentation section:

Popen.returncode
  The child return code, set by poll() and wait() (and indirectly by communicate()).
  A None value indicates that the process hasn’t terminated yet.

  A negative value -N indicates that the child was terminated by signal N (Unix only).

So you can just do (I didn't test it but it should work):

import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode

(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls wait.


问:
WPF Databinding vs Programmatically generating controls
My underlying data structure consists of a hierarchy of objects that are built upon a common abstract class:

```<code>public abstract class model {
   public string name {get;};
   public string type {get;};
}

public class A:model {
   public int val1 {get; set;};
}

public class B:model {
   public int val2 {get; set;};
}

public class C:B {
   public Dictionary<string, int> extra_props;
}
</code>```

My goal is to create a UI that upon object selection, is able to dynamically preview but also be able to modify the object's underlying properties.

I'm an absolute noob regarding WPF, so I have no idea what its full capabilities are. For now regarding the single value properties, I have found my way to use Databinding to bind the properties to the UI elements. It works like a charm for showing and also modifying the values.

```<code><GroupBox x:Name="InfoBox" Header="Object Information">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="41*"/>
            <ColumnDefinition Width="200*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="50*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <DockPanel Grid.Row="0" Grid.ColumnSpan="2" >
            <TextBlock>Name:</TextBlock>
            <TextBlock Text="{Binding name}" HorizontalAlignment="Right"></TextBlock>
        </DockPanel>
        <DockPanel Grid.Row="1" Grid.ColumnSpan="2" >
            <TextBlock>Type:</TextBlock>
            <TextBlock Text="{Binding type}" HorizontalAlignment="Right"></TextBlock>
        </DockPanel>
        <DockPanel Grid.Row="2" Grid.ColumnSpan="2" >
            <TextBlock>Material Name:</TextBlock>
            <TextBlock Text="{Binding val1}" HorizontalAlignment="Right"></TextBlock>
        </DockPanel>
    </Grid>
</GroupBox>
</code>```

Problem 1:
When an object of type B is bound, property val1 doesn't exist and I'm getting some BindingErrors in the debug output. These cause no problem during execution at all, but I have found no way of catching them and returning a default value or something.

The only way that I have thought of for solving this issue is to add all the desired properties in the abstract class so that they all exist on all derived classes with some null values or something, but this doesn't feel right at all.

Problem 2:
For more complex classes like C, I want to dynamically generate the UI based on a set/list of properties of the class. For now I have absolutely no idea how to do it with databinding, except for adding them all one by one in the XML and working around the issues of problem 1.

The most viable solution that I thought of is to programmatically generate a Control and add it to the main window with textboxes and inputs for the class properties that I need, and again programmatically hopefully be able to bind the object to the control so that the values are read/set appropriately. Obviously this method would resolve problem 1 as well.

I'm not even sure if this solution is possible or not, but in any case I need recommendations and advice on mainly if there is a way to resolve my issues with data-binding or if I should go with with programmatically updating the UI (if possible).

答:
Well for a noob you're doing well so far :) There's actually a very simple solution to both of these problems: DataTemplates. You can read all about them on the microsoft site.

In your case you want to declare a separate template for each type you're trying to display:

```<code> <DataTemplate DataType="{x:Type local:A}">
     <TextBlock Text="This object is type A">
 </DataTemplate>

 <DataTemplate DataType="{x:Type local:B}">
     <TextBlock Text="This object is type B">
 </DataTemplate>
</code>```

...and so on. This is typically done in the Resources block of whatever window/user control that this code appears on, although it can also be declared in the App.xaml resources block etc.

DataTemplates are used by any WPF control that is able to bind to data in some way. Take Button, for example....the overall look of the button including the border and how it behaves to mouse-over etc is dictated by its ControlTemplate (which you can also override yourself of course). But at some point in the XAML it has to render the actual data that you've assigned to its "Content" property, and if you were to look at the ControlTemplate for Button you'd find something like this buried inside it:

```<code><ContentPresenter />
</code>```

This effectively says "ok, this is where my actual data should be rendered, but instead of declaring it specifically here I want you to refer to the object's corresponding DataTemplate instead". In this way you can create a top-level button style using a single ControlTemplate, but you can then specify multiple DataTemplates for each of the types of things that you'll render inside it.

Lots of controls use DataTemplate, including things like ListBox etc where each element in the list can be given a different graphical representation based on its type. Going back to your own specific problem, if you just want to render the data itself without any bells and whistles etc around it then just use a ContentControl:

```<code> <ContentControl Content="{Binding MyModel}" />
</code>```

So MyModel should be a property of type model that's in your view model layer (or whatever else you've set the DataContext to). Assigning that property to be an instance of type A, B or C will cause the ContentControl to be populated with an instance of whatever you've declared in its DataTemplate.

Body:
My underlying data structure consists of a hierarchy of objects that are built upon a common abstract class:

public abstract class model {
   public string name {get;};
   public string type {get;};
}

public class A:model {
   public int val1 {get; set;};
}

public class B:model {
   public int val2 {get; set;};
}

public class C:B {
   public Dictionary<string, int> extra_props;
}

My goal is to create a UI that upon object selection, is able to dynamically preview but also be able to modify the object's underlying properties.

I'm an absolute noob regarding WPF, so I have no idea what its full capabilities are. For now regarding the single value properties, I have found my way to use Databinding to bind the properties to the UI elements. It works like a charm for showing and also modifying the values.

<GroupBox x:Name="InfoBox" Header="Object Information">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="41*"/>
            <ColumnDefinition Width="200*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="50*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <DockPanel Grid.Row="0" Grid.ColumnSpan="2" >
            <TextBlock>Name:</TextBlock>
            <TextBlock Text="{Binding name}" HorizontalAlignment="Right"></TextBlock>
        </DockPanel>
        <DockPanel Grid.Row="1" Grid.ColumnSpan="2" >
            <TextBlock>Type:</TextBlock>
            <TextBlock Text="{Binding type}" HorizontalAlignment="Right"></TextBlock>
        </DockPanel>
        <DockPanel Grid.Row="2" Grid.ColumnSpan="2" >
            <TextBlock>Material Name:</TextBlock>
            <TextBlock Text="{Binding val1}" HorizontalAlignment="Right"></TextBlock>
        </DockPanel>
    </Grid>
</GroupBox>

Problem 1:
When an object of type B is bound, property val1 doesn't exist and I'm getting some BindingErrors in the debug output. These cause no problem during execution at all, but I have found no way of catching them and returning a default value or something.

The only way that I have thought of for solving this issue is to add all the desired properties in the abstract class so that they all exist on all derived classes with some null values or something, but this doesn't feel right at all.

Problem 2:
For more complex classes like C, I want to dynamically generate the UI based on a set/list of properties of the class. For now I have absolutely no idea how to do it with databinding, except for adding them all one by one in the XML and working around the issues of problem 1.

The most viable solution that I thought of is to programmatically generate a Control and add it to the main window with textboxes and inputs for the class properties that I need, and again programmatically hopefully be able to bind the object to the control so that the values are read/set appropriately. Obviously this method would resolve problem 1 as well.

I'm not even sure if this solution is possible or not, but in any case I need recommendations and advice on mainly if there is a way to resolve my issues with data-binding or if I should go with with programmatically updating the UI (if possible).

Body:
Well for a noob you're doing well so far :) There's actually a very simple solution to both of these problems: DataTemplates. You can read all about them on the microsoft site.

In your case you want to declare a separate template for each type you're trying to display:

 <DataTemplate DataType="{x:Type local:A}">
     <TextBlock Text="This object is type A">
 </DataTemplate>

 <DataTemplate DataType="{x:Type local:B}">
     <TextBlock Text="This object is type B">
 </DataTemplate>

...and so on. This is typically done in the Resources block of whatever window/user control that this code appears on, although it can also be declared in the App.xaml resources block etc.

DataTemplates are used by any WPF control that is able to bind to data in some way. Take Button, for example....the overall look of the button including the border and how it behaves to mouse-over etc is dictated by its ControlTemplate (which you can also override yourself of course). But at some point in the XAML it has to render the actual data that you've assigned to its "Content" property, and if you were to look at the ControlTemplate for Button you'd find something like this buried inside it:

<ContentPresenter />

This effectively says "ok, this is where my actual data should be rendered, but instead of declaring it specifically here I want you to refer to the object's corresponding DataTemplate instead". In this way you can create a top-level button style using a single ControlTemplate, but you can then specify multiple DataTemplates for each of the types of things that you'll render inside it.

Lots of controls use DataTemplate, including things like ListBox etc where each element in the list can be given a different graphical representation based on its type. Going back to your own specific problem, if you just want to render the data itself without any bells and whistles etc around it then just use a ContentControl:

 <ContentControl Content="{Binding MyModel}" />

So MyModel should be a property of type model that's in your view model layer (or whatever else you've set the DataContext to). Assigning that property to be an instance of type A, B or C will cause the ContentControl to be populated with an instance of whatever you've declared in its DataTemplate.


问:
How to evaluate a symbolic expression in different ways?
I have a list of symbolic expressions, like below:

```<code>import numpy as np
import sympy
s = sympy.Symbol('s')
x = [ s, s+1, 10*s**2, 5]
</code>```

After adding the elements by using "sum":

```<code>y = sum (x)
</code>```

I will get: 10*s**2 + 2*s + 6
I want to evaluate this expression for each of the elements of the list below:

```<code>s = [1, 2 , 3 , 4 , 5]
</code>```

I know that I can define a function like below:

```<code>def F (s):

    F = 10*s**2 + 2*s + 6
    return F
f_dis = [F(value )for value in s]
</code>```

and it will give the result I'm looking for: [18, 50, 102, 174, 266]
However, my problem is that I have to define the F and write the expression in my code. Is there any other way that I can evaluate the sum (x) without writing the F = 10*s**2 + 2*s + 6 inside my code?
I can not copy and paste the result of sum (x) inside my code.

答:
You could try this

import numpy as np
import sympy
s = sympy.Symbol('s')
x = [ s, s+1, 10*s**2, 5]

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

evals = [sum(x).subs(s, el) for el in a]
```

<p>Output</p>

```[18, 50, 102, 174, 266]
```

<p>Complex number</p>

<pre class="lang-py prettyprint-override"><code>a = [1, 2 , 3 , 4 , 5, 1+1j]

evals = [sum(x).subs(s, el).as_real_imag() for el in a]
</code>```

You can easily parse the tuples to get the first element.

def re_(tpl: tuple) -> float:
    return tpl[0]

def img_(tpl: tuple) -> float:
    return tpl[-1]

```

<p>Or</p>

<pre class="lang-py prettyprint-override"><code>a = [1, 2 , 3 , 4 , 5, 1+1j]

evals = [sum(x).subs(s, el).evalf() for el in a]
</code>```

Output

[18.0000000000000, 50.0000000000000,
102.000000000000, 174.000000000000,
266.000000000000, 8.0 + 22.0*I]
```

But the last one will have to be converted to complex.

Body:
I have a list of symbolic expressions, like below:

import numpy as np
import sympy
s = sympy.Symbol('s')
x = [ s, s+1, 10*s**2, 5]

After adding the elements by using "sum":

y = sum (x)

I will get: 10*s**2 + 2*s + 6
I want to evaluate this expression for each of the elements of the list below:

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

I know that I can define a function like below:

def F (s):

    F = 10*s**2 + 2*s + 6
    return F
f_dis = [F(value )for value in s]

and it will give the result I'm looking for: [18, 50, 102, 174, 266]
However, my problem is that I have to define the F and write the expression in my code. Is there any other way that I can evaluate the sum (x) without writing the F = 10*s**2 + 2*s + 6 inside my code?
I can not copy and paste the result of sum (x) inside my code.

Body:
You could try this

import numpy as np
import sympy
s = sympy.Symbol('s')
x = [ s, s+1, 10*s**2, 5]

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

evals = [sum(x).subs(s, el) for el in a]

Output

[18, 50, 102, 174, 266]

Complex number

a = [1, 2 , 3 , 4 , 5, 1+1j]

evals = [sum(x).subs(s, el).as_real_imag() for el in a]

You can easily parse the tuples to get the first element.

def re_(tpl: tuple) -> float:
    return tpl[0]

def img_(tpl: tuple) -> float:
    return tpl[-1]

Or

a = [1, 2 , 3 , 4 , 5, 1+1j]

evals = [sum(x).subs(s, el).evalf() for el in a]

Output

[18.0000000000000, 50.0000000000000,
102.000000000000, 174.000000000000,
266.000000000000, 8.0 + 22.0*I]

But the last one will have to be converted to complex.


问:
How to throw variable result of an array on flutter from class to class
I'm trying to transport function result of json process from class to another class.
This is the json I rendered:

```<code>[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat",
    "body": "quia et suscipit\nsuscipit"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi"
  }
]
</code>```

Result of method is showing when I tried to print inside that method, but not printed on destination class. These is my codes:

Source class:

class DataNews {
  final String id;
  final String title;
  final String body;

  DataNews({this.id, this.title, this.body});

  factory DataNews.fromJson(json) {
    return DataNews(id: json['id'].toString(), title: json['title'], body: json['body']);
  }
}

getData() async {
    final response = await http.get('https://jsonplaceholder.typicode.com/posts');
    List data = json.decode(response.body);
    final items = (data).map((i) => new DataNews.fromJson(i));
    print('Satu');
    print(items.elementAt(1).id);
    print(items.elementAt(1).title);
    print(items.elementAt(1).body);
    print('Dua');
    return items;
}
```

<p>Destionation class:</p>

<pre class="lang-dart prettyprint-override"><code>class News extends StatefulWidget {
  @override
  _NewsState createState() => _NewsState(post: getData());
}

class _NewsState extends State<News> {
  Iterable<dynamic> post;
  _NewsState({Key key, this.post});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Text(post.elementAt(0).title),
      ),
    );
  }
}
</code>```

I want to show one of the result on Container. How to do that?

答:
First, your method getData() doesn't return an Iterable, it returns a Future<Iterable>, but it would be better if it returned a Future<List>, instead. Please, annotate the types you're using, it'll make your life much easier.

Future<List<DataNews>> getData() async {
  final response = await http.get('https://jsonplaceholder.typicode.com/posts');
  List data = json.decode(response.body);
  List<DataNews> items = data.map((i) => DataNews.fromJson(i)).toList();
  return items;
}
```

<p>Second, you should not pass any data to <code>_NewsState</code>. Either the data comes from the parent <code>Widget</code> and gets stored in <code>News</code> or you fetch the data inside <code>_NewsState</code> itself. <code>FutureBuilder</code> can help you to display the content that comes from a <code>Future</code>.</p>

<pre class="lang-dart prettyprint-override"><code>class News extends StatefulWidget {
  @override
  _NewsState createState() => _NewsState();
}

class _NewsState extends State<News> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: getData(), // Fetch the data
        builder: (_, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            // If your List got fetched, them show each DataNews using a ListView
            List<DataNews> newsList = snapshot.data;
            return ListView.builder(
              itemCount: newsList.length,
              itemBuilder: (_, int index) {
                return Container(
                  child: Text(newsList[index].title),
                );
              },
            );
          } else {
            // If you have no data, show a progress indicator
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }
}
</code>```

Body:
I'm trying to transport function result of json process from class to another class.
This is the json I rendered:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat",
    "body": "quia et suscipit\nsuscipit"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi"
  }
]

Result of method is showing when I tried to print inside that method, but not printed on destination class. These is my codes:

Source class:

class DataNews {
  final String id;
  final String title;
  final String body;

  DataNews({this.id, this.title, this.body});

  factory DataNews.fromJson(json) {
    return DataNews(id: json['id'].toString(), title: json['title'], body: json['body']);
  }
}

getData() async {
    final response = await http.get('https://jsonplaceholder.typicode.com/posts');
    List data = json.decode(response.body);
    final items = (data).map((i) => new DataNews.fromJson(i));
    print('Satu');
    print(items.elementAt(1).id);
    print(items.elementAt(1).title);
    print(items.elementAt(1).body);
    print('Dua');
    return items;
}

Destionation class:

class News extends StatefulWidget {
  @override
  _NewsState createState() => _NewsState(post: getData());
}

class _NewsState extends State<News> {
  Iterable<dynamic> post;
  _NewsState({Key key, this.post});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Text(post.elementAt(0).title),
      ),
    );
  }
}

I want to show one of the result on Container. How to do that?

Body:
First, your method getData() doesn't return an Iterable, it returns a Future<Iterable>, but it would be better if it returned a Future<List>, instead. Please, annotate the types you're using, it'll make your life much easier.

Future<List<DataNews>> getData() async {
  final response = await http.get('https://jsonplaceholder.typicode.com/posts');
  List data = json.decode(response.body);
  List<DataNews> items = data.map((i) => DataNews.fromJson(i)).toList();
  return items;
}

Second, you should not pass any data to _NewsState. Either the data comes from the parent Widget and gets stored in News or you fetch the data inside _NewsState itself. FutureBuilder can help you to display the content that comes from a Future.

class News extends StatefulWidget {
  @override
  _NewsState createState() => _NewsState();
}

class _NewsState extends State<News> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: getData(), // Fetch the data
        builder: (_, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            // If your List got fetched, them show each DataNews using a ListView
            List<DataNews> newsList = snapshot.data;
            return ListView.builder(
              itemCount: newsList.length,
              itemBuilder: (_, int index) {
                return Container(
                  child: Text(newsList[index].title),
                );
              },
            );
          } else {
            // If you have no data, show a progress indicator
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }
}


问:
CSS: translateY white space between
I have simple code with transform: skew and transform: translateY. I have problem with white space on bottom when I use this transforms.

I skewed 2 divs and last I moved with translateY and on bottom is white space which I must remove.

When last div is not transformed with translateY white space is between last and penultimate.

This is only exmaple not real website.

.wrapper0 {
  padding: 200px;
  background: pink;
}

.skews {
  transform: translateY(-150px);
}

.wrapper1 {
  background: lightblue;
  transform: skew(0deg, 5deg);
}

.container1 {
  transform: skew(0deg, -5deg);
  padding: 50px;
}

.wrapper2 {
  background: red;
  transform: skew(0deg, 5deg);
}

.container2 {
  transform: skew(0deg, -5deg);
  padding: 50px;
}

.wrapper1, .wrapper2 {
  padding: 20px;
}

footer {
  position: relative;
  z-index: -1;
  transform: translateY(-300px);
  background: yellow;
  padding: 20px;
  padding-top: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="wrapper0">
            <div class="container0">
              <p>
                Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.
              </p>
            </div>
          </div>

          <div class="skews">
              <div class="wrapper1">
                <div class="container1">
                  <p>
                    Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.
                  </p>
                </div>
              </div>

                  <div class="wrapper2">
                      <div class="container2">
                          <p>
                              Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.
                          </p>
                      </div>
                  </div>
          </div>

<footer>
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.</p>
</footer></code>```

答:
Your code is a little chaotic. Read in your free time about ":after", ":before", it's very useful. I simplified your code as much as possible. In addition, I have increased response.

body{
 margin: 0;
 padding: 0;
}
.wrapper0, .wrapper1, .wrapper2, footer {
 height: 200px;
    padding: 100px;
 position: relative;
 align-items: center;
  justify-content: center;
  display: flex;
}

.wrapper0 {
    z-index: 1;
}
.wrapper1 {
    z-index: 2;
}
.wrapper2 {
    z-index: 3;
}
footer {
    z-index: 1;
}
.wrapper0:before, .wrapper1:before, .wrapper2:before {
    left: 0;
    top: 0;

}
.wrapper0:before, .wrapper1:before, .wrapper2:before, footer:before {
 content: "";
    position: absolute;
    width: 100%;
    z-index: -1;
}
.wrapper0:before{
 background: pink;
 height: 500px;
}
.wrapper1:before, .wrapper2:before {
    transform: skew(0deg, 5deg);
 height: 430px;
}
.wrapper1:before{
    background: lightblue;

}
.wrapper2:before {
    background: red;
}
footer:before {
    height: 450px;
    top: -50px;
    left: 0;
    background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper0">
 Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.
</div>
<div class="wrapper1">
 Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.
</div>

<div class="wrapper2">
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.
</div>

<footer>
 Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.
</footer></code>```

Title: CSS: translateY white space between

Body:
I have simple code with transform: skew and transform: translateY. I have problem with white space on bottom when I use this transforms.

I skewed 2 divs and last I moved with translateY and on bottom is white space which I must remove.

When last div is not transformed with translateY white space is between last and penultimate.

This is only exmaple not real website.

.wrapper0 {
  padding: 200px;
  background: pink;
}

.skews {
  transform: translateY(-150px);
}

.wrapper1 {
  background: lightblue;
  transform: skew(0deg, 5deg);
}

.container1 {
  transform: skew(0deg, -5deg);
  padding: 50px;
}

.wrapper2 {
  background: red;
  transform: skew(0deg, 5deg);
}

.container2 {
  transform: skew(0deg, -5deg);
  padding: 50px;
}

.wrapper1, .wrapper2 {
  padding: 20px;
}

footer {
  position: relative;
  z-index: -1;
  transform: translateY(-300px);
  background: yellow;
  padding: 20px;
  padding-top: 200px;
}

                Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.

                    Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.

                              Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.

Body:
Your code is a little chaotic. Read in your free time about ":after", ":before", it's very useful. I simplified your code as much as possible. In addition, I have increased response.

body{
 margin: 0;
 padding: 0;
}
.wrapper0, .wrapper1, .wrapper2, footer {
 height: 200px;
    padding: 100px;
 position: relative;
 align-items: center;
  justify-content: center;
  display: flex;
}

.wrapper0 {
    z-index: 1;
}
.wrapper1 {
    z-index: 2;
}
.wrapper2 {
    z-index: 3;
}
footer {
    z-index: 1;
}
.wrapper0:before, .wrapper1:before, .wrapper2:before {
    left: 0;
    top: 0;

}
.wrapper0:before, .wrapper1:before, .wrapper2:before, footer:before {
 content: "";
    position: absolute;
    width: 100%;
    z-index: -1;
}
.wrapper0:before{
 background: pink;
 height: 500px;
}
.wrapper1:before, .wrapper2:before {
    transform: skew(0deg, 5deg);
 height: 430px;
}
.wrapper1:before{
    background: lightblue;

}
.wrapper2:before {
    background: red;
}
footer:before {
    height: 450px;
    top: -50px;
    left: 0;
    background: yellow;
}

<div class="wrapper0">
 Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.
</div>
<div class="wrapper1">
 Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.
</div>

<div class="wrapper2">
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.
</div>

<footer>
 Lorem ipsum dolor sit amet consectetur adipisicing elit. Explicabo dolorem maxime magnam tempora, maiores totam fugiat quisquam a minus sunt aut voluptatum at veniam deserunt quibusdam mollitia culpa necessitatibus labore.
</footer>


问:
Axios get call fired on select
I am receiving multiple json files from a server. They are all accessible on different urls based on years (2018,2019 and 2020). I am prefilling these years into a dropdown but now I want to fire a get call with axios everytime I change the value(?year=2018, ?year=2019 or ?year=2020). I also have another dropdown that is prefilled with IDs but have no idea how to attach a certain ID to selected year. These dropdowns are acting as filter for a table that is rendered below.

So to be more clear, when I reload I fire a get call for current year like so:    baseurl?year=2019, with this selection I get ALL the data but then if I select an ID, this ID needs to be added to url like so:
   baseurl?year=2019?id=0

My current code:

```<code>data() {
 return {
  year:[],
  id: 0,
 }
},

computed: {
 axiosParams(){
  const params = new URLSearchParams();
  params.append('year', this.year);
  return params;
 },

 //this returns my current year
 year() {
  var now = new Date()
  var nowy = now.getFullYear()

  return nowy
},

 //this method makes sure that the dropdown is always preffiled
 //with following years - eg. next year I only need 2019, 2020 and
 //2021
 years() {
   var yearsArray = []
   var now = new Date()
   for (let i = -1; i < 2; i++) {
     var nowy = now.getFullYear() + i
     yearsArray.push(nowy)
   }
   return yearsArray
 },

},
methods: {
 getYears: function() {
    axios.get('myurl',{
     params : this.axiosParams
    }
    }).then((response) => {
      this.year = response.data;
      this.table = response.data;
    })
 },
 getId: function() {
    axios.get('myurl',{
     params : {
      year: this.year,
      id : this.id
    }
    }
    }).then((response) => {
      this.id = response.data;
      this.table = response.data;
    })
 },
},

created: {
 this.getYears();
 this.getId();
}
</code>```

My HTML:

```<code><select v-model="year">
 <option v-model="yearsArray" v-for="year in years">{{year}} .
</option></select>

<select v-model="id"><option v-for="item in id">{{item}}</option> .
</select>
</code>```

Thanks!

答:
So, if I understand, you want to trigger an axios call when an id is selected. This can be done a couple of ways but this way will trigger on the selection of an id, and also on the selection of a year.

```<code><select v-model="selectedYear"  @change="yearSelected">
  <option v-for="year in years" :key="year" :value="year">{{year}} .</option>
</select>

<select v-model="selectedId" @change="idSelected">
  <option v-for="id in ids" :key="id" :value="id">{{id}}</option> .
</select>
</code>```

Here, the years is from your computed property for years and ids is what you said was a dropdown "prefilled with IDs". The two v-model properties are initially set to null then are assigned a value on selection. They are defined in data like so.

```<code>data: () => ({
  selectedId: null,
  selectedYear: null,
}),
</code>```

Each  has a function call to do something with the selected option, @change="idSelected" which calls this method:

```<code>methods: {
  idSelected() {
    console.log(this.selectedId)
    // here you make you axios call using this.selectedId as the param
    axios.get('myurl',{
      params : {
        year: this.selectedYear,
        id : this.selectedId
      }
    },
...
}
</code>```

You could have the two selects without the @change and have a button that triggers the function call with @click. Either way you use the selectedId and selectedYear in that method.

Title: Axios get call fired on select

Body:
I am receiving multiple json files from a server. They are all accessible on different urls based on years (2018,2019 and 2020). I am prefilling these years into a dropdown but now I want to fire a get call with axios everytime I change the value(?year=2018, ?year=2019 or ?year=2020). I also have another dropdown that is prefilled with IDs but have no idea how to attach a certain ID to selected year. These dropdowns are acting as filter for a table that is rendered below.

So to be more clear, when I reload I fire a get call for current year like so:    baseurl?year=2019, with this selection I get ALL the data but then if I select an ID, this ID needs to be added to url like so:
   baseurl?year=2019?id=0

My current code:

data() {
 return {
  year:[],
  id: 0,
 }
},

computed: {
 axiosParams(){
  const params = new URLSearchParams();
  params.append('year', this.year);
  return params;
 },

 //this returns my current year
 year() {
  var now = new Date()
  var nowy = now.getFullYear()

  return nowy
},

 //this method makes sure that the dropdown is always preffiled
 //with following years - eg. next year I only need 2019, 2020 and
 //2021
 years() {
   var yearsArray = []
   var now = new Date()
   for (let i = -1; i < 2; i++) {
     var nowy = now.getFullYear() + i
     yearsArray.push(nowy)
   }
   return yearsArray
 },

},
methods: {
 getYears: function() {
    axios.get('myurl',{
     params : this.axiosParams
    }
    }).then((response) => {
      this.year = response.data;
      this.table = response.data;
    })
 },
 getId: function() {
    axios.get('myurl',{
     params : {
      year: this.year,
      id : this.id
    }
    }
    }).then((response) => {
      this.id = response.data;
      this.table = response.data;
    })
 },
},

created: {
 this.getYears();
 this.getId();
}

My HTML:

<select v-model="year">
 <option v-model="yearsArray" v-for="year in years">{{year}} .
</option></select>

<select v-model="id"><option v-for="item in id">{{item}}</option> .
</select>

Thanks!

Body:
So, if I understand, you want to trigger an axios call when an id is selected. This can be done a couple of ways but this way will trigger on the selection of an id, and also on the selection of a year.

<select v-model="selectedYear"  @change="yearSelected">
  <option v-for="year in years" :key="year" :value="year">{{year}} .</option>
</select>

<select v-model="selectedId" @change="idSelected">
  <option v-for="id in ids" :key="id" :value="id">{{id}}</option> .
</select>

Here, the years is from your computed property for years and ids is what you said was a dropdown "prefilled with IDs". The two v-model properties are initially set to null then are assigned a value on selection. They are defined in data like so.

data: () => ({
  selectedId: null,
  selectedYear: null,
}),

Each  has a function call to do something with the selected option, @change="idSelected" which calls this method:

methods: {
  idSelected() {
    console.log(this.selectedId)
    // here you make you axios call using this.selectedId as the param
    axios.get('myurl',{
      params : {
        year: this.selectedYear,
        id : this.selectedId
      }
    },
...
}

You could have the two selects without the @change and have a button that triggers the function call with @click. Either way you use the selectedId and selectedYear in that method.


问:
Pass external variable to xidel in bash loop script
I try to parse html page using XPath with xidel.
The page have a table with multiple rows and columns
I need to get values from each row from columns 2 and 5 (IP and port) and store them in csv-like file.
Here is my script

```<code>#!/bin/bash
for (( i = 2; i <= 100; i++ ))
do
xidel http://www.vpngate.net/en/ -e '//*[@id="vg_hosts_table_id"]/tbody/tr["'$i'"]/td[2]/span[1]' >> "$i".txt #get value from first column
xidel http://www.vpngate.net/en/ -e '//*[@id="vg_hosts_table_id"]/tbody/tr["'$i'"]/td[5]' >> "$i".txt #get value from second column
sed -i ':a;N;$!ba;s/\n/^/g' "$i".txt #replace newline with custom delimiter
sed -i '/\s/d' "$i".txt #remove blanks
cat "$i".txt >> ip_port_list #create list
zip -m ips.zip "$i".txt #archive unneeded texts
done
</code>```

The perfomance is not issue
When i manually increment each tr - looks perfect. But not with variable from loop.
I want to receive a pair of values from each row.
Now i got only partial data or even empty file

答:
I need to get values from each row from columns 2 and 5 (IP and port) and store them in csv-like file.

```<code>xidel -s "https://www.vpngate.net/en/" -e '
  (//table[@id="vg_hosts_table_id"])[3]//tr[not(td[@class="vg_table_header"])]/concat(
    td[2]/span[@style="font-size: 10pt;"],
    ",",
    extract(
      td[5],
      "TCP: (\d+)",
      1
    )
  )
'
220.218.70.177,443
211.58.36.54,995
1.239.223.190,1351
[...]
153.207.18.229,1542
</code>```

(//table[@id="vg_hosts_table_id"])[3]: Select the 3rd table of its
kind. The one you want.

//tr[not(td[@class="vg_table_header"])]: Select all rows, except the headers.

td[2]/span[@style="font-size: 10pt;"]: Select the 2nd column and the  that contains just the IP-address.

extract(td[5],"TCP: (\d+)",1): Select the 5th column and extract (regex) the numerical value after "TCP ".

Body:
I try to parse html page using XPath with xidel.
The page have a table with multiple rows and columns
I need to get values from each row from columns 2 and 5 (IP and port) and store them in csv-like file.
Here is my script

#!/bin/bash
for (( i = 2; i <= 100; i++ ))
do
xidel http://www.vpngate.net/en/ -e '//*[@id="vg_hosts_table_id"]/tbody/tr["'$i'"]/td[2]/span[1]' >> "$i".txt #get value from first column
xidel http://www.vpngate.net/en/ -e '//*[@id="vg_hosts_table_id"]/tbody/tr["'$i'"]/td[5]' >> "$i".txt #get value from second column
sed -i ':a;N;$!ba;s/\n/^/g' "$i".txt #replace newline with custom delimiter
sed -i '/\s/d' "$i".txt #remove blanks
cat "$i".txt >> ip_port_list #create list
zip -m ips.zip "$i".txt #archive unneeded texts
done

The perfomance is not issue
When i manually increment each tr - looks perfect. But not with variable from loop.
I want to receive a pair of values from each row.
Now i got only partial data or even empty file

Body:
I need to get values from each row from columns 2 and 5 (IP and port) and store them in csv-like file.

xidel -s "https://www.vpngate.net/en/" -e '
  (//table[@id="vg_hosts_table_id"])[3]//tr[not(td[@class="vg_table_header"])]/concat(
    td[2]/span[@style="font-size: 10pt;"],
    ",",
    extract(
      td[5],
      "TCP: (\d+)",
      1
    )
  )
'
220.218.70.177,443
211.58.36.54,995
1.239.223.190,1351
[...]
153.207.18.229,1542

(//table[@id="vg_hosts_table_id"])[3]: Select the 3rd table of its
kind. The one you want.

//tr[not(td[@class="vg_table_header"])]: Select all rows, except the headers.

td[2]/span[@style="font-size: 10pt;"]: Select the 2nd column and the <span> that contains just the IP-address.

extract(td[5],"TCP: (\d+)",1): Select the 5th column and extract (regex) the numerical value after "TCP ".


问:
Webpack config for SSR SCSS
I have a React-TypeScript SSR app where I used SCSS files for my styling. I need to write a rule in Webpack to load the SCSS and I haven't been able to do it.

I found various solutions online, all of which are extremely complex and use things like mini-css-extract-plugin. I couldn't get any of them to work.

I currently have two webpack config files, one for the client (web) and one for the server (node), both of which load the SCSS as such:

```<code>{
    test: /\.scss$/,
    use: ["css-loader", "sass-loader"]
}
</code>```

I also encountered another issue in that I can't use style-loader as it throws an error about the window object. Does anyone have a working example (simple preferably) of loading SCSS in Webpack?

答:
You are on right track with 2 web config file you can use

https://gist.github.com/mburakerman/629783c16acf5e5f03de60528d3139af

But don't set any other config file like babel.rc .yaml etc or other definition in project.json

try this

```<code>        test: /\.scss$/,
        use: [
            MiniCssExtractPlugin.loader,
            'css-loader',
            'postcss-loader',
            'sass-loader'
        ]
</code>```

//..

```<code>plugins: [
    new MiniCssExtractPlugin({
        filename: 'assets/css/bundle-[contenthash].css',
        chunkFilename: 'assets/css/bundle-[contenthash].css'
    })
],
</code>```

Look full example https://github.com/dewelloper/pzone/blob/master/webpack.config.store.js

Title: Webpack config for SSR SCSS

Body:
I have a React-TypeScript SSR app where I used SCSS files for my styling. I need to write a rule in Webpack to load the SCSS and I haven't been able to do it.

I found various solutions online, all of which are extremely complex and use things like mini-css-extract-plugin. I couldn't get any of them to work.

I currently have two webpack config files, one for the client (web) and one for the server (node), both of which load the SCSS as such:

{
    test: /\.scss$/,
    use: ["css-loader", "sass-loader"]
}

I also encountered another issue in that I can't use style-loader as it throws an error about the window object. Does anyone have a working example (simple preferably) of loading SCSS in Webpack?

Body:
You are on right track with 2 web config file you can use

https://gist.github.com/mburakerman/629783c16acf5e5f03de60528d3139af

But don't set any other config file like babel.rc .yaml etc or other definition in project.json

try this

        test: /\.scss$/,
        use: [
            MiniCssExtractPlugin.loader,
            'css-loader',
            'postcss-loader',
            'sass-loader'
        ]

//..

plugins: [
    new MiniCssExtractPlugin({
        filename: 'assets/css/bundle-[contenthash].css',
        chunkFilename: 'assets/css/bundle-[contenthash].css'
    })
],

Look full example https://github.com/dewelloper/pzone/blob/master/webpack.config.store.js