问:
How to resolve LifeCycleException while starting tomcat
I am facing following error while starting the project.

It is not first time to start this project with tomcat.
It was working fine but suddenly it is generating following errors.

I am also trying to solve it. Please help me out.

I am attaching the error messages I am facing. Thanks

```<code>java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:188)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1122)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:819)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.NoClassDefFoundError: org/mozilla/javascript/ScriptableObject
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2959)
    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1212)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1692)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1573)
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2499)
    at java.lang.Class.getDeclaredFields(Class.java:1811)
    at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
    at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:270)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:139)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:65)
    at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:415)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:892)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:386)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5419)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.lang.ClassNotFoundException: org.mozilla.javascript.ScriptableObject
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1722)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1573)
    ... 27 more

12월 16, 2022 1:49:26 오후 org.apache.catalina.core.ContainerBase startInternal
심각: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:188)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1122)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1130)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:819)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

12월 16, 2022 1:49:26 오후 org.apache.catalina.startup.Catalina start
심각: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[9045]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1130)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more
</code>```

adding another tomcat server in eclipse,

check server.xml

check web.xml

clean tomcat work directory
clean project
clean server

Body:
I am facing following error while starting the project.

It is not first time to start this project with tomcat.
It was working fine but suddenly it is generating following errors.

I am also trying to solve it. Please help me out.

I am attaching the error messages I am facing. Thanks

java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:188)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1122)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:819)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.NoClassDefFoundError: org/mozilla/javascript/ScriptableObject
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2959)
    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1212)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1692)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1573)
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2499)
    at java.lang.Class.getDeclaredFields(Class.java:1811)
    at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
    at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:270)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:139)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:65)
    at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:415)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:892)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:386)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5419)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.lang.ClassNotFoundException: org.mozilla.javascript.ScriptableObject
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1722)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1573)
    ... 27 more

12월 16, 2022 1:49:26 오후 org.apache.catalina.core.ContainerBase startInternal
심각: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:188)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1122)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1130)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:819)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

12월 16, 2022 1:49:26 오후 org.apache.catalina.startup.Catalina start
심각: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[9045]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1130)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more

adding another tomcat server in eclipse,

check server.xml

check web.xml

clean tomcat work directory
clean project
clean server


来源: stackexchange

问:
split character string in cell with sql databricks
I have the following input:

order_id
item_order_detail

17889
{"itemID":"1123","itemName":"banh baom1"},{"itemID":"1124","itemName":"khan tam"},{"itemID":"1125","itemName":"nuoc giat"},{"itemID":"1127","itemName":"sua tam da"},{"itemID":"1110","itemName":"phao khong9"},{"itemID":"1121","itemName":"het lam sao"},{"itemID":"1134","itemName":"trai ban"},{"itemID":"1141","itemName":"tim ban"},{"itemID":"1177","itemName":khai  hang"},{"itemID":"1161","itemName":"chinh phat"}

17892
{"itemID":"1177","itemName":"hang tang "},{"itemID":"1167","itemName":"ban tam"},{"itemID":"1188","itemName":"nam hoa"},{"itemID":"11667","itemName":"mua dong"},{"itemID":"1198","itemName":"57mua xuan yi"},{"itemID":"1156","itemName":"hai hoang"},{"itemID":"1173","itemName":"tim ve hoa"},{"itemID":"1165","itemName":"nam hoa tim hoa"},{"itemID":"1187","itemName":"tram cai cao"},{"itemID":"116653","itemName":"Set TTT44"}

I am looking for a way to split the characters in the item_order_detail column into 2 columns itemID and itemName. As below output table uses SQL function in databricks with spark_sql version 3.2.1.

order_id
itemID
itemName

17889
1123
banh baom1

17889
1124
khan tam

17889
1125
nuoc giat

17889
1127
sua tam da

17889
1110
phao khong9

17889
1121
het lam sao

17889
1134
trai ban

17889
1141
tim ban

17889
1177
khai  hang

17889
1161
chinh phat

17892
1177
hang tang

17892
1167
ban tam

17892
1188
nam hoa

17892
11667
mua dong

17892
1198
57mua xuan yi

17892
1156
hai hoang

17892
1173
tim ve hoa

17892
1165
nam hoa tim hoa

17892
1187
tram cai cao

17892
116653
Set TTT44

Can someone suggest a solution for me?

Thanks all

ContentLicense: CC BY-SA 4.0


问:
GraphicsBuffer's GetData always returning 0s
I'm trying to clone a mesh using GraphicsBuffer because its read/write option is false, and I can't change that. This is my current code:

```<code>public static bool Run(Mesh sourceMesh, out Mesh generatedMesh)
{
    GraphicsBuffer sourceDataBuffer = sourceMesh.GetVertexBuffer(0);
    GraphicsBuffer sourceIndexBuffer = sourceMesh.GetIndexBuffer();

    var vertexCount = sourceDataBuffer.count;
    var indexCount = sourceIndexBuffer.count;

    byte[] sourceData = new byte[vertexCount * (sourceDataBuffer.stride / sizeof(byte))];
    byte[] sourceIndex = new byte[(int)(indexCount * ((float)sourceIndexBuffer.stride / sizeof(byte)))];

    sourceDataBuffer.GetData(sourceData);
    sourceIndexBuffer.GetData(sourceIndex);

    var attributes = sourceMesh.GetVertexAttributes();

    generatedMesh = new Mesh();
    generatedMesh.vertexBufferTarget |= GraphicsBuffer.Target.Raw;

    generatedMesh.SetVertexBufferParams(vertexCount, attributes);
    generatedMesh.SetVertexBufferData(sourceData, 0, 0, sourceData.Length);
    generatedMesh.SetIndexBufferParams(indexCount, sourceMesh.indexFormat);
    generatedMesh.SetIndexBufferData(sourceIndex, 0, 0, sourceIndex.Length);

    generatedMesh.subMeshCount = sourceMesh.subMeshCount;
    for (int i = 0; i < sourceMesh.subMeshCount; i++)
    {
        var subMeshDescriptor = sourceMesh.GetSubMesh(i);
        generatedMesh.SetSubMesh(i, subMeshDescriptor);
    }

    sourceDataBuffer.Release();
    sourceIndexBuffer.Release();

    generatedMesh.RecalculateBounds();

    return true; // No error
}
</code>```

It works like a charm in my test project. But when I try to clone things in my main project, GetData(sourceData) and GetData(sourceIndex) both return arrays of 0s. What could be causing that? Could it be because of the read/write being disabled?

Edit: The problem only happens in bundles with non-readable meshes. I thought GraphicsBuffer should work with them, but it doesn't.

Body:
I'm trying to clone a mesh using GraphicsBuffer because its read/write option is false, and I can't change that. This is my current code:

public static bool Run(Mesh sourceMesh, out Mesh generatedMesh)
{
    GraphicsBuffer sourceDataBuffer = sourceMesh.GetVertexBuffer(0);
    GraphicsBuffer sourceIndexBuffer = sourceMesh.GetIndexBuffer();

    var vertexCount = sourceDataBuffer.count;
    var indexCount = sourceIndexBuffer.count;

    byte[] sourceData = new byte[vertexCount * (sourceDataBuffer.stride / sizeof(byte))];
    byte[] sourceIndex = new byte[(int)(indexCount * ((float)sourceIndexBuffer.stride / sizeof(byte)))];

    sourceDataBuffer.GetData(sourceData);
    sourceIndexBuffer.GetData(sourceIndex);

    var attributes = sourceMesh.GetVertexAttributes();

    generatedMesh = new Mesh();
    generatedMesh.vertexBufferTarget |= GraphicsBuffer.Target.Raw;

    generatedMesh.SetVertexBufferParams(vertexCount, attributes);
    generatedMesh.SetVertexBufferData(sourceData, 0, 0, sourceData.Length);
    generatedMesh.SetIndexBufferParams(indexCount, sourceMesh.indexFormat);
    generatedMesh.SetIndexBufferData(sourceIndex, 0, 0, sourceIndex.Length);

    generatedMesh.subMeshCount = sourceMesh.subMeshCount;
    for (int i = 0; i < sourceMesh.subMeshCount; i++)
    {
        var subMeshDescriptor = sourceMesh.GetSubMesh(i);
        generatedMesh.SetSubMesh(i, subMeshDescriptor);
    }

    sourceDataBuffer.Release();
    sourceIndexBuffer.Release();

    generatedMesh.RecalculateBounds();

    return true; // No error
}

It works like a charm in my test project. But when I try to clone things in my main project, GetData(sourceData) and GetData(sourceIndex) both return arrays of 0s. What could be causing that? Could it be because of the read/write being disabled?

Edit: The problem only happens in bundles with non-readable meshes. I thought GraphicsBuffer should work with them, but it doesn't.


问:
Nodejs Mongoose | Fetch the array of values for a given field
From the query below

```<code>let fields = { 'local.email': 1 };
UserModel.find({ '_id': { $in: userIds } }).select(fields).setOptions({ lean: true });
</code>```

Result which we get is

```<code>[
            {
                "_id": "54bf2d7415eaaa570c9ed5a0",
                "local": {
                    "email": "neo@q.com"
                }
            },
            {
                "_id": "54bfb753e4c9406112267056",
                "local": {
                    "email": "test@q.com"
                }
            }
]
</code>```

Is is possible to modify query itself to get below result

["neo@q.com", "test@q.com"]

Thanks in advance

Body:
From the query below

let fields = { 'local.email': 1 };
UserModel.find({ '_id': { $in: userIds } }).select(fields).setOptions({ lean: true });

Result which we get is

[
            {
                "_id": "54bf2d7415eaaa570c9ed5a0",
                "local": {
                    "email": "neo@q.com"
                }
            },
            {
                "_id": "54bfb753e4c9406112267056",
                "local": {
                    "email": "test@q.com"
                }
            }
]

Is is possible to modify query itself to get below result

["neo@q.com", "test@q.com"]

Thanks in advance


问:
Issues with std::put_time in C++
I want to create a log file with the name mentioning the date and time and I am using Visual Studio 2013(V120). currently I am implemented a code like this but get into issues at run time. Could anyone has a method for this

```<code>std::string Logger::GetTimeStampWithMilliSeconds() const
{
    const auto now = std::chrono::system_clock::now();
    const auto nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;

    const auto nowAsTimeT = std::chrono::system_clock::to_time_t(now);
    struct tm tm {};
    localtime_s(&tm, &nowAsTimeT);

    std::stringstream nowSs;
    nowSs << std::put_time(&tm, "%Y-%m-%d %T") << '.' << std::setfill('0') << std::setw(3) << nowMs.count();
    return nowSs.str();
</code>```

The issue is replicate below.

Title: Issues with std::put_time in C++

Body:
I want to create a log file with the name mentioning the date and time and I am using Visual Studio 2013(V120). currently I am implemented a code like this but get into issues at run time. Could anyone has a method for this

std::string Logger::GetTimeStampWithMilliSeconds() const
{
    const auto now = std::chrono::system_clock::now();
    const auto nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;

    const auto nowAsTimeT = std::chrono::system_clock::to_time_t(now);
    struct tm tm {};
    localtime_s(&tm, &nowAsTimeT);

    std::stringstream nowSs;
    nowSs << std::put_time(&tm, "%Y-%m-%d %T") << '.' << std::setfill('0') << std::setw(3) << nowMs.count();
    return nowSs.str();

The issue is replicate below.


问:
how to query exo trackselector in seperate dialog like video and audio in seperate dialog
I want to query exo quality dialog or default dialog in different dialog. like when user press setting button it will load only video or quality list if they press subtitle button that query only available subtitle and same way for audio track.
is there any possibilities to so this
current implementation</p>
```<code> MappingTrackSelector.MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
                if (mappedTrackInfo != null) {
                    CharSequence title = "Video";
                    int rendererIndex = 0;
                    int rendererType = mappedTrackInfo.getRendererType(rendererIndex);
                    boolean allowAdaptiveSelections = rendererType == C.TRACK_TYPE_VIDEO && mappedTrackInfo.getTypeSupport(C.TRACK_TYPE_VIDEO) == MappingTrackSelector.MappedTrackInfo.RENDERER_SUPPORT_NO_TRACKS;

                    TrackSelectionDialog trackSelectionDialog = TrackSelectionDialog.createForPlayer(simpleExoPlayer,
                            /* onDismissListener= */ dismissedDialog -> isShowingTrackSelectionDialog = false);
                    trackSelectionDialog.show(getSupportFragmentManager(), /* tag= */ null);
</code>```

Body:
I want to query exo quality dialog or default dialog in different dialog. like when user press setting button it will load only video or quality list if they press subtitle button that query only available subtitle and same way for audio track.
is there any possibilities to so this
current implementation

 MappingTrackSelector.MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
                if (mappedTrackInfo != null) {
                    CharSequence title = "Video";
                    int rendererIndex = 0;
                    int rendererType = mappedTrackInfo.getRendererType(rendererIndex);
                    boolean allowAdaptiveSelections = rendererType == C.TRACK_TYPE_VIDEO && mappedTrackInfo.getTypeSupport(C.TRACK_TYPE_VIDEO) == MappingTrackSelector.MappedTrackInfo.RENDERER_SUPPORT_NO_TRACKS;

                    TrackSelectionDialog trackSelectionDialog = TrackSelectionDialog.createForPlayer(simpleExoPlayer,
                            /* onDismissListener= */ dismissedDialog -> isShowingTrackSelectionDialog = false);
                    trackSelectionDialog.show(getSupportFragmentManager(), /* tag= */ null);


问:
How to check floating notifications permission on MIUI
this permission screen At the moment, when notifications are shown on MIUI, notifications do not pop up . When viewing the settings, I found that on some XIOMI devices, this setting is disabled. Is there any way to enable it by default, or check if it is enabled

```<code>NotificationCompat.Builder(context, SOME_CHANNEL_ID).apply {
    setupNotificationData(newRide)
    setTimeoutAfter(1000* someTimeout.toLong())
    setContentTitle(context.getString(R.string.offer_description))
    setContentText(context.getString(R.string.offer_new_event))
    setCustomHeadsUpContentView(createHeadsUpContentView())
    setSmallIcon(R.drawable.logo_notification)
    setContentIntent(pendingIntent)
    setSound(getSoundUri())
    setStyle(NotificationCompat.DecoratedCustomViewStyle())
    priority = NotificationCompat.PRIORITY_MAX
    setDeleteIntent(getDeleteAction())
    setVibrate(longArrayOf(500, 500, 500, 500, 500))
    setOngoing(true)
}

</code>```
```<code>private fun getNotificationChannelForOffer() =
    NotificationChannel(
        SOME_CHANNEL_ID, OSOME_CHANNEL_ID,
        NotificationManager.IMPORTANCE_HIGH
    ).apply {
        setSound(
            getOfferSoundUri(),
            audioAttributes
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            canBubble()
        }
        shouldVibrate()
        setBypassDnd(true)
        enableVibration(true)
        lockscreenVisibility = Notification.VISIBILITY_PUBLIC
        vibrationPattern = longArrayOf(500, 500, 500, 500, 500)
    }
</code>```

I've tried to use

```<code>setCustomHeadsUpContentView(createHeadsUpContentView())
</code>```

but notifications do not overlay without this permission .
Add this
permission to Manifest

Body:
this permission screen At the moment, when notifications are shown on MIUI, notifications do not pop up . When viewing the settings, I found that on some XIOMI devices, this setting is disabled. Is there any way to enable it by default, or check if it is enabled

NotificationCompat.Builder(context, SOME_CHANNEL_ID).apply {
    setupNotificationData(newRide)
    setTimeoutAfter(1000* someTimeout.toLong())
    setContentTitle(context.getString(R.string.offer_description))
    setContentText(context.getString(R.string.offer_new_event))
    setCustomHeadsUpContentView(createHeadsUpContentView())
    setSmallIcon(R.drawable.logo_notification)
    setContentIntent(pendingIntent)
    setSound(getSoundUri())
    setStyle(NotificationCompat.DecoratedCustomViewStyle())
    priority = NotificationCompat.PRIORITY_MAX
    setDeleteIntent(getDeleteAction())
    setVibrate(longArrayOf(500, 500, 500, 500, 500))
    setOngoing(true)
}

private fun getNotificationChannelForOffer() =
    NotificationChannel(
        SOME_CHANNEL_ID, OSOME_CHANNEL_ID,
        NotificationManager.IMPORTANCE_HIGH
    ).apply {
        setSound(
            getOfferSoundUri(),
            audioAttributes
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            canBubble()
        }
        shouldVibrate()
        setBypassDnd(true)
        enableVibration(true)
        lockscreenVisibility = Notification.VISIBILITY_PUBLIC
        vibrationPattern = longArrayOf(500, 500, 500, 500, 500)
    }

I've tried to use

setCustomHeadsUpContentView(createHeadsUpContentView())

but notifications do not overlay without this permission .
Add this
permission to Manifest


问:
Change the styling of Blockquote inside a markdown from headless wordpress
I'm using dangerouslySetInnerHTML to render the markdown from my headless wordpress post and I noticed the blockquote tag does not get styled in the markdown. I want to reference a quote in my blog post but how do I get the same styling as with wordpress into the markdown when using nextjs or react?</p>


问:
SPI From AdaFruit Trinket to ST7789 Display
I am working with the ST7789 Display and my ultimate goal is to display images on the screen using the built in MicroSD slot. I have a AdaFruit Trinket 3v that I'm using for the primary logic but I cannot seem to figure out how to program the trinket to communicate with the display.

From my research, I've been able to solder the wires in place to set up an SPI compatible connection between the two using the #1 and #0 pins on the trinket along with reset pin which are connected to the SI, SO, and Reset on the display in that order. I am writing the code in C++ using VS Code and the PlatformIO plugin to add the appropriate libraries for the trinket and ST7789 display.


问:
ES: Sort on the result of a Query function
I'm quite new to ES and have been trying many different ways to sort on a subset results from Query/Filter. The aggs always sort on the whole collection instead of the result from the above query. My final goal is to sort on field price from the result of query (which was already sorted by _score and only 5 docs)

{
  "query": {
    "bool": {
      "must": {
        "function_score": {
          "functions": [....],
          "query": {....}
          },
          "score_mode": "sum",
          "max_boost": 1.5
        }
      },
      "filter": [...]
    }
  },
  "size": 5,
  "from": 0,
  "sort": {
    "_score": "desc"
  },
  "_source": [
    "title",
    "price"
  ],
  "aggs": {
    "i_am_confused": {
      "terms": {
        "field": "price",
        "order": {
          "_term": "desc"
        }
      }
    }
  }
}
```

I don't want to sort on client (because the subset result would be at least 700 docs).

I appreciate your help.

I've tried a couple of aggs they all don't work as I want, probably I didn't use them right.

Body:
I'm quite new to ES and have been trying many different ways to sort on a subset results from Query/Filter. The aggs always sort on the whole collection instead of the result from the above query. My final goal is to sort on field price from the result of query (which was already sorted by _score and only 5 docs)

{
  "query": {
    "bool": {
      "must": {
        "function_score": {
          "functions": [....],
          "query": {....}
          },
          "score_mode": "sum",
          "max_boost": 1.5
        }
      },
      "filter": [...]
    }
  },
  "size": 5,
  "from": 0,
  "sort": {
    "_score": "desc"
  },
  "_source": [
    "title",
    "price"
  ],
  "aggs": {
    "i_am_confused": {
      "terms": {
        "field": "price",
        "order": {
          "_term": "desc"
        }
      }
    }
  }
}

I don't want to sort on client (because the subset result would be at least 700 docs).

I appreciate your help.

I've tried a couple of aggs they all don't work as I want, probably I didn't use them right.


问:
How do I fix "the code excecution cannot proceed because hdf5.dll was not found" error?
I recently uninstalled and reinstalled Anaconda, along with Python on my Windows PC. I removed a bunch of path variables (and admittedly cannot remember which ones I had).

I am using VS Code and OpenCV 4.6.0 (along with the contrib modules). The project builds just fine; however, when I run this program I receive the error "the code excecution cannot proceed because hdf5.dll was not found"

Does anyone know how to fix this?

This error was also posted here: Getting the error : 'The code execution cannot proceed because hdf5.dll was not found' in Visual Studio 2015
But I cannot seem to get this to work.


问:
How to correct code formatting and delete ^M signs in WebStorm
I have some weird problem with formatting, using WebStorm on Windows. In WebStorm preview code is looking just fine but when I open GitHub preview there are some weird signs like ^M and all code is just one-liner. I was trying to investigate this but without any success.

My only solution is to cut file content, paste to Notepad and then create a new file and paste content from Notepad.

I don't know does it matter but a lot of files in this project was copy+pasted from other project which might be initially wrote on Mac. I don't think it matters because it is happening also for newly created files.

It is a problem with only one repository so I excluded some global problem.


问:
TLS error when connecting to local MQTT broker from iOS client
I'm getting the following error when connecting to my local mosquitto MQTT broker with TLS (self signed certificate) from my iOS client:

SSL routines:ssl3_get_record:wrong version number.

mosquitto.conf

```<code>...
listener 8883
protocol mqtt
allow_anonymous true
require_certificate true
cafile /opt/homebrew/etc/mosquitto/certs/ca.crt
certfile /opt/homebrew/etc/mosquitto/certs/server.crt
keyfile /opt/homebrew/etc/mosquitto/certs/server.key
...
</code>```

Certificate creation:

```<code>openssl genrsa -out ca.key 2048
openssl req -new -x509 -key ca.key -out ca.crt (CN=CA)
openssl genrsa -out server.key 2048
openssl req -new -sha256 -out server.csr -key server.key (CN=localhost)
openssl x509 -req -sha256 -days 365 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt
openssl genrsa -out client.key 2048
openssl req -new -sha256 -out client.csr -key client.key (CN=localhost)
openssl x509 -req -sha256 -days 365 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt
openssl pkcs12 -export -out client.p12 -inkey client.key -in client.crt -certfile ca.crt
openssl x509 -inform pem -in ca.crt -outform der -out root.der
</code>```

iOS client certificate parsing (client.p12, root.der):

public static func importIdentities(from url: URL, password: String) throws -> [SecIdentity] {
    let p12Data = try Data(contentsOf: url)
    let options: [String: String] = [kSecImportExportPassphrase as String: password]

    var rawItems: CFArray?
    let result = DispatchQueue.global().sync {
        SecPKCS12Import(p12Data as CFData, options as CFDictionary, &rawItems)
    }

    guard result == errSecSuccess else {
        if result == errSecAuthFailed {
            throw Error.invalidPassword
        } else {
            throw Error.invalidData
        }
    }

    guard let items = rawItems as? [[CFString: SecIdentity]] else {
        throw Error.invalidData
    }

    return items.compactMap({ $0[kSecImportItemIdentity] })
}

public static func importCertificate(from url: URL) throws -> SecCertificate {
    let certificateData = try Data(contentsOf: url) as CFData
    guard let certificate = SecCertificateCreateWithData(nil, certificateData) else {
        throw Error.invalidData
    }
    return certificate
}
```
<p>iOS client <code>NWProtocolTLS.Options</code>:</p>
<pre class="lang-swift prettyprint-override"><code>func getNWProtocolTLSOptions() -> NWProtocolTLS.Options {
    let options = NWProtocolTLS.Options()

    sec_protocol_options_set_min_tls_protocol_version(options.securityProtocolOptions, minimumTLSVersion)

    if let maximumTLSVersion = maximumTLSVersion {
        sec_protocol_options_set_max_tls_protocol_version(options.securityProtocolOptions, maximumTLSVersion)
    }

    if let clientIdentity = clientIdentity, let secClientIdentity = sec_identity_create(clientIdentity) {
        sec_protocol_options_set_local_identity(options.securityProtocolOptions, secClientIdentity)
    }

    securityProtocols.forEach {
        sec_protocol_options_add_tls_application_protocol(options.securityProtocolOptions, $0)
    }

    if trustRootCertificates != nil {
        sec_protocol_options_set_verify_block(options.securityProtocolOptions, { _, sec_trust, sec_protocol_verify_complete in
            let trust = sec_trust_copy_ref(sec_trust).takeRetainedValue()

            if let trustRootCertificates = trustRootCertificates {
                SecTrustSetAnchorCertificates(trust, trustRootCertificates as CFArray)
            }

            SecTrustEvaluateAsyncWithError(trust, queue) { _, result, error in
                if let error = error {
                    log.error("Trust failed: \(error.localizedDescription)")
                }
                sec_protocol_verify_complete(result)
            }
        }, queue)
    }

    return options
}
</code>```

I can establish the connection but get the following error in the client logs:

[connection] nw_socket_handle_socket_event [C1.1.1.1:1] Socket SO_ERROR [54: Connection reset by peer]

And the broker logs are as follows:

```<code>1671167575: mosquitto version 2.0.15 starting
1671167575: Config loaded from /opt/homebrew/etc/mosquitto/mosquitto.conf.
1671167575: Opening ipv6 listen socket on port 8883.
1671167575: Opening ipv4 listen socket on port 8883.
1671167575: mosquitto version 2.0.15 running
1671167582: New connection from 127.0.0.1:56685 on port 8883.
1671167582: OpenSSL Error[0]: error:1408F10B:SSL routines:ssl3_get_record:wrong version number
1671167582: Client <unknown> disconnected: Protocol error.
</code>```

Anyone know what might be the issue here?

Body:
I'm getting the following error when connecting to my local mosquitto MQTT broker with TLS (self signed certificate) from my iOS client:

SSL routines:ssl3_get_record:wrong version number.

mosquitto.conf

...
listener 8883
protocol mqtt
allow_anonymous true
require_certificate true
cafile /opt/homebrew/etc/mosquitto/certs/ca.crt
certfile /opt/homebrew/etc/mosquitto/certs/server.crt
keyfile /opt/homebrew/etc/mosquitto/certs/server.key
...

Certificate creation:

openssl genrsa -out ca.key 2048
openssl req -new -x509 -key ca.key -out ca.crt (CN=CA)
openssl genrsa -out server.key 2048
openssl req -new -sha256 -out server.csr -key server.key (CN=localhost)
openssl x509 -req -sha256 -days 365 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt
openssl genrsa -out client.key 2048
openssl req -new -sha256 -out client.csr -key client.key (CN=localhost)
openssl x509 -req -sha256 -days 365 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt
openssl pkcs12 -export -out client.p12 -inkey client.key -in client.crt -certfile ca.crt
openssl x509 -inform pem -in ca.crt -outform der -out root.der

iOS client certificate parsing (client.p12, root.der):

public static func importIdentities(from url: URL, password: String) throws -> [SecIdentity] {
    let p12Data = try Data(contentsOf: url)
    let options: [String: String] = [kSecImportExportPassphrase as String: password]

    var rawItems: CFArray?
    let result = DispatchQueue.global().sync {
        SecPKCS12Import(p12Data as CFData, options as CFDictionary, &rawItems)
    }

    guard result == errSecSuccess else {
        if result == errSecAuthFailed {
            throw Error.invalidPassword
        } else {
            throw Error.invalidData
        }
    }

    guard let items = rawItems as? [[CFString: SecIdentity]] else {
        throw Error.invalidData
    }

    return items.compactMap({ $0[kSecImportItemIdentity] })
}

public static func importCertificate(from url: URL) throws -> SecCertificate {
    let certificateData = try Data(contentsOf: url) as CFData
    guard let certificate = SecCertificateCreateWithData(nil, certificateData) else {
        throw Error.invalidData
    }
    return certificate
}

iOS client NWProtocolTLS.Options:

func getNWProtocolTLSOptions() -> NWProtocolTLS.Options {
    let options = NWProtocolTLS.Options()

    sec_protocol_options_set_min_tls_protocol_version(options.securityProtocolOptions, minimumTLSVersion)

    if let maximumTLSVersion = maximumTLSVersion {
        sec_protocol_options_set_max_tls_protocol_version(options.securityProtocolOptions, maximumTLSVersion)
    }

    if let clientIdentity = clientIdentity, let secClientIdentity = sec_identity_create(clientIdentity) {
        sec_protocol_options_set_local_identity(options.securityProtocolOptions, secClientIdentity)
    }

    securityProtocols.forEach {
        sec_protocol_options_add_tls_application_protocol(options.securityProtocolOptions, $0)
    }

    if trustRootCertificates != nil {
        sec_protocol_options_set_verify_block(options.securityProtocolOptions, { _, sec_trust, sec_protocol_verify_complete in
            let trust = sec_trust_copy_ref(sec_trust).takeRetainedValue()

            if let trustRootCertificates = trustRootCertificates {
                SecTrustSetAnchorCertificates(trust, trustRootCertificates as CFArray)
            }

            SecTrustEvaluateAsyncWithError(trust, queue) { _, result, error in
                if let error = error {
                    log.error("Trust failed: \(error.localizedDescription)")
                }
                sec_protocol_verify_complete(result)
            }
        }, queue)
    }

    return options
}

I can establish the connection but get the following error in the client logs:

[connection] nw_socket_handle_socket_event [C1.1.1.1:1] Socket SO_ERROR [54: Connection reset by peer]

And the broker logs are as follows:

1671167575: mosquitto version 2.0.15 starting
1671167575: Config loaded from /opt/homebrew/etc/mosquitto/mosquitto.conf.
1671167575: Opening ipv6 listen socket on port 8883.
1671167575: Opening ipv4 listen socket on port 8883.
1671167575: mosquitto version 2.0.15 running
1671167582: New connection from 127.0.0.1:56685 on port 8883.
1671167582: OpenSSL Error[0]: error:1408F10B:SSL routines:ssl3_get_record:wrong version number
1671167582: Client <unknown> disconnected: Protocol error.

Anyone know what might be the issue here?


问:
Automated flow of power bi reports from power bi service to sharepoint or onedrive
I Want to have an environment where whenever a power-bi report (in .pbix format) is created or updated in a workspace in my power bi service, it will automatically be reflected in my sharepoint without any manual effort so that I can manage different versions of a report on organization level. Is there a way to achieve this automated connection between power bi service and sharepoint?

Tried to use sharepoint web-embedded option for pages but I guess it is not an option to make the connection automatic and requires multiple layers of manual effort for each page.


问:
@EJB annotation not working for REST API class file
@EJB not working, returning null pointer exception when used. I am  using jersey. It is working in the similar project of jersey earlier.

Rest API class

```<code>@Path("")
public class Services
{
    @EJB
    UserSessionBeanLocal userBean;

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("register")
    public Response register(@FormParam("userName") final String name, @FormParam("userPassword") final String pass, @FormParam("userEmail") String email)
    {
        if (userBean.isEmailRegistered(email))   // userBean is null here
            {
                           // code
                        }
    }
}
</code>```

Stateless EJB

```<code>@Stateless
public class UserSessionBean implements UserSessionBeanLocal
{
    static ArrayList<User> usersList = new ArrayList<User>();
    static int userCount = 0;
    User u = null;

    @Override
    public boolean isEmailRegistered(final String email)
    {
        return usersList.stream().anyMatch(d -> d.getEmail().equals(email));
    }
}
</code>```

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.enovate.assignment.ejb1</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/user/*</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

Any help is appreciated. Thanks in advance.

I was expecting it should work fine. Now I have to use the JNDI lookup way to instantiate the bean.
As I mentioned it is working in almost similar project. I found something that @EJB does not work in non-managed bean if is related, but I don't understand it.

Body:
@EJB not working, returning null pointer exception when used. I am  using jersey. It is working in the similar project of jersey earlier.

Rest API class

@Path("")
public class Services
{
    @EJB
    UserSessionBeanLocal userBean;

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("register")
    public Response register(@FormParam("userName") final String name, @FormParam("userPassword") final String pass, @FormParam("userEmail") String email)
    {
        if (userBean.isEmailRegistered(email))   // userBean is null here
            {
                           // code
                        }
    }
}

Stateless EJB

@Stateless
public class UserSessionBean implements UserSessionBeanLocal
{
    static ArrayList<User> usersList = new ArrayList<User>();
    static int userCount = 0;
    User u = null;

    @Override
    public boolean isEmailRegistered(final String email)
    {
        return usersList.stream().anyMatch(d -> d.getEmail().equals(email));
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.enovate.assignment.ejb1</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/user/*</url-pattern>
    </servlet-mapping>
</web-app>

Any help is appreciated. Thanks in advance.

I was expecting it should work fine. Now I have to use the JNDI lookup way to instantiate the bean.
As I mentioned it is working in almost similar project. I found something that @EJB does not work in non-managed bean if is related, but I don't understand it.


问:
Handle many function parameters through many layers of functions?
I have a library that has functions like the following:

```<code>class ResultObject:
    def __init__(self)
        self.object_string = []
    ...
    def append(self, other_result_object)
        self.object_string.append(other_result_object)
    ...

def bottom_func_A(option_1, option_2, param_0=def_arg_0, param_1=def_arg_1, ..., param_14=def_arg_14):
    """"
    This is a process whose output genuinely depends on 15 input parameters enumerated param_n
    """
    ...
    return result_object_A

def bottom_func_B(option_1, option_2, param_0=def_arg_0, param_1=def_arg_1, ..., param_14=def_arg_14):
    """"
    This is a different process whose output genuinely depends on 15 input parameters
    enumerated param_n. parameters values or defautsare not shared with bottom_func_A
    """
    ...
    return result_object_A

def wrapper_A(wrapper_option):
    result_1 = bottom_func_A(True, True)
    if wrapper_option:
        result_2 = bottom_func_A(True, False)
    # Do something with result_1 and result_2 if present...
    ...
    return wrapper_object_A

def wrapper_B(wrapper_option):
    result_1 = bottom_func_B(True, True)
    if wrapper_option:
        result_2 = bottom_func_B(True, False)
    # Do something with result_1 and result_2 if present...
    ...
    return wrapper_object_B

def do_both_A_B(wrapper_option)
    result_A = wrapper_A(wrapper_option)
    result_B = wrapper_B(wrapper_option)
    # Do something with result_A and result_B
    ...
    return wrapper_A_B_object

</code>```

In the library the bottom_func_X functions do not always have similar signatures, sometimes they have more or less "option"-like params and more or less "numerical parameter" parameters like param_N. Their bodies are also generic. Similar in this case I've shown wrapper_A and wrapper_B with similar structures but the "wrapper" functions need not have similar structures to eachother. Also, there may be a wrapper (like do_both_A_B) that involves bottom functions A, R, G etc. That is wrappers aren't 1:1 with bottom_funcs. The only structural consistency is that ALL of these functions (bottom funcs and wrappers at all layers) return instances of the ResultObject class. These result objects get "strung together" into long strings where each node in the string was probably generated by some bottom_func with a set of parameters. Note also that are many dozens of bottom_func type objects and wrappers and super-wrappers that string together many combinations of bottom_funcs. That is, these many parameter functions are not one-off things, but that there are many of them in the library.

This is fine and can be made to work. The problem is this. It is very often the case that I want parameters from the bottom functions to be exposed in the signatures of the wrappers at various levels. I see 4 ways to do this.

(1) Just include additional parameters for inner functions at each layer.
(1a) Only do this on an as-needed basis. If I or someone has a use case for exposing param_4 from bottom_func_A in wrapper_A then add it. The downside of this is you have a hodge-podge of exposed and unexposed parameters so you may find yourself often needing to modify this library rather than just call things from it.
(1b) Do this carte-blanche. Expose all parameters at all layers. Obviously this is a mess because do_both_A_B would need to expose 30 parameters, 15 for each of its bottom layer functions. Most of the code in the library would rapidly become function signatures.

Option (1a) is what I'd say has been de-facto the existing solution in the library.

(2) Don't call bottom_funcs within wrappers, rather, accept results from bottom_funcs in the wrappers. That is, bottom_func_A produces a result_object_A and this is al wrapper_A requires. So wrapper_A could have a parameter called result_object_A or something. Maybe it could default to None and in this case wrapper_A will indeed call bottom_func_A using the default arguments of bottom_func_A. But if for some reason a caller doesn't want the default result_object_A they can call bottom_func_A themselves with their desired custom parameters.

(3) Bundle the param_N parameters into some sort of dataclass bundle that can be passed more fluidly. This param bundle would then be exposed at all layers and a caller could modify it from the default. The downside is class or instance of this databundle would need to be defined for each bottom_func. Each of the bottom_funcs would also now have the job of unbundling the data bundle within the bottom_func body. The data bundle and bottom_func would need to cooperate, so if bottom_func is modified to include some new feature (that requires additional params) the dev would need to make sure to modify the corresponding data bundle. I think in practice this would have a similar effect on the codebase as option (2). That is, the default data bundle would be used if callers of the wrappers don't choose to modify the bundle, but if they like, they can do the work of generating a custom bundle and passing that through. In effect this isn't much different than calling bottom_func_A with the caller's desired parameters and passing the result through.

(4) Similar to option 3, but the "bundle" could just be kwargs dictionaries that get passed with appropriate names through the different layers. That is do_both_A_B could have something like bottom_func_A_kwargs as an input parameter that exposes the ability to modify one or both versions of bottom_func_A in it.

(5) The nested parameters could be turned into some sort of global variables whose value can be modified in wrappers or by callers. These could be python global variables or entries in some sort of database module/file or actual database. This is a pretty nasty idea for a few reasons but in practice this sort of solution has arisen in this code base as well. The major downside that pops in my mind first is if a caller modifies a param value but forgets to set it back to its default value but that's not to say there's not other big ones.

Which of these patterns (or other patterns I haven't listed) most aptly solves the parameter explosion problem that arises from wanting to expose the ability to modify the lowest level parameters at higher layers? Perhaps to some degree the issue is that I want a very high degree of flexibility in what this code can do so I just have to pay the price of having tons of code dedicated to handling parameters?

Body:
I have a library that has functions like the following:

class ResultObject:
    def __init__(self)
        self.object_string = []
    ...
    def append(self, other_result_object)
        self.object_string.append(other_result_object)
    ...

def bottom_func_A(option_1, option_2, param_0=def_arg_0, param_1=def_arg_1, ..., param_14=def_arg_14):
    """"
    This is a process whose output genuinely depends on 15 input parameters enumerated param_n
    """
    ...
    return result_object_A

def bottom_func_B(option_1, option_2, param_0=def_arg_0, param_1=def_arg_1, ..., param_14=def_arg_14):
    """"
    This is a different process whose output genuinely depends on 15 input parameters
    enumerated param_n. parameters values or defautsare not shared with bottom_func_A
    """
    ...
    return result_object_A

def wrapper_A(wrapper_option):
    result_1 = bottom_func_A(True, True)
    if wrapper_option:
        result_2 = bottom_func_A(True, False)
    # Do something with result_1 and result_2 if present...
    ...
    return wrapper_object_A

def wrapper_B(wrapper_option):
    result_1 = bottom_func_B(True, True)
    if wrapper_option:
        result_2 = bottom_func_B(True, False)
    # Do something with result_1 and result_2 if present...
    ...
    return wrapper_object_B

def do_both_A_B(wrapper_option)
    result_A = wrapper_A(wrapper_option)
    result_B = wrapper_B(wrapper_option)
    # Do something with result_A and result_B
    ...
    return wrapper_A_B_object

In the library the bottom_func_X functions do not always have similar signatures, sometimes they have more or less "option"-like params and more or less "numerical parameter" parameters like param_N. Their bodies are also generic. Similar in this case I've shown wrapper_A and wrapper_B with similar structures but the "wrapper" functions need not have similar structures to eachother. Also, there may be a wrapper (like do_both_A_B) that involves bottom functions A, R, G etc. That is wrappers aren't 1:1 with bottom_funcs. The only structural consistency is that ALL of these functions (bottom funcs and wrappers at all layers) return instances of the ResultObject class. These result objects get "strung together" into long strings where each node in the string was probably generated by some bottom_func with a set of parameters. Note also that are many dozens of bottom_func type objects and wrappers and super-wrappers that string together many combinations of bottom_funcs. That is, these many parameter functions are not one-off things, but that there are many of them in the library.

This is fine and can be made to work. The problem is this. It is very often the case that I want parameters from the bottom functions to be exposed in the signatures of the wrappers at various levels. I see 4 ways to do this.

(1) Just include additional parameters for inner functions at each layer.
(1a) Only do this on an as-needed basis. If I or someone has a use case for exposing param_4 from bottom_func_A in wrapper_A then add it. The downside of this is you have a hodge-podge of exposed and unexposed parameters so you may find yourself often needing to modify this library rather than just call things from it.
(1b) Do this carte-blanche. Expose all parameters at all layers. Obviously this is a mess because do_both_A_B would need to expose 30 parameters, 15 for each of its bottom layer functions. Most of the code in the library would rapidly become function signatures.

Option (1a) is what I'd say has been de-facto the existing solution in the library.

(2) Don't call bottom_funcs within wrappers, rather, accept results from bottom_funcs in the wrappers. That is, bottom_func_A produces a result_object_A and this is al wrapper_A requires. So wrapper_A could have a parameter called result_object_A or something. Maybe it could default to None and in this case wrapper_A will indeed call bottom_func_A using the default arguments of bottom_func_A. But if for some reason a caller doesn't want the default result_object_A they can call bottom_func_A themselves with their desired custom parameters.

(3) Bundle the param_N parameters into some sort of dataclass bundle that can be passed more fluidly. This param bundle would then be exposed at all layers and a caller could modify it from the default. The downside is class or instance of this databundle would need to be defined for each bottom_func. Each of the bottom_funcs would also now have the job of unbundling the data bundle within the bottom_func body. The data bundle and bottom_func would need to cooperate, so if bottom_func is modified to include some new feature (that requires additional params) the dev would need to make sure to modify the corresponding data bundle. I think in practice this would have a similar effect on the codebase as option (2). That is, the default data bundle would be used if callers of the wrappers don't choose to modify the bundle, but if they like, they can do the work of generating a custom bundle and passing that through. In effect this isn't much different than calling bottom_func_A with the caller's desired parameters and passing the result through.

(4) Similar to option 3, but the "bundle" could just be kwargs dictionaries that get passed with appropriate names through the different layers. That is do_both_A_B could have something like bottom_func_A_kwargs as an input parameter that exposes the ability to modify one or both versions of bottom_func_A in it.

(5) The nested parameters could be turned into some sort of global variables whose value can be modified in wrappers or by callers. These could be python global variables or entries in some sort of database module/file or actual database. This is a pretty nasty idea for a few reasons but in practice this sort of solution has arisen in this code base as well. The major downside that pops in my mind first is if a caller modifies a param value but forgets to set it back to its default value but that's not to say there's not other big ones.

Which of these patterns (or other patterns I haven't listed) most aptly solves the parameter explosion problem that arises from wanting to expose the ability to modify the lowest level parameters at higher layers? Perhaps to some degree the issue is that I want a very high degree of flexibility in what this code can do so I just have to pay the price of having tons of code dedicated to handling parameters?


问:
BouncyCastle FIPS: getting StackOverFlowError when converting default keystore from JKS to BCFKS
So I am working on a FIPS compliant java base image with JDK11. The requirement was to convert the default keystore from JKS to BCFKS.
This is my java.security setting:

```<code>security.provider.1=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider
security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider fips:BCFIPS
security.provider.3=SUN
security.provider.4=SunRsaSign
security.provider.5=SunEC
security.provider.6=SunJSSE BCFIPS
security.provider.7=SunJCE
security.provider.8=SunJGSS
security.provider.9=SunSASL
security.provider.10=XMLDSig
security.provider.11=SunPCSC
security.provider.12=JdkLDAP
security.provider.13=JdkSASL
security.provider.14=Apple
security.provider.15=SunPKCS11
</code>```
```<code>#
# Default keystore type.
#
keystore.type=BCFKS
</code>```

So when I try to convert the default keystore from JKS to BCFKS with the following command:

```<code>keytool -importkeystore -srckeystore /etc/ssl/certs/java/cacerts.orig -srcstoretype JKS \
     -srcstorepass changeit -destkeystore /etc/ssl/certs/java/cacerts -deststorepass changeit \
     -deststoretype BCFKS -providerClass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \
     --providerpath /usr/lib/jvm/java-11-openjdk-amd64/jar/bc-fips-1.0.2.3.jar
</code>```

I get the following error:

```<code>Exception in thread "main" java.lang.StackOverflowError
    at java.base/java.util.Dictionary.<init>(Dictionary.java:55)
    at java.base/java.util.Hashtable.<init>(Hashtable.java:239)
    at java.base/java.util.Properties.<init>(Properties.java:206)
    at java.base/java.util.Properties.<init>(Properties.java:174)
    at java.base/java.security.Provider.<init>(Provider.java:262)
    at java.base/sun.security.ssl.SunJSSE.<init>(SunJSSE.java:138)
    at java.base/sun.security.ssl.SunJSSE.<init>(SunJSSE.java:126)
    at java.base/com.sun.net.ssl.internal.ssl.Provider.<init>(Provider.java:52)
    at java.base/sun.security.jca.ProviderConfig.getProvider(ProviderConfig.java:183)
    at java.base/sun.security.jca.ProviderList.getProvider(ProviderList.java:266)
    at java.base/sun.security.jca.ProviderList.getIndex(ProviderList.java:296)
    at java.base/sun.security.jca.ProviderList.getProviderConfig(ProviderList.java:280)
    at java.base/sun.security.jca.ProviderList.getProvider(ProviderList.java:286)

        ...
</code>```

When I remove "BCFIPS" in provider.6, the error is gone, but I do need it to be there for the SSL to load BCFIPS as provider.

The same settings worked fine by my colleagues, but a notable difference is they use JDK8. Not sure if that's the reason.

Also I saw this https://github.com/bcgit/bc-java/issues/1000 who has exactly the same issue with me, unfortunately the workaround didn't work for me and there was no follow-up.

I've been stuck with this for days...HELP appreciated! Thank you!s

I tried the settings mentioned above, tried the keytool command, was expecting the keystore type converted correctly from JKS to BCFKS, but StackOverFlowError happened.

Body:
So I am working on a FIPS compliant java base image with JDK11. The requirement was to convert the default keystore from JKS to BCFKS.
This is my java.security setting:

security.provider.1=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider
security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider fips:BCFIPS
security.provider.3=SUN
security.provider.4=SunRsaSign
security.provider.5=SunEC
security.provider.6=SunJSSE BCFIPS
security.provider.7=SunJCE
security.provider.8=SunJGSS
security.provider.9=SunSASL
security.provider.10=XMLDSig
security.provider.11=SunPCSC
security.provider.12=JdkLDAP
security.provider.13=JdkSASL
security.provider.14=Apple
security.provider.15=SunPKCS11

#
# Default keystore type.
#
keystore.type=BCFKS

So when I try to convert the default keystore from JKS to BCFKS with the following command:

keytool -importkeystore -srckeystore /etc/ssl/certs/java/cacerts.orig -srcstoretype JKS \
     -srcstorepass changeit -destkeystore /etc/ssl/certs/java/cacerts -deststorepass changeit \
     -deststoretype BCFKS -providerClass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \
     --providerpath /usr/lib/jvm/java-11-openjdk-amd64/jar/bc-fips-1.0.2.3.jar

I get the following error:

Exception in thread "main" java.lang.StackOverflowError
    at java.base/java.util.Dictionary.<init>(Dictionary.java:55)
    at java.base/java.util.Hashtable.<init>(Hashtable.java:239)
    at java.base/java.util.Properties.<init>(Properties.java:206)
    at java.base/java.util.Properties.<init>(Properties.java:174)
    at java.base/java.security.Provider.<init>(Provider.java:262)
    at java.base/sun.security.ssl.SunJSSE.<init>(SunJSSE.java:138)
    at java.base/sun.security.ssl.SunJSSE.<init>(SunJSSE.java:126)
    at java.base/com.sun.net.ssl.internal.ssl.Provider.<init>(Provider.java:52)
    at java.base/sun.security.jca.ProviderConfig.getProvider(ProviderConfig.java:183)
    at java.base/sun.security.jca.ProviderList.getProvider(ProviderList.java:266)
    at java.base/sun.security.jca.ProviderList.getIndex(ProviderList.java:296)
    at java.base/sun.security.jca.ProviderList.getProviderConfig(ProviderList.java:280)
    at java.base/sun.security.jca.ProviderList.getProvider(ProviderList.java:286)

        ...

When I remove "BCFIPS" in provider.6, the error is gone, but I do need it to be there for the SSL to load BCFIPS as provider.

The same settings worked fine by my colleagues, but a notable difference is they use JDK8. Not sure if that's the reason.

Also I saw this https://github.com/bcgit/bc-java/issues/1000 who has exactly the same issue with me, unfortunately the workaround didn't work for me and there was no follow-up.

I've been stuck with this for days...HELP appreciated! Thank you!s

I tried the settings mentioned above, tried the keytool command, was expecting the keystore type converted correctly from JKS to BCFKS, but StackOverFlowError happened.


问:
How do I remove the avg raw query legend from my grafana dashboard?
enter image description here
I do not want the avg by(container) (irate(container_cpu_usage_seconds_total{namespace="prod", container!="POD"}[5m])) legend value, just container label. Is there any way I can remove it?

I tried for other panel, it display correctly.

```<code>(100 - (avg by (node) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100))
</code>```

Body:
enter image description here
I do not want the avg by(container) (irate(container_cpu_usage_seconds_total{namespace="prod", container!="POD"}[5m])) legend value, just container label. Is there any way I can remove it?

I tried for other panel, it display correctly.

(100 - (avg by (node) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100))


问:
Can't convert input element to re-usable component in react js
I created a login form and now I want to convert my input fields to re- usable component. I created separate common input.jsx file. This is input.jsx file's code.

import React from "react";

const Input = ({ name, label, value, onChange }) => {
  return (

      {label}
      <input
        value={value}
        onChange={onChange}
        id={name}
        name={name}
        type="text"
        className="form-control"
      />

  );
};

export default Input;
```
<p>and imported it to my loginForm.jsx. Here is my loginForm.jsx render method</p>
<pre class="lang-jsx prettyprint-override"><code>handleChange = ({ currentTarget: input }) => {
  const account = { ...this.state.account };
  account[input.name] = input.value;
  this.setState({ account });
};

render() {
  const { account } = this.state;

  return (
    <div>
      <h1>Login</h1>
      <form onSubmit={this.handleSubmit}>
        <Input
          name="username"
          value={account.username}
          label="Username"
          onChange={this.handleChange}
        />
        <Input
          name="password"
          value={account.password}
          label="Password"
          onChange={this.handleChange}
        />

        <button className="btn btn-primary">Login</button>
      </form>
    </div>
  );
}
</code>```

But after adding below code to my loginForm.jsx,

<Input
  name="username"
  value={account.username}
  label="Username"
  onChange={this.handleChange}
/>
```
<p>code and deleted previous code ,</p>
<pre class="lang-jsx prettyprint-override"><code><div className="form-group">
  <label htmlFor="username">Username</label>
  <input
    value={account.username}
    name="username"
    onChange={this.handleChange}
    ref={this.username}
    id="username"
    type="text"
    className="form-control"
  />
</div>
</code>```

suddenly my login page not loading.(Empty page).

My login page's console showing below error.

```<code>The above error occurred in the <LoginForm> component:

at LoginForm (http://localhost:3000/main.5d4e82bfe117bc198b43.hot-update.js:27:5)
at Route (http://localhost:3000/static/js/bundle.js:54444:5)
at Switch (http://localhost:3000/static/js/bundle.js:54739:5)
at main
at App
at Router (http://localhost:3000/static/js/bundle.js:54612:5)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:53870:5)
</code>```

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

Body:
I created a login form and now I want to convert my input fields to re- usable component. I created separate common input.jsx file. This is input.jsx file's code.

import React from "react";

const Input = ({ name, label, value, onChange }) => {
  return (

      {label}
      <input
        value={value}
        onChange={onChange}
        id={name}
        name={name}
        type="text"
        className="form-control"
      />

  );
};

export default Input;

and imported it to my loginForm.jsx. Here is my loginForm.jsx render method

handleChange = ({ currentTarget: input }) => {
  const account = { ...this.state.account };
  account[input.name] = input.value;
  this.setState({ account });
};

render() {
  const { account } = this.state;

  return (

Login

      <form onSubmit={this.handleSubmit}>
        <Input
          name="username"
          value={account.username}
          label="Username"
          onChange={this.handleChange}
        />
        <Input
          name="password"
          value={account.password}
          label="Password"
          onChange={this.handleChange}
        />

        <button className="btn btn-primary">Login</button>
      </form>

  );
}

But after adding below code to my loginForm.jsx,

<Input
  name="username"
  value={account.username}
  label="Username"
  onChange={this.handleChange}
/>

code and deleted previous code ,

  Username
  <input
    value={account.username}
    name="username"
    onChange={this.handleChange}
    ref={this.username}
    id="username"
    type="text"
    className="form-control"
  />

suddenly my login page not loading.(Empty page).

My login page's console showing below error.

The above error occurred in the <LoginForm> component:

at LoginForm (http://localhost:3000/main.5d4e82bfe117bc198b43.hot-update.js:27:5)
at Route (http://localhost:3000/static/js/bundle.js:54444:5)
at Switch (http://localhost:3000/static/js/bundle.js:54739:5)
at main
at App
at Router (http://localhost:3000/static/js/bundle.js:54612:5)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:53870:5)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.


问:
In nodejs, NaN is returned when a post request of api using bodyparser is made
Version

nodejs v16.15.0

npm 8.10.0

I created an api in nodejs as follows

```<code>const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.json());

const sayHi = (req, res) => {
  res.send("Hi!");
};

app.get("/", sayHi);

app.post("/add", (req, res) => {
  const { a, b } = req.body;
  res.send(`The sum is: ${a + b}`);
});

app.listen(5000, () => {
  console.log(`Server is running on port 5000.`);
});
</code>```

The get request became a response.

NaN is returned in response to post requests.

```<code>{
    "a": 5,
    "b": 10
}
</code>```
```<code>The sum is: NaN
</code>```

Body:
Version

nodejs v16.15.0

npm 8.10.0

I created an api in nodejs as follows

const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.json());

const sayHi = (req, res) => {
  res.send("Hi!");
};

app.get("/", sayHi);

app.post("/add", (req, res) => {
  const { a, b } = req.body;
  res.send(`The sum is: ${a + b}`);
});

app.listen(5000, () => {
  console.log(`Server is running on port 5000.`);
});

The get request became a response.

NaN is returned in response to post requests.

{
    "a": 5,
    "b": 10
}

The sum is: NaN


问:
Time x axis does not catch data from service (Angular, SignalR)
The service

```<code>import { Injectable } from '@angular/core';
import * as signalR from '@aspnet/signalr';
import { Chart } from 'chart.js';
import { resolve } from 'dns';
import { BehaviorSubject, Observable } from 'rxjs';
import { ChartDataPm1200 } from '../_models/chartmodel';

export interface ChartData{
  data: number,
  time: number
}

@Injectable({
  providedIn: 'root'
})

export class SpeedService {
  baseUrl = 'https://localhost:7068/';
  data: ChartDataPm1200[];
  datachart: ChartDataPm1200;
  resulttime: string;
  finaltime : any;
  result:any;

  private hubConnection: signalR.HubConnection;

  public StartConnection = () =>{
    this.hubConnection = new signalR.HubConnectionBuilder().configureLogging(signalR.LogLevel.Debug)
    .withUrl("https://localhost:7068/charts", {
      skipNegotiation: true,
      transport: signalR.HttpTransportType.WebSockets
    })
    .build();
    this.hubConnection.start().then(()=>console.log('Connection started')).catch(err => console.log('Error while connecting: '+err));
  }

  public addTransferChartDataListener = () => {
    this.hubConnection.on('transferchartdataPm1200', (data) => {
      this.data= data;
      console.log(data);
    });
}

public addTransferTime = async() => {
  this.hubConnection.on('transfertime',(data) => {
    this.resulttime =  JSON.stringify(data).replaceAll('{"time":','');
    this.finaltime = this.resulttime.replaceAll('}','');
    console.log(this.finaltime);
})
return this.finaltime;
}

}
</code>```

I have the HTML of the line chart set up like this:

`

```<code><h1>{{signalRService.finaltime}}</h1> <!-- for testing purpose -->
        <div style="display: block;">
    <canvas baseChart width= "400px" height= "200px"
            [data]="linechartdata"
            [options]="linechartOptions"
            [legend]="linechartLegend"
            [type]="'line'">
          </canvas>
  </div>
</code>```

And the signalRService works well as I get the result like this:

However, in the component, I set up signalRService.finaltime for the source of the x axis (time axis) like this
`

```<code>export class LineSpeedChartComponent implements OnInit {
    public linechartdata:ChartData = {
      datasets: [{
        label:"Ampere",
        data: [{x:+this.signalRService.finaltime,y:12}]
    }]
    };

    public linechartOptions: ChartOptions = {

      responsive: true,
      scales: {
        x: {
          type: 'time',
          min: Date.now() - (24 * 60 * 60 * 1000),
          max: Date.now() + (24 * 60 * 60 * 1000),
          ticks: {
            source: 'auto',
          },
          time:{
            unit: 'hour', //second
            displayFormats:{
              hour: "dd/MM/yyyy HH:mm:ss" //second = 'dd/MM/yyyy HH:mm:ss'
            },
            tooltipFormat: "dd/MM/yyyy HH:mm:ss",
          },
          adapters: {
            date: {
              locale: vi,
            },
        },
      },
        y: {
            min: 0,

        },
      }
  };
</code>```

And no data is showed in the chart, including the data of the y axis. But if I replace this.signalRService.finaltime with a specific value, it works fine.

Please send help !!!

Body:
The service

import { Injectable } from '@angular/core';
import * as signalR from '@aspnet/signalr';
import { Chart } from 'chart.js';
import { resolve } from 'dns';
import { BehaviorSubject, Observable } from 'rxjs';
import { ChartDataPm1200 } from '../_models/chartmodel';

export interface ChartData{
  data: number,
  time: number
}

@Injectable({
  providedIn: 'root'
})

export class SpeedService {
  baseUrl = 'https://localhost:7068/';
  data: ChartDataPm1200[];
  datachart: ChartDataPm1200;
  resulttime: string;
  finaltime : any;
  result:any;

  private hubConnection: signalR.HubConnection;

  public StartConnection = () =>{
    this.hubConnection = new signalR.HubConnectionBuilder().configureLogging(signalR.LogLevel.Debug)
    .withUrl("https://localhost:7068/charts", {
      skipNegotiation: true,
      transport: signalR.HttpTransportType.WebSockets
    })
    .build();
    this.hubConnection.start().then(()=>console.log('Connection started')).catch(err => console.log('Error while connecting: '+err));
  }

  public addTransferChartDataListener = () => {
    this.hubConnection.on('transferchartdataPm1200', (data) => {
      this.data= data;
      console.log(data);
    });
}

public addTransferTime = async() => {
  this.hubConnection.on('transfertime',(data) => {
    this.resulttime =  JSON.stringify(data).replaceAll('{"time":','');
    this.finaltime = this.resulttime.replaceAll('}','');
    console.log(this.finaltime);
})
return this.finaltime;
}

}

I have the HTML of the line chart set up like this:

`

{{signalRService.finaltime}}

    <canvas baseChart width= "400px" height= "200px"
            [data]="linechartdata"
            [options]="linechartOptions"
            [legend]="linechartLegend"
            [type]="'line'">
          </canvas>

And the signalRService works well as I get the result like this:

However, in the component, I set up signalRService.finaltime for the source of the x axis (time axis) like this
`

export class LineSpeedChartComponent implements OnInit {
    public linechartdata:ChartData = {
      datasets: [{
        label:"Ampere",
        data: [{x:+this.signalRService.finaltime,y:12}]
    }]
    };

    public linechartOptions: ChartOptions = {

      responsive: true,
      scales: {
        x: {
          type: 'time',
          min: Date.now() - (24 * 60 * 60 * 1000),
          max: Date.now() + (24 * 60 * 60 * 1000),
          ticks: {
            source: 'auto',
          },
          time:{
            unit: 'hour', //second
            displayFormats:{
              hour: "dd/MM/yyyy HH:mm:ss" //second = 'dd/MM/yyyy HH:mm:ss'
            },
            tooltipFormat: "dd/MM/yyyy HH:mm:ss",
          },
          adapters: {
            date: {
              locale: vi,
            },
        },
      },
        y: {
            min: 0,

        },
      }
  };

And no data is showed in the chart, including the data of the y axis. But if I replace this.signalRService.finaltime with a specific value, it works fine.

Please send help !!!


问:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery in SQL Server
One of our projects has to be moved from Oracle to SQL server. I converted one of the queries from Oracle to SQL Server and I am receiving the error below now (the query works in Oracle).

It is complaining about every column that has SUM in it. Would anyone know how to correct it, how to modify the query so it work also in SQL Server?

Msg 130, Level 15, State 1, Line 3

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

Here is the converted query for SQL Server that is having the issues with all columns that contain SUM:

```<code>SELECT
    epoch, sourceID,
    SUM(CASE (SELECT classification
              FROM CLASSIFICATION_lookup cl
              WHERE cl.Classification_Id = p.Proposal_ID)
            WHEN 'Class_A' THEN Estimate
            ELSE 0
         END) "Class_A" ,
    SUM(CASE ISNULL((SELECT classification
                     FROM CLASSIFICATION_lookup cl
                     WHERE cl.Classification_Id = p.Proposal_ID), 'InvalidCls')
            WHEN 'NonValid' THEN Estimate ELSE 0
         END) "NonValid" ,
    SUM(CASE (SELECT classification
              FROM CLASSIFICATION_lookup cl
              WHERE cl.Classification_Id = p.Proposal_ID)
           WHEN 'Class_A'
               THEN 0
               ELSE (CASE ISNULL((SELECT classification
                                  FROM CLASSIFICATION_lookup cl
                                  WHERE cl.Classification_Id = tr.TimeWorkTypeID), 'InvalidCls')
                          WHEN 'NonValid'
                              THEN 0
                          WHEN 'InvalidCls'
                              THEN Estimate
                          ELSE Estimate
                      END)
        END) "Authorized" ,
    SUM(CASE (SELECT classification
              FROM CLASSIFICATION_lookup cl
              WHERE cl.Classification_Id = tr.TimeWorkTypeID)
           WHEN 'General' THEN Estimate ELSE 0
        END) "General"
FROM
    TimeReports TR
LEFT OUTER JOIN
    Proposals p ON tr.TimeWorkTypeID = p.ProposalCode
WHERE
    Accepted = 'Y'
    AND tr.epoch BETWEEN 100 AND 300
GROUP BY
    tr.epoch, tr.sourceID;
</code>```

Here is the original Oracle query for reference:

```<code>SELECT
    epoch, sourceID,
    SUM(DECODE( (SELECT classification FROM CLASSIFICATION_lookup cl WHERE cl.Classification_Id = p.Proposal_ID), 'Class_A',   Estimate, 0) )          "Class_A" ,
    SUM(DECODE ( NVL((SELECT classification FROM CLASSIFICATION_lookup cl WHERE cl.Classification_Id = p.Proposal_ID),'InvalidCls' ), 'NonValid', Estimate, 0) )          "NonValid" ,
    SUM(DECODE ( (SELECT classification FROM CLASSIFICATION_lookup cl WHERE cl.Classification_Id = p.Proposal_ID), 'Class_A', 0,
                (DECODE( NVL((SELECT classification FROM CLASSIFICATION_lookup cl WHERE cl.Classification_Id = tr.TimeWorkTypeID),'InvalidCls'),
                'NonValid', 0,
                'InvalidCls', Estimate, Estimate) ) )   )           "Authorized" ,
     SUM(DECODE ( (SELECT classification FROM CLASSIFICATION_lookup cl WHERE cl.Classification_Id = tr.TimeWorkTypeID),'General', Estimate, 0 ) )                "General"
FROM
    TimeReports TR, Proposals p
WHERE Accepted = 'Y'
AND tr.epoch between 100 AND 300
AND tr.TimeWorkTypeID = p.ProposalCode(+)
GROUP BY tr.epoch, tr.sourceID;
</code>```

I tried removing columns containing SUM and the query works, of course (but we need those columns).

I am not sure what the best approach would be, I was thinking if converting those subqueries into functions would work, but I am afraid that it would be huge performance hit since the query returns several millions records (it is part of scheduled job to copy data).

The SQL Server is running version 2019 if it makes a difference.

I appreciate any help, tips, ideas etc.!

Body:
One of our projects has to be moved from Oracle to SQL server. I converted one of the queries from Oracle to SQL Server and I am receiving the error below now (the query works in Oracle).

It is complaining about every column that has SUM in it. Would anyone know how to correct it, how to modify the query so it work also in SQL Server?

Msg 130, Level 15, State 1, Line 3

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

Here is the converted query for SQL Server that is having the issues with all columns that contain SUM:

SELECT
    epoch, sourceID,
    SUM(CASE (SELECT classification
              FROM CLASSIFICATION_lookup cl
              WHERE cl.Classification_Id = p.Proposal_ID)
            WHEN 'Class_A' THEN Estimate
            ELSE 0
         END) "Class_A" ,
    SUM(CASE ISNULL((SELECT classification
                     FROM CLASSIFICATION_lookup cl
                     WHERE cl.Classification_Id = p.Proposal_ID), 'InvalidCls')
            WHEN 'NonValid' THEN Estimate ELSE 0
         END) "NonValid" ,
    SUM(CASE (SELECT classification
              FROM CLASSIFICATION_lookup cl
              WHERE cl.Classification_Id = p.Proposal_ID)
           WHEN 'Class_A'
               THEN 0
               ELSE (CASE ISNULL((SELECT classification
                                  FROM CLASSIFICATION_lookup cl
                                  WHERE cl.Classification_Id = tr.TimeWorkTypeID), 'InvalidCls')
                          WHEN 'NonValid'
                              THEN 0
                          WHEN 'InvalidCls'
                              THEN Estimate
                          ELSE Estimate
                      END)
        END) "Authorized" ,
    SUM(CASE (SELECT classification
              FROM CLASSIFICATION_lookup cl
              WHERE cl.Classification_Id = tr.TimeWorkTypeID)
           WHEN 'General' THEN Estimate ELSE 0
        END) "General"
FROM
    TimeReports TR
LEFT OUTER JOIN
    Proposals p ON tr.TimeWorkTypeID = p.ProposalCode
WHERE
    Accepted = 'Y'
    AND tr.epoch BETWEEN 100 AND 300
GROUP BY
    tr.epoch, tr.sourceID;

Here is the original Oracle query for reference:

SELECT
    epoch, sourceID,
    SUM(DECODE( (SELECT classification FROM CLASSIFICATION_lookup cl WHERE cl.Classification_Id = p.Proposal_ID), 'Class_A',   Estimate, 0) )          "Class_A" ,
    SUM(DECODE ( NVL((SELECT classification FROM CLASSIFICATION_lookup cl WHERE cl.Classification_Id = p.Proposal_ID),'InvalidCls' ), 'NonValid', Estimate, 0) )          "NonValid" ,
    SUM(DECODE ( (SELECT classification FROM CLASSIFICATION_lookup cl WHERE cl.Classification_Id = p.Proposal_ID), 'Class_A', 0,
                (DECODE( NVL((SELECT classification FROM CLASSIFICATION_lookup cl WHERE cl.Classification_Id = tr.TimeWorkTypeID),'InvalidCls'),
                'NonValid', 0,
                'InvalidCls', Estimate, Estimate) ) )   )           "Authorized" ,
     SUM(DECODE ( (SELECT classification FROM CLASSIFICATION_lookup cl WHERE cl.Classification_Id = tr.TimeWorkTypeID),'General', Estimate, 0 ) )                "General"
FROM
    TimeReports TR, Proposals p
WHERE Accepted = 'Y'
AND tr.epoch between 100 AND 300
AND tr.TimeWorkTypeID = p.ProposalCode(+)
GROUP BY tr.epoch, tr.sourceID;

I tried removing columns containing SUM and the query works, of course (but we need those columns).

I am not sure what the best approach would be, I was thinking if converting those subqueries into functions would work, but I am afraid that it would be huge performance hit since the query returns several millions records (it is part of scheduled job to copy data).

The SQL Server is running version 2019 if it makes a difference.

I appreciate any help, tips, ideas etc.!


问:
custom object detection with tensorflow lite model maker
i  tried object detection with tensor flow lite model maker but am not able to build good model i mean good accuracy...

my theme of the project as following link

https://www.youtube.com/watch?v=gaAhAnN0FOk&ab_channel=ThomGibson

in above video link each card has 4 unique shapes and associated with A,B,C,D Respectively...

So what kind of approach i need to go with object detection or something else..
please look into this once..

cards link
https://assets.plickers.com/plickers-cards/PlickersCards_2up.pdf

tried detecting cards with 4 direction of cards


问:
OPENSSL ERROR C++ 17 error:80000005:system library::Input/output error when passing path to client cert file
I am trying to create a TLS GUI Client using c++/WinRT.
The TLS Client I am using is https://github.com/embeddedmz/socket-cpp

For some reason when I try to connect to the socket server the connection fails when using the BlankApp(C++/WinRT Template) and no errors thrown.

When I test it with the blank console application, it works. Everything is the same across the board except the one being a console application and the other being a BlankApp(C++/WinRT Template) application.

Any ideas would be appreciated.

C++ Version: IS0 C++ 17 Standard

**Update 12/16/2022 **

I finally got OPENSSL to print errors to Visual Studio Debugger.
I have the following error.

Code that fails

```<code>
int e = SSL_CTX_use_certificate_file(m_SSLConnectSocket.m_pCTXSSL, m_strSSLCertFile.c_str(), SSL_FILETYPE_PEM)

</code>```

That function should return a 1 but returns -2147483643 and this is the error in I get from ERR_error_string method:
error:80000005:system library::Input/output error

Body:
I am trying to create a TLS GUI Client using c++/WinRT.
The TLS Client I am using is https://github.com/embeddedmz/socket-cpp

For some reason when I try to connect to the socket server the connection fails when using the BlankApp(C++/WinRT Template) and no errors thrown.

When I test it with the blank console application, it works. Everything is the same across the board except the one being a console application and the other being a BlankApp(C++/WinRT Template) application.

Any ideas would be appreciated.

C++ Version: IS0 C++ 17 Standard

**Update 12/16/2022 **

I finally got OPENSSL to print errors to Visual Studio Debugger.
I have the following error.

Code that fails

int e = SSL_CTX_use_certificate_file(m_SSLConnectSocket.m_pCTXSSL, m_strSSLCertFile.c_str(), SSL_FILETYPE_PEM)

That function should return a 1 but returns -2147483643 and this is the error in I get from ERR_error_string method:
error:80000005:system library::Input/output error


问:
Custome legend for antd pie chart
currently, I have a pie chart which is display the data like this
(https://i.stack.imgur.com/E1geb.png)

this is my config now
(https://i.stack.imgur.com/61cP6.png)
what I want is to display the value of each piece next to label

Title: Custome legend for antd pie chart


问:
correct way to catch error from backend in a async function
The response.json() from a backend is an data object which can be if request is OK:

```<code>{
    "items": [
        {
            "id": "p2",
            "name": "My Second Book",
            "price": 8.98,
            "quantity": 2,
            "totalPrice": 17.96
        },
        {
            "id": "p1",
            "name": "My First Book",
            "price": 6.99,
            "quantity": 3,
            "totalPrice": 20.97
        }
    ],
    "totalQuantity": 5
}

</code>```

Or if  there any error, it responses with this object:

```<code>{
    "code": 404,
    "description": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.",
    "message": "Not Found"
}
</code>```

The function for fetching request exports dispatch result.

```<code>export function fetchCartData() {
  return async (dispatch) => {
    const fetchData = async () => {
      const response = await fetch("http://127.0.0.1:5000/api/cart");
      const result = await response.json();
      if (!response.ok) {
        console.log(result);
        throw new Error(result);
      } else {
        console.log(result);
        return result;
      }
    };
    try {
      const cartData = await fetchData();
      dispatch(cartActions.replaceCart(cartData));
    } catch (error) {
      // console.log(error);
      dispatch(
        uiActions.showNotification({
          status: "error",
          title: "Error!",
          message: "Fetching cart data failed!",
        })
      );
    }
  };
}
</code>```

The goal of fetchData function nested is sending GET request to API, store OK or not OK response in constant result and pass it to try-catch for handle response or error.

if response is OK in fetchData function, try dispatch it, but when response is not OK the object result brings information such message: Not Found which I want to pass to catch(error) for replacing in message into 'dispatch(uiActions.showNotification({message:` key.

I tried returning result when response is not OK but it still does not pass object to catch, for example:

```<code>if (!response.ok) {
   console.log(result);
   return result;
   }
</code>```

Body:
The response.json() from a backend is an data object which can be if request is OK:

{
    "items": [
        {
            "id": "p2",
            "name": "My Second Book",
            "price": 8.98,
            "quantity": 2,
            "totalPrice": 17.96
        },
        {
            "id": "p1",
            "name": "My First Book",
            "price": 6.99,
            "quantity": 3,
            "totalPrice": 20.97
        }
    ],
    "totalQuantity": 5
}

Or if  there any error, it responses with this object:

{
    "code": 404,
    "description": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.",
    "message": "Not Found"
}

The function for fetching request exports dispatch result.

export function fetchCartData() {
  return async (dispatch) => {
    const fetchData = async () => {
      const response = await fetch("http://127.0.0.1:5000/api/cart");
      const result = await response.json();
      if (!response.ok) {
        console.log(result);
        throw new Error(result);
      } else {
        console.log(result);
        return result;
      }
    };
    try {
      const cartData = await fetchData();
      dispatch(cartActions.replaceCart(cartData));
    } catch (error) {
      // console.log(error);
      dispatch(
        uiActions.showNotification({
          status: "error",
          title: "Error!",
          message: "Fetching cart data failed!",
        })
      );
    }
  };
}

The goal of fetchData function nested is sending GET request to API, store OK or not OK response in constant result and pass it to try-catch for handle response or error.

if response is OK in fetchData function, try dispatch it, but when response is not OK the object result brings information such message: Not Found which I want to pass to catch(error) for replacing in message into 'dispatch(uiActions.showNotification({message:` key.

I tried returning result when response is not OK but it still does not pass object to catch, for example:

if (!response.ok) {
   console.log(result);
   return result;
   }