问:
Why is NGINX only executing the last if statement and not the others?
I am trying to troubleshoot why NGINX is only executing the last if statement and adding the header that I specified. I tried adding a header to each statement, but only the last one is being executed. I am attempting to create a link where each commit redirects to an S3 bucket with the app files. A simmilar URL for this is https://17de2b5.xxx-123.test.domain-dev.com/auth.

```<code>server {
    listen 80 default_server;
    listen [::]:80 default_server;

    access_log /dev/stdout;
    error_log /dev/stdout;
    server_name _;

    # resolve using Google's DNS server to force DNS resolution and prevent caching of IPs
    resolver 8.8.8.8 valid=20s;

    ##
    # Gzip Settings
    ##
    gzip on;
    gzip_http_version 1.1;
    gzip_disable      "MSIE [1-6]\.";
    gzip_min_length   1100;
    gzip_vary         on;
    gzip_proxied      any;
    gzip_types        text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_comp_level   9;

    # Enable byte-range support for both cached and uncached responses
    proxy_force_ranges on;

    # Static files caching
    expires $expires;

    location ^~ /ping {
        return 200 "OK";
    }

    location / {
          if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            #
            # Custom headers and headers various browsers *should* be OK with but aren't
            #
            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            #
            # Tell client that this pre-flight info is valid for 20 days
            #
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }

        if ($request_method = 'GET') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        }

        set $bucket "${BUCKET}";
        set $domain "${DOMAIN}";

        add_header X-debug-bucket-is $bucket always;
        add_header X-debug-domain-is $domain always;
        add_header X-debug-escape-domain-is ${ESC_DOMAIN} always;

        set $s3location http://$bucket/${BUCKET_FOLDER_PREFIX}/master/index.html;

        # matches: commit.branch-name.subdomain.domain
        if ($host ~ ^([^.]*)\.([^.]*)\.([^.]*)\.${ESC_DOMAIN}) {
            add_header X-TEST-matchescommitbranch-namesubdomaindomain only-true;
            set $commit $1;
            set $branch $2;
            set $subdomain $3;
            set $s3location http://$bucket/branchBuilds/$branch/$commit;
        }

        # matches: branch-name.subdomain.domain
        if ($host ~ ^([^.]*)\.([^.]*)\.${ESC_DOMAIN}) {
            add_header X-TEST-matchesbranch-namesubdomaindomain only-true;
            set $branch $1;
            set $subdomain $2;
            set $s3location http://$bucket/branchBuilds/$branch;
        }

        # matches subdomain
        if ($host ~ ^([^.]*)\.${ESC_DOMAIN}) {
            add_header X-TEST-matchessubdomain only-true;
            set $subdomain $1;
            set $s3location http://$bucket/${BUCKET_FOLDER_PREFIX}/master;
        }

        # matches domain
        if ($host ~ ${ESC_DOMAIN}) {
            add_header X-TEST-matchesdomain only-true;
            set $branch $1;
            set $s3location http://$bucket/${BUCKET_FOLDER_PREFIX}/master;
        }

        add_header X-debug-s3-is $s3location always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

        if ($uri ~* "\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|otf|woff|woff2|svg|eot)") {
            add_header Access-Control-Allow-Origin *;
            proxy_pass $s3location$uri;
        }

        proxy_pass $s3location/$INDEX_FILE;

        proxy_intercept_errors on;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_hide_header x-amz-id-2;
        proxy_hide_header x-amz-request-id;
    }
}
</code>```

I tried adding headers in each if statement, and I expected each location to show the corresponding headers. However, only the headers for the last one appear. I also tried specifying the exact address without using regex, but the issue persists.

Body:
I am trying to troubleshoot why NGINX is only executing the last if statement and adding the header that I specified. I tried adding a header to each statement, but only the last one is being executed. I am attempting to create a link where each commit redirects to an S3 bucket with the app files. A simmilar URL for this is https://17de2b5.xxx-123.test.domain-dev.com/auth.

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    access_log /dev/stdout;
    error_log /dev/stdout;
    server_name _;

    # resolve using Google's DNS server to force DNS resolution and prevent caching of IPs
    resolver 8.8.8.8 valid=20s;

    ##
    # Gzip Settings
    ##
    gzip on;
    gzip_http_version 1.1;
    gzip_disable      "MSIE [1-6]\.";
    gzip_min_length   1100;
    gzip_vary         on;
    gzip_proxied      any;
    gzip_types        text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_comp_level   9;

    # Enable byte-range support for both cached and uncached responses
    proxy_force_ranges on;

    # Static files caching
    expires $expires;

    location ^~ /ping {
        return 200 "OK";
    }

    location / {
          if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            #
            # Custom headers and headers various browsers *should* be OK with but aren't
            #
            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            #
            # Tell client that this pre-flight info is valid for 20 days
            #
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }

        if ($request_method = 'GET') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        }

        set $bucket "${BUCKET}";
        set $domain "${DOMAIN}";

        add_header X-debug-bucket-is $bucket always;
        add_header X-debug-domain-is $domain always;
        add_header X-debug-escape-domain-is ${ESC_DOMAIN} always;

        set $s3location http://$bucket/${BUCKET_FOLDER_PREFIX}/master/index.html;

        # matches: commit.branch-name.subdomain.domain
        if ($host ~ ^([^.]*)\.([^.]*)\.([^.]*)\.${ESC_DOMAIN}) {
            add_header X-TEST-matchescommitbranch-namesubdomaindomain only-true;
            set $commit $1;
            set $branch $2;
            set $subdomain $3;
            set $s3location http://$bucket/branchBuilds/$branch/$commit;
        }

        # matches: branch-name.subdomain.domain
        if ($host ~ ^([^.]*)\.([^.]*)\.${ESC_DOMAIN}) {
            add_header X-TEST-matchesbranch-namesubdomaindomain only-true;
            set $branch $1;
            set $subdomain $2;
            set $s3location http://$bucket/branchBuilds/$branch;
        }

        # matches subdomain
        if ($host ~ ^([^.]*)\.${ESC_DOMAIN}) {
            add_header X-TEST-matchessubdomain only-true;
            set $subdomain $1;
            set $s3location http://$bucket/${BUCKET_FOLDER_PREFIX}/master;
        }

        # matches domain
        if ($host ~ ${ESC_DOMAIN}) {
            add_header X-TEST-matchesdomain only-true;
            set $branch $1;
            set $s3location http://$bucket/${BUCKET_FOLDER_PREFIX}/master;
        }

        add_header X-debug-s3-is $s3location always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

        if ($uri ~* "\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|otf|woff|woff2|svg|eot)") {
            add_header Access-Control-Allow-Origin *;
            proxy_pass $s3location$uri;
        }

        proxy_pass $s3location/$INDEX_FILE;

        proxy_intercept_errors on;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_hide_header x-amz-id-2;
        proxy_hide_header x-amz-request-id;
    }
}

I tried adding headers in each if statement, and I expected each location to show the corresponding headers. However, only the headers for the last one appear. I also tried specifying the exact address without using regex, but the issue persists.


来源: stackexchange

问:
Dynamic Screens with React Navigation Top Tab Navigator state.routes[index].name undefined and scroll behaviour?
I have two problems that seem to be related. I'm using a MaterialTopTabNavigator with tabBarScrollEnabled. It works fine when I initially have my screens under it. But in my final screen I have a button that marks the flow "complete", which should update the top tab navigator to not list the previous tabs. That part all works surprisingly well, but I'm running into 2 issues on iOS (possibly android as well, but I only have a simulator for that and it appears to work correctly there). The first is that after clicking the complete button it drops to the proper single tab at the top, but it still allows scroll to the left, which then throws an exception that "undefined is not an object (evaluating 'state.routes[index].name')". The second is that if I click complete, and then click it again to mark it incomplete again the Screen stays on the "Final" screen, but the Top Tab Navigator shows that it is in on the first screen, and if I scroll left it pops the same "undefined is not an object (evaluating 'state.routes[index].name').

I've attempted to reduce the issue to the following snack:
https://snack.expo.dev/@linkeddg/materialtoptabnavigator-issue?platform=ios

ContentLicense: CC BY-SA 4.0


问:
zoom webBrowser when embedded by pdf
Is there a way to zoom webbrowser when it loaded by pdf file.

I tried some code but it didn't work.

Like:

```<code>private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        webBrowser1.Document.Body.Style = "zoom:300%";
    }
</code>```

Also:

```<code>int zoomFactor = 300;
((SHDocVw.WebBrowser)webBrowser1.ActiveXInstance).ExecWB(SHDocVw.OLECMDID.OLECMDID_OPTICAL_ZOOM,
    SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, zoomFactor, IntPtr.Zero);
</code>```

This works when you open link like google.com etc. But in my case my web browser display PDF file.

Title: zoom webBrowser when embedded by pdf

Body:
Is there a way to zoom webbrowser when it loaded by pdf file.

I tried some code but it didn't work.

Like:

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        webBrowser1.Document.Body.Style = "zoom:300%";
    }

Also:

int zoomFactor = 300;
((SHDocVw.WebBrowser)webBrowser1.ActiveXInstance).ExecWB(SHDocVw.OLECMDID.OLECMDID_OPTICAL_ZOOM,
    SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, zoomFactor, IntPtr.Zero);

This works when you open link like google.com etc. But in my case my web browser display PDF file.


问:
NextJS rewrites error while proxying a request to the backend
I'm trying to proxy a request to a backend with Next rewrites.

next.config.js:

```<code>async rewrites() {
  return [
    {
      source: "/api/:path*",
      destination: "http://somedomain.loc/api/:path*",
    },
  ]
},
</code>```

/etc/host:

```<code>127.0.0.1  somedomain.loc
</code>```

and in the end i get this error:

```<code>Failed to proxy http://somedomain.loc/api/offers Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 80
}
error - Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 80
}
</code>```

While if you make a request via postman or directly from the browser, everything works fine.

Please help me understand what is the problem here.

tried:
Proxy request to backend
expected:
The request is proxied to the backend
as a result:
Proxy error

Body:
I'm trying to proxy a request to a backend with Next rewrites.

next.config.js:

async rewrites() {
  return [
    {
      source: "/api/:path*",
      destination: "http://somedomain.loc/api/:path*",
    },
  ]
},

/etc/host:

127.0.0.1  somedomain.loc

and in the end i get this error:

Failed to proxy http://somedomain.loc/api/offers Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 80
}
error - Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 80
}

While if you make a request via postman or directly from the browser, everything works fine.

Please help me understand what is the problem here.

tried:
Proxy request to backend
expected:
The request is proxied to the backend
as a result:
Proxy error


问:
VLC MediaPlayer stops after a MediaList element and hangs, how can I restart it seamlessly?
I've got a vlc python program that I'd like load up a media list with multiple elements. If a clip (A) that I've defined as 'primary' is playing, it simply repeats. When I interrupt that with a different clip (B), I want to jump seamlessly to that clipB, then when clipB ends, jump back to the time that clipA left off. This will happen in fullscreen on a raspi4.

Here's the class for this so far (I've removed the fullscreen call for the moment):

```<code>from Colleague import Colleague
import vlc

class MyPlayer(Colleague):

    def __init__(self, mediator):
        super().__init__(mediator)
        # init the list
        self.media_list = vlc.MediaList()
        # make the players
        self.initializeVLCElements()
        # create clip end data
        self.ClipFinishedData = {'previousMediaIndex': 0, 'previousStopTime': 0}

    def addMedia(self, mediaElement):
        """Add media to the media list as it gets passed in, then log the index
        """
        # Set the index
        mediaElement.setIndex(self.media_list.count())
        # get the media
        new_media = vlc.Media(mediaElement.getPath())
        new_media.parse()
        self.media_list.add_media(new_media)

    def initializeVLCElements(self):
        self.main_instance = vlc.Instance()
        # create list player
        self.list_player = self.main_instance.media_list_player_new()
        # assign list to list player
        self.list_player.set_media_list(self.media_list)
        self.list_player.set_playback_mode(2)
        # get the list player media player
        self.media_player = self.list_player.get_media_player()
        # set up event managers
        events = self.media_player.event_manager()
        events.event_attach(vlc.EventType.MediaPlayerEndReached, self.clipFinishedEvent)

    def playMediaElement(self, mediaElement):
        if  mediaElement.getType() in ['default', 'primary']:
            self.playPrimaryElement(mediaElement.getIndex())
        else:
            self.playOverlayElement(mediaElement.getIndex())

    def playPrimaryElement(self, index):
        logging.info('play primary')
        self.list_player.play_item_at_index(index)
        self.ClipFinishedData['previousMediaIndex'] = index
        self.ClipFinishedData['previousStopTime'] = 0

    def playOverlayElement(self, index):
        logging.info('play overlay')
        self.ClipFinishedData['previousStopTime'] = self.media_player.get_time()
        self.list_player.play_item_at_index(index)
        print('Prev video stopped at: ', self.ClipFinishedData['previousStopTime'])

    def restartPreviousElement(self):
        print(self.media_player.get_state()) # <-- this prints State.Stopped
        #### program hangs here...
        self.list_player.play_item_at_index(self.ClipFinishedData['previousMediaIndex'])
        self.media_player.set_time(self.ClipFinishedData['previousStopTime'])

        self.ClipFinishedData['previousStopTime'] = 0
        self.ClipFinishedData['loopCurrent'] = True

    def clipFinishedEvent(self, event):
        self.restartPreviousElement()
</code>```

I'm logging the departure time from the prior media, then on a clipFinishedEvent I'm restarting. If it's an overlay - I don't log the departure time and index in the playlist, so it should go back, otherwise the index is logged and the time is set to zero to repeat the media.

If I kill the player or create a new one, there's a flash frame, or other issue and I'd much prefer this to be just jumping around the playlist.

Any help here would be great.

Body:
I've got a vlc python program that I'd like load up a media list with multiple elements. If a clip (A) that I've defined as 'primary' is playing, it simply repeats. When I interrupt that with a different clip (B), I want to jump seamlessly to that clipB, then when clipB ends, jump back to the time that clipA left off. This will happen in fullscreen on a raspi4.

Here's the class for this so far (I've removed the fullscreen call for the moment):

from Colleague import Colleague
import vlc

class MyPlayer(Colleague):

    def __init__(self, mediator):
        super().__init__(mediator)
        # init the list
        self.media_list = vlc.MediaList()
        # make the players
        self.initializeVLCElements()
        # create clip end data
        self.ClipFinishedData = {'previousMediaIndex': 0, 'previousStopTime': 0}

    def addMedia(self, mediaElement):
        """Add media to the media list as it gets passed in, then log the index
        """
        # Set the index
        mediaElement.setIndex(self.media_list.count())
        # get the media
        new_media = vlc.Media(mediaElement.getPath())
        new_media.parse()
        self.media_list.add_media(new_media)

    def initializeVLCElements(self):
        self.main_instance = vlc.Instance()
        # create list player
        self.list_player = self.main_instance.media_list_player_new()
        # assign list to list player
        self.list_player.set_media_list(self.media_list)
        self.list_player.set_playback_mode(2)
        # get the list player media player
        self.media_player = self.list_player.get_media_player()
        # set up event managers
        events = self.media_player.event_manager()
        events.event_attach(vlc.EventType.MediaPlayerEndReached, self.clipFinishedEvent)

    def playMediaElement(self, mediaElement):
        if  mediaElement.getType() in ['default', 'primary']:
            self.playPrimaryElement(mediaElement.getIndex())
        else:
            self.playOverlayElement(mediaElement.getIndex())

    def playPrimaryElement(self, index):
        logging.info('play primary')
        self.list_player.play_item_at_index(index)
        self.ClipFinishedData['previousMediaIndex'] = index
        self.ClipFinishedData['previousStopTime'] = 0

    def playOverlayElement(self, index):
        logging.info('play overlay')
        self.ClipFinishedData['previousStopTime'] = self.media_player.get_time()
        self.list_player.play_item_at_index(index)
        print('Prev video stopped at: ', self.ClipFinishedData['previousStopTime'])

    def restartPreviousElement(self):
        print(self.media_player.get_state()) # <-- this prints State.Stopped
        #### program hangs here...
        self.list_player.play_item_at_index(self.ClipFinishedData['previousMediaIndex'])
        self.media_player.set_time(self.ClipFinishedData['previousStopTime'])

        self.ClipFinishedData['previousStopTime'] = 0
        self.ClipFinishedData['loopCurrent'] = True

    def clipFinishedEvent(self, event):
        self.restartPreviousElement()

I'm logging the departure time from the prior media, then on a clipFinishedEvent I'm restarting. If it's an overlay - I don't log the departure time and index in the playlist, so it should go back, otherwise the index is logged and the time is set to zero to repeat the media.

If I kill the player or create a new one, there's a flash frame, or other issue and I'd much prefer this to be just jumping around the playlist.

Any help here would be great.


问:
Network error when posting formData in react native
Network error when posting formData in react native  "0.70.5" and FLIPPER_VERSION=0.125.0

```<code> const data = new FormData();
    data.append('title', title);
    data.append('description', description);
    data.append('categoryId', categoryId);
    data.append('startDate', date);
    data.append('endDate', endDate);

     data.append('displayImage', {
       uri: secondImage[0].uri,
       name: displayImage,
       type:'image/jpeg'
    })
</code>```
```<code>
    const res = await axios
      .post(`${Base_URL}/events`, data, {
        headers: {
          "Content-Type": "multipart/form-data",
          'token': JSON.parse(token)
        }
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
        // handle error
      });

</code>```

i downgraded react native version still same isssue

i  changed FLIPPER_VERSION from FLIPPER_VERSION=0.125.0 to FLIPPER_VERSION=0.46.0. i get the error Could not find com.facebook.flipper:flipper:0.46.0.

Body:
Network error when posting formData in react native  "0.70.5" and FLIPPER_VERSION=0.125.0

 const data = new FormData();
    data.append('title', title);
    data.append('description', description);
    data.append('categoryId', categoryId);
    data.append('startDate', date);
    data.append('endDate', endDate);

     data.append('displayImage', {
       uri: secondImage[0].uri,
       name: displayImage,
       type:'image/jpeg'
    })

    const res = await axios
      .post(`${Base_URL}/events`, data, {
        headers: {
          "Content-Type": "multipart/form-data",
          'token': JSON.parse(token)
        }
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
        // handle error
      });

i downgraded react native version still same isssue

i  changed FLIPPER_VERSION from FLIPPER_VERSION=0.125.0 to FLIPPER_VERSION=0.46.0. i get the error Could not find com.facebook.flipper:flipper:0.46.0.


问:
Tab layout and Nav drawer
I am creating a navigation drawer for my app. The goal is for it to have 2 tabs, 1 with a recyclerview with clickable textviews, and one with a recyclerview with clickable webviews. My activity contains a swipable webview. When an item of the navigation drawer is clicked, it should direct me to the related webview. Is there a way to set it up, without the 2 views being different fragments?

So far, I have only created the first recyclerview, and have successfully made it clickable

The picture posted down below is what I am going for

My xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".presentation.activity.book.BookActivity">

<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<com.google.android.material.navigation.NavigationView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true">

            <androidx.core.widget.NestedScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical" >

                    <androidx.recyclerview.widget.RecyclerView
                        android:id="@+id/rvSideMenu"
                    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:visibility="visible"
                        android:layout_marginStart="16dp"
                        app:layout_constraintBottom_toBottomOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toBottomOf="@+id/ibSideMenu" />

                </LinearLayout>

            </androidx.core.widget.NestedScrollView>

</com.google.android.material.navigation.NavigationView>
</code>```

Title: Tab layout and Nav drawer

Body:
I am creating a navigation drawer for my app. The goal is for it to have 2 tabs, 1 with a recyclerview with clickable textviews, and one with a recyclerview with clickable webviews. My activity contains a swipable webview. When an item of the navigation drawer is clicked, it should direct me to the related webview. Is there a way to set it up, without the 2 views being different fragments?

So far, I have only created the first recyclerview, and have successfully made it clickable

The picture posted down below is what I am going for

My xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".presentation.activity.book.BookActivity">

<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<com.google.android.material.navigation.NavigationView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true">

            <androidx.core.widget.NestedScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical" >

                    <androidx.recyclerview.widget.RecyclerView
                        android:id="@+id/rvSideMenu"
                    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:visibility="visible"
                        android:layout_marginStart="16dp"
                        app:layout_constraintBottom_toBottomOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toBottomOf="@+id/ibSideMenu" />

                </LinearLayout>

            </androidx.core.widget.NestedScrollView>

</com.google.android.material.navigation.NavigationView>


问:
In memory buffer with write() and readline()
I want to store byte data I’m getting into an in memory buffer. I want to then call a method to receive a line from that buffer, similar to readline(), whilst also removing it from the buffer.

Is there an existing python class that I can use that will achieve this?

I’m staying away from decoding the bytes to a string, and string.split(‘\n’) because it can fail if an escaped new line character exists in that string etc. The readline() is more complicated and capable than a split().

I’ve looked at io.BytesIO but it doesn’t satisfy all my requirements, mainly because the readline() method doesn’t remove the returned line from the buffer.


问:
Firebase auth type error with typescript in react
I'm following this article:https://dev.to/vikirobles/react-authentication-with-firebase-v9-typescript-and-yup-4025

Yet I get this error:

```<code>Argument of type 'User' is not assignable to parameter of type 'SetStateAction<User | null>'.
Type 'firebase.default.User' is not assignable to type 'import("C:/Users/josht/Documents/invoice-ts/node_modules/@firebase/auth/dist/auth-public").User'.
    Types of property 'providerData' are incompatible.
      Type '(UserInfo | null)[]' is not assignable to type 'UserInfo[]'.
        Type 'UserInfo | null' is not assignable to type 'UserInfo'.
          Type 'null' is not assignable to type 'UserInfo'.ts(2345)
</code>```

When I do this:

```<code>  const authListener = () => {
    auth.onAuthStateChanged((user) => {
      if (user && user.emailVerified) {
        setUser(user);
      } else {
        setUser(null);
      }
      setFirebaseLoaded(true);
    });
  };
</code>```

This is the full component:

```<code>import React, { createContext, useEffect, useState } from "react";
import { auth } from "./Fire";
// import { User  } from "firebase/auth/dist/auth";
// import { User } from "@firebase/auth/dist/auth-public";
import { Auth, User } from 'firebase/auth'

interface IStore {
    auth: Auth,
    user: User,
    setUser: React.Dispatch<React.SetStateAction<User>>,
    firebaseLoaded: boolean
}

export const StoreContext = createContext<IStore | null>(null);

interface Props {
    children: React.ReactNode
}

const ContextAppProvider: React.FC<Props> = (props) => {
  const [user, setUser] = useState<User | null>(null);
  const [firebaseLoaded, setFirebaseLoaded] = useState(false);

  const authListener = () => {
    auth.onAuthStateChanged((user) => {
      if (user && user.emailVerified) {
        setUser(user);
      } else {
        setUser(null);
      }
      setFirebaseLoaded(true);
    });
  };

  useEffect(() => {
    authListener();
  }, []);

  return (
    <StoreContext.Provider
      value={{
         user,
         setUser,
         firebaseLoaded
      }}
    >
      {props.children}
    </StoreContext.Provider>
  );
};
export default ContextAppProvider;
</code>```

I am using firebase v9.15.0

Body:
I'm following this article:https://dev.to/vikirobles/react-authentication-with-firebase-v9-typescript-and-yup-4025

Yet I get this error:

Argument of type 'User' is not assignable to parameter of type 'SetStateAction<User | null>'.
Type 'firebase.default.User' is not assignable to type 'import("C:/Users/josht/Documents/invoice-ts/node_modules/@firebase/auth/dist/auth-public").User'.
    Types of property 'providerData' are incompatible.
      Type '(UserInfo | null)[]' is not assignable to type 'UserInfo[]'.
        Type 'UserInfo | null' is not assignable to type 'UserInfo'.
          Type 'null' is not assignable to type 'UserInfo'.ts(2345)

When I do this:

  const authListener = () => {
    auth.onAuthStateChanged((user) => {
      if (user && user.emailVerified) {
        setUser(user);
      } else {
        setUser(null);
      }
      setFirebaseLoaded(true);
    });
  };

This is the full component:

import React, { createContext, useEffect, useState } from "react";
import { auth } from "./Fire";
// import { User  } from "firebase/auth/dist/auth";
// import { User } from "@firebase/auth/dist/auth-public";
import { Auth, User } from 'firebase/auth'

interface IStore {
    auth: Auth,
    user: User,
    setUser: React.Dispatch<React.SetStateAction<User>>,
    firebaseLoaded: boolean
}

export const StoreContext = createContext<IStore | null>(null);

interface Props {
    children: React.ReactNode
}

const ContextAppProvider: React.FC<Props> = (props) => {
  const [user, setUser] = useState<User | null>(null);
  const [firebaseLoaded, setFirebaseLoaded] = useState(false);

  const authListener = () => {
    auth.onAuthStateChanged((user) => {
      if (user && user.emailVerified) {
        setUser(user);
      } else {
        setUser(null);
      }
      setFirebaseLoaded(true);
    });
  };

  useEffect(() => {
    authListener();
  }, []);

  return (
    <StoreContext.Provider
      value={{
         user,
         setUser,
         firebaseLoaded
      }}
    >
      {props.children}
    </StoreContext.Provider>
  );
};
export default ContextAppProvider;

I am using firebase v9.15.0


问:
Assets Empty in Unity Remote Project
I Downloaded the projects that i have on the cloud but they are empty when i open, no assets whatsoever

No erros apear the files are just missing

It used to work and download the files.

After the end of colab i could at least download the saves but now the are reported to be there but dont apear

Title: Assets Empty in Unity Remote Project


问:
Vectorbt type object 'DOMWidget' has no attribute '_ipython_display_'
So I'm trying to plot a simple RSI indicator in Python using the Vectorbt library. The RSI plots correctly but there's an error that comes with it.
As can be seen here
`

```<code>#nilagyan ng r para raw file dahil nababasa ng python as UNICODE pag may slash tapos U ang kasunod
df = pd.read_csv(r"C:\Users\Mark\Documents\Trading\BTC-2021min\BTC-2021min.csv")

#dahil ang unix code ay about sa time, cinonvert sa seconds para magkaroon ng column na date
#basically nag add tayo ng COLUMN or Data Frame na pangalan ay date
df["date"] = pd.to_datetime(df["unix"], unit = "s")

#nanggawa ng column at index na date at time kaya nakaSET ang INDEX sa DATE
df.set_index("date", inplace=True)

#aggregation ng 1 minute candles into something bigger, sakin ay 15 minutes kaya 15T
df = df.resample("15T").agg({
    "open":"first",
    "high": "max",
    "low": "min",
    "close": "last",
})

#this makes it go through only a specific date rather than the whole csv file, start date at end date lang
df = df.loc["2021-10-01":"2021-10-31"]

rsi = vbt.RSI.run(df.close, window=8)

rsi.plot()
</code>```

When I run this using Jupyter notebook, I encounter this error:

```<code>`

AttributeError                            Traceback (most recent call last)
File c:\Users\Mark\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\formatters.py:920, in IPythonDisplayFormatter.__call__(self, obj)
    918 method = get_real_method(obj, self.print_method)
    919 if method is not None:
--> 920     method()
    921     return True

File c:\Users\Mark\AppData\Local\Programs\Python\Python310\lib\site-packages\plotly\basewidget.py:741, in BaseFigureWidget._ipython_display_(self)
    737 """
    738 Handle rich display of figures in ipython contexts
    739 """
    740 # Override BaseFigure's display to make sure we display the widget version
--> 741 widgets.DOMWidget._ipython_display_(self)

AttributeError: type object 'DOMWidget' has no attribute '_ipython_display_'

</code>```

How do I remove this error?

I actually tried using ChatGPT to gain some ideas. But it told me to upgrade plotly which I did. But I got the latest version.

Im using Python 3.10.9 because it's the latest version supported by Vectorbt.

Body:
So I'm trying to plot a simple RSI indicator in Python using the Vectorbt library. The RSI plots correctly but there's an error that comes with it.
As can be seen here
`

#nilagyan ng r para raw file dahil nababasa ng python as UNICODE pag may slash tapos U ang kasunod
df = pd.read_csv(r"C:\Users\Mark\Documents\Trading\BTC-2021min\BTC-2021min.csv")

#dahil ang unix code ay about sa time, cinonvert sa seconds para magkaroon ng column na date
#basically nag add tayo ng COLUMN or Data Frame na pangalan ay date
df["date"] = pd.to_datetime(df["unix"], unit = "s")

#nanggawa ng column at index na date at time kaya nakaSET ang INDEX sa DATE
df.set_index("date", inplace=True)

#aggregation ng 1 minute candles into something bigger, sakin ay 15 minutes kaya 15T
df = df.resample("15T").agg({
    "open":"first",
    "high": "max",
    "low": "min",
    "close": "last",
})

#this makes it go through only a specific date rather than the whole csv file, start date at end date lang
df = df.loc["2021-10-01":"2021-10-31"]

rsi = vbt.RSI.run(df.close, window=8)

rsi.plot()

When I run this using Jupyter notebook, I encounter this error:

`

AttributeError                            Traceback (most recent call last)
File c:\Users\Mark\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\formatters.py:920, in IPythonDisplayFormatter.__call__(self, obj)
    918 method = get_real_method(obj, self.print_method)
    919 if method is not None:
--> 920     method()
    921     return True

File c:\Users\Mark\AppData\Local\Programs\Python\Python310\lib\site-packages\plotly\basewidget.py:741, in BaseFigureWidget._ipython_display_(self)
    737 """
    738 Handle rich display of figures in ipython contexts
    739 """
    740 # Override BaseFigure's display to make sure we display the widget version
--> 741 widgets.DOMWidget._ipython_display_(self)

AttributeError: type object 'DOMWidget' has no attribute '_ipython_display_'

How do I remove this error?

I actually tried using ChatGPT to gain some ideas. But it told me to upgrade plotly which I did. But I got the latest version.

Im using Python 3.10.9 because it's the latest version supported by Vectorbt.


问:
create custom decoder page on godaddy host that fix querystring and redirects to an API
A friend contracted some wordpress agency to create a webpage that based on input data entered by user on a form create a custom URL to redirect to a third party API that shows some data to rent a car, this wordpress is done with elementor plugin and the problem is that when redirecting the query params separators are being encoded as html entities i.e the url must be something like www.site.com/?value1=value1&value2=value2&value3=value3 but the plugin is changing the url to www.site.com/?value1=value1&value2=value2&value3=value3 the & is being encoded to &, this agency left the work unfinished and don't want and also can't fix this, he asked me if I can fix it, I am not a wordpress developer so have been difficult for me, in my desperation one idea arose to my mind, them have this site hosted on goddady I think I can code a custom decoder with regex that change the & to & and then redirects with the corrected url to the the API that brings the car data, so the wordpress now won't redirect to www.site.com/?... which is the car rental API instead will redirect to the custom url decoder like www.customdecoder.com/{wrong query params}, so the question is if please you can explain me how can I host this custom decoder on goddady alongside the wordpress page? or should I better do this as a aws lambda function? if this is a lambda function could it cost a lot? please forgive me if this question is kinda weird but is not a wordpress question.


问:
TS-2590 error produced by custom chakra-ui component style overrider fn
I've created a function that works similarly to @chakra-ui/react's chakra() factory function, that can overload any property on target component. It works but I can't seem to resolve the TS-2590 union type error it creates.

```<code>import { As, chakra, ChakraComponent, Stack } from '@chakra-ui/react';
import { ComponentProps, ForwardedRef, forwardRef, ForwardRefExoticComponent, PropsWithoutRef } from 'react';

function makeChakra<
  T extends As,
  P = {},
  FP = PropsWithoutRef<ComponentProps<T> & P> ,
  FPR = ForwardRefExoticComponent<FP & ComponentProps<ChakraComponent<T>>>
>(
  comp: T,
  label?: string
): (
  props?: Partial<ComponentProps<ChakraComponent<T>>>
) => FPR {
  const Component = chakra(comp, {
    label,
  });

  // type RT = ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;

  return (props = {}) =>
    // eslint-disable-next-line react/display-name
    (forwardRef<ChakraComponent<T>, ComponentProps<T>>(
      (
        innerProps: ComponentProps<T>,
        ref: ForwardedRef<ChakraComponent<T>>
      ) => {

        return <Component ref={ref} {...props} {...innerProps} />;
      }
    ) as FPR);
}

// HERE

export const CustomStack = makeChakra(
    Stack,
    "CustomStack"
)({
    pos: "relative",
    spacing: 24,
    m: 20,
    placeItems: "stretch",
    placeContent: "stretch",

    lineHeight: "shorter",
});
// =>  Expression produces a union type that is too complex to represent.nts(2590)
</code>```

Body:
I've created a function that works similarly to @chakra-ui/react's chakra() factory function, that can overload any property on target component. It works but I can't seem to resolve the TS-2590 union type error it creates.

import { As, chakra, ChakraComponent, Stack } from '@chakra-ui/react';
import { ComponentProps, ForwardedRef, forwardRef, ForwardRefExoticComponent, PropsWithoutRef } from 'react';

function makeChakra<
  T extends As,
  P = {},
  FP = PropsWithoutRef<ComponentProps<T> & P> ,
  FPR = ForwardRefExoticComponent<FP & ComponentProps<ChakraComponent<T>>>
>(
  comp: T,
  label?: string
): (
  props?: Partial<ComponentProps<ChakraComponent<T>>>
) => FPR {
  const Component = chakra(comp, {
    label,
  });

  // type RT = ForwardRefExoticComponent<PropsWithoutRef
 & RefAttributes<T>>;

  return (props = {}) =>
    // eslint-disable-next-line react/display-name
    (forwardRef<ChakraComponent<T>, ComponentProps<T>>(
      (
        innerProps: ComponentProps<T>,
        ref: ForwardedRef<ChakraComponent<T>>
      ) => {

        return <Component ref={ref} {...props} {...innerProps} />;
      }
    ) as FPR);
}

// HERE

export const CustomStack = makeChakra(
    Stack,
    "CustomStack"
)({
    pos: "relative",
    spacing: 24,
    m: 20,
    placeItems: "stretch",
    placeContent: "stretch",

    lineHeight: "shorter",
});
// =>  Expression produces a union type that is too complex to represent.nts(2590)


问:
Internal Server Error 500 -- EC2, django, nginx, uwsgi
I'm developing and deploying django based web-app through EC2 with nginx and uwsgi.

Because of developing Front-side (based on react), I send several http request to my server's public IPv4.
And the first few moment, my request is normally answered by server. All data is safely delivered to "http://localhost:3000".

But in some reason, after rebooting my EC2 instance, my nginx returned "500 (Internal Server Error)". More detailed information is descripted below.

[log]

/var/nginx/access.log --> any further information than internal server error

```<code>3.21.102.102 - - [22/Dec/2022:04:07:08 +0000] "GET /beta/.env HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-"
3.21.102.102 - - [22/Dec/2022:04:07:08 +0000] "GET /beta/.env.local HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-"
3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /beta/.env.production HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-"
3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /beta/.env.staging HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-"
3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /live/.env HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-"
</code>```

/var/nginx/access.log --> empty

[configure files and django settings.py]

nginx.configure

```<code>include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  {{server_address_of_mine}};
        root         /home/ec2-user/cury_engine;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

         location / {

                include         uwsgi_params;
                uwsgi_pass      unix:/home/ec2-user/cury.sock;

        }

    }

</code>```

django settings.py

```<code># SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

WSGI_APPLICATION = 'cury_engine.wsgi.application'

CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000',
    "http://localhost:8000",
    '{{my_domain}}',
    "http://127.0.0.1:8000",
]
</code>```

[What I tried after reboot server]

sudo systemctl restart nginx

sudo systemctl restart nginx.service

sudo systemctl restart uwsgi (my django server is automatically run server with this command)

sudo systemctl restart uwsgi.service
-> I check nginx and uwsgi is running safely. (with sudo systemctl status XXX command)

[What I tried differently to test server status]

postman request --> same result: 500 (Internal Server Error)

curl request inside EC2 instance terminal --> same result: 500 (Internal Server Error)

i expect to recover my server and know how to debug this error

Body:
I'm developing and deploying django based web-app through EC2 with nginx and uwsgi.

Because of developing Front-side (based on react), I send several http request to my server's public IPv4.
And the first few moment, my request is normally answered by server. All data is safely delivered to "http://localhost:3000".

But in some reason, after rebooting my EC2 instance, my nginx returned "500 (Internal Server Error)". More detailed information is descripted below.

[log]

/var/nginx/access.log --> any further information than internal server error

3.21.102.102 - - [22/Dec/2022:04:07:08 +0000] "GET /beta/.env HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-"
3.21.102.102 - - [22/Dec/2022:04:07:08 +0000] "GET /beta/.env.local HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-"
3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /beta/.env.production HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-"
3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /beta/.env.staging HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-"
3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /live/.env HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-"

/var/nginx/access.log --> empty

[configure files and django settings.py]

nginx.configure

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  {{server_address_of_mine}};
        root         /home/ec2-user/cury_engine;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

         location / {

                include         uwsgi_params;
                uwsgi_pass      unix:/home/ec2-user/cury.sock;

        }

    }

django settings.py

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

WSGI_APPLICATION = 'cury_engine.wsgi.application'

CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000',
    "http://localhost:8000",
    '{{my_domain}}',
    "http://127.0.0.1:8000",
]

[What I tried after reboot server]

sudo systemctl restart nginx

sudo systemctl restart nginx.service

sudo systemctl restart uwsgi (my django server is automatically run server with this command)

sudo systemctl restart uwsgi.service
-> I check nginx and uwsgi is running safely. (with sudo systemctl status XXX command)

[What I tried differently to test server status]

postman request --> same result: 500 (Internal Server Error)

curl request inside EC2 instance terminal --> same result: 500 (Internal Server Error)

i expect to recover my server and know how to debug this error


问:
How to dynamically create a pathvariable to create a view?
How to dynamically create a pathvariable to create a view?

When the button is clicked, it moves to the corresponding url, such as localhost:8080/viewer/{id}.
I wonder how to pass the id to admin.html without creating a controller.

```<code>@Override
     public void addViewControllers(ViewControllerRegistry registry) {
         this.getPathView().forEach((path, view) -> registry.addViewController(path).setViewName(view));
     }
</code>```

As above, only the url to the current viewer exists because of dynamic url mapping.

When I pass the id in the script, I want to receive the id in admin.html and map it dynamically.

Body:
How to dynamically create a pathvariable to create a view?

When the button is clicked, it moves to the corresponding url, such as localhost:8080/viewer/{id}.
I wonder how to pass the id to admin.html without creating a controller.

@Override
     public void addViewControllers(ViewControllerRegistry registry) {
         this.getPathView().forEach((path, view) -> registry.addViewController(path).setViewName(view));
     }

As above, only the url to the current viewer exists because of dynamic url mapping.

When I pass the id in the script, I want to receive the id in admin.html and map it dynamically.


问:
Strategy ATR TP/SL target doesn't stay 'locked' to my entry readings
I want a strategy to Take Profit/Stop Loss to be based on the ATR (plus multiplier). However, I want it to be whatever the readings were at the point of entry, not simply the last candle (which is what it seems to be doing). Weird thing is that I have other strategies that use this approach, and they seem fine, so I'm really stumped by what I'm doing wrong.

Any help would be much appreciated!

```<code>// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dave-browning

//@version=5
strategy("Dead-Cat Bounce", overlay = true, initial_capital = 1000, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, currency = currency.GBP, commission_value = 0.05, use_bar_magnifier = true)

trendEMAlength = input.int(130, "Trend EMA Length")
fastSMALength = input.int(14, "Fast SMA Length")
tpATRmultiplyer = input.float(6.2, "Short TP ATR Multiplier")
slATRmultiplier = input.float(4, "Short SL ATR Multiplier")

//Trade Conditions
shortCondition = close > ta.sma(close, fastSMALength) and close < ta.ema(close, length=trendEMAlength)
notInTrade = strategy.position_size <= 0

atr = ta.atr(14)
ema=ta.ema(close, trendEMAlength)

plot(ta.sma(close,length=fastSMALength), color=color.blue, linewidth = 2)
plot(ta.ema(close, length=trendEMAlength), color=color.yellow, linewidth = 4)
plot(low - (atr * tpATRmultiplyer), color=color.green)
plot(high + (atr * slATRmultiplier), color=color.red)

if shortCondition and notInTrade
    stopLoss = (high + (atr * slATRmultiplier))
    takeProfit = (low - (atr * tpATRmultiplyer))
    strategy.entry("Short", strategy.short)
    strategy.exit("Short Exit", "Short", limit=takeProfit, stop=stopLoss)
</code>```

Body:
I want a strategy to Take Profit/Stop Loss to be based on the ATR (plus multiplier). However, I want it to be whatever the readings were at the point of entry, not simply the last candle (which is what it seems to be doing). Weird thing is that I have other strategies that use this approach, and they seem fine, so I'm really stumped by what I'm doing wrong.

Any help would be much appreciated!

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dave-browning

//@version=5
strategy("Dead-Cat Bounce", overlay = true, initial_capital = 1000, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, currency = currency.GBP, commission_value = 0.05, use_bar_magnifier = true)

trendEMAlength = input.int(130, "Trend EMA Length")
fastSMALength = input.int(14, "Fast SMA Length")
tpATRmultiplyer = input.float(6.2, "Short TP ATR Multiplier")
slATRmultiplier = input.float(4, "Short SL ATR Multiplier")

//Trade Conditions
shortCondition = close > ta.sma(close, fastSMALength) and close < ta.ema(close, length=trendEMAlength)
notInTrade = strategy.position_size <= 0

atr = ta.atr(14)
ema=ta.ema(close, trendEMAlength)

plot(ta.sma(close,length=fastSMALength), color=color.blue, linewidth = 2)
plot(ta.ema(close, length=trendEMAlength), color=color.yellow, linewidth = 4)
plot(low - (atr * tpATRmultiplyer), color=color.green)
plot(high + (atr * slATRmultiplier), color=color.red)

if shortCondition and notInTrade
    stopLoss = (high + (atr * slATRmultiplier))
    takeProfit = (low - (atr * tpATRmultiplyer))
    strategy.entry("Short", strategy.short)
    strategy.exit("Short Exit", "Short", limit=takeProfit, stop=stopLoss)


问:
When a user removes my Chrome Extension, the storage associated with it gets removed also. Is there any way to request that this storage persists?
Basically, I use Chrome local storage to track usage of the extension. This allows me to put in place "Free User" limits, versus unlimited usage for "Paid Users."

However if a person simply removes, then re-installs the extension, it purges the data, and they're able to use the extension above and beyond the "Free User" level that they should be allowed to use it at.

Is there any way I can request in my extension code, that this chrome storage persists somehow, perhaps for a certain duration of time, after the extension gets removed? Can I request some kind of permission in the manifest for this?

Thanks


问:
Can I display the _id to the user
I have two questions.

Can I display the the id to the user, not in the url or so. Let's say they need a JWT to be authenticated, would it be dangerous to display it to them?

To see a profile would it be also dangerous to show the id on the URL? For example profile/:id.... using ExpressJS and MongoDB. How can you get around this if thats not recommended?

Thank you in advance

Title: Can I display the _id to the user


问:
Looking for current price > previous day high . Works fine but plotting for all the 5 minutes candle
Here is my usecase :

if currentprice of 5 minutes candle  is greater than previous day high , plot the chart with the 'x' mark in green .

If currentprice of 5 minutes candle is lesser than previous day low , plot the chart with 'x' mark in green

This script prints the 'x' mark for every 5 minutes but I want to plot only first for the first time when condition is met

I used a counter to check if it is a new day but seems that is not working as expected

```<code>//@version=5
</code>```

indicator("HLPrice", max_lines_count = 11, overlay=true)

emaValue8 = ta.ema(close,8)

emaValue21 = ta.ema(close,21)

vwapValue = ta.vwap(hlc3)

// to highlight the session

timeframe = "1D"

isNewDay = timeframe.change(timeframe)

bgcolor(isNewDay ? color.new(color.green, 80) : na)

[dh,dl,dc] = request.security(syminfo.ticker, "D", [high[1],low[1], close[1]], lookahead=barmerge.lookahead_on)

isNewDayy = time("D") != time("D")[1]

var plotcond = false

greaterThanPreviousDayHigh = false

lesserThanPreviousDayLow = false

if isNewDayy

plotcond := true

if close[0] > dh and plotcond

greaterThanPreviousDayHigh:=true

if close[0] < dl and plotcond

lesserThanPreviousDayLow:=true

plotshape(series=greaterThanPreviousDayHigh , title="Candle on All EMAs" ,color = color.green, size=size.tiny)

plotshape(series=lesserThanPreviousDayLow , title="Candle on All EMAs" ,color = color.red, size=size.tiny)

Body:
Here is my usecase :

if currentprice of 5 minutes candle  is greater than previous day high , plot the chart with the 'x' mark in green .

If currentprice of 5 minutes candle is lesser than previous day low , plot the chart with 'x' mark in green

This script prints the 'x' mark for every 5 minutes but I want to plot only first for the first time when condition is met

I used a counter to check if it is a new day but seems that is not working as expected

//@version=5

indicator("HLPrice", max_lines_count = 11, overlay=true)

emaValue8 = ta.ema(close,8)

emaValue21 = ta.ema(close,21)

vwapValue = ta.vwap(hlc3)

// to highlight the session

timeframe = "1D"

isNewDay = timeframe.change(timeframe)

bgcolor(isNewDay ? color.new(color.green, 80) : na)

[dh,dl,dc] = request.security(syminfo.ticker, "D", [high[1],low[1], close[1]], lookahead=barmerge.lookahead_on)

isNewDayy = time("D") != time("D")[1]

var plotcond = false

greaterThanPreviousDayHigh = false

lesserThanPreviousDayLow = false

if isNewDayy

plotcond := true

if close[0] > dh and plotcond

greaterThanPreviousDayHigh:=true

if close[0] < dl and plotcond

lesserThanPreviousDayLow:=true

plotshape(series=greaterThanPreviousDayHigh , title="Candle on All EMAs" ,color = color.green, size=size.tiny)

plotshape(series=lesserThanPreviousDayLow , title="Candle on All EMAs" ,color = color.red, size=size.tiny)


问:
Kotlin - Keep button sticky in AppBarLayout$ScrollingViewBehavior (in FragmentContainerView)
I have an issue with FragmentContainerView, it looks like this:

```<code> <androidx.fragment.app.FragmentContainerView
    android:id="@+id/myFragment"
    android:name="com.me.MyFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</code>```

And in its fragment, I have a recycler view, and a button:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/swipeRefreshLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"/>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

<Button
    android:id="@+id/myBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerInParent="true"
    android:gravity="bottom|center" />
</code>```

However, when I am scrolling, button is also moving up, even though I set up alignParentBottom. I believe the issue is in this line of code:

```<code>app:layout_behavior="@string/appbar_scrolling_view_behavior"
</code>```

which is actually:

```<code>    <string name="appbar_scrolling_view_behavior" translatable="false">com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior</string>
</code>```

FragmentContainerView is used in CoordinatorLayout. Note that button is out of SwipeRefreshLayout, so it shouldn't be affected by scrolling the recycler view.
I want to keep it sticky, so it doesn't move when I scroll the screen.
Any ideas?

Body:
I have an issue with FragmentContainerView, it looks like this:

 <androidx.fragment.app.FragmentContainerView
    android:id="@+id/myFragment"
    android:name="com.me.MyFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

And in its fragment, I have a recycler view, and a button:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/swipeRefreshLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"/>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

<Button
    android:id="@+id/myBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerInParent="true"
    android:gravity="bottom|center" />

However, when I am scrolling, button is also moving up, even though I set up alignParentBottom. I believe the issue is in this line of code:

app:layout_behavior="@string/appbar_scrolling_view_behavior"

which is actually:

    <string name="appbar_scrolling_view_behavior" translatable="false">com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior</string>

FragmentContainerView is used in CoordinatorLayout. Note that button is out of SwipeRefreshLayout, so it shouldn't be affected by scrolling the recycler view.
I want to keep it sticky, so it doesn't move when I scroll the screen.
Any ideas?


问:
pivot point color conditionally: support and resistances according with higher high etc
I have 2 simple script, the first that plot the label shapes of higher high, higher low, etc with relative colors:

```<code>leftbars = input(title='LeftBars', defval=10)
rightbars = input(title='Rightbars', defval=5)

ph = ta.pivothigh(leftbars, rightbars)
pl = ta.pivotlow(leftbars, rightbars)

// Higher Highs and Higher Lows
hl = ta.valuewhen(ph, ph, 0) < ta.valuewhen(ph[1], ph[1], 0)
hh = ta.valuewhen(ph, ph, 0) > ta.valuewhen(ph[1], ph[1], 0)
plotshape(hh, title='Higher High', style=shape.square, location=location.abovebar, color=color.new(color.green, 75), text='[HH]', offset=-rightbars, size=size.auto)
plotshape(hl, title='Higher Low', style=shape.square, location=location.abovebar, color=color.new(color.red, 75), text='[HL]', offset=-rightbars, size=size.auto)

// Lower Lows and Lower Highs
ll = ta.valuewhen(pl[1], pl[1], 0) > ta.valuewhen(pl, pl, 0)
lh = ta.valuewhen(pl[1], pl[1], 0) < ta.valuewhen(pl, pl, 0)
plotshape(ll, title='Lower Low', style=shape.square, location=location.belowbar, color=color.new(color.red, 75), text='[LL]', offset=-rightbars, size=size.auto)
plotshape(lh, title='Lower High', style=shape.square, location=location.belowbar, color=color.new(color.green, 75), text='[LH]', offset=-rightbars, size=size.auto)

</code>```

and the second that plot the lines at pivot points as support and resistances with fixed colors:

```<code>piv_hig = ta.pivothigh(high, leftbars, rightbars)
piv_low = ta.pivotlow(low, leftbars, rightbars)

top = ta.valuewhen(piv_hig, high[rightbars], 0)
bottom = ta.valuewhen(piv_low, low[rightbars], 0)

resist = plot(top, color=top != top[1] ? na : color.green, offset=-rightbars)
support = plot(bottom, color=bottom != bottom[1] ? na : color.red, offset=-rightbars)
</code>```

What I'm trying to do is to merge the two scripts avoiding the labels hh, hl, etc, and coloring the support and resistance lines according with the colors and conditions of the first script.  I thinked was simply but really I am not able ( obviously I'm a beginner)

At first I tried to plot the condition (hh, hl , ll , lh) but it's impossible because one is bool and the other require float:
resistance_hl = plot(hl, color=top != top[1] ? na : color.red, offset=-rightbars)

I tried to set color conditionally but nothing:
resistance_hl = plot(top, color=top != top[1] ? na : color_condition, offset=-rightbars)

I tried to apply the condition to the plotted value:
resistance_hl = plot(top and hl, color=top != top[1] ? na : color.red, offset=-rightbars)

I tried to change color=top != top[1] with color=top < top[1] and other various similar attempts but nothing.

I think I need to use line.new but I never used it and I'm trying to understand, but I'm not a coder so I proceed by trial.

any simple suggestions for the right way to follow?

can someone help me?
Thanks in advance

Body:
I have 2 simple script, the first that plot the label shapes of higher high, higher low, etc with relative colors:

leftbars = input(title='LeftBars', defval=10)
rightbars = input(title='Rightbars', defval=5)

ph = ta.pivothigh(leftbars, rightbars)
pl = ta.pivotlow(leftbars, rightbars)

// Higher Highs and Higher Lows
hl = ta.valuewhen(ph, ph, 0) < ta.valuewhen(ph[1], ph[1], 0)
hh = ta.valuewhen(ph, ph, 0) > ta.valuewhen(ph[1], ph[1], 0)
plotshape(hh, title='Higher High', style=shape.square, location=location.abovebar, color=color.new(color.green, 75), text='[HH]', offset=-rightbars, size=size.auto)
plotshape(hl, title='Higher Low', style=shape.square, location=location.abovebar, color=color.new(color.red, 75), text='[HL]', offset=-rightbars, size=size.auto)

// Lower Lows and Lower Highs
ll = ta.valuewhen(pl[1], pl[1], 0) > ta.valuewhen(pl, pl, 0)
lh = ta.valuewhen(pl[1], pl[1], 0) < ta.valuewhen(pl, pl, 0)
plotshape(ll, title='Lower Low', style=shape.square, location=location.belowbar, color=color.new(color.red, 75), text='[LL]', offset=-rightbars, size=size.auto)
plotshape(lh, title='Lower High', style=shape.square, location=location.belowbar, color=color.new(color.green, 75), text='[LH]', offset=-rightbars, size=size.auto)

and the second that plot the lines at pivot points as support and resistances with fixed colors:

piv_hig = ta.pivothigh(high, leftbars, rightbars)
piv_low = ta.pivotlow(low, leftbars, rightbars)

top = ta.valuewhen(piv_hig, high[rightbars], 0)
bottom = ta.valuewhen(piv_low, low[rightbars], 0)

resist = plot(top, color=top != top[1] ? na : color.green, offset=-rightbars)
support = plot(bottom, color=bottom != bottom[1] ? na : color.red, offset=-rightbars)

What I'm trying to do is to merge the two scripts avoiding the labels hh, hl, etc, and coloring the support and resistance lines according with the colors and conditions of the first script.  I thinked was simply but really I am not able ( obviously I'm a beginner)

At first I tried to plot the condition (hh, hl , ll , lh) but it's impossible because one is bool and the other require float:
resistance_hl = plot(hl, color=top != top[1] ? na : color.red, offset=-rightbars)

I tried to set color conditionally but nothing:
resistance_hl = plot(top, color=top != top[1] ? na : color_condition, offset=-rightbars)

I tried to apply the condition to the plotted value:
resistance_hl = plot(top and hl, color=top != top[1] ? na : color.red, offset=-rightbars)

I tried to change color=top != top[1] with color=top < top[1] and other various similar attempts but nothing.

I think I need to use line.new but I never used it and I'm trying to understand, but I'm not a coder so I proceed by trial.

any simple suggestions for the right way to follow?

can someone help me?
Thanks in advance


问:
CKEditor 4.20 source editing area plugin loses all formatting (line breaks)
I upgraded from CKE 4.13 to CKE 4.20 and the source editing area plugin has now lost all line breaks. I used the online builder and suspect something in my plugin set up may be slightly different. The best way to explain is in some screen grabs. Sample text...

Here is what Source looked like in 4.13...

And in 4.20...

I am also using the CodeMirror plug in. Am NOT using the source dialog plugin. Seems to be line break related.


问:
Standard style from Chakra not applied
I tried NextJS and Chakra in a sandbox. Taking a simple example, I do not apply the standard styles. Connected from the Chakra instructions for NextJS.

https://codesandbox.io/s/brave-vaughan-z32tyn?file=/pages/_app.tsx

Title: Standard style from Chakra not applied


问:
Getting mismatching_state error in fastapi while signin through the starlette package in python
I cannot authenticate properly and get some errors while handling authentication. I clicked on google accounts but was not able to get the user and the token due to the error.

Code

```<code>import json
from fastapi import FastAPI
from starlette.config import Config
from starlette.requests import Request
from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import HTMLResponse, RedirectResponse
from authlib.integrations.starlette_client import OAuth, OAuthError

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="secret")

config = Config('.env')
oauth = OAuth(config)

CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'
oauth.register(
    name='google',
    server_metadata_url=CONF_URL,
    client_kwargs={
        'scope': 'openid email profile'
    }
)

@app.get('/')
async def homepage(request: Request):
    user = request.session.get('user')
    if user:
        data = json.dumps(user)
        html = (
            f'```{data}```'
            'logout'
        )
        return HTMLResponse(html)
    return HTMLResponse('login')

@app.get('/login')
async def login(request: Request):
    redirect_uri = request.url_for('auth')
    return await oauth.google.authorize_redirect(request, redirect_uri)

@app.get('/auth')
async def auth(request: Request):
    try:
        token = await oauth.google.authorize_access_token(request)
    except OAuthError as error:
        print(OAuthError)
        return HTMLResponse(f'<h1>{error.error}</h1>')
    user = token.get('userinfo')
    if user:
        request.session['user'] = dict(user)
        print(user)
    return RedirectResponse(url='/')

@app.get('/logout')
async def logout(request: Request):
    request.session.pop('user', None)
    return RedirectResponse(url='/')

</code>```

After signing in through the google account, I am getting this error.

<class 'authlib.integrations.base_client.errors.OAuthError'>

Body:
I cannot authenticate properly and get some errors while handling authentication. I clicked on google accounts but was not able to get the user and the token due to the error.

Code

import json
from fastapi import FastAPI
from starlette.config import Config
from starlette.requests import Request
from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import HTMLResponse, RedirectResponse
from authlib.integrations.starlette_client import OAuth, OAuthError

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="secret")

config = Config('.env')
oauth = OAuth(config)

CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'
oauth.register(
    name='google',
    server_metadata_url=CONF_URL,
    client_kwargs={
        'scope': 'openid email profile'
    }
)

@app.get('/')
async def homepage(request: Request):
    user = request.session.get('user')
    if user:
        data = json.dumps(user)
        html = (
            f'
{data}
'
            'logout'
        )
        return HTMLResponse(html)
    return HTMLResponse('login')

@app.get('/login')
async def login(request: Request):
    redirect_uri = request.url_for('auth')
    return await oauth.google.authorize_redirect(request, redirect_uri)

@app.get('/auth')
async def auth(request: Request):
    try:
        token = await oauth.google.authorize_access_token(request)
    except OAuthError as error:
        print(OAuthError)
        return HTMLResponse(f'
{error.error}
')
    user = token.get('userinfo')
    if user:
        request.session['user'] = dict(user)
        print(user)
    return RedirectResponse(url='/')

@app.get('/logout')
async def logout(request: Request):
    request.session.pop('user', None)
    return RedirectResponse(url='/')

After signing in through the google account, I am getting this error.

<class 'authlib.integrations.base_client.errors.OAuthError'>


问:
Nextjs exported project, uploaded the out file to cPanel in bluehost, images do not appear, I made sure in the code the filepath is correct
I used lazy loading images using

```<code>import Image from 'next/image';
</code>```
```<code>import rentalsImg from '../public/projects/LuxuryRentals.png';
</code>```
```<code>const Projects = () => {
  return (
    <div id='projects' className='w-full pt-10'>
        <div className='max-w-[1240px] mx-auto px-2 py-16'>
            <p className='text-xl tracking-widest uppercase text-[#5651e5]'>Projects</p>
            <h2 className='py-4'>What I've Developed</h2>
            <div className='grid md:grid-cols-2 gap-8'>
            <ProjectItem
                title='Luxury Rentals'
                technologies='HTML, Bootstrap, PHP, SQL'
                backgroundImg={rentalsImg}
                projectUrl='/rental'
            />
            <ProjectItem
                title='Vibe App'
                technologies='Java, Android Studio'
                backgroundImg={vibeImg}
                projectUrl='/vibe'
            />
</code>```

none of my images on my website, mobenl.com , are appearing. i exported my project using
npm run export.
when I check the network, for all pictures I get a status 200.

this is my first time doing a project with react and next js so I can't pinpoint what the issue could be, maybe the filepaths change when the files are converted into html files?

I am still in school so my knowledge isn't the best but it seems as though ive exhausted all my options.

Body:
I used lazy loading images using

import Image from 'next/image';

import rentalsImg from '../public/projects/LuxuryRentals.png';

const Projects = () => {
  return (

Projects

What I've Developed

            <ProjectItem
                title='Luxury Rentals'
                technologies='HTML, Bootstrap, PHP, SQL'
                backgroundImg={rentalsImg}
                projectUrl='/rental'
            />
            <ProjectItem
                title='Vibe App'
                technologies='Java, Android Studio'
                backgroundImg={vibeImg}
                projectUrl='/vibe'
            />

none of my images on my website, mobenl.com , are appearing. i exported my project using
npm run export.
when I check the network, for all pictures I get a status 200.

this is my first time doing a project with react and next js so I can't pinpoint what the issue could be, maybe the filepaths change when the files are converted into html files?

I am still in school so my knowledge isn't the best but it seems as though ive exhausted all my options.


问:
useState in a ContextProvider causes a 1-2second delay

Context

I have a ContextProvider around my components.
To this ContextProvider I connected a useState hook.
In one of my components I want to set the value of the useState hook.
If the value is the same value of the current state, then there is no delay.
if the value is a new value compared to the current state, then there is a 2second delay.

As weird as my statement sounds, these stack questions have the same behavior:

React Context API is slow

Delay in useContext React JS

What I found out by debugging

The delay is not caused by the sum (adding 1 to the previous value of the usestate), because setting a random value (for example the current datetime) will cause a 2sec delay as well

removing useCallback has no effect

rerenders of my own components are not causing the 2sec delay, because no components are using the context (and thus have no reason to rerender).

using useMemo to save the usestate variables has no effect on the delay

Project configurations

React-native:0.70.6

Code

(especially notice the last two components)

Contextprovider:

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

type CurrentEntryContextType = {
  answersBeingSaved: number;
  setAnswersBeingSaved: (count: number) => void;
};

export const CurrentEntryContext = React.createContext<CurrentEntryContextType>({
  answersBeingSaved: 5,
  setAnswersBeingSaved: () => {},
});

</code>```

Main:

```<code>function App() {
  const [answersBeingSaved, setAnswersBeingSaved] = useState<number>(5);
  const currentEntryContext = useMemo(() => {
    return {
      answersBeingSaved: answersBeingSaved,
      setAnswersBeingSaved: setAnswersBeingSaved,
    };
  }, [answersBeingSaved]);
  return (
    <>
      <CurrentEntryContext.Provider value={currentEntryContext}>
              <MainNavigationBar />
      </CurrentEntryContext.Provider>
    </>
  );
}
</code>```

Component that changes the context with 2s delay (calling the acknowledge is what's causing the delay):

```<code>function RandomComponent() {
  const currentEntryContext = useContext(CurrentEntryContext);

  const acknowledgeAnswerBeingSaved = useCallback(() => {
    currentEntryContext.setAnswersBeingSaved(
      currentEntryContext.answersBeingSaved + 3
    );
  }, [currentEntryContext]);
  return <></>;
}
</code>```

Component that changes the context without 2s delay (this is just to demonstrate that the issue only occurs when the useState is set to a different value each time):

```<code>function RandomComponent() {
  const currentEntryContext = useContext(CurrentEntryContext);

  const acknowledgeAnswerBeingSaved = useCallback(() => {
    const redundantVariable = currentEntryContext.answersBeingSaved + 3;
    currentEntryContext.setAnswersBeingSaved(
      5
    );
  }, [currentEntryContext]);
  return <></>;
}
</code>```

Body:
Context

I have a ContextProvider around my components.
To this ContextProvider I connected a useState hook.
In one of my components I want to set the value of the useState hook.
If the value is the same value of the current state, then there is no delay.
if the value is a new value compared to the current state, then there is a 2second delay.

As weird as my statement sounds, these stack questions have the same behavior:

React Context API is slow

Delay in useContext React JS

What I found out by debugging

The delay is not caused by the sum (adding 1 to the previous value of the usestate), because setting a random value (for example the current datetime) will cause a 2sec delay as well

removing useCallback has no effect

rerenders of my own components are not causing the 2sec delay, because no components are using the context (and thus have no reason to rerender).

using useMemo to save the usestate variables has no effect on the delay

Project configurations

React-native:0.70.6

Code

(especially notice the last two components)

Contextprovider:

import React from 'react';

type CurrentEntryContextType = {
  answersBeingSaved: number;
  setAnswersBeingSaved: (count: number) => void;
};

export const CurrentEntryContext = React.createContext<CurrentEntryContextType>({
  answersBeingSaved: 5,
  setAnswersBeingSaved: () => {},
});

Main:

function App() {
  const [answersBeingSaved, setAnswersBeingSaved] = useState<number>(5);
  const currentEntryContext = useMemo(() => {
    return {
      answersBeingSaved: answersBeingSaved,
      setAnswersBeingSaved: setAnswersBeingSaved,
    };
  }, [answersBeingSaved]);
  return (
    <>
      <CurrentEntryContext.Provider value={currentEntryContext}>
              <MainNavigationBar />
      </CurrentEntryContext.Provider>
    </>
  );
}

Component that changes the context with 2s delay (calling the acknowledge is what's causing the delay):

function RandomComponent() {
  const currentEntryContext = useContext(CurrentEntryContext);

  const acknowledgeAnswerBeingSaved = useCallback(() => {
    currentEntryContext.setAnswersBeingSaved(
      currentEntryContext.answersBeingSaved + 3
    );
  }, [currentEntryContext]);
  return <></>;
}

Component that changes the context without 2s delay (this is just to demonstrate that the issue only occurs when the useState is set to a different value each time):

function RandomComponent() {
  const currentEntryContext = useContext(CurrentEntryContext);

  const acknowledgeAnswerBeingSaved = useCallback(() => {
    const redundantVariable = currentEntryContext.answersBeingSaved + 3;
    currentEntryContext.setAnswersBeingSaved(
      5
    );
  }, [currentEntryContext]);
  return <></>;
}


问:
Error installing Mike's Arbitrary Precision Math Library (MAPM)
Please I need help, I need to install this library quickly for a project I am working on (https://github.com/LuaDist/mapm) and I don't understand makefile. Per the instructions I run the command "make" and get the following output:

gcc -c -Wall -O2 mapmhsin.c
gcc -c -Wall -O2 mapm_pow.c
gcc -c -Wall -O2 mapm_log.c
gcc -c -Wall -O2 mapm_lg2.c
gcc -c -Wall -O2 mapm_lg4.c
gcc -c -Wall -O2 mapm_exp.c
gcc -c -Wall -O2 mapm_lg3.c
gcc -c -Wall -O2 mapmasin.c
gcc -c -Wall -O2 mapmasn0.c
gcc -c -Wall -O2 mapm_sin.c
gcc -c -Wall -O2 mapm5sin.c
gcc -c -Wall -O2 mapmrsin.c
gcc -c -Wall -O2 mapm_cpi.c
gcc -c -Wall -O2 mapmsqrt.c
gcc -c -Wall -O2 mapmcbrt.c
gcc -c -Wall -O2 mapmgues.c
gcc -c -Wall -O2 mapmfact.c
gcc -c -Wall -O2 mapm_gcd.c
gcc -c -Wall -O2 mapmipwr.c
gcc -c -Wall -O2 mapmpwr2.c
gcc -c -Wall -O2 mapm_rnd.c
gcc -c -Wall -O2 mapm_flr.c
gcc -c -Wall -O2 mapm_fpf.c
gcc -c -Wall -O2 mapm_rcp.c
gcc -c -Wall -O2 mapmstck.c
gcc -c -Wall -O2 mapm_div.c
gcc -c -Wall -O2 mapm_mul.c
gcc -c -Wall -O3 mapmfmul.c
gcc -c -Wall -O2 mapm_fft.c
gcc -c -Wall -O2 mapm_add.c
gcc -c -Wall -O2 mapmistr.c
gcc -c -Wall -O2 mapm_set.c
gcc -c -Wall -O2 mapm_fam.c
gcc -c -Wall -O3 mapmutil.c
gcc -c -Wall -O2 mapmutl2.c
gcc -c -Wall -O2 mapmutl1.c
gcc -c -Wall -O2 mapmcnst.c
rm -f libmapm.a
ar rc libmapm.a mapmhasn.o mapmhsin.o mapm_pow.o mapm_log.o mapm_lg2.o mapm_lg4.o mapm_exp.o mapm_lg3.o mapmasin.o mapmasn0.o mapm_sin.o mapm5sin.o mapmrsin.o mapm_cpi.o mapmsqrt.o mapmcbrt.o mapmgues.o mapmfact.o mapm_gcd.o mapmipwr.o mapmpwr2.o mapm_rnd.o mapm_flr.o mapm_fpf.o mapm_rcp.o mapmstck.o mapm_div.o mapm_mul.o mapmfmul.o mapm_fft.o mapm_add.o mapmistr.o mapm_set.o mapm_fam.o mapmutil.o mapmutl2.o mapmutl1.o mapmcnst.o
gcc -c -Wall -O2 calc.c
gcc -s -static -o calc calc.o libmapm.a -lm
/usr/bin/ld: cannot find -lm
/usr/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status
make: *** [Makefile:63: calc] Error 1
```
<p>It looks like everything goes fine until the end:</p>
```/usr/bin/ld: cannot find -lm
/usr/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status
```

Is there any way I fix this, and what does the command -lm and -lc do?

Body:
Please I need help, I need to install this library quickly for a project I am working on (https://github.com/LuaDist/mapm) and I don't understand makefile. Per the instructions I run the command "make" and get the following output:

gcc -c -Wall -O2 mapmhsin.c
gcc -c -Wall -O2 mapm_pow.c
gcc -c -Wall -O2 mapm_log.c
gcc -c -Wall -O2 mapm_lg2.c
gcc -c -Wall -O2 mapm_lg4.c
gcc -c -Wall -O2 mapm_exp.c
gcc -c -Wall -O2 mapm_lg3.c
gcc -c -Wall -O2 mapmasin.c
gcc -c -Wall -O2 mapmasn0.c
gcc -c -Wall -O2 mapm_sin.c
gcc -c -Wall -O2 mapm5sin.c
gcc -c -Wall -O2 mapmrsin.c
gcc -c -Wall -O2 mapm_cpi.c
gcc -c -Wall -O2 mapmsqrt.c
gcc -c -Wall -O2 mapmcbrt.c
gcc -c -Wall -O2 mapmgues.c
gcc -c -Wall -O2 mapmfact.c
gcc -c -Wall -O2 mapm_gcd.c
gcc -c -Wall -O2 mapmipwr.c
gcc -c -Wall -O2 mapmpwr2.c
gcc -c -Wall -O2 mapm_rnd.c
gcc -c -Wall -O2 mapm_flr.c
gcc -c -Wall -O2 mapm_fpf.c
gcc -c -Wall -O2 mapm_rcp.c
gcc -c -Wall -O2 mapmstck.c
gcc -c -Wall -O2 mapm_div.c
gcc -c -Wall -O2 mapm_mul.c
gcc -c -Wall -O3 mapmfmul.c
gcc -c -Wall -O2 mapm_fft.c
gcc -c -Wall -O2 mapm_add.c
gcc -c -Wall -O2 mapmistr.c
gcc -c -Wall -O2 mapm_set.c
gcc -c -Wall -O2 mapm_fam.c
gcc -c -Wall -O3 mapmutil.c
gcc -c -Wall -O2 mapmutl2.c
gcc -c -Wall -O2 mapmutl1.c
gcc -c -Wall -O2 mapmcnst.c
rm -f libmapm.a
ar rc libmapm.a mapmhasn.o mapmhsin.o mapm_pow.o mapm_log.o mapm_lg2.o mapm_lg4.o mapm_exp.o mapm_lg3.o mapmasin.o mapmasn0.o mapm_sin.o mapm5sin.o mapmrsin.o mapm_cpi.o mapmsqrt.o mapmcbrt.o mapmgues.o mapmfact.o mapm_gcd.o mapmipwr.o mapmpwr2.o mapm_rnd.o mapm_flr.o mapm_fpf.o mapm_rcp.o mapmstck.o mapm_div.o mapm_mul.o mapmfmul.o mapm_fft.o mapm_add.o mapmistr.o mapm_set.o mapm_fam.o mapmutil.o mapmutl2.o mapmutl1.o mapmcnst.o
gcc -c -Wall -O2 calc.c
gcc -s -static -o calc calc.o libmapm.a -lm
/usr/bin/ld: cannot find -lm
/usr/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status
make: *** [Makefile:63: calc] Error 1

It looks like everything goes fine until the end:

/usr/bin/ld: cannot find -lm
/usr/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status

Is there any way I fix this, and what does the command -lm and -lc do?


问:
how to connect to metamask with react native
I want to connect to metamask with react native.
I searched on google and I am using react-native-walletconnect
But I got an error.
Somebody helps me.
I tried to use useWalletConnect from react-native-walletconnect</p>


问:
VSCode Java RedHat extension - disable linting but keep formatter
Using Red Hat's Language Support for Java extension in VS Code, is there any way to disable all linting while retaining the formatting? I basically want the extension to do nothing except format my code.

At the end of the day, I just want an extension that formats exactly like the Red Hat extension according to eclipse profiles. If there's a better alternative, that works too.


问:
nextjs antd5 refresh break css first time
nextjs antd5 refresh break css first time

I create create-next-app@latest --typescript and install antd

but refresh page (F5) first time break css ( not load? )

this is problem cssinjs?

Error view gif

```<code>    "dependencies": {
        "@ant-design/icons": "^4.8.0",
        "@next/font": "13.1.0",
        "@types/node": "18.11.17",
        "@types/react": "18.0.26",
        "@types/react-dom": "18.0.9",
        "antd": "^5.0.2",
        "eslint": "8.30.0",
        "eslint-config-next": "13.1.0",
        "next": "13.1.0",
        "react": "18.2.0",
        "react-dom": "18.2.0",
        "typescript": "4.9.4"
    }
</code>```

`

and I tired antd version downgrade 4.x.x then this problem is not detect

but antd 5.x.x is this problem detected

nextjs version is 12.x.x , 13.x.x no problem

Body:
nextjs antd5 refresh break css first time

I create create-next-app@latest --typescript and install antd

but refresh page (F5) first time break css ( not load? )

this is problem cssinjs?

Error view gif

    "dependencies": {
        "@ant-design/icons": "^4.8.0",
        "@next/font": "13.1.0",
        "@types/node": "18.11.17",
        "@types/react": "18.0.26",
        "@types/react-dom": "18.0.9",
        "antd": "^5.0.2",
        "eslint": "8.30.0",
        "eslint-config-next": "13.1.0",
        "next": "13.1.0",
        "react": "18.2.0",
        "react-dom": "18.2.0",
        "typescript": "4.9.4"
    }

`

and I tired antd version downgrade 4.x.x then this problem is not detect

but antd 5.x.x is this problem detected

nextjs version is 12.x.x , 13.x.x no problem


问:
Setting up a data generator for learning a hidden layer
Long time lurker, first-time poster here :)

I am trying to build a CNN in python that will take as input an image and output 25 continuous values predicted from said image. I have a directory containing subdirectories each with the image as a .jpg and the corresponding 25 values stored as a .csv. I have done something similar in the past by reading my images and labels in as numpy arrays but thought it wise to try to learn how to do this with data generators. My code so far is below but as far as I can tell it is not loading the label sets since my model keeps returning an error indicating there is no gradient for it to train on.

I am doing everything in TensorFlow, but am not necessarily married to it. Likewise, I can regenerate how my images and labels are stored so if the way I did it is the problem I am happy to change that structure as well.

Any help or suggestions is appreciated!

Using plt.imshow(train_generator[0][0]) I can confirm the images are loaded correctly.

The specific error I am returning ends with

```<code>
ValueError: No gradients provided for any variable:
</code>```

The relevant code I have so far is:

```<code>
import os, shutil, csv
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

def data_generator(data_dir, batch_size):

# Set up the data generator

datagen = ImageDataGenerator(rescale=1./255)

    # Read in the data from the specified directory
    generator = datagen.flow_from_directory(
        data_dir,
        target_size=image_size,
        batch_size=batch_size,
        class_mode=None,  # since the labels are stored in separate .csv files
        shuffle=True
    )

    # Iterate over the data
    for data_batch, _ in generator:
        # Read in the corresponding .csv file for each image
        labels_batch = []
        for i, filename in enumerate(data_batch):
            # Get the file name without the extension
            file_base = os.path.splitext(filename)[0]

            # Read in the labels from the .csv file
            with open(file_base + '.csv', 'r') as csv_file:
                reader = csv.reader(csv_file)
                labels_batch.append(next(reader))
        yield data_batch, labels_batch

train_generator = data_generator(os.path.join(data_dir, 'train'), batch_size)
</code>```

Skipping a little

```<code>
# Compile the model

model.compile(optimizer='adam', loss='mean_squared_error', metrics=\['accuracy'\])

# Train the model using the data generators

history = model.fit_generator(
train_generator,
steps_per_epoch=len(train_generator),
epochs=10,
validation_data=val_generator,
validation_steps=len(val_generator)
)

# Evaluate the model on the testing data

test_loss, test_acc = model.evaluate_generator(test_generator, steps=len(test_generator))
</code>```

Body:
Long time lurker, first-time poster here :)

I am trying to build a CNN in python that will take as input an image and output 25 continuous values predicted from said image. I have a directory containing subdirectories each with the image as a .jpg and the corresponding 25 values stored as a .csv. I have done something similar in the past by reading my images and labels in as numpy arrays but thought it wise to try to learn how to do this with data generators. My code so far is below but as far as I can tell it is not loading the label sets since my model keeps returning an error indicating there is no gradient for it to train on.

I am doing everything in TensorFlow, but am not necessarily married to it. Likewise, I can regenerate how my images and labels are stored so if the way I did it is the problem I am happy to change that structure as well.

Any help or suggestions is appreciated!

Using plt.imshow(train_generator[0][0]) I can confirm the images are loaded correctly.

The specific error I am returning ends with

ValueError: No gradients provided for any variable:

The relevant code I have so far is:

import os, shutil, csv
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

def data_generator(data_dir, batch_size):

# Set up the data generator

datagen = ImageDataGenerator(rescale=1./255)

    # Read in the data from the specified directory
    generator = datagen.flow_from_directory(
        data_dir,
        target_size=image_size,
        batch_size=batch_size,
        class_mode=None,  # since the labels are stored in separate .csv files
        shuffle=True
    )

    # Iterate over the data
    for data_batch, _ in generator:
        # Read in the corresponding .csv file for each image
        labels_batch = []
        for i, filename in enumerate(data_batch):
            # Get the file name without the extension
            file_base = os.path.splitext(filename)[0]

            # Read in the labels from the .csv file
            with open(file_base + '.csv', 'r') as csv_file:
                reader = csv.reader(csv_file)
                labels_batch.append(next(reader))
        yield data_batch, labels_batch

train_generator = data_generator(os.path.join(data_dir, 'train'), batch_size)

Skipping a little

# Compile the model

model.compile(optimizer='adam', loss='mean_squared_error', metrics=\['accuracy'\])

# Train the model using the data generators

history = model.fit_generator(
train_generator,
steps_per_epoch=len(train_generator),
epochs=10,
validation_data=val_generator,
validation_steps=len(val_generator)
)

# Evaluate the model on the testing data

test_loss, test_acc = model.evaluate_generator(test_generator, steps=len(test_generator))