问:
SQLAlchemy/Flask: How to implement local and global unique slugs with SQLAlchemy events?
We are implementing a webservice, that displays data from my database with flask and sqlalchemy. The database schema is done, but now we struggle with the implementation of the slugs to display all the elements from the database.

Example of the database relation:

```<code>class Parent(Base, db.Model):

    __tablename__ = "parent"

    id = Column(Integer, primary_key=True)
    name = Column(String(80), unique=True, nullable=False)
    slug = Column(String, nullable=False, default=set_slug())

class Child(Base, db.Model):

    __tablename__ = "child"

    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey("parent.id"), nullable=False)
    name = Column(String(80), unique=True, nullable=False)
    slug = Column(String, nullable=False, default=set_slug())
</code>```

The default value for the slug is just the name, that get's slugified with the slugify method from the slugify package. In the database also exist elements with the same name, but they are different because of their relationship to the parent element. So the slug should be the same, if there are two elements with the same name but a different parent. Also if two elements have the same name and parent, the slug should be unique for both elements.

My first idea was to implement an attribute event for child.name and parent.name whenever a set event is triggered.

```<code>from functools import partial
from slugify import slugify

def set_slug(target: Base, value: str, oldvalue: str, initiator: Event, global_unique=False) -> None:
    slug_value = slugify(value)

    # build the database query
    db_query = target.__class__.query
    if not global_unique:
         # case, the slug is local unique
         db_query = db_query.filter(target.__class__.parent_id == target.parent_id )

    all_slugs = [entry.slug for entry in db_query.all()]
    if value and (not target.slug or value != oldvalue):
        if slug_value not in all_slugs:
            # case, the standard slug (name = slug) is available
            target.slug = slug_value
        else:
            # case, the standard slug is already in use
            counter = 1
            while True:
                # iterate as long as no unique slug was found
                new_slug = f"{slug_value}-{counter}"
                if new_slug not in all_slugs:
                    target.slug = new_slug
                    return
                counter += 1

event.listen(Child.name, "set", set_slug, retval=False)
event.listen(Parent.name, "set", partial(set_slug, global_unique=True), retval=False)
</code>```

The method works overall, if the target object already exists in the database. The problem is, that this doesn't work if the object was created, because every attribute is just None. Is there a way to get the parent_id in that state of the event or do you have any other ideas, how to implement that uniquify?

答:
Slugs can really slow you down.  Why not just make them all globally unique?  A positive side-effect is that if you change a name then you don't have to revisit the entire uniqueness issue again because the code/id in the slug is already unique.

Using sequences

If you use postgresql you can use sequences for your primary keys which can be created before an object is created.

Then you don't need to involve the parent ids, like this:

child_id = session.execute(childs_seq)
child = Child(id=child_id, slug=f"{slugify(name)}--{child_id}", name=name))
#...
```
<h3>Using random code</h3>
<p>Another option, which is probably better, is to just generate a random string and attach it to the slug, you might want to save it to more easily regenerate the slug or for fast lookup and make the column unique.  You could generate a code using something like Random string generation with upper case letters and digits</p>
<pre class="lang-py prettyprint-override"><code>random_code = get_random_code()
child = Child(slug=f"{slugify(name)}--{random_code}", code=random_code, name=name)
#...
</code>```

Body:
We are implementing a webservice, that displays data from my database with flask and sqlalchemy. The database schema is done, but now we struggle with the implementation of the slugs to display all the elements from the database.

Example of the database relation:

class Parent(Base, db.Model):

    __tablename__ = "parent"

    id = Column(Integer, primary_key=True)
    name = Column(String(80), unique=True, nullable=False)
    slug = Column(String, nullable=False, default=set_slug())

class Child(Base, db.Model):

    __tablename__ = "child"

    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey("parent.id"), nullable=False)
    name = Column(String(80), unique=True, nullable=False)
    slug = Column(String, nullable=False, default=set_slug())

The default value for the slug is just the name, that get's slugified with the slugify method from the slugify package. In the database also exist elements with the same name, but they are different because of their relationship to the parent element. So the slug should be the same, if there are two elements with the same name but a different parent. Also if two elements have the same name and parent, the slug should be unique for both elements.

My first idea was to implement an attribute event for child.name and parent.name whenever a set event is triggered.

from functools import partial
from slugify import slugify

def set_slug(target: Base, value: str, oldvalue: str, initiator: Event, global_unique=False) -> None:
    slug_value = slugify(value)

    # build the database query
    db_query = target.__class__.query
    if not global_unique:
         # case, the slug is local unique
         db_query = db_query.filter(target.__class__.parent_id == target.parent_id )

    all_slugs = [entry.slug for entry in db_query.all()]
    if value and (not target.slug or value != oldvalue):
        if slug_value not in all_slugs:
            # case, the standard slug (name = slug) is available
            target.slug = slug_value
        else:
            # case, the standard slug is already in use
            counter = 1
            while True:
                # iterate as long as no unique slug was found
                new_slug = f"{slug_value}-{counter}"
                if new_slug not in all_slugs:
                    target.slug = new_slug
                    return
                counter += 1

event.listen(Child.name, "set", set_slug, retval=False)
event.listen(Parent.name, "set", partial(set_slug, global_unique=True), retval=False)

The method works overall, if the target object already exists in the database. The problem is, that this doesn't work if the object was created, because every attribute is just None. Is there a way to get the parent_id in that state of the event or do you have any other ideas, how to implement that uniquify?

Body:
Slugs can really slow you down.  Why not just make them all globally unique?  A positive side-effect is that if you change a name then you don't have to revisit the entire uniqueness issue again because the code/id in the slug is already unique.

Using sequences

If you use postgresql you can use sequences for your primary keys which can be created before an object is created.

Then you don't need to involve the parent ids, like this:

child_id = session.execute(childs_seq)
child = Child(id=child_id, slug=f"{slugify(name)}--{child_id}", name=name))
#...

Using random code

Another option, which is probably better, is to just generate a random string and attach it to the slug, you might want to save it to more easily regenerate the slug or for fast lookup and make the column unique.  You could generate a code using something like Random string generation with upper case letters and digits

random_code = get_random_code()
child = Child(slug=f"{slugify(name)}--{random_code}", code=random_code, name=name)
#...


来源: stackexchange

问:
How to set transition for 2 backgrounds in an element?
in this code:

```<code>    #p1 {
        background-image: url(backimgs/first/1.jpg), url(backimgs/first/2.jpg);
        background-color: #05080d;
        background-position: left top, left bottom;
        background-size: 100% 35%, 100% 65%;
    }
</code>```

I want when the page shows up, first show backimgs/first/1.jpg then after 1 sec show backimgs/first/2.jpg. how can I do it?

答:
You mention 'transition' in the title so you will need to control the two parts of the background separately.

To enable this, this snippet removes the backgrounds from the element itself, instead putting them onto two pseudo elements. The before pseudo element having the first image as background and the after pseudo element having the second one.

Separating the components in this way means we can animate the opacities, the first pseudo element going from opacity 0 to opacity 1 in the first second.

Note however that a little hack has been added to ths snippet. As the animation on the before pseudo element is to happen on load then there needs to be some method of waiting for the background image to load before the animation starts else there is a danger it will be part way through, or even finished, before the image is actually available.

I do not know the wider context of how you are testing for load being complete so have just put a delay in here for demo purposes. You'll need to decide what to do to avoid this inital load situation.

* {
  margin: 0;
  padding: 0;
}

#p1 {
  /* added for this demo */
  display: inline-block;
  width: 100vw;
  height: 100vh;
  position: relative;
}

#p1::before,
#p1::after {
  content: '';
  position: absolute;
  z-index: -1;
  width: 100%;
  left: 0;
  display: inline-block;
  background-color: #05080d;
  background-size: cover;
  background-repeat: no-repeat no-repeat;
  background-position: center center;
  animation: fadein 1s linear;
  animation-fill-mode: forwards;
  opacity: 0;
}

#p1::before {
  top: 0;
  height: 35%;
  background-image: url(https://picsum.photos/id/1018/1024/768);
  animation-delay: 1s;
  /* a hack to ensure it is loaded before start the animation */
}

#p1::after {
  bottom: 0;
  height: 65%;
  background-image: url(https://picsum.photos/id/1015/1024/768);
  animation-delay: 2s;
}

@keyframes fadein {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="p1"></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
in this code:

    #p1 {
        background-image: url(backimgs/first/1.jpg), url(backimgs/first/2.jpg);
        background-color: #05080d;
        background-position: left top, left bottom;
        background-size: 100% 35%, 100% 65%;
    }

I want when the page shows up, first show backimgs/first/1.jpg then after 1 sec show backimgs/first/2.jpg. how can I do it?

Body:
You mention 'transition' in the title so you will need to control the two parts of the background separately.

To enable this, this snippet removes the backgrounds from the element itself, instead putting them onto two pseudo elements. The before pseudo element having the first image as background and the after pseudo element having the second one.

Separating the components in this way means we can animate the opacities, the first pseudo element going from opacity 0 to opacity 1 in the first second.

Note however that a little hack has been added to ths snippet. As the animation on the before pseudo element is to happen on load then there needs to be some method of waiting for the background image to load before the animation starts else there is a danger it will be part way through, or even finished, before the image is actually available.

I do not know the wider context of how you are testing for load being complete so have just put a delay in here for demo purposes. You'll need to decide what to do to avoid this inital load situation.

* {
  margin: 0;
  padding: 0;
}

#p1 {
  /* added for this demo */
  display: inline-block;
  width: 100vw;
  height: 100vh;
  position: relative;
}

#p1::before,
#p1::after {
  content: '';
  position: absolute;
  z-index: -1;
  width: 100%;
  left: 0;
  display: inline-block;
  background-color: #05080d;
  background-size: cover;
  background-repeat: no-repeat no-repeat;
  background-position: center center;
  animation: fadein 1s linear;
  animation-fill-mode: forwards;
  opacity: 0;
}

#p1::before {
  top: 0;
  height: 35%;
  background-image: url(https://picsum.photos/id/1018/1024/768);
  animation-delay: 1s;
  /* a hack to ensure it is loaded before start the animation */
}

#p1::after {
  bottom: 0;
  height: 65%;
  background-image: url(https://picsum.photos/id/1015/1024/768);
  animation-delay: 2s;
}

@keyframes fadein {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

<div id="p1"></div>


问:
using a fetch inside another fetch in javascript
I want to get an api and after that call another one. Is it wisely using a code like this in javascript?</p>

```<code>fetch(url, {
 method: 'get',
 }).then(function(response) {
  response.json().then(function(data) {
    fetch(anotherUrl).then(function(response) {
      return response.json();
    }).catch(function() {
      console.log("Booo");
    });
  });
})
.catch(function(error) {
  console.log('Request failed', error)
});
</code>```

答:
just some ways of doing it.

1, using async -await

```<code> app.get("/getemployeedetails/:id", async (req, res) => {
  const id = req.params.id;
  const employeeUrl = "http://localhost:3000/employee/" + id;
  try {
    const response = await fetch(employeeUrl);
    const employee = await response.json();

    const projectUrl = "http://localhost:3000/project/" + employee.project_id;
    const response1 = await fetch(projectUrl);
    const project = await response1.json();

    const result = {
      ...employee,
      ...project,
    };
    res.send(result);
  } catch (error) {
    console.log("getData: ", error);
  }
});
</code>```

2, chaining of then

```<code>app.get("/getemployeedetails/:id", (req, res) => {
  const id = req.params.id;
  const employeeUrl = "http://localhost:3000/employee/" + id;
  let employeeResponse = null;
  fetch(employeeUrl)
    .then((employee) => employee.json())
    .then((resp) => {
        employeeResponse = resp
      const projectUrl =
        "http://localhost:3000/project/" + employeeResponse.project_id;
      return fetch(projectUrl);
    })
    .then((project) => project.json())
    .then((projectResponse) => {
      const result = {
        ...employeeResponse,
        ...projectResponse,
      };
      res.send(result);
    })
    .catch((err) => console.log(err));
});
</code>```

3, chaining in a better way

```<code>app.get("/getemployeedetails/:id", (req, res) => {
  const id = req.params.id;
  getEmployeeResponse(id).then((employeeResponse) => {
    getProjectResponse(employeeResponse.project_id)
      .then((projectResponse) => {
        const result = {
          ...employeeResponse,
          ...projectResponse,
        };
        res.send(result);
      })
      .catch((err) => console.log(err));
  });
});

function getEmployeeResponse(id) {
  return new Promise((resolve, reject) => {
    const employeeUrl = "http://localhost:3000/employee/" + id;
    fetch(employeeUrl)
      .then((employee) => employee.json())
      .then((resp) => resolve(resp))
      .catch((err) => reject(err));
  });
}

function getProjectResponse(id) {
  return new Promise((resolve, reject) => {
    const projectUrl = "http://localhost:3000/project/" + id;
    fetch(projectUrl)
      .then((project) => project.json())
      .then((resp) => resolve(resp))
      .catch((err) => reject(err));
  });
}
</code>```

you decide.

ContentLicense: CC BY-SA 3.0

Body:
I want to get an api and after that call another one. Is it wisely using a code like this in javascript?

fetch(url, {
 method: 'get',
 }).then(function(response) {
  response.json().then(function(data) {
    fetch(anotherUrl).then(function(response) {
      return response.json();
    }).catch(function() {
      console.log("Booo");
    });
  });
})
.catch(function(error) {
  console.log('Request failed', error)
});

Body:
just some ways of doing it.

1, using async -await

 app.get("/getemployeedetails/:id", async (req, res) => {
  const id = req.params.id;
  const employeeUrl = "http://localhost:3000/employee/" + id;
  try {
    const response = await fetch(employeeUrl);
    const employee = await response.json();

    const projectUrl = "http://localhost:3000/project/" + employee.project_id;
    const response1 = await fetch(projectUrl);
    const project = await response1.json();

    const result = {
      ...employee,
      ...project,
    };
    res.send(result);
  } catch (error) {
    console.log("getData: ", error);
  }
});

2, chaining of then

app.get("/getemployeedetails/:id", (req, res) => {
  const id = req.params.id;
  const employeeUrl = "http://localhost:3000/employee/" + id;
  let employeeResponse = null;
  fetch(employeeUrl)
    .then((employee) => employee.json())
    .then((resp) => {
        employeeResponse = resp
      const projectUrl =
        "http://localhost:3000/project/" + employeeResponse.project_id;
      return fetch(projectUrl);
    })
    .then((project) => project.json())
    .then((projectResponse) => {
      const result = {
        ...employeeResponse,
        ...projectResponse,
      };
      res.send(result);
    })
    .catch((err) => console.log(err));
});

3, chaining in a better way

app.get("/getemployeedetails/:id", (req, res) => {
  const id = req.params.id;
  getEmployeeResponse(id).then((employeeResponse) => {
    getProjectResponse(employeeResponse.project_id)
      .then((projectResponse) => {
        const result = {
          ...employeeResponse,
          ...projectResponse,
        };
        res.send(result);
      })
      .catch((err) => console.log(err));
  });
});

function getEmployeeResponse(id) {
  return new Promise((resolve, reject) => {
    const employeeUrl = "http://localhost:3000/employee/" + id;
    fetch(employeeUrl)
      .then((employee) => employee.json())
      .then((resp) => resolve(resp))
      .catch((err) => reject(err));
  });
}

function getProjectResponse(id) {
  return new Promise((resolve, reject) => {
    const projectUrl = "http://localhost:3000/project/" + id;
    fetch(projectUrl)
      .then((project) => project.json())
      .then((resp) => resolve(resp))
      .catch((err) => reject(err));
  });
}

you decide.


问:
SQL method for returning data from multiple tables based on column names
I am trying to do something a little weird and cannot figure out the right method for getting it done. Essentially I am trying to pull all tables/views and columns where the column name is like some string. In addition to that I would like to pull 1 row of data from that table/view and column combination. The second part is where I am lost. I know I can pull the necessary tables/views and columns with the below select statement.

```<code>SELECT      COLUMN_NAME AS 'ColumnName'
            ,TABLE_NAME AS  'TableName'
FROM        INFORMATION_SCHEMA.COLUMNS
WHERE       COLUMN_NAME LIKE '%email%'
ORDER BY    TableName,ColumnName;
</code>```

So that I get something like the below

```<code>|ColumnName   |TableName   |
|emailAddress |all_emails  |
           ....
</code>```

But I want to get something like this:

```<code>|ColumnName   |TableName   |Example             |
|emailAddress |all_emails  |first.last@gmail.com|
                    ....
</code>```

Can anyone offer any insight?

答:
I can't think of a simple way to do this within a query, but here's one option...

Put the list of the columns and tables into a temp table and run them through a loop, using dynamic SQL to select the max row for each.

I've added plenty of comments below to explain it.

DECLARE @SQL NVARCHAR(1000)
DECLARE @TABLE NVARCHAR(1000)
DECLARE @COLUMN NVARCHAR(1000)
DECLARE @SAMPLE NVARCHAR(1000)

DROP TABLE IF EXISTS ##TABLELIST

SELECT      COLUMN_NAME AS 'ColumnName'
           ,TABLE_NAME AS  'TableName'
           ,ROW_NUMBER() OVER (ORDER BY COLUMN_NAME,TABLE_NAME)[RN]

INTO ##TABLELIST

FROM        INFORMATION_SCHEMA.COLUMNS
WHERE       COLUMN_NAME LIKE '%email%';

ALTER TABLE ##TABLELIST

ADD [Sample] NVARCHAR(1000) -- Add a column for your sample row.

DECLARE @ROWCOUNTER INT = 1 -- Add a counter for the loop to use.

WHILE @ROWCOUNTER <= (SELECT MAX([RN]) FROM ##TABLELIST) -- Keep the loop running until the end of the list.

BEGIN

UPDATE ##TABLELIST
SET @TABLE  = TableName WHERE [RN] = @ROWCOUNTER -- Get the table name into a variable.

UPDATE ##TABLELIST
SET @COLUMN = ColumnName WHERE [RN] = @ROWCOUNTER -- Get the column name into a variable.

SET @SQL = 'SELECT @SAMPLE = MAX([' + @COLUMN + ']) FROM [' + @TABLE + ']' -- Create SQL statement to pull max column from table specified in variables.

EXEC SP_EXECUTESQL @SQL, N'@SAMPLE NVARCHAR(1000) OUTPUT', @SAMPLE OUTPUT -- Execute SQL and put the output into the @SAMPLE variable.

UPDATE ##TABLELIST
SET [Sample] = CAST(@SAMPLE AS NVARCHAR(1000)) WHERE [RN] = @ROWCOUNTER -- Insert the SQL output into the sample column.

SET @ROWCOUNTER = @ROWCOUNTER+1 -- Add one to the row counter to move to the next column and table.

END

SELECT * FROM ##TABLELIST -- Select final output.

```

Body:
I am trying to do something a little weird and cannot figure out the right method for getting it done. Essentially I am trying to pull all tables/views and columns where the column name is like some string. In addition to that I would like to pull 1 row of data from that table/view and column combination. The second part is where I am lost. I know I can pull the necessary tables/views and columns with the below select statement.

SELECT      COLUMN_NAME AS 'ColumnName'
            ,TABLE_NAME AS  'TableName'
FROM        INFORMATION_SCHEMA.COLUMNS
WHERE       COLUMN_NAME LIKE '%email%'
ORDER BY    TableName,ColumnName;

So that I get something like the below

|ColumnName   |TableName   |
|emailAddress |all_emails  |
           ....

But I want to get something like this:

|ColumnName   |TableName   |Example             |
|emailAddress |all_emails  |first.last@gmail.com|
                    ....

Can anyone offer any insight?


问:
When running script on Camera.main play doesn't update scene
I currently have the following scene that appears in game mode and in my scene mode.

I attempt to add some movement with a mouse in a script with the following code:

```<code>using UnityEngine;

public class MouseHandler : MonoBehaviour
{
    // horizontal rotation speed
    public float horizontalSpeed = 1f;
    // vertical rotation speed
    public float verticalSpeed = 1f;
    private float xRotation = 0.0f;
    private float yRotation = 0.0f;
    private Camera cam;

    void Start()
    {
        cam = Camera.main;
    }

    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * horizontalSpeed;
        float mouseY = Input.GetAxis("Mouse Y") * verticalSpeed;

        yRotation += mouseX;
        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90, 90);
// this is for the mouse to move around the scene
        cam.transform.eulerAngles = new Vector3(xRotation, yRotation, 0.0f);
    }
}
</code>```

It works fine.  It's important to note the camera Main Camera displays the image above.

So it looks right.

Here is what the play view looks like when cam.transform.eulerAngles is not commented out.  When it's commented out it appears exactly as the first reference which is correct.  Any idea what's causing this?

答:
The camera's rotation has some nonzero value assigned in your scene. So, when xRotation and yRotation are initialized with zeros, the offending line cam.transform.eulerAngles = new Vector3(xRotation, yRotation, 0.0f); overwrites the scene-defined rotation with zeros, aka, the "identity rotation".

To avoid this, have your code read what your camera's rotation is at the start and use those values instead of zeros:

```<code>void Start()
{
    cam = Camera.main;

    Vector3 camEulers = cam.transform.eulerAngles;
    xRotation = camEulers.x;
    yRotation = camEulers.y;
}
</code>```

Body:
I currently have the following scene that appears in game mode and in my scene mode.

I attempt to add some movement with a mouse in a script with the following code:

using UnityEngine;

public class MouseHandler : MonoBehaviour
{
    // horizontal rotation speed
    public float horizontalSpeed = 1f;
    // vertical rotation speed
    public float verticalSpeed = 1f;
    private float xRotation = 0.0f;
    private float yRotation = 0.0f;
    private Camera cam;

    void Start()
    {
        cam = Camera.main;
    }

    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * horizontalSpeed;
        float mouseY = Input.GetAxis("Mouse Y") * verticalSpeed;

        yRotation += mouseX;
        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90, 90);
// this is for the mouse to move around the scene
        cam.transform.eulerAngles = new Vector3(xRotation, yRotation, 0.0f);
    }
}

It works fine.  It's important to note the camera Main Camera displays the image above.

So it looks right.

Here is what the play view looks like when cam.transform.eulerAngles is not commented out.  When it's commented out it appears exactly as the first reference which is correct.  Any idea what's causing this?

Body:
The camera's rotation has some nonzero value assigned in your scene. So, when xRotation and yRotation are initialized with zeros, the offending line cam.transform.eulerAngles = new Vector3(xRotation, yRotation, 0.0f); overwrites the scene-defined rotation with zeros, aka, the "identity rotation".

To avoid this, have your code read what your camera's rotation is at the start and use those values instead of zeros:

void Start()
{
    cam = Camera.main;

    Vector3 camEulers = cam.transform.eulerAngles;
    xRotation = camEulers.x;
    yRotation = camEulers.y;
}


问:
Set base href on publish in Blazor WebAssembly project
The index.html file in Blazor WebAsssembly has a value of "/" for href. My understanding is that I would just change this if I need to host my app in a subdirectory of a website.

I'm working on an ASP.NET hosted Blazor WebAppsembly app.

What if I have multiple environments and I want to publish this with different bases - for example http://mysite/someapptest/ and http://mysite/someappstage/.

Since it's static HTML I don't think I can get to it programmatically at runtime. Is there any way to do that at build time without writing some kind of custom handler to swap out a placeholder or something?

For example, Angular has ng build --base-href /someapptest/

Anything similar for Blazor?

答:
There are two settings that you use:

<Base..>

The settings depend on your Css setup.

    <base href="/red/" />
    <link href="/red/css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="/red/css/app.css" rel="stylesheet" />
    <link href="/red/Hydra.Red.styles.css" rel="stylesheet" />
```
<h3><StaticWebAssetBasePath..></h3>
<p>Set in the WebAssembly Proj file.  This sets the path that the WASM files can be accessed.</p>
```    <StaticWebAssetBasePath>red</StaticWebAssetBasePath>
```
<p>The main problem you face is Page Refreshes. What happens when a user hits F5 on say <code>/Red/FetchData</code>.  You need to make sure the server site knows which SPA launch page to hit,  and the SPA router needs to know the route <code>/Red/FetchData</code>, not just <code>FetchData</code> which may be the route internally in the project.</p>
<p>You end up with multiple End Points in your server config:</p>
```app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/red"), app1 =>
{
    app1.UseBlazorFrameworkFiles("/red");
    app1.UseRouting();
    app1.UseEndpoints(endpoints =>
    {
      endpoints.MapFallbackToPage("/red/{*path:nonfile}", "/_Red");
    });

});
```

I wrote a proof of concept article on the subject a while ago on Code Project.  It's a bit dated now - https://www.codeproject.com/Articles/5287009/Blazor-Hydra-Hosting-Multiple-Blazor-SPAs-on-a-sin.
There's an associated Repo here: https://github.com/ShaunCurtis/Hydra

Body:
There are two settings that you use:

<Base..>

The settings depend on your Css setup.

    <base href="/red/" />
    <link href="/red/css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="/red/css/app.css" rel="stylesheet" />
    <link href="/red/Hydra.Red.styles.css" rel="stylesheet" />

<StaticWebAssetBasePath..>

Set in the WebAssembly Proj file.  This sets the path that the WASM files can be accessed.

    <StaticWebAssetBasePath>red</StaticWebAssetBasePath>

The main problem you face is Page Refreshes. What happens when a user hits F5 on say /Red/FetchData.  You need to make sure the server site knows which SPA launch page to hit,  and the SPA router needs to know the route /Red/FetchData, not just FetchData which may be the route internally in the project.

You end up with multiple End Points in your server config:

app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/red"), app1 =>
{
    app1.UseBlazorFrameworkFiles("/red");
    app1.UseRouting();
    app1.UseEndpoints(endpoints =>
    {
      endpoints.MapFallbackToPage("/red/{*path:nonfile}", "/_Red");
    });

});

I wrote a proof of concept article on the subject a while ago on Code Project.  It's a bit dated now - https://www.codeproject.com/Articles/5287009/Blazor-Hydra-Hosting-Multiple-Blazor-SPAs-on-a-sin.
There's an associated Repo here: https://github.com/ShaunCurtis/Hydra


问:
AWS Lambda, saving S3 file to /tmp directory
I want to copy a set of files over from S3, and put them in the /tmp directory while my lambda function is running, to use and manipulate the contents. The following code excerpt works fine on my PC (which is running windows)

```<code>s3 = boto3.resource('s3')
BUCKET_NAME = 'car_sentiment'
keys = ['automated.csv', 'connected_automated.csv', 'connected.csv',
        'summary.csv']
for KEY in keys:
    try:
        local_file_name = 'tmp/'+KEY
        s3.Bucket(BUCKET_NAME).download_file(KEY, local_file_name)
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            continue
        else:
            raise
</code>```

However, when I try to run on AWS lambda, I get:

```<code>{
  "errorMessage": "[Errno 2] No such file or directory: 'tmp/automated.csv.4Bcd0bB9'",
  "errorType": "FileNotFoundError",
  "stackTrace": [
    [
      "/var/task/SentimentForAWS.py",
      28,
      "my_handler",
      "s3.Bucket(BUCKET_NAME).download_file(KEY, local_file_name)"
    ],
    [
      "/var/runtime/boto3/s3/inject.py",
      246,
      "bucket_download_file",
      "ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)"
    ],
    [
      "/var/runtime/boto3/s3/inject.py",
      172,
      "download_file",
      "extra_args=ExtraArgs, callback=Callback)"
    ],
    [
      "/var/runtime/boto3/s3/transfer.py",
      307,
      "download_file",
      "future.result()"
    ],
    [
      "/var/runtime/s3transfer/futures.py",
      73,
      "result",
      "return self._coordinator.result()"
    ],
    [
      "/var/runtime/s3transfer/futures.py",
      233,
      "result",
      "raise self._exception"
    ],
    [
      "/var/runtime/s3transfer/tasks.py",
      126,
      "__call__",
      "return self._execute_main(kwargs)"
    ],
    [
      "/var/runtime/s3transfer/tasks.py",
      150,
      "_execute_main",
      "return_value = self._main(**kwargs)"
    ],
    [
      "/var/runtime/s3transfer/download.py",
      582,
      "_main",
      "fileobj.seek(offset)"
    ],
    [
      "/var/runtime/s3transfer/utils.py",
      335,
      "seek",
      "self._open_if_needed()"
    ],
    [
      "/var/runtime/s3transfer/utils.py",
      318,
      "_open_if_needed",
      "self._fileobj = self._open_function(self._filename, self._mode)"
    ],
    [
      "/var/runtime/s3transfer/utils.py",
      244,
      "open",
      "return open(filename, mode)"
    ]
  ]
}
</code>```

Why does it think the file name is tmp/automated.csv.4Bcd0bB9 rather than just tmp/automated.csv and how do I fix it? Been pulling my hair out on this one, trying multiple approaches, some of which generate a similar error when running locally on my PC. Thanks!

答: Well the reason why lambda gives the above error is because it doesn't allow to write in the heirarchial structure with in the /tmp/ directory. You can write the files directly to /tmp/example.txt dir but not to say /tmp/dir1/example.txt</p>

Body:
I want to copy a set of files over from S3, and put them in the /tmp directory while my lambda function is running, to use and manipulate the contents. The following code excerpt works fine on my PC (which is running windows)

s3 = boto3.resource('s3')
BUCKET_NAME = 'car_sentiment'
keys = ['automated.csv', 'connected_automated.csv', 'connected.csv',
        'summary.csv']
for KEY in keys:
    try:
        local_file_name = 'tmp/'+KEY
        s3.Bucket(BUCKET_NAME).download_file(KEY, local_file_name)
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            continue
        else:
            raise

However, when I try to run on AWS lambda, I get:

{
  "errorMessage": "[Errno 2] No such file or directory: 'tmp/automated.csv.4Bcd0bB9'",
  "errorType": "FileNotFoundError",
  "stackTrace": [
    [
      "/var/task/SentimentForAWS.py",
      28,
      "my_handler",
      "s3.Bucket(BUCKET_NAME).download_file(KEY, local_file_name)"
    ],
    [
      "/var/runtime/boto3/s3/inject.py",
      246,
      "bucket_download_file",
      "ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)"
    ],
    [
      "/var/runtime/boto3/s3/inject.py",
      172,
      "download_file",
      "extra_args=ExtraArgs, callback=Callback)"
    ],
    [
      "/var/runtime/boto3/s3/transfer.py",
      307,
      "download_file",
      "future.result()"
    ],
    [
      "/var/runtime/s3transfer/futures.py",
      73,
      "result",
      "return self._coordinator.result()"
    ],
    [
      "/var/runtime/s3transfer/futures.py",
      233,
      "result",
      "raise self._exception"
    ],
    [
      "/var/runtime/s3transfer/tasks.py",
      126,
      "__call__",
      "return self._execute_main(kwargs)"
    ],
    [
      "/var/runtime/s3transfer/tasks.py",
      150,
      "_execute_main",
      "return_value = self._main(**kwargs)"
    ],
    [
      "/var/runtime/s3transfer/download.py",
      582,
      "_main",
      "fileobj.seek(offset)"
    ],
    [
      "/var/runtime/s3transfer/utils.py",
      335,
      "seek",
      "self._open_if_needed()"
    ],
    [
      "/var/runtime/s3transfer/utils.py",
      318,
      "_open_if_needed",
      "self._fileobj = self._open_function(self._filename, self._mode)"
    ],
    [
      "/var/runtime/s3transfer/utils.py",
      244,
      "open",
      "return open(filename, mode)"
    ]
  ]
}

Why does it think the file name is tmp/automated.csv.4Bcd0bB9 rather than just tmp/automated.csv and how do I fix it? Been pulling my hair out on this one, trying multiple approaches, some of which generate a similar error when running locally on my PC. Thanks!


问:
AWS DAX ConnectionException when accessing with VPC peering from lambda
I have an AWS lambda function in a VPC on AWS account A that has a peering connection with a VPC on AWS account B containing a DAX cluster. I'm getting the following error when trying to connect to the DAX cluster from my lambda.

```<code>2021-12-17T17:29:34.096Z    279f4ed8-a6ea-4f50-b1d7-31c307cc3f30    ERROR   Failed to pull from my-cluster.v3fh7d.dax-clusters.us-east-1.amazonaws.com (11.0.225.143): TimeoutError: ConnectionException: Connection timeout after 10000ms
    at SocketTubePool.alloc (/var/task/node_modules/amazon-dax-client/src/Tube.js:244:64)
    at /var/task/node_modules/amazon-dax-client/generated-src/Operations.js:215:30 {
  time: 1639762164096,
  code: 'ConnectionException',
  retryable: true,
  requestId: null,
  statusCode: -1,
  _tubeInvalid: false,
  waitForRecoveryBeforeRetrying: false
}
</code>```

The relevant part of my lambda code is here.

```<code>let assumedRole;

const sts = new AWS.STS({ region: "us-east-1" });
const params = {
  RoleArn:
    "arn:aws:iam::<account-b>:role/role-to-access-dax",
  RoleSessionName: "testAssumeRoleSession" + Date.now().toString(),
  DurationSeconds: 3600,
};

try {
  assumedRole = await sts.assumeRole(params).promise();
} catch (error) {
  console.log("Failed getting sts assume role: " + error);
}

const dax = new AmazonDaxClient({
  endpoint:
    "dax://my-cluster.v3fh7d.dax-clusters.us-east-1.amazonaws.com",
  region: "us-east-1",
  accessKeyId: assumedRole.Credentials.AccessKeyId,
  secretAccessKey: assumedRole.Credentials.SecretAccessKey,
  sessionToken: assumedRole.Credentials.SessionToken,
  httpOptions: { timeout: 150000 },
  maxRetries: 1,
});

const dynamodb = new AWS.DynamoDB.DocumentClient({ service: dax });

try {
  const params = {
    Key: {
      userid: requestData.userid,
    },
    TableName: "my-users-table",
  };
  const result = await dynamodb.get(params).promise();

  if (result.Item == undefined || result.Item == null) {
    return createResponse(401, "Unauthorized");
  }
  return createResponse(200, JSON.stringify(result.Item));
} catch (error) {
  return createResponse(500, error);
}
</code>```

The role arn:aws:iam::<account-b>:role/role-to-access-dax has the following permissions

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "dax:GetItem",
                "dax:BatchGetItem",
                "dax:Query",
                "dax:Scan",
                "dax:PutItem",
                "dax:UpdateItem",
                "dax:DeleteItem",
                "dax:BatchWriteItem",
                "dax:ConditionCheckItem"
            ],
            "Resource": "arn:aws:dax:us-east-1:<account-b>:cache/my-cluster"
        }
    ]
}
</code>```

and the following trust relationship.

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::<account-a>:root"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
</code>```

The DAX cluster has the policy AmazonDynamoDBFullAccess.

The peering connection shows up as Active in the AWS console.

The DAX cluster's security group has an inbound rule to allow TCP traffic on port 8111 from source <account-a> / <sg-of-lambda>.

The CIDR of the Account A VPC is 10.0.0.0/24 and the CIDR of the Account B VPC is 11.0.0.0/16.

The Account A VPC's main route table has a route directing traffic with destination 11.0.0.0/16 to the peering connection. Likewise, the Account B VPC's main route table has a route directing traffic with destination 10.0.0.0/24 to the peering connection.

As an aside, the following lines in the lambda code appear to be ignored as there are quite a few retries on the DAX request and the timeout is not changing from 10000 ms.

```<code>  httpOptions: { timeout: 150000 },
  maxRetries: 1,
</code>```

答: I was able to solve this issue with the help of an AWS rep. It turns out I needed a public and private subnet in my VPC containing the lambda. The lambda itself had to be in a private subnet with the public subnet containing a NAT gateway and an internet gateway. Instead of a single route table in the VPC, I needed separate route tables for the two subnets. The private one contains the peering connection route and VPC CIDR route like I mentioned in my question but also contains a route with destination 0.0.0.0/0 with the NAT gateway as the target. The public subnet route table contains the VPC CIDR route as well as a route with destination 0.0.0.0/0 with the internet gateway as the target.

Body:
I have an AWS lambda function in a VPC on AWS account A that has a peering connection with a VPC on AWS account B containing a DAX cluster. I'm getting the following error when trying to connect to the DAX cluster from my lambda.

2021-12-17T17:29:34.096Z    279f4ed8-a6ea-4f50-b1d7-31c307cc3f30    ERROR   Failed to pull from my-cluster.v3fh7d.dax-clusters.us-east-1.amazonaws.com (11.0.225.143): TimeoutError: ConnectionException: Connection timeout after 10000ms
    at SocketTubePool.alloc (/var/task/node_modules/amazon-dax-client/src/Tube.js:244:64)
    at /var/task/node_modules/amazon-dax-client/generated-src/Operations.js:215:30 {
  time: 1639762164096,
  code: 'ConnectionException',
  retryable: true,
  requestId: null,
  statusCode: -1,
  _tubeInvalid: false,
  waitForRecoveryBeforeRetrying: false
}

The relevant part of my lambda code is here.

let assumedRole;

const sts = new AWS.STS({ region: "us-east-1" });
const params = {
  RoleArn:
    "arn:aws:iam::<account-b>:role/role-to-access-dax",
  RoleSessionName: "testAssumeRoleSession" + Date.now().toString(),
  DurationSeconds: 3600,
};

try {
  assumedRole = await sts.assumeRole(params).promise();
} catch (error) {
  console.log("Failed getting sts assume role: " + error);
}

const dax = new AmazonDaxClient({
  endpoint:
    "dax://my-cluster.v3fh7d.dax-clusters.us-east-1.amazonaws.com",
  region: "us-east-1",
  accessKeyId: assumedRole.Credentials.AccessKeyId,
  secretAccessKey: assumedRole.Credentials.SecretAccessKey,
  sessionToken: assumedRole.Credentials.SessionToken,
  httpOptions: { timeout: 150000 },
  maxRetries: 1,
});

const dynamodb = new AWS.DynamoDB.DocumentClient({ service: dax });

try {
  const params = {
    Key: {
      userid: requestData.userid,
    },
    TableName: "my-users-table",
  };
  const result = await dynamodb.get(params).promise();

  if (result.Item == undefined || result.Item == null) {
    return createResponse(401, "Unauthorized");
  }
  return createResponse(200, JSON.stringify(result.Item));
} catch (error) {
  return createResponse(500, error);
}

The role arn:aws:iam::<account-b>:role/role-to-access-dax has the following permissions

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "dax:GetItem",
                "dax:BatchGetItem",
                "dax:Query",
                "dax:Scan",
                "dax:PutItem",
                "dax:UpdateItem",
                "dax:DeleteItem",
                "dax:BatchWriteItem",
                "dax:ConditionCheckItem"
            ],
            "Resource": "arn:aws:dax:us-east-1:<account-b>:cache/my-cluster"
        }
    ]
}

and the following trust relationship.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::<account-a>:root"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

The DAX cluster has the policy AmazonDynamoDBFullAccess.

The peering connection shows up as Active in the AWS console.

The DAX cluster's security group has an inbound rule to allow TCP traffic on port 8111 from source <account-a> / <sg-of-lambda>.

The CIDR of the Account A VPC is 10.0.0.0/24 and the CIDR of the Account B VPC is 11.0.0.0/16.

The Account A VPC's main route table has a route directing traffic with destination 11.0.0.0/16 to the peering connection. Likewise, the Account B VPC's main route table has a route directing traffic with destination 10.0.0.0/24 to the peering connection.

As an aside, the following lines in the lambda code appear to be ignored as there are quite a few retries on the DAX request and the timeout is not changing from 10000 ms.

  httpOptions: { timeout: 150000 },
  maxRetries: 1,


问:
How to return Jtoken in JsonResult
Tell me please. How can I get this data back in the JsonResult? I can't figure it out for 2 hours.
My task:
I need to take this data, return it to JsonResult and process it in ajax. I will be glad to any hint</p>
```<code>public async Task<JsonResult> PostsPartial()
{
    var client = new RestClient($"https://jsonplaceholder.typicode.com/posts");
    var request = new RestRequest(Method.GET);
    IRestResponse response = await client.ExecuteAsync(request);
    var postsData = JsonConvert.DeserializeObject<JToken>(response.Content);

    return Json(postsData);
}
</code>```

答:
try to use</p>
```<code>   await New JsonResult(JObject.FromObject(postsData))
</code>```

Title: How to return Jtoken in JsonResult

Body:
Tell me please. How can I get this data back in the JsonResult? I can't figure it out for 2 hours.
My task:
I need to take this data, return it to JsonResult and process it in ajax. I will be glad to any hint

public async Task<JsonResult> PostsPartial()
{
    var client = new RestClient($"https://jsonplaceholder.typicode.com/posts");
    var request = new RestRequest(Method.GET);
    IRestResponse response = await client.ExecuteAsync(request);
    var postsData = JsonConvert.DeserializeObject<JToken>(response.Content);

    return Json(postsData);
}

Body:
try to use

   await New JsonResult(JObject.FromObject(postsData))


问:
How to select a graph vertex with igraph in R?
In Python you can simply use graph.select() (atleast when reading the documentation: https://igraph.org/python/doc/api/igraph.VertexSeq.html) to select a vertex based on a value. I have a huge graph connecting movies that share an actor. However I would simply like to select one vertex from that graph and then plot it with its direct neighbors. I'm running into issues when I want to select just that single vertex.

I had hoped something like worked

```<code>graph.movies.select('Snatch (2000)')
</code>```

But no luck.

Another approach I took was grabbing the single Snatch vertex by filtering all others out and then adding the edges.

```<code>snatch.graph <- induced.subgraph(g.movies, vids=V(g.movies)$name == 'Snatch (2000)')
snatch.edges <- edges(g.movies, "Snatch (2000)")
add_edges(snatch.graph, snatch.edges$edges)
</code>```

However this returns an empty graph with only the snatch vertex.

My goal is to grab the Snatch vertex and plot this vertex, its DIRECT neighbors and the edges amomng them. Any suggestions? Thanks alot :D Been stuck o nthis for a quite a while -.-

答:
I think the method using ego (by @user20650) is comprehensive and efficient.

Here is another option if you would like to find the sub-graph built on direct neighbors, which applies distances + induced_subgraph

```<code>> induced_subgraph(g, which(distances(g, "1") <= 1))
IGRAPH 99f872b UN-- 4 3 -- Erdos renyi (gnp) graph
+ attr: name (g/c), type (g/c), loops (g/l), p (g/n), name (v/n)
+ edges from 99f872b (vertex names):
[1] 1--4 1--6 1--9
</code>```

Body:
In Python you can simply use graph.select() (atleast when reading the documentation: https://igraph.org/python/doc/api/igraph.VertexSeq.html) to select a vertex based on a value. I have a huge graph connecting movies that share an actor. However I would simply like to select one vertex from that graph and then plot it with its direct neighbors. I'm running into issues when I want to select just that single vertex.

I had hoped something like worked

graph.movies.select('Snatch (2000)')

But no luck.

Another approach I took was grabbing the single Snatch vertex by filtering all others out and then adding the edges.

snatch.graph <- induced.subgraph(g.movies, vids=V(g.movies)$name == 'Snatch (2000)')
snatch.edges <- edges(g.movies, "Snatch (2000)")
add_edges(snatch.graph, snatch.edges$edges)

However this returns an empty graph with only the snatch vertex.

My goal is to grab the Snatch vertex and plot this vertex, its DIRECT neighbors and the edges amomng them. Any suggestions? Thanks alot :D Been stuck o nthis for a quite a while -.-

Body:
I think the method using ego (by @user20650) is comprehensive and efficient.

Here is another option if you would like to find the sub-graph built on direct neighbors, which applies distances + induced_subgraph

> induced_subgraph(g, which(distances(g, "1") <= 1))
IGRAPH 99f872b UN-- 4 3 -- Erdos renyi (gnp) graph
+ attr: name (g/c), type (g/c), loops (g/l), p (g/n), name (v/n)
+ edges from 99f872b (vertex names):
[1] 1--4 1--6 1--9


问:
Equivalent of scss @import for styled-components?
I'm making an embeddable widget with react and styled-components, and want to do a big CSS reset in my main app container. I'm going to use the styles from cleanslate to do that, however I don't want to just drop it into my main styled component because it's 400 lines long. Ideally, those styles would live in a separate js file, and then in StyledApp I'd do something similar to scss' @import cleanslate.

The suggestions I've found include make a separate call to the CDN version of the css file, but I don't want to do that for two reasons: 1. don't want the extra performance hit, 2. I want to make edits.

Is there a way I can import all of those styles into my main StyledApp and have them applied to that app component?

答:
You can declare css styles with the css helper from styled-components and then invoke it where you need it:

```<code>export const cleanSlateRules = css`
// styles
`;

export const StyledWhatever = styled.div`
  ${cleanSlateRules}
`;
</code>```

EDIT: Turns out this currently doesn't work in prod. I think because of the same issue as the @import problem.

EDIT 2: I got this to work in production using the babel plugin for styled components. The custom css was successfully applied after that. See my answer here: styled-components only rendering certain styles after successful build with parcel

Body:
You can declare css styles with the css helper from styled-components and then invoke it where you need it:

export const cleanSlateRules = css`
// styles
`;

export const StyledWhatever = styled.div`
  ${cleanSlateRules}
`;

EDIT: Turns out this currently doesn't work in prod. I think because of the same issue as the @import problem.

EDIT 2: I got this to work in production using the babel plugin for styled components. The custom css was successfully applied after that. See my answer here: styled-components only rendering certain styles after successful build with parcel


问:
Why not sprite larger images that are page content?
The typical rule of thumb when it comes to using CSS sprites for images is that you should only do it for smaller images (like icons) and that actual image content should always be represented through  elements. My question is: why? Aren't the advantages of spriting worthwhile for content images as well?

One reason I have read is to enable the use of alt text, to be more syntactically correct and accessible to screen-readers. However, when that is a concern, couldn't you just as easily use a single tiny transparent image with all the syntactical sugar atop a sprite that presents the real visual content?

答:
Sprites should be used for common icons across the whole website and not for page specific content. When you use sprites for big images you get a lot of white space that is wasted.

According to http://blog.vlad1.com/2009/06/22/to-sprite-or-not-to-sprite/ this is also a problem:

Another (but much less important) downside is that if a sprite-using
  page is zoomed using the full-page zoom feature that’s present in many
  browsers, the browser may need to do extra work to get the correct
  behaviour at the edges of these images — basically, to avoid adjacent
  images in the sprite from “leaking in.”  This isn’t a problem for
  small images, but can be a performance hit for bigger ones.


问:
How to combine the elements of two lists using zip function in python?
I have two different lists and I would like to know how I can get each element of one list print with each element of another list. I know I could use two for loops (each for one of the lists), however I want to use the zip() function because there's more that I will be doing in this for loop for which I will require parallel iteration.

I therefore attempted the following but the output is as shown below.

```<code>lasts = ['x', 'y', 'z']
firsts = ['a', 'b', 'c']

for last, first in zip(lasts, firsts):
    print (last, first, "\n")
</code>```

Output:

```<code>x a
y b
z c
</code>```

Expected Output:

```<code>x a
x b
x c
y a
y b
y c
z a
z b
z c
</code>```

答:
Honestly I think you wont be able to do it with zip because you are searching for another behaviour.
To use syntactic sugar and make it work with zip will just void your debugging experience.

But if you would drag me by the knee:

```<code>zip([val for val in l1 for _ in range(len(l2))],
    [val for _ in l1 for val in l2])

</code>```

where you first duplicate the first list to get xxxyyyzzz and duplicate the second list with abcabcabc

or

```<code>for last,first in [(l,f) for l in lasts for f in firsts]:
     print(last, first, "\n")
</code>```

Body:
I have two different lists and I would like to know how I can get each element of one list print with each element of another list. I know I could use two for loops (each for one of the lists), however I want to use the zip() function because there's more that I will be doing in this for loop for which I will require parallel iteration.

I therefore attempted the following but the output is as shown below.

lasts = ['x', 'y', 'z']
firsts = ['a', 'b', 'c']

for last, first in zip(lasts, firsts):
    print (last, first, "\n")

Output:

x a
y b
z c

Expected Output:

x a
x b
x c
y a
y b
y c
z a
z b
z c

Body:
Honestly I think you wont be able to do it with zip because you are searching for another behaviour.
To use syntactic sugar and make it work with zip will just void your debugging experience.

But if you would drag me by the knee:

zip([val for val in l1 for _ in range(len(l2))],
    [val for _ in l1 for val in l2])

where you first duplicate the first list to get xxxyyyzzz and duplicate the second list with abcabcabc

or

for last,first in [(l,f) for l in lasts for f in firsts]:
     print(last, first, "\n")


问:
how to add click listener to row of a-table in antd vue
This is the code snippet for the table which I am trying to render, have imported a-table from antd. Currently, we can add an extra td to achieve click functionality to route to details page from this listing page

```<code><a-table
    :columns="companiesColumns"
    :dataSource="getDisplayData"
    class="companies-table"
    :pagination="false"
    rowKey="id"
    >
    <span slot="nse_symbol" slot-scope="nse_symbol" class="nse-symbol">
        <span>{{ nse_symbol || '-' }}</span>
    </span>
</a-table>
</code>```

答:
Vue 3

AntDesign v3.0.0-beta.9

This is the only way that worked for me:

```<code>#template

<template>
  <a-table
    :columns='columns'
    :data-source='data'
    @change='onChange'
    :customRow="customRow"
    :row-selection='rowSelection'
    :pagination="pagination"
  />
</template>

#methods

methods: {
 customRow(record: TableDataType) {
      return {
          onClick: (event: PointerEvent) => console.log('record', record, 'event', event)
      }
    }
}
</code>```

Body:
This is the code snippet for the table which I am trying to render, have imported a-table from antd. Currently, we can add an extra td to achieve click functionality to route to details page from this listing page

        {{ nse_symbol || '-' }}

Body:
Vue 3

AntDesign v3.0.0-beta.9

This is the only way that worked for me:

#template

<template>
  <a-table
    :columns='columns'
    :data-source='data'
    @change='onChange'
    :customRow="customRow"
    :row-selection='rowSelection'
    :pagination="pagination"
  />
</template>

#methods

methods: {
 customRow(record: TableDataType) {
      return {
          onClick: (event: PointerEvent) => console.log('record', record, 'event', event)
      }
    }
}


问:
Find the length of the longest list that a contains a certain character in another list
I have a list [[1],[2,3],[a, b, c], [1, a, b, 3]]
I need to find the longest list that contains the char a.
I have the code to find the lenght of the longest list, but can't implement the search for the a char:

```<code>def find_max_list(list):
    list_len = [len(i) for i in list]
    print(max(list_len))

find_max_list(your_list)
</code>```

答:
Try this:</p>
```<code>import collections

def find_max_list(a_list):
    most_common = []
    for i in a_list:
        a_counter = collections.Counter(i)
        most_common.append(a_counter.most_common())
    maxfinal = [a[:1] for a in most_common]

    return maxfinal
</code>```

Body:
I have a list [[1],[2,3],[a, b, c], [1, a, b, 3]]
I need to find the longest list that contains the char a.
I have the code to find the lenght of the longest list, but can't implement the search for the a char:

def find_max_list(list):
    list_len = [len(i) for i in list]
    print(max(list_len))

find_max_list(your_list)

Body:
Try this:

import collections

def find_max_list(a_list):
    most_common = []
    for i in a_list:
        a_counter = collections.Counter(i)
        most_common.append(a_counter.most_common())
    maxfinal = [a[:1] for a in most_common]

    return maxfinal


问:
Can variational autoencoders be used on non-image data?
I have a question about variational autoencoders (VAE),

I need to generate new data from my dataset which contains just numerical data, so i want to use VAE for that task, but all the available tutorials and articles use images as input data for the variatioanl autoencoder.

My question is: can i use VAE for generating new data from my datasets eventhough my data is not images ??

Thank you.

答: Short answer is yes. You should read up a bit on the basics of neural nets if this wasn't obvious already - an image is just a Channel X Height X Width dimensional vector. You might use different kinds of layers in your network to suit the kind of data that you have to give a better inductive bias, but otherwise nothing changes. Follow those tutorials!</p>


问:
How to bypass warning Unexpected any. Specify a different type @typescript-eslint/no-explicit-any
We have a strict zero lint issues policy. This means all errors and warnings need to be fixed.

Facing this lint error in our React typescript project:

warning  Unexpected any. Specify a different type  @typescript-eslint/no-explicit-any

Searched on Google and on the lint website. I didn't find a solution as such!

Tried this: // eslint:@typescript-eslint/no-explicit-any: "off" which is not working

Does anyone know how to bypass this eslint rule in a React typescript project?

答:
As described by typescript-eslint:

If you want a type meaning "any object", you probably want Record<string, unknown> instead.

If you want a type meaning "any value", you probably want unknown instead

In fact you can often replace any with a better option. For that you can use Record type as mentioned by @RollingInTheDeep or you can use index signature like:

```<code>{[key1: string]: number | unknown} // object.x = number | unknown
{[key2: string]: {[key3:string]: number | undefined}} | boolean // object.x can be a boolean or another object that contains key strings with numeric or undefined values
</code>```

Body:
As described by typescript-eslint:

If you want a type meaning "any object", you probably want Record<string, unknown> instead.

If you want a type meaning "any value", you probably want unknown instead

In fact you can often replace any with a better option. For that you can use Record type as mentioned by @RollingInTheDeep or you can use index signature like:

{[key1: string]: number | unknown} // object.x = number | unknown
{[key2: string]: {[key3:string]: number | undefined}} | boolean // object.x can be a boolean or another object that contains key strings with numeric or undefined values


问:
PlatformIO Unidentified reference error to defined attributes
I am creating a project using PlatformIO and a Nodemcuv2 micro-controller.

I have written a class for serial communication SerialCommunicationHandler. This class ICommunicationHandler implements a Interface. See the code below.

ICommunicationHandler.h

class ICommunicationHandler {
public:
    virtual void sendTemperature(float temp) = 0;
    virtual void receiveData() = 0;
    virtual void update() = 0;

protected:
    virtual void parseData() = 0;
    virtual void showParsedData() = 0;
};
```
<h4>SerialCommunicationHandler</h4>
<p>headerfile</p>
<pre class="lang-cpp prettyprint-override"><code>#include "ICommunicationHandler.h"
class SerialCommunicationHandler : public ICommunicationHandler {
private:
//atributes needed for storing and modifying incoming data.

    static char incomingData[6]; //char array to temporarily store incoming data.
    static char receivedData[6]; //char array to copy incoming data to.
    static unsigned int messagePosition; //index of the incomingData array.

    bool receiving;
    bool newData;
    void parseData() override;
    void receiveData() override;
    void showParsedData() override;

public:
    explicit SerialCommunicationHandler();
    void sendTemperature(float temp) override;
    void update() override;
};
</code>```

.cpp

#include <Arduino.h>
#include "SerialCommunicationHandler.h"

SerialCommunicationHandler::SerialCommunicationHandler() {
    messagePosition = 0;
    receiving = false;
    newData = false;
}

void SerialCommunicationHandler::receiveData() {
    //check if there are bytes in the serial buffer.
    while (Serial.available() > 0){
        char inByte = Serial.read();
        //check if the byte is a starting or ending character;
        switch (inByte) {
            case '<':
                //start receiving characters
                receiving = true;
                break;
            case '>':
                //stop receiving and parse the incoming data.
                receiving = false;
                newData = true;
                strcpy(receivedData, incomingData); //copy incoming data into receivedData for further parsing.
                memset(incomingData, 0, sizeof(incomingData)); //resetting incomingData.
                messagePosition = 0;
                break;
            default:
                if (receiving) {
                    incomingData[messagePosition] = inByte; //add incoming byte to array.
                    messagePosition++;
                }
                break;
        }
    }
}

void SerialCommunicationHandler::parseData() {
    if (newData) {
        showParsedData();
    }
    newData = false;
}

void SerialCommunicationHandler::showParsedData() {
    Serial.println(receivedData);
}

void SerialCommunicationHandler::sendTemperature(float temp) {
    Serial.println(temp);
}

void SerialCommunicationHandler::update() {
    receiveData();
    parseData();
}
```
<p>When building I get multiple undefined refernce errors:</p>
```*/ld.exe: .pio\build\nodemcuv2\src\SerialCommunicationHandler.cpp.o:(.text._ZN26SerialCommunicationHandler14s
howParsedDataEv+0x0): undefined reference to `_ZN26SerialCommunicationHandler12receivedDataE`
*/ld.exe: .pio\build\nodemcuv2\src\SerialCommunicationHandler.cpp.o:(.text._ZN26SerialCommunicationHandlerC2E
v+0x4): undefined reference to `_ZN26SerialCommunicationHandler15messagePositionE'
*/ld.exe: .pio\build\nodemcuv2\src\SerialCommunicationHandler.cpp.o:(.text._ZN26SerialCommunicationHandler11r
eceiveDataEv+0x0): undefined reference to `_ZN26SerialCommunicationHandler12incomingDataE'

collect2.exe: error: ld returned 1 exit status
*** [.pio\build\nodemcuv2\firmware.elf] Error 1
```

I have checked my code multiple times for syntax errors or misspelling but have found nothing. My IDE doesnt bring up any errors as well. Any information on what might be causing the undefined reference error is welcome.

答:
headerfile

```<code>#include "ICommunicationHandler.h"

class SerialCommunicationHandler : public ICommunicationHandler {
private:
//atributes needed for storing and modifying incoming data.
static char incomingData[6]; //char array to temporarily store incoming data.
static char receivedData[6]; //char array to copy incoming data to.
static unsigned int messagePosition; //index of the incomingData array.
   // ... etc
</code>```

These are only declarations of the static member variables. You also have to define them in the cpp file, just like you do with the member functions:

.cpp file:

```<code>void SerialCommunicationHandler::showParsedData() {
    Serial.println(receivedData);
}

// static data members
char SerialCommunicationHandler::incomingData[6] = {};
char SerialCommunicationHandler::receivedData[6] = {};
unsigned int SerialCommunicationHandler::messagePosition = 0;
</code>```

Body:
I am creating a project using PlatformIO and a Nodemcuv2 micro-controller.

I have written a class for serial communication SerialCommunicationHandler. This class ICommunicationHandler implements a Interface. See the code below.

ICommunicationHandler.h

class ICommunicationHandler {
public:
    virtual void sendTemperature(float temp) = 0;
    virtual void receiveData() = 0;
    virtual void update() = 0;

protected:
    virtual void parseData() = 0;
    virtual void showParsedData() = 0;
};

SerialCommunicationHandler

headerfile

#include "ICommunicationHandler.h"
class SerialCommunicationHandler : public ICommunicationHandler {
private:
//atributes needed for storing and modifying incoming data.

    static char incomingData[6]; //char array to temporarily store incoming data.
    static char receivedData[6]; //char array to copy incoming data to.
    static unsigned int messagePosition; //index of the incomingData array.

    bool receiving;
    bool newData;
    void parseData() override;
    void receiveData() override;
    void showParsedData() override;

public:
    explicit SerialCommunicationHandler();
    void sendTemperature(float temp) override;
    void update() override;
};

.cpp

#include <Arduino.h>
#include "SerialCommunicationHandler.h"

SerialCommunicationHandler::SerialCommunicationHandler() {
    messagePosition = 0;
    receiving = false;
    newData = false;
}

void SerialCommunicationHandler::receiveData() {
    //check if there are bytes in the serial buffer.
    while (Serial.available() > 0){
        char inByte = Serial.read();
        //check if the byte is a starting or ending character;
        switch (inByte) {
            case '<':
                //start receiving characters
                receiving = true;
                break;
            case '>':
                //stop receiving and parse the incoming data.
                receiving = false;
                newData = true;
                strcpy(receivedData, incomingData); //copy incoming data into receivedData for further parsing.
                memset(incomingData, 0, sizeof(incomingData)); //resetting incomingData.
                messagePosition = 0;
                break;
            default:
                if (receiving) {
                    incomingData[messagePosition] = inByte; //add incoming byte to array.
                    messagePosition++;
                }
                break;
        }
    }
}

void SerialCommunicationHandler::parseData() {
    if (newData) {
        showParsedData();
    }
    newData = false;
}

void SerialCommunicationHandler::showParsedData() {
    Serial.println(receivedData);
}

void SerialCommunicationHandler::sendTemperature(float temp) {
    Serial.println(temp);
}

void SerialCommunicationHandler::update() {
    receiveData();
    parseData();
}

When building I get multiple undefined refernce errors:

*/ld.exe: .pio\build\nodemcuv2\src\SerialCommunicationHandler.cpp.o:(.text._ZN26SerialCommunicationHandler14s
howParsedDataEv+0x0): undefined reference to `_ZN26SerialCommunicationHandler12receivedDataE`
*/ld.exe: .pio\build\nodemcuv2\src\SerialCommunicationHandler.cpp.o:(.text._ZN26SerialCommunicationHandlerC2E
v+0x4): undefined reference to `_ZN26SerialCommunicationHandler15messagePositionE'
*/ld.exe: .pio\build\nodemcuv2\src\SerialCommunicationHandler.cpp.o:(.text._ZN26SerialCommunicationHandler11r
eceiveDataEv+0x0): undefined reference to `_ZN26SerialCommunicationHandler12incomingDataE'

collect2.exe: error: ld returned 1 exit status
*** [.pio\build\nodemcuv2\firmware.elf] Error 1

I have checked my code multiple times for syntax errors or misspelling but have found nothing. My IDE doesnt bring up any errors as well. Any information on what might be causing the undefined reference error is welcome.

Body:
headerfile

#include "ICommunicationHandler.h"

class SerialCommunicationHandler : public ICommunicationHandler {
private:
//atributes needed for storing and modifying incoming data.
static char incomingData[6]; //char array to temporarily store incoming data.
static char receivedData[6]; //char array to copy incoming data to.
static unsigned int messagePosition; //index of the incomingData array.
   // ... etc

These are only declarations of the static member variables. You also have to define them in the cpp file, just like you do with the member functions:

.cpp file:

void SerialCommunicationHandler::showParsedData() {
    Serial.println(receivedData);
}

// static data members
char SerialCommunicationHandler::incomingData[6] = {};
char SerialCommunicationHandler::receivedData[6] = {};
unsigned int SerialCommunicationHandler::messagePosition = 0;


问:
Unknown JavaScript Error - Only run first function
I have created two functions but the browser is running only one of them and after the rest of the functions not running.

You can see the below code. this getElementById("loginbtn") is running properly because it is first once but the same function put below this getElementById("actionmenuaction-6") function getElementById("loginbtn") will not work and getElementById("actionmenuaction-6") will work

```<code>document.getElementById("loginbtn").onclick = function(){
    location.href = localStorage.getItem("lastPage");
    alert("Login");
}
document.getElementById("actionmenuaction-6").onclick = function(){
    localStorage.setItem("lastPage", location.href);
}

if(document.getElementById("page-mod-page-view") || document.getElementById("page-mod-quiz-
view") || document.getElementById("page-mod-quiz-attempt")){
    if(document.querySelector('[role="main"] form#responseform')){
        document.querySelector('[role="main"] form#responseform').scrollIntoView(true)
    } else {
        document.querySelector('[role="main"]').scrollIntoView(true);
    }
}

//QUIZ PAGE
if(document.querySelector('#page-mod-quiz-view')) {
    //change button color start quiz or attemp to quiz to primary
    if(document.querySelector('.quizattempt .quizstartbuttondiv button')){
        document.querySelector('.quizattempt .quizstartbuttondiv button').className = "btn btn-secondary btn-primary"
    }
}

if(document.querySelector('#page-mod-quiz-attempt')){
    if(document.querySelector('#page-mod-quiz-attempt div[role=main] .im-controls input') && document.querySelector('#page-mod-quiz-attempt div[role=main] .im-controlsinput').className.length > 0){
        document.querySelector('#page-mod-quiz-attempt div[role=main] .im-controls input').className = "submit btn btn-primary";
    }

    if(document.querySelector('#page-mod-quiz-attempt div[role=main] .im-controls input')) {
        document.querySelector('#page-mod-quiz-attempt div[role=main] .submitbtns .mod_quiz-next-nav').className = 'mod_quiz-next-nav btn btn-secondary-imp'
    } else if(document.querySelector('#page-mod-quiz-attempt div[role=main] .submitbtns .mod_quiz-next-nav') && document.querySelector('#page-mod-quiz-attempt div[role=main] .submitbtns.mod_quiz-next-nav').className.length > 0){
        document.querySelector('#page-mod-quiz-attempt div[role=main] .submitbtns .mod_quiz-next-nav').className = 'mod_quiz-next-nav btn btn-secondary'
    }

    if(document.querySelector('#page-mod-quiz-attempt form .que.correct .outcome')) {
        document.querySelector('#page-mod-quiz-attempt form .correct .outcome').hidden = true;
    }
}
</code>```

These are some console errors.

How can I solve this problem?

答:
Maybe "actionmenuaction-6" is null
It s written in console.</p>

Body:
I have created two functions but the browser is running only one of them and after the rest of the functions not running.

You can see the below code. this getElementById("loginbtn") is running properly because it is first once but the same function put below this getElementById("actionmenuaction-6") function getElementById("loginbtn") will not work and getElementById("actionmenuaction-6") will work

document.getElementById("loginbtn").onclick = function(){
    location.href = localStorage.getItem("lastPage");
    alert("Login");
}
document.getElementById("actionmenuaction-6").onclick = function(){
    localStorage.setItem("lastPage", location.href);
}

if(document.getElementById("page-mod-page-view") || document.getElementById("page-mod-quiz-
view") || document.getElementById("page-mod-quiz-attempt")){
    if(document.querySelector('[role="main"] form#responseform')){
        document.querySelector('[role="main"] form#responseform').scrollIntoView(true)
    } else {
        document.querySelector('[role="main"]').scrollIntoView(true);
    }
}

//QUIZ PAGE
if(document.querySelector('#page-mod-quiz-view')) {
    //change button color start quiz or attemp to quiz to primary
    if(document.querySelector('.quizattempt .quizstartbuttondiv button')){
        document.querySelector('.quizattempt .quizstartbuttondiv button').className = "btn btn-secondary btn-primary"
    }
}

if(document.querySelector('#page-mod-quiz-attempt')){
    if(document.querySelector('#page-mod-quiz-attempt div[role=main] .im-controls input') && document.querySelector('#page-mod-quiz-attempt div[role=main] .im-controlsinput').className.length > 0){
        document.querySelector('#page-mod-quiz-attempt div[role=main] .im-controls input').className = "submit btn btn-primary";
    }

    if(document.querySelector('#page-mod-quiz-attempt div[role=main] .im-controls input')) {
        document.querySelector('#page-mod-quiz-attempt div[role=main] .submitbtns .mod_quiz-next-nav').className = 'mod_quiz-next-nav btn btn-secondary-imp'
    } else if(document.querySelector('#page-mod-quiz-attempt div[role=main] .submitbtns .mod_quiz-next-nav') && document.querySelector('#page-mod-quiz-attempt div[role=main] .submitbtns.mod_quiz-next-nav').className.length > 0){
        document.querySelector('#page-mod-quiz-attempt div[role=main] .submitbtns .mod_quiz-next-nav').className = 'mod_quiz-next-nav btn btn-secondary'
    }

    if(document.querySelector('#page-mod-quiz-attempt form .que.correct .outcome')) {
        document.querySelector('#page-mod-quiz-attempt form .correct .outcome').hidden = true;
    }
}

These are some console errors.

How can I solve this problem?


问:
AutoMapper mapping unmapped properties to Dictionary / ExtensionData
How can I make AutoMapper to map missing unmapped properties to a dictionary inside the destination object? (Like ExtensionData during serialization)

Example:

```<code>class Source
{
    public int A {get;set;}
    public int B {get;set;}
    public int C {get;set;}
}

class Destination
{
    public int A {get;set;}
    public Dictionary<string, object> D {get;set;}
}

Source s = new Source { A = 1, B = 2, C = 3 };
Destination d = ... // Mapping code
</code>```

Now I want the following result:

```<code>d.A ==> 1
d.D ==> {{ "B", 2 }, { "C", 3 }}
</code>```

* EDIT *

In the end I am looking for a solution w/o reflection. Meaning: During setup/configuration/initialization reflection is allowed, but during the mapping itself, I do not want any delays caused by reflection.

* EDIT *

I am looking for a generic solution, just like the serializers.

答:
You could combine Pawel's answer and Reflection.Emit to make it fast.  Be aware that Reflection.Emit is not supported on all platforms (like iOS).

Unlike ExtensionData, this includes all property values from the source.  I don't have an elegant solution to determine which properties were already mapped so I just provided an easy way to exclude certain properties.

```<code>public class PropertyDictionaryResolver<TSource> : IValueResolver<TSource, object, Dictionary<string, object>>
{
    private static readonly PropertyInfo[] Properties = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    private static readonly ConcurrentDictionary<PropertyInfo, Func<TSource, object>> GetterCache = new ConcurrentDictionary<PropertyInfo, Func<TSource, object>>();

    public HashSet<MemberInfo> ExcludedProperties;

    public PropertyDictionaryResolver()
    {
        ExcludedProperties = new HashSet<MemberInfo>();
    }

    public PropertyDictionaryResolver(Expression<Func<TSource, object>> excludeMembers)
    {
        var members = ExtractMembers(excludeMembers);
        ExcludedProperties = new HashSet<MemberInfo>(members);
    }

    public Dictionary<string, object> Resolve(TSource source, object destination, Dictionary<string, object> existing, ResolutionContext context)
    {
        var destMember = new Dictionary<string, object>();

        foreach (var property in Properties)
        {
            if (ExcludedProperties.Contains(property)) continue;

            var exp = GetOrCreateExpression(property);
            var value = exp(source);
            if (value != null)
            {
                destMember.Add(property.Name, value);
            }
        }

        return destMember;
    }

    /// <summary>
    /// Creates and compiles a getter function for a property
    /// </summary>
    /// <param name="propInfo"></param>
    /// <returns></returns>
    public Func<TSource, object> GetOrCreateExpression(PropertyInfo propInfo)
    {
        if (GetterCache.TryGetValue(propInfo, out var existing))
        {
            return existing;
        }

        var parameter = Expression.Parameter(typeof(TSource));
        var property = Expression.Property(parameter, propInfo);
        var conversion = Expression.Convert(property, typeof(object));
        var lambda = Expression.Lambda<Func<TSource, object>>(conversion, parameter);

        existing = lambda.Compile();
        GetterCache.TryAdd(propInfo, existing);
        return existing;
    }

    /// <summary>
    /// Pull the used MemberInfo out of a simple expression.  Supports the following expression types only:
    /// s => s.Prop1
    /// s => new { s.Prop1, s.Prop2 }
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="expression"></param>
    /// <returns></returns>
    public static IEnumerable<MemberInfo> ExtractMembers<T>(Expression<Func<T, object>> expression)
    {
        if (expression == null)
        {
            throw new ArgumentNullException(nameof(expression));
        }

        switch (expression.Body)
        {
            case MemberExpression memberExpression:
                yield return memberExpression.Member;
                yield break;

            // s => s.BarFromBaseType
            case UnaryExpression convertExpression:
                if (convertExpression.Operand is MemberExpression exp)
                {
                    yield return exp.Member;
                }

                yield break;

            // s => new { s.Foo, s.Bar }
            case NewExpression newExpression:
                if (newExpression.Arguments.Count == 0)
                {
                    yield break;
                }

                foreach (var argument in newExpression.Arguments.OfType<MemberExpression>())
                {
                    yield return argument.Member;
                }

                yield break;
        }

        throw new NotImplementedException("Unrecognized lambda expression.");
    }
}
</code>```

And use it like one of these

```<code>[TestClass]
public class Examples
{
    [TestMethod]
    public void AllProperties()
    {
        var mapper = new Mapper(new MapperConfiguration(p =>
        {
            p.CreateMap<Source, Destination>()
                .ForMember(x => x.A, cfg => cfg.MapFrom(x => x.A))
                .ForMember(x => x.D, cfg => cfg.MapFrom<PropertyDictionaryResolver<Source>>());

        }));

        var source = new Source { A = 1, B = 2, C = 3 };
        var d = mapper.Map<Destination>(source);
        // {"A":1,"D":{"A":1,"B":2,"C":3}}
    }

    [TestMethod]
    public void ExcludeSingleProperty()
    {
        var mapper = new Mapper(new MapperConfiguration(p =>
        {
            p.CreateMap<Source, Destination>()
            .ForMember(x => x.A, cfg => cfg.MapFrom(x => x.A))
            .ForMember(x => x.D, cfg => cfg.MapFrom(new PropertyDictionaryResolver<Source>(x => x.A)));

        }));

        var source = new Source { A = 1, B = 2, C = 3 };
        var d = mapper.Map<Destination>(source);
        // {"A":1,"D":{"B":2,"C":3}}
    }

    [TestMethod]
    public void ExcludeMultipleProperties()
    {
        var mapper = new Mapper(new MapperConfiguration(p =>
        {
            p.CreateMap<Source, Destination>()
                .ForMember(x => x.A, cfg => cfg.MapFrom(x => x.A))
                .ForMember(x => x.D, cfg => cfg.MapFrom(new PropertyDictionaryResolver<Source>(x => new
                {
                    x.A,
                    x.B
                })));

        }));

        var source = new Source { A = 1, B = 2, C = 3 };
        var d = mapper.Map<Destination>(source);
        // {"A":1,"D":{"C":3}}
    }
}
</code>```

Body:
How can I make AutoMapper to map missing unmapped properties to a dictionary inside the destination object? (Like ExtensionData during serialization)

Example:

class Source
{
    public int A {get;set;}
    public int B {get;set;}
    public int C {get;set;}
}

class Destination
{
    public int A {get;set;}
    public Dictionary<string, object> D {get;set;}
}

Source s = new Source { A = 1, B = 2, C = 3 };
Destination d = ... // Mapping code

Now I want the following result:

d.A ==> 1
d.D ==> {{ "B", 2 }, { "C", 3 }}

* EDIT *

In the end I am looking for a solution w/o reflection. Meaning: During setup/configuration/initialization reflection is allowed, but during the mapping itself, I do not want any delays caused by reflection.

* EDIT *

I am looking for a generic solution, just like the serializers.

Body:
You could combine Pawel's answer and Reflection.Emit to make it fast.  Be aware that Reflection.Emit is not supported on all platforms (like iOS).

Unlike ExtensionData, this includes all property values from the source.  I don't have an elegant solution to determine which properties were already mapped so I just provided an easy way to exclude certain properties.

public class PropertyDictionaryResolver<TSource> : IValueResolver<TSource, object, Dictionary<string, object>>
{
    private static readonly PropertyInfo[] Properties = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    private static readonly ConcurrentDictionary<PropertyInfo, Func<TSource, object>> GetterCache = new ConcurrentDictionary<PropertyInfo, Func<TSource, object>>();

    public HashSet<MemberInfo> ExcludedProperties;

    public PropertyDictionaryResolver()
    {
        ExcludedProperties = new HashSet<MemberInfo>();
    }

    public PropertyDictionaryResolver(Expression<Func<TSource, object>> excludeMembers)
    {
        var members = ExtractMembers(excludeMembers);
        ExcludedProperties = new HashSet<MemberInfo>(members);
    }

    public Dictionary<string, object> Resolve(TSource source, object destination, Dictionary<string, object> existing, ResolutionContext context)
    {
        var destMember = new Dictionary<string, object>();

        foreach (var property in Properties)
        {
            if (ExcludedProperties.Contains(property)) continue;

            var exp = GetOrCreateExpression(property);
            var value = exp(source);
            if (value != null)
            {
                destMember.Add(property.Name, value);
            }
        }

        return destMember;
    }

    /// <summary>
    /// Creates and compiles a getter function for a property
    /// </summary>
    /// <param name="propInfo"></param>
    /// <returns></returns>
    public Func<TSource, object> GetOrCreateExpression(PropertyInfo propInfo)
    {
        if (GetterCache.TryGetValue(propInfo, out var existing))
        {
            return existing;
        }

        var parameter = Expression.Parameter(typeof(TSource));
        var property = Expression.Property(parameter, propInfo);
        var conversion = Expression.Convert(property, typeof(object));
        var lambda = Expression.Lambda<Func<TSource, object>>(conversion, parameter);

        existing = lambda.Compile();
        GetterCache.TryAdd(propInfo, existing);
        return existing;
    }

    /// <summary>
    /// Pull the used MemberInfo out of a simple expression.  Supports the following expression types only:
    /// s => s.Prop1
    /// s => new { s.Prop1, s.Prop2 }
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="expression"></param>
    /// <returns></returns>
    public static IEnumerable<MemberInfo> ExtractMembers<T>(Expression<Func<T, object>> expression)
    {
        if (expression == null)
        {
            throw new ArgumentNullException(nameof(expression));
        }

        switch (expression.Body)
        {
            case MemberExpression memberExpression:
                yield return memberExpression.Member;
                yield break;

            // s => s.BarFromBaseType
            case UnaryExpression convertExpression:
                if (convertExpression.Operand is MemberExpression exp)
                {
                    yield return exp.Member;
                }

                yield break;

            // s => new { s.Foo, s.Bar }
            case NewExpression newExpression:
                if (newExpression.Arguments.Count == 0)
                {
                    yield break;
                }

                foreach (var argument in newExpression.Arguments.OfType<MemberExpression>())
                {
                    yield return argument.Member;
                }

                yield break;
        }

        throw new NotImplementedException("Unrecognized lambda expression.");
    }
}

And use it like one of these

[TestClass]
public class Examples
{
    [TestMethod]
    public void AllProperties()
    {
        var mapper = new Mapper(new MapperConfiguration(p =>
        {
            p.CreateMap<Source, Destination>()
                .ForMember(x => x.A, cfg => cfg.MapFrom(x => x.A))
                .ForMember(x => x.D, cfg => cfg.MapFrom<PropertyDictionaryResolver<Source>>());

        }));

        var source = new Source { A = 1, B = 2, C = 3 };
        var d = mapper.Map<Destination>(source);
        // {"A":1,"D":{"A":1,"B":2,"C":3}}
    }

    [TestMethod]
    public void ExcludeSingleProperty()
    {
        var mapper = new Mapper(new MapperConfiguration(p =>
        {
            p.CreateMap<Source, Destination>()
            .ForMember(x => x.A, cfg => cfg.MapFrom(x => x.A))
            .ForMember(x => x.D, cfg => cfg.MapFrom(new PropertyDictionaryResolver<Source>(x => x.A)));

        }));

        var source = new Source { A = 1, B = 2, C = 3 };
        var d = mapper.Map<Destination>(source);
        // {"A":1,"D":{"B":2,"C":3}}
    }

    [TestMethod]
    public void ExcludeMultipleProperties()
    {
        var mapper = new Mapper(new MapperConfiguration(p =>
        {
            p.CreateMap<Source, Destination>()
                .ForMember(x => x.A, cfg => cfg.MapFrom(x => x.A))
                .ForMember(x => x.D, cfg => cfg.MapFrom(new PropertyDictionaryResolver<Source>(x => new
                {
                    x.A,
                    x.B
                })));

        }));

        var source = new Source { A = 1, B = 2, C = 3 };
        var d = mapper.Map<Destination>(source);
        // {"A":1,"D":{"C":3}}
    }
}