问:
react-native-pie: Invariant Violation: requireNativeComponent: "ARTShape" was not found in the UIManager
I'm new to react native, and am tring to create a doughnut chart using react-native-pie but when i install and import the package, it says this error:

```<code>Invariant Violation: requireNativeComponent: "ARTShape" was not found in the UIManager.

This error is located at:
    in ARTShape (created by Shape)
    in Shape (created by ArcShape)
    in ArcShape (created by Sections)
    in Sections (created by Pie)
    in ARTGroup (created by Group)
    in Group (created by Pie)
    in ARTSurfaceView (created by Surface)
    in Surface (created by Pie)
    in Pie (created by SpendingHabits)
    in RCTView (created by View)
    in View (created by SpendingHabits)
    in SpendingHabits (created by Home)
    in RCTView (created by View)
    in View (created by Home)
    in RCTView (created by View)
    in View (created by Home)
    in RNCSafeAreaView
    in Unknown (created by Home)
    in RCTView (created by View)
    in View (created by Home)
    in Home (created by Index)
    in RCTView (created by View)
    in View (created by Index)
    in Index (created by App)
    in RCTView (created by View)
    in View (created by App)
    in ThemeProvider (created by Provider)
    in RCTView (created by View)
    in View (created by Portal.Host)
    in Portal.Host (created by Provider)
    in RNCSafeAreaProvider (created by SafeAreaProvider)
    in SafeAreaProvider (created by SafeAreaInsetsContext)
    in SafeAreaProviderCompat (created by Provider)
    in Provider (created by App)
    in App (created by withDevTools(App))
    in withDevTools(App)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:95:17 in reportException
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:141:19 in handleException
at node_modules/react-native/Libraries/Core/ReactFiberErrorDialog.js:52:19 in showErrorDialog
at App.js:56:21 in prepare
</code>```

Also, my code editor is giving out this warning in the import statement:

```<code>Could not find a declaration file for module 'react-native-pie'. '/node_modules/react-native-pie/src/Pie.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/react-native-pie` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-native-pie';`
</code>```
```<code>import Pie from "react-native-pie";
</code>```

Since it is a blank expo project, i couldn't do pod install which seemed to be working for this error.

Body:
I'm new to react native, and am tring to create a doughnut chart using react-native-pie but when i install and import the package, it says this error:

Invariant Violation: requireNativeComponent: "ARTShape" was not found in the UIManager.

This error is located at:
    in ARTShape (created by Shape)
    in Shape (created by ArcShape)
    in ArcShape (created by Sections)
    in Sections (created by Pie)
    in ARTGroup (created by Group)
    in Group (created by Pie)
    in ARTSurfaceView (created by Surface)
    in Surface (created by Pie)
    in Pie (created by SpendingHabits)
    in RCTView (created by View)
    in View (created by SpendingHabits)
    in SpendingHabits (created by Home)
    in RCTView (created by View)
    in View (created by Home)
    in RCTView (created by View)
    in View (created by Home)
    in RNCSafeAreaView
    in Unknown (created by Home)
    in RCTView (created by View)
    in View (created by Home)
    in Home (created by Index)
    in RCTView (created by View)
    in View (created by Index)
    in Index (created by App)
    in RCTView (created by View)
    in View (created by App)
    in ThemeProvider (created by Provider)
    in RCTView (created by View)
    in View (created by Portal.Host)
    in Portal.Host (created by Provider)
    in RNCSafeAreaProvider (created by SafeAreaProvider)
    in SafeAreaProvider (created by SafeAreaInsetsContext)
    in SafeAreaProviderCompat (created by Provider)
    in Provider (created by App)
    in App (created by withDevTools(App))
    in withDevTools(App)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:95:17 in reportException
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:141:19 in handleException
at node_modules/react-native/Libraries/Core/ReactFiberErrorDialog.js:52:19 in showErrorDialog
at App.js:56:21 in prepare

Also, my code editor is giving out this warning in the import statement:

Could not find a declaration file for module 'react-native-pie'. '/node_modules/react-native-pie/src/Pie.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/react-native-pie` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-native-pie';`

import Pie from "react-native-pie";

Since it is a blank expo project, i couldn't do pod install which seemed to be working for this error.


来源: stackexchange

问:
MySQL dropping the indexes (with more than one field) of all exsisting tables except for primary indexes
I am struggling with deleting indexes of each table

that seems quite easy but there are some catches. drop clause takes only one index to be deleted
and mysql gives me an error when i am trying to make a second loop ( which would go through indexes so that i could delete needed ones)

```<code> delimiter &&
 CREATE PROCEDURE dropping_indexes_excpt_for_primaryone()
 BEGIN
    DECLARE done INT DEFAULT 0;

    DECLARE tbl_name VARCHAR(200) DEFAULT '';

    DECLARE all_tables_cursor CURSOR for
     (SELECT TABLE_NAME
      FROM information_schema.tables
      WHERE table_schema = DATABASE()
      AND table_type = 'BASE TABLE');

    DECLARE CONTINUE handler FOR NOT FOUND SET done = 1;
    OPEN all_tables_cursor;
    tables_loop: LOOP
        fetch all_tables_cursor INTO tbl_name;
        if done then
            leave tables_loop;
        END if;
--------------------------------------------------------------------------
                #how can i delete them using the following statement?
                #SELECT index_name  FROM information_schema.STATISTICS WHERE TABLE_NAME= tbl_name AND                                       table_schema= DATABASE()
                 AND index_name <>'PRIMARY'
                 GROUP BY index_name
                 HAVING COUNT(*)>1
 ---------------------------------------------

    END loop tables_loop;
    close all_tables_cursor;
    END;
&&
</code>```

i tried to make a second loop but it didn't work because i needed to have some cursor to store it in
it is impossible to declare cursor not in the begining because table hasn`t been taken yet and ,to the best of my knowledge, it is not legitimate to use declare clause inside the loop (or in general - not in the begining)
i also tried to create a separate procedure to do it but something went wrong there,too
but i would like to do it in one stored procedure

ContentLicense: CC BY-SA 4.0

Body:
I am struggling with deleting indexes of each table

that seems quite easy but there are some catches. drop clause takes only one index to be deleted
and mysql gives me an error when i am trying to make a second loop ( which would go through indexes so that i could delete needed ones)

 delimiter &&
 CREATE PROCEDURE dropping_indexes_excpt_for_primaryone()
 BEGIN
    DECLARE done INT DEFAULT 0;

    DECLARE tbl_name VARCHAR(200) DEFAULT '';

    DECLARE all_tables_cursor CURSOR for
     (SELECT TABLE_NAME
      FROM information_schema.tables
      WHERE table_schema = DATABASE()
      AND table_type = 'BASE TABLE');

    DECLARE CONTINUE handler FOR NOT FOUND SET done = 1;
    OPEN all_tables_cursor;
    tables_loop: LOOP
        fetch all_tables_cursor INTO tbl_name;
        if done then
            leave tables_loop;
        END if;
--------------------------------------------------------------------------
                #how can i delete them using the following statement?
                #SELECT index_name  FROM information_schema.STATISTICS WHERE TABLE_NAME= tbl_name AND                                       table_schema= DATABASE()
                 AND index_name <>'PRIMARY'
                 GROUP BY index_name
                 HAVING COUNT(*)>1
 ---------------------------------------------

    END loop tables_loop;
    close all_tables_cursor;
    END;
&&

i tried to make a second loop but it didn't work because i needed to have some cursor to store it in
it is impossible to declare cursor not in the begining because table hasn`t been taken yet and ,to the best of my knowledge, it is not legitimate to use declare clause inside the loop (or in general - not in the begining)
i also tried to create a separate procedure to do it but something went wrong there,too
but i would like to do it in one stored procedure


问:
The function _getch() behaves unexpectedly in git-bash terminal
I have been trying to figure out how it is possible to change the terminal's mode from "cooked" to "raw" using C and in a Git Bash terminal.

I have tried to execute the program with winpty and that makes that certain part of the program function as expected. However, it messes up the other parts, like clearing the screen with the control sequence \x1b[2J, and vice versa. Clearing the screen works perfectly when I am NOT executing the program with winpty.

I have also tried using system("clear") and system("cls") but with no luck. I have also tried to set the mode using the function _setmode(_fileno(stdin), _O_BINARY) but no such function seems to be working with Git Bash and more specifically MinTTY.

When I am using getch() nothing simply happens and I have to use CTRL+C to exit the program. However, it should exit the program when I press the 'i' character.

The code looks like this:

```<code>#include <windows.h>
#include <conio.h>
#include <stdio.h>

void clear_screen() {
    printf("\\033\[2J");
    printf("\\033\[1;1H");
    fflush(stdout);
}

int main() {
#ifdef _WIN32
    clear_screen();
    while (1) {
        char c = _getch();
        if (c == 'i') {
            exit(0);
        }
    }
#endif

#ifdef linux
#endif
}
</code>```

Body:
I have been trying to figure out how it is possible to change the terminal's mode from "cooked" to "raw" using C and in a Git Bash terminal.

I have tried to execute the program with winpty and that makes that certain part of the program function as expected. However, it messes up the other parts, like clearing the screen with the control sequence \x1b[2J, and vice versa. Clearing the screen works perfectly when I am NOT executing the program with winpty.

I have also tried using system("clear") and system("cls") but with no luck. I have also tried to set the mode using the function _setmode(_fileno(stdin), _O_BINARY) but no such function seems to be working with Git Bash and more specifically MinTTY.

When I am using getch() nothing simply happens and I have to use CTRL+C to exit the program. However, it should exit the program when I press the 'i' character.

The code looks like this:

#include <windows.h>
#include <conio.h>
#include <stdio.h>

void clear_screen() {
    printf("\\033\[2J");
    printf("\\033\[1;1H");
    fflush(stdout);
}

int main() {
#ifdef _WIN32
    clear_screen();
    while (1) {
        char c = _getch();
        if (c == 'i') {
            exit(0);
        }
    }
#endif

#ifdef linux
#endif
}


问:
Android WebView: Request permission to access camera
I am trying to develop an app using HTML and JavaScript which uses camera. But when I export the app using android Studio, the app doesn't request the permission to access camera. So I allowed it manually. Then, it seems the camera worked, but still the problem is that the camera freezes and will continue to work only when I keep touching the screen.

Here is the codes:

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.CameraTest"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>
</code>```

MainActivity.java

```<code>package com.test.camera;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;

import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

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

        WebView webView=findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
        webView.setWebChromeClient(new WebChromeClient() {});
    }
}
</code>```

index.html

```<code><html>
  <head>
    <title>Video</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
      .fitter {
          max-width: 100%;
          height: auto;
      }
    </style>
  </head>
  <body>
    <div id="camScrn" class="scrn">
      <div id="title" style="position: fixed; left: 0px; top: 5px; width: 100%; text-align: center;">Top</div>
      <div style="position: absolute; left: 0px; top: 0px;">
        <video class="fitter" id="video" style="position: fixed; width: 100%; height: 100%"></video>
      </div>
    </div>
  </body>
  <script src="code.js"></script>
</html>
</code>```

code.js

```<code>//Camera Setup
navigator.mediaDevices
  .getUserMedia({ video: { width: parseInt(screen.height), height: parseInt(screen.width), facingMode: { exact: "environment" }}, audio: false})
  .then((stream) => {
    video.srcObject = stream;
    video.play();
  })
  .catch((err) => {
    console.error(`An error occurred: ${err}`);
  });
</code>```

I browsed a lot and tried all of it, but still it doesn't seem to work. Maybe it could be because I am just a beginner in Java.

Body:
I am trying to develop an app using HTML and JavaScript which uses camera. But when I export the app using android Studio, the app doesn't request the permission to access camera. So I allowed it manually. Then, it seems the camera worked, but still the problem is that the camera freezes and will continue to work only when I keep touching the screen.

Here is the codes:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.CameraTest"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

MainActivity.java

package com.test.camera;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;

import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

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

        WebView webView=findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
        webView.setWebChromeClient(new WebChromeClient() {});
    }
}

index.html

    <title>Video</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Top

        <video class="fitter" id="video" style="position: fixed; width: 100%; height: 100%"></video>

code.js

//Camera Setup
navigator.mediaDevices
  .getUserMedia({ video: { width: parseInt(screen.height), height: parseInt(screen.width), facingMode: { exact: "environment" }}, audio: false})
  .then((stream) => {
    video.srcObject = stream;
    video.play();
  })
  .catch((err) => {
    console.error(`An error occurred: ${err}`);
  });

I browsed a lot and tried all of it, but still it doesn't seem to work. Maybe it could be because I am just a beginner in Java.


问:
Store multiple data with file upload and insert in multiple rows in database
I want to store some data in multiple rows in database. I can store this data without any file. But I cannot store data with file. How can I store data with upload file and also empty file field. Please help. It will be more helpful for me.

My contoller is look like this:

```<code>public function store(Request $request) {
        $id = '12';

        foreach($request->pass_issue_con as $key=>$v) {
            $data = [
                'emp_id'=>$id,
                'pass_issue_con'=>$v,
                'pass_no'=>$request->pass_no[$key],
                'pass_issue'=>$request->pass_issue[$key],
                'pass_expiry'=>$request->pass_expiry[$key],
                'pass_biometric'=>$request->pass_biometric[$key],
                'pass_doc'=>$request->pass_doc[$key]
                ];
                EmployeeTravelDocumentsInfo::insert($data);
        }

    return redirect()->back()->with('message', 'Data Has Been Submitted Successfully!');
}
</code>```

My Blade file is look like this:

```<code><form action="{{ route('registration.store') }}" method="post" enctype="multipart/form-data">
 @csrf

<td>
<select class="form-control select2" style="width: 100%;" name="pass_issue_con[]">
 <option value="N/A">Choose an item...</option>
   @foreach( $countries as $country)
   <option value="{{$country->id}}">{{$country->nicename}}</option>
 @endforeach
</select>
</td>
                        <td><input type="text" name="pass_no[]" class="form-control" style="width:160px;"></td>
                        <td><input type="date" name="pass_issue[]" class="form-control"></td>
                        <td><input type="date" name="pass_expiry[]" class="form-control"></td>
                        <td>
                        <select class="form-control select2" style="width: 100%;" name="pass_biometric[]">
                      <option>Choose an item...</option>
                    <option value="0">Yes</option>
                    <option value="1">No</option>
                  </select>
                  </td>
                  <td><input type="file" class="form-control" name="pass_doc[]" style="width:160px;" multiple></td>
                      </tr>
                  </tbody>
           </table>

            </div>
            <div class="row">
              <div class="col-md-12 mt-3 pb-3 pr-3 text-right"><input type="submit" name="" value="SAVE" class="btn btn-lg btn-success"></div>
          </div>
              </form>

$('.pass thead').on('click', '.passAdd', function(){
          var pass = "<tr>"+
                        "<td><a href='javascript:void(0)' class='btn btn-sm btn-danger passDelete'>-</a></td>"+
                          "<td>"+
                            "<select class='form-control select2' style='width: 100%;' name='pass_issue_con[]'>"+
                            "<option>Choose an item...</option>"+
                            "@foreach( $countries as $country)"+
                            "<option value='{{$country->id}}'>{{$country->nicename}}</option>"+
                            "@endforeach"+
                            "</select>"+
                          "</td>"+
                          "<td class='column'><input type='text' name='pass_no[]' class='form-control'></td>"+
                          "<td class='column'><input type='date' name='pass_issue[]' class='form-control'></td>"+
                          "<td class='column'><input type='date' name='pass_expiry[]' class='form-control'></td>"+
                          "<td class='column'><select class='form-control' style='width: 100%;' name='pass_biometric[]'>"+
                      "<option>Choose an item...</option>"+
                    "<option value='0'>Yes</option>"+
                    "<option value='1'>No</option>"+
                  "</select>"+
                  "</td>"+
                  "<td><input type='file' class='form-control' name='pass_doc[]'></td>"+
                  "</tr>"

        $('.pass tbody').append(pass);
        $('.pass tbody').on('click', '.passDelete', function(){
            $(this).parent().parent().remove();
        });
      });
</code>```

Body:
I want to store some data in multiple rows in database. I can store this data without any file. But I cannot store data with file. How can I store data with upload file and also empty file field. Please help. It will be more helpful for me.

My contoller is look like this:

public function store(Request $request) {
        $id = '12';

        foreach($request->pass_issue_con as $key=>$v) {
            $data = [
                'emp_id'=>$id,
                'pass_issue_con'=>$v,
                'pass_no'=>$request->pass_no[$key],
                'pass_issue'=>$request->pass_issue[$key],
                'pass_expiry'=>$request->pass_expiry[$key],
                'pass_biometric'=>$request->pass_biometric[$key],
                'pass_doc'=>$request->pass_doc[$key]
                ];
                EmployeeTravelDocumentsInfo::insert($data);
        }

    return redirect()->back()->with('message', 'Data Has Been Submitted Successfully!');
}

My Blade file is look like this:

<form action="{{ route('registration.store') }}" method="post" enctype="multipart/form-data">
 @csrf

<select class="form-control select2" style="width: 100%;" name="pass_issue_con[]">
 <option value="N/A">Choose an item...</option>
   @foreach( $countries as $country)
   <option value="{{$country->id}}">{{$country->nicename}}</option>
 @endforeach
</select>

                        <input type="text" name="pass_no[]" class="form-control" style="width:160px;">
                        <input type="date" name="pass_issue[]" class="form-control">
                        <input type="date" name="pass_expiry[]" class="form-control">

                        <select class="form-control select2" style="width: 100%;" name="pass_biometric[]">
                      <option>Choose an item...</option>
                    <option value="0">Yes</option>
                    <option value="1">No</option>
                  </select>

                  <input type="file" class="form-control" name="pass_doc[]" style="width:160px;" multiple>

<input type="submit" name="" value="SAVE" class="btn btn-lg btn-success">

              </form>

$('.pass thead').on('click', '.passAdd', function(){
          var pass = "
"+
                        "-	"+
                          ""+
                            "<select class='form-control select2' style='width: 100%;' name='pass_issue_con[]'>"+
                            "<option>Choose an item...</option>"+
                            "@foreach( $countries as $country)"+
                            "<option value='{{$country->id}}'>{{$country->nicename}}</option>"+
                            "@endforeach"+
                            "</select>"+
                          "	"+
                          "<input type='text' name='pass_no[]' class='form-control'>	"+
                          "<input type='date' name='pass_issue[]' class='form-control'>	"+
                          "<input type='date' name='pass_expiry[]' class='form-control'>	"+
                          "<select class='form-control' style='width: 100%;' name='pass_biometric[]'>"+
                      "<option>Choose an item...</option>"+
                    "<option value='0'>Yes</option>"+
                    "<option value='1'>No</option>"+
                  "</select>"+
                  "	"+
                  "<input type='file' class='form-control' name='pass_doc[]'>	"+
                  "
"

        $('.pass tbody').append(pass);
        $('.pass tbody').on('click', '.passDelete', function(){
            $(this).parent().parent().remove();
        });
      });


问:
Should I use single Tweepy instance for multiple bots or create a new one for each?
I'm creating several Twitter bots using Tweepy. All of those run on the same account so the api keys and tokens are same.

Let's say one bot likes tweets. Another bot retweets tweets. Should I create a separate Tweepy for each one or should I create one instance and use that in all bots? What is the better practice?


问:
Limit Signals Interval
So I want RSI to give a signal, draw a box, and then ignore the rest of the signals for 50 bars interval.

Right now it draws boxes after each signal it gets

How do I go about fixing it?

```<code>//@version=5
indicator("RSI PROP Strategy 4", overlay=true)

//RSI Inputs
length = input(14)
overSold = input(30 )
overBought = input(70)
price = close
vrsi = ta.rsi(price, length)
co = ta.crossover(vrsi, overSold)
cu = ta.crossunder(vrsi, overBought)

if (not na(vrsi))
    if (cu) or (co)
        box.new(left=bar_index, top=open + open * 0.000025 / syminfo.mintick, right=bar_index + 50, bottom=open - open * 0.000025 / syminfo.mintick, border_width=boxBorderSize)
</code>```

Title: Limit Signals Interval

Body:
So I want RSI to give a signal, draw a box, and then ignore the rest of the signals for 50 bars interval.

Right now it draws boxes after each signal it gets

How do I go about fixing it?

//@version=5
indicator("RSI PROP Strategy 4", overlay=true)

//RSI Inputs
length = input(14)
overSold = input(30 )
overBought = input(70)
price = close
vrsi = ta.rsi(price, length)
co = ta.crossover(vrsi, overSold)
cu = ta.crossunder(vrsi, overBought)

if (not na(vrsi))
    if (cu) or (co)
        box.new(left=bar_index, top=open + open * 0.000025 / syminfo.mintick, right=bar_index + 50, bottom=open - open * 0.000025 / syminfo.mintick, border_width=boxBorderSize)


问:
CSS - IOS Keyboard shifts whole document up
I have a Text Messaging Mobile Site App that has the following divisions and CSS

.messageDisplay {
  background-color: #ffffff;
  position: absolute;
  z-index: 99999;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: hidden;
  overflow-x: hidden;
  visibility: hidden;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  transform: translateY(100%);
}

.messageDisplayHeader {
  display: flex;
  padding-top: 0.5em;
  padding-bottom: 0.5em;
  padding-left: 1em;
  padding-right: 1em;
  align-items: center;
  background-color: #ffffff;
  position: relative;
  box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 4px;
}

.messageDisplayTextboxArea {
  height: 3.5em;
  position: relative;
  box-shadow: rgb(0 0 0 / 16%) 0px -1px 4px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding-left: 0.5em;
  padding-right: 0.5em;
  padding-top: 0.2em;
  padding-bottom: 0.2em;
  background-color: #000000;
}

.messageTextbox {
  resize: none;
  height: 2.5em;
  width: calc(100% - 14%);
  background-color: #fef3f1;
  border: none;
  border-radius: 100px;
  padding-left: 1em;
  padding-top: 0.5em;
  padding-right: 1em;
  color: #fc768a;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="messageDisplay" id="messageDisplay">
  <div class="messageDisplayHeader"></div>
  <div class="messageDisplayBody" id="messageDisplayBody">

  </div>
  <div class="messageDisplayTextboxArea" id="messageDisplayTextboxArea">
    <textarea id="messageTextbox" class="messageTextbox" maxlength="300" placeholder="Type a message"></textarea>
    <div class="messageSendBtn" id="messageSendBtn">
      <i data-feather="chevron-right"></i>
    </div>
  </div>
</div></code>```

When using an IOS Device to focus in on the textarea the whole page shifts up.
When the textarea is focused out, the page stays shifted upwards.

I tried to solve this by doing the following:

var messageTextBoxEle = document.getElementById('messageTextbox');
  messageTextBoxEle.onfocus = function(){
  window.scrollTo(0, 0);
  document.body.scrollTop = 0;
}
```

Right now it behaves as such

I also tried setting the page's margin-bottom:0; when the textarea is focused out but it doesnt seem to work.

Anyone have suggestions?

Body:
I have a Text Messaging Mobile Site App that has the following divisions and CSS

.messageDisplay {
  background-color: #ffffff;
  position: absolute;
  z-index: 99999;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: hidden;
  overflow-x: hidden;
  visibility: hidden;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  transform: translateY(100%);
}

.messageDisplayHeader {
  display: flex;
  padding-top: 0.5em;
  padding-bottom: 0.5em;
  padding-left: 1em;
  padding-right: 1em;
  align-items: center;
  background-color: #ffffff;
  position: relative;
  box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 4px;
}

.messageDisplayTextboxArea {
  height: 3.5em;
  position: relative;
  box-shadow: rgb(0 0 0 / 16%) 0px -1px 4px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding-left: 0.5em;
  padding-right: 0.5em;
  padding-top: 0.2em;
  padding-bottom: 0.2em;
  background-color: #000000;
}

.messageTextbox {
  resize: none;
  height: 2.5em;
  width: calc(100% - 14%);
  background-color: #fef3f1;
  border: none;
  border-radius: 100px;
  padding-left: 1em;
  padding-top: 0.5em;
  padding-right: 1em;
  color: #fc768a;
}

    <textarea id="messageTextbox" class="messageTextbox" maxlength="300" placeholder="Type a message"></textarea>

When using an IOS Device to focus in on the textarea the whole page shifts up.
When the textarea is focused out, the page stays shifted upwards.

I tried to solve this by doing the following:

var messageTextBoxEle = document.getElementById('messageTextbox');
  messageTextBoxEle.onfocus = function(){
  window.scrollTo(0, 0);
  document.body.scrollTop = 0;
}

Right now it behaves as such

I also tried setting the page's margin-bottom:0; when the textarea is focused out but it doesnt seem to work.

Anyone have suggestions?


问:
More Waiting in request in python(pymssql)
i use request  from pymssql and in a loop i use  this code :

this code is working in loop . but sometimes not working  in this line and waiting or stop in this line without any error and however much i will wait program freez and i must stop and start this code for working ...

```<code>

   schedule.every(30).seconds.do(Quantity)

</code>```

and function Quantity is :

```<code>def Quantity():
    z = "Token"
    sql1 = "exec dbo.Quantity"
    dt = datetime.now().strftime('%Y-%m-%d-%H-%M')
    cursor3 = conn.cursor()
    cursor3.execute(sql1)
    conn.commit()
    sublist=[]
    sqltest = 'select distinct storeid from Quantity'
    cursor = conn.cursor()

    cursor.execute(sqltest)

    result = cursor.fetchall()
    conn.commit()
    for x in result:
        sublist.extend(x)

    #print(sublist)
    if sublist:
        for y in sublist:

        sql3=f"select * from Quantity where storeid = {y}"
            cursor4 = conn.cursor()

            cursor4.execute(sql3)
            result2 = cursor4.fetchall()
            insertObject = []
            columnNames = [column[0] for column in cursor4.description]
            NewColumn=columnNames[1:]
            for record in result2:
                insertObject.append(dict(zip(columnNames, record)))
            storeid = y
            #print(insertObject)
            #print(storeid)
            data2 = json.dumps({
                "storeCode": y,
                "products": insertObject
            }
            )
            try :
                print('quantity')
            except :
                print('No Data Quantity')
            headers = {
                'Authorization': z,
                'Content-Type': 'application/json'
            }
            response2 = requests.request("POST", url2, headers=headers, data=data2, timeout=30)
            uz=response2.status_code
            print(str(uz) +' ' +dt)
            if u == 200:
        print('Success '+ dt)
    else :
        print('No_Data_For_Quantity '+ dt)
</code>```

Body:
i use request  from pymssql and in a loop i use  this code :

this code is working in loop . but sometimes not working  in this line and waiting or stop in this line without any error and however much i will wait program freez and i must stop and start this code for working ...

   schedule.every(30).seconds.do(Quantity)

and function Quantity is :

def Quantity():
    z = "Token"
    sql1 = "exec dbo.Quantity"
    dt = datetime.now().strftime('%Y-%m-%d-%H-%M')
    cursor3 = conn.cursor()
    cursor3.execute(sql1)
    conn.commit()
    sublist=[]
    sqltest = 'select distinct storeid from Quantity'
    cursor = conn.cursor()

    cursor.execute(sqltest)

    result = cursor.fetchall()
    conn.commit()
    for x in result:
        sublist.extend(x)

    #print(sublist)
    if sublist:
        for y in sublist:

        sql3=f"select * from Quantity where storeid = {y}"
            cursor4 = conn.cursor()

            cursor4.execute(sql3)
            result2 = cursor4.fetchall()
            insertObject = []
            columnNames = [column[0] for column in cursor4.description]
            NewColumn=columnNames[1:]
            for record in result2:
                insertObject.append(dict(zip(columnNames, record)))
            storeid = y
            #print(insertObject)
            #print(storeid)
            data2 = json.dumps({
                "storeCode": y,
                "products": insertObject
            }
            )
            try :
                print('quantity')
            except :
                print('No Data Quantity')
            headers = {
                'Authorization': z,
                'Content-Type': 'application/json'
            }
            response2 = requests.request("POST", url2, headers=headers, data=data2, timeout=30)
            uz=response2.status_code
            print(str(uz) +' ' +dt)
            if u == 200:
        print('Success '+ dt)
    else :
        print('No_Data_For_Quantity '+ dt)


问:
ktor client: cant catch ConnectException even when I catch all Exceptions and Throwables
I'm using ktor client to make a simple REST request, when a network exception error occurs inside the client.get() call, I cannot catch this error no matter what I do and it causes the app to crash.

Keep in mind, I'm NOT trying to find the cause/solution of the crash, I'm trying to figure out how I can catch the Exception so the app doesnt crash.

here are all things I've tried:

```<code>try {

        val response = runCatching {
            client.post("$BASE_URL/api/users/login")
        }.getOrElse {
            throw it
        }

        return Result.Success(response.body())
    } catch (e: RedirectResponseException) { // 3xx
        Result.Error(e, e.response.status.description)
    } catch (e: ClientRequestException) { // 4xx
        Result.Error(e, e.response.status.description)
    } catch (e: ServerResponseException) { // 5xx
        Result.Error(e, e.response.status.description)
    } catch (e: java.net.ConnectException) {
        Result.Error(e, e.message.orEmpty())
    } catch (e: Exception) {
        Result.Error(e, e.message.orEmpty())
    } catch (e: Throwable) {
        Result.Error(java.lang.Exception(), e.message.orEmpty())
    }
</code>```

None of these is able to catch the crash.
I'm assuming the crash is happening on another thread or process and that's why I cant catch it, and that I need to add some sort of error handler to the httpClient during initialization, However I cant figure out how to do this. This is what I have so far in my httpClient Initialization:

```<code>val client = HttpClient(Android) {
        install(Logging) {
            level = LogLevel.ALL
        }
        install(ContentNegotiation) {
            json(Json {
                prettyPrint = true
                isLenient = true
                ignoreUnknownKeys = true
            })
        }

    }
</code>```

The actauly exception that's causing my app to crash is this:

```<code>java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8090
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:147)
</code>```

Body:
I'm using ktor client to make a simple REST request, when a network exception error occurs inside the client.get() call, I cannot catch this error no matter what I do and it causes the app to crash.

Keep in mind, I'm NOT trying to find the cause/solution of the crash, I'm trying to figure out how I can catch the Exception so the app doesnt crash.

here are all things I've tried:

try {

        val response = runCatching {
            client.post("$BASE_URL/api/users/login")
        }.getOrElse {
            throw it
        }

        return Result.Success(response.body())
    } catch (e: RedirectResponseException) { // 3xx
        Result.Error(e, e.response.status.description)
    } catch (e: ClientRequestException) { // 4xx
        Result.Error(e, e.response.status.description)
    } catch (e: ServerResponseException) { // 5xx
        Result.Error(e, e.response.status.description)
    } catch (e: java.net.ConnectException) {
        Result.Error(e, e.message.orEmpty())
    } catch (e: Exception) {
        Result.Error(e, e.message.orEmpty())
    } catch (e: Throwable) {
        Result.Error(java.lang.Exception(), e.message.orEmpty())
    }

None of these is able to catch the crash.
I'm assuming the crash is happening on another thread or process and that's why I cant catch it, and that I need to add some sort of error handler to the httpClient during initialization, However I cant figure out how to do this. This is what I have so far in my httpClient Initialization:

val client = HttpClient(Android) {
        install(Logging) {
            level = LogLevel.ALL
        }
        install(ContentNegotiation) {
            json(Json {
                prettyPrint = true
                isLenient = true
                ignoreUnknownKeys = true
            })
        }

    }

The actauly exception that's causing my app to crash is this:

java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8090
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:147)


问:
How can I decrypt the password sent by OpenVPN on a custom RADIUS server with a private key?
I am trying to use a Custom RADIUS server with MikroTik based OVPN server for authenticating my VPN clients, but I have some issue with TLS Setup, that the password is encrypted and we couldn't decrypt it even with Private Key.

According to the articles of NetworkRadius.com, I using PAP protocol.
RADIUS Server Development is based on .NET


问:
Restore Auto renewal subscription in iOS
I have implemented auto-renewal subscription in iOS by swift language. The plan is for 1 year and has 3 days trial, the purchase is working perfectly. For checking if user has already buy a subscription or not, for that I am restoring purchases every time when app will open, and that also works. but problem is even subscription is expired or i have canceled from Settings > App Store > Sandbox account > Manage > Subscription then also restored the purchase successfully. I think should be not work right?

I am using SwiftyStoreKit package for handle in-app purchase.

How should I restore purchases?

```<code>    SwiftyStoreKit.restorePurchases(atomically: true) { results in
        if results.restoreFailedPurchases.count > 0 {
            print("Restore Failed: \(results.restoreFailedPurchases)")
        }
        else if results.restoredPurchases.count > 0 {
            print("Restore Success: \(results.restoredPurchases)")
        }
        else {
            print("Nothing to Restore")
        }
    }
</code>```

Body:
I have implemented auto-renewal subscription in iOS by swift language. The plan is for 1 year and has 3 days trial, the purchase is working perfectly. For checking if user has already buy a subscription or not, for that I am restoring purchases every time when app will open, and that also works. but problem is even subscription is expired or i have canceled from Settings > App Store > Sandbox account > Manage > Subscription then also restored the purchase successfully. I think should be not work right?

I am using SwiftyStoreKit package for handle in-app purchase.

How should I restore purchases?

    SwiftyStoreKit.restorePurchases(atomically: true) { results in
        if results.restoreFailedPurchases.count > 0 {
            print("Restore Failed: \(results.restoreFailedPurchases)")
        }
        else if results.restoredPurchases.count > 0 {
            print("Restore Success: \(results.restoredPurchases)")
        }
        else {
            print("Nothing to Restore")
        }
    }


问:
getting undefined from my req.body, was working originally but after attempting to upload to heroku it won't work anymore
```<code>app.post('/register', (req, res) => {
  const { email, name, password } = req.body;
  if (!email || !name || !password) {
    return res
      .status(400)
      .json(
        `incorrect form submission ${console.log({ email, name, password })}`
      );
  }
  const hash = bcrypt.hashSync(password);
  postgres.transaction((trx) => {
    trx
      .insert({
        hash: hash,
        email: email,
      })
      .into('login')
      .returning('email')
      .then((loginEmail) => {
        return trx('users')
          .returning('*')
          .insert({
            email: loginEmail[0].email,
            name: name,
            joined: new Date(),
          })
          .then((user) => {
            res.json(user[0]);
          })
          .then(trx.commit)
          .catch(trx.rollback);
      })
      .catch((err) => res.status(400).json('unable to register'));
  });
});
</code>```

when i enter information into my form it should either return incorrect form submission if anything is missing or continue with the rest of the code but no matter what I put in it always returns with "incorrect form submission" and when i try to console log my req.body objects it returns undefined for all 3
postgres is the name of how i declare my database

import React from 'react';

class Register extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            email: '',
            password: '',
            name: ''
        }
    }

    onNameChange = (event) => {
        this.setState({name: event.target.value})
    }

    onEmailChange = (event) => {
        this.setState({email: event.target.value})
    }

    onPasswordChange = (event) => {
        this.setState({password: event.target.value})
    }

    onSubmitSignIn = () => {

        fetch("https://morning-brushlands-83652.herokuapp.com/register", {
            method: 'post',
            mode: "no-cors",
            headers: {'Content-Type': "application/json"},
            body: JSON.stringify({
                email: this.state.email,
                password: this.state.password,
                name: this.state.name

            })
        })
        //.then(response => response.json())
        .then(
            user => {
                if (user.id) {

                    this.props.loadUser(user)
                    this.props.onRouteChange('home')

                }
            }
        )
    }

    render() {

        return (

                    <form className="measure">
                        <fieldset id="sign_up" className="ba b--transparent ph0 mh0">
                            <legend className="f1 fw6 ph0 mh0">Register</legend>

                                Name
                                <input
                                className="pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
                                type="text"
                                name="name"
                                id="name"
                                onChange = {this.onNameChange}
                                />

                                Email
                                <input
                                className="pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
                                type="email"
                                name="email-address"
                                id="email-address"
                                onChange = {this.onEmailChange}
                                />

                                Password
                                <input className="b pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
                                type="password"
                                name="password"
                                id="password"
                                onChange = {this.onPasswordChange}
                                />

                        </fieldset>

                            <input
                                onClick={this.onSubmitSignIn}
                                className="b ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
                                type="button"
                                value="Register"
                            />

                    </form>

        )
    }
}

export default Register;```

Body:
app.post('/register', (req, res) => {
  const { email, name, password } = req.body;
  if (!email || !name || !password) {
    return res
      .status(400)
      .json(
        `incorrect form submission ${console.log({ email, name, password })}`
      );
  }
  const hash = bcrypt.hashSync(password);
  postgres.transaction((trx) => {
    trx
      .insert({
        hash: hash,
        email: email,
      })
      .into('login')
      .returning('email')
      .then((loginEmail) => {
        return trx('users')
          .returning('*')
          .insert({
            email: loginEmail[0].email,
            name: name,
            joined: new Date(),
          })
          .then((user) => {
            res.json(user[0]);
          })
          .then(trx.commit)
          .catch(trx.rollback);
      })
      .catch((err) => res.status(400).json('unable to register'));
  });
});

when i enter information into my form it should either return incorrect form submission if anything is missing or continue with the rest of the code but no matter what I put in it always returns with "incorrect form submission" and when i try to console log my req.body objects it returns undefined for all 3
postgres is the name of how i declare my database

import React from 'react';

class Register extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            email: '',
            password: '',
            name: ''
        }
    }

    onNameChange = (event) => {
        this.setState({name: event.target.value})
    }

    onEmailChange = (event) => {
        this.setState({email: event.target.value})
    }

    onPasswordChange = (event) => {
        this.setState({password: event.target.value})
    }

    onSubmitSignIn = () => {

        fetch("https://morning-brushlands-83652.herokuapp.com/register", {
            method: 'post',
            mode: "no-cors",
            headers: {'Content-Type': "application/json"},
            body: JSON.stringify({
                email: this.state.email,
                password: this.state.password,
                name: this.state.name

            })
        })
        //.then(response => response.json())
        .then(
            user => {
                if (user.id) {

                    this.props.loadUser(user)
                    this.props.onRouteChange('home')

                }
            }
        )
    }

    render() {

        return (

                    <form className="measure">
                        <fieldset id="sign_up" className="ba b--transparent ph0 mh0">
                            <legend className="f1 fw6 ph0 mh0">Register</legend>

                                Name
                                <input
                                className="pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
                                type="text"
                                name="name"
                                id="name"
                                onChange = {this.onNameChange}
                                />

                                Email
                                <input
                                className="pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
                                type="email"
                                name="email-address"
                                id="email-address"
                                onChange = {this.onEmailChange}
                                />

                                Password
                                <input className="b pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
                                type="password"
                                name="password"
                                id="password"
                                onChange = {this.onPasswordChange}
                                />

                        </fieldset>

                            <input
                                onClick={this.onSubmitSignIn}
                                className="b ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
                                type="button"
                                value="Register"
                            />

                    </form>

        )
    }
}

export default Register;


问:
How to Crop an Image before Image Classification with TFLite on Android Studio?
I am trying to create an app that can classify an image using TFlite, based upon a learned model created on Teachable Machine.

I am struggling to find a way to give the user an option to crop the image before it is classified. Here is my code for the Java class:

```<code>package com.example.app;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.app.R;
import com.example.app.ml.Model;

import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class MainActivity extends AppCompatActivity {

    TextView result, confidence;
    ImageView imageView;
    Button picture;
    int imageSize = 224;

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

        result = findViewById(R.id.result);
        confidence = findViewById(R.id.confidence);
        imageView = findViewById(R.id.imageView);
        picture = findViewById(R.id.button);

        picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Launch camera if we have permission
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(cameraIntent, 1);
                    } else {
                        //Request camera permission if we don't have it.
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
                    }
                }
            }
        });
    }

    public void classifyImage(Bitmap image){
        try {
            Model model = Model.newInstance(getApplicationContext());

            // Creates inputs for reference.
            TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 224, 224, 3}, DataType.FLOAT32);
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * imageSize * imageSize * 3);
            byteBuffer.order(ByteOrder.nativeOrder());

            int [] intValues = new int[imageSize * imageSize];
            image.getPixels(intValues, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
            int pixel = 0;
            for(int i = 0; i < imageSize; i++){
                for(int j = 0; j < imageSize; j++){
                    int val = intValues[pixel++]; // RGB
                    byteBuffer.putFloat(((val >> 16 ) & 0xFF) * (1.f / 255.f));
                    byteBuffer.putFloat(((val >> 8 ) & 0xFF) * (1.f / 255.f));
                    byteBuffer.putFloat((val & 0xFF  ) * (1.f / 255.f));
                }
            }

            inputFeature0.loadBuffer(byteBuffer);

            // Runs model inference and gets result.
            Model.Outputs outputs = model.process(inputFeature0);
            TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();

            float[] confidences = outputFeature0.getFloatArray();
            int maxPos = 0;
            float maxConfidence = 0;
            for(int i = 0; i < confidences.length; i++){
                if(confidences[i] > maxConfidence){
                    maxConfidence = confidences[i];
                    maxPos = i;
                }
            }
            String[] classes = {"Negative", "+/-100", "250", "500", "1000", ">=2000"};

            result.setText(classes[maxPos]);

            String s = "";
            for(int i = 0; i < classes.length; i++){
                s += String.format("%s: %.1f%%\n", classes[i], confidences[i] * 100);
            }

            confidence.setText(s);

            // Releases model resources if no longer used.
            model.close();
        } catch (IOException e) {
            // TODO Handle the exception
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK) {

            Bitmap image = (Bitmap) data.getExtras().get("data");
            int dimension = Math.min(image.getWidth(), image.getHeight());
            image = ThumbnailUtils.extractThumbnail(image, dimension, dimension);
            imageView.setImageBitmap(image);

            image = Bitmap.createScaledBitmap(image, imageSize, imageSize, false);
            System.out.println(image);
            classifyImage(image);

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
</code>```

This is the video tutorial I followed: https://www.youtube.com/watch?v=jhGm4KDafKU

I found a tutorial to be able to crop an image from your gallery and display it in the image view, however I wasn't able to link this with my image classification. This is the part of the code I edited to try and link these together:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 100 && resultCode == 101){
        String result = data.getStringExtra("CROP");
        Uri uri = data.getData();

        if (result!=null){
            uri = Uri.parse(result);
        }

        binding.imageView.setImageURI(uri);

       // I added this:

        try {

            Bitmap image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);

            int dimension = Math.min(image.getWidth(), image.getHeight());

            image = ThumbnailUtils.extractThumbnail(image, dimension, dimension);

            image = Bitmap.createScaledBitmap(image, imageSize, imageSize, false);

            classifyImage(image);

        } catch (IOException e) {
            e.printStackTrace();

        }

    }
}
</code>```

However, it always results in the activity crashing, these are the errors:

```<code>I/BitmapCropTask: Should crop: true
I/tflite: Initialized TensorFlow Lite runtime.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.phoenixapp, PID: 21124
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=101, data=Intent { (has extras) }} to activity {com.example.phoenixapp/com.example.phoenixapp.Tensor}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5301)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5340)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54)
        at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.phoenixapp.Tensor.classifyImage(Tensor.java:113)
        at com.example.phoenixapp.Tensor.onActivityResult(Tensor.java:184)
        at android.app.Activity.dispatchActivityResult(Activity.java:8382)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5294)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5340)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54)
        at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
I/Process: Sending signal. PID: 21124 SIG: 9
</code>```

Is there a simple solution to be able to perform image classification, whilst being able to crop the image beforehand?

Body:
I am trying to create an app that can classify an image using TFlite, based upon a learned model created on Teachable Machine.

I am struggling to find a way to give the user an option to crop the image before it is classified. Here is my code for the Java class:

package com.example.app;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.app.R;
import com.example.app.ml.Model;

import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class MainActivity extends AppCompatActivity {

    TextView result, confidence;
    ImageView imageView;
    Button picture;
    int imageSize = 224;

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

        result = findViewById(R.id.result);
        confidence = findViewById(R.id.confidence);
        imageView = findViewById(R.id.imageView);
        picture = findViewById(R.id.button);

        picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Launch camera if we have permission
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(cameraIntent, 1);
                    } else {
                        //Request camera permission if we don't have it.
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
                    }
                }
            }
        });
    }

    public void classifyImage(Bitmap image){
        try {
            Model model = Model.newInstance(getApplicationContext());

            // Creates inputs for reference.
            TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 224, 224, 3}, DataType.FLOAT32);
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * imageSize * imageSize * 3);
            byteBuffer.order(ByteOrder.nativeOrder());

            int [] intValues = new int[imageSize * imageSize];
            image.getPixels(intValues, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
            int pixel = 0;
            for(int i = 0; i < imageSize; i++){
                for(int j = 0; j < imageSize; j++){
                    int val = intValues[pixel++]; // RGB
                    byteBuffer.putFloat(((val >> 16 ) & 0xFF) * (1.f / 255.f));
                    byteBuffer.putFloat(((val >> 8 ) & 0xFF) * (1.f / 255.f));
                    byteBuffer.putFloat((val & 0xFF  ) * (1.f / 255.f));
                }
            }

            inputFeature0.loadBuffer(byteBuffer);

            // Runs model inference and gets result.
            Model.Outputs outputs = model.process(inputFeature0);
            TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();

            float[] confidences = outputFeature0.getFloatArray();
            int maxPos = 0;
            float maxConfidence = 0;
            for(int i = 0; i < confidences.length; i++){
                if(confidences[i] > maxConfidence){
                    maxConfidence = confidences[i];
                    maxPos = i;
                }
            }
            String[] classes = {"Negative", "+/-100", "250", "500", "1000", ">=2000"};

            result.setText(classes[maxPos]);

            String s = "";
            for(int i = 0; i < classes.length; i++){
                s += String.format("%s: %.1f%%\n", classes[i], confidences[i] * 100);
            }

            confidence.setText(s);

            // Releases model resources if no longer used.
            model.close();
        } catch (IOException e) {
            // TODO Handle the exception
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK) {

            Bitmap image = (Bitmap) data.getExtras().get("data");
            int dimension = Math.min(image.getWidth(), image.getHeight());
            image = ThumbnailUtils.extractThumbnail(image, dimension, dimension);
            imageView.setImageBitmap(image);

            image = Bitmap.createScaledBitmap(image, imageSize, imageSize, false);
            System.out.println(image);
            classifyImage(image);

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

This is the video tutorial I followed: https://www.youtube.com/watch?v=jhGm4KDafKU

I found a tutorial to be able to crop an image from your gallery and display it in the image view, however I wasn't able to link this with my image classification. This is the part of the code I edited to try and link these together:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 100 && resultCode == 101){
        String result = data.getStringExtra("CROP");
        Uri uri = data.getData();

        if (result!=null){
            uri = Uri.parse(result);
        }

        binding.imageView.setImageURI(uri);

       // I added this:

        try {

            Bitmap image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);

            int dimension = Math.min(image.getWidth(), image.getHeight());

            image = ThumbnailUtils.extractThumbnail(image, dimension, dimension);

            image = Bitmap.createScaledBitmap(image, imageSize, imageSize, false);

            classifyImage(image);

        } catch (IOException e) {
            e.printStackTrace();

        }

    }
}

However, it always results in the activity crashing, these are the errors:

I/BitmapCropTask: Should crop: true
I/tflite: Initialized TensorFlow Lite runtime.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.phoenixapp, PID: 21124
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=101, data=Intent { (has extras) }} to activity {com.example.phoenixapp/com.example.phoenixapp.Tensor}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5301)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5340)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54)
        at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.phoenixapp.Tensor.classifyImage(Tensor.java:113)
        at com.example.phoenixapp.Tensor.onActivityResult(Tensor.java:184)
        at android.app.Activity.dispatchActivityResult(Activity.java:8382)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5294)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5340)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54)
        at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
I/Process: Sending signal. PID: 21124 SIG: 9

Is there a simple solution to be able to perform image classification, whilst being able to crop the image beforehand?


问:
Incrementally loading into a Synapse table using Spark
I am creating a data warehouse using Azure Data Factory to extract data from a MySQL table and saving it in parquet format in an ADLS Gen 2 filesystem. From there, I use Synapse notebooks to process and load data into destination tables.

The initial load is fairly easy using spark.write.saveAsTable('orders') however, I am running into some issues doing incremental load following the intial load. In particular, I have not been able to find a way to reliably insert/update information into an existing Synapse table.

Since Spark does not allow DML operations on a table, I have resorted to reading the current table into a Spark DataFrame and inserting/updating records in that DataFrame. However, when I try to save that DataFrame using spark.write.saveAsTable('orders', mode='overwrite', format='parquet'), I run into a Cannot overwrite table 'orders' that is also being read from error.

A solution indicated by this suggests creating a temporary table and then inserting using that but that still resorts in the above error.

Another solution in this post suggests to write the data into a temporary table, drop the target table, and then rename the table but upon doing this, Spark gives me a FileNotFound errors regarding metadata.

I know Delta Tables can fix this issue pretty reliably but our company is not yet ready to move over to DataBricks.

All suggestions are greatly appreciated.


问:
Issue with location proxy_pass setting "connect() failed (111: Connection refused) while connecting to upstream"
I have nginx and metabase in docker. When I try to access "https://MYDOMAIN/metabase" I get the error - connect() failed (111: Connection refused) while connecting to upstream, client: 60.243.254.30, server: MYDOMAIN, request: "GET /metabase/ HTTP/2.0", upstream: "http://127.0.0.1:3000/metabase/", host: "MYDOMAIN".

This works - "curl http://localhost:3000/metabase". This also works - "curl http://127.0.0.1:3000/metabase".

nginx is running fine - I am able to access other sites that are running.

What am I doing wrong in the configuration?

```<code>docker-compose.yml
-------------------
webserver:
    image: nginx:1.20.0
    restart: "no"
    volumes:
      - ./public:/var/www/html
      - ./conf.d:/etc/nginx/conf.d
      - ./sites-available:/etc/nginx/sites-available
      - ./sites-enabled:/etc/nginx/sites-enabled
      - ./ssl:/etc/nginx/ssl
    ports:
      - '80:80'
      - '443:443'

metabase:
    image: metabase/metabase:latest
    container_name: metabase
    restart: "no"
    volumes:
      - metabase-data:/LOCATION/metabase
    ports:
      - '3000:3000'
    environment:
      MB_SITE_URL: http://localhost:3000/metabase
      MB_DB_TYPE: postgres
      MB_DB_DBNAME: metabase
      MB_DB_PORT: 5432
      MB_DB_USER: xxxxx
      MB_DB_PASS: yyyyyy

nginx conf.d/default.conf
--------------------------
upstream metabase {
     server 127.0.0.1:3000;
}

server {

...
    location /metabase/ {
             proxy_pass http://metabase;
             proxy_set_header   Host     $http_host;
             proxy_set_header   X-Real-IP     $remote_addr;
             proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
             proxy_set_header   X-Forwarded-Proto $scheme;
             break;
        }
}
</code>```

Body:
I have nginx and metabase in docker. When I try to access "https://MYDOMAIN/metabase" I get the error - connect() failed (111: Connection refused) while connecting to upstream, client: 60.243.254.30, server: MYDOMAIN, request: "GET /metabase/ HTTP/2.0", upstream: "http://127.0.0.1:3000/metabase/", host: "MYDOMAIN".

This works - "curl http://localhost:3000/metabase". This also works - "curl http://127.0.0.1:3000/metabase".

nginx is running fine - I am able to access other sites that are running.

What am I doing wrong in the configuration?

docker-compose.yml
-------------------
webserver:
    image: nginx:1.20.0
    restart: "no"
    volumes:
      - ./public:/var/www/html
      - ./conf.d:/etc/nginx/conf.d
      - ./sites-available:/etc/nginx/sites-available
      - ./sites-enabled:/etc/nginx/sites-enabled
      - ./ssl:/etc/nginx/ssl
    ports:
      - '80:80'
      - '443:443'

metabase:
    image: metabase/metabase:latest
    container_name: metabase
    restart: "no"
    volumes:
      - metabase-data:/LOCATION/metabase
    ports:
      - '3000:3000'
    environment:
      MB_SITE_URL: http://localhost:3000/metabase
      MB_DB_TYPE: postgres
      MB_DB_DBNAME: metabase
      MB_DB_PORT: 5432
      MB_DB_USER: xxxxx
      MB_DB_PASS: yyyyyy

nginx conf.d/default.conf
--------------------------
upstream metabase {
     server 127.0.0.1:3000;
}

server {

...
    location /metabase/ {
             proxy_pass http://metabase;
             proxy_set_header   Host     $http_host;
             proxy_set_header   X-Real-IP     $remote_addr;
             proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
             proxy_set_header   X-Forwarded-Proto $scheme;
             break;
        }
}


问:
550-5.7.26 error while cancelling the invite to gmail account through MS graph(through MIME object)
While sending the schedule meeting email from our java application, we are creating an ics file through MIME object and its works perfect

While cancelling the meeting the mail is bounced back with 550-5.7.26

Error Description from Google

```<code>550, "5.7.26", " Unauthenticated email from domain-name is not accepted due to domain's DMARC policy. Please contact the administrator of domain-name domain. If this was a legitimate mail please visit Control unauthenticated mail from your domain to learn about the DMARC initiative. If the messages are valid and aren't spam, contact the administrator of the receiving mail server to determine why your outgoing messages don't pass authentication checks.
</code>```

Below is the only difference in ics file between schedule and cancel email

For schedule invite

```<code>METHOD:REQUEST
STATUS:CONFIRMED
</code>```

For cancel invite

```<code>METHOD:CANCEL
STATUS:CANCELLED
</code>```

All other attributes(ORGANIZER, ATTENDEE ) are same

```<code>ORGANIZER;CN=<name>@<domain>.net:mailto:<name>@<domain>.net
ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=<name>@gmail.com:mailto:<name>@gmail.com
</code>```

And interesting things are:

We are facing this issue only when we send through MS graph((through MIME object)) not with
normal SMTP config

And the same ics is working fine for the outlook recipient. its not
working only for gmail recipient

Can any one please help with the below queries?

Why its only failing for cancel invite and working for sent invite?

What is the difference in consuming ics between request and cancel methods?

Why its working with normal SMTP config and not with MS
graph?

Why its not working only for gmail recipient?

Body:
While sending the schedule meeting email from our java application, we are creating an ics file through MIME object and its works perfect

While cancelling the meeting the mail is bounced back with 550-5.7.26

Error Description from Google

550, "5.7.26", " Unauthenticated email from domain-name is not accepted due to domain's DMARC policy. Please contact the administrator of domain-name domain. If this was a legitimate mail please visit Control unauthenticated mail from your domain to learn about the DMARC initiative. If the messages are valid and aren't spam, contact the administrator of the receiving mail server to determine why your outgoing messages don't pass authentication checks.

Below is the only difference in ics file between schedule and cancel email

For schedule invite

METHOD:REQUEST
STATUS:CONFIRMED

For cancel invite

METHOD:CANCEL
STATUS:CANCELLED

All other attributes(ORGANIZER, ATTENDEE ) are same

ORGANIZER;CN=<name>@<domain>.net:mailto:<name>@<domain>.net
ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=<name>@gmail.com:mailto:<name>@gmail.com

And interesting things are:

We are facing this issue only when we send through MS graph((through MIME object)) not with
normal SMTP config

And the same ics is working fine for the outlook recipient. its not
working only for gmail recipient

Can any one please help with the below queries?

Why its only failing for cancel invite and working for sent invite?

What is the difference in consuming ics between request and cancel methods?

Why its working with normal SMTP config and not with MS
graph?

Why its not working only for gmail recipient?


问:
CLS optimization, avoid layout shift
I'm trying to optimize a website in order to reach a better score in Google Lighthouse analysis. The score is significantly affected by the CLS(layout shifts). The significant impact comes from the hero section which is contributing to the CLS analysis by 0.642. The problem here is that I'm unable to detect what exactly is causing this layout shift in the hero section. I'm using Next.js along side with Styled Components the here's the code for the hero section below. I would be really grateful if someone helps me detect that layout shift.</p>
```<code>import styled from "styled-components";
import Image from "next/image";

const Section = styled.section`
    position: relative;
    max-width: 100%;
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    overflow: hidden;
    background-color: blue;

    img {
        width: 100vw;
        height: 100vh;
        object-fit: cover;
    }

    @media(max-width: 990px) {
        min-height: 80vh;
        text-align: center;
    }

    @media(max-width: 600px) {
        min-height: 75vh;
    }

    video {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
        pointer-events: none;
    }
`

const Video = styled.video`
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    pointer-events: none;
`

const Container = styled.span`
    padding-inline: 4rem;
    z-index: 1;

    h1 {
        color: #fff;
        font-size: ${({ language }) => language === "English" ? "2.5rem" : "2.7rem"};
        line-height: 3.5rem;
        margin-bottom: 0.3rem;
    }

    div {
        height: 0.15rem;
        background-color: #F26630;
    }

    h3 {
        color: #fff;
        font-size: ${({ language }) => language === "English" ? "1.1rem" : "1.5rem"};
        margin: ${({ language }) => language === "العربية" ? "0.7rem 0rem" : ""};
        font-weight: normal;
    }

    button {
        font-size: ${({ language }) => language === "English" ? "1.4rem" : "1.7rem"};
        font-weight: 500;
        padding: ${({ language }) => language === "English" ? "0.6rem" : "0.4rem 2rem"};
        background-color: transparent;
        color: #fff;
        border: 2px solid #F26630;
        cursor: pointer;
        transition: background-color 500ms ease;

        &:hover {
            background-color: #F26630;
        }
    }

    // 10 inch
    @media(min-width: 1024px) {
        text-align: center;
        h1 {
            font-size: ${({ language }) => language === "English" ? "2rem" : "2.2rem"};
        }

        h3 {
            font-size: ${({ language }) => language === "English" ? "0.9rem" : "1.3rem"};
        }

        button {
            font-size: ${({ language }) => language === "English" ? "0.9rem" : "1.2rem"};
            padding: ${({ language }) => language === "English" ? "0.4rem" : "0.3rem 0.8rem"};
        }
    }

    // 19 inch
    @media(min-width: 1440px) {
        padding-inline: 6rem;

        h1 {
            font-size: 2.6rem;
            line-height: 3.5rem;
        }

        h3 {
            font-size: 1.1rem;
        }

        button {
            font-size: 1rem;
        }
    }

    // 22 inch
    @media(min-width: 1680px) {

        h1 {
            font-size: 3.2rem;
            line-height: 4.8rem;
        }

        h3 {
            font-size: 1.3rem;
        }

        button {
            font-size: 1.3rem;
        }
    }

    @media(max-width: 990px) {
        padding-top: 4rem;

        h1 {
            font-size: 2.1rem;
            line-height: 3rem;
        }

        h3 {
            font-size: 1rem;
        }

        button {
            font-size: 1.1rem;
        }
    }

    @media(max-width: 600px) {
        h1 {
            font-size: 1.2rem;
            line-height: 1.8rem;
        }

        h3 {
            font-size: 0.5rem;
        }

        button {
            font-size: 0.8rem;
            padding: 0.3rem;
        }
    }
`

const Hero = ({ language, onLinkClick }) => {
    return (
        <Section language={language} id="hero-section">
            <Image layout="fill" src="https://res.cloudinary.com/dqmqc0uaa/image/upload/c_scale,h_1057,w_1280/v1672178208/uploads/bg-masthead_1_1_yvvplw.png" alt="Image for mount Sinai" />
            <Container language={language}>
                <h1> {language === "English" ? "Your Favorite Agency for" : "الاختيار الافضل للسياحة داخل مصر"}
                    <br></br>
                    {language === "English" ? "Traveling Around Egypt" : "وقضاء عطلة مميزة بافضل سعر"}
                </h1>

                <div />

                <h3 className="text-white">
                    {
                        language === "English"
                            ? "It is a long established fact that a reader will be distracted by the"
                            : "اذا كنت من محبي السفر والاستكشاف وترغب في الاستمتاع بعطلة "
                    }
                    <br></br>
                    {
                        language === "English"
                            ? "reader will be distracted by the."
                            : "نهاية الاسبوع ، فانت في المكان الصحيح"
                    }

                </h3>
                {/* <button goto='trips-section' onClick={(e) => onLinkClick(e)}> */}
                <button onClick={() => {
                    window.scrollTo({ top: document.getElementById('hero-section').offsetHeight - 10 });
                }}>
                    {language === "English" ? "Find Out More" : "اعرف اكثر"}
                </button>
            </Container>
        </Section>
    )
}

export default Hero
</code>```

Title: CLS optimization, avoid layout shift

Body:
I'm trying to optimize a website in order to reach a better score in Google Lighthouse analysis. The score is significantly affected by the CLS(layout shifts). The significant impact comes from the hero section which is contributing to the CLS analysis by 0.642. The problem here is that I'm unable to detect what exactly is causing this layout shift in the hero section. I'm using Next.js along side with Styled Components the here's the code for the hero section below. I would be really grateful if someone helps me detect that layout shift.

import styled from "styled-components";
import Image from "next/image";

const Section = styled.section`
    position: relative;
    max-width: 100%;
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    overflow: hidden;
    background-color: blue;

    img {
        width: 100vw;
        height: 100vh;
        object-fit: cover;
    }

    @media(max-width: 990px) {
        min-height: 80vh;
        text-align: center;
    }

    @media(max-width: 600px) {
        min-height: 75vh;
    }

    video {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
        pointer-events: none;
    }
`

const Video = styled.video`
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    pointer-events: none;
`

const Container = styled.span`
    padding-inline: 4rem;
    z-index: 1;

    h1 {
        color: #fff;
        font-size: ${({ language }) => language === "English" ? "2.5rem" : "2.7rem"};
        line-height: 3.5rem;
        margin-bottom: 0.3rem;
    }

    div {
        height: 0.15rem;
        background-color: #F26630;
    }

    h3 {
        color: #fff;
        font-size: ${({ language }) => language === "English" ? "1.1rem" : "1.5rem"};
        margin: ${({ language }) => language === "العربية" ? "0.7rem 0rem" : ""};
        font-weight: normal;
    }

    button {
        font-size: ${({ language }) => language === "English" ? "1.4rem" : "1.7rem"};
        font-weight: 500;
        padding: ${({ language }) => language === "English" ? "0.6rem" : "0.4rem 2rem"};
        background-color: transparent;
        color: #fff;
        border: 2px solid #F26630;
        cursor: pointer;
        transition: background-color 500ms ease;

        &:hover {
            background-color: #F26630;
        }
    }

    // 10 inch
    @media(min-width: 1024px) {
        text-align: center;
        h1 {
            font-size: ${({ language }) => language === "English" ? "2rem" : "2.2rem"};
        }

        h3 {
            font-size: ${({ language }) => language === "English" ? "0.9rem" : "1.3rem"};
        }

        button {
            font-size: ${({ language }) => language === "English" ? "0.9rem" : "1.2rem"};
            padding: ${({ language }) => language === "English" ? "0.4rem" : "0.3rem 0.8rem"};
        }
    }

    // 19 inch
    @media(min-width: 1440px) {
        padding-inline: 6rem;

        h1 {
            font-size: 2.6rem;
            line-height: 3.5rem;
        }

        h3 {
            font-size: 1.1rem;
        }

        button {
            font-size: 1rem;
        }
    }

    // 22 inch
    @media(min-width: 1680px) {

        h1 {
            font-size: 3.2rem;
            line-height: 4.8rem;
        }

        h3 {
            font-size: 1.3rem;
        }

        button {
            font-size: 1.3rem;
        }
    }

    @media(max-width: 990px) {
        padding-top: 4rem;

        h1 {
            font-size: 2.1rem;
            line-height: 3rem;
        }

        h3 {
            font-size: 1rem;
        }

        button {
            font-size: 1.1rem;
        }
    }

    @media(max-width: 600px) {
        h1 {
            font-size: 1.2rem;
            line-height: 1.8rem;
        }

        h3 {
            font-size: 0.5rem;
        }

        button {
            font-size: 0.8rem;
            padding: 0.3rem;
        }
    }
`

const Hero = ({ language, onLinkClick }) => {
    return (

            <Image layout="fill" src="https://res.cloudinary.com/dqmqc0uaa/image/upload/c_scale,h_1057,w_1280/v1672178208/uploads/bg-masthead_1_1_yvvplw.png" alt="Image for mount Sinai" />
            <Container language={language}>

 {language === "English" ? "Your Favorite Agency for" : "الاختيار الافضل للسياحة داخل مصر"}

                    {language === "English" ? "Traveling Around Egypt" : "وقضاء عطلة مميزة بافضل سعر"}

                    {
                        language === "English"
                            ? "It is a long established fact that a reader will be distracted by the"
                            : "اذا كنت من محبي السفر والاستكشاف وترغب في الاستمتاع بعطلة "
                    }

                    {
                        language === "English"
                            ? "reader will be distracted by the."
                            : "نهاية الاسبوع ، فانت في المكان الصحيح"
                    }

                {/* <button goto='trips-section' onClick={(e) => onLinkClick(e)}> */}
                <button onClick={() => {
                    window.scrollTo({ top: document.getElementById('hero-section').offsetHeight - 10 });
                }}>
                    {language === "English" ? "Find Out More" : "اعرف اكثر"}
                </button>
            </Container>

    )
}

export default Hero


问:
Cannot find module './routes/Auth' Require stack: - C:\Users\me\Desktop\E-commerce_Web\backendnode\index.js
I am doing a mern project but at begin I got an error .

const express=require("express");
const mongoose= require("mongoose");
const app=express();
const dotenv=require("dotenv")
dotenv.config()

//connect router
const route=require("./routes/User");
const authRoute=require("./routes/Auth");

mongoose
    .connect(
        process.env.local
        )
        .then(()=>console.log("MongoDB connected")).catch((err)=>{
            console.log(err)
        });

//accept json
app.use(express.json())

app.use("/authData",authRoute)

app.listen(process.env.PORT || 5000,()=>{
    console.log("Backend server is running ")
});```

the error is

internal/modules/cjs/loader.js:888
throw err;
^
Error: Cannot find module './routes/Auth'
Require stack:

C:\Users\me\Desktop\E-commerce_Web\backendnode\index.js

Body:
I am doing a mern project but at begin I got an error .

const express=require("express");
const mongoose= require("mongoose");
const app=express();
const dotenv=require("dotenv")
dotenv.config()

//connect router
const route=require("./routes/User");
const authRoute=require("./routes/Auth");

mongoose
    .connect(
        process.env.local
        )
        .then(()=>console.log("MongoDB connected")).catch((err)=>{
            console.log(err)
        });

//accept json
app.use(express.json())

app.use("/authData",authRoute)

app.listen(process.env.PORT || 5000,()=>{
    console.log("Backend server is running ")
});

the error is

internal/modules/cjs/loader.js:888
throw err;
^
Error: Cannot find module './routes/Auth'
Require stack:

C:\Users\me\Desktop\E-commerce_Web\backendnode\index.js


问:
Next.js landing and React Dashboard on Heroku good for SEO?
I have finished building my app. I built it with create-react-app. However I now realize the for SEO purposes I should be using Server Side Rendering (SSR) in order to increase my ranking on google.

Is it bad practice to host my app ( MERN Stack ) at my.myapp.com which is a heroku build of my app?

And build a landing out of Next.js and host it at www.myapp.com which would be another Heroku build.

I can just direct traffic to my.myapp.com when someone clicks the register, or login, or free trial button.

Is this how it should be or should my react-app be built with next.js for SEO aswell.