问:
Sceneform - How to fix leaking SceneView?
I've been using SceneView for loading 3D models for almost a year now but I never understood what caused this leak. I would implement LeakCanary, but just this one leak because I couldn't figure out how to fix the problem.

But now I want to get to the bottom of the issue and try to fix it. I've tested it on two versions of Sceneform -- 1.15.0 and the last version before being deprecated by Google 1.17.1 and the issue happens on both.

The leak happens when you load a model using SceneView in an Activity or Fragment (I've tried both) and you "exit the app" by doing the System home navigation or switching to a different app via the Recent tasks list.

The logs for the leak:

```<code>┬───
│ GC Root: System class
│
├─ android.app.ActivityThread class
│    Leaking: NO (MainActivity↓ is not leaking and a class is never leaking)
│    ↓ static ActivityThread.sCurrentActivityThread
├─ android.app.ActivityThread instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    mInitialApplication instance of android.app.Application
│    ↓ ActivityThread.mActivities
├─ android.util.ArrayMap instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    ↓ ArrayMap.mArray
├─ java.lang.Object[] array
│    Leaking: NO (MainActivity↓ is not leaking)
│    ↓ Object[].[1]
├─ android.app.ActivityThread$ActivityClientRecord instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    activity instance of com.example.a3dmodeltester.MainActivity with
│    mDestroyed = false
│    ↓ ActivityThread$ActivityClientRecord.activity
├─ com.example.a3dmodeltester.MainActivity instance
│    Leaking: NO (SceneView↓ is not leaking and Activity#mDestroyed is false)
│    mApplication instance of android.app.Application
│    mBase instance of android.app.ContextImpl
│    ↓ MainActivity.sceneView
├─ com.google.ar.sceneform.SceneView instance
│    Leaking: NO (View attached)
│    View is part of a window view hierarchy
│    View.mAttachInfo is not null (view attached)
│    View.mID = R.id.sceneview
│    View.mWindowAttachCount = 1
│    mContext instance of com.example.a3dmodeltester.MainActivity with
│    mDestroyed = false
│    ↓ SceneView.renderer
│                ~~~~~~~~
├─ com.google.ar.sceneform.rendering.Renderer instance
│    Leaking: UNKNOWN
│    Retaining 2.9 kB in 38 objects
│    ↓ Renderer.viewAttachmentManager
│               ~~~~~~~~~~~~~~~~~~~~~
├─ com.google.ar.sceneform.rendering.ViewAttachmentManager instance
│    Leaking: UNKNOWN
│    Retaining 2.2 kB in 19 objects
│    ↓ ViewAttachmentManager.frameLayout
│                            ~~~~~~~~~~~
╰→ android.widget.FrameLayout instance
     Leaking: YES (ObjectWatcher was watching this because android.widget.
     FrameLayout received View#onDetachedFromWindow() callback)
     Retaining 1.9 kB in 15 objects
     key = 10550463-895e-443a-898f-11c5131da209
     watchDurationMillis = 5165
     retainedDurationMillis = 157
     View not part of a window view hierarchy
     View.mAttachInfo is null (view detached)
     View.mWindowAttachCount = 1
     mContext instance of com.example.a3dmodeltester.MainActivity with
     mDestroyed = false

METADATA

Build.VERSION.SDK_INT: 27
Build.MANUFACTURER: Google
LeakCanary version: 2.7
App process name: com.example.a3dmodeltester
Stats: LruCache[maxSize=3000,hits=892,misses=24408,hitRate=3%]
RandomAccess[bytes=1232425,reads=24408,travel=6462427001,range=8963521,size=1161
0814]
Heap dump reason: 1 retained objects, app is not visible
Analysis duration: 5411 ms
</code>```

Reproducing the leak:

Last version before deprecation:

```<code> implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.17.1'
 debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7'
</code>```

I have also tried it with 1.15.0

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.ar.sceneform.SceneView
        android:id="@+id/sceneview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"/>
</RelativeLayout>
</code>```

MainActivity (have also tested on a fragment)

```<code>public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private static final Vector3   STARTING_CAMERA_POSITION = new Vector3(0f, 1f, 3f);
    private              SceneView sceneView;
    private              Node      node;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sceneView = findViewById(R.id.sceneview);
        Scene scene = sceneView.getScene();
        node = new Node();
        scene.addChild(node);

        ModelRenderable.builder()
                .setSource(this, Uri.parse("Andy.sfb"))
                .build()
                .thenAccept(renderable -> node.setRenderable(renderable))
                .exceptionally(
                        throwable -> {
                            Log.e(TAG, "Unable to load Renderable.", throwable);
                            return null;
                        });
        Camera camera = scene.getCamera();
        camera.setWorldPosition(STARTING_CAMERA_POSITION);
    }

    @Override
    public void onPause() {
        super.onPause();
        sceneView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            sceneView.resume();
        } catch (CameraNotAvailableException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sceneView.destroy();
    }
}
</code>```

The .sfb file

https://drive.google.com/file/d/1NchJ2NGNM7NZzRZkq4fewALc7m4dnGG3/view?usp=sharing

To reproduce press the Home or Recent task list button while SceneView is running

I've also tested it with only just the SceneView, but it leaks as well.

How would I fix this leak?

I've also tested it on multiple APIs, emulators, and real devices and it happens on all of them.

答:
as you already said is the last version 1.17.1
A few enthusiasts are working on a maintained version. Maybe this version fixes your Memory Leak issue.</p>

Body:
I've been using SceneView for loading 3D models for almost a year now but I never understood what caused this leak. I would implement LeakCanary, but just this one leak because I couldn't figure out how to fix the problem.

But now I want to get to the bottom of the issue and try to fix it. I've tested it on two versions of Sceneform -- 1.15.0 and the last version before being deprecated by Google 1.17.1 and the issue happens on both.

The leak happens when you load a model using SceneView in an Activity or Fragment (I've tried both) and you "exit the app" by doing the System home navigation or switching to a different app via the Recent tasks list.

The logs for the leak:

┬───
│ GC Root: System class
│
├─ android.app.ActivityThread class
│    Leaking: NO (MainActivity↓ is not leaking and a class is never leaking)
│    ↓ static ActivityThread.sCurrentActivityThread
├─ android.app.ActivityThread instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    mInitialApplication instance of android.app.Application
│    ↓ ActivityThread.mActivities
├─ android.util.ArrayMap instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    ↓ ArrayMap.mArray
├─ java.lang.Object[] array
│    Leaking: NO (MainActivity↓ is not leaking)
│    ↓ Object[].[1]
├─ android.app.ActivityThread$ActivityClientRecord instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    activity instance of com.example.a3dmodeltester.MainActivity with
│    mDestroyed = false
│    ↓ ActivityThread$ActivityClientRecord.activity
├─ com.example.a3dmodeltester.MainActivity instance
│    Leaking: NO (SceneView↓ is not leaking and Activity#mDestroyed is false)
│    mApplication instance of android.app.Application
│    mBase instance of android.app.ContextImpl
│    ↓ MainActivity.sceneView
├─ com.google.ar.sceneform.SceneView instance
│    Leaking: NO (View attached)
│    View is part of a window view hierarchy
│    View.mAttachInfo is not null (view attached)
│    View.mID = R.id.sceneview
│    View.mWindowAttachCount = 1
│    mContext instance of com.example.a3dmodeltester.MainActivity with
│    mDestroyed = false
│    ↓ SceneView.renderer
│                ~~~~~~~~
├─ com.google.ar.sceneform.rendering.Renderer instance
│    Leaking: UNKNOWN
│    Retaining 2.9 kB in 38 objects
│    ↓ Renderer.viewAttachmentManager
│               ~~~~~~~~~~~~~~~~~~~~~
├─ com.google.ar.sceneform.rendering.ViewAttachmentManager instance
│    Leaking: UNKNOWN
│    Retaining 2.2 kB in 19 objects
│    ↓ ViewAttachmentManager.frameLayout
│                            ~~~~~~~~~~~
╰→ android.widget.FrameLayout instance
     Leaking: YES (ObjectWatcher was watching this because android.widget.
     FrameLayout received View#onDetachedFromWindow() callback)
     Retaining 1.9 kB in 15 objects
     key = 10550463-895e-443a-898f-11c5131da209
     watchDurationMillis = 5165
     retainedDurationMillis = 157
     View not part of a window view hierarchy
     View.mAttachInfo is null (view detached)
     View.mWindowAttachCount = 1
     mContext instance of com.example.a3dmodeltester.MainActivity with
     mDestroyed = false

METADATA

Build.VERSION.SDK_INT: 27
Build.MANUFACTURER: Google
LeakCanary version: 2.7
App process name: com.example.a3dmodeltester
Stats: LruCache[maxSize=3000,hits=892,misses=24408,hitRate=3%]
RandomAccess[bytes=1232425,reads=24408,travel=6462427001,range=8963521,size=1161
0814]
Heap dump reason: 1 retained objects, app is not visible
Analysis duration: 5411 ms

Reproducing the leak:

Last version before deprecation:

 implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.17.1'
 debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7'

I have also tried it with 1.15.0

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.ar.sceneform.SceneView
        android:id="@+id/sceneview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"/>
</RelativeLayout>

MainActivity (have also tested on a fragment)

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private static final Vector3   STARTING_CAMERA_POSITION = new Vector3(0f, 1f, 3f);
    private              SceneView sceneView;
    private              Node      node;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sceneView = findViewById(R.id.sceneview);
        Scene scene = sceneView.getScene();
        node = new Node();
        scene.addChild(node);

        ModelRenderable.builder()
                .setSource(this, Uri.parse("Andy.sfb"))
                .build()
                .thenAccept(renderable -> node.setRenderable(renderable))
                .exceptionally(
                        throwable -> {
                            Log.e(TAG, "Unable to load Renderable.", throwable);
                            return null;
                        });
        Camera camera = scene.getCamera();
        camera.setWorldPosition(STARTING_CAMERA_POSITION);
    }

    @Override
    public void onPause() {
        super.onPause();
        sceneView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            sceneView.resume();
        } catch (CameraNotAvailableException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sceneView.destroy();
    }
}

The .sfb file

https://drive.google.com/file/d/1NchJ2NGNM7NZzRZkq4fewALc7m4dnGG3/view?usp=sharing

To reproduce press the Home or Recent task list button while SceneView is running

I've also tested it with only just the SceneView, but it leaks as well.

How would I fix this leak?

I've also tested it on multiple APIs, emulators, and real devices and it happens on all of them.


来源: stackexchange

问:
How do I stop ASP.net forms authentication / session from renewing in setInterval ajax web service call?
I have a control that i've written that has a javascript component and a web service component.  The problem i'm having is that the javascript is set to do:

```<code>setInterval(this._checkAlertsHandler, this._messageCheckInterval * 1000);
</code>```

This calls a function which makes a webservice call like so:

```<code>Alert.SiteAlertService.GetAlerts(this._receivedAlertsHandler, this._errorReceivedAlertsHandler);
</code>```

So this is using the web service javascript proxy methods to access the web service.  The issue is that our application has forms authentication and a timeout value, so if the user is idle for too long it will log them out.

My webservice call apparently sends the cookie which includes the session and the forms authentication key to the web service.  The asp.net webservice then automatically renews the session AND the forms authentication. Everytime the javascript hits the web service it basically keeps the user alive.  I do not want this behavior, this should just circumvent that, so that even though this js is hitting the web service to check for new messages, if the user hasn't done a postback on our application (and is effectively idle) it will still log them out.  This isn't happening :(

What i would like to happen is this interval call to the web service does not renew any authentication (the session renewal i can get around by using an application level variable with dictionary key/value for the users session id, so i dont have to use any session level variables).

How do i do this / change my web service / or control to work like the way i want it?

答:
I'm working on different approaches to this as well.  One way I'm doing it is by adding this to the Ajax service endpoint:

```<code>// Hide the cookie so this call doesn't extend the user's ticket
HttpContext ctx = HttpContext.Current;
ctx.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
</code>```

This way you can negate an Auth Ticket renewal, sine the updated cookie will never make it back to the client.

If you have multiple Ajax endpoints that you want to exclude, a module can be implemented to identify those endpoints and include the code to remove the cookie from the response.

ContentLicense: CC BY-SA 2.5

Body:
I have a control that i've written that has a javascript component and a web service component.  The problem i'm having is that the javascript is set to do:

setInterval(this._checkAlertsHandler, this._messageCheckInterval * 1000);

This calls a function which makes a webservice call like so:

Alert.SiteAlertService.GetAlerts(this._receivedAlertsHandler, this._errorReceivedAlertsHandler);

So this is using the web service javascript proxy methods to access the web service.  The issue is that our application has forms authentication and a timeout value, so if the user is idle for too long it will log them out.

My webservice call apparently sends the cookie which includes the session and the forms authentication key to the web service.  The asp.net webservice then automatically renews the session AND the forms authentication. Everytime the javascript hits the web service it basically keeps the user alive.  I do not want this behavior, this should just circumvent that, so that even though this js is hitting the web service to check for new messages, if the user hasn't done a postback on our application (and is effectively idle) it will still log them out.  This isn't happening :(

What i would like to happen is this interval call to the web service does not renew any authentication (the session renewal i can get around by using an application level variable with dictionary key/value for the users session id, so i dont have to use any session level variables).

How do i do this / change my web service / or control to work like the way i want it?

Body:
I'm working on different approaches to this as well.  One way I'm doing it is by adding this to the Ajax service endpoint:

// Hide the cookie so this call doesn't extend the user's ticket
HttpContext ctx = HttpContext.Current;
ctx.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);

This way you can negate an Auth Ticket renewal, sine the updated cookie will never make it back to the client.

If you have multiple Ajax endpoints that you want to exclude, a module can be implemented to identify those endpoints and include the code to remove the cookie from the response.

ContentLicense: CC BY-SA 3.0


问:
Where do I add repositories in my root-level build.gradle file?
Recently, I updated my Android Studio to Bumblebee(stable version) that was released around 2 weeks back. The structure of the build.gradle(root-level) file seems to have changed a lot since the last version.

I am facing issue in adding dependencies in the root-level build.gradle file.

Here is what I want to add.

in the build.gradle file

答:
settings.gradle instead of build.gradle:

```<code>dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
      // ...
        maven { url 'https://jitpack.io' }
    }
}
</code>```

this way you dont need to use the build.gradle instead use the settings.gradle, these way it worked for me in Android Studio   Bumblebee

ContentLicense: CC BY-SA 4.0

Body:
settings.gradle instead of build.gradle:

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
      // ...
        maven { url 'https://jitpack.io' }
    }
}

this way you dont need to use the build.gradle instead use the settings.gradle, these way it worked for me in Android Studio   Bumblebee


问:
Correct way to setup a class variable for total QTY of product to be altered by buttons (React JS)
I am building a product detail page and created a class app to contain the main code of the project to facilitate a constructor for loading data from my API.

I want to have 3 numeric variables which I can increase/decrease via buttons on page
It set for 3 products of QHD, HD, Batteries.

I wrote the following code but its not correct and I am searching for correct ways to implement this.

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false,
      HD: 0,
    };
  }

  componentDidMount() {
    fetch("https://fe-assignment.vaimo.net/")
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        this.setState({
          isLoaded: true,
          items: data,
          TI: 0,
        });
      });
  }

  increaseHD() {
    HD = 1;
  }
</code>```

Continued

```<code>render() {
    const HD = 0;
</code>```
```<code><div className="button-row">
                    <button className="minus">-</button>
                    <form className="input">{HD}</form>
                    <button className="plus" onClick={this.increaseHD}>+</button>
                  </div>

</code>```

Returns the error that this undefined.
I know it should be setup up perhaps in the constructor or class wide as  but I am new to reactjs and need some help

答:
```<code>class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false,
      HD: 0,
    }
  }

  increaseHD = () => {
    this.setState({
      HD: 5
    })
  }

  render() {

    return (
     <div>
       Hello {this.state.HD}
       <button className="plus" onClick={this.increaseHD}>+</button>
      </div>
    )
  }
}
</code>```

You can also increase hd by taking in prev state of the component

```<code>increaseHD = () => {
    this.setState({
      HD: this.state.HD + 1
    })
  }
</code>```

Body:
I am building a product detail page and created a class app to contain the main code of the project to facilitate a constructor for loading data from my API.

I want to have 3 numeric variables which I can increase/decrease via buttons on page
It set for 3 products of QHD, HD, Batteries.

I wrote the following code but its not correct and I am searching for correct ways to implement this.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false,
      HD: 0,
    };
  }

  componentDidMount() {
    fetch("https://fe-assignment.vaimo.net/")
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        this.setState({
          isLoaded: true,
          items: data,
          TI: 0,
        });
      });
  }

  increaseHD() {
    HD = 1;
  }

Continued

render() {
    const HD = 0;

                    <button className="minus">-</button>
                    <form className="input">{HD}</form>
                    <button className="plus" onClick={this.increaseHD}>+</button>

Returns the error that this undefined.
I know it should be setup up perhaps in the constructor or class wide as  but I am new to reactjs and need some help

Body:
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false,
      HD: 0,
    }
  }

  increaseHD = () => {
    this.setState({
      HD: 5
    })
  }

  render() {

    return (
     <div>
       Hello {this.state.HD}
       <button className="plus" onClick={this.increaseHD}>+</button>
      </div>
    )
  }
}

You can also increase hd by taking in prev state of the component

increaseHD = () => {
    this.setState({
      HD: this.state.HD + 1
    })
  }


问:
Fetch returns unresolved `[object Response]`
I am trying to fetch the latest blog posts from Hubspot using their API and to do so I have to consume 2 endpoints (1 for the blog posts and 1 for the tag info for each blog post).

The first call brings back the latest blog posts. Then, for each blog post I need to retrieve the info for its tag, that the post has.

Below is the code that implements what described above,

```<code>  async getBlogs(contentGroupID: string = null, limit: number = null) {
    this.url = 'https://api.hubapi.com/cms/v3/blogs/posts?state=PUBLISHED&sort=-publish_date';

    const posts = await useFetch(
      this.url
      + '&hapikey=' + this.HS_API_KEY
      + (contentGroupID ? '&content_group_id=' + contentGroupID : null)
      + (limit ? '&limit=' + limit : null)
    ).then(response => {
      return response;
    });

    const tags = (posts.data.value as any).results.map(post => fetch(`https://api.hubapi.com/blogs/v3/topics/${post.tagIds[0]+'?hapikey='+this.HS_API_KEY}`));
    const taggs = await Promise.all(tags);

    const payload = new Object();

    payload['blogPosts'] = posts;
    payload['tags'] = taggs;

    return payload;
  }
</code>```

And here's the response at the Browser

As shown in screenshot above, the blogPosts object has been resolved just fine but the Promise.all() part to retrieve the tagIds[0] hasn't. It returns [object Response].

I have tried several different ways to do this and each one is always returning the Promise object unresolved.
What is the correct way to do this and get the actual data?

Just to give an example of what the tag data object looks like, for the tag with id 41520763199 its data is as shown below. This is what I should be getting as a response instead of the promise object.

```<code>{
    "categoryId": 3,
    "contentIds": [],
    "created": 1613125431347,
    "deletedAt": 0,
    "description": "",
    "id": 41520763199,
    "language": "en-us",
    "name": "Case Studies",
    "portalId": 2734675,
    "slug": "case-studies",
    "translations": {},
    "updated": 1616091635999
}
</code>```

答:
fetch will return a Promise<Response>, to actually get the result as a js object from a json string, you'd have to call .json() on the response object. You can do this within a .then callback, to not have to write two awaits.

async getBlogs(contentGroupID: string = null, limit: number = null) {
    this.url = 'https://api.hubapi.com/cms/v3/blogs/posts?state=PUBLISHED&sort=-publish_date';

    const blogPosts = await useFetch(
      this.url
      + '&hapikey=' + this.HS_API_KEY
      + (contentGroupID ? '&content_group_id=' + contentGroupID : '')
      + (limit ? '&limit=' + limit : '')
    );

    const tagPromises = (posts.data.value as any).results
        .map(post => fetch(`https://api.hubapi.com/blogs/v3/topics/${post.tagIds[0]+'?hapikey='+this.HS_API_KEY}`)
            .then(r => r.json()));

    const tags = await Promise.all(tagPromises);

    return {
        blogPosts,
        tags
    };
}
```

Body:
I am trying to fetch the latest blog posts from Hubspot using their API and to do so I have to consume 2 endpoints (1 for the blog posts and 1 for the tag info for each blog post).

The first call brings back the latest blog posts. Then, for each blog post I need to retrieve the info for its tag, that the post has.

Below is the code that implements what described above,

  async getBlogs(contentGroupID: string = null, limit: number = null) {
    this.url = 'https://api.hubapi.com/cms/v3/blogs/posts?state=PUBLISHED&sort=-publish_date';

    const posts = await useFetch(
      this.url
      + '&hapikey=' + this.HS_API_KEY
      + (contentGroupID ? '&content_group_id=' + contentGroupID : null)
      + (limit ? '&limit=' + limit : null)
    ).then(response => {
      return response;
    });

    const tags = (posts.data.value as any).results.map(post => fetch(`https://api.hubapi.com/blogs/v3/topics/${post.tagIds[0]+'?hapikey='+this.HS_API_KEY}`));
    const taggs = await Promise.all(tags);

    const payload = new Object();

    payload['blogPosts'] = posts;
    payload['tags'] = taggs;

    return payload;
  }

And here's the response at the Browser

As shown in screenshot above, the blogPosts object has been resolved just fine but the Promise.all() part to retrieve the tagIds[0] hasn't. It returns [object Response].

I have tried several different ways to do this and each one is always returning the Promise object unresolved.
What is the correct way to do this and get the actual data?

Just to give an example of what the tag data object looks like, for the tag with id 41520763199 its data is as shown below. This is what I should be getting as a response instead of the promise object.

{
    "categoryId": 3,
    "contentIds": [],
    "created": 1613125431347,
    "deletedAt": 0,
    "description": "",
    "id": 41520763199,
    "language": "en-us",
    "name": "Case Studies",
    "portalId": 2734675,
    "slug": "case-studies",
    "translations": {},
    "updated": 1616091635999
}


问:
Get child element from element through an event with Vue
Goal

What I'm trying to achieve is that whenever the user clicks on the .menu-item element, the dropdown element .menu-item-dropdown will get a class that will show the element.

Problem

Currently, when I click on the .menu-item class element, the returned value from the console.log in showMobileNavDropdown() returns null. When clicking, the event.target element is .menu-item-main and not .menu-item. This happens only when I click on the text of the li. Otherwise this works as intended.

What would be the best way to include the li text so that I can still grab the .menu-item-dropdown class?

Vue

```<code><template>
    <div>
        <nav class="nav">
            <div class="nav-left">
                <img class="logo" src="/images/logo.svg" alt="" />
            </div>
            <div class="nav-center">
                <ul class="menu-items">
                    <li
                        class="menu-item"
                        @click="showMobileNavDropdown($event)"
                    >
                        <!-- Main Title On Nav -->
                        <a class="menu-item-main" href="#">Company</a>

                        <!-- Dropdown -->
                        <div class="menu-item-dropdown">
                            <ul>
                                <li class="">
                                    <a href="">About</a>
                                </li>
                                <li class="">
                                    <a href="">Contact</a>
                                </li>
                            </ul>
                        </div>
                    </li>
                </ul>
            </div>

            <div class="nav-right">
                <a href="" class="btn">Contact us</a>
            </div>

            <div class="hamburger" @click="openMobileNav">
                <span class="ham-line"></span>
                <span class="ham-line ham-line-2"></span>
            </div>
        </nav>

        <div class="mobile-nav"></div>
    </div>
</template>

<script>
export default {
    methods: {
        openMobileNav() {
            var mobileNav = document.querySelector(".mobile-nav");
            mobileNav.classList.toggle("showMobileNav");
        },

        // This function
        showMobileNavDropdown(event) {
            console.log(event); // This element returns 'menu-item-main' and not 'menu-item'
            console.log(event.target.querySelector(".menu-item-dropdown"));
        },
    },
};
</script>

</code>```

答:
Assuming you have a longer list of possible click-targets and can't or won't just use refs, I would use event-delegation and in the click-handler check, whether the clicked element is inside a clickable parent and based on that, toggle a class on the parent, which can then be used to select the child in CSS, for example to change it's opacity.

Vue.component('foo-bar', {
  methods: {
    toggleSubItemVisibility({ target }) {
      const item = target.closest('.nav-item');
      // we check because the user might have clicked on the surrounding ul
      if (item) {
        item.classList.toggle('active');
      }
    }
  },
  template: `

        Foo

More details...

        Bar

More details...

  `
})

new Vue({
  el: '#app'
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>nav ul {
  list-style-type: none;
  display: flex;
  flex-direction: row;
  gap: 12px;
}

.nav-label {
  cursor: pointer;
}

.nav-sub-item {
  opacity: 0;
  transition: opacity 1s ease;
}

.nav-item.active .nav-sub-item {
  opacity: 1;
}</code>```

<foo-bar></foo-bar>

```

Body:
Goal

What I'm trying to achieve is that whenever the user clicks on the .menu-item element, the dropdown element .menu-item-dropdown will get a class that will show the element.

Problem

Currently, when I click on the .menu-item class element, the returned value from the console.log in showMobileNavDropdown() returns null. When clicking, the event.target element is .menu-item-main and not .menu-item. This happens only when I click on the text of the li. Otherwise this works as intended.

What would be the best way to include the li text so that I can still grab the .menu-item-dropdown class?

Vue

<template>

                        Company

                                    About

                                    Contact

                Contact us

</template>

Body:
Assuming you have a longer list of possible click-targets and can't or won't just use refs, I would use event-delegation and in the click-handler check, whether the clicked element is inside a clickable parent and based on that, toggle a class on the parent, which can then be used to select the child in CSS, for example to change it's opacity.

Vue.component('foo-bar', {
  methods: {
    toggleSubItemVisibility({ target }) {
      const item = target.closest('.nav-item');
      // we check because the user might have clicked on the surrounding ul
      if (item) {
        item.classList.toggle('active');
      }
    }
  },
  template: `
  <nav>
    <ul @click="toggleSubItemVisibility">
      <li class="nav-item">
        <span class="nav-label">Foo</span>
        <div class="nav-sub-item">More details...</div>
      </li>
      <li class="nav-item">
        <span class="nav-label">Bar</span>
        <div class="nav-sub-item">More details...</div>
      </li>
    </ul>
  </nav>`
})

new Vue({
  el: '#app'
});

nav ul {
  list-style-type: none;
  display: flex;
  flex-direction: row;
  gap: 12px;
}

.nav-label {
  cursor: pointer;
}

.nav-sub-item {
  opacity: 0;
  transition: opacity 1s ease;
}

.nav-item.active .nav-sub-item {
  opacity: 1;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<foo-bar></foo-bar>
</div>


问:
How can I do not use constructor in MainActivity in Android Studio?
I'm a beginner.
I'm trying to make Locale project with Android Studio.
So I made a class regard with Context.
In MainActivity required a constructor.
But, I'm heard that MainActivity do not need constructor but onCreate.

Here is my code.

BaseContextWrapper

```<code>    public class BaseContextWrapper extends AppCompatActivity {
    //AppCompatActivity-FragmentActivity-ComponentActivity-Activity-ContextThemeWrapper-ContextWrapper-Context
    public BaseContextWrapper(Context base) {
        super.attachBaseContext(base);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @NonNull
    public static ContextWrapper wrap(Context context) {
        Resources resources = context.getResources();
        Configuration newConfig = new Configuration();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        newConfig.setToDefaults();

        newConfig.densityDpi = metrics.densityDpi;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
            context = context.createConfigurationContext(newConfig);
        } else {
            resources.updateConfiguration(newConfig, resources.getDisplayMetrics());
        }
        return new BaseContextWrapper(context);
    }
}
</code>```

MainActivity

```<code>    public class MainActivity extends BaseContextWrapper {
    public MainActivity(Context base) {
        super(base);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

答:
Rewrite your MainActivity as

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

Body:
I'm a beginner.
I'm trying to make Locale project with Android Studio.
So I made a class regard with Context.
In MainActivity required a constructor.
But, I'm heard that MainActivity do not need constructor but onCreate.

Here is my code.

BaseContextWrapper

    public class BaseContextWrapper extends AppCompatActivity {
    //AppCompatActivity-FragmentActivity-ComponentActivity-Activity-ContextThemeWrapper-ContextWrapper-Context
    public BaseContextWrapper(Context base) {
        super.attachBaseContext(base);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @NonNull
    public static ContextWrapper wrap(Context context) {
        Resources resources = context.getResources();
        Configuration newConfig = new Configuration();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        newConfig.setToDefaults();

        newConfig.densityDpi = metrics.densityDpi;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
            context = context.createConfigurationContext(newConfig);
        } else {
            resources.updateConfiguration(newConfig, resources.getDisplayMetrics());
        }
        return new BaseContextWrapper(context);
    }
}

MainActivity

    public class MainActivity extends BaseContextWrapper {
    public MainActivity(Context base) {
        super(base);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Body:
Rewrite your MainActivity as

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}


问:
Extract only 1 month from a multi-year netcdf file
I am quite new to programming and I wanted to know if you could help me. I have a file that contains daily precipitation data from 2000 to 2020. I think with pandas I could create a dataframe that contains only the values of the month of January but I can't understand how. Or maybe with CDO create a new file that only contains those values. Could someone help me? I would appreciate it

答:
Steps -

Add a month column to your dataframe

df['month']= pd.to_datetime(df['date']).dt.month

Select the rows you want using the condition df.month == 1

df[(df['month'] == 1)]


问:
How to downgrade version of sumo
I am using instant veins with version 1.8.0 for Sumo. However, I want to use a veins project that was last tested on 0.30 version and I can't run the simulation without that version. How can I downgrade to that version of sumo?

More precisely, I am getting this error: TraCI server SUMO 1.8.0 reports API version 20, which is unsupported. We recommend using SUMO 0.30.0 in module

答: If you can comment the lines which check for the sumo version in veins. But remember possibility of simulation crash can't be ruled out in this case.</p>

Title: How to downgrade version of sumo


问:
Python: while followed by elif
I thought else if and elif are logically identical.

But when I try elif after while, I get a syntax error.

However, else is OK after while, as shown here (see comments A & B):

```<code>MENU_COMMANDS = {
'goal': 'the objective of the game is .... ',
'close': 'exit menu',
'menu': 'show all menu commands',
'quit': 'quit game' }

GAME_KEYBOARD = {
'1': 1,
'2': 2 }

def turn1():
key = input("Player 1, make your move")  # == 'goal'

while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")
else:  # why not 'elif' ?    COMMENT A
    if key not in GAME_KEYBOARD:
        print("invalid move")
        return False

# elif key not in GAME_KEYBOARD:  # why won't this work? :(    COMMENT B
#     print("invalid move")
#     return False
</code>```

Is this the only way to execute this logic, or is there a better one?

Thank you!

答:
```<code>if a:
    do something
elif b:
    do something
elif c:
    do something
else:
    ouch
</code>```

is the same as

```<code>if a:
    do this
if (not a) and b:
    do that
if (not a) and (not b) and c:
    do these
if (not a) and (not b) and (not c):
    no
</code>```

Title: Python: while followed by elif

Body:
I thought else if and elif are logically identical.

But when I try elif after while, I get a syntax error.

However, else is OK after while, as shown here (see comments A & B):

MENU_COMMANDS = {
'goal': 'the objective of the game is .... ',
'close': 'exit menu',
'menu': 'show all menu commands',
'quit': 'quit game' }

GAME_KEYBOARD = {
'1': 1,
'2': 2 }

def turn1():
key = input("Player 1, make your move")  # == 'goal'

while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")
else:  # why not 'elif' ?    COMMENT A
    if key not in GAME_KEYBOARD:
        print("invalid move")
        return False

# elif key not in GAME_KEYBOARD:  # why won't this work? :(    COMMENT B
#     print("invalid move")
#     return False

Is this the only way to execute this logic, or is there a better one?

Thank you!

Body:
if a:
    do something
elif b:
    do something
elif c:
    do something
else:
    ouch

is the same as

if a:
    do this
if (not a) and b:
    do that
if (not a) and (not b) and c:
    do these
if (not a) and (not b) and (not c):
    no


问:
How to connect to sql server 2008 via an IP address using pyodbc in Python
I am able to connect to server with mssql management studio but not able to connect using python I think  some problem in connection string please help below is string I am using.

```<code>import pyodbc as p

connStr = ( r'DRIVER={SQL Server};Server=ip; Network=DBMSSOCN;Initial Catalog=' + database + ';User ID=' + id +';Password=' + pass1 +';Trusted_Connection=True' +';')

conn = p.connect(connStr)
</code>```

error is like below

```<code> conn = p.connect(connStr)
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][TCP/IP Sock
ets]SQL Server does not exist or access denied. (17) (SQLDriverConnectW); [01000
] [Microsoft][ODBC SQL Server Driver][TCP/IP Sockets]ConnectionOpen (Connect()).
 (10060); [01S00] [Microsoft][ODBC SQL Server Driver]Invalid connection string a
ttribute (0)')
</code>```

答:
There are actually two or three SQL Server drivers written and distrubuted by Microsoft: one referred to as "SQL Server" and the other as "SQL Native Client" and "SQL Server Native Client 10.0}".

DRIVER={SQL
  Server};SERVER=cloak;DATABASE=test;UID=user;PWD=password

DRIVER={SQL Native
  Client};SERVER=dagger;DATABASE=test;UID=user;PWD=password

DRIVER={SQL Server Native Client
  10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password

The "SQL Server" one works for all versions of SQL Server, but only enables features and data types supported by SQL Server 2000, regardless of your actual server version.

For SQL Server 2005 installations, use "SQL Native Client" to enable 2005 features and types. Note that this version is not provided in all SQL Server 2008 installations!

Finally, you need "SQL Server Native Client 10.0" for SQL Server 2008 features and types.

Body:
I am able to connect to server with mssql management studio but not able to connect using python I think  some problem in connection string please help below is string I am using.

import pyodbc as p

connStr = ( r'DRIVER={SQL Server};Server=ip; Network=DBMSSOCN;Initial Catalog=' + database + ';User ID=' + id +';Password=' + pass1 +';Trusted_Connection=True' +';')

conn = p.connect(connStr)

error is like below

 conn = p.connect(connStr)
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][TCP/IP Sock
ets]SQL Server does not exist or access denied. (17) (SQLDriverConnectW); [01000
] [Microsoft][ODBC SQL Server Driver][TCP/IP Sockets]ConnectionOpen (Connect()).
 (10060); [01S00] [Microsoft][ODBC SQL Server Driver]Invalid connection string a
ttribute (0)')


问:
Scrape data from webpage with BeautifulSoup - How to append data to existing dataframe?
With the following code I try to scrape data from a website (reference: https://towardsdatascience.com/web-scraping-scraping-table-data-1665b6b2271c):

```<code>df = pd.DataFrame(columns=headings)
for i in range (102,158):
    URL = 'http://BuLidata.xyz/'
    URL_ = URL + 'B100' +str(i+1) + '.html'
    r = urllib.request.urlopen(URL_).read()
    soup = BeautifulSoup(r,'lxml')
    table = soup.find('table' ,attrs={'class':'abschluss'})
    body = table.find_all("tr")
    head = body[0]
    body_rows = body[1:]
    headings = []
    for item in head.find_all('th'):
        item = (item.text).rstrip('\n')
        headings.append(item)
    all_rows = []
    for row_num in range(len(body_rows)):
        row = []
        for row_item in body_rows[row_num].find_all("td"):
            aa = re.sub("(\xa0)|(\n)|,","",row_item.text)
            row.append(aa)
        all_rows.append(row)
    df1 = pd.DataFrame(data=all_rows,columns=headings)
    df.append(df1, ignore_index=True)
</code>```

I 'intialized' the dataframe as an empty dataframe only with the correct column names and then tried to use a loop in order to loop over the data on the website. Partially it seems to work because df1 is the data of the last website link. But df is still the initialized empty dataframe. I am wondering what I did wrong here?

答:
This is not the best strategy to append to a dataframe. Use instead a python data structure like list or dict then at the end of the loop, concat them to get your dataframe:

data = []
for i in range(102, 158)
    # do stuff here
    df1 = ...
    data.append(df1)
df = pd.concat(data, ignore_index=True)
```
<p>Output:</p>
```>>> df
     Platz             Mannschaft Spiele    S-U-N        Tore Pkt.         Statistik
0       1.       TSV 1860 München     34  20-10-4  80:40(+40)   50  Saison 1965/1966
1       2.      Borussia Dortmund     34   19-9-6  70:36(+34)   47  Saison 1965/1966
2       3.         Bayern München     34   20-7-7  71:38(+33)   47  Saison 1965/1966
3       4.          Werder Bremen     34  21-3-10  76:40(+36)   45  Saison 1965/1966
4       5.             1. FC Köln     34   19-6-9  74:41(+33)   44  Saison 1965/1966
...    ...                    ...    ...      ...         ...  ...               ...
1005   14.             Hertha BSC     34  8-11-15  41:52(-11)   35  Saison 2020/2021
1006   15.  DSC Arminia Bielefeld     34   9-8-17  26:52(-26)   35  Saison 2020/2021
1007   16.             1. FC Köln     34   8-9-17  34:60(-26)   33  Saison 2020/2021
1008   17.       SV Werder Bremen     34  7-10-17  36:57(-21)   31  Saison 2020/2021
1009   18.          FC Schalke 04     34   3-7-24  25:86(-61)   16  Saison 2020/2021

[1010 rows x 7 columns]
```

Body:
With the following code I try to scrape data from a website (reference: https://towardsdatascience.com/web-scraping-scraping-table-data-1665b6b2271c):

df = pd.DataFrame(columns=headings)
for i in range (102,158):
    URL = 'http://BuLidata.xyz/'
    URL_ = URL + 'B100' +str(i+1) + '.html'
    r = urllib.request.urlopen(URL_).read()
    soup = BeautifulSoup(r,'lxml')
    table = soup.find('table' ,attrs={'class':'abschluss'})
    body = table.find_all("tr")
    head = body[0]
    body_rows = body[1:]
    headings = []
    for item in head.find_all('th'):
        item = (item.text).rstrip('\n')
        headings.append(item)
    all_rows = []
    for row_num in range(len(body_rows)):
        row = []
        for row_item in body_rows[row_num].find_all("td"):
            aa = re.sub("(\xa0)|(\n)|,","",row_item.text)
            row.append(aa)
        all_rows.append(row)
    df1 = pd.DataFrame(data=all_rows,columns=headings)
    df.append(df1, ignore_index=True)

I 'intialized' the dataframe as an empty dataframe only with the correct column names and then tried to use a loop in order to loop over the data on the website. Partially it seems to work because df1 is the data of the last website link. But df is still the initialized empty dataframe. I am wondering what I did wrong here?

Body:
This is not the best strategy to append to a dataframe. Use instead a python data structure like list or dict then at the end of the loop, concat them to get your dataframe:

data = []
for i in range(102, 158)
    # do stuff here
    df1 = ...
    data.append(df1)
df = pd.concat(data, ignore_index=True)

Output:

>>> df
     Platz             Mannschaft Spiele    S-U-N        Tore Pkt.         Statistik
0       1.       TSV 1860 München     34  20-10-4  80:40(+40)   50  Saison 1965/1966
1       2.      Borussia Dortmund     34   19-9-6  70:36(+34)   47  Saison 1965/1966
2       3.         Bayern München     34   20-7-7  71:38(+33)   47  Saison 1965/1966
3       4.          Werder Bremen     34  21-3-10  76:40(+36)   45  Saison 1965/1966
4       5.             1. FC Köln     34   19-6-9  74:41(+33)   44  Saison 1965/1966
...    ...                    ...    ...      ...         ...  ...               ...
1005   14.             Hertha BSC     34  8-11-15  41:52(-11)   35  Saison 2020/2021
1006   15.  DSC Arminia Bielefeld     34   9-8-17  26:52(-26)   35  Saison 2020/2021
1007   16.             1. FC Köln     34   8-9-17  34:60(-26)   33  Saison 2020/2021
1008   17.       SV Werder Bremen     34  7-10-17  36:57(-21)   31  Saison 2020/2021
1009   18.          FC Schalke 04     34   3-7-24  25:86(-61)   16  Saison 2020/2021

[1010 rows x 7 columns]


问:
Show already exist data in UpdateView
I have class which is the inheritance of UpdateView

```<code>class BotContentsUpdateView(LoginRequiredMixin, UpdateView):
    model = BotContents
    template_name = 'bot_contents/bot_contents_edit.html'

    form_class = UploadBotContentsForm
    success_url = reverse_lazy("bot-contents-list")
    success_message = "success!!"
    def get_initial(self):

        initial = super().get_initial()
        initial['name'] = BotContents.name
        return initial

class UploadBotContentsForm(forms.ModelForm):
    name = forms.CharField(label="name")

    class Meta:
       model = BotContents
       fields = ["name"]
</code>```

in bot_contents_edit.html

```<code> {{ form.name }}
</code>```

In this case it shows text box automatically.

It's quite easy but I want to show the original stored data in BotContents as placeholder.

I thought get_initial is for this purpose , but it doesn't work.

How can I do this?

答:
You can render every field in custom way with passing in html: placeholder={{ form.name.value }}. You can firstfully check how is field generated automatically and use same classes and ids. It should look something like this:

```<code><input
type="text"
name="name"
value=""    # important to leave that empty
maxlength="100"
class="textinput textInput form-control"
id="id_name"
placeholder="{{ form.name.value }}"   # here you pass your name as placeholder
required >
</code>```

Title: Show already exist data in UpdateView

Body:
I have class which is the inheritance of UpdateView

class BotContentsUpdateView(LoginRequiredMixin, UpdateView):
    model = BotContents
    template_name = 'bot_contents/bot_contents_edit.html'

    form_class = UploadBotContentsForm
    success_url = reverse_lazy("bot-contents-list")
    success_message = "success!!"
    def get_initial(self):

        initial = super().get_initial()
        initial['name'] = BotContents.name
        return initial

class UploadBotContentsForm(forms.ModelForm):
    name = forms.CharField(label="name")

    class Meta:
       model = BotContents
       fields = ["name"]

in bot_contents_edit.html

 {{ form.name }}

In this case it shows text box automatically.

It's quite easy but I want to show the original stored data in BotContents as placeholder.

I thought get_initial is for this purpose , but it doesn't work.

How can I do this?

Body:
You can render every field in custom way with passing in html: placeholder={{ form.name.value }}. You can firstfully check how is field generated automatically and use same classes and ids. It should look something like this:

<input
type="text"
name="name"
value=""    # important to leave that empty
maxlength="100"
class="textinput textInput form-control"
id="id_name"
placeholder="{{ form.name.value }}"   # here you pass your name as placeholder
required >


问:
How to get sorted dictionary from another one instead of a list
I have Dict ={'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]} dictionary and want to sort it based on the second element of the value which is a list.

I tried OrderedDict = sorted(Dict.items(), key=lambda x: x[1][1]) but it returns an ordered list instead of a dictionary.

This is what I expect :

```<code>OrderedDict = {('Deblai', [100, 1]), ('Beton de propreté', [50, 2]), ('Blocage', [10, 4])}
</code>```

How I can get a dictionary instead of list ?

答:
Since normal dictionaries preserve the ordering in which their keys were inserted, you're most of the way there; just take the list of items and pass it to the dict constructor.  Making it an actual OrderedDict (yes, that's an actual thing) isn't necessary.

```<code>>>> my_dict = {'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]}
>>> sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1][1]))
>>> sorted_dict
{'Deblai': [100, 1], 'Beton de propreté': [50, 2], 'Blocage': [10, 4]}
</code>```

You probably don't want to name your instances Dict and OrderedDict, since these are the names of standard classes (and you should name instances with snake_case instead of CamelCase regardless).

Body:
I have Dict ={'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]} dictionary and want to sort it based on the second element of the value which is a list.

I tried OrderedDict = sorted(Dict.items(), key=lambda x: x[1][1]) but it returns an ordered list instead of a dictionary.

This is what I expect :

OrderedDict = {('Deblai', [100, 1]), ('Beton de propreté', [50, 2]), ('Blocage', [10, 4])}

How I can get a dictionary instead of list ?

Body:
Since normal dictionaries preserve the ordering in which their keys were inserted, you're most of the way there; just take the list of items and pass it to the dict constructor.  Making it an actual OrderedDict (yes, that's an actual thing) isn't necessary.

>>> my_dict = {'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]}
>>> sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1][1]))
>>> sorted_dict
{'Deblai': [100, 1], 'Beton de propreté': [50, 2], 'Blocage': [10, 4]}

You probably don't want to name your instances Dict and OrderedDict, since these are the names of standard classes (and you should name instances with snake_case instead of CamelCase regardless).


问:
There is a code drawing a heart. How to insert a photo inside this figure so that the remaining background does not change?
There is a code drawing a heart. How to insert a photo inside this figure so that the remaining background does not change?</p>
```<code>import time
import math
import turtle
def xt(t):
    return 16 * math.sin(t) ** 3
def yt(t):
    return 13 * math.cos(t) - 5 * \
        math.cos(2 * t) - 2 * \
        math.cos(3 * t) - \
        math.cos(4 * t)
t = turtle.Turtle()
turtle.Screen().screensize(1040, 1080)
t.speed(1500)
turtle.colormode(255)
turtle.Screen().bgcolor(0, 0, 0)
time.sleep(2)
for i in range(300):
    t.goto((xt(i) * 20, yt(i) * 20))
    t.pencolor((255 - i) % 255, i % 255, (255 + i) // 2 % 255)
    t.goto(0, 0)
t.hideturtle()
turtle.update()
turtle.mainloop()
</code>```

答:
We can use the combination of register_shape() and stamp() to place an image atop the drawing.  Below is an example of doing this as well as some tweaks of your original code:

```<code>from math import sin, cos
from turtle import Screen, Turtle

def xt(t):
    return 16 * sin(t) ** 3

def yt(t):
    return 13 * \
        cos(1 * t) - 5 * \
        cos(2 * t) - 2 * \
        cos(3 * t) - \
        cos(4 * t)

screen = Screen()
screen.setup(1040, 1080)
screen.bgcolor('black')
screen.colormode(255)
screen.register_shape("picture.gif")

turtle = Turtle()
turtle.hideturtle()
turtle.speed('fastest')

for i in range(300):
    turtle.goto((xt(i) * 20, yt(i) * 20))
    turtle.pencolor((255 - i) % 255, i % 255, (255 + i) // 2 % 255)
    turtle.home()

turtle.shape("picture.gif")
turtle.stamp()

screen.mainloop()
</code>```

Body:
There is a code drawing a heart. How to insert a photo inside this figure so that the remaining background does not change?

import time
import math
import turtle
def xt(t):
    return 16 * math.sin(t) ** 3
def yt(t):
    return 13 * math.cos(t) - 5 * \
        math.cos(2 * t) - 2 * \
        math.cos(3 * t) - \
        math.cos(4 * t)
t = turtle.Turtle()
turtle.Screen().screensize(1040, 1080)
t.speed(1500)
turtle.colormode(255)
turtle.Screen().bgcolor(0, 0, 0)
time.sleep(2)
for i in range(300):
    t.goto((xt(i) * 20, yt(i) * 20))
    t.pencolor((255 - i) % 255, i % 255, (255 + i) // 2 % 255)
    t.goto(0, 0)
t.hideturtle()
turtle.update()
turtle.mainloop()

Body:
We can use the combination of register_shape() and stamp() to place an image atop the drawing.  Below is an example of doing this as well as some tweaks of your original code:

from math import sin, cos
from turtle import Screen, Turtle

def xt(t):
    return 16 * sin(t) ** 3

def yt(t):
    return 13 * \
        cos(1 * t) - 5 * \
        cos(2 * t) - 2 * \
        cos(3 * t) - \
        cos(4 * t)

screen = Screen()
screen.setup(1040, 1080)
screen.bgcolor('black')
screen.colormode(255)
screen.register_shape("picture.gif")

turtle = Turtle()
turtle.hideturtle()
turtle.speed('fastest')

for i in range(300):
    turtle.goto((xt(i) * 20, yt(i) * 20))
    turtle.pencolor((255 - i) % 255, i % 255, (255 + i) // 2 % 255)
    turtle.home()

turtle.shape("picture.gif")
turtle.stamp()

screen.mainloop()


问:
SwiftUI - Firebase - Save Date without time
hi everyone I have this structure that I use to save data on firebase ... As you can see I have a var reservation_date: Date  field

Firebase obviously saves a date with the time but I would need only the date without the time to be saved how can I get this?

This is how I save me

```<code>struct Reservations: Identifiable, Codable {
    @DocumentID var id: String?
    var reservation_date: Date
    var user: String
    @ExplicitNull var userID: String?
    var reservation_id: String
    @FirebaseFirestoreSwift.ServerTimestamp var createdAt: Timestamp?

    enum CodingKeys: String, CodingKey {
        case id
        case reservation_date
        case user
        case userID
        case reservation_id
        case createdAt
    }
    static let sample = Reservations(reservation_date: Date(), user: "", userID: "", reservation_id: "")

}
</code>```

```<code>// MARK: - Firebase
extension ReservationViewModel {
    func addReservation() {
        guard let newDate = Calendar.current.date(bySettingHour: hour, minute: minute, second: 0, of: selectedDate) else {
            print("Non è stato possibile creare una data di prenotazione valida")
            return }

        let dBPath = db.collection("Prenotazioni")
            .document(newDate.formatted(.dateTime.year()))
            .collection(newDate.formatted(.dateTime.month(.wide).locale(Locale(identifier: "it"))))
            .document(newDate.formatted(.dateTime.day(.twoDigits)))
            .collection("Ore \(newDate.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).locale(Locale(identifier: "it"))) + ":" + newDate.formatted(.dateTime.minute(.twoDigits)))")
        do {
            let _ = try dBPath.addDocument(from: reservation)
        }
        catch {
            print(error)
        }
    }
}
</code>```

答:
If you're only interested in the date value then I would recommend using a string that conforms to the ISO 8601 standard, which in this particular case would just be yyyy-mm-dd (ex: "2022-02-13"). Swift has a ready-made ISO-8601 formatter exactly for this.

```<code>let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withFullDate]

// From String to Date
let reservationDay = "2022-03-25" // save this in your database
if let date = formatter.date(from: reservationDay) {
    print(date) // Swift Date object
}

// From Date to String
let reservationDate = Date()
let day = formatter.string(from: reservationDate)
print(day) // String "2022-02-13"
</code>```

Be mindful of timezones, however, because the default is GMT and you will want to use GMT throughout the conversions (and then render the local timezone value) or the local timezone throughout the conversions (just don't mix them as you convert). To always deal in the local timezone you can set its property on the formatter:

```<code>formatter.timeZone = .current
</code>```

Body:
hi everyone I have this structure that I use to save data on firebase ... As you can see I have a var reservation_date: Date  field

Firebase obviously saves a date with the time but I would need only the date without the time to be saved how can I get this?

This is how I save me

struct Reservations: Identifiable, Codable {
    @DocumentID var id: String?
    var reservation_date: Date
    var user: String
    @ExplicitNull var userID: String?
    var reservation_id: String
    @FirebaseFirestoreSwift.ServerTimestamp var createdAt: Timestamp?

    enum CodingKeys: String, CodingKey {
        case id
        case reservation_date
        case user
        case userID
        case reservation_id
        case createdAt
    }
    static let sample = Reservations(reservation_date: Date(), user: "", userID: "", reservation_id: "")

}

// MARK: - Firebase
extension ReservationViewModel {
    func addReservation() {
        guard let newDate = Calendar.current.date(bySettingHour: hour, minute: minute, second: 0, of: selectedDate) else {
            print("Non è stato possibile creare una data di prenotazione valida")
            return }

        let dBPath = db.collection("Prenotazioni")
            .document(newDate.formatted(.dateTime.year()))
            .collection(newDate.formatted(.dateTime.month(.wide).locale(Locale(identifier: "it"))))
            .document(newDate.formatted(.dateTime.day(.twoDigits)))
            .collection("Ore \(newDate.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).locale(Locale(identifier: "it"))) + ":" + newDate.formatted(.dateTime.minute(.twoDigits)))")
        do {
            let _ = try dBPath.addDocument(from: reservation)
        }
        catch {
            print(error)
        }
    }
}

Body:
If you're only interested in the date value then I would recommend using a string that conforms to the ISO 8601 standard, which in this particular case would just be yyyy-mm-dd (ex: "2022-02-13"). Swift has a ready-made ISO-8601 formatter exactly for this.

let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withFullDate]

// From String to Date
let reservationDay = "2022-03-25" // save this in your database
if let date = formatter.date(from: reservationDay) {
    print(date) // Swift Date object
}

// From Date to String
let reservationDate = Date()
let day = formatter.string(from: reservationDate)
print(day) // String "2022-02-13"

Be mindful of timezones, however, because the default is GMT and you will want to use GMT throughout the conversions (and then render the local timezone value) or the local timezone throughout the conversions (just don't mix them as you convert). To always deal in the local timezone you can set its property on the formatter:

formatter.timeZone = .current


问:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'"
Im creating a chrome extension for Rss reader in that im getting the above error. please help

manifest.json

{
    "name": "Tutorialzine Extension",
    "manifest_version": 2,
    "version": "1.1",
    "description": "Making your first Google Chrome extension.",
    "icons": {
        "128": "icon_128.png"
    },
    "web_accessible_resources": ["script.js", "https://query.yahooapis.com"],
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "tutorialzine.html"
    },
    "permissions": [
        "tabs",
        "<all_urls",
        "http://localhost/",
        "http://*/*",
        "https://*/*",
        "https://query.yahooapis.com"
    ],
    "content_security_policy": "script-src 'self'; 'https://query.yahooapis.com';unsafe-inline; object-src 'self'"
}
```
<p><strong>script.js</strong></p>
<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {

    var query = "SELECT * FROM feed WHERE url='http://feeds.feedburner.com/Tutorialzine' LIMIT 2";

    // Storing the seconds since the epoch in now:
    var now = (new Date()).getTime() / 1000;

    // If there is no cache set in localStorage, or the cache is older than 1 hour:
    if (!localStorage.cache || now - parseInt(localStorage.time) > 1 * 60 * 60) {
        $.get("yahoo.js", function (msg) {

            // msg.query.results.item is an array:
            var items = msg.query.results.item;
            var htmlString = "";

            for (var i = 0; i < items.length; i++) {
                var tut = items[i];

                // Extracting the post ID from the permalink:
                var id = tut.guid.content.match(/(\d+)$/)[0];

                // Looping and generating the markup of the tutorials:

                htmlString += '<div class="tutorial">\
                            <img src="http://tutorialzine.com/img/posts/' + id + '.jpg" />\
                            <h2>' + tut.title + '</h2>\
                            <p>' + tut.description + '</p>\
                            Read more\
                            </div>';
            }

            // Setting the cache
            localStorage.cache = htmlString;
            localStorage.time = now;

            // Updating the content div:
            $('#content').html(htmlString);
        }, 'json');
    } else {
        // The cache is fresh, use it:
        $('#content').html(localStorage.cache);
    }
}
</code>```

Error in jquery.min.js:

Jquery.min.js contains inline script what to do

parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=
```

答:
I had this error a couple of times in a few days, for no apparent reason (I forget the first "cause", but the second occurrance of this message was after a machine restart).

No amount of returning to previous working branches helped, nor adding the meta tags detailed in this question and here (basically the same).

So I deleted node_modules, and it's gone away now, and all is working well.  Maybe someone else's code is as random as mine...

Body:
Im creating a chrome extension for Rss reader in that im getting the above error. please help

manifest.json

{
    "name": "Tutorialzine Extension",
    "manifest_version": 2,
    "version": "1.1",
    "description": "Making your first Google Chrome extension.",
    "icons": {
        "128": "icon_128.png"
    },
    "web_accessible_resources": ["script.js", "https://query.yahooapis.com"],
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "tutorialzine.html"
    },
    "permissions": [
        "tabs",
        "<all_urls",
        "http://localhost/",
        "http://*/*",
        "https://*/*",
        "https://query.yahooapis.com"
    ],
    "content_security_policy": "script-src 'self'; 'https://query.yahooapis.com';unsafe-inline; object-src 'self'"
}

script.js

$(document).ready(function () {

    var query = "SELECT * FROM feed WHERE url='http://feeds.feedburner.com/Tutorialzine' LIMIT 2";

    // Storing the seconds since the epoch in now:
    var now = (new Date()).getTime() / 1000;

    // If there is no cache set in localStorage, or the cache is older than 1 hour:
    if (!localStorage.cache || now - parseInt(localStorage.time) > 1 * 60 * 60) {
        $.get("yahoo.js", function (msg) {

            // msg.query.results.item is an array:
            var items = msg.query.results.item;
            var htmlString = "";

            for (var i = 0; i < items.length; i++) {
                var tut = items[i];

                // Extracting the post ID from the permalink:
                var id = tut.guid.content.match(/(\d+)$/)[0];

                // Looping and generating the markup of the tutorials:

                htmlString += '
\
                            \

' + tut.title + '
\

' + tut.description + '
\
                            Read more\

';
            }

            // Setting the cache
            localStorage.cache = htmlString;
            localStorage.time = now;

            // Updating the content div:
            $('#content').html(htmlString);
        }, 'json');
    } else {
        // The cache is fresh, use it:
        $('#content').html(localStorage.cache);
    }
}

Error in jquery.min.js:

Jquery.min.js contains inline script what to do

parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=


问:
Error when more than one fight in same channel
I am trying to make a fight command in discord.js v13
So how this code works is
Every time a select_menu is selected,
It runs the collector and loops over 'collect' event till the health one of the players zero.
It works fine if there is only one fight going on in the channel,but when someone uses fight command when there is a fight command going on in the same channel, It throws

throw new DiscordAPIError(data, res.status, request);
^

DiscordAPIError: Interaction has already been acknowledged.

```<code>const collector1 = await interaction.channel.createMessageComponentCollector({ filter, componentType: 'SELECT_MENU', time: 600000 })
collector1.on('collect', async i => {
if (//my condition){
//action
collector1
}
Thank you any help would be appreciated!

</code>```

答:
Need to see more of your code (specifically, your filter declaration), but that is where the problem seems to be. Make sure your filter is only looking at the user who started the interaction:

```<code>const filter = (i) => (i.user.id === interaction.user.id);
</code>```

Additionally, make sure your collector is running multiple times (it would help if you post your entire interactionCreate function.

Body:
I am trying to make a fight command in discord.js v13
So how this code works is
Every time a select_menu is selected,
It runs the collector and loops over 'collect' event till the health one of the players zero.
It works fine if there is only one fight going on in the channel,but when someone uses fight command when there is a fight command going on in the same channel, It throws

throw new DiscordAPIError(data, res.status, request);
^

DiscordAPIError: Interaction has already been acknowledged.

const collector1 = await interaction.channel.createMessageComponentCollector({ filter, componentType: 'SELECT_MENU', time: 600000 })
collector1.on('collect', async i => {
if (//my condition){
//action
collector1
}
Thank you any help would be appreciated!

Body:
Need to see more of your code (specifically, your filter declaration), but that is where the problem seems to be. Make sure your filter is only looking at the user who started the interaction:

const filter = (i) => (i.user.id === interaction.user.id);

Additionally, make sure your collector is running multiple times (it would help if you post your entire interactionCreate function.


问:
How to pass prop of a child to another child? (React Hooks)
I need to pass a prop (it's a unique id) from one child component to another, but I can't do it.

The operation is simple: Homepage is the parent and has two direct children: Gallery and Detail. Gallery using a map prints its children Cards, which have a unique id. I need that when clicking on a card button, that unique id can be received by Detail.

I tried to manage it through handleClick but since I already manage a state there, I don't know if it is possible to manage it from there or are other methods.

This is the code:

```<code>interface DetailProps {}

const Detail: React.FC<DetailProps> = (props) => {
  return (
    <div>
      <span className="tituloJuego">DENTRO DE DETAIL</span>
    </div>
  );
};

interface CardProps {
  id: number;
  image: string;
  title: string;
  price: string;
  onClick: (result: string) => void;
}

const Card: React.FC<CardProps> = (props) => {
  return (
    <div className="card">
      <img className="image" src={props.image} />

      <div className="card-info">
        <div className="containerTitlePrice">
          <span className="tituloJuego">{props.title}</span>
          <br></br>
          <span className="-USD">{props.price}</span>
        </div>

        <div className="containerButton">
          <button className="Rectangle" onClick={(event) => props.onClick("detail")}>
            <span className="Install-Game">BUY NOW</span>
          </button>
        </div>
      </div>
    </div>
  );
};

interface GalleryProps {
  onClick: (result: string) => void;
}

const Gallery: React.FC<GalleryProps> = (props) => {
  return (
    // Se recorren los datos de json con map y se imprime cada card
    <div className="container">
      {data.map((games, key) => {
        return (
          <Card
            id={games.id}
            image={games.image}
            title={games.title}
            price={games.price}
            onClick={(event) => props.onClick("detail")}
          />
        );
      })}
    </div>
  );
};

const Homepage: React.FC = () => {
  // Por defecto el estado muestra homepage
  const [currentView, setCurrentView] = React.useState<string>("homepage");
  const handleClick = () => setCurrentView("detail");

  const [currentClickedGame, setCurrentClickedGame] = React.useState<number>(0);

  return (
    <div className="Simplified-homepage">
      {currentView === "homepage" ? (
        <div className="store-gallery">
          <Gallery onClick={handleClick} />
        </div>
      ) : (
        <div className="">
          <Detail />
        </div>
      )}
    </div>
  );
};

// ========================================

ReactDOM.render(<Homepage />, document.getElementById("root"));
</code>```

Here is the json file. The data from this file is the data that im showing in the Cards. The "ID" is the number that I want to pass from Card to Homepage:

JSON file

答:
You can pass the state currentClickedGame in both the child components for handling the ID.
You can't pass props on components in the same level or from child to parent as react follows unidirectional data flow .Also, instead of passing the handleClick from Homepage you can manage it inside Card component itself and set setCurrentView from there.
I've drilled props to 2 levels, consider using context in a more complex case

In HomePage:

```<code>return (
    <div className="Simplified-homepage">
      {currentView === "homepage" ? (
        <div className="store-gallery">
          <Gallery setCurrentClickedGame ={setCurrentClickedGame}/>
        </div>
      ) : (
        <div className="">
          <Detail currentClickedGame={currentClickedGame}/>
        </div>
      )}
    </div>
  );
</code>```

And in Gallery component:

```<code>   return (
          <div key={games.id}>
            <Card
              id={games.id}
              image={games.image}
              title={games.title}
              price={games.price}
              setCurrentView={props.setCurrentView}
              setCurrentClickedGame={props.setCurrentClickedGame}
            />
          </div>
        );
</code>```

View demo on Codesandbox

Body:
I need to pass a prop (it's a unique id) from one child component to another, but I can't do it.

The operation is simple: Homepage is the parent and has two direct children: Gallery and Detail. Gallery using a map prints its children Cards, which have a unique id. I need that when clicking on a card button, that unique id can be received by Detail.

I tried to manage it through handleClick but since I already manage a state there, I don't know if it is possible to manage it from there or are other methods.

This is the code:

interface DetailProps {}

const Detail: React.FC<DetailProps> = (props) => {
  return (

      DENTRO DE DETAIL

  );
};

interface CardProps {
  id: number;
  image: string;
  title: string;
  price: string;
  onClick: (result: string) => void;
}

const Card: React.FC<CardProps> = (props) => {
  return (

          {props.title}

          {props.price}

          <button className="Rectangle" onClick={(event) => props.onClick("detail")}>
            BUY NOW
          </button>

  );
};

interface GalleryProps {
  onClick: (result: string) => void;
}

const Gallery: React.FC<GalleryProps> = (props) => {
  return (
    // Se recorren los datos de json con map y se imprime cada card

      {data.map((games, key) => {
        return (
          <Card
            id={games.id}
            image={games.image}
            title={games.title}
            price={games.price}
            onClick={(event) => props.onClick("detail")}
          />
        );
      })}

  );
};

const Homepage: React.FC = () => {
  // Por defecto el estado muestra homepage
  const [currentView, setCurrentView] = React.useState<string>("homepage");
  const handleClick = () => setCurrentView("detail");

  const [currentClickedGame, setCurrentClickedGame] = React.useState<number>(0);

  return (

      {currentView === "homepage" ? (

          <Gallery onClick={handleClick} />

      ) : (

          <Detail />

      )}

  );
};

// ========================================

ReactDOM.render(<Homepage />, document.getElementById("root"));

Here is the json file. The data from this file is the data that im showing in the Cards. The "ID" is the number that I want to pass from Card to Homepage:

JSON file

Body:
You can pass the state currentClickedGame in both the child components for handling the ID.
You can't pass props on components in the same level or from child to parent as react follows unidirectional data flow .Also, instead of passing the handleClick from Homepage you can manage it inside Card component itself and set setCurrentView from there.
I've drilled props to 2 levels, consider using context in a more complex case

In HomePage:

return (
    <div className="Simplified-homepage">
      {currentView === "homepage" ? (
        <div className="store-gallery">
          <Gallery setCurrentClickedGame ={setCurrentClickedGame}/>
        </div>
      ) : (
        <div className="">
          <Detail currentClickedGame={currentClickedGame}/>
        </div>
      )}
    </div>
  );

And in Gallery component:

   return (
          <div key={games.id}>
            <Card
              id={games.id}
              image={games.image}
              title={games.title}
              price={games.price}
              setCurrentView={props.setCurrentView}
              setCurrentClickedGame={props.setCurrentClickedGame}
            />
          </div>
        );

View demo on Codesandbox


问:
Get main content in a page while web scraping node js, Puppeteer, Cheerio
I have a Project with Node JS on web scraping where I will have to scrape Heading and Text from Main Content. But the Problem is I'm not able to Determine which is Main Content When there is No aside or main tag or class/id/role named aside or main. I'm Using Puppeteer and Cheerio Library. I have Tried using Mercury Web Parser But it has its Own problems. Like It doesn't return any content from Pages that Built with Elementor Theme builder on Wordpress. If anyone have any idea on how can I differentiate main content from rest of the web page it will be really helpful.

答:
Try to explore more about CSS Selectors and specificity.

If you're scraping Elementor, be sure to use this trick for the selector:
Use data-elementor-(attributename) attributes for everything in DOM.

```<code>const mainContent = await page.waitForElement('[data-elementor-type="wp-page"]', {visible: true, timeout: 0})
</code>```

Body:
Try to explore more about CSS Selectors and specificity.

If you're scraping Elementor, be sure to use this trick for the selector:
Use data-elementor-(attributename) attributes for everything in DOM.

const mainContent = await page.waitForElement('[data-elementor-type="wp-page"]', {visible: true, timeout: 0})


问:
import web3 into react js getting BREAKING CHANGE: webpack < 5 used to incl
I am having problems with importing web3 into reactjs. To replicate my problem, initiallize a new react app as so

```<code>npx create-react-app my-app
cd my-app
</code>```

then open terminal in this location. Write:

```<code>npm install web3
npm install
</code>```

in the App,js file add the following line

```<code>import Web3 from "web3";
</code>```

I got the error after I do npm start then I got the unsolved error which is

Module not found: Error: Can't resolve 'stream'

Module not found: Error: Can't resolve 'crypto'

I tried finding a solution online, in particular I tried each of

How to Polyfill node core modules in webpack 5

https://www.youtube.com/watch?v=u1PPNIBvQjk

Importing web3 causing a problem in react js

https://github.com/facebook/create-react-app/issues/11756#issuecomment-1001162736

https://namespaceit.com/blog/how-fix-breaking-change-webpack-5-used-to-include-polyfills-for-nodejs-core-modules-by-default-error

How to create React App including Web3 using create-react-app? I am getting Module not found Error. BREAKING CHANGE: webpack < 5 used

None seem to work with me. Is there any advice on how to solve this problem?
Thank you!

答:
Try installing the missing modules using</p>
```<code>npm i stream crypto
</code>```

Body:
I am having problems with importing web3 into reactjs. To replicate my problem, initiallize a new react app as so

npx create-react-app my-app
cd my-app

then open terminal in this location. Write:

npm install web3
npm install

in the App,js file add the following line

import Web3 from "web3";

I got the error after I do npm start then I got the unsolved error which is

Module not found: Error: Can't resolve 'stream'

Module not found: Error: Can't resolve 'crypto'

I tried finding a solution online, in particular I tried each of

How to Polyfill node core modules in webpack 5

https://www.youtube.com/watch?v=u1PPNIBvQjk

Importing web3 causing a problem in react js

https://github.com/facebook/create-react-app/issues/11756#issuecomment-1001162736

https://namespaceit.com/blog/how-fix-breaking-change-webpack-5-used-to-include-polyfills-for-nodejs-core-modules-by-default-error

How to create React App including Web3 using create-react-app? I am getting Module not found Error. BREAKING CHANGE: webpack < 5 used

None seem to work with me. Is there any advice on how to solve this problem?
Thank you!

Body:
Try installing the missing modules using

npm i stream crypto


问:
When I use pushViewController I don't get any response
I try to play a video and I want to switch to a new storyboard afterwards. But for some reason the pushViewController is not doing anything.

I will appreciate any hint to get this running. Thank you all.

View Controller File

```<code>class ViewController: UIViewController, WKNavigationDelegate {

    let playerController = AVPlayerViewController()

    private func playVideo() {
        guard let path = Bundle.main.path(forResource: "screen3", ofType: "mp4" ) else {
            debugPrint("video missing")
            return
        }

        let player = AVPlayer(url: URL(fileURLWithPath: path) )

        playerController.showsPlaybackControls = false
        playerController.player = player
        playerController.videoGravity = .resizeAspectFill

        NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem )

        present(playerController, animated: true ) {
            player.play()
        }

    }

    @objc func playerDidFinishPlaying(note: NSNotification ) {
        print("Video finished")

        let vc = UIStoryboard.init(name: "Alternate", bundle: Bundle.main).instantiateViewController(withIdentifier: "SecondVC") as? SecondVC

        self.navigationController?.pushViewController(vc!, animated: false)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        playVideo()

    }

}
</code>```

SecondVC

```<code>    class SecondVC: UIViewController {

    override func viewDidLoad() {

        print("alterante")
        super.viewDidLoad()
        view.backgroundColor = .link
    }

}
</code>```

答:
I believe this is what is happening:

You have a Navigation Controller which contains UIViewController

You present the AVPlayerViewController on top of the UIViewController and its UINavigationController

When you push the SecondVC, it is over UIViewController and its UINavigationController but under AVPlayerViewController so you don't see it

Why don't you update your playerDidFinishPlaying function to something like this:

```<code>@objc
func playerDidFinishPlaying(note: NSNotification ) {
    print("Video finished")

    let vc = UIStoryboard.init(name: "Alternate",
                               bundle: Bundle.main)
        .instantiateViewController(withIdentifier: "SecondVC") as? SecondVC

    // Push SecondVC
    self.navigationController?.pushViewController(vc!, animated: false)

    // Dismiss AVPlayerViewController
    dismiss(animated: true) {
        // do what you want
    }
}
</code>```

Does this give you the results you were looking for ?

Body:
I try to play a video and I want to switch to a new storyboard afterwards. But for some reason the pushViewController is not doing anything.

I will appreciate any hint to get this running. Thank you all.

View Controller File

class ViewController: UIViewController, WKNavigationDelegate {

    let playerController = AVPlayerViewController()

    private func playVideo() {
        guard let path = Bundle.main.path(forResource: "screen3", ofType: "mp4" ) else {
            debugPrint("video missing")
            return
        }

        let player = AVPlayer(url: URL(fileURLWithPath: path) )

        playerController.showsPlaybackControls = false
        playerController.player = player
        playerController.videoGravity = .resizeAspectFill

        NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem )

        present(playerController, animated: true ) {
            player.play()
        }

    }

    @objc func playerDidFinishPlaying(note: NSNotification ) {
        print("Video finished")

        let vc = UIStoryboard.init(name: "Alternate", bundle: Bundle.main).instantiateViewController(withIdentifier: "SecondVC") as? SecondVC

        self.navigationController?.pushViewController(vc!, animated: false)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        playVideo()

    }

}

SecondVC

    class SecondVC: UIViewController {

    override func viewDidLoad() {

        print("alterante")
        super.viewDidLoad()
        view.backgroundColor = .link
    }

}

Body:
I believe this is what is happening:

You have a Navigation Controller which contains UIViewController

You present the AVPlayerViewController on top of the UIViewController and its UINavigationController

When you push the SecondVC, it is over UIViewController and its UINavigationController but under AVPlayerViewController so you don't see it

Why don't you update your playerDidFinishPlaying function to something like this:

@objc
func playerDidFinishPlaying(note: NSNotification ) {
    print("Video finished")

    let vc = UIStoryboard.init(name: "Alternate",
                               bundle: Bundle.main)
        .instantiateViewController(withIdentifier: "SecondVC") as? SecondVC

    // Push SecondVC
    self.navigationController?.pushViewController(vc!, animated: false)

    // Dismiss AVPlayerViewController
    dismiss(animated: true) {
        // do what you want
    }
}

Does this give you the results you were looking for ?


问:
converting images to movies using ffmpeg - passing wildcards to ffmpeg glob -i input using Bash
I have a number of non-sequentially numbered image jpgs which have the same starting string and can be identified by eg

```<code>ls car_drive*.jpg

</code>```

I can assemble into a movie using my bash function as follows which works well

```<code>ffimage2movie_scaling() {
echo "files input in double quotes"
echo "input and output file "
/usr/bin/nice ffmpeg -pix_fmt yuv420p -v quiet -framerate 9 -pattern_type \
glob -i "$1" -c:v libx264 -vf "scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2"  "$2"

}
export -f ffimage2movie_scaling

</code>```

invoked as

```<code>ffimage2movie_scaling "car_drive*.*" output.mp4

</code>```

I want to implement this so that I can use the stem term "car_drive" to prefix the output mp4 using the following slight edit of the previous function

```<code>prepare_video_from_images () {
inputStem="$1"
inputFile="$1""*.*"
echo "$inputFile"
outputFile="movie_""$inputStem"".mp4"

/usr/bin/nice ffmpeg -pix_fmt yuv420p -v quiet -framerate 9 -pattern_type \
glob -i "$inputFile"  \
 -c:v libx264 -vf "scale='min(1280,iw)':min'(720,ih)':force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2" -crf 18 "$outputFile"
}
export -f prepare_video_from_images

</code>```

However no variant of presenting glob -i with the equivalent input seems to work.  I've tried shopt -s/u extglob,  set -/+f,  adding " wrap around etc etc .  All help greatly appreciated to get it working

答:
Bit of lateral thinking,   I took the glob input that worked in the first example, input it and then carved it up with sed / cut to give me the stem which I could then use in naming the output file.

```<code>prepare_video_from_images () {
inputStem="$1"
outputStem=$(echo "$inputStem" | sed 's/\*//' | cut -d. -f1 )
echo "$outputStem"
outputFile="movie_""$outputStem"".mp4"

/usr/bin/nice ffmpeg  -pix_fmt yuv420p -v quiet -framerate 9 -pattern_type \
glob -i "$inputStem"  \
 -c:v libx264 -vf "scale='min(1280,iw)':min'(720,ih)':force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2" -crf 18 "$outputFile"
}

</code>```

invoked as before  by

```<code>prepare_video_from_images "car_drive*.jp*g"

</code>```

Body:
I have a number of non-sequentially numbered image jpgs which have the same starting string and can be identified by eg

ls car_drive*.jpg

I can assemble into a movie using my bash function as follows which works well

ffimage2movie_scaling() {
echo "files input in double quotes"
echo "input and output file "
/usr/bin/nice ffmpeg -pix_fmt yuv420p -v quiet -framerate 9 -pattern_type \
glob -i "$1" -c:v libx264 -vf "scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2"  "$2"

}
export -f ffimage2movie_scaling

invoked as

ffimage2movie_scaling "car_drive*.*" output.mp4

I want to implement this so that I can use the stem term "car_drive" to prefix the output mp4 using the following slight edit of the previous function

prepare_video_from_images () {
inputStem="$1"
inputFile="$1""*.*"
echo "$inputFile"
outputFile="movie_""$inputStem"".mp4"

/usr/bin/nice ffmpeg -pix_fmt yuv420p -v quiet -framerate 9 -pattern_type \
glob -i "$inputFile"  \
 -c:v libx264 -vf "scale='min(1280,iw)':min'(720,ih)':force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2" -crf 18 "$outputFile"
}
export -f prepare_video_from_images

However no variant of presenting glob -i with the equivalent input seems to work.  I've tried shopt -s/u extglob,  set -/+f,  adding " wrap around etc etc .  All help greatly appreciated to get it working

Body:
Bit of lateral thinking,   I took the glob input that worked in the first example, input it and then carved it up with sed / cut to give me the stem which I could then use in naming the output file.

prepare_video_from_images () {
inputStem="$1"
outputStem=$(echo "$inputStem" | sed 's/\*//' | cut -d. -f1 )
echo "$outputStem"
outputFile="movie_""$outputStem"".mp4"

/usr/bin/nice ffmpeg  -pix_fmt yuv420p -v quiet -framerate 9 -pattern_type \
glob -i "$inputStem"  \
 -c:v libx264 -vf "scale='min(1280,iw)':min'(720,ih)':force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2" -crf 18 "$outputFile"
}

invoked as before  by

prepare_video_from_images "car_drive*.jp*g"


问:
In Rails 3, how do I implement breadcrumbs with multiple paths to nodes?
In our application, various articles can be reached via a number of paths.

You could, for example, go
"home > category 'rock music' > article 'Behind the Beatles'",

or "home > category 'pop music' > article 'Behind the Beatles'",

or even "home > magazine > series 'background' > article 'Behind the Beatles'"

and reach the same article every time.

I'm guessing I need to save the path the user takes in the session, and push / pop individual elements, but I'm hoping someone somewhere already has a working solution.

I checked out the following gems already: crummy, breadcrumbs-on-rails and gretel, and (barring me misunderstanding the documention) they all seem to expect a single path to a node.

答:
I would recommend that you don't do what you are proposing. Search engines recognise breadcrumbs (with use of proper tags). What you're talking about sounds more like related navigable content 'See also...'.

If you decide this is really what you want to do, have separate routes and noindex tags on one of the pages.


问:
Fetch returns unresolved `[object Response]`
I am trying to fetch the latest blog posts from Hubspot using their API and to do so I have to consume 2 endpoints (1 for the blog posts and 1 for the tag info for each blog post).

The first call brings back the latest blog posts. Then, for each blog post I need to retrieve the info for its tag, that the post has.

Below is the code that implements what described above,

```<code>  async getBlogs(contentGroupID: string = null, limit: number = null) {
    this.url = 'https://api.hubapi.com/cms/v3/blogs/posts?state=PUBLISHED&sort=-publish_date';

    const posts = await useFetch(
      this.url
      + '&hapikey=' + this.HS_API_KEY
      + (contentGroupID ? '&content_group_id=' + contentGroupID : null)
      + (limit ? '&limit=' + limit : null)
    ).then(response => {
      return response;
    });

    const tags = (posts.data.value as any).results.map(post => fetch(`https://api.hubapi.com/blogs/v3/topics/${post.tagIds[0]+'?hapikey='+this.HS_API_KEY}`));
    const taggs = await Promise.all(tags);

    const payload = new Object();

    payload['blogPosts'] = posts;
    payload['tags'] = taggs;

    return payload;
  }
</code>```

And here's the response at the Browser

As shown in screenshot above, the blogPosts object has been resolved just fine but the Promise.all() part to retrieve the tagIds[0] hasn't. It returns [object Response].

I have tried several different ways to do this and each one is always returning the Promise object unresolved.
What is the correct way to do this and get the actual data?

Just to give an example of what the tag data object looks like, for the tag with id 41520763199 its data is as shown below. This is what I should be getting as a response instead of the promise object.

```<code>{
    "categoryId": 3,
    "contentIds": [],
    "created": 1613125431347,
    "deletedAt": 0,
    "description": "",
    "id": 41520763199,
    "language": "en-us",
    "name": "Case Studies",
    "portalId": 2734675,
    "slug": "case-studies",
    "translations": {},
    "updated": 1616091635999
}
</code>```

答:
It's not returning a promise. The promise is resolved to a Response object as per this fetchAPI resource

One of the methods that you will find useful is Response.json that returns a promise that resolves with the result of parsing the response body text as JSON

As an example:

```<code>const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
</code>```

will result in response being a Response object.

```<code> Response {type: 'basic', url: 'https://jsonplaceholder.typicode.com/todos/1', redirected: false, status: 200, ok: true, …}
</code>```

Now calling:

```<code>const json = await response.json()
</code>```

Will result in json being your actual response:

```<code>{userId: 1, id: 1, title: 'delectus aut autem', completed: false}
</code>```

Body:
I am trying to fetch the latest blog posts from Hubspot using their API and to do so I have to consume 2 endpoints (1 for the blog posts and 1 for the tag info for each blog post).

The first call brings back the latest blog posts. Then, for each blog post I need to retrieve the info for its tag, that the post has.

Below is the code that implements what described above,

  async getBlogs(contentGroupID: string = null, limit: number = null) {
    this.url = 'https://api.hubapi.com/cms/v3/blogs/posts?state=PUBLISHED&sort=-publish_date';

    const posts = await useFetch(
      this.url
      + '&hapikey=' + this.HS_API_KEY
      + (contentGroupID ? '&content_group_id=' + contentGroupID : null)
      + (limit ? '&limit=' + limit : null)
    ).then(response => {
      return response;
    });

    const tags = (posts.data.value as any).results.map(post => fetch(`https://api.hubapi.com/blogs/v3/topics/${post.tagIds[0]+'?hapikey='+this.HS_API_KEY}`));
    const taggs = await Promise.all(tags);

    const payload = new Object();

    payload['blogPosts'] = posts;
    payload['tags'] = taggs;

    return payload;
  }

And here's the response at the Browser

As shown in screenshot above, the blogPosts object has been resolved just fine but the Promise.all() part to retrieve the tagIds[0] hasn't. It returns [object Response].

I have tried several different ways to do this and each one is always returning the Promise object unresolved.
What is the correct way to do this and get the actual data?

Just to give an example of what the tag data object looks like, for the tag with id 41520763199 its data is as shown below. This is what I should be getting as a response instead of the promise object.

{
    "categoryId": 3,
    "contentIds": [],
    "created": 1613125431347,
    "deletedAt": 0,
    "description": "",
    "id": 41520763199,
    "language": "en-us",
    "name": "Case Studies",
    "portalId": 2734675,
    "slug": "case-studies",
    "translations": {},
    "updated": 1616091635999
}

Body:
It's not returning a promise. The promise is resolved to a Response object as per this fetchAPI resource

One of the methods that you will find useful is Response.json that returns a promise that resolves with the result of parsing the response body text as JSON

As an example:

const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')

will result in response being a Response object.

 Response {type: 'basic', url: 'https://jsonplaceholder.typicode.com/todos/1', redirected: false, status: 200, ok: true, …}

Now calling:

const json = await response.json()

Will result in json being your actual response:

{userId: 1, id: 1, title: 'delectus aut autem', completed: false}