问:
SMTP Error: Could not connect to SMTP host. Failed to connect to server
I am new to SMTP and i am able to  send mails from localhost .When i host using big rock i am unable to mail in my mail id.I am getting error.This Is my Code

```<code><?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

  require 'vendor/phpmailer/phpmailer/src/Exception.php';
  require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
  require 'vendor/phpmailer/phpmailer/src/SMTP.php';
  require 'vendor/autoload.php';
  $mail = new PHPMailer(true);
  $output = '';
  if (isset($_POST['submit'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $mobile = $_POST['mobile'];
    $message = $_POST['message'];

    try {
      $mail->isSMTP();
      $mail->Host = 'smtp.gmail.com';
      $mail->SMTPAuth = true;
      $mail->Username = 'mail id';
      $mail->Password = 'password';
      $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
      $mail->Port = 587;
      $mail->setFrom('mail id');
      $mail->addAddress('mail id');
      $mail->isHTML(true);
      $mail->Subject = 'Contact Form';
      $mail->Body = "<h3>Name : $name <br>Email : $email <br> Mobile : $mobile <br>Message : $message</h3>";

      $mail->send();
      $output = '<div class="alert alert-success">
                  <h5>Thankyou! for contacting us, We will get back to you soon!</h5>
                </div>';
    } catch (Exception $e) {
      $output = '<div class="alert alert-danger">
                  <h5>' . $e->getMessage() . '</h5>
                </div>';
    }
  }

?>
</code>```

i have hosted in big rock and its working in localhost and showing error like

SMTP Error: Could not connect to SMTP host. Failed to connect to
server

Body:
I am new to SMTP and i am able to  send mails from localhost .When i host using big rock i am unable to mail in my mail id.I am getting error.This Is my Code

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

  require 'vendor/phpmailer/phpmailer/src/Exception.php';
  require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
  require 'vendor/phpmailer/phpmailer/src/SMTP.php';
  require 'vendor/autoload.php';
  $mail = new PHPMailer(true);
  $output = '';
  if (isset($_POST['submit'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $mobile = $_POST['mobile'];
    $message = $_POST['message'];

    try {
      $mail->isSMTP();
      $mail->Host = 'smtp.gmail.com';
      $mail->SMTPAuth = true;
      $mail->Username = 'mail id';
      $mail->Password = 'password';
      $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
      $mail->Port = 587;
      $mail->setFrom('mail id');
      $mail->addAddress('mail id');
      $mail->isHTML(true);
      $mail->Subject = 'Contact Form';
      $mail->Body = "
Name : $name
Email : $email
 Mobile : $mobile
Message : $message
";

      $mail->send();
      $output = '

Thankyou! for contacting us, We will get back to you soon!

';
    } catch (Exception $e) {
      $output = '

' . $e->getMessage() . '

';
    }
  }

?>

i have hosted in big rock and its working in localhost and showing error like

SMTP Error: Could not connect to SMTP host. Failed to connect to
server


来源: stackexchange

问:
Storm MQTT throws dispatch queue was not executing assertion error when I try to subscribe
I have successfully connected to MQTT on Storm (via the org.fusesource.mqtt.client.* library) but when I try to subscribe to the topics I keep getting the following error:

org.opentest4j.AssertionFailedError: Unexpected exception thrown:
java.lang.AssertionError: Dispatch queue 'mqtt client' was not
executing, (currently executing: '')

at
org.junit.jupiter.api.AssertDoesNotThrow.createAssertionFailedError(AssertDoesNotThrow.java:83)
at
org.junit.jupiter.api.AssertDoesNotThrow.assertDoesNotThrow(AssertDoesNotThrow.java:54)
at
org.junit.jupiter.api.AssertDoesNotThrow.assertDoesNotThrow(AssertDoesNotThrow.java:37)
at
org.junit.jupiter.api.Assertions.assertDoesNotThrow(Assertions.java:3135)
at
com.wiz.bi.core.storm.mqtt.conn.MqttConnTest.testSubscribe(MqttConnTest.java:96)
at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)   at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)   at
org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
at
org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at
org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at
org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at
org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at
org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at
org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103)
at
org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
at
org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at
org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at
org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at
org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at
org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
at
org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at
org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)   at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at
org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)   at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at
org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at
org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at
org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
at
org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at
org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at
org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at
org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at
com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
at
com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at
com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at
com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at
com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.lang.AssertionError: Dispatch queue 'mqtt client' was
not executing, (currently executing: '')  at
org.fusesource.hawtdispatch.internal.SerialDispatchQueue.assertExecuting(SerialDispatchQueue.java:145)
at
org.fusesource.mqtt.client.CallbackConnection.subscribe(CallbackConnection.java:599)
at
com.wiz.bi.core.storm.mqtt.conn.MqttConn.subscribe(MqttConn.java:126)
at
com.wiz.bi.core.storm.mqtt.conn.MqttConnTest.lambda$testSubscribe$2(MqttConnTest.java:98)
at
org.junit.jupiter.api.AssertDoesNotThrow.assertDoesNotThrow(AssertDoesNotThrow.java:50)
... 73 more

I have checked that the transport have been connected, I am connected and the login have been accepted.

ContentLicense: CC BY-SA 4.0


问:
what is the significance and use of snapshot file in kafa data directory?
I am looking at kafa data dir and I see there are several *.snapshot files (00000offset.snapshot). While I understand what the other files (like *.log, *.index, *.timestamp) in the data dir are used for - it is not clear what is the use of snapshot file. And what data does the snapshot file have (format and fields).

I found this article - Understanding Kafka's Internal Storage and Log Retention.
It says -

snapshot file - contains a snapshot of the producer state regarding
sequence IDs used to avoid duplicate records. It is used when, after a
new leader is elected, the preferred one comes back and needs such a
state to become a leader again. This is only available for the active
segment (log file).

The above is definitely not clear. If there are n-producers pushing to the topic, will the snapshot file have a sqeuence ID for each producer. And how does it use this ID to avoid duplicates.


问:
Open application from scanned qr code in default camera
I am using breoadcast receiver to open my app when scanning a qr code from the device default camera. I tested this with Android 11 and Android 12 and it works fine. When I tried this out with Android 13 the qr string is shown when I click on it, it's opened on the browser.
Here is my implementation of the Qr code scan method:

In AndroidManifest.xml

```<code><activity
    android:name="com.cibingenierie.nomadmobile.screens.MainActivity"
    android:exported="true"
    android:theme="@style/AppTheme.NoActionBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="nm" />
    </intent-filter>
</activity>
</code>```

On MainActivity.kt

here is my onCrete function

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val intent = intent
    val data = intent.data.toString()

    val dataArgs = data.replace("nm://", "")

    onBroadcastReceived()
    window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

    setContent {
        AppTheme {
            NomadApplication(userViewModel, registerViewModel, ticketViewModel,intent)
        }
    }
}
</code>```

and onBroadcastReceived function

```<code>private fun onBroadcastReceived() {
    val receiver = (object : ExternalReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val launchIntent = Intent("android.intent.action.MAIN")
            launchIntent.putExtra("camera", "")
            context.startActivity(launchIntent)
        }
    })
}
</code>```

Can you please help me fix this?

I dont get an error it's actually the qr code string always detected as a web url

Body:
I am using breoadcast receiver to open my app when scanning a qr code from the device default camera. I tested this with Android 11 and Android 12 and it works fine. When I tried this out with Android 13 the qr string is shown when I click on it, it's opened on the browser.
Here is my implementation of the Qr code scan method:

In AndroidManifest.xml

<activity
    android:name="com.cibingenierie.nomadmobile.screens.MainActivity"
    android:exported="true"
    android:theme="@style/AppTheme.NoActionBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="nm" />
    </intent-filter>
</activity>

On MainActivity.kt

here is my onCrete function

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val intent = intent
    val data = intent.data.toString()

    val dataArgs = data.replace("nm://", "")

    onBroadcastReceived()
    window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

    setContent {
        AppTheme {
            NomadApplication(userViewModel, registerViewModel, ticketViewModel,intent)
        }
    }
}

and onBroadcastReceived function

private fun onBroadcastReceived() {
    val receiver = (object : ExternalReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val launchIntent = Intent("android.intent.action.MAIN")
            launchIntent.putExtra("camera", "")
            context.startActivity(launchIntent)
        }
    })
}

Can you please help me fix this?

I dont get an error it's actually the qr code string always detected as a web url


问:
FacebookActivity could not be started when I have an activity-alias
I have set the icon change dynamically in my app. Icon switching is set with an activity-alias (as described in the Android documentation). After changing the icon, and then changing the activity, login with Facebook no longer works with error "Log in attempt failed: FacebookActivity could not be started. Please make sure you added FacebookActivity to the AndroidManifest". My AndroidManifest.xml is configured as Facebook's documentation. Do you have any ideas? Thank you.

PS. The code I'm using right now is just a test project but partially replicating what's configured in my main project :)

Change Icon and Facebook login functions

My AndroidManifest.xml

flutter doctor -v

```<code>[✓] Flutter (Channel stable, 3.3.8, on macOS 13.0.1 22A400 darwin-x64, locale it-IT)
    • Flutter version 3.3.8 on channel stable at /Users/wiwo/fvm/versions/3.3.8
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 52b3dc25f6 (4 settimane fa), 2022-11-09 12:09:26 +0800
    • Engine revision 857bd6b74c
    • Dart version 2.18.4
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/Wiwo/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14B47b
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] IntelliJ IDEA Ultimate Edition (version 2022.2.3)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin version 71.0.5
    • Dart plugin version 222.4345.14

[✓] VS Code (version 1.73.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.54.0

[✓] Connected device (4 available)
    • ONEPLUS A6003 (mobile)    • 192.168.178.110:5555      • android-arm64  • Android 11 (API 30)
    • iPhone di Silvio (mobile) • 00008101-00126D1821E3003A • ios            • iOS 16.2 20C5049e
    • macOS (desktop)           • macos                     • darwin-x64     • macOS 13.0.1 22A400 darwin-x64
    • Chrome (web)              • chrome                    • web-javascript • Google Chrome 108.0.5359.94
    ! Error: iPhone di Silvio is busy: Fetching debug symbols for iPhone di Silvio. Xcode will continue when iPhone di Silvio is finished. (code -10)
    ! Error: Apple Watch di Silvio needs to connect to determine its availability. Check the connection between the device and its companion iPhone, and the connection between the iPhone and Xcode. Both devices may also need to be restarted and unlocked. (code 1)

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
</code>```

I expect the activity to be found even when I am an activity-alias

Body:
I have set the icon change dynamically in my app. Icon switching is set with an activity-alias (as described in the Android documentation). After changing the icon, and then changing the activity, login with Facebook no longer works with error "Log in attempt failed: FacebookActivity could not be started. Please make sure you added FacebookActivity to the AndroidManifest". My AndroidManifest.xml is configured as Facebook's documentation. Do you have any ideas? Thank you.

PS. The code I'm using right now is just a test project but partially replicating what's configured in my main project :)

Change Icon and Facebook login functions

My AndroidManifest.xml

flutter doctor -v

[✓] Flutter (Channel stable, 3.3.8, on macOS 13.0.1 22A400 darwin-x64, locale it-IT)
    • Flutter version 3.3.8 on channel stable at /Users/wiwo/fvm/versions/3.3.8
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 52b3dc25f6 (4 settimane fa), 2022-11-09 12:09:26 +0800
    • Engine revision 857bd6b74c
    • Dart version 2.18.4
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/Wiwo/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14B47b
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] IntelliJ IDEA Ultimate Edition (version 2022.2.3)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin version 71.0.5
    • Dart plugin version 222.4345.14

[✓] VS Code (version 1.73.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.54.0

[✓] Connected device (4 available)
    • ONEPLUS A6003 (mobile)    • 192.168.178.110:5555      • android-arm64  • Android 11 (API 30)
    • iPhone di Silvio (mobile) • 00008101-00126D1821E3003A • ios            • iOS 16.2 20C5049e
    • macOS (desktop)           • macos                     • darwin-x64     • macOS 13.0.1 22A400 darwin-x64
    • Chrome (web)              • chrome                    • web-javascript • Google Chrome 108.0.5359.94
    ! Error: iPhone di Silvio is busy: Fetching debug symbols for iPhone di Silvio. Xcode will continue when iPhone di Silvio is finished. (code -10)
    ! Error: Apple Watch di Silvio needs to connect to determine its availability. Check the connection between the device and its companion iPhone, and the connection between the iPhone and Xcode. Both devices may also need to be restarted and unlocked. (code 1)

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

I expect the activity to be found even when I am an activity-alias


问:
Comparing C# records with other types using Equals(object) method
In C# the object.Equals(object?) virtual method of the record types is generated by the compiler automatically. The generated method looks like:

    [IsReadOnly]
    [CompilerGenerated]
    public override bool Equals(object obj)
    {
        if (obj is MyRecord)
        {
            return Equals((MyRecord)obj);
        }
        return false;
    }
```
<p>But what if the record implements other <code>IEquatalbe<T></code> interfaces:</p>
<pre class="lang-cs prettyprint-override"><code>public readonly record struct MyRecord : IEquatable<int>
{
    // ....

    public bool Equals(int other)
    {
         return Whatever();
    }
}
</code>```

In this case, the the int values do not considered by the Equals(object?) method and libraries using the Equals(object?) don't not work properly (like FluentAssertions):

   myRecord.Should().Be(4); // will never pass
```
<p>Is there any solution to customize the <code>Equals(object?)</code> method for the <code>record</code> types?</p>
<p>I tried to override the <code>Equals(object)</code> method in the record, but the compiler generated an error:</p>
```  Error CS0111: Type 'MyRecord' already defines a member called 'Equals' with the same parameter types
```

Body:
In C# the object.Equals(object?) virtual method of the record types is generated by the compiler automatically. The generated method looks like:

    [IsReadOnly]
    [CompilerGenerated]
    public override bool Equals(object obj)
    {
        if (obj is MyRecord)
        {
            return Equals((MyRecord)obj);
        }
        return false;
    }

But what if the record implements other IEquatalbe<T> interfaces:

public readonly record struct MyRecord : IEquatable<int>
{
    // ....

    public bool Equals(int other)
    {
         return Whatever();
    }
}

In this case, the the int values do not considered by the Equals(object?) method and libraries using the Equals(object?) don't not work properly (like FluentAssertions):

   myRecord.Should().Be(4); // will never pass

Is there any solution to customize the Equals(object?) method for the record types?

I tried to override the Equals(object) method in the record, but the compiler generated an error:

  Error CS0111: Type 'MyRecord' already defines a member called 'Equals' with the same parameter types


问:
What is the right syntax?
Ive got the message

PHP Parse error:  syntax error, unexpected character 0x1D, expecting
")" in securimagejumppage.php on line 658

This is the Code

```<code>@imagettftext($this->im, $this->font_size, $angle, $x, $y, $font_color, $this->ttf_file, $this->code{$i});
</code>```

What is the problem?

Before it tells me:

PHP Fatal error:  Array and string offset access syntax with curly
braces is no longer supported

and I've changed the Brakets from  $this->code{$i});  to  $this->code[$i]);

Title: What is the right syntax?

Body:
Ive got the message

PHP Parse error:  syntax error, unexpected character 0x1D, expecting
")" in securimagejumppage.php on line 658

This is the Code

@imagettftext($this->im, $this->font_size, $angle, $x, $y, $font_color, $this->ttf_file, $this->code{$i});

What is the problem?

Before it tells me:

PHP Fatal error:  Array and string offset access syntax with curly
braces is no longer supported

and I've changed the Brakets from  $this->code{$i});  to  $this->code[$i]);


问:
No visible @interface for 'NSObject' declares the selector 'objectAtIndex:'
I'm trying to iterate an array, however the code fails with the following error message:

No visible @interface for NSObject declares the selector objectAtIndex:

Here is how my code looks like:

_elements = [NSMutableArray array];
[_elements addObject:_arrins1 ];
[_elements addObject:_arrins2 ];
[_elements addObject:_arrins3 ];

_arrins1 = [NSMutableArray array];
[_arrins1 addObject:ins1.title = @"test1"];
[_arrins1 addObject:ins1.size = @90];
[_arrins1 addObject:ins1.text = @"example"];
[_arrins1 addObject:ins1.ids = @0];

_arrins2 = [NSMutableArray array];
[_arrins2 addObject:ins2.title = @"test2"];
[_arrins2 addObject:ins2.size = @40];
[_arrins2 addObject:ins2.text = @"example"];
[_arrins2 addObject:ins2.ids = @1];

_arrins3 = [NSMutableArray array];
[_arrins3 addObject:ins3.title = @"test3"];
[_arrins3 addObject:ins3.size = @20];
[_arrins3 addObject:ins3.text = @"example"];
[_arrins3 addObject:ins3.ids = @2];
```
<pre class="lang-objc prettyprint-override"><code>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    for (NSObject *j in _elements) {
        // Error: No visible @interface for 'NSObject' declares the selector 'objectAtIndex:'
        height = [j objectAtIndex:1];
    }

    return height;
}
</code>```

I also tried to change the type of elements in the loop, but it didn't help:

for (id j in _elements) {
    // Error: Assigning to 'CGFloat' (aka 'double') from incompatible type 'id'
    height = [j objectAtIndex:1];
}

```

Body:
I'm trying to iterate an array, however the code fails with the following error message:

No visible @interface for NSObject declares the selector objectAtIndex:

Here is how my code looks like:

_elements = [NSMutableArray array];
[_elements addObject:_arrins1 ];
[_elements addObject:_arrins2 ];
[_elements addObject:_arrins3 ];

_arrins1 = [NSMutableArray array];
[_arrins1 addObject:ins1.title = @"test1"];
[_arrins1 addObject:ins1.size = @90];
[_arrins1 addObject:ins1.text = @"example"];
[_arrins1 addObject:ins1.ids = @0];

_arrins2 = [NSMutableArray array];
[_arrins2 addObject:ins2.title = @"test2"];
[_arrins2 addObject:ins2.size = @40];
[_arrins2 addObject:ins2.text = @"example"];
[_arrins2 addObject:ins2.ids = @1];

_arrins3 = [NSMutableArray array];
[_arrins3 addObject:ins3.title = @"test3"];
[_arrins3 addObject:ins3.size = @20];
[_arrins3 addObject:ins3.text = @"example"];
[_arrins3 addObject:ins3.ids = @2];

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    for (NSObject *j in _elements) {
        // Error: No visible @interface for 'NSObject' declares the selector 'objectAtIndex:'
        height = [j objectAtIndex:1];
    }

    return height;
}

I also tried to change the type of elements in the loop, but it didn't help:

for (id j in _elements) {
    // Error: Assigning to 'CGFloat' (aka 'double') from incompatible type 'id'
    height = [j objectAtIndex:1];
}


问:
How to fetcha all data on the basis of search data
Family will book the tutor.

Step-1: Family will search Tutor by Subject and which dates family want to tutor their kids by Teacher.

Step--2: Need to show all tutor  of that subject for those days which are not booked yet.

```<code>class TutorProfile(models.Model):

user = models.ForeignKey(
    settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

which_grade = models.ForeignKey(
    Grade, on_delete=models.CASCADE, blank=True, null=True)
tutoring_subject = models.ForeignKey(
    TutoringSubject, on_delete=models.CASCADE, blank=True, null=True)

sat = models.BooleanField(default=False)
sat_time = models.CharField(
    _("Saturday Time:"), max_length=255, null=True, blank=True)
sun = models.BooleanField(default=False)
sun_time = models.CharField(
    _("Sunday Time:"), max_length=255, null=True, blank=True)
mon = models.BooleanField(default=False)
mon_time = models.CharField(
    _("Monday Time:"), max_length=255, null=True, blank=True)
tue = models.BooleanField(default=False)
tue_time = models.CharField(
    _("Tuesday Time:"), max_length=255, null=True, blank=True)
wed = models.BooleanField(default=False)
wed_time = models.CharField(
    _("Wednesday Time:"), max_length=255, null=True, blank=True)

thu = models.BooleanField(default=False)
thu_time = models.CharField(
    _("Thursday Time:"), max_length=255, null=True, blank=True)
fri = models.BooleanField(default=False)
fri_time = models.CharField(
    _("Friday Time:"), max_length=255, null=True, blank=True)
</code>```

And the Booking Models is:

```<code>class Booking(models.Model):

user = models.ForeignKey(
    settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
book_day = models.CharField(
    _("Book Day"), max_length=255, null=True, blank=True)

book_time = models.CharField(
    _("Book Time"), max_length=255, null=True, blank=True)

status = models.CharField(
    _("Status"), max_length=255, null=True, blank=True)
</code>```

Code in viewset.py:

```<code>def get_queryset(self):
    subject_param = self.request.GET.get('subject')

    bookday = self.request.GET.get('book_day')
    grade = self.request.GET.get('grade')

    import ast

    li = list(bookday.split(","))
    print("Book Info:", li)
    from datetime import datetime
    for i in range(len(li)):

        print(li[i])
        day_name = datetime.strptime(li[i], "%d-%m-%Y").strftime("%A")

        print("Day Name:", day_name)

        search_booking = Booking.objects.filter(book_day=li[i])

        print(search_booking)

        if not search_booking:

            if day_name == "Wednesday":
                print("This is Wednesday")

                try:

                    result = TutorProfile.objects.filter(wed=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Tuesday":
                try:

                    result = TutorProfile.objects.filter(tue=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Monday":
                try:

                    result = TutorProfile.objects.filter(mon=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Sunday":
                try:

                    result = TutorProfile.objects.filter(sun=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Saturday":
                try:

                    result = TutorProfile.objects.filter(sat=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Thursday":
                try:

                    result = TutorProfile.objects.filter(thu=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Friday":
                try:

                    result = TutorProfile.objects.filter(thu=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            else:
                result = TutorProfile.objects.all()

            return result
</code>```

What should be the right way to search tutor on the basis of subject and grade for multiple days booking?

Body:
Family will book the tutor.

Step-1: Family will search Tutor by Subject and which dates family want to tutor their kids by Teacher.

Step--2: Need to show all tutor  of that subject for those days which are not booked yet.

class TutorProfile(models.Model):

user = models.ForeignKey(
    settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

which_grade = models.ForeignKey(
    Grade, on_delete=models.CASCADE, blank=True, null=True)
tutoring_subject = models.ForeignKey(
    TutoringSubject, on_delete=models.CASCADE, blank=True, null=True)

sat = models.BooleanField(default=False)
sat_time = models.CharField(
    _("Saturday Time:"), max_length=255, null=True, blank=True)
sun = models.BooleanField(default=False)
sun_time = models.CharField(
    _("Sunday Time:"), max_length=255, null=True, blank=True)
mon = models.BooleanField(default=False)
mon_time = models.CharField(
    _("Monday Time:"), max_length=255, null=True, blank=True)
tue = models.BooleanField(default=False)
tue_time = models.CharField(
    _("Tuesday Time:"), max_length=255, null=True, blank=True)
wed = models.BooleanField(default=False)
wed_time = models.CharField(
    _("Wednesday Time:"), max_length=255, null=True, blank=True)

thu = models.BooleanField(default=False)
thu_time = models.CharField(
    _("Thursday Time:"), max_length=255, null=True, blank=True)
fri = models.BooleanField(default=False)
fri_time = models.CharField(
    _("Friday Time:"), max_length=255, null=True, blank=True)

And the Booking Models is:

class Booking(models.Model):

user = models.ForeignKey(
    settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
book_day = models.CharField(
    _("Book Day"), max_length=255, null=True, blank=True)

book_time = models.CharField(
    _("Book Time"), max_length=255, null=True, blank=True)

status = models.CharField(
    _("Status"), max_length=255, null=True, blank=True)

Code in viewset.py:

def get_queryset(self):
    subject_param = self.request.GET.get('subject')

    bookday = self.request.GET.get('book_day')
    grade = self.request.GET.get('grade')

    import ast

    li = list(bookday.split(","))
    print("Book Info:", li)
    from datetime import datetime
    for i in range(len(li)):

        print(li[i])
        day_name = datetime.strptime(li[i], "%d-%m-%Y").strftime("%A")

        print("Day Name:", day_name)

        search_booking = Booking.objects.filter(book_day=li[i])

        print(search_booking)

        if not search_booking:

            if day_name == "Wednesday":
                print("This is Wednesday")

                try:

                    result = TutorProfile.objects.filter(wed=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Tuesday":
                try:

                    result = TutorProfile.objects.filter(tue=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Monday":
                try:

                    result = TutorProfile.objects.filter(mon=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Sunday":
                try:

                    result = TutorProfile.objects.filter(sun=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Saturday":
                try:

                    result = TutorProfile.objects.filter(sat=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Thursday":
                try:

                    result = TutorProfile.objects.filter(thu=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            elif day_name == "Friday":
                try:

                    result = TutorProfile.objects.filter(thu=1).all()
                    print(result)
                except Exception as e:
                    print('type is:', e.__class__.__name__)

            else:
                result = TutorProfile.objects.all()

            return result

What should be the right way to search tutor on the basis of subject and grade for multiple days booking?


问:
How does facebook track app installs for ads
I want to display ads on instagram for an app i created. The setup with facebook ads is incredibly complex and there is many things one needs to fill out (or not).

I wondered, do i need to implement facebook libraries within my app or how do their metrics such as installs otherwise work (i do not want to add their libraries only to be able to display ads)?


问:
force subprocss to return a value before importing a module
Objective : To Create UnitTestCases for main.py
How can we run subprocess.run as unittest case

File : main.py

```<code>import os
_ENV = os.environ['server']

BASE_PATH = '/home/test'
SERVER_URL = {
    'DEV':{'ENV_URL':'https://dev.net'},
    'UAT':{'ENV_URL':'https://uat.net'},
    'PROD':{'ENV_URL':'https://prod.net'}
}[_ENV]

if _CYBERARK=='DYNAMIC' and _ENV.upper() in ('DEV','UAT','PROD') :
      TOKEN = json.load(open(BASE_PATH + "secrets/cyberark_env.json"))
      APPID = CONFIGURE_TOKEN.get('desc').get('appID')

      ## --> error on this because its running .sh files
      VALUE=subprocess.run(["sh",BASE_PATH + "bin/cyberark.sh",APPID],capture_output=True,text=True).stdout.strip()
</code>```

In my test_main.py
I am trying to import main.py to my test.py without any issues, but i find it challenging on how we to manually make VALUE variable return as 'ABCD'
Similar to below scripts

Testing : test_main.py

```<code>import unittest, sys
from unittest import mock

os.environ['server']='DEV'

# Similar to os.environ , i want to create temporarily VALUE before import main is called.
sys.path.insert(1, 'C:/home/src')
import main.py as conf

class test_tbrp_case(unittest.TestCase):
    def  test_port(self):
        #function yet to be created
        pass

if __name__=='__main__':
    unittest.main()
</code>```

Is this achieveable or i need to relogic my whole function

Body:
Objective : To Create UnitTestCases for main.py
How can we run subprocess.run as unittest case

File : main.py

import os
_ENV = os.environ['server']

BASE_PATH = '/home/test'
SERVER_URL = {
    'DEV':{'ENV_URL':'https://dev.net'},
    'UAT':{'ENV_URL':'https://uat.net'},
    'PROD':{'ENV_URL':'https://prod.net'}
}[_ENV]

if _CYBERARK=='DYNAMIC' and _ENV.upper() in ('DEV','UAT','PROD') :
      TOKEN = json.load(open(BASE_PATH + "secrets/cyberark_env.json"))
      APPID = CONFIGURE_TOKEN.get('desc').get('appID')

      ## --> error on this because its running .sh files
      VALUE=subprocess.run(["sh",BASE_PATH + "bin/cyberark.sh",APPID],capture_output=True,text=True).stdout.strip()

In my test_main.py
I am trying to import main.py to my test.py without any issues, but i find it challenging on how we to manually make VALUE variable return as 'ABCD'
Similar to below scripts

Testing : test_main.py

import unittest, sys
from unittest import mock

os.environ['server']='DEV'

# Similar to os.environ , i want to create temporarily VALUE before import main is called.
sys.path.insert(1, 'C:/home/src')
import main.py as conf

class test_tbrp_case(unittest.TestCase):
    def  test_port(self):
        #function yet to be created
        pass

if __name__=='__main__':
    unittest.main()

Is this achieveable or i need to relogic my whole function


问:
How to render text from SVG pictures using SDL2?
I'm trying to render a picture from an SVG file, using the graphics rendering library SDL2.

My code to load SVG files is as follows:

u8* textureData = /*Irrelevant function for me to load the file as a byte array*/
SDL_RWops *rw = SDL_RWFromMem(textureData, size);
SDL_Texture* tex = IMG_LoadTexture_RW(renderer, rw, true);
```
<p>I'm using <code>IMG_LoadTexture_RW</code> because I need to be able to render multiple image formats, hence why I need to load them this way so SDL2 checks for the file format by itself and returns me a <code>SDL_Texture*</code> to render.</p>
<p>But when rendering the <code>SDL_Texture*</code> returned by the <code>IMG_LoadTexture_RW</code> function, there's no text to be found on the picture rendered on screen.</p>
<p>The text elements in my SVG files are as follows:</p>
<pre class="lang-xml prettyprint-override"><code><text xmlns="http://www.w3.org/2000/svg" transform="translate(263.9375,206.64214) scale(0.8792,0.8792)" font-size="40" xml:space="preserve" fill="#8c3600" fill-rule="nonzero" stroke="#8c3600" stroke-width="3" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="Sans Serif" font-weight="normal" text-anchor="start" style="mix-blend-mode: normal">
    <tspan x="0" dy="0">Text</tspan>
</text>
</code>```

I did link SDL_TTF and SDL_Image to my project, and emptied google search pages without any result.

(Oh and, no, I can't just "not use SVG")

Body:
I'm trying to render a picture from an SVG file, using the graphics rendering library SDL2.

My code to load SVG files is as follows:

u8* textureData = /*Irrelevant function for me to load the file as a byte array*/
SDL_RWops *rw = SDL_RWFromMem(textureData, size);
SDL_Texture* tex = IMG_LoadTexture_RW(renderer, rw, true);

I'm using IMG_LoadTexture_RW because I need to be able to render multiple image formats, hence why I need to load them this way so SDL2 checks for the file format by itself and returns me a SDL_Texture* to render.

But when rendering the SDL_Texture* returned by the IMG_LoadTexture_RW function, there's no text to be found on the picture rendered on screen.

The text elements in my SVG files are as follows:

<text xmlns="http://www.w3.org/2000/svg" transform="translate(263.9375,206.64214) scale(0.8792,0.8792)" font-size="40" xml:space="preserve" fill="#8c3600" fill-rule="nonzero" stroke="#8c3600" stroke-width="3" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="Sans Serif" font-weight="normal" text-anchor="start" style="mix-blend-mode: normal">
    <tspan x="0" dy="0">Text</tspan>
</text>

I did link SDL_TTF and SDL_Image to my project, and emptied google search pages without any result.

(Oh and, no, I can't just "not use SVG")


问:
Spring Boot Adding Bearer Token to swagger shows the Authorization (lock symbol), but doesn't give 401 Unauthorized when triggered it without a token
I have my swagger config file as below,

```<code>@Configuration
@SecurityScheme(
        name = "BearerAuth",
        type = SecuritySchemeType.HTTP,
        bearerFormat = "JWT",
        scheme = "bearer"
)

public class SwaggerConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI().info(new Info().title("---- API")
                .version("1.0.0")
                .description("This is --- API"));
    }
}
</code>```

And in the controller,

```<code>@Validated
@CrossOrigin("*")
@RestController
@RequestMapping("/api/v1")
@SecurityRequirement(name = "BearerAuth")
public class StudentController {

 @PostMapping("students")
    public ResponseEntity<StudentModel> saveStudent(                                                                    @Valid @RequestBody(required = true) Student student, BindingResult bindingResult) {
...
</code>```

But when I access http://localhost:8080/swagger-ui/ it does shows the  lock symbol Infront of the api but when execute the relevant url, I'm not getting 401 unauthorized status when I don't pass the bearer token.

My build.gradle file,

```<code>implementation('org.springdoc:springdoc-openapi-ui:1.5.3')
</code>```

Body:
I have my swagger config file as below,

@Configuration
@SecurityScheme(
        name = "BearerAuth",
        type = SecuritySchemeType.HTTP,
        bearerFormat = "JWT",
        scheme = "bearer"
)

public class SwaggerConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI().info(new Info().title("---- API")
                .version("1.0.0")
                .description("This is --- API"));
    }
}

And in the controller,

@Validated
@CrossOrigin("*")
@RestController
@RequestMapping("/api/v1")
@SecurityRequirement(name = "BearerAuth")
public class StudentController {

 @PostMapping("students")
    public ResponseEntity<StudentModel> saveStudent(                                                                    @Valid @RequestBody(required = true) Student student, BindingResult bindingResult) {
...

But when I access http://localhost:8080/swagger-ui/ it does shows the  lock symbol Infront of the api but when execute the relevant url, I'm not getting 401 unauthorized status when I don't pass the bearer token.

My build.gradle file,

implementation('org.springdoc:springdoc-openapi-ui:1.5.3')


问:
data generator in python for BRATS 2020
i don't know the problem of this code special train_img_datagen line and  img,msk = train_img_datagen.next() line,these line dont work at all why?????/
the code is below:

```<code>import os
import numpy as np

def load_img(img_dir,img_list):
    images=[]
    for i, image_name in  enumerate(img_list):
        if(image_name.split('.')[1] == 'npy'):
            image = np.load(img_dir+image_name)

            images.append(image)
    images = np.array(images)

    return(images)

def imageLoader(img_dir , img_list , mask_dir , mask_list , batch_size):
    L = len (img_list)
    print(L)

    while True:

        batch_start = 0 ;
        batch_end = batch_size;Í

        while batch_start < L:
            limit = min(batch_end ,L)

            X = load_img(img_dir,img_list[batch_start:limit])
            Y = load_img(mask_dir,mask_list[batch_start:limit])

            # as a tuple with two numpy arrays with batch_size samples.å
            yield(X,Y)

            batch_start += batch_size
            batch_end   += batch_size

#Test the generator
from matplotlib import pyplot as plt
import random

train_img_dir = '/Users/najmeh/Desktop/proposal/MAIN WORK/database/validation+test/archive/BraTS2020_TrainingData/input_data_3channels/images/'
train_mask_dir = '/Users/najmeh/Desktop/proposal/MAIN WORK/database/validation+test/archive/BraTS2020_TrainingData/input_data_3channels/masks/'
train_img_list = os.listdir (train_img_dir)
train_mask_list = os.listdir (train_mask_dir)

batch_size = 2

train_img_datagen = imageLoader(train_img_dir,train_img_list,train_mask_dir,train_mask_list)

#verify generator
img,msk = train_img_datagen.__next__()

#Randomly select the image and use argmax to convert categorical to integer
img_num = random.randint(0,img.shape[0]-1)
test_img = img[img_num]
test_mask = msk[img_num]
tset_mask = np.argmax(test_mask, axis=3)

#Select the slice of image randomly and plot them
n_slice = random.randint(0, test_mask.shape[2])
plt.figure(figsize=(12,8))

plt.subplot(221)
plt.imshow(test_img[:,:,n_slice, 0], cmap='gray')
plt.title(" Image flair ")
plt.subplot(222)
plt.imshow(test_img[:,:,n_slice, 1], cmap='gray')
plt.title(" Image t1ce ")
plt.subplot(223)
plt.imshow(test_img[:,:,n_slice, 2], cmap='gray')
plt.title(" Image t2 ")
plt.subplot(224)
plt.imshow(test_mask[:,:,n_slice])
plt.title(" Mask ")
plt.show()
</code>```

i watched the toutrial and write the exact code but doesnt work
i print the list everything is ok but in the test part there is a problem

Title: data generator in python for BRATS 2020

Body:
i don't know the problem of this code special train_img_datagen line and  img,msk = train_img_datagen.next() line,these line dont work at all why?????/
the code is below:

import os
import numpy as np

def load_img(img_dir,img_list):
    images=[]
    for i, image_name in  enumerate(img_list):
        if(image_name.split('.')[1] == 'npy'):
            image = np.load(img_dir+image_name)

            images.append(image)
    images = np.array(images)

    return(images)

def imageLoader(img_dir , img_list , mask_dir , mask_list , batch_size):
    L = len (img_list)
    print(L)

    while True:

        batch_start = 0 ;
        batch_end = batch_size;Í

        while batch_start < L:
            limit = min(batch_end ,L)

            X = load_img(img_dir,img_list[batch_start:limit])
            Y = load_img(mask_dir,mask_list[batch_start:limit])

            # as a tuple with two numpy arrays with batch_size samples.å
            yield(X,Y)

            batch_start += batch_size
            batch_end   += batch_size

#Test the generator
from matplotlib import pyplot as plt
import random

train_img_dir = '/Users/najmeh/Desktop/proposal/MAIN WORK/database/validation+test/archive/BraTS2020_TrainingData/input_data_3channels/images/'
train_mask_dir = '/Users/najmeh/Desktop/proposal/MAIN WORK/database/validation+test/archive/BraTS2020_TrainingData/input_data_3channels/masks/'
train_img_list = os.listdir (train_img_dir)
train_mask_list = os.listdir (train_mask_dir)

batch_size = 2

train_img_datagen = imageLoader(train_img_dir,train_img_list,train_mask_dir,train_mask_list)

#verify generator
img,msk = train_img_datagen.__next__()

#Randomly select the image and use argmax to convert categorical to integer
img_num = random.randint(0,img.shape[0]-1)
test_img = img[img_num]
test_mask = msk[img_num]
tset_mask = np.argmax(test_mask, axis=3)

#Select the slice of image randomly and plot them
n_slice = random.randint(0, test_mask.shape[2])
plt.figure(figsize=(12,8))

plt.subplot(221)
plt.imshow(test_img[:,:,n_slice, 0], cmap='gray')
plt.title(" Image flair ")
plt.subplot(222)
plt.imshow(test_img[:,:,n_slice, 1], cmap='gray')
plt.title(" Image t1ce ")
plt.subplot(223)
plt.imshow(test_img[:,:,n_slice, 2], cmap='gray')
plt.title(" Image t2 ")
plt.subplot(224)
plt.imshow(test_mask[:,:,n_slice])
plt.title(" Mask ")
plt.show()

i watched the toutrial and write the exact code but doesnt work
i print the list everything is ok but in the test part there is a problem


问:
Motion detection in Blazor WebAssembly
Is there any way to do a fast motion detection on a video recorded from webcam in a Blazor WebAssembly app in .net core (PWA) ?

I did some  experiments getting the (some) frames from the video through js interop with requestVideoFrameCallback and elaborating them with ImageSharp e ImageSharpCompare but it required about 4 sec to analyze each frame.
All the specialized libraries I've found require a OS specific installation on the PC.

Do you have any suggestion?

Title: Motion detection in Blazor WebAssembly


问:
X2Go Error: X server does not support XInput 2
I am using the remote desktop software X2Go to use an Ubuntu 20.04 linux workstation from remote. I am tunneling from an Ubuntu 20.04 laptop. Initially, everything seems to work fine. When I start paraFoam, i get the following error message:

qt.qpa.xcb: X server does not support XInput 2

Aborted (core dumped)

Any ideas what could cause this problem?
I am using the mate-desktop-environment, had the exact same problem with xfce.

There is a thread relating to this in the X2Go mail archive, leading to a solution for Ubuntu 14. Has anyone tried this and can give detailed instructions?

Thread:
https://www.mail-archive.com/x2go-user@lists.x2go.org/msg04042.html

Workaround: https://wiki.x2go.org/doku.php/wiki:development:glx-xlib-workaround


问:
the page re-rendering when the params pass from the route changed, can anyone help me ,tell me why. Thanks a lot！

I Get params from route（IN Page2)

```<code>const ChatDetail: FunctionComponent = (props) => {
  const [messages, setMessages] = useState(null);
  const sendRef = useRef(GiftedChat)

  const chatData=props.route?.params.chatData;
}
</code>```

Use at here（IN Page2)

```<code>navigationOptions: {
  title: chatData?.userID.length>=10 ? chatData.userID.substring(0, 5) +
  '...' + chatData.userID.substring((chatData.userID.length-5)):chatData.userID,
}
</code>```

My question is: when the page1 (parent page) update the chataData (by web socket monitor)

and the page2 is auto re-rending, why for this happen?

Body:
I Get params from route（IN Page2)

const ChatDetail: FunctionComponent = (props) => {
  const [messages, setMessages] = useState(null);
  const sendRef = useRef(GiftedChat)

  const chatData=props.route?.params.chatData;
}

Use at here（IN Page2)

navigationOptions: {
  title: chatData?.userID.length>=10 ? chatData.userID.substring(0, 5) +
  '...' + chatData.userID.substring((chatData.userID.length-5)):chatData.userID,
}

My question is: when the page1 (parent page) update the chataData (by web socket monitor)

and the page2 is auto re-rending, why for this happen?


问:
Dividing a dataset into three subsets with similar development of mean
I have a simple set of data that shows a certain score over time for each data point. This dataset looks somewhat like this:

id
day 1
day 2
day 3
day 4

0
0
0.5
1
3

1
0
0.25
0.75
2.25

2
0
0
0.5
2.75

3
0
0.5
1
2

...
...
...
...
...

The objective is to divide this dataset into 3 groups which have a similar mean-value for any given day. I know that this is an NP-minimization problem and finding the optimal solution is inefficient. But an approximate solution would be absolutely fine.

Randomly picking data points and putting them into one of the groups showed these results:

Where global-mean is the mean of the unsplit data, group1-3 are the split groups.
Which already does not look too bad, however there is obviously room for improvement, as this was just randomly thrown together.

The longer I thought about this problem, the more complex it seemed to grow.

I am currently using Python 3.10 to try and solve it.

Does anyone have an idea how to tackle this? It does not necessarily have to be an elegant solution. Brute force should yield adequate results too, right?

Thank you in advance for your time.


问:
Flutter textAheadField how to get selected data from a custom class data
I have a textAheadField to display school list of data, its works normally. then i want to get the data selected by the user from the textAheadField suggestion but i just get an instance of my class.

This is my textAheadField

```<code>Widget SDBuildTextAhead() {
    return Container(
      child: TypeAheadField<SchoolData?>(
        debounceDuration: Duration(milliseconds: 500),
        textFieldConfiguration: TextFieldConfiguration(
          controller: sdAheadController,
        ),
        suggestionsCallback: SchoolApi.getUserSuggestions,
        itemBuilder: (context, SchoolData? suggestion) {
          final datasugestion = suggestion!;
          return ListTile(
            title: Text(datasugestion.university),
          );
        },
        onSuggestionSelected: (SchoolData? suggestion) =>
            sdAheadController.text = suggestion!.toString(), // this is selected by user.
      ),
    );
  }
</code>```

This is the class and SchoolApi

```<code>import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:skolae2_project/utils/utils.dart';

class SchoolData {
  final String university;

const SchoolData({
    required this.university,
  });

static SchoolData fromJson(Map<String, dynamic> json) => SchoolData(
    university: json['University'],
   );
}

class SchoolApi {
  static Future<List<SchoolData>> getUserSuggestions(String query) async {
    final String response =
        await rootBundle.loadString('assets/schooljson.json');

    if (response.isNotEmpty) {
      try {
        final List data = await json.decode(response.toString());

        return data.map((json) => SchoolData.fromJson(json)).where((type) {
          print("object");
          final nameLower = type.university.toLowerCase();
          final queryLower = query.toLowerCase();

          return nameLower.contains(queryLower);
        }).toList();
      } on Exception catch (e) {
        print(e);
        throw Utils.showSnackBar(e.toString());
      }
    } else {
      throw Exception();
    }
  }
}

</code>```

Here is the output when i choose one of the university data displayed

any suggestion about how to display the actual String data? not the instance of class??

Body:
I have a textAheadField to display school list of data, its works normally. then i want to get the data selected by the user from the textAheadField suggestion but i just get an instance of my class.

This is my textAheadField

Widget SDBuildTextAhead() {
    return Container(
      child: TypeAheadField<SchoolData?>(
        debounceDuration: Duration(milliseconds: 500),
        textFieldConfiguration: TextFieldConfiguration(
          controller: sdAheadController,
        ),
        suggestionsCallback: SchoolApi.getUserSuggestions,
        itemBuilder: (context, SchoolData? suggestion) {
          final datasugestion = suggestion!;
          return ListTile(
            title: Text(datasugestion.university),
          );
        },
        onSuggestionSelected: (SchoolData? suggestion) =>
            sdAheadController.text = suggestion!.toString(), // this is selected by user.
      ),
    );
  }

This is the class and SchoolApi

import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:skolae2_project/utils/utils.dart';

class SchoolData {
  final String university;

const SchoolData({
    required this.university,
  });

static SchoolData fromJson(Map<String, dynamic> json) => SchoolData(
    university: json['University'],
   );
}

class SchoolApi {
  static Future<List<SchoolData>> getUserSuggestions(String query) async {
    final String response =
        await rootBundle.loadString('assets/schooljson.json');

    if (response.isNotEmpty) {
      try {
        final List data = await json.decode(response.toString());

        return data.map((json) => SchoolData.fromJson(json)).where((type) {
          print("object");
          final nameLower = type.university.toLowerCase();
          final queryLower = query.toLowerCase();

          return nameLower.contains(queryLower);
        }).toList();
      } on Exception catch (e) {
        print(e);
        throw Utils.showSnackBar(e.toString());
      }
    } else {
      throw Exception();
    }
  }
}

Here is the output when i choose one of the university data displayed

any suggestion about how to display the actual String data? not the instance of class??


问:
Hibernate.xml file issue with <session-factory> tag
I have given the code below of my hibernate.cfg.xml file. While I was writing the code following a tutorial, I have encountered an error which states

The content of element type "session-factory" must match
"(property*,mapping*,(class-cache|collection-cache),event,listener*)".

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/</property>

        <property name="hibernate.connection.username">root</property>>

        <property name="hibernate.connection.password">Feelslikedope</property>

        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

    </session-factory>
</hibernate-configuration>
```

I am not able to find any proper solution for this type of error. One more thing is that when i am trying to change the SYSTEM to PUBLIC there is an error occurs which states there should be some white space after systemID.

Body:
I have given the code below of my hibernate.cfg.xml file. While I was writing the code following a tutorial, I have encountered an error which states

The content of element type "session-factory" must match
"(property*,mapping*,(class-cache|collection-cache),event,listener*)".

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/</property>

        <property name="hibernate.connection.username">root</property>>

        <property name="hibernate.connection.password">Feelslikedope</property>

        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

    </session-factory>
</hibernate-configuration>

I am not able to find any proper solution for this type of error. One more thing is that when i am trying to change the SYSTEM to PUBLIC there is an error occurs which states there should be some white space after systemID.


Title: Order the variable of the Y axis in "geom_title"

Body:
Question: I want order the variable in Y axis based on the number of "Zero". Other than, what if I have 20 or more variable?

my data is simple and show in the fig:

I use ggplot2 to draw that, here is my code:

ggplot(data, aes(year, factor(name))) +
  geom_tile(aes(fill =value),colour = "white") +
  scale_fill_distiller(palette="Spectral",name="value") +
  coord_fixed(ratio=1)+
  scale_x_continuous(expand = c(0,0))+
  scale_x_continuous(expand=c(0,0),
                 breaks=seq(1990, 2022, by=1)) +

theme_bw()

run the code:

dput(data) can show all the structure of data. The information display here:

structure(list(year = c(1998, 1999, 2000, 2001, 2002, 2003, 2004,
2005, 2006, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006), name = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), levels = c("c", "b",
"a"), class = "factor"), value = c(0, 0, 0, 0.346651040983634,
0.575355736998419, 0.258813293790067, 0.996722462580923, 0.634714417365377,
0.574420498061632, 0, 0.2, 0.244170435115193, 0.614290360870049,
0.886645071330728, 0.902835323742732, 0.0956880849086607, 0.229170033665038,
0.4679607332906, 0, 0, 0.8, 0.3, 0.0223354578076282, 0.957371777609129,
0.619967737221035, 0.79910708466687, 0.623430562124169)), row.names = c(NA,
27L), class = "data.frame")


问:
Multitenancy in Okta with Ruby on Rails
We have been trying to include Okta as a SSO option for our Ruby on Rails application.

In contrast to other SSO options, it uses a local credential system, which means that we need to save a set of credentials for each customer using our OIN app.

The omniauth-okta gem's install guide describes you need to put the credentials in an initialiser (where other omniauth strategies also exists). The issue with that is that it is set once per boot, and therefore static. So it only works for one set of credentials.

We have circumvented that by using a SETUP_PROC, that make it possible to hook into the network request and extract user data for getting credentials.

This work fines when going to Okta, but when redirecting back, it only returns state and code in the url. We need to identify the user that went through the SSO process.

Is there anyway to use these two get some user information from Okta?

Title: Multitenancy in Okta with Ruby on Rails


问:
SSL error in urllib: "certificate verify failed: unable to get local issuer certificate" while calling Rest API
I am working on calling the Rest-API from Python. All the Rest-API I have tested using Postman and are working fine. But, While executing those using Python scripts I am facing certification error. To fix that I have used certifi.

Below is the code:

`    import requests
import certifi
from urllib.request import urlopen
import ssl

```<code>requestCert = 'http://someurl.com:4443/api/project/'
urlopen(requestCert, context=ssl.create_default_context(cafile=certifi.where()))

headers = {
    "Authorization": "TokenXXXXXXXXXXX",
    "X-Auth-Token": "XXXXXXXXXXXXXXXXXXXX"
}
response = requests.get('http://someurl.com:4443/api/project/', headers=headers)

print(response)`
</code>```

Error:

 urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)>

Please let me know what needs to be modify in the above code.

Body:
I am working on calling the Rest-API from Python. All the Rest-API I have tested using Postman and are working fine. But, While executing those using Python scripts I am facing certification error. To fix that I have used certifi.

Below is the code:

`    import requests
import certifi
from urllib.request import urlopen
import ssl

requestCert = 'http://someurl.com:4443/api/project/'
urlopen(requestCert, context=ssl.create_default_context(cafile=certifi.where()))

headers = {
    "Authorization": "TokenXXXXXXXXXXX",
    "X-Auth-Token": "XXXXXXXXXXXXXXXXXXXX"
}
response = requests.get('http://someurl.com:4443/api/project/', headers=headers)

print(response)`

Error:

 urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)>

Please let me know what needs to be modify in the above code.


问:
Filter in get_context_data and get_query_set not working
I have a listview where I'm trying to filter out products by category. Some products have a subcategory. When a product has a subcategory I want the listview to display them by subcategory.
Problem is: The listview works perfect for items with a subcategory, but does not work for items who do not have a subcategory. Where am I taking a wrong turn here?

Models:

```<code>class Category(models.Model):
    category_name = models.CharField(max_length=200)
    sub_category = models.CharField(max_length=200,blank=True,null=True)
    category_picture = ResizedImageField(upload_to='category/', null=True, blank=True)
    category_info = models.TextField(blank=True, null=True)
    category_video = models.CharField(max_length=250,blank=True, null=True)

    def __str__(self):
        if self.sub_category is None:
            return self.category_name
        else:
            return f" {self.sub_category}"

    class Meta:
        ordering = ['category_name']

class Bottle(models.Model):
    category_name = models.ForeignKey('Category', on_delete=models.SET_NULL,null=True,blank=True)
    brand = models.ForeignKey('Brand', on_delete=models.CASCADE)
    bottle_name = models.CharField(max_length=255)
    bottle_info = models.TextField()
    bottle_tasting_notes = models.TextField()
    bottle_barcode = models.IntegerField()
    bottle_image = ResizedImageField(upload_to='bottles/',null=True, blank=True)
    bottle_shop_link = models.CharField(max_length=250, null=True, blank=True)

    def __str__(self):
        return f"{self.brand}, {self.bottle_name}"

    class Meta:
        ordering = ['bottle_name']
</code>```

View:

```<code>class BottlesByCategoryView(ListView):
    model = Bottle
    context_object_name = 'bottles'

    #Filter bij subcategory in the category model. If no subcategory exists, load by category_name
    def get_queryset(self):
        if Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) is None:
            return Bottle.objects.filter(category_name__category_name=self.kwargs['category'])
        else:
            return Bottle.objects.filter(category_name__sub_category=self.kwargs['category'])

    def get_context_data(self, **kwargs):
        context = super(BottlesByCategoryView, self).get_context_data(**kwargs)
        if Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) is None:
            context['category_info'] = Category.objects.filter(category_name=self.kwargs['category'])
        else:
            context['category_info'] = Category.objects.filter(sub_category=self.kwargs['category'])
        return context
</code>```

URLS:

```<code>path('BottlesByCategory/<str:category>/',BottlesByCategoryView.as_view(template_name='academy/bottlesByCat_list.html'),name='bottlesByCat_list'),
</code>```

Can i not use if statements in the get_context_data and get_query_set?

Body:
I have a listview where I'm trying to filter out products by category. Some products have a subcategory. When a product has a subcategory I want the listview to display them by subcategory.
Problem is: The listview works perfect for items with a subcategory, but does not work for items who do not have a subcategory. Where am I taking a wrong turn here?

Models:

class Category(models.Model):
    category_name = models.CharField(max_length=200)
    sub_category = models.CharField(max_length=200,blank=True,null=True)
    category_picture = ResizedImageField(upload_to='category/', null=True, blank=True)
    category_info = models.TextField(blank=True, null=True)
    category_video = models.CharField(max_length=250,blank=True, null=True)

    def __str__(self):
        if self.sub_category is None:
            return self.category_name
        else:
            return f" {self.sub_category}"

    class Meta:
        ordering = ['category_name']

class Bottle(models.Model):
    category_name = models.ForeignKey('Category', on_delete=models.SET_NULL,null=True,blank=True)
    brand = models.ForeignKey('Brand', on_delete=models.CASCADE)
    bottle_name = models.CharField(max_length=255)
    bottle_info = models.TextField()
    bottle_tasting_notes = models.TextField()
    bottle_barcode = models.IntegerField()
    bottle_image = ResizedImageField(upload_to='bottles/',null=True, blank=True)
    bottle_shop_link = models.CharField(max_length=250, null=True, blank=True)

    def __str__(self):
        return f"{self.brand}, {self.bottle_name}"

    class Meta:
        ordering = ['bottle_name']

View:

class BottlesByCategoryView(ListView):
    model = Bottle
    context_object_name = 'bottles'

    #Filter bij subcategory in the category model. If no subcategory exists, load by category_name
    def get_queryset(self):
        if Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) is None:
            return Bottle.objects.filter(category_name__category_name=self.kwargs['category'])
        else:
            return Bottle.objects.filter(category_name__sub_category=self.kwargs['category'])

    def get_context_data(self, **kwargs):
        context = super(BottlesByCategoryView, self).get_context_data(**kwargs)
        if Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) is None:
            context['category_info'] = Category.objects.filter(category_name=self.kwargs['category'])
        else:
            context['category_info'] = Category.objects.filter(sub_category=self.kwargs['category'])
        return context

URLS:

path('BottlesByCategory/<str:category>/',BottlesByCategoryView.as_view(template_name='academy/bottlesByCat_list.html'),name='bottlesByCat_list'),

Can i not use if statements in the get_context_data and get_query_set?


问:
API/SDK to create Server
Hey I am trying to Build a service which can be a Web server or window server, This server will be running on the local system.

The client which will be running on the same network will be listening continuously for the data from server, or send data to the server if needed.

The issue is I don't know which is the best method, the system is complex where server has to handle all the clients and process the data every 900 millisecond and update the client with latest data, and it should be run on local network with MySQL server.

I have tried SingnelR with web server but i am not able to run the server locally (Means I am not able to connect with server using IP address).

Socket Programming is also one of the options, but it required lot of exception handling and Time consuming.

This server is like MQTT server where server will continuously Publish data and Subscribe to the Clients Topics.

Title: API/SDK to create Server


问:
How does the equals greater "=>" operator work?
How does the => operator work and how does m come into existence in the following code ?:

```<code>using System;
using System.IO;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var line = "Keeping the line intact, replace me, but not you, keep this too.\n\nRetaining me, replace one, but not two, ignore three.";
        var res = Regex.Replace(line, @"replace (?<target>.*), but not (?<source>.*),", m => "replace " + m.Groups["source"].Value.Replace("o", "1") + ", but not " + m.Groups["source"].Value + ",");
        Console.WriteLine(res);
    }
}
</code>```

See the online compilation & output here.

EDIT:

This question is a duplicate but it should remain visible to searches because nowhere on StackOveflow is possible to find this association by searching for: => or for its English expansion: equals greater.  The first duplicate questions refers to it as arrow which caused my searches to return - NO HITS.

An "arrow" is e.g.: → (U+02192) , not the two characters =>

EDIT EDIT:

Never mind, the first duplicate question's title has been edited and now the search finds it with the search terms => or its English expansion "equal greater".

Body:
How does the => operator work and how does m come into existence in the following code ?:

using System;
using System.IO;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var line = "Keeping the line intact, replace me, but not you, keep this too.\n\nRetaining me, replace one, but not two, ignore three.";
        var res = Regex.Replace(line, @"replace (?<target>.*), but not (?<source>.*),", m => "replace " + m.Groups["source"].Value.Replace("o", "1") + ", but not " + m.Groups["source"].Value + ",");
        Console.WriteLine(res);
    }
}

See the online compilation & output here.

EDIT:

This question is a duplicate but it should remain visible to searches because nowhere on StackOveflow is possible to find this association by searching for: => or for its English expansion: equals greater.  The first duplicate questions refers to it as arrow which caused my searches to return - NO HITS.

An "arrow" is e.g.: → (U+02192) , not the two characters =>

EDIT EDIT:

Never mind, the first duplicate question's title has been edited and now the search finds it with the search terms => or its English expansion "equal greater".


问:
Redirection is possible in postman but not in chrome
I'm in a big trouble. I have to redirect the web page at the last stage after developing the API, but it seems to be redirected in the "postman" application, but it does not work at all in Chrome. What should I do?

enter image description here

First, This is view to receive parameters.

```<code><!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>forgot_password</title>
    <link rel = "stylesheet" href ="/css/sample.css">
    <link href = "/css/font.css" rel = "stylesheet">
    <link href = "/css/navbar2.css" rel = "stylesheet">
    <link href = "/css/forgot_password_css.css" rel = "stylesheet">

    <script>
      function findId() {
        let FindEmail = document.getElementById('exampleCheck1').checked;
        let PhoneNumber = document.getElementById('exampleInputPhoneNumber').value;
        let Name = document.getElementById('exampleInputName').value;

        let FindPassword = document.getElementById('exampleCheck2').checked;
        let PhoneNumber2 = document.getElementById('exampleInputPhoneNumber2').value;
        let email = document.getElementById('exampleInputEmail2').value;

        if (FindEmail == true && FindPassword == false) {
          const url = new URL("/find_email",location);
          url.searchParams.append('Name',Name);
          url.searchParams.append('PhoneNumber',PhoneNumber);
          location = url;

        } else if (FindEmail == false && FindPassword == true) {

        } else {
          alert("아이디 찾기와 비밀번호 찾기 중 하나만 선택하세요.");
          history.back();
        }
      }

    </script>
  </head>
  <body>

    <nav class="navbar bg-light fixed-top" id = "navbar_custom">
        <div class="container-fluid" id = "container-fluid_custom">
            <a class="navbar-brand" href="#">
                <img src="https://cdn-icons-png.flaticon.com/512/6815/6815258.png" alt="Bootstrap" width="30" height="24">
              </a>
          <a class="navbar-brand" href="http://localhost:8080/">Main Page</a>
          <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbar" aria-controls="offcanvasNavbar">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasNavbar" aria-labelledby="offcanvasNavbarLabel">
            <div class="offcanvas-header">
              <h5 class="offcanvas-title" id="offcanvasNavbarLabel">My Page</h5>
              <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
            </div>
            <div class="offcanvas-body">
              <ul class="navbar-nav justify-content-end flex-grow-1 pe-3">
                <li class="nav-item">
                  <a class="nav-link active" aria-current="page" href="#">설정</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#">마이페이지</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" aria-current="page" href="http://localhost:8080/mypoint">마이포인트</a>
                  </li>
               </ul>
            </div>
          </div>
        </div>
      </nav>

      <form class = "forgot_password_form">
    <h1> 아이디 찾기</h1>
    <div class="mb-3 form-check">
      <input type="checkbox" class="form-check-input" id="exampleCheck1">
      <label class="form-check-label" for="exampleCheck1">아이디 찾기 사용</label>

    </div> <div class="mb-3">
      <label for="exampleInputPhoneNumber" class="form-label">전화번호</label>
      <input type="text" class="form-control" id="exampleInputPhoneNumber" aria-describedby="emailHelp" placeholder="ex) 01012341234">
      <div id="emailHelp1" class="form-text">가입 시 사용한 전화번호여야 합니다.</div>
    </div>
    <div class="mb-3">
      <label for="exampleInputName" class="form-label">이름</label>
      <input type="text" class="form-control" id="exampleInputName" placeholder="ex) 세종대왕">
      <div id="emailHelp2" class="form-text">가입자의 이름이여야 합니다.</div>
    </div>
    <button type="submit" class="btn btn-primary" onclick= "findId()">실행</button>
  </form>

    <hr class ="one">

    <form class = "forgot_password_form">
      <h1> 비밀번호 찾기</h1>
      <div class="mb-3 form-check">
        <input type="checkbox" class="form-check-input" id="exampleCheck2">
        <label class="form-check-label" for="exampleCheck2">비밀번호 찾기 사용</label>

      </div> <div class="mb-3">
        <label for="exampleInputPhoneNumber2" class="form-label">전화번호</label>
        <input type="text" class="form-control" id="exampleInputPhoneNumber2" placeholder="ex) 01012341234">
        <div id="emailHelp3" class="form-text">가입 시 사용한 전화번호여야 합니다.</div>
      </div>
      <div class="mb-3">
        <label for="exampleInputEmail2" class="form-label">이메일</label>
        <input type="email" class="form-control" id="exampleInputEmail2" placeholder="ex) apple1234@naver.com">
        <div id="emailHelp" class="form-text">가입 시 사용한 이메일이여야 합니다.</div>
      </div>
      <button type="submit" class="btn btn-danger">실행</button>
    </form>

    <hr class ="one">

    <!-- Footer -->
<footer class="text-center text-lg-start bg-white text-muted">
  <!-- Section: Social media -->
  <section class="d-flex justify-content-center justify-content-lg-between p-4 border-bottom">
    <!-- Left -->
    <div class="me-5 d-none d-lg-block">
      <span>Get connected with us on social networks:</span>
    </div>
    <!-- Left -->

    <!-- Right -->
    <div>
      <a href="" class="me-4 link-secondary">
        <i class="fab fa-facebook-f"></i>
      </a>
      <a href="" class="me-4 link-secondary">
        <i class="fab fa-twitter"></i>
      </a>
      <a href="" class="me-4 link-secondary">
        <i class="fab fa-google"></i>
      </a>
      <a href="" class="me-4 link-secondary">
        <i class="fab fa-instagram"></i>
      </a>
      <a href="" class="me-4 link-secondary">
        <i class="fab fa-linkedin"></i>
      </a>
      <a href="" class="me-4 link-secondary">
        <i class="fab fa-github"></i>
      </a>
    </div>
    <!-- Right -->
  </section>
  <!-- Section: Social media -->

  <!-- Section: Links  -->
  <section class="">
    <div class="container text-center text-md-start mt-5">
      <!-- Grid row -->
      <div class="row mt-3">
        <!-- Grid column -->
        <div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
          <!-- Content -->
          <h6 class="text-uppercase fw-bold mb-4">
            <i class="fas fa-gem me-3 text-secondary"></i>Company name
          </h6>
          <p>
            This is a side project website, and we're not generating any revenue yet.
            Thank you for your visit. :)
          </p>
        </div>
        <!-- Grid column -->

        <!-- Grid column -->
        <div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
          <!-- Links -->
          <h6 class="text-uppercase fw-bold mb-4">
            Products
          </h6>
          <p>
            <a href="#!" class="text-reset">HTML, CSS, BOOTSTRAP</a>
          </p>
          <p>
            <a href="#!" class="text-reset">SPRING</a>
          </p>
          <p>
            <a href="#!" class="text-reset">JPA</a>
          </p>
          <p>
            <a href="#!" class="text-reset">MYSQL</a>
          </p>
        </div>
        <!-- Grid column -->

        <!-- Grid column -->
        <div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
          <!-- Links -->
          <h6 class="text-uppercase fw-bold mb-4">Contact</h6>
          <p><i class="fas fa-home me-3 text-secondary"></i> Seoul, 129 Teheran-ro, KR</p>
          <p>
            <i class="fas fa-envelope me-3 text-secondary"></i>
            gurtjd97@naver.com
          </p>
          <p><i class="fas fa-phone me-3 text-secondary"></i> +82)10-2729-3646</p>
        </div>
        <!-- Grid column -->
      </div>
      <!-- Grid row -->
    </div>
  </section>
  <!-- Section: Links  -->

  <!-- Copyright -->
  <div class="text-center p-4" style="background-color: rgba(0, 0, 0, 0.025);">
    © 2021 Copyright:
    <a class="text-reset fw-bold" href="https://mdbootstrap.com/">MDBootstrap.com</a>
  </div>
  <!-- Copyright -->
</footer>
<!-- Footer -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  </body>
</html>
</code>```

This is the page to be redirected.

```<code><!DOCTYPE html>
<html lang="en" xmlns:th = "http://www.thymeleafg">
<head>
    <meta charset="UTF-8">
    <title>Alert Page</title>

    <script th:inline = "javascript">
        var username = [[${string}]];
        alert(username);
    </script>
</head>
<body>

</body>
</html>
</code>```

Controller that processes and redirects values. (Normaly operated in Postman)

```<code>@Controller
public class ForgotController {

    @Autowired
    private UserService userService;

    @GetMapping("/find_email")
    public String findEmail(FindEmailDto findEmailDto,RedirectAttributes redirectAttributes) {
            Optional<Users> users = userService.findEmail(findEmailDto);
            if (users.isPresent()) {
                String email = users.get().getEmail();
                redirectAttributes.addAttribute("value", email);
                return "redirect:/alert";
            }

        redirectAttributes.addAttribute("value","없는 회원 정보 입니다");
        return "redirect:/alert";
    }

    @GetMapping("/alert")
    public String alertPage(@RequestParam("value") String s, Model model) {
        model.addAttribute("string", s);
        return "alert";
    }
}

</code>```

Body:
I'm in a big trouble. I have to redirect the web page at the last stage after developing the API, but it seems to be redirected in the "postman" application, but it does not work at all in Chrome. What should I do?

enter image description here

First, This is view to receive parameters.

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>forgot_password</title>
    <link rel = "stylesheet" href ="/css/sample.css">
    <link href = "/css/font.css" rel = "stylesheet">
    <link href = "/css/navbar2.css" rel = "stylesheet">
    <link href = "/css/forgot_password_css.css" rel = "stylesheet">

          Main Page
          <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbar" aria-controls="offcanvasNavbar">

          </button>

My Page

              <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>

                  설정

                  마이페이지

                    마이포인트

      <form class = "forgot_password_form">

 아이디 찾기

      <input type="checkbox" class="form-check-input" id="exampleCheck1">
      아이디 찾기 사용

      전화번호
      <input type="text" class="form-control" id="exampleInputPhoneNumber" aria-describedby="emailHelp" placeholder="ex) 01012341234">

가입 시 사용한 전화번호여야 합니다.

      이름
      <input type="text" class="form-control" id="exampleInputName" placeholder="ex) 세종대왕">

가입자의 이름이여야 합니다.

    <button type="submit" class="btn btn-primary" onclick= "findId()">실행</button>
  </form>

    <form class = "forgot_password_form">

 비밀번호 찾기

        <input type="checkbox" class="form-check-input" id="exampleCheck2">
        비밀번호 찾기 사용

        전화번호
        <input type="text" class="form-control" id="exampleInputPhoneNumber2" placeholder="ex) 01012341234">

가입 시 사용한 전화번호여야 합니다.

        이메일
        <input type="email" class="form-control" id="exampleInputEmail2" placeholder="ex) apple1234@naver.com">

가입 시 사용한 이메일이여야 합니다.

      <button type="submit" class="btn btn-danger">실행</button>
    </form>

      Get connected with us on social networks:

            Company name

            This is a side project website, and we're not generating any revenue yet.
            Thank you for your visit. :)

            Products

            HTML, CSS, BOOTSTRAP

            SPRING

            JPA

            MYSQL

Contact

 Seoul, 129 Teheran-ro, KR

            gurtjd97@naver.com

 +82)10-2729-3646

    © 2021 Copyright:
    MDBootstrap.com

This is the page to be redirected.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Alert Page</title>

Controller that processes and redirects values. (Normaly operated in Postman)

@Controller
public class ForgotController {

    @Autowired
    private UserService userService;

    @GetMapping("/find_email")
    public String findEmail(FindEmailDto findEmailDto,RedirectAttributes redirectAttributes) {
            Optional<Users> users = userService.findEmail(findEmailDto);
            if (users.isPresent()) {
                String email = users.get().getEmail();
                redirectAttributes.addAttribute("value", email);
                return "redirect:/alert";
            }

        redirectAttributes.addAttribute("value","없는 회원 정보 입니다");
        return "redirect:/alert";
    }

    @GetMapping("/alert")
    public String alertPage(@RequestParam("value") String s, Model model) {
        model.addAttribute("string", s);
        return "alert";
    }
}


问:
Saving scaled UUImage to default Document folder in SwiftUI
I'm trying to save a scaled UUImage in default Document folder in the SwiftUI world. In particular I would like to resize the image before saving it. The flow is: the user takes a picture and at some point this picture is saved. Regardless of its size, its width should be 512 px and its height will be calculated keeping the aspect ratio. I wrote a function to resize the picture before save it and if I debug, the original picture's size is changed correctly but after I save it in document folder, the width and height are completely different. What am i doing wrong?

this is my function that resizes the image:

```<code>
extension UIImage {
    func imageResized(to size: CGSize) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { _ in
            draw(in: CGRect(origin: .zero, size: size))
        }
    }
}
</code>```

this is my function that resize and save the picture:

```<code>    func saveImageToDocuments(imageName: String, image: UIImage) -> String? {

     guard let directoryToSave = getOrCreateCurrentMonthYearFolder() else { return nil }

        let absolutePath = directoryToSave.absoluteString
        let tokens = absolutePath.split(separator: "/")

        let relativePath = String(tokens[tokens.count-2]) + "/" + (String(tokens[tokens.count-1]))

        let fileURL = directoryToSave.appendingPathComponent(imageName)

        let newHeight = (image.size.height * 512) / image.size.width;
        let cgSize= CGSize(width: 512, height: newHeight)
        let resizedImage = image.imageResized(to: cgSize)
        guard let data = resizedImage.jpegData(compressionQuality: 0.5) else { return nil }

        do {
            try data.write(to: fileURL, options: .atomic)
            print("Immagine salvata")

            return relativePath

        } catch let error {
            print("error saving file with error", error)
            return nil

        }

    }
</code>```

Body:
I'm trying to save a scaled UUImage in default Document folder in the SwiftUI world. In particular I would like to resize the image before saving it. The flow is: the user takes a picture and at some point this picture is saved. Regardless of its size, its width should be 512 px and its height will be calculated keeping the aspect ratio. I wrote a function to resize the picture before save it and if I debug, the original picture's size is changed correctly but after I save it in document folder, the width and height are completely different. What am i doing wrong?

this is my function that resizes the image:

extension UIImage {
    func imageResized(to size: CGSize) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { _ in
            draw(in: CGRect(origin: .zero, size: size))
        }
    }
}

this is my function that resize and save the picture:

    func saveImageToDocuments(imageName: String, image: UIImage) -> String? {

     guard let directoryToSave = getOrCreateCurrentMonthYearFolder() else { return nil }

        let absolutePath = directoryToSave.absoluteString
        let tokens = absolutePath.split(separator: "/")

        let relativePath = String(tokens[tokens.count-2]) + "/" + (String(tokens[tokens.count-1]))

        let fileURL = directoryToSave.appendingPathComponent(imageName)

        let newHeight = (image.size.height * 512) / image.size.width;
        let cgSize= CGSize(width: 512, height: newHeight)
        let resizedImage = image.imageResized(to: cgSize)
        guard let data = resizedImage.jpegData(compressionQuality: 0.5) else { return nil }

        do {
            try data.write(to: fileURL, options: .atomic)
            print("Immagine salvata")

            return relativePath

        } catch let error {
            print("error saving file with error", error)
            return nil

        }

    }


问:
How can i put a string as a title in header for table calendar?
Is it possible to put a const string as a header title for table calendar ?

And the package i am using is

table calendar

```<code>TableCalendar(
        firstDay: DateTime.now(),
        lastDay: DateTime.utc(2040, 10, 10),
        focusedDay: DateTime.now(),
        headerStyle: const HeaderStyle(
          leftChevronVisible: false,
          rightChevronVisible: false,
          formatButtonVisible: false,
        ),
      ),
</code>```

Body:
Is it possible to put a const string as a header title for table calendar ?

And the package i am using is

table calendar

TableCalendar(
        firstDay: DateTime.now(),
        lastDay: DateTime.utc(2040, 10, 10),
        focusedDay: DateTime.now(),
        headerStyle: const HeaderStyle(
          leftChevronVisible: false,
          rightChevronVisible: false,
          formatButtonVisible: false,
        ),
      ),


问:
200 with Error body instead of 4xx response from AWS API Gateway
I'm using API Gateway to get access to S3 Bucket through REST API. Everything works as I would expect except when I want to fetch data from a wrong file/folder. Instead of 4xx code I get 200 with Error in the xml format:

<?xml version="1.0" encoding="UTF-8"?>
<Error>
    NoSuchKey
    <Message>The specified key does not exist.</Message>
    <Key>dir/dir2/dir3/file.ext</Key>
    <RequestId>XXXX</RequestId>
    <HostId>YYYY/J+ZZZZ/XXX/YYYY/ZZZ=</HostId>
</Error>
```

Is there any way to get non-200 response code? In the documentation there is an example with the NoSuchKey and info about "An appropriate 3xx, 4xx or 5xx HTTP status code"

Body:
I'm using API Gateway to get access to S3 Bucket through REST API. Everything works as I would expect except when I want to fetch data from a wrong file/folder. Instead of 4xx code I get 200 with Error in the xml format:

<?xml version="1.0" encoding="UTF-8"?>
<Error>
    NoSuchKey
    <Message>The specified key does not exist.</Message>
    <Key>dir/dir2/dir3/file.ext</Key>
    <RequestId>XXXX</RequestId>
    <HostId>YYYY/J+ZZZZ/XXX/YYYY/ZZZ=</HostId>
</Error>

Is there any way to get non-200 response code? In the documentation there is an example with the NoSuchKey and info about "An appropriate 3xx, 4xx or 5xx HTTP status code"