问:
Different behavior with user defined default constructor (only MSVC)
I came across the following problem, with two classes X and Y where Y has a member of type X

If I then:

create a vector of objects of type Y via std::vector<Y> list = {{}}

and Y has a defaulted default constructor

One of the instances of type X will be destroyed twice. Even when using rule of three (or five).

It does not happen, if I either create the vector via {Y{}} or define a user supplied default constructor for Y.

See the console output of the following example:

#include <iostream>
#include <vector>

class X
{
public:
    X()
    {
        std::cout << "constructed " << this << std::endl;
    }
    ~X()
    {
        std::cout << "deleted " << this << std::endl;
    }
    X(const X& other)
    {
        std::cout << "copy constructed " << &other << " to " << this << std::endl;
    }
};

class Y
{
public:
    //Y(){}; // works
    Y() = default; // doesn't work
    ~Y() = default;
    Y(const Y& y) = default; // copy constructor
    Y& operator=(const Y& y) = default; // copy assignment
    // Y(Y&& other) noexcept = default; // move constructor
    // Y& operator=(Y&& other) noexcept = default; // move assignment
private:
    X x;
};

int main()
{
    std::cout << "start" << std::endl;
    std::vector<Y> list = {{}}; // doesn't work
    //std::vector<Y> list = {Y{}}; // works
    std::cout << "done" << std::endl;
    return 0;
}
```
<p>Outputs</p>
```start
constructed 000000271CAFFCD0
copy constructed 000000271CAFFCD0 to 000001727F7145B0
deleted 000000271CAFFCD0
deleted 000000271CAFFCD0
done
deleted 000001727F7145B0
```

https://godbolt.org/z/vscP4TexE

This is only reproducable in MSVC.

Am I missing something or is this a compiler bug?

Edit

Thanks for the hint about the missing return statements.
I added them, but get the same results.

I did enable warnings, but it only shows that the unreferenced inline functions are removed.

Edit 2

Since they are unused, I removed copy and move constructors and assignment operators from the example.

Edit 3

Adapted Output to the new code example. It still contains the double delete. Note that MSVC is a bit flakey on godbolt and it sometimes does not compile the example.

Body:
I came across the following problem, with two classes X and Y where Y has a member of type X

If I then:

create a vector of objects of type Y via std::vector<Y> list = {{}}

and Y has a defaulted default constructor

One of the instances of type X will be destroyed twice. Even when using rule of three (or five).

It does not happen, if I either create the vector via {Y{}} or define a user supplied default constructor for Y.

See the console output of the following example:

#include <iostream>
#include <vector>

class X
{
public:
    X()
    {
        std::cout << "constructed " << this << std::endl;
    }
    ~X()
    {
        std::cout << "deleted " << this << std::endl;
    }
    X(const X& other)
    {
        std::cout << "copy constructed " << &other << " to " << this << std::endl;
    }
};

class Y
{
public:
    //Y(){}; // works
    Y() = default; // doesn't work
    ~Y() = default;
    Y(const Y& y) = default; // copy constructor
    Y& operator=(const Y& y) = default; // copy assignment
    // Y(Y&& other) noexcept = default; // move constructor
    // Y& operator=(Y&& other) noexcept = default; // move assignment
private:
    X x;
};

int main()
{
    std::cout << "start" << std::endl;
    std::vector<Y> list = {{}}; // doesn't work
    //std::vector<Y> list = {Y{}}; // works
    std::cout << "done" << std::endl;
    return 0;
}

Outputs

start
constructed 000000271CAFFCD0
copy constructed 000000271CAFFCD0 to 000001727F7145B0
deleted 000000271CAFFCD0
deleted 000000271CAFFCD0
done
deleted 000001727F7145B0

https://godbolt.org/z/vscP4TexE

This is only reproducable in MSVC.

Am I missing something or is this a compiler bug?

Edit

Thanks for the hint about the missing return statements.
I added them, but get the same results.

I did enable warnings, but it only shows that the unreferenced inline functions are removed.

Edit 2

Since they are unused, I removed copy and move constructors and assignment operators from the example.

Edit 3

Adapted Output to the new code example. It still contains the double delete. Note that MSVC is a bit flakey on godbolt and it sometimes does not compile the example.


来源: stackexchange

问:
How to remove warning: unknown enum constant ISO.DATE_TIME warning in android studio?
There are two warning:-

```<code>warning: unknown enum constant ISO.DATE_TIME
  reason: class file for org.springframework.format.annotation.DateTimeFormat$ISO not found
</code>```
```<code>One or more classes has class file version >= 56 which is not officially supported.
</code>```

The Gradle file is:-

```<code>plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-android'
    id 'kotlin-parcelize'
    id 'com.google.dagger.hilt.android'
    id 'kotlin-kapt'
}
def oktaProperties = new Properties()
rootProject.file("okta.properties").withInputStream { oktaProperties.load(it) }
android {
    compileSdk 33

    defaultConfig {
        applicationId ""
        minSdk 21
        targetSdk 33
        versionCode 1
        versionName "1.0"
        multiDexEnabled = true

    ...
    }

    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
        kotlinOptions {
            freeCompilerArgs += [
                    '-opt-in=kotlin.RequiresOptIn',
            ]
        }
    }

    kotlinOptions {
        jvmTarget = '11'
    }

    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    implementation files('libs/abc-models.jar')
    implementation files('libs/abc-models.jar')
    ...
</code>```

I think it's coming from the .jar file that I imported. I tried different Java Versions too but it's not working.

ContentLicense: CC BY-SA 4.0

Body:
There are two warning:-

warning: unknown enum constant ISO.DATE_TIME
  reason: class file for org.springframework.format.annotation.DateTimeFormat$ISO not found

One or more classes has class file version >= 56 which is not officially supported.

The Gradle file is:-

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-android'
    id 'kotlin-parcelize'
    id 'com.google.dagger.hilt.android'
    id 'kotlin-kapt'
}
def oktaProperties = new Properties()
rootProject.file("okta.properties").withInputStream { oktaProperties.load(it) }
android {
    compileSdk 33

    defaultConfig {
        applicationId ""
        minSdk 21
        targetSdk 33
        versionCode 1
        versionName "1.0"
        multiDexEnabled = true

    ...
    }

    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
        kotlinOptions {
            freeCompilerArgs += [
                    '-opt-in=kotlin.RequiresOptIn',
            ]
        }
    }

    kotlinOptions {
        jvmTarget = '11'
    }

    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    implementation files('libs/abc-models.jar')
    implementation files('libs/abc-models.jar')
    ...

I think it's coming from the .jar file that I imported. I tried different Java Versions too but it's not working.


问:
X11 virtual desktops: which are visible?
My Python program uses Xlib and Gtk3 and runs in an X-session with the window manager i3. I have 3 (real) monitors in this setup. i3 provides virtual desktops (and many other window managers behave similar here), at least 3 of them, as each monitor represents a desktop (on this standard setup). A monitor can have more desktops, but only one of them will be visible at a time.

I managed to move windows to any desktop:

```<code>gtk_window.get_window().move_to_desktop(2)
</code>```

I can also distinguish on which monitor a desktop/window is:

```<code>x11display = Gdk.get_default_root_window().get_display()
x11monitor = x11display.get_monitor_at_window(gtk_window)
xid = GdkX11.X11Monitor.get_output(x11monitor)
# different xid → different monitor
</code>```

But I found no way to see which desktop is visible whenever multiple desktops are associated with a monitor.

Any solution?

Body:
My Python program uses Xlib and Gtk3 and runs in an X-session with the window manager i3. I have 3 (real) monitors in this setup. i3 provides virtual desktops (and many other window managers behave similar here), at least 3 of them, as each monitor represents a desktop (on this standard setup). A monitor can have more desktops, but only one of them will be visible at a time.

I managed to move windows to any desktop:

gtk_window.get_window().move_to_desktop(2)

I can also distinguish on which monitor a desktop/window is:

x11display = Gdk.get_default_root_window().get_display()
x11monitor = x11display.get_monitor_at_window(gtk_window)
xid = GdkX11.X11Monitor.get_output(x11monitor)
# different xid → different monitor

But I found no way to see which desktop is visible whenever multiple desktops are associated with a monitor.

Any solution?


问:
VS Code opens a new editor group for data viewer
I'm using two editor groups in VS Code to write Python code. The left group has open files, and the right group has an interactive Jupyter-like window to test code and also displays data frames with the data viewer.

Alas, since a few days ago, VS Code always opens a third editor group to the right when I open the data viewer (subsequent data frames will also be displayed in this group). This, of course, needs space and everything is reshuffled and it's driving me nuts.

I must have changed something inadvertently so that VS Code is no longer limited to opening 2 editor groups, but I can't find the setting. How do I turn this back?

I have looked through the settings (global and workspace) and can't find anything remotely indicating how to configure it.


问:
Django authentication password returning False
I'm trying to create an authentication system using Django with a custom backend and user class, but every time I try to authenticate with an existing user and password in my Postgresql database the check_password() function always returns False and I can't proceed.

Here's the code for the UserBackend on backends.py

from django.contrib.auth.backends import ModelBackend
from .models import user

class UserBackend(ModelBackend):
    def authenticate(self, **kwargs):
        username = kwargs['username']
        password = kwargs['password']

        print('user: ', username)
        print('pass: ', password)
        #try:
        user_ = user.objects.get(username=username)

        try:
            print(user_.check_password(password))
            if user_.check_password(password) is True:  #Here check_password() is always false
                return user_
        except user.DoesNotExist:
            pass

        def get_user(self, user_id):
            try:
                return user.objects.get(pk=user_id)
            except user.DoesNotExist:
                return None
```
<p><em>views.py</em></p>
<pre class="lang-py prettyprint-override"><code>def signin(request):
now = datetime.now()
if request.method == 'POST':
    username = request.POST['username']
    password = request.POST['password']

    user = UserBackend.authenticate(ModelBackend(),username=username, password=password)

    if user is not None:
        #auth.login(request, user)
        return redirect('/index')
    else:
        messages.info(request, 'invalid username or password')
        return redirect("/signin")
else:
    return render(request,'signin.html')

return render(request, 'signin.html')
</code>```

models.py

class user(AbstractBaseUser):
    id = models.AutoField(primary_key=True)
    username = models.TextField()
    real_name = models.TextField()
    email = models.TextField()
    password = models.TextField()
    description = models.TextField()
    last_login = models.DateField()
    created_at = models.DateField()
    class Meta:
        managed = False
        db_table = 'user'

    def __str__(self) -> str:
        return self.username

```

what am I doing wrong?

Body:
I'm trying to create an authentication system using Django with a custom backend and user class, but every time I try to authenticate with an existing user and password in my Postgresql database the check_password() function always returns False and I can't proceed.

Here's the code for the UserBackend on backends.py

from django.contrib.auth.backends import ModelBackend
from .models import user

class UserBackend(ModelBackend):
    def authenticate(self, **kwargs):
        username = kwargs['username']
        password = kwargs['password']

        print('user: ', username)
        print('pass: ', password)
        #try:
        user_ = user.objects.get(username=username)

        try:
            print(user_.check_password(password))
            if user_.check_password(password) is True:  #Here check_password() is always false
                return user_
        except user.DoesNotExist:
            pass

        def get_user(self, user_id):
            try:
                return user.objects.get(pk=user_id)
            except user.DoesNotExist:
                return None

views.py

def signin(request):
now = datetime.now()
if request.method == 'POST':
    username = request.POST['username']
    password = request.POST['password']

    user = UserBackend.authenticate(ModelBackend(),username=username, password=password)

    if user is not None:
        #auth.login(request, user)
        return redirect('/index')
    else:
        messages.info(request, 'invalid username or password')
        return redirect("/signin")
else:
    return render(request,'signin.html')

return render(request, 'signin.html')

models.py

class user(AbstractBaseUser):
    id = models.AutoField(primary_key=True)
    username = models.TextField()
    real_name = models.TextField()
    email = models.TextField()
    password = models.TextField()
    description = models.TextField()
    last_login = models.DateField()
    created_at = models.DateField()
    class Meta:
        managed = False
        db_table = 'user'

    def __str__(self) -> str:
        return self.username

what am I doing wrong?


问:
Errors in my java security manager policy - which permission needed
I am trying to lock down a Java program using the security manager.
It provides a lot of guidance to you in the error state to tell you want it failed on.

I am down to three issue that don't show up as any "access denied" errors that come with the recommended policy entry.

This application works when the policy is

```<code>grant {
    // Allow everything for now
    permission java.security.AllPermission;
};
</code>```

when it is the policy at the bottom of this post.  These errors show up.  I can't find any "denied" msgs for them

Issue 1:

```<code>Fri Dec 09 00:30:29 CST 2022:ExecGroup-0:err:java.security.NoSuchAlgorithmException: PBKDF2WithHmacSHA512 SecretKeyFactory not available
Fri Dec 09 00:30:29 CST 2022:ExecGroup-0:err:   at javax.crypto.SecretKeyFactory.<init>(SecretKeyFactory.java:122)
Fri Dec 09 00:30:29 CST 2022:ExecGroup-0:err:   at javax.crypto.SecretKeyFactory.getInstance(SecretKeyFactory.java:160)
</code>```

Issue 2

```<code>Fri Dec 09 00:30:29 CST 2022:ExecGroup-0:err:FATAL ERROR: java.lang.IllegalArgumentException: DatabaseUserid security exception
</code>```

Issue 3

```<code>rmid: activation group inactive: java.rmi.ConnectException: Connection refused to host: SJohns-XPS7590.snafuHQ.local; nested exception is:
        java.net.ConnectException: Connection refused: connect
java.rmi.ConnectException: Connection refused to host: SJohns-XPS7590.snafuHQ.local; nested exception is:
        java.net.ConnectException: Connection refused: connect
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:623)
        at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
        at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
        at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:132)
        at java.rmi.activation.ActivationGroup_Stub.newInstance(Unknown Source)
        at sun.rmi.server.Activation$ObjectEntry.activate(Activation.java:1494)
        at sun.rmi.server.Activation$GroupEntry.activate(Activation.java:1180)
        at sun.rmi.server.Activation$ActivatorImpl.activate(Activation.java:409)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
        at sun.rmi.transport.Transport$1.run(Transport.java:200)
        at sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused: connect
        at java.net.DualStackPlainSocketImpl.connect0(Native Method)
        at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:607)
        at java.net.Socket.connect(Socket.java:556)
        at java.net.Socket.<init>(Socket.java:452)
        at java.net.Socket.<init>(Socket.java:229)
        at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
        at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:617)
        ... 24 more
access: access allowed ("java.util.PropertyPermission" "line.separator" "read")
Dec 09, 2022 12:30:32 AM sun.rmi.server.UnicastServerRef logCallException
FINE: RMI TCP Connection(3)-192.168.1.125: [192.168.1.125] exception:
java.rmi.activation.ActivationException: object activation failed after 2 tries; nested exception is:
        java.rmi.ConnectException: Connection refused to host: SJohns-XPS7590.snafuHQ.local; nested exception is:
        java.net.ConnectException: Connection refused: connect
        at sun.rmi.server.Activation$GroupEntry.activate(Activation.java:1223)
        at sun.rmi.server.Activation$ActivatorImpl.activate(Activation.java:409)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
        at sun.rmi.transport.Transport$1.run(Transport.java:200)
        at sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.rmi.ConnectException: Connection refused to host: SJohns-XPS7590.snafuHQ.local; nested exception is:
        java.net.ConnectException: Connection refused: connect
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:623)
        at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
        at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
        at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:132)
        at java.rmi.activation.ActivationGroup_Stub.newInstance(Unknown Source)
        at sun.rmi.server.Activation$ObjectEntry.activate(Activation.java:1494)
        at sun.rmi.server.Activation$GroupEntry.activate(Activation.java:1180)
        ... 18 more
Caused by: java.net.ConnectException: Connection refused: connect
        at java.net.DualStackPlainSocketImpl.connect0(Native Method)
        at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:607)
        at java.net.Socket.connect(Socket.java:556)
        at java.net.Socket.<init>(Socket.java:452)
        at java.net.Socket.<init>(Socket.java:229)
        at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
        at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:617)
        ... 24 more
</code>```

LOCK DOWN POLICY FILE

```<code>// https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8229532
// https://stackoverflow.com/questions/57433655/classnotfoundexception-issued-by-urlclassloader-when-the-security-manager-is-ena

//grant {
    // Allow everything for now
    //permission java.security.AllPermission;
//};

grant codeBase "file:/C:/apps/snafu/foobar/*" {

    //
    // Allow everything for now
    //permission java.security.AllPermission;

    permission java.net.SocketPermission "127.0.0.1:*", "accept,connect,resolve";
    permission java.net.SocketPermission "localhost:6990", "listen,accept,connect,resolve";
    permission java.net.SocketPermission "localhost:6993", "listen,accept,connect,resolve";
    permission java.net.SocketPermission "SJohns-XPS7590.snafuHQ.local:*", "listen,accept,connect,resolve";
    permission java.net.SocketPermission "192.168.1.125:6993", "listen,accept,connect,resolve";

    permission java.util.PropertyPermission "user.dir", "read";
    permission java.util.PropertyPermission "user.home", "read";
    permission java.util.PropertyPermission "LicenseFilename", "read";
    permission java.util.PropertyPermission "HostId", "read";
    permission java.util.PropertyPermission "InstanceID", "read";
    permission java.util.PropertyPermission "slc.ps_loc", "write";
    permission java.util.PropertyPermission "org.owasp.esapi.SecurityConfiguration", "read";
    permission java.util.PropertyPermission "org.owasp.esapi.logSpecial.discard", "read";
    permission java.util.PropertyPermission "org.owasp.esapi.resources", "read";
    permission java.util.PropertyPermission "*", "read,write";
    permission java.util.PropertyPermission "org.owasp.esapi.opsteam", "read";

    permission java.util.logging.LoggingPermission "control";

    permission java.io.FilePermission ".", "read";
    permission java.io.FilePermission "C:/Apps/snafu/foobar/-", "read,write,delete";

    permission java.lang.management.ManagementPermission "monitor";

    permission java.lang.reflect.ReflectPermission "suppressAccessChecks";

    permission java.lang.RuntimePermission "setFactory";
    permission java.lang.RuntimePermission "getClassLoader";
    permission java.lang.RuntimePermission "setContextClassLoader";
    permission java.lang.RuntimePermission "getenv.*";
    permission java.lang.RuntimePermission "getProtectionDomain";
    permission java.lang.RuntimePermission "accessDeclaredMembers";
    permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect";
    permission java.lang.RuntimePermission "loadLibrary.sunec";
    permission java.lang.RuntimePermission "loadLibrary.sunmscapi";

    permission javax.management.MBeanTrustPermission "register";
    permission javax.management.MBeanServerPermission "createMBeanServer";
    permission javax.management.MBeanPermission "*", "queryNames";
    permission javax.management.MBeanPermission "*", "registerMBean,unregisterMBean";

    permission java.security.SecurityPermission "putProviderProperty.SunJCE";
};
</code>```

Body:
I am trying to lock down a Java program using the security manager.
It provides a lot of guidance to you in the error state to tell you want it failed on.

I am down to three issue that don't show up as any "access denied" errors that come with the recommended policy entry.

This application works when the policy is

grant {
    // Allow everything for now
    permission java.security.AllPermission;
};

when it is the policy at the bottom of this post.  These errors show up.  I can't find any "denied" msgs for them

Issue 1:

Fri Dec 09 00:30:29 CST 2022:ExecGroup-0:err:java.security.NoSuchAlgorithmException: PBKDF2WithHmacSHA512 SecretKeyFactory not available
Fri Dec 09 00:30:29 CST 2022:ExecGroup-0:err:   at javax.crypto.SecretKeyFactory.<init>(SecretKeyFactory.java:122)
Fri Dec 09 00:30:29 CST 2022:ExecGroup-0:err:   at javax.crypto.SecretKeyFactory.getInstance(SecretKeyFactory.java:160)

Issue 2

Fri Dec 09 00:30:29 CST 2022:ExecGroup-0:err:FATAL ERROR: java.lang.IllegalArgumentException: DatabaseUserid security exception

Issue 3

rmid: activation group inactive: java.rmi.ConnectException: Connection refused to host: SJohns-XPS7590.snafuHQ.local; nested exception is:
        java.net.ConnectException: Connection refused: connect
java.rmi.ConnectException: Connection refused to host: SJohns-XPS7590.snafuHQ.local; nested exception is:
        java.net.ConnectException: Connection refused: connect
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:623)
        at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
        at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
        at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:132)
        at java.rmi.activation.ActivationGroup_Stub.newInstance(Unknown Source)
        at sun.rmi.server.Activation$ObjectEntry.activate(Activation.java:1494)
        at sun.rmi.server.Activation$GroupEntry.activate(Activation.java:1180)
        at sun.rmi.server.Activation$ActivatorImpl.activate(Activation.java:409)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
        at sun.rmi.transport.Transport$1.run(Transport.java:200)
        at sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused: connect
        at java.net.DualStackPlainSocketImpl.connect0(Native Method)
        at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:607)
        at java.net.Socket.connect(Socket.java:556)
        at java.net.Socket.<init>(Socket.java:452)
        at java.net.Socket.<init>(Socket.java:229)
        at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
        at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:617)
        ... 24 more
access: access allowed ("java.util.PropertyPermission" "line.separator" "read")
Dec 09, 2022 12:30:32 AM sun.rmi.server.UnicastServerRef logCallException
FINE: RMI TCP Connection(3)-192.168.1.125: [192.168.1.125] exception:
java.rmi.activation.ActivationException: object activation failed after 2 tries; nested exception is:
        java.rmi.ConnectException: Connection refused to host: SJohns-XPS7590.snafuHQ.local; nested exception is:
        java.net.ConnectException: Connection refused: connect
        at sun.rmi.server.Activation$GroupEntry.activate(Activation.java:1223)
        at sun.rmi.server.Activation$ActivatorImpl.activate(Activation.java:409)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
        at sun.rmi.transport.Transport$1.run(Transport.java:200)
        at sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.rmi.ConnectException: Connection refused to host: SJohns-XPS7590.snafuHQ.local; nested exception is:
        java.net.ConnectException: Connection refused: connect
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:623)
        at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
        at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
        at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:132)
        at java.rmi.activation.ActivationGroup_Stub.newInstance(Unknown Source)
        at sun.rmi.server.Activation$ObjectEntry.activate(Activation.java:1494)
        at sun.rmi.server.Activation$GroupEntry.activate(Activation.java:1180)
        ... 18 more
Caused by: java.net.ConnectException: Connection refused: connect
        at java.net.DualStackPlainSocketImpl.connect0(Native Method)
        at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:607)
        at java.net.Socket.connect(Socket.java:556)
        at java.net.Socket.<init>(Socket.java:452)
        at java.net.Socket.<init>(Socket.java:229)
        at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
        at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
        at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:617)
        ... 24 more

LOCK DOWN POLICY FILE

// https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8229532
// https://stackoverflow.com/questions/57433655/classnotfoundexception-issued-by-urlclassloader-when-the-security-manager-is-ena

//grant {
    // Allow everything for now
    //permission java.security.AllPermission;
//};

grant codeBase "file:/C:/apps/snafu/foobar/*" {

    //
    // Allow everything for now
    //permission java.security.AllPermission;

    permission java.net.SocketPermission "127.0.0.1:*", "accept,connect,resolve";
    permission java.net.SocketPermission "localhost:6990", "listen,accept,connect,resolve";
    permission java.net.SocketPermission "localhost:6993", "listen,accept,connect,resolve";
    permission java.net.SocketPermission "SJohns-XPS7590.snafuHQ.local:*", "listen,accept,connect,resolve";
    permission java.net.SocketPermission "192.168.1.125:6993", "listen,accept,connect,resolve";

    permission java.util.PropertyPermission "user.dir", "read";
    permission java.util.PropertyPermission "user.home", "read";
    permission java.util.PropertyPermission "LicenseFilename", "read";
    permission java.util.PropertyPermission "HostId", "read";
    permission java.util.PropertyPermission "InstanceID", "read";
    permission java.util.PropertyPermission "slc.ps_loc", "write";
    permission java.util.PropertyPermission "org.owasp.esapi.SecurityConfiguration", "read";
    permission java.util.PropertyPermission "org.owasp.esapi.logSpecial.discard", "read";
    permission java.util.PropertyPermission "org.owasp.esapi.resources", "read";
    permission java.util.PropertyPermission "*", "read,write";
    permission java.util.PropertyPermission "org.owasp.esapi.opsteam", "read";

    permission java.util.logging.LoggingPermission "control";

    permission java.io.FilePermission ".", "read";
    permission java.io.FilePermission "C:/Apps/snafu/foobar/-", "read,write,delete";

    permission java.lang.management.ManagementPermission "monitor";

    permission java.lang.reflect.ReflectPermission "suppressAccessChecks";

    permission java.lang.RuntimePermission "setFactory";
    permission java.lang.RuntimePermission "getClassLoader";
    permission java.lang.RuntimePermission "setContextClassLoader";
    permission java.lang.RuntimePermission "getenv.*";
    permission java.lang.RuntimePermission "getProtectionDomain";
    permission java.lang.RuntimePermission "accessDeclaredMembers";
    permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect";
    permission java.lang.RuntimePermission "loadLibrary.sunec";
    permission java.lang.RuntimePermission "loadLibrary.sunmscapi";

    permission javax.management.MBeanTrustPermission "register";
    permission javax.management.MBeanServerPermission "createMBeanServer";
    permission javax.management.MBeanPermission "*", "queryNames";
    permission javax.management.MBeanPermission "*", "registerMBean,unregisterMBean";

    permission java.security.SecurityPermission "putProviderProperty.SunJCE";
};


问:
C extension as sub-module for existing python package
I'm trying to add a c extension as a submodule to an existing python package. I've tried following the documentation but most either are focused on a purely C extension package or it doesn't seem to work for me.

Here is what I'm trying to do:

```<code>main/
|--> main/
      |--> __init__.py
      |--> sub/
            |--> sub.c
            |--> __init__.py
      |--> setup.py
</code>```

Setup.py file has

```<code>from setuptools import setup
from setuptools.extension import Extension

extensions = [
    Extension(
    name="main.sub",
    sources=["main/sub/sub.c"])

]

setup(name='main',
      version='1.0',
      packages=['main'],
      ext_modules = extensions,
)
</code>```

sub.c has

```<code>#include <Python.h>

// This is the definition of a method
static PyObject *division(PyObject *self, PyObject *args)
{
    long dividend, divisor;
    if (!PyArg_ParseTuple(args, "ll", &dividend, &divisor))
    {
        return NULL;
    }
    if (0 == divisor)
    {
        PyErr_Format(PyExc_ZeroDivisionError, "Dividing %d by zero!", dividend);
        return NULL;
    }
    return PyLong_FromLong(dividend / divisor);
}

// Exported methods are collected in a table
PyMethodDef method_table[] = {
    {"division", (PyCFunction)division, METH_VARARGS, "Method docstring"},
    {NULL, NULL, 0, NULL} // Sentinel value ending the table
};

// A struct contains the definition of a module
PyModuleDef sub_module = {
    PyModuleDef_HEAD_INIT,
    "main.sub", // Module name
    "This is the module docstring",
    -1, // Optional size of the module state memory
    method_table,
    NULL, // Optional slot definitions
    NULL, // Optional traversal function
    NULL, // Optional clear function
    NULL  // Optional module deallocation function
};

// The module init function
PyMODINIT_FUNC PyInit_sub(void)
{
    return PyModule_Create(&sub_module);
}

</code>```

I want to be able to do:

```<code>import main
main.sub.division(4,2)
</code>```

but not matter what I do, I can't see division. It's driving me nuts... I've tried a bunch of different variations with no luck.

Body:
I'm trying to add a c extension as a submodule to an existing python package. I've tried following the documentation but most either are focused on a purely C extension package or it doesn't seem to work for me.

Here is what I'm trying to do:

main/
|--> main/
      |--> __init__.py
      |--> sub/
            |--> sub.c
            |--> __init__.py
      |--> setup.py

Setup.py file has

from setuptools import setup
from setuptools.extension import Extension

extensions = [
    Extension(
    name="main.sub",
    sources=["main/sub/sub.c"])

]

setup(name='main',
      version='1.0',
      packages=['main'],
      ext_modules = extensions,
)

sub.c has

#include <Python.h>

// This is the definition of a method
static PyObject *division(PyObject *self, PyObject *args)
{
    long dividend, divisor;
    if (!PyArg_ParseTuple(args, "ll", &dividend, &divisor))
    {
        return NULL;
    }
    if (0 == divisor)
    {
        PyErr_Format(PyExc_ZeroDivisionError, "Dividing %d by zero!", dividend);
        return NULL;
    }
    return PyLong_FromLong(dividend / divisor);
}

// Exported methods are collected in a table
PyMethodDef method_table[] = {
    {"division", (PyCFunction)division, METH_VARARGS, "Method docstring"},
    {NULL, NULL, 0, NULL} // Sentinel value ending the table
};

// A struct contains the definition of a module
PyModuleDef sub_module = {
    PyModuleDef_HEAD_INIT,
    "main.sub", // Module name
    "This is the module docstring",
    -1, // Optional size of the module state memory
    method_table,
    NULL, // Optional slot definitions
    NULL, // Optional traversal function
    NULL, // Optional clear function
    NULL  // Optional module deallocation function
};

// The module init function
PyMODINIT_FUNC PyInit_sub(void)
{
    return PyModule_Create(&sub_module);
}

I want to be able to do:

import main
main.sub.division(4,2)

but not matter what I do, I can't see division. It's driving me nuts... I've tried a bunch of different variations with no luck.


问:
react-big-scheduler Module Warning - Failed to parse source map - no such file or directory - node_modules\rrule\src\weekday.ts
I have installed react-big-scheduler package in my react app. Facing warnings like these:

WARNING in ./node_modules/rrule/dist/esm/weekday.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'path\node_modules\rrule\src\weekday.ts' file: Error: ENOENT: no such file
or directory, open 'path\node_modules\rrule\src\weekday.ts'

Is it possible to solve?


问:
Replacing Google OAuth API in Laravel
I have an app that I was tasked with to renew. However, the app runs a Google OAuth API to authenticate the users. However, this instance of the API no longer works as the company has changed name and thus the old mail domain no longer exists.

E.g: name@companyname.com

Is there a way for me to change the instance of the api so it will allow any gmail to get in.

here's my current controller for the oauth

```<code>public function checkUserByToken($social_token)
    {
        $client  = new \Google_Client(['client_id' => env('GOOGLE_CLIENT_ID', '')]);
        $payload = $client->verifyIdToken($social_token);
        if ($payload) {
            $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)oldcompany.com$/i',
            ]);
            if ($validator->fails()) {
                return false;
            }
            $user = User::where('email', $payload['email'])->first();
            if (!$user) {
                $data = [
                    'name'      => $payload['family_name'],
                    'full_name' => $payload['name'],
                    'email'     => $payload['email'],
                    'password'  => bcrypt(str_random(8)),
                ];
                $user = $this->createUser($data);
            }
            $user->forceFill([
                'email' => $payload['email'],
                'email_verified_at' => Carbon::now(),
            ])->save();
            $tokenResult = $user->createToken('Personal Access Client');
            $token = $tokenResult->token;
            $token->expires_at = Carbon::now()->addMonth();
            $token->save();
            $data = [
                    'access_token' => $tokenResult->accessToken,
                    'token_type'   => 'Bearer',
                    'expires_at'   => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString(),
                    'full_name'    => $payload['name'],
                    'avatar'       => $payload['picture'],
                    'role'         => $user->role,
                    'section'      => isset($user->section)?$user->section->name:"",
                    'id'           => $user->id
            ];
            return $data;
        } else {
            return false;
        }
    }
</code>```

I have tried replacing the google OAuth API in .env and change

```<code> $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)oldcompany.com$/i',
            ]);
</code>```

to

```<code> $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)newcompany.com$/i',
            ]);
</code>```

no avail as I think the google API outside of sending back auth token also send back something else but I'm not sure what it is.

Title: Replacing Google OAuth API in Laravel

Body:
I have an app that I was tasked with to renew. However, the app runs a Google OAuth API to authenticate the users. However, this instance of the API no longer works as the company has changed name and thus the old mail domain no longer exists.

E.g: name@companyname.com

Is there a way for me to change the instance of the api so it will allow any gmail to get in.

here's my current controller for the oauth

public function checkUserByToken($social_token)
    {
        $client  = new \Google_Client(['client_id' => env('GOOGLE_CLIENT_ID', '')]);
        $payload = $client->verifyIdToken($social_token);
        if ($payload) {
            $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)oldcompany.com$/i',
            ]);
            if ($validator->fails()) {
                return false;
            }
            $user = User::where('email', $payload['email'])->first();
            if (!$user) {
                $data = [
                    'name'      => $payload['family_name'],
                    'full_name' => $payload['name'],
                    'email'     => $payload['email'],
                    'password'  => bcrypt(str_random(8)),
                ];
                $user = $this->createUser($data);
            }
            $user->forceFill([
                'email' => $payload['email'],
                'email_verified_at' => Carbon::now(),
            ])->save();
            $tokenResult = $user->createToken('Personal Access Client');
            $token = $tokenResult->token;
            $token->expires_at = Carbon::now()->addMonth();
            $token->save();
            $data = [
                    'access_token' => $tokenResult->accessToken,
                    'token_type'   => 'Bearer',
                    'expires_at'   => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString(),
                    'full_name'    => $payload['name'],
                    'avatar'       => $payload['picture'],
                    'role'         => $user->role,
                    'section'      => isset($user->section)?$user->section->name:"",
                    'id'           => $user->id
            ];
            return $data;
        } else {
            return false;
        }
    }

I have tried replacing the google OAuth API in .env and change

 $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)oldcompany.com$/i',
            ]);

to

 $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)newcompany.com$/i',
            ]);

no avail as I think the google API outside of sending back auth token also send back something else but I'm not sure what it is.


问:
Change CSS in html table using JavaScript if/else
i want to add in advance that i have just started coding and this is my first project in html/php/js (Until now, I've only really worked with C#).
I am currently writing a code that displays a mssql table inside a php/html file (I connected to the DB using PHP and displayed the table using html).
Now I need the different elements to change backgrond color if they exceed certain values.
For this to work, I first have to change the data types into integers and then compare them inside an if/elsestatement (or so I believe).
I already have a reload function (using JavaScript) so they colors would need to change after the page has been reloaded.

I already have a reload function (using JavaScript) so the colors would need to change after the page has been reloaded.

I edited my code to be able to show it to you. Hope this clear most of the confusions.

This is the JS part:

```
</div>
</div>
</p>
<p>This is the CSS part:</p>
<pre class="lang-css prettyprint-override"><code><style>
    table {
      width: 100%;
      border-collapse: collapse;
      font-family: Arial, Helvetica, sans-serif;
    }

    table,
    th,
    td {
      border: 1px solid;
    }

    th {
      font-size: large;
    }

    h1 {
      font-family: Arial, Helvetica, sans-serif;
    }
  </style>
</code>```

And this is my html/php part:

<!doctype html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>test</title>

test

        var_1
        var_2
        var_3
        var_4

      <?php
          $serverName = "srvtest";
          $connectionInfo = array( "Database"=>"DB", "UID"=>"sa", "PWD"=>"***", "CharacterSet"=>"UTF-8");
          $conn = sqlsrv_connect( $serverName, $connectionInfo);

          if( !$conn )
          {
               echo "Connection could not be established.
";
               die( print_r( sqlsrv_errors(), true));
          }
          $sql = 'select * from view_test order by cast(Line as int) asc';
          $stmt = sqlsrv_query($conn, $sql);

          while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) )
          {
               echo "

               " .$row['var_1']. "
               " .$row['var_2']. "
               " .$row['var_3']. "
               " .$row['var_4']. "

";
          }
          ?>

```

Body:
i want to add in advance that i have just started coding and this is my first project in html/php/js (Until now, I've only really worked with C#).
I am currently writing a code that displays a mssql table inside a php/html file (I connected to the DB using PHP and displayed the table using html).
Now I need the different elements to change backgrond color if they exceed certain values.
For this to work, I first have to change the data types into integers and then compare them inside an if/elsestatement (or so I believe).
I already have a reload function (using JavaScript) so they colors would need to change after the page has been reloaded.

I already have a reload function (using JavaScript) so the colors would need to change after the page has been reloaded.

I edited my code to be able to show it to you. Hope this clear most of the confusions.

This is the JS part:

This is the CSS part:

And this is my html/php part:

<!doctype html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>test</title>

test

        var_1
        var_2
        var_3
        var_4

      <?php
          $serverName = "srvtest";
          $connectionInfo = array( "Database"=>"DB", "UID"=>"sa", "PWD"=>"***", "CharacterSet"=>"UTF-8");
          $conn = sqlsrv_connect( $serverName, $connectionInfo);

          if( !$conn )
          {
               echo "Connection could not be established.
";
               die( print_r( sqlsrv_errors(), true));
          }
          $sql = 'select * from view_test order by cast(Line as int) asc';
          $stmt = sqlsrv_query($conn, $sql);

          while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) )
          {
               echo "

               " .$row['var_1']. "
               " .$row['var_2']. "
               " .$row['var_3']. "
               " .$row['var_4']. "

";
          }
          ?>


问:
How to setup OMISE PHP SDK to Laravel framework
I'm starting to learn Omise Payment Getway. On Omise documentation have information about PHP SDK. I'm using Laravel Framework on it. However, i'm struggling to implement the Omise PHP SDK into my Laravel site..

I have 2 question when setup the Omise PHP SDK :

The integration - after i install Omise by composer. i don't know how to use it. first, i want to display my Omise balance. here is my code on controller

```<code>use Omise\OmiseBalance;

class OmiseController extends Controller
{
    public function index()
    {
        $balance = OmiseBalance::retrieve();
        dd($balance);
    }
}
</code>```

but display error

```<code>Class "Omise\OmiseBalance" not found
</code>```

i tried other way, but still not work..

Place the Secret and Public Key - where should i put the Secret key and Public Key on my Laravel. and how to fetch the keys?
Currently i just put this keys into my file .env

```<code>OMISE_PUBLIC_KEY=pkey_test_xxx
OMISE_SECRET_KEY=skey_test_xxx
OMISE_API_VERSION=2019-05-29
</code>```

What is the correct way for me to integrate Omise PHP SDK into my Laravel Site. please help.

Body:
I'm starting to learn Omise Payment Getway. On Omise documentation have information about PHP SDK. I'm using Laravel Framework on it. However, i'm struggling to implement the Omise PHP SDK into my Laravel site..

I have 2 question when setup the Omise PHP SDK :

The integration - after i install Omise by composer. i don't know how to use it. first, i want to display my Omise balance. here is my code on controller

use Omise\OmiseBalance;

class OmiseController extends Controller
{
    public function index()
    {
        $balance = OmiseBalance::retrieve();
        dd($balance);
    }
}

but display error

Class "Omise\OmiseBalance" not found

i tried other way, but still not work..

Place the Secret and Public Key - where should i put the Secret key and Public Key on my Laravel. and how to fetch the keys?
Currently i just put this keys into my file .env

OMISE_PUBLIC_KEY=pkey_test_xxx
OMISE_SECRET_KEY=skey_test_xxx
OMISE_API_VERSION=2019-05-29

What is the correct way for me to integrate Omise PHP SDK into my Laravel Site. please help.


问:
Getting GPS data from Twilio Photo
I'm building a app that allows users to text in there photos to a twilio phone number which stores the photo on an AWS server.

However it appears the end photo is modified both in resolution and redacted exif data.

Does anyone know is this something Twilio is doing and can hopefully be switched off or is this happening during transit somehow?

I've tested from multiple phone models / os's and the results always seem the same which makes me think it twilio.

Maybe there is a better way to extract GPS data from a texted photo???

Title: Getting GPS data from Twilio Photo


问:
how to set specific part of the image to white and remaining part to black in matlab
I am trying to learn image processing and I just found one question related to my area of interest. I have an image in which there is two things one is mug and the other is thermos. I just want to show the cup in white color for that first i convert the image in graysacle and then I convert with imbinarize. This is my problem statement

Example 1

The original image on the left is given i.e., original.jpg. The middle image (theft 1) shows that mug is stolen from the original image. Now you have to generate the output in such a way that the stolen object i.e., the mug is visible only. The rightmost image shows the stolen object i.e., mug, that is the required output to be generate by your code.

This is an image the kind of output I want

This is my code for that

```<code>close all
I = imread('Original-min-min.JPG');
gray = rgb2gray(I)
BW = imbinarize(gray);
% Display the original image next to the binary version.
 figure
 imshowpair(gray,BW,'montage')

     [r,c] = size(BW);
     for i=1:r
         for j=1:c
             f=BW(i,j);
             if f>127 && f<256
                 BW(i,j)=255;
             end
         end
     end
     figure
     imshow(BW)
</code>```

This is the output of my codeenter image description here
how to set black everything except cup i want the output like  i upload the picture before

Body:
I am trying to learn image processing and I just found one question related to my area of interest. I have an image in which there is two things one is mug and the other is thermos. I just want to show the cup in white color for that first i convert the image in graysacle and then I convert with imbinarize. This is my problem statement

Example 1

The original image on the left is given i.e., original.jpg. The middle image (theft 1) shows that mug is stolen from the original image. Now you have to generate the output in such a way that the stolen object i.e., the mug is visible only. The rightmost image shows the stolen object i.e., mug, that is the required output to be generate by your code.

This is an image the kind of output I want

This is my code for that

close all
I = imread('Original-min-min.JPG');
gray = rgb2gray(I)
BW = imbinarize(gray);
% Display the original image next to the binary version.
 figure
 imshowpair(gray,BW,'montage')

     [r,c] = size(BW);
     for i=1:r
         for j=1:c
             f=BW(i,j);
             if f>127 && f<256
                 BW(i,j)=255;
             end
         end
     end
     figure
     imshow(BW)

This is the output of my codeenter image description here
how to set black everything except cup i want the output like  i upload the picture before


Title: Is there a program for 2D circular convolution in python

Body:
I am wondering is there a program defined for 2D circular convolution?
If not, I am looking for how to perform it.
I did search for it. Could not find anything. So I am wondering does anybody know it.
Here is a sample 2D data I have taken

a= np.array([[ -3-3j, 0-10j,  +3-3j, +3-3j],
                   [-10+0j, 0+ 0j, +10+0j, 0-10.8j],
                   [ -3+3j, 0+10j,  +3+3j, 0-10.7j],
                   [-10+0j, 0+ 0j, +2+0.2j, -1+0j]]);
b = np.array([[ -3-3.2j, 0-10.8j,  +3-3j, +3.2+4j],
                   [-10+0j, 0+ 0j, +2+0.2j, -1+0j],
                   [ -3+3j, 0+10j,  +3+4j, 0+ 0j],
                   [ -3-3j, 0-10j,  +3-3j, +3-3j]]);

I tried c = scipy.signal.convolve2d(a, b, boundary='wrap').
It's output is

[[ 166.96 -60.j    -66.4   -8.1j  -393.4  -37.6j  -158.9  -30.1j
   166.96 -60.j    -66.4   -8.1j  -393.4  -37.6j ]
 [ -25.84 +35.2j    46.1  +77.1j   -23.9  -76.86j  -62.66 -35.5j
   -25.84 +35.2j    46.1  +77.1j   -23.9  -76.86j]
 [ 106.64+102.2j   106.66 +70.9j    96.    -2.64j   61.56+166.3j
   106.64+102.2j   106.66 +70.9j    96.    -2.64j]
 [ 180.   -46.j    -15.06-113.16j -271.16 -22.9j   -89.44+138.j
   180.   -46.j    -15.06-113.16j -271.16 -22.9j ]
 [ 166.96 -60.j    -66.4   -8.1j  -393.4  -37.6j  -158.9  -30.1j
   166.96 -60.j    -66.4   -8.1j  -393.4  -37.6j ]
 [ -25.84 +35.2j    46.1  +77.1j   -23.9  -76.86j  -62.66 -35.5j
   -25.84 +35.2j    46.1  +77.1j   -23.9  -76.86j]
 [ 106.64+102.2j   106.66 +70.9j    96.    -2.64j   61.56+166.3j
   106.64+102.2j   106.66 +70.9j    96.    -2.64j]]

It is giving correct result. But this correct result is only a subset of the  above output. i.e. I have extract the first few rows and columns of size as much as the input size. So this way I got the correct output.

[[ 166.96 -60.j    -66.4   -8.1j  -393.4  -37.6j  -158.9  -30.1j ]
 [ -25.84 +35.2j    46.1  +77.1j   -23.9  -76.86j  -62.66 -35.5j ]
 [ 106.64+102.2j   106.66 +70.9j    96.    -2.64j   61.56+166.3j ]
 [ 180.   -46.j    -15.06-113.16j -271.16 -22.9j   -89.44+138.j  ]]

I tried spicy.fft.fftshift with using mode='same' in spicy.fft.convolve2D but it is not giving correct output.

I am looking for either a built in function or normal code


问:
PageInit does not work when on different class
As the title says I am using PageFactory to initialize my elements.

When I use PageFactory.initElements on the page I want to use my elements everything is fine and works correctly, but when I try to create a new class with PageFactory to have it initialize all elements there I get a null pointer exception.

Below you will find the code I am using:

Actions.java

```<code>TestIds testIds = new TestIds();
public void initElements(WebDriver driver) {
        PageFactory.initElements(driver, cashierIds);
    }
</code>```

The above lines work when included in my Actions class but when I create a new Class called ElementInitialization.java, move everything in it and then call it my elements throw nullPointerException.

Is there a different way to call the specific faction to work everywhere?

Body:
As the title says I am using PageFactory to initialize my elements.

When I use PageFactory.initElements on the page I want to use my elements everything is fine and works correctly, but when I try to create a new class with PageFactory to have it initialize all elements there I get a null pointer exception.

Below you will find the code I am using:

Actions.java

TestIds testIds = new TestIds();
public void initElements(WebDriver driver) {
        PageFactory.initElements(driver, cashierIds);
    }

The above lines work when included in my Actions class but when I create a new Class called ElementInitialization.java, move everything in it and then call it my elements throw nullPointerException.

Is there a different way to call the specific faction to work everywhere?


问:
OkHttpClient: <-- HTTP FAILED: java.io.IOException: unexpected end of stream on
In my app when i am opening any of module twice or thrice this problem occurs and automatically after couple of minutes it starts working !! every time for the first time if i am using an app it works all api works perfect but after clicking it twice or thrice this error appears in my logCat!

I/m.medgini.vone: Background concurrent copying GC freed 187892(6362KB) AllocSpace objects, 0(0B) LOS objects, 44% free, 7812KB/13MB, paused 348us total 187.563ms
I/okhttp.OkHttpClient: <-- HTTP FAILED: java.io.IOException: unexpected end of stream on https://voney.in/...
I/okhttp.OkHttpClient: <-- HTTP FAILED: java.io.IOException: unexpected end of stream on https://voney.in/...
I/okhttp.OkHttpClient: <-- HTTP FAILED: java.io.IOException: unexpected end of stream on https://voney.in/...
V/FA: Inactivity, disconnecting from the service

private RetrofitClient() {

```<code>// Create a new object from HttpLoggingInterceptor
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(20L, TimeUnit.SECONDS)
        .readTimeout(20L, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .protocols(Collections.singletonList(Protocol.HTTP_1_1))
        .addInterceptor(interceptor).build();

//creating Retrofit client singleton object
retrofit = new Retrofit.Builder()
        .baseUrl(base_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
</code>```

}

I am using retrofit as well as volley also, some modules of this app is on volley and maximum of are on retrofit!
Please help me! why is this happening and automatically starts working! what is the main cause for this!

I tried to add okHttp's protocols in it but still it didn't work.

Body:
In my app when i am opening any of module twice or thrice this problem occurs and automatically after couple of minutes it starts working !! every time for the first time if i am using an app it works all api works perfect but after clicking it twice or thrice this error appears in my logCat!

I/m.medgini.vone: Background concurrent copying GC freed 187892(6362KB) AllocSpace objects, 0(0B) LOS objects, 44% free, 7812KB/13MB, paused 348us total 187.563ms
I/okhttp.OkHttpClient: <-- HTTP FAILED: java.io.IOException: unexpected end of stream on https://voney.in/...
I/okhttp.OkHttpClient: <-- HTTP FAILED: java.io.IOException: unexpected end of stream on https://voney.in/...
I/okhttp.OkHttpClient: <-- HTTP FAILED: java.io.IOException: unexpected end of stream on https://voney.in/...
V/FA: Inactivity, disconnecting from the service

private RetrofitClient() {

// Create a new object from HttpLoggingInterceptor
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(20L, TimeUnit.SECONDS)
        .readTimeout(20L, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .protocols(Collections.singletonList(Protocol.HTTP_1_1))
        .addInterceptor(interceptor).build();

//creating Retrofit client singleton object
retrofit = new Retrofit.Builder()
        .baseUrl(base_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

}

I am using retrofit as well as volley also, some modules of this app is on volley and maximum of are on retrofit!
Please help me! why is this happening and automatically starts working! what is the main cause for this!

I tried to add okHttp's protocols in it but still it didn't work.


问:
Invoking TaskbarItemInfo in C#, to avoid using .NET 4.0
I would like to know if it is possible to change the ProgressValue and ProgressState of an application using P/Invoke, so that I do not have to change my .NET 3.5 to .NET 4.0. Thanks ahead of time.</p>

ContentLicense: CC BY-SA 3.0


问:
Cant use functions from wingdi.h
I'm trying to draw an image to a Win32 Window, but as soon as I try to use BitBlt() or any other function from <wingdi.h>, I get an error. This is the code where I use these functions:

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

void MainWindow::UpdatePieces() {
    PAINTSTRUCT ps;
    HDC hdc;
    BITMAP bitmap;
    HDC hdcMem;
    HGDIOBJ oldBitmap;

    hdc = BeginPaint(m_hwnd, &ps);
    hdcMem = CreateCompatibleDC(hdc);
    oldBitmap = SelectObject(hdcMem, WhiteKing);
    GetObject(WhiteKing, sizeof(bitmap), &bitmap);
    BitBlt(hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcMem, 0, 0, SRCCOPY);
    SelectObject(hdcMem, oldBitmap);
    DeleteDC(hdcMem);
    EndPaint(m_hwnd, &ps);
}
...
</code>```

This is the error I get:

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol __imp_CreateCompatibleDC referenced in function "private: void __cdecl MainWindow::UpdatePieces(void)" (?UpdatePieces@MainWindow@@AEAAXXZ)   C++Learn    C:\Users\lives\source\repos\C++Learn\C++Learn\main.obj  1
Error   LNK2019 unresolved external symbol __imp_DeleteDC referenced in function "private: void __cdecl MainWindow::UpdatePieces(void)" (?UpdatePieces@MainWindow@@AEAAXXZ) C++Learn    C:\Users\lives\source\repos\C++Learn\C++Learn\main.obj  1
Error   LNK2019 unresolved external symbol __imp_SelectObject referenced in function "private: void __cdecl MainWindow::UpdatePieces(void)" (?UpdatePieces@MainWindow@@AEAAXXZ) C++Learn    C:\Users\lives\source\repos\C++Learn\C++Learn\main.obj  1
Error   LNK2019 unresolved external symbol __imp_GetObjectW referenced in function "private: void __cdecl MainWindow::UpdatePieces(void)" (?UpdatePieces@MainWindow@@AEAAXXZ)   C++Learn    C:\Users\lives\source\repos\C++Learn\C++Learn\main.obj  1
```

Title: Cant use functions from wingdi.h

Body:
I'm trying to draw an image to a Win32 Window, but as soon as I try to use BitBlt() or any other function from <wingdi.h>, I get an error. This is the code where I use these functions:

#include <windows.h>
...

void MainWindow::UpdatePieces() {
    PAINTSTRUCT ps;
    HDC hdc;
    BITMAP bitmap;
    HDC hdcMem;
    HGDIOBJ oldBitmap;

    hdc = BeginPaint(m_hwnd, &ps);
    hdcMem = CreateCompatibleDC(hdc);
    oldBitmap = SelectObject(hdcMem, WhiteKing);
    GetObject(WhiteKing, sizeof(bitmap), &bitmap);
    BitBlt(hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcMem, 0, 0, SRCCOPY);
    SelectObject(hdcMem, oldBitmap);
    DeleteDC(hdcMem);
    EndPaint(m_hwnd, &ps);
}
...

This is the error I get:

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol __imp_CreateCompatibleDC referenced in function "private: void __cdecl MainWindow::UpdatePieces(void)" (?UpdatePieces@MainWindow@@AEAAXXZ)   C++Learn    C:\Users\lives\source\repos\C++Learn\C++Learn\main.obj  1
Error   LNK2019 unresolved external symbol __imp_DeleteDC referenced in function "private: void __cdecl MainWindow::UpdatePieces(void)" (?UpdatePieces@MainWindow@@AEAAXXZ) C++Learn    C:\Users\lives\source\repos\C++Learn\C++Learn\main.obj  1
Error   LNK2019 unresolved external symbol __imp_SelectObject referenced in function "private: void __cdecl MainWindow::UpdatePieces(void)" (?UpdatePieces@MainWindow@@AEAAXXZ) C++Learn    C:\Users\lives\source\repos\C++Learn\C++Learn\main.obj  1
Error   LNK2019 unresolved external symbol __imp_GetObjectW referenced in function "private: void __cdecl MainWindow::UpdatePieces(void)" (?UpdatePieces@MainWindow@@AEAAXXZ)   C++Learn    C:\Users\lives\source\repos\C++Learn\C++Learn\main.obj  1


问:
Performance impact of Spring Sleuth
I read somewhere that Spring Sleuth has performance impact. Whatever I read over internet are old posts.

Does anyone know whether with new version of Spring Boot this issue is resolved or it is still there.

Title: Performance impact of Spring Sleuth


问:
Anyone help me to get thus <x-jet-welcome /> file, i start learning jetstream using livewire
#Anyone help me to get  file, i start learning jetstream using livewire</p>
```<code>    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
                <x-jet-welcome />
            </div>
        </div>
    </div>
</code>```

Body:
#Anyone help me to get  file, i start learning jetstream using livewire

                <x-jet-welcome />


问:
How to fix this MongoServerError: bad auth : Authentication failed
I am new to backend development. I took a project from GitHub and tried to run it, but when I am doing node index.js I am facing this error MongoServerError: bad auth : Authentication failed.How can i fix it? I tried to do mongodb://localhost:27017/server in DB_CREDENTIAL but the error is not fixed yet. Can anyone tell me how to fix that? How to fix this error in my case?

Code of db connect file:

```<code>const mongoose = require('mongoose');

async function initializeDBConnection(){

const mySecret = process.env['DB_CREDENTIAL']

    try{
        const uri = `mongodb+srv://${mySecret}@cluster0.iha7u.mongodb.net/social-media?retryWrites=true&w=majority`;

        await mongoose.connect(uri, {
                useNewUrlParser: true,
            useUnifiedTopology: true
        })
        console.log("Connection Completed!");
    }catch(error){
        console.log(error);
    }
}

module.exports = { initializeDBConnection };
</code>```

Body:
I am new to backend development. I took a project from GitHub and tried to run it, but when I am doing node index.js I am facing this error MongoServerError: bad auth : Authentication failed.How can i fix it? I tried to do mongodb://localhost:27017/server in DB_CREDENTIAL but the error is not fixed yet. Can anyone tell me how to fix that? How to fix this error in my case?

Code of db connect file:

const mongoose = require('mongoose');

async function initializeDBConnection(){

const mySecret = process.env['DB_CREDENTIAL']

    try{
        const uri = `mongodb+srv://${mySecret}@cluster0.iha7u.mongodb.net/social-media?retryWrites=true&w=majority`;

        await mongoose.connect(uri, {
                useNewUrlParser: true,
            useUnifiedTopology: true
        })
        console.log("Connection Completed!");
    }catch(error){
        console.log(error);
    }
}

module.exports = { initializeDBConnection };


问:
SMS not delivered to India number with hindi text using AWS SNS but its working in English text properly
I have integrated the AWS SNS for sending SMS. English text SMS messages are working fine, but when we try to send the Hindi text SMS then it is not working properly. The first time it worked but the second time it was not received. There is no error message in the AWS log. AWS also generated a successful response with MessageId.

```<code>    const sendSMS = async(template, phone) => {
        var credentials = {
            accessKeyId: awsconfig.main.accessKeyId,
            secretAccessKey : awsconfig.main.secretAccessKey
        };

        AWS.config.update({credentials: credentials, region: 'ap-south-1'});

        var SNS = new AWS.SNS({apiVersion: '2010-03-31'});
        const params = { "Message": template, "PhoneNumber": phone };
        return await SNS.publish(params).promise();
    }
</code>```

I have checked with apiVersion: 2010-03-31 or without apiVersion.

Body:
I have integrated the AWS SNS for sending SMS. English text SMS messages are working fine, but when we try to send the Hindi text SMS then it is not working properly. The first time it worked but the second time it was not received. There is no error message in the AWS log. AWS also generated a successful response with MessageId.

    const sendSMS = async(template, phone) => {
        var credentials = {
            accessKeyId: awsconfig.main.accessKeyId,
            secretAccessKey : awsconfig.main.secretAccessKey
        };

        AWS.config.update({credentials: credentials, region: 'ap-south-1'});

        var SNS = new AWS.SNS({apiVersion: '2010-03-31'});
        const params = { "Message": template, "PhoneNumber": phone };
        return await SNS.publish(params).promise();
    }

I have checked with apiVersion: 2010-03-31 or without apiVersion.


问:
Sorting a query in Appsync graphql
I'm trying to sort the query results based on created date

I followed the amplify api example:
https://docs.amplify.aws/guides/api-graphql/query-with-sorting/q/platform/js/

I have a message model

```<code>type Todo @model {
    id: ID!
    name: String!
    user_id: String!
    recipient_id: String!
    description: String
    createdAt: AWSDateTime!
    updatedAt: AWSDateTime!
    time: String!
    type: String!
        @index(name: "todosByDate",queryField: "todosByDate",sortKeyFields: ["createdAt"])
}
</code>```

I'm using the type parameter to group the items i want sorted.
But the docs says that I can use a query called "todosByDate" which isn't automatically created when the @index is attached to the type field. So I created a query with the exact structure:

```<code>type Query {
    todosByDate(type: String!, sortDirection: ModelSortDirection): ModelTodoConnection
}
</code>```

But when using the query, it always returns null. Even when I populate the table with items containing the same type field and type name. What am I doing wrong?

```<code>type Query {
    todosByDate(type: String!, sortDirection: ModelSortDirection): ModelTodoConnection
}
</code>```

@index(name: "todosByDate",queryField: "todosByDate",sortKeyFields: ["createdAt"])

expected to receive a query result of items arranged in order of created date. Using a normal query to list the items in the table works fine. What's wrong here?

Title: Sorting a query in Appsync graphql

Body:
I'm trying to sort the query results based on created date

I followed the amplify api example:
https://docs.amplify.aws/guides/api-graphql/query-with-sorting/q/platform/js/

I have a message model

type Todo @model {
    id: ID!
    name: String!
    user_id: String!
    recipient_id: String!
    description: String
    createdAt: AWSDateTime!
    updatedAt: AWSDateTime!
    time: String!
    type: String!
        @index(name: "todosByDate",queryField: "todosByDate",sortKeyFields: ["createdAt"])
}

I'm using the type parameter to group the items i want sorted.
But the docs says that I can use a query called "todosByDate" which isn't automatically created when the @index is attached to the type field. So I created a query with the exact structure:

type Query {
    todosByDate(type: String!, sortDirection: ModelSortDirection): ModelTodoConnection
}

But when using the query, it always returns null. Even when I populate the table with items containing the same type field and type name. What am I doing wrong?

type Query {
    todosByDate(type: String!, sortDirection: ModelSortDirection): ModelTodoConnection
}

@index(name: "todosByDate",queryField: "todosByDate",sortKeyFields: ["createdAt"])

expected to receive a query result of items arranged in order of created date. Using a normal query to list the items in the table works fine. What's wrong here?


问:
Is there a fee to redirect to Google or Yandex Map in the application?
I am writing a map based application in Flutter. I integrated OpenStreetMap into the application. I want to redirect to maps like Google or Yandex for directions section in my app. Do I have to pay any fees for the referral or is there no fee for the referral?

Can you inform about this?


问:
I am working with stream signup is working with status 200 but did not create user in stream
const handleSubmit = async (e) => {
e.preventDefault();</p>
```<code>    const { username, password, phoneNumber, avatarURL } = form;

    const URL = 'http://localhost:5000/auth';

     const { data: { token, userId, hashedPassword, fullName } } = await axios.post(`${URL}/${isSignup ? 'signup' : 'login'}`, {
        username, password, fullName: form.fu
     llName, phoneNumber, avatarURL,
     });
</code>```

Body:
const handleSubmit = async (e) => {
e.preventDefault();

    const { username, password, phoneNumber, avatarURL } = form;

    const URL = 'http://localhost:5000/auth';

     const { data: { token, userId, hashedPassword, fullName } } = await axios.post(`${URL}/${isSignup ? 'signup' : 'login'}`, {
        username, password, fullName: form.fu
     llName, phoneNumber, avatarURL,
     });


问:
Can't update global variable inside of run consumer's function kafka js
I have global variable result_crnt. I try to update it inside of consumerRun function:

```<code>global.result_crnt = '';

async function consumerRun(){
    try{
        await consumer.run({
            eachMessage: async({ topic, partition, message }) => {
                console.log({
                    topic: topic,
                    partition: partition,
                    message: message.value.toString(),
                })

                result_crnt = message.value.toString();

            }

        })

    }catch (error){
        console.log('ERROR: ', error);
    }
}
</code>```

When I try to send a response using this variable (result_crnt):

```<code>api.get("/test/req", async function(req, res){

    consumerRun();
    while(true){
        if (result_crnt != '') break;
    }
    res.status(200).json({"result_crnt": result_crnt});

})
</code>```

But it stuck inside while block, and result_crnt doesn't seem to update, even though I get the message inside run (I can see output in console). What am I doing wrong? How can I fix it?

Body:
I have global variable result_crnt. I try to update it inside of consumerRun function:

global.result_crnt = '';

async function consumerRun(){
    try{
        await consumer.run({
            eachMessage: async({ topic, partition, message }) => {
                console.log({
                    topic: topic,
                    partition: partition,
                    message: message.value.toString(),
                })

                result_crnt = message.value.toString();

            }

        })

    }catch (error){
        console.log('ERROR: ', error);
    }
}

When I try to send a response using this variable (result_crnt):

api.get("/test/req", async function(req, res){

    consumerRun();
    while(true){
        if (result_crnt != '') break;
    }
    res.status(200).json({"result_crnt": result_crnt});

})

But it stuck inside while block, and result_crnt doesn't seem to update, even though I get the message inside run (I can see output in console). What am I doing wrong? How can I fix it?


问:
Windows Filtering Platform Veto
I am learning Windows Filtering Platform in kernel mode. Could anyone give me an example of Veto in WFP? I know the below code is Hard Block, but I can't imagine what Veto looks like.

```<code> classifyOut->actionType = FWP_ACTION_BLOCK;
 classifyOut->rights &= ~FWPS_RIGHT_ACTION_WRITE;
</code>```

MSDN link for this: Filter Arbitration

Title: Windows Filtering Platform Veto

Body:
I am learning Windows Filtering Platform in kernel mode. Could anyone give me an example of Veto in WFP? I know the below code is Hard Block, but I can't imagine what Veto looks like.

 classifyOut->actionType = FWP_ACTION_BLOCK;
 classifyOut->rights &= ~FWPS_RIGHT_ACTION_WRITE;

MSDN link for this: Filter Arbitration


问:
Android: retrofit file corrupted
I cannot open the pdf file I downloaded from the internet on my android device.
It gives the error that the file is corrupt. (corrupt file opens in pc)

```<code>//Request;
@GET("url")
suspend fun getDocumentDownload(@Path("File") file: String?): Response<ResponseBody>
</code>```

```<code>//writeResponseBodyToDisk
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
val byteArray = ByteArray(4096)
val fileSize = body.contentLength()
var fileSizeDownloaded: Long = 0
inputStream = body.byteStream()
outputStream = FileOutputStream(file)
while (true) {
    val read = inputStream.read(byteArray)
    if (read == -1) {
        break
    }
    outputStream.write(byteArray, 0, read)
    fileSizeDownloaded += read.toLong()
}
outputStream.flush()
</code>```

Response corrupt;

Response success;

Title: Android: retrofit file corrupted

Body:
I cannot open the pdf file I downloaded from the internet on my android device.
It gives the error that the file is corrupt. (corrupt file opens in pc)

//Request;
@GET("url")
suspend fun getDocumentDownload(@Path("File") file: String?): Response<ResponseBody>

//writeResponseBodyToDisk
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
val byteArray = ByteArray(4096)
val fileSize = body.contentLength()
var fileSizeDownloaded: Long = 0
inputStream = body.byteStream()
outputStream = FileOutputStream(file)
while (true) {
    val read = inputStream.read(byteArray)
    if (read == -1) {
        break
    }
    outputStream.write(byteArray, 0, read)
    fileSizeDownloaded += read.toLong()
}
outputStream.flush()

Response corrupt;

Response success;


问:
User is returning null even after modifying it with context API
I am making an API call using Axios and after that I am send those details to context API but I am getting null. I am using formik to send data to backend and on submit of that form I make an api call using axios then get the user from backend end pass it on to context API.

UserContext

```<code>import { createContext, useReducer } from "react";
import UserReducer from "./UserReducer";

const INITIAL_STATE = {
  user: null,
};

export const UserContext = createContext(INITIAL_STATE);

export const UserContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(UserReducer, INITIAL_STATE);

  const setUser = (userDetails) => {
    dispatch({
      type: "GET_USER",
      payload: userDetails,
    });

    // Here it is returning the user data but INITIAL_STATE.user is null
  };

  return (
    <UserContext.Provider
      value={{
        user: state.user,
        setUser,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};
</code>```

UserReducer

```<code>    const UserReducer = (state, action) => {
      switch (action.type) {
        case "GET_USER":
          return {
            user: action.payload,
          };

        default:
          return state;
      }
    };

    export default UserReducer;
</code>```

Login

```<code>const { user, setUser } = useContext(UserContext);
  const formik = useFormik({
    initialValues: {
      email: "",
      password: "",
    },
    onSubmit: () => {
      const getUser = async () => {
        const userData = await Axios.post("http://localhost:3001/login", {
          email: formik.values.email,
          password: formik.values.password,
        });

        setUser(userData.data); // Here I am sending the data to context API
      };
      getUser();
    },
    validationSchema,
  });
</code>```

Body:
I am making an API call using Axios and after that I am send those details to context API but I am getting null. I am using formik to send data to backend and on submit of that form I make an api call using axios then get the user from backend end pass it on to context API.

UserContext

import { createContext, useReducer } from "react";
import UserReducer from "./UserReducer";

const INITIAL_STATE = {
  user: null,
};

export const UserContext = createContext(INITIAL_STATE);

export const UserContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(UserReducer, INITIAL_STATE);

  const setUser = (userDetails) => {
    dispatch({
      type: "GET_USER",
      payload: userDetails,
    });

    // Here it is returning the user data but INITIAL_STATE.user is null
  };

  return (
    <UserContext.Provider
      value={{
        user: state.user,
        setUser,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};

UserReducer

    const UserReducer = (state, action) => {
      switch (action.type) {
        case "GET_USER":
          return {
            user: action.payload,
          };

        default:
          return state;
      }
    };

    export default UserReducer;

Login

const { user, setUser } = useContext(UserContext);
  const formik = useFormik({
    initialValues: {
      email: "",
      password: "",
    },
    onSubmit: () => {
      const getUser = async () => {
        const userData = await Axios.post("http://localhost:3001/login", {
          email: formik.values.email,
          password: formik.values.password,
        });

        setUser(userData.data); // Here I am sending the data to context API
      };
      getUser();
    },
    validationSchema,
  });


问:
I want to found not received orders count after last received orde in POWER BI
I want to found count of each product not received orders after last received order date. Here is formulas and data: *sorry i couldnt write code here so i upload photos.

enter image description here

enter image description here


问:
dlv debug error: could not launch process: fork/exec ./demo function not implemented
I encounter error when I launched a dlv debug process in docker with Goland IDE. Could anyone give me some help or has encountered this same issue?

```<code>root@d91e9c7df361:/workdir/demo# dlv --listen=:40000 --headless=true --api-version=2 --accept-multiclient exec ./bin/demo -- s

API server listening at: [::]:40000

2022-12-09T07:27:18Z warning layer=rpc Listening for remote connections (connections are not authenticated nor encrypted)

could not launch process: fork/exec /workdir/demo/bin/demo: function not implemented
</code>```

Go version: go version go1.18.3 linux/amd64

dlv version:
Delve Debugger
Version: 1.20.0
Build: $Id: 8ec46ee3d275c276b8e7465d69a23399e0e14789 $

build command:

```<code>go build -gcflags="all=-N -l" -o bin/demo ./demo.go
</code>```

Goland version: GoLand 2022.3

reinstall the dlv in go docker container

rebuild go code

only exec exec ./bin/demo -- s working

Body:
I encounter error when I launched a dlv debug process in docker with Goland IDE. Could anyone give me some help or has encountered this same issue?

root@d91e9c7df361:/workdir/demo# dlv --listen=:40000 --headless=true --api-version=2 --accept-multiclient exec ./bin/demo -- s

API server listening at: [::]:40000

2022-12-09T07:27:18Z warning layer=rpc Listening for remote connections (connections are not authenticated nor encrypted)

could not launch process: fork/exec /workdir/demo/bin/demo: function not implemented

Go version: go version go1.18.3 linux/amd64

dlv version:
Delve Debugger
Version: 1.20.0
Build: $Id: 8ec46ee3d275c276b8e7465d69a23399e0e14789 $

build command:

go build -gcflags="all=-N -l" -o bin/demo ./demo.go

Goland version: GoLand 2022.3

reinstall the dlv in go docker container

rebuild go code

only exec exec ./bin/demo -- s working


问:
Helm chart with json value
I'm trying to pass a JSON array into a Helm Chart. The chart's source code is here.

I'm passing the value like this:

helm upgrade  --install ingress-nginx ingress-nginx/ingress-nginx  \
   --repo https://kubernetes.github.io/ingress-nginx \
   --set controller.configAnnotations='{"mykey":"myval"}'
```
<p>I've tried various forms of escaping the <code>"</code> and the curly brackets as recommended in several other SO answers but I have not been able to find the combination which makes it work. My shell is Bash.</p>
<p>I always end up with this error:</p>
<pre class="lang-none prettyprint-override"><code>coalesce.go:220: warning: cannot overwrite table with non table
for ingress-nginx.controller.configAnnotations (map[])

Error: UPGRADE FAILED: YAML parse error on ingress-nginx/templates/controller-configmap.yaml:
error unmarshaling JSON: while decoding JSON: json:
cannot unmarshal string into Go struct field .metadata.annotations of type map[string]string
</code>```

Note that I'm using the Helm Chart for Kubernetes NGINX Controller from the Kubernetes project, not the equivalent from NGINX Inc. Not that I think it makes any difference to the question.

Title: Helm chart with json value

Body:
I'm trying to pass a JSON array into a Helm Chart. The chart's source code is here.

I'm passing the value like this:

helm upgrade  --install ingress-nginx ingress-nginx/ingress-nginx  \
   --repo https://kubernetes.github.io/ingress-nginx \
   --set controller.configAnnotations='{"mykey":"myval"}'

I've tried various forms of escaping the " and the curly brackets as recommended in several other SO answers but I have not been able to find the combination which makes it work. My shell is Bash.

I always end up with this error:

coalesce.go:220: warning: cannot overwrite table with non table
for ingress-nginx.controller.configAnnotations (map[])

Error: UPGRADE FAILED: YAML parse error on ingress-nginx/templates/controller-configmap.yaml:
error unmarshaling JSON: while decoding JSON: json:
cannot unmarshal string into Go struct field .metadata.annotations of type map[string]string

Note that I'm using the Helm Chart for Kubernetes NGINX Controller from the Kubernetes project, not the equivalent from NGINX Inc. Not that I think it makes any difference to the question.