问:
Identify free faces on each side in salome with python

I have a cubic structure filled with voronoi regions. And this is the image with all free faces. I want to computationally determine the faces on each side individually.

Thanks in advance.

```<code>geompy.GetFreeFacesIDs(partition_all_volumes)
# [34, 42, 63, 70, 78, 80, 108, 121, 124, 129, 132, 154, 161, 166, 169, 172]
</code>```

I can obtain ID of all the free faces. But I want to group them by side. say I want to group them by only faces from one side faces. How can I do that. Can we really do that using python? I want to computationally determine the faces on the right xy plane. It would be great if some body shares a way to do it. I guess If I find out the corner vertices of each shape I can determine on which plane it is on..that should be ok too . how do I obtain those vertices?.

Body:
I have a cubic structure filled with voronoi regions. And this is the image with all free faces. I want to computationally determine the faces on each side individually.

Thanks in advance.

geompy.GetFreeFacesIDs(partition_all_volumes)
# [34, 42, 63, 70, 78, 80, 108, 121, 124, 129, 132, 154, 161, 166, 169, 172]

I can obtain ID of all the free faces. But I want to group them by side. say I want to group them by only faces from one side faces. How can I do that. Can we really do that using python? I want to computationally determine the faces on the right xy plane. It would be great if some body shares a way to do it. I guess If I find out the corner vertices of each shape I can determine on which plane it is on..that should be ok too . how do I obtain those vertices?.


来源: stackexchange

问:
Dynamic parameter to onelogin service
I am new to onelogin service.

I want to know any possibilities to pass a dynamic parameter value to relay state URL in onelogin.

This is my current situation.

User tries to login to "sampleproduct.com"

"sampleproduct.com" redirects to onelogin console (no parameters are passed from "sampleproduct.com")

User logs in to portal

Then user click on the application configured in the onelogin service

After clicking the application a call back will reach at "sampleproduct.com"

This is what I am looking for.

User tries to log in to "sampleproduct.com"

"sampleproduct.com" redirects to onelogin console with a parameter with value [like subdomain.onelogin.com?dateVal=5844588]

After succesfully logging in to onelogin, a callback will reach "sampleproduct.com" with "dateVal=5844588"

Please note "dateVal" parameter value will change. That means the value of the "dateVal" parameter is dynamic and this parameter is passed from "sampleproduct.com"

ContentLicense: CC BY-SA 4.0

Title: Dynamic parameter to onelogin service


问:
Error while installing Swift Package - unable to access /Package.swift
I recently added a Swift Package (IQKeyboardManager) from GitHub on to my xcworkspace Project. The Package.swift file is in the root folder of the repository. However, I got an error: /Package.swift cannot be accessed

Unable to resolve the error.

How do I fix it?

How do I remove Swift packages?

I tried updating the package a number of time, without luck. As I am not able to delete the package from the Project, I am not even able to run the project now.


问:
How to Enter Text and Db value in a ternary operator in certificate.pug file
I need Text and value in same line in certificate.pug file as a ternary operator

I tried

td.border-top-1.border-bottom-0(class="wrapword" colspan='15')
b
i= (10 == '10' ? +'Text Welds'+ thicknessRQValueMin - buttThicknessRQValueMax; +'Fillet Welds'+ filletThicknessRQValueMin - filletThicknessRQValueMax : +'Butt Welds'+ buttThicknessRQValueMin - buttThicknessRQValueMax)

I expect the coorect line


问:
how to install tookenizers for paraphrasing in python
tokenizers or transformers not install in python 3.11.1. I am worked on paraphrasing in python 3.11.1. Please help me for this error:

Error:
 ERROR: Failed building wheel for tokenizers
Failed to build tokenizers
ERROR: Could not build wheels for tokenizers, which is required to install pyproject.toml-based projects
```


问:
databricks on AWS are not printing the value when run as a job
When I tried to run code as job in databricks with multiple print command ,job running
successful without executing print commands and getting the below error.

```<code>Failed to fetch the result.Retry
</code>```

Body:
When I tried to run code as job in databricks with multiple print command ,job running
successful without executing print commands and getting the below error.

Failed to fetch the result.Retry


问:
Encountering SerializationException while using custom EntityManger with physicalNamingStrategy
I have my entity classes and jpaRepos written in a commons module which I'm trying to use across various micro-services. I was able to use them in all the services without any issue except for one micro-service, which has custom entityManager

Issue while using these classes
First issue I encountered was the fields in the entity classes were not getting converted from camelcase to snakecase then I have introduced these properties

"hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName() "hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName()

this resolved my first issue. Now after introducing these properties. I'm starting to face deserialization error

```<code>org.hibernate.type.SerializationException: could not deserialize
    at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:243)
    at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:287)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:138)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:113)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:29)
    at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:60)
    at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:243)
    at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:329)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3131)
    at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.loadFromResultSet(EntityReferenceInitializerImpl.java:342)
    at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.hydrateEntityState(EntityReferenceInitializerImpl.java:269)
    at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.readRow(AbstractRowReader.java:102)
    at org.hibernate.loader.plan.exec.internal.EntityLoadQueryDetails$EntityLoaderRowReader.readRow(EntityLoadQueryDetails.java:288)
    at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractRows(ResultSetProcessorImpl.java:157)
    at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:94)
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:105)
    at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:285)
    at org.hibernate.persister.entity.AbstractEntityPersister.doLoad(AbstractEntityPersister.java:4437)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4427)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:576)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:544)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:208)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:332)
    at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:108)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:74)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:110)
    at org.hibernate.internal.SessionImpl.fireLoadNoChecks(SessionImpl.java:1186)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1175)
    at org.hibernate.internal.SessionImpl.access$2100(SessionImpl.java:193)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2786)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.lambda$load$1(SessionImpl.java:2767)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.perform(SessionImpl.java:2723)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2767)
    at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3322)
    at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3289)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
    at com.sun.proxy.$Proxy283.find(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findById(SimpleJpaRepository.java:310)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)
</code>```

I can't touch my entity classes as it is being used at multiple places. And there is no issue there.

my entityManger

```<code>@Bean(name = "entityManagerFactory")
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier(value = "dataSource") DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
    entityManager.setDataSource(dataSource);
    entityManager.setPackagesToScan(ApplicationConstants.CUSTOM_CONTROL_ENTITY_BASE_PACKAGE, ApplicationConstants.ENTITY_BASE_PACKAGE_CONN_ORACLE,ApplicationConstants.APPLICATION_BASE_BACKAGE_USER);
    HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
    entityManager.setJpaVendorAdapter(hibernateJpaVendorAdapter);

    final Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("hibernate.dialect", dialect);
    properties.put("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());
    properties.put("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());
    entityManager.setJpaPropertyMap(properties);

    return entityManager;
}
</code>```

spring boot version : 2.X
hibernate version: 5.4.32.Final

Body:
I have my entity classes and jpaRepos written in a commons module which I'm trying to use across various micro-services. I was able to use them in all the services without any issue except for one micro-service, which has custom entityManager

Issue while using these classes
First issue I encountered was the fields in the entity classes were not getting converted from camelcase to snakecase then I have introduced these properties

"hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName() "hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName()

this resolved my first issue. Now after introducing these properties. I'm starting to face deserialization error

org.hibernate.type.SerializationException: could not deserialize
    at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:243)
    at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:287)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:138)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:113)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:29)
    at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:60)
    at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:243)
    at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:329)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3131)
    at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.loadFromResultSet(EntityReferenceInitializerImpl.java:342)
    at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.hydrateEntityState(EntityReferenceInitializerImpl.java:269)
    at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.readRow(AbstractRowReader.java:102)
    at org.hibernate.loader.plan.exec.internal.EntityLoadQueryDetails$EntityLoaderRowReader.readRow(EntityLoadQueryDetails.java:288)
    at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractRows(ResultSetProcessorImpl.java:157)
    at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:94)
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:105)
    at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:285)
    at org.hibernate.persister.entity.AbstractEntityPersister.doLoad(AbstractEntityPersister.java:4437)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4427)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:576)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:544)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:208)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:332)
    at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:108)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:74)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:110)
    at org.hibernate.internal.SessionImpl.fireLoadNoChecks(SessionImpl.java:1186)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1175)
    at org.hibernate.internal.SessionImpl.access$2100(SessionImpl.java:193)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2786)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.lambda$load$1(SessionImpl.java:2767)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.perform(SessionImpl.java:2723)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2767)
    at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3322)
    at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3289)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
    at com.sun.proxy.$Proxy283.find(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findById(SimpleJpaRepository.java:310)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)

I can't touch my entity classes as it is being used at multiple places. And there is no issue there.

my entityManger

@Bean(name = "entityManagerFactory")
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier(value = "dataSource") DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
    entityManager.setDataSource(dataSource);
    entityManager.setPackagesToScan(ApplicationConstants.CUSTOM_CONTROL_ENTITY_BASE_PACKAGE, ApplicationConstants.ENTITY_BASE_PACKAGE_CONN_ORACLE,ApplicationConstants.APPLICATION_BASE_BACKAGE_USER);
    HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
    entityManager.setJpaVendorAdapter(hibernateJpaVendorAdapter);

    final Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("hibernate.dialect", dialect);
    properties.put("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());
    properties.put("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());
    entityManager.setJpaPropertyMap(properties);

    return entityManager;
}

spring boot version : 2.X
hibernate version: 5.4.32.Final


问:
Repeatative crash for viewpager after release
I just released a new version of my app on play store, I observed that I am constantly getting an crash for few users related to viewpager in my Activity, my app targetSdkVersion is 33

```<code>Fatal Exception: java.lang.IllegalStateException
FragmentManager is already executing transactions
    androidx.fragment.app.FragmentManager.ensureExecReady (FragmentManager.java:1695)
androidx.fragment.app.FragmentManager.execSingleAction (FragmentManager.java:1725)
androidx.fragment.app.BackStackRecord.commitNow (BackStackRecord.java:317)
androidx.viewpager2.adapter.FragmentStateAdapter$FragmentMaxLifecycleEnforcer.updateFragmentMaxLifecycle (FragmentStateAdapter.java:752)
androidx.viewpager2.adapter.FragmentStateAdapter$FragmentMaxLifecycleEnforcer$3.onStateChanged (FragmentStateAdapter.java:678)
androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent (LifecycleRegistry.java:360)
androidx.lifecycle.LifecycleRegistry.forwardPass (LifecycleRegistry.java:271)
androidx.lifecycle.LifecycleRegistry.sync (LifecycleRegistry.java:313)
androidx.lifecycle.LifecycleRegistry.moveToState (LifecycleRegistry.java:151)
androidx.lifecycle.LifecycleRegistry.handleLifecycleEvent (LifecycleRegistry.java:134)
androidx.fragment.app.Fragment.performStart (Fragment.java:3167)
androidx.fragment.app.FragmentStateManager.start (FragmentStateManager.java:588)
androidx.fragment.app.FragmentStateManager.moveToExpectedState (FragmentStateManager.java:279)
androidx.fragment.app.FragmentStore.moveToExpectedState (FragmentStore.java:113)
androidx.fragment.app.FragmentManager.moveToState (FragmentManager.java:1433)
androidx.fragment.app.FragmentManager.dispatchStateChange (FragmentManager.java:2977)
androidx.fragment.app.FragmentManager.dispatchStart (FragmentManager.java:2902)
androidx.fragment.app.FragmentController.dispatchStart (FragmentController.java:274)
androidx.fragment.app.FragmentActivity.onStart (FragmentActivity.java:359)
androidx.appcompat.app.AppCompatActivity.onStart (AppCompatActivity.java:248)
android.app.Instrumentation.callActivityOnStart (Instrumentation.java:1432)
android.app.Activity.performStart (Activity.java:7995)
</code>```

Wherever i used viewpager2 it's working fine, and all this crashes just started after the new release.

Libraries:

```<code>implementation "androidx.fragment:fragment-ktx:1.5.5"
implementation "androidx.activity:activity-ktx:1.6.1"
</code>```

I tried and found that it is suggested to use childFragmentManager for my adapter, but since my viewpager is in Activity I am using supportFragmentManager.

Can anyone please help me with this issue.

Body:
I just released a new version of my app on play store, I observed that I am constantly getting an crash for few users related to viewpager in my Activity, my app targetSdkVersion is 33

Fatal Exception: java.lang.IllegalStateException
FragmentManager is already executing transactions
    androidx.fragment.app.FragmentManager.ensureExecReady (FragmentManager.java:1695)
androidx.fragment.app.FragmentManager.execSingleAction (FragmentManager.java:1725)
androidx.fragment.app.BackStackRecord.commitNow (BackStackRecord.java:317)
androidx.viewpager2.adapter.FragmentStateAdapter$FragmentMaxLifecycleEnforcer.updateFragmentMaxLifecycle (FragmentStateAdapter.java:752)
androidx.viewpager2.adapter.FragmentStateAdapter$FragmentMaxLifecycleEnforcer$3.onStateChanged (FragmentStateAdapter.java:678)
androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent (LifecycleRegistry.java:360)
androidx.lifecycle.LifecycleRegistry.forwardPass (LifecycleRegistry.java:271)
androidx.lifecycle.LifecycleRegistry.sync (LifecycleRegistry.java:313)
androidx.lifecycle.LifecycleRegistry.moveToState (LifecycleRegistry.java:151)
androidx.lifecycle.LifecycleRegistry.handleLifecycleEvent (LifecycleRegistry.java:134)
androidx.fragment.app.Fragment.performStart (Fragment.java:3167)
androidx.fragment.app.FragmentStateManager.start (FragmentStateManager.java:588)
androidx.fragment.app.FragmentStateManager.moveToExpectedState (FragmentStateManager.java:279)
androidx.fragment.app.FragmentStore.moveToExpectedState (FragmentStore.java:113)
androidx.fragment.app.FragmentManager.moveToState (FragmentManager.java:1433)
androidx.fragment.app.FragmentManager.dispatchStateChange (FragmentManager.java:2977)
androidx.fragment.app.FragmentManager.dispatchStart (FragmentManager.java:2902)
androidx.fragment.app.FragmentController.dispatchStart (FragmentController.java:274)
androidx.fragment.app.FragmentActivity.onStart (FragmentActivity.java:359)
androidx.appcompat.app.AppCompatActivity.onStart (AppCompatActivity.java:248)
android.app.Instrumentation.callActivityOnStart (Instrumentation.java:1432)
android.app.Activity.performStart (Activity.java:7995)

Wherever i used viewpager2 it's working fine, and all this crashes just started after the new release.

Libraries:

implementation "androidx.fragment:fragment-ktx:1.5.5"
implementation "androidx.activity:activity-ktx:1.6.1"

I tried and found that it is suggested to use childFragmentManager for my adapter, but since my viewpager is in Activity I am using supportFragmentManager.

Can anyone please help me with this issue.


问:
How to create a file containing a set of entries from a larger file in UNIX?
I'm working with a large fasta file, and want to create a file containing only the entries for a specific genus. grep alone is not working for this as it only includes the line containing the genus name, and I also want to include the protein code.

I tried

```<code>grep -i genus file.fasta > genus.txt

</code>```

This did work but created a file with only the first line of each data entry, thus not including the protein sequence. I also tried

```<code>grep -iC6 genus file.fasta > genus.txt
</code>```

This did not work as not all the sequences are the same length. Appreciate any help. I'm using Cygwin if it makes any difference.

Body:
I'm working with a large fasta file, and want to create a file containing only the entries for a specific genus. grep alone is not working for this as it only includes the line containing the genus name, and I also want to include the protein code.

I tried

grep -i genus file.fasta > genus.txt

This did work but created a file with only the first line of each data entry, thus not including the protein sequence. I also tried

grep -iC6 genus file.fasta > genus.txt

This did not work as not all the sequences are the same length. Appreciate any help. I'm using Cygwin if it makes any difference.


问:
How to read/write "binary" files form Hadoop/HDFS using RUBY gem ganapati
I am using the Ganapati Ruby gem to read/write files from a Hadoop HDFS cluster as pointed out in this question - How to write and read files in/from Hadoop HDFS using Ruby?

But this works properly only for text files. How to make it work for binary files (images, pdf, doc, xls, etc)?
I have already edited the client.rb file in the gem code to use the 'b' flag as required by Ruby for binary files in Kernel.open(). The original gem was not using this flag.
But this still does not help.

Thanks for your suggestions.

ContentLicense: CC BY-SA 3.0


问:
How can i control android keyboard in flutter inAppWebView and react?

I have a trouble with controlling the enter key with using InAppWebView in flutter.
there are issue with inputs which automatically move to next input with android keyboard.
i tried to make blur in react code with 'OnkeyDownCature' or 'OnkeyDown'. it works well.
however, the android enter key is different when there are next input like images above.
So, i want to change the android keyboard with react, js side.

```<code><InputBox isFocus={isFocus} disabledProp={disabledProp} {...props}>
                <Input
                    type={currentType}
                    ref={ref}
                    // onKeyDownCapture={onKeyDownCapture}
                    onKeyDownCapture={(e) => {
                        if(e.key === 'Enter'){
                            (document.activeElement as HTMLElement).blur();
                            e.stopPropagation();
                        }
                }}
</code>```

how can i control the android keyboard from react side through the InAppWebView in Flutter.

Body:
I have a trouble with controlling the enter key with using InAppWebView in flutter.
there are issue with inputs which automatically move to next input with android keyboard.
i tried to make blur in react code with 'OnkeyDownCature' or 'OnkeyDown'. it works well.
however, the android enter key is different when there are next input like images above.
So, i want to change the android keyboard with react, js side.

<InputBox isFocus={isFocus} disabledProp={disabledProp} {...props}>
                <Input
                    type={currentType}
                    ref={ref}
                    // onKeyDownCapture={onKeyDownCapture}
                    onKeyDownCapture={(e) => {
                        if(e.key === 'Enter'){
                            (document.activeElement as HTMLElement).blur();
                            e.stopPropagation();
                        }
                }}

how can i control the android keyboard from react side through the InAppWebView in Flutter.


问:
how to pass cloudwatch logs to lambda in terraform
I have created two lambda functions. now i wanted to pass all the cloudwatch logs from first lambda to second lambda. i have created new log group name and subscription filter to pass the cloudwatch logs to second lambda.

I am not sure if this configuration needs to be added any resource.

```<code>resource "aws_lambda_function" "audit-logs" {
  filename         = var.audit_filename
  function_name    = var.audit_function
  source_code_hash = filebase64sha256(var.audit_filename)
  role             = module.lambda_role.arn
  handler          = "cloudwatch.lambda_handler"
  runtime          = "python3.9"
  timeout          = 200
  description      = "audit logs"
  depends_on       = [module.lambda_role, module.security_group]
}

resource "aws_cloudwatch_log_group" "splunk_cloudwatch_loggroup" {
  name = "/aws/lambda/audit_logs"
}

resource "aws_lambda_permission" "allow_cloudwatch_for_splunk" {
  statement_id  = "AllowExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.splunk-logs.arn
  principal     = "logs.amazonaws.com" #"logs.region.amazonaws.com"
  source_arn    = "${aws_cloudwatch_log_group.splunk_cloudwatch_loggroup.arn}:*"
}

resource "aws_cloudwatch_log_subscription_filter" "splunk_cloudwatch_trigger" {
  depends_on      = [aws_lambda_permission.allow_cloudwatch_for_splunk]
  destination_arn = aws_lambda_function.splunk-logs.arn
  filter_pattern  = ""
  log_group_name  = aws_cloudwatch_log_group.splunk_cloudwatch_loggroup.name
  name            = "splunk_filter"
}

# splunk logs lambda function
resource "aws_lambda_function" "splunk-logs" {
  filename         = var.splunk_filename
  function_name    = var.splunk_function
  source_code_hash = filebase64sha256(var.splunk_filename)
  role             = module.lambda_role.arn
  handler          = "${var.splunk_handler}.handler"
  runtime          = "python3.9"
  timeout          = 200
  description      = "audit logs"
  depends_on       = [module.lambda_role, module.security_group]
}
</code>```

how can i pass all the logs from first lambda to newly created log group ? any help ?

Body:
I have created two lambda functions. now i wanted to pass all the cloudwatch logs from first lambda to second lambda. i have created new log group name and subscription filter to pass the cloudwatch logs to second lambda.

I am not sure if this configuration needs to be added any resource.

resource "aws_lambda_function" "audit-logs" {
  filename         = var.audit_filename
  function_name    = var.audit_function
  source_code_hash = filebase64sha256(var.audit_filename)
  role             = module.lambda_role.arn
  handler          = "cloudwatch.lambda_handler"
  runtime          = "python3.9"
  timeout          = 200
  description      = "audit logs"
  depends_on       = [module.lambda_role, module.security_group]
}

resource "aws_cloudwatch_log_group" "splunk_cloudwatch_loggroup" {
  name = "/aws/lambda/audit_logs"
}

resource "aws_lambda_permission" "allow_cloudwatch_for_splunk" {
  statement_id  = "AllowExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.splunk-logs.arn
  principal     = "logs.amazonaws.com" #"logs.region.amazonaws.com"
  source_arn    = "${aws_cloudwatch_log_group.splunk_cloudwatch_loggroup.arn}:*"
}

resource "aws_cloudwatch_log_subscription_filter" "splunk_cloudwatch_trigger" {
  depends_on      = [aws_lambda_permission.allow_cloudwatch_for_splunk]
  destination_arn = aws_lambda_function.splunk-logs.arn
  filter_pattern  = ""
  log_group_name  = aws_cloudwatch_log_group.splunk_cloudwatch_loggroup.name
  name            = "splunk_filter"
}

# splunk logs lambda function
resource "aws_lambda_function" "splunk-logs" {
  filename         = var.splunk_filename
  function_name    = var.splunk_function
  source_code_hash = filebase64sha256(var.splunk_filename)
  role             = module.lambda_role.arn
  handler          = "${var.splunk_handler}.handler"
  runtime          = "python3.9"
  timeout          = 200
  description      = "audit logs"
  depends_on       = [module.lambda_role, module.security_group]
}

how can i pass all the logs from first lambda to newly created log group ? any help ?


问:
SSL Certificate Folder Path Not Found in react.js Application
`I have SSL certificate file for react application. i have added those certificate is package.json but pem and key path not found. i have marked details in image. image-details

Here i need help how specify certificate path `


问:
How to Subscribe to Platform Event Notifications with React Native
I am developing a mobile application with React Native. With this application, I connect to salesforce and make transactions.

I created Platform Events on Salesforce side and I want React Native Component to subscribe to it.

I can't use lightning/empApi or CometD because I don't code web. According to the document, my only option is Pub/Sub API.

I tried to pull it directly with FETCH but with no result.

import {View, Text} from 'react-native';
import React, { useEffect, useState } from 'react';
import { Force, oauth } from 'react-native-force';

function History() {
    const [session, setSession] = useState()
    const eventName = "Test_PE__e";
    const replayId = -1;
    const [subscription, setSubscription] = React.useState();

    useEffect(() => {
        oauth.getAuthCredentials(
            (data) => console.log(data), // already logged in
            () => {
                oauth.authenticate(
                    () => setSession(data),
                    (error) => console.log('Failed to authenticate:' + error)
                );
            });
    },[]);

    return (
      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
            <Text> Subscribed to {eventName} </Text>
        </View>
    );

    async function setPEvents(session) {
        const headers = new Headers({
            'Authorization': `Bearer ${session.accessToken}`,
            'Content-Type': 'application/json'
        });
        const body = {
            "event": `/event/${eventName}`,
            "replayId": replayId
        };
        const url = `${session.instanceUrl}/services/data/v57.0/event/${eventName}/subscriptions`;
        const requestOptions = {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(body)
        };
        const resp = await fetch(url, requestOptions)
            .then(async (response) => {
                console.log(response);
                return await response.json();
            })
            .catch(error => console.log('Error:', error));
        setSubscription(resp);
        console.log("FIRATTT");
        console.log("Result:",resp);
    }
}

export default History;

```

What can I do to subscribe?
Or how can I use the SalesForce Pub/Sub API in React Native?

Body:
I am developing a mobile application with React Native. With this application, I connect to salesforce and make transactions.

I created Platform Events on Salesforce side and I want React Native Component to subscribe to it.

I can't use lightning/empApi or CometD because I don't code web. According to the document, my only option is Pub/Sub API.

I tried to pull it directly with FETCH but with no result.

import {View, Text} from 'react-native';
import React, { useEffect, useState } from 'react';
import { Force, oauth } from 'react-native-force';

function History() {
    const [session, setSession] = useState()
    const eventName = "Test_PE__e";
    const replayId = -1;
    const [subscription, setSubscription] = React.useState();

    useEffect(() => {
        oauth.getAuthCredentials(
            (data) => console.log(data), // already logged in
            () => {
                oauth.authenticate(
                    () => setSession(data),
                    (error) => console.log('Failed to authenticate:' + error)
                );
            });
    },[]);

    return (
      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
            <Text> Subscribed to {eventName} </Text>
        </View>
    );

    async function setPEvents(session) {
        const headers = new Headers({
            'Authorization': `Bearer ${session.accessToken}`,
            'Content-Type': 'application/json'
        });
        const body = {
            "event": `/event/${eventName}`,
            "replayId": replayId
        };
        const url = `${session.instanceUrl}/services/data/v57.0/event/${eventName}/subscriptions`;
        const requestOptions = {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(body)
        };
        const resp = await fetch(url, requestOptions)
            .then(async (response) => {
                console.log(response);
                return await response.json();
            })
            .catch(error => console.log('Error:', error));
        setSubscription(resp);
        console.log("FIRATTT");
        console.log("Result:",resp);
    }
}

export default History;

What can I do to subscribe?
Or how can I use the SalesForce Pub/Sub API in React Native?


问:
Why matplotlib animation getting slower and slower on every interval?
```<code>import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import datetime

plt.style.use("fivethirtyeight")
todaydate = datetime.date.today()
chartname = "allcharts"
fig, axs = plt.subplots(3)

def animatechart(i):
    data = pd.read_csv(f'{todaydate}-history.csv')

    time = data["time"]
    volume = data["volume"]
    buyorders = data["buyorders"]
    sellorders = data["sellorders"]

    plt.cla()
    #plt.clf()
    #plt.clear()

    axs[0].bar(time, volume, color="black")
    axs[1].bar(time, buyorders, color="green")
    axs[2].bar(time, sellorders, color="red")

    axs[0].axis('off')
    axs[1].axis('off')
    axs[2].axis('off')

    axs[0].autoscale(tight=True)
    axs[1].autoscale(tight=True)
    axs[2].autoscale(tight=True)

    plt.tight_layout()

    plt.savefig(f'{chartname}.png')

ani = FuncAnimation(plt.gcf(), animatechart, interval = 5000)
plt.show()
</code>```

This animation gets slower and slower on every interval. I have to close and re-open the figure window after every 10 minutes.
Additional Info: I am using linux operating system.

I tried plt.clf() plt.clear() but that didn't work either.

Body:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import datetime

plt.style.use("fivethirtyeight")
todaydate = datetime.date.today()
chartname = "allcharts"
fig, axs = plt.subplots(3)

def animatechart(i):
    data = pd.read_csv(f'{todaydate}-history.csv')

    time = data["time"]
    volume = data["volume"]
    buyorders = data["buyorders"]
    sellorders = data["sellorders"]

    plt.cla()
    #plt.clf()
    #plt.clear()

    axs[0].bar(time, volume, color="black")
    axs[1].bar(time, buyorders, color="green")
    axs[2].bar(time, sellorders, color="red")

    axs[0].axis('off')
    axs[1].axis('off')
    axs[2].axis('off')

    axs[0].autoscale(tight=True)
    axs[1].autoscale(tight=True)
    axs[2].autoscale(tight=True)

    plt.tight_layout()

    plt.savefig(f'{chartname}.png')

ani = FuncAnimation(plt.gcf(), animatechart, interval = 5000)
plt.show()

This animation gets slower and slower on every interval. I have to close and re-open the figure window after every 10 minutes.
Additional Info: I am using linux operating system.

I tried plt.clf() plt.clear() but that didn't work either.


问:
Modification of pdf in nodejs
I want to Modify the pdf such that.
First we need to search the string in the pdf after that Replace by the same string but now I want to string Font size is increased or Make the string Bold.
I am able to replace String with other string.
Please help me with proper code.

This is part of PDF

As shown in the image suppose i have search string is 9.R&R Continuous ridge vent - shingle after that bold all the content in this line
R&R Continuous ridge vent - shingle- 92.46 LF 10.1823.30241.141,205.68(0.00)1,205.68
like that

This is the link for my pdf https://surajpdf.s3.ap-south-1.amazonaws.com/1672653281338

Title: Modification of pdf in nodejs


问:
How to verify the signer of a public key with a signing authority?
I'm working through implementing the algorithm outlined by apple here for authenticating a player given a public key and signature, and I don't quite understand what they mean by

Verify with the appropriate signing authority that Apple signed the public key.

Once I've downloaded the .cer file, with NodeJS I can do something like this:

const publicKey = new X509Certificate(response.data)
console.log(publicKey.subject)
```

which will indeed show that the organization is Apple. If you look at some other implementations of this algorithm, it seems people are just checking "hey, is this a valid cert?", but not actually confirming with the signing authority.

In this case, the issuer of the certificate (I assume that a certificate authority is this is analogous with signing authority, but please correct me if I'm wrong) is DigiCert, Inc., so it seems like we'd almost have to somehow make some API call to them and ask "Hey, did you guys grant Apple this specific public key?"

Is this what apple means by "verify with the appropriate signing authority that Apple signed the public key."? Or am I getting signing authority confused and certificate authority confused?

Thanks!

Body:
I'm working through implementing the algorithm outlined by apple here for authenticating a player given a public key and signature, and I don't quite understand what they mean by

Verify with the appropriate signing authority that Apple signed the public key.

Once I've downloaded the .cer file, with NodeJS I can do something like this:

const publicKey = new X509Certificate(response.data)
console.log(publicKey.subject)

which will indeed show that the organization is Apple. If you look at some other implementations of this algorithm, it seems people are just checking "hey, is this a valid cert?", but not actually confirming with the signing authority.

In this case, the issuer of the certificate (I assume that a certificate authority is this is analogous with signing authority, but please correct me if I'm wrong) is DigiCert, Inc., so it seems like we'd almost have to somehow make some API call to them and ask "Hey, did you guys grant Apple this specific public key?"

Is this what apple means by "verify with the appropriate signing authority that Apple signed the public key."? Or am I getting signing authority confused and certificate authority confused?

Thanks!


问:
tp = torch.sum(temp_target[...,:-1] * temp_inputs, axis=[0,1]), What does temp_target[...,:-1] mean?
When I was learning diceloss, I didn't understand how to write this code:

```<code>tp = torch.sum(temp_target[...,:-1] * temp_inputs, axis=[0,1])
</code>```

What does temp_target[...,:-1] mean?
The code for the entire diceloss calculation is as follows:

```<code>def Dice_loss(inputs, target, beta=1, smooth = 1e-5):
n, c, h, w = inputs.size()
nt, ht, wt, ct = target.size()
temp_inputs = torch.softmax(inputs.transpose(1, 2).transpose(2, 3).contiguous().view(n, -1, c),-1)
temp_target = target.view(n, -1, ct)

tp = torch.sum(temp_target[...,:-1] * temp_inputs, axis=[0,1])
fp = torch.sum(temp_inputs                       , axis=[0,1]) - tp
fn = torch.sum(temp_target[...,:-1]              , axis=[0,1]) - tp
score = ((1 + beta ** 2) * tp + smooth) / ((1 + beta ** 2) * tp + beta ** 2 * fn + fp + smooth)
dice_loss = 1 - torch.mean(score)
return dice_loss
</code>```

Body:
When I was learning diceloss, I didn't understand how to write this code:

tp = torch.sum(temp_target[...,:-1] * temp_inputs, axis=[0,1])

What does temp_target[...,:-1] mean?
The code for the entire diceloss calculation is as follows:

def Dice_loss(inputs, target, beta=1, smooth = 1e-5):
n, c, h, w = inputs.size()
nt, ht, wt, ct = target.size()
temp_inputs = torch.softmax(inputs.transpose(1, 2).transpose(2, 3).contiguous().view(n, -1, c),-1)
temp_target = target.view(n, -1, ct)

tp = torch.sum(temp_target[...,:-1] * temp_inputs, axis=[0,1])
fp = torch.sum(temp_inputs                       , axis=[0,1]) - tp
fn = torch.sum(temp_target[...,:-1]              , axis=[0,1]) - tp
score = ((1 + beta ** 2) * tp + smooth) / ((1 + beta ** 2) * tp + beta ** 2 * fn + fp + smooth)
dice_loss = 1 - torch.mean(score)
return dice_loss


问:
Selenium ui automation using user-data-dir along with set session storgae
I'm having a situation where I have to use user-data-dir to persist some cookies, but we are using sessionStorage to navigate between pages. Can user-data-dir affect the sessionStorage some how? I've tried through the documentation couldn't find any useful info.
Found that when the browser is closed sessionStorage is cleared. But can using user-data-dir can affect that part?

I'm using below code to set user profile.

```<code>option.AddArguments($"user-data-dir={path + @"\profile\"}");
</code>```

Body:
I'm having a situation where I have to use user-data-dir to persist some cookies, but we are using sessionStorage to navigate between pages. Can user-data-dir affect the sessionStorage some how? I've tried through the documentation couldn't find any useful info.
Found that when the browser is closed sessionStorage is cleared. But can using user-data-dir can affect that part?

I'm using below code to set user profile.

option.AddArguments($"user-data-dir={path + @"\profile\"}");


问:
why the Other memory in JVM is growing, how to identify and make it free
I've built a spring-boot app to sniff document contents in computer.

the source: https://github.com/just226/messy-doc

after the sniffing work done, I did some native memory tracking and found that the OTHER memory swelled huge.

Other (reserved=901MB +821MB, committed=901MB +821MB)
(malloc=901MB +821MB #26)

What does Other memory use for and is it some kinds of memory leak?

then how to identify the memory and do some optimize in the code or let it free.

```<code>
Native Memory Tracking:

(Omitting categories weighting less than 1MB)

Total: reserved=4559MB +903MB, committed=1512MB +1106MB

-                 Java Heap (reserved=2048MB, committed=324MB +155MB)
                            (mmap: reserved=2048MB, committed=324MB +155MB)

-                     Class (reserved=1026MB +1MB, committed=12MB +5MB)
                            (classes #15684 +4582)
                            (  instance classes #14564 +4254, array classes #1120 +328)
                            (malloc=2MB +1MB #47199 +22834)
                            (mmap: reserved=1024MB, committed=10MB +4MB)
                           : (  Metadata)
                            (    reserved=80MB +32MB, committed=77MB +34MB)
                            (    used=76MB +34MB)
                            (    waste=0MB =0.45%)
                           : (  Class space)
                            (    reserved=1024MB, committed=10MB +4MB)
                            (    used=10MB +4MB)
                            (    waste=0MB =3.88%)

-                    Thread (reserved=63MB +7MB, committed=3MB)
                            (thread #0)
                            (stack: reserved=63MB +7MB, committed=3MB)

-                      Code (reserved=247MB +4MB, committed=65MB +47MB)
                            (malloc=5MB +4MB #18065 +11571)
                            (mmap: reserved=242MB, committed=60MB +43MB)

-                        GC (reserved=149MB +23MB, committed=85MB +29MB)
                            (malloc=41MB +23MB #46820 +41274)
                            (mmap: reserved=109MB, committed=45MB +6MB)

-                  Internal (reserved=4MB +4MB, committed=4MB +4MB)
                            (malloc=4MB +4MB #43693 +35806)

-                     Other (reserved=901MB +821MB, committed=901MB +821MB)
                            (malloc=901MB +821MB #26)

-                    Symbol (reserved=18MB +6MB, committed=18MB +6MB)
                            (malloc=16MB +5MB #474310 +185639)
                            (arena=2MB +1 #1)

-    Native Memory Tracking (reserved=10MB +5MB, committed=10MB +5MB)
                            (tracking overhead=10MB +5MB)

-        Shared class space (reserved=12MB, committed=12MB)
                            (mmap: reserved=12MB, committed=12MB)

-                    Module (reserved=1MB, committed=1MB)
                            (malloc=1MB #3395 +1237)

-                 Metaspace (reserved=80MB +32MB, committed=77MB +35MB)
                            (mmap: reserved=80MB +32MB, committed=77MB +34MB)
</code>```

work around the problem

Body:
I've built a spring-boot app to sniff document contents in computer.

the source: https://github.com/just226/messy-doc

after the sniffing work done, I did some native memory tracking and found that the OTHER memory swelled huge.

Other (reserved=901MB +821MB, committed=901MB +821MB)
(malloc=901MB +821MB #26)

What does Other memory use for and is it some kinds of memory leak?

then how to identify the memory and do some optimize in the code or let it free.

Native Memory Tracking:

(Omitting categories weighting less than 1MB)

Total: reserved=4559MB +903MB, committed=1512MB +1106MB

-                 Java Heap (reserved=2048MB, committed=324MB +155MB)
                            (mmap: reserved=2048MB, committed=324MB +155MB)

-                     Class (reserved=1026MB +1MB, committed=12MB +5MB)
                            (classes #15684 +4582)
                            (  instance classes #14564 +4254, array classes #1120 +328)
                            (malloc=2MB +1MB #47199 +22834)
                            (mmap: reserved=1024MB, committed=10MB +4MB)
                           : (  Metadata)
                            (    reserved=80MB +32MB, committed=77MB +34MB)
                            (    used=76MB +34MB)
                            (    waste=0MB =0.45%)
                           : (  Class space)
                            (    reserved=1024MB, committed=10MB +4MB)
                            (    used=10MB +4MB)
                            (    waste=0MB =3.88%)

-                    Thread (reserved=63MB +7MB, committed=3MB)
                            (thread #0)
                            (stack: reserved=63MB +7MB, committed=3MB)

-                      Code (reserved=247MB +4MB, committed=65MB +47MB)
                            (malloc=5MB +4MB #18065 +11571)
                            (mmap: reserved=242MB, committed=60MB +43MB)

-                        GC (reserved=149MB +23MB, committed=85MB +29MB)
                            (malloc=41MB +23MB #46820 +41274)
                            (mmap: reserved=109MB, committed=45MB +6MB)

-                  Internal (reserved=4MB +4MB, committed=4MB +4MB)
                            (malloc=4MB +4MB #43693 +35806)

-                     Other (reserved=901MB +821MB, committed=901MB +821MB)
                            (malloc=901MB +821MB #26)

-                    Symbol (reserved=18MB +6MB, committed=18MB +6MB)
                            (malloc=16MB +5MB #474310 +185639)
                            (arena=2MB +1 #1)

-    Native Memory Tracking (reserved=10MB +5MB, committed=10MB +5MB)
                            (tracking overhead=10MB +5MB)

-        Shared class space (reserved=12MB, committed=12MB)
                            (mmap: reserved=12MB, committed=12MB)

-                    Module (reserved=1MB, committed=1MB)
                            (malloc=1MB #3395 +1237)

-                 Metaspace (reserved=80MB +32MB, committed=77MB +35MB)
                            (mmap: reserved=80MB +32MB, committed=77MB +34MB)

work around the problem


问:
How do I get only the top 5 of rank() in mysql?
I am trying to limit the rank to just the top 5 by country. Right now it's giving me every track. How do I fix this? Thank you

```<code> SELECT
        critic_country,
        r.artist,
        r.title,
        RANK() OVER(PARTITION BY critic_country ORDER BY points DESC) AS ranked_songs
    FROM rankings AS r
    JOIN polls AS p
        ON r.title = p.title
</code>```

Body:
I am trying to limit the rank to just the top 5 by country. Right now it's giving me every track. How do I fix this? Thank you

 SELECT
        critic_country,
        r.artist,
        r.title,
        RANK() OVER(PARTITION BY critic_country ORDER BY points DESC) AS ranked_songs
    FROM rankings AS r
    JOIN polls AS p
        ON r.title = p.title


问:
ElasticSearch should_index? not checking the correct condition in Model.reindex
I'm using searchkick gem for elastic-search. I'v implemented the "shouldindex?" method in model to reindex selected records.

For example, First there were 2 boolean columns with AND condition in the "should_index?" method on which basis i was checking the record should be reindex or not . Afterwards i changed the columns count from 2 to 4 and condition from AND to OR in the "should_index?" but it is still reading the old conditions.

should_index? method is working correctly with the model object. Like i do reindex this way "Model.all.map(:reindex)". It reads the condition properly from the "should_index?" method in the model and update the records accordingly.

But when i do reindex this way "Model.reindex". It reads the old conditions of the "should_index?" method rather than the updated once in the modsel.

I did reset the elastic-search and read the gem document but could not find any solution.


问:
Navigatiion Component using @mui/material not rendering
SOLVED:
The Navigation Component placed outside the ThemeProvider renders fine. I'm not sure why because the theme works with other components but my assumption is something to do with Links being used with a theme incorrectly

Without the Navigation component, the root page of my react app renders correctly. But when I add it no components inside App() are rendered: the page only uses App.css to style a blank page(the correct component(home/about/projects) appears for a second when i run yarn start but disappears immediately and doesnt appear again if refreshed/urls are changed)

This is my App.js file:

```<code>import React from 'react';
// Styling imports
import './App.css';
import { ThemeProvider } from '@emotion/react'
import { theme } from './theme';

// Routing imports
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

// Component imports
import Navigation from './components/Navigation.js'
import Footer from './components/Footer.js'
import Home from './pages/home.js';
import About from './pages/about.js';
import Projects from './pages/projects.js';

function App() {
    return (
    <div className="App">
        <Router>
            <ThemeProvider theme={theme}>
                <Navigation />
                <Routes>
                    <Route path="/" component={Home} />
                    <Route path="/about" element={About } />
                    <Route path="projects" element={Projects }/>
                </Routes>
                <Footer />
            </ThemeProvider>
        </Router>
    </div>
    );
}

export default App;
</code>```

This is my Navigation.js file:

```<code>import { Component } from 'react';
import { Link } from 'react-router-dom';
import { Box, AppBar, Toolbar, Button } from '@mui/material';
import styled from '@emotion/styled';

const NavBar = styled(Box)
background-color: ${props => props.theme.palette.secondary};
color: ${props => props.theme.palette.primary};
border: 2px solid black;
;

class Navigation extends Component {
    render() {
        return (
            <NavBar>
                <AppBar position="static">
                    <Toolbar>
                        <Link color="inherit" to="/">Home</Link>
                        <Link color="inherit" to="/about">About</Link>
                        <Link color="inherit" to="/projects">Projects</Link>
                        <Button>[Header section]</Button>
                    </Toolbar>
                </AppBar>
            </NavBar>
        );
    }
}

export default Navigation;
</code>```

I tried rendering each component(Navigation, Home, About, Projects, and Footer) individually with and without the Router tag in App.js. All components except Navigation are rendered correctly.

The issue doesn't seem to be with BrowserRouter because when I manually enter the http://localhost:3000//about or /projects without the Navigation component in App.js, the expected components are being rendered.

I've tried making the navigation component as bare as possible - removing the styling, adding and removing the nav tag around the links

I made sure all the imported libraries were installed inside the root directory of the app(I used create-react-app)

I'm using react@18.2.0, react-router-dom@6.6.2, @mui/material@5.11.4
I've been unable to debug the issue with documentation, any help would be appreciated.

Body:
SOLVED:
The Navigation Component placed outside the ThemeProvider renders fine. I'm not sure why because the theme works with other components but my assumption is something to do with Links being used with a theme incorrectly

Without the Navigation component, the root page of my react app renders correctly. But when I add it no components inside App() are rendered: the page only uses App.css to style a blank page(the correct component(home/about/projects) appears for a second when i run yarn start but disappears immediately and doesnt appear again if refreshed/urls are changed)

This is my App.js file:

import React from 'react';
// Styling imports
import './App.css';
import { ThemeProvider } from '@emotion/react'
import { theme } from './theme';

// Routing imports
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

// Component imports
import Navigation from './components/Navigation.js'
import Footer from './components/Footer.js'
import Home from './pages/home.js';
import About from './pages/about.js';
import Projects from './pages/projects.js';

function App() {
    return (

        <Router>
            <ThemeProvider theme={theme}>
                <Navigation />
                <Routes>
                    <Route path="/" component={Home} />
                    <Route path="/about" element={About } />
                    <Route path="projects" element={Projects }/>
                </Routes>

            </ThemeProvider>
        </Router>

    );
}

export default App;

This is my Navigation.js file:

import { Component } from 'react';
import { Link } from 'react-router-dom';
import { Box, AppBar, Toolbar, Button } from '@mui/material';
import styled from '@emotion/styled';

const NavBar = styled(Box)
background-color: ${props => props.theme.palette.secondary};
color: ${props => props.theme.palette.primary};
border: 2px solid black;
;

class Navigation extends Component {
    render() {
        return (
            <NavBar>
                <AppBar position="static">
                    <Toolbar>
                        <Link color="inherit" to="/">Home</Link>
                        <Link color="inherit" to="/about">About</Link>
                        <Link color="inherit" to="/projects">Projects</Link>
                        <Button>[Header section]</Button>
                    </Toolbar>
                </AppBar>
            </NavBar>
        );
    }
}

export default Navigation;

I tried rendering each component(Navigation, Home, About, Projects, and Footer) individually with and without the Router tag in App.js. All components except Navigation are rendered correctly.

The issue doesn't seem to be with BrowserRouter because when I manually enter the http://localhost:3000//about or /projects without the Navigation component in App.js, the expected components are being rendered.

I've tried making the navigation component as bare as possible - removing the styling, adding and removing the nav tag around the links

I made sure all the imported libraries were installed inside the root directory of the app(I used create-react-app)

I'm using react@18.2.0, react-router-dom@6.6.2, @mui/material@5.11.4
I've been unable to debug the issue with documentation, any help would be appreciated.


问:
openssl VS wincrypt produce different result
I have used the same plain text, same public key, but get different result in Wincrypt and openssl.
My enviroment is win7 64bit and VS 2010 and openssl 1.1.1S.

here is the code:

```<code>/*
* An example of using PEM encoded RSA private keys with CAPI
*    - Modified on March 29th 2014 to show how to use PEM encoded RSA public key
*
* Copyright (c) 2012 Mounir IDRASSI <mounir.idrassi@idrix.fr>. All rights reserved.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
//
//#ifndef _WIN32_WINNT
//#define _WIN32_WINNT 0x0501
//#endif
//
//#include <windows.h>
//#include <wincrypt.h>
//#include <stdio.h>
//
//#pragma comment(lib, "Crypt32.lib")
//
//const char* szPemPrivKey =
//    "-----BEGIN RSA PRIVATE KEY-----"
//    "MIICXAIBAAKBgQCf6YAJOSBYPve1jpYDzq+w++8YVoATI/YCi/RKZaQk+l2ZfoUQ"
//    "g0qrYrfkzeoOa/qd5VLjTTvHEgwXnlDXMfo+vSgxosUxDOZXMTBqJGOViv5K2QBv"
//    "k8A1wi4k8tuo/7OWya29HvcfavUk3YXaV2YFe8V6ssaZjNcVWmDdjqNkXwIDAQAB"
//    "AoGALrd+ijNAOcebglT3ioE1XpUbUpbir7TPyAqvAZUUESF7er41jY9tnwgmBRgL"
//    "Cs+M1dgLERCdKBkjozrDDzswifFQmq6PrmYrBkFFqCoLJwepSYdWnK1gbZ/d43rR"
//    "2sXzSGZngscx0CxO7KZ7xUkwENGd3+lKXV7J6/vgzJ4XnkECQQDTP6zWKT7YDckk"
//    "We04hbhHyBuNOW068NgUUvoZdBewerR74MJx6nz28Tp+DeNvc0EveiQxsEnbV8u+"
//    "NRkX5y0xAkEAwcnEAGBn5kJd6SpU0ALA9XEpUv7tHTAGQYgCRbfTT59hhOq6I22A"
//    "ivjOCNG9c6E7EB2kcPVGuCpYUhy7XBIGjwJAK5lavKCqncDKoLwGn8HJdNcyCIWv"
//    "q5iFoDw37gTt1ricg2yx9PzmabkDz3xiUmBBNeFJkw/FToXiQRGIakyGIQJAJIem"
//    "PPPvYgZssYFbT4LVYO8d/Rk1FWVyKHQ9CWtnmADRXz7oK7l+m7PfEuaGsf9YpOcR"
//    "koGJ/TluQLxNzUNQnQJBAImwr/yYFenIx3HQ6UX/fCt6qpGDv0VfOLyR64MNeegx"
//    "o7DhNxHbFkIGzk4lKhMKcHKDrawZbdJtS9ie2geSwVQ="
//    "-----END RSA PRIVATE KEY-----";
//
//const char* szPemPubKey =
//  "-----BEGIN RSA PUBLIC KEY-----"
//  "MIGJAoGBAJ/pgAk5IFg+97WOlgPOr7D77xhWgBMj9gKL9EplpCT6XZl+hRCDSqti"
//  "t+TN6g5r+p3lUuNNO8cSDBeeUNcx+j69KDGixTEM5lcxMGokY5WK/krZAG+TwDXC"
//  "LiTy26j/s5bJrb0e9x9q9STdhdpXZgV7xXqyxpmM1xVaYN2Oo2RfAgMBAAE="
//  "-----END RSA PUBLIC KEY-----";
//
//const char* szDataToSign = "Data to be signed by the private key";
//
//
//
//
//
//int main(int argc, char* argv[])
//{
//    DWORD dwBufferLen = 0, cbKeyBlob = 0, cbSignature = 0,i;
//    LPBYTE pbBuffer = NULL, pbKeyBlob = NULL, pbSignature = NULL;
//    HCRYPTPROV hProv = NULL;
//    HCRYPTKEY hKey = NULL;
//    HCRYPTHASH hHash = NULL;
//
//    if (!CryptStringToBinaryA(szPemPrivKey, 0, CRYPT_STRING_BASE64HEADER, NULL, &dwBufferLen, NULL, NULL))
//    {
//        printf("Failed to convert BASE64 private key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    pbBuffer = (LPBYTE) LocalAlloc(0, dwBufferLen);
//    if (!CryptStringToBinaryA(szPemPrivKey, 0, CRYPT_STRING_BASE64HEADER, pbBuffer, &dwBufferLen, NULL, NULL))
//    {
//        printf("Failed to convert BASE64 private key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_RSA_PRIVATE_KEY, pbBuffer, dwBufferLen, 0, NULL, NULL, &cbKeyBlob))
//    {
//        printf("Failed to parse private key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    pbKeyBlob = (LPBYTE) LocalAlloc(0, cbKeyBlob);
//    if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_RSA_PRIVATE_KEY, pbBuffer, dwBufferLen, 0, NULL, pbKeyBlob, &cbKeyBlob))
//    {
//        printf("Failed to parse private key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    // Create a temporary and volatile CSP context in order to import
//    // the key and use for signing
//    if (!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
//    {
//        printf("CryptAcquireContext failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptImportKey(hProv, pbKeyBlob, cbKeyBlob, NULL, 0, &hKey))
//    {
//        printf("CryptImportKey for private key failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    // Hash the data
//    if (!CryptCreateHash(hProv, CALG_SHA1, NULL, 0, &hHash))
//    {
//        printf("CryptCreateHash failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptHashData(hHash, (LPCBYTE) szDataToSign, strlen(szDataToSign), 0))
//    {
//        printf("CryptHashData failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    // Sign the hash using our imported key
//    if (!CryptSignHash(hHash, AT_KEYEXCHANGE, NULL, 0, NULL, &cbSignature))
//    {
//        printf("CryptSignHash failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    pbSignature = (LPBYTE) LocalAlloc(0, cbSignature);
//    if (!CryptSignHash(hHash, AT_KEYEXCHANGE, NULL, 0, pbSignature, &cbSignature))
//    {
//        printf("CryptSignHash failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    printf("Signature = ");
//    for (i = 0; i < cbSignature; i++)
//    {
//        printf("%.2X", pbSignature[i]);
//    }
//    printf("\n\n");
//
//  /***************************************************
//   * Import the public key and verify the signature
//   ***************************************************/
//
//    if (!CryptStringToBinaryA(szPemPubKey, 0, CRYPT_STRING_BASE64HEADER, NULL, &dwBufferLen, NULL, NULL))
//    {
//        printf("Failed to convert BASE64 public key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//  LocalFree(pbBuffer);
//    pbBuffer = (LPBYTE) LocalAlloc(0, dwBufferLen);
//    if (!CryptStringToBinaryA(szPemPubKey, 0, CRYPT_STRING_BASE64HEADER, pbBuffer, &dwBufferLen, NULL, NULL))
//    {
//        printf("Failed to convert BASE64 public key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB, pbBuffer, dwBufferLen, 0, NULL, NULL, &cbKeyBlob))
//    {
//        printf("Failed to parse public key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//  LocalFree(pbKeyBlob);
//    pbKeyBlob = (LPBYTE) LocalAlloc(0, cbKeyBlob);
//    if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB, pbBuffer, dwBufferLen, 0, NULL, pbKeyBlob, &cbKeyBlob))
//    {
//        printf("Failed to parse public key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    CryptDestroyHash(hHash);
//    CryptDestroyKey(hKey);
//    CryptReleaseContext(hProv, 0);
//
//    if (!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
//    {
//        printf("CryptAcquireContext failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptImportKey(hProv, pbKeyBlob, cbKeyBlob, NULL, 0, &hKey))
//    {
//        printf("CryptImportKey for public key failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    // Hash the data
//    if (!CryptCreateHash(hProv, CALG_SHA1, NULL, 0, &hHash))
//    {
//        printf("CryptCreateHash failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptHashData(hHash, (LPCBYTE) szDataToSign, strlen(szDataToSign), 0))
//    {
//        printf("CryptHashData failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    // Sign the hash using our imported key
//  if (!CryptVerifySignature(hHash, pbSignature, cbSignature, hKey, NULL, 0))
//    {
//        printf("Signature verification failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//  printf("Signature verified successfully!\n\n");
//
//main_exit:
//    if (pbBuffer) LocalFree(pbBuffer);
//    if (pbKeyBlob) LocalFree(pbKeyBlob);
//    if (pbSignature) LocalFree(pbSignature);
//    if (hHash) CryptDestroyHash(hHash);
//    if (hKey) CryptDestroyKey(hKey);
//    if (hProv) CryptReleaseContext(hProv, 0);
//
//  system("pause");
//    return 0;
//}

#include <stdio.h>
#include <string>

//openssl
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/sha.h>
#include <openssl/crypto.h>
#pragma comment(lib, "libcrypto.lib")
#pragma comment(lib, "libssl.lib")
#pragma comment(lib, "ws2_32.lib")

int main()
{
    FILE *fp = NULL;
    RSA *pubRsa = NULL;
    unsigned char buf[128] = { 0 };
    int nOutLen = sizeof(buf);

    char * p_KeyPath = "D:/PublicKey.pem";

    printf("PublicKeyPath[%s]\n", p_KeyPath);

    /*  打开密钥文件 */
    if (NULL == (fp = fopen(p_KeyPath, "r")))
    {
        printf("fopen[%s] \n", p_KeyPath);
        return NULL;
    }
    /*  获取公钥 */
    if (NULL == (pubRsa = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL)))
    {
        printf("PEM_read_RSA_PUBKEY error\n");
        fclose(fp);
        return NULL;
    }
    fclose(fp);

    char * message = "BFEBFBFF000906E9:L1HF73P055S";
    unsigned char md[SHA256_DIGEST_LENGTH];
    SHA256((unsigned char *)message, strlen(message), md);

    int nRet = RSA_verify(NID_sha256, md, SHA256_DIGEST_LENGTH, buf, nOutLen, pubRsa);
    if (nRet != 1)
    {
        printf("RSA_verify err !!! \n");
    }
    printf("RSA_verify Success !!! \n");

    system("pause");
    return 0;
}
</code>```

The wincrypt method is commented. and the openssl method is presented. you can toggle the comment to reproduce both results.
PS: I don't have the public pem directly. I converted the xml file to pem by BouncyCastle.Crypto API in C#.
The original xml public key is

```<code><RSAKeyValue><Modulus>wz1A5Neh5XiRPa+FDdqpVxQGpNSoz4GWj4D4iYC1w4Lf8quQ73iz8iHz9x+U/Ep+EJtdQyBCOveT0999uQuvH6/GDIAX9QXr5+uE7Koxbh680hCMqDE7DP3VR2UVzluVLVVqfdSQZIFad5+xKAnpgVHBWFxPgRjijHSDHnHnEVU=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
</code>```

Body:
I have used the same plain text, same public key, but get different result in Wincrypt and openssl.
My enviroment is win7 64bit and VS 2010 and openssl 1.1.1S.

here is the code:

/*
* An example of using PEM encoded RSA private keys with CAPI
*    - Modified on March 29th 2014 to show how to use PEM encoded RSA public key
*
* Copyright (c) 2012 Mounir IDRASSI <mounir.idrassi@idrix.fr>. All rights reserved.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
//
//#ifndef _WIN32_WINNT
//#define _WIN32_WINNT 0x0501
//#endif
//
//#include <windows.h>
//#include <wincrypt.h>
//#include <stdio.h>
//
//#pragma comment(lib, "Crypt32.lib")
//
//const char* szPemPrivKey =
//    "-----BEGIN RSA PRIVATE KEY-----"
//    "MIICXAIBAAKBgQCf6YAJOSBYPve1jpYDzq+w++8YVoATI/YCi/RKZaQk+l2ZfoUQ"
//    "g0qrYrfkzeoOa/qd5VLjTTvHEgwXnlDXMfo+vSgxosUxDOZXMTBqJGOViv5K2QBv"
//    "k8A1wi4k8tuo/7OWya29HvcfavUk3YXaV2YFe8V6ssaZjNcVWmDdjqNkXwIDAQAB"
//    "AoGALrd+ijNAOcebglT3ioE1XpUbUpbir7TPyAqvAZUUESF7er41jY9tnwgmBRgL"
//    "Cs+M1dgLERCdKBkjozrDDzswifFQmq6PrmYrBkFFqCoLJwepSYdWnK1gbZ/d43rR"
//    "2sXzSGZngscx0CxO7KZ7xUkwENGd3+lKXV7J6/vgzJ4XnkECQQDTP6zWKT7YDckk"
//    "We04hbhHyBuNOW068NgUUvoZdBewerR74MJx6nz28Tp+DeNvc0EveiQxsEnbV8u+"
//    "NRkX5y0xAkEAwcnEAGBn5kJd6SpU0ALA9XEpUv7tHTAGQYgCRbfTT59hhOq6I22A"
//    "ivjOCNG9c6E7EB2kcPVGuCpYUhy7XBIGjwJAK5lavKCqncDKoLwGn8HJdNcyCIWv"
//    "q5iFoDw37gTt1ricg2yx9PzmabkDz3xiUmBBNeFJkw/FToXiQRGIakyGIQJAJIem"
//    "PPPvYgZssYFbT4LVYO8d/Rk1FWVyKHQ9CWtnmADRXz7oK7l+m7PfEuaGsf9YpOcR"
//    "koGJ/TluQLxNzUNQnQJBAImwr/yYFenIx3HQ6UX/fCt6qpGDv0VfOLyR64MNeegx"
//    "o7DhNxHbFkIGzk4lKhMKcHKDrawZbdJtS9ie2geSwVQ="
//    "-----END RSA PRIVATE KEY-----";
//
//const char* szPemPubKey =
//  "-----BEGIN RSA PUBLIC KEY-----"
//  "MIGJAoGBAJ/pgAk5IFg+97WOlgPOr7D77xhWgBMj9gKL9EplpCT6XZl+hRCDSqti"
//  "t+TN6g5r+p3lUuNNO8cSDBeeUNcx+j69KDGixTEM5lcxMGokY5WK/krZAG+TwDXC"
//  "LiTy26j/s5bJrb0e9x9q9STdhdpXZgV7xXqyxpmM1xVaYN2Oo2RfAgMBAAE="
//  "-----END RSA PUBLIC KEY-----";
//
//const char* szDataToSign = "Data to be signed by the private key";
//
//
//
//
//
//int main(int argc, char* argv[])
//{
//    DWORD dwBufferLen = 0, cbKeyBlob = 0, cbSignature = 0,i;
//    LPBYTE pbBuffer = NULL, pbKeyBlob = NULL, pbSignature = NULL;
//    HCRYPTPROV hProv = NULL;
//    HCRYPTKEY hKey = NULL;
//    HCRYPTHASH hHash = NULL;
//
//    if (!CryptStringToBinaryA(szPemPrivKey, 0, CRYPT_STRING_BASE64HEADER, NULL, &dwBufferLen, NULL, NULL))
//    {
//        printf("Failed to convert BASE64 private key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    pbBuffer = (LPBYTE) LocalAlloc(0, dwBufferLen);
//    if (!CryptStringToBinaryA(szPemPrivKey, 0, CRYPT_STRING_BASE64HEADER, pbBuffer, &dwBufferLen, NULL, NULL))
//    {
//        printf("Failed to convert BASE64 private key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_RSA_PRIVATE_KEY, pbBuffer, dwBufferLen, 0, NULL, NULL, &cbKeyBlob))
//    {
//        printf("Failed to parse private key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    pbKeyBlob = (LPBYTE) LocalAlloc(0, cbKeyBlob);
//    if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_RSA_PRIVATE_KEY, pbBuffer, dwBufferLen, 0, NULL, pbKeyBlob, &cbKeyBlob))
//    {
//        printf("Failed to parse private key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    // Create a temporary and volatile CSP context in order to import
//    // the key and use for signing
//    if (!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
//    {
//        printf("CryptAcquireContext failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptImportKey(hProv, pbKeyBlob, cbKeyBlob, NULL, 0, &hKey))
//    {
//        printf("CryptImportKey for private key failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    // Hash the data
//    if (!CryptCreateHash(hProv, CALG_SHA1, NULL, 0, &hHash))
//    {
//        printf("CryptCreateHash failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptHashData(hHash, (LPCBYTE) szDataToSign, strlen(szDataToSign), 0))
//    {
//        printf("CryptHashData failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    // Sign the hash using our imported key
//    if (!CryptSignHash(hHash, AT_KEYEXCHANGE, NULL, 0, NULL, &cbSignature))
//    {
//        printf("CryptSignHash failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    pbSignature = (LPBYTE) LocalAlloc(0, cbSignature);
//    if (!CryptSignHash(hHash, AT_KEYEXCHANGE, NULL, 0, pbSignature, &cbSignature))
//    {
//        printf("CryptSignHash failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    printf("Signature = ");
//    for (i = 0; i < cbSignature; i++)
//    {
//        printf("%.2X", pbSignature[i]);
//    }
//    printf("\n\n");
//
//  /***************************************************
//   * Import the public key and verify the signature
//   ***************************************************/
//
//    if (!CryptStringToBinaryA(szPemPubKey, 0, CRYPT_STRING_BASE64HEADER, NULL, &dwBufferLen, NULL, NULL))
//    {
//        printf("Failed to convert BASE64 public key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//  LocalFree(pbBuffer);
//    pbBuffer = (LPBYTE) LocalAlloc(0, dwBufferLen);
//    if (!CryptStringToBinaryA(szPemPubKey, 0, CRYPT_STRING_BASE64HEADER, pbBuffer, &dwBufferLen, NULL, NULL))
//    {
//        printf("Failed to convert BASE64 public key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB, pbBuffer, dwBufferLen, 0, NULL, NULL, &cbKeyBlob))
//    {
//        printf("Failed to parse public key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//  LocalFree(pbKeyBlob);
//    pbKeyBlob = (LPBYTE) LocalAlloc(0, cbKeyBlob);
//    if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB, pbBuffer, dwBufferLen, 0, NULL, pbKeyBlob, &cbKeyBlob))
//    {
//        printf("Failed to parse public key. Error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    CryptDestroyHash(hHash);
//    CryptDestroyKey(hKey);
//    CryptReleaseContext(hProv, 0);
//
//    if (!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
//    {
//        printf("CryptAcquireContext failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptImportKey(hProv, pbKeyBlob, cbKeyBlob, NULL, 0, &hKey))
//    {
//        printf("CryptImportKey for public key failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    // Hash the data
//    if (!CryptCreateHash(hProv, CALG_SHA1, NULL, 0, &hHash))
//    {
//        printf("CryptCreateHash failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    if (!CryptHashData(hHash, (LPCBYTE) szDataToSign, strlen(szDataToSign), 0))
//    {
//        printf("CryptHashData failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//    // Sign the hash using our imported key
//  if (!CryptVerifySignature(hHash, pbSignature, cbSignature, hKey, NULL, 0))
//    {
//        printf("Signature verification failed with error 0x%.8X\n", GetLastError());
//        goto main_exit;
//    }
//
//  printf("Signature verified successfully!\n\n");
//
//main_exit:
//    if (pbBuffer) LocalFree(pbBuffer);
//    if (pbKeyBlob) LocalFree(pbKeyBlob);
//    if (pbSignature) LocalFree(pbSignature);
//    if (hHash) CryptDestroyHash(hHash);
//    if (hKey) CryptDestroyKey(hKey);
//    if (hProv) CryptReleaseContext(hProv, 0);
//
//  system("pause");
//    return 0;
//}

#include <stdio.h>
#include <string>

//openssl
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/sha.h>
#include <openssl/crypto.h>
#pragma comment(lib, "libcrypto.lib")
#pragma comment(lib, "libssl.lib")
#pragma comment(lib, "ws2_32.lib")

int main()
{
    FILE *fp = NULL;
    RSA *pubRsa = NULL;
    unsigned char buf[128] = { 0 };
    int nOutLen = sizeof(buf);

    char * p_KeyPath = "D:/PublicKey.pem";

    printf("PublicKeyPath[%s]\n", p_KeyPath);

    /*  打开密钥文件 */
    if (NULL == (fp = fopen(p_KeyPath, "r")))
    {
        printf("fopen[%s] \n", p_KeyPath);
        return NULL;
    }
    /*  获取公钥 */
    if (NULL == (pubRsa = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL)))
    {
        printf("PEM_read_RSA_PUBKEY error\n");
        fclose(fp);
        return NULL;
    }
    fclose(fp);

    char * message = "BFEBFBFF000906E9:L1HF73P055S";
    unsigned char md[SHA256_DIGEST_LENGTH];
    SHA256((unsigned char *)message, strlen(message), md);

    int nRet = RSA_verify(NID_sha256, md, SHA256_DIGEST_LENGTH, buf, nOutLen, pubRsa);
    if (nRet != 1)
    {
        printf("RSA_verify err !!! \n");
    }
    printf("RSA_verify Success !!! \n");

    system("pause");
    return 0;
}

The wincrypt method is commented. and the openssl method is presented. you can toggle the comment to reproduce both results.
PS: I don't have the public pem directly. I converted the xml file to pem by BouncyCastle.Crypto API in C#.
The original xml public key is

<RSAKeyValue><Modulus>wz1A5Neh5XiRPa+FDdqpVxQGpNSoz4GWj4D4iYC1w4Lf8quQ73iz8iHz9x+U/Ep+EJtdQyBCOveT0999uQuvH6/GDIAX9QXr5+uE7Koxbh680hCMqDE7DP3VR2UVzluVLVVqfdSQZIFad5+xKAnpgVHBWFxPgRjijHSDHnHnEVU=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>


问:
How a create a Flutter Frameworking using an MVC pattern
This is my github project link https://github.com/RajTechnologiesPvtLtd/flutter-moonlight

How to convert to MVC patten and also given suggetion on it.

Create a Own Framework using MVC pattern


问:
How to extract only email addresses from text file. I'm trying to use Dreamweaver
How to extract only email addresses from text file.  I'm trying to do it in Dreamweaver (Search and Replace)…… however, I’m open to other solutions.

The email addresses will need to be saved to a text file; one email address per line.

Thanks

The Text file looks like this:

jon.park@CALPERS.CA.GOV                               anne.hollinhead@LAO.CA.GOV                                    karn.whites.COMMUNITYSOLUTIONS.ORG                                  dperkins@CITYOFAVENAL.COM                           marykathryn.clay@DHCS.CA.GOV                    charlene.manning@CALHR.CA.GOV

arivera@HFH-CONSULTANTS.COM Andy River 488-390-8293                           kristi.biwn@SEN.CA.GOV Kristina Brn/916-631-1769                           andy.diff@DOF.CA.GOV Andy Diff                                            Liren.goadian@GMAIL.COM Liren goadian                                         joenfly@KERN.ORG Jay Fly /; 661-684-4215                                jmcark@CI.OCEANSIDE.CA.US Jay Mark / 763-495-5832                       tytgomez@CI.OCEANSIDE.CA.US Tera Gomez/ 769-435-5818                           rdxteming@BEAUMONTCARES.COM Rebe Ddorming 657-577-3255                           vgytierorz@SCO.CA.GOV Vilma G/916.319.8550                           timmyriverlin@OCFA.ORG Timmera Riverline                                               dcurdoch@M-W-H.COM dclex Milant (918) 445-3902                                  kavinm.listw@EMSA.CA.GOV Kavinm Lists  918-431-3745

I tried different expressions in Dreamweaver that let me only see part of the email addresses; however, I cannot save only the email address as a list/other.

I use this expression in Search and Replace to find the email address: (\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}\b)|

How do I copy/export the results to a HTML or Txt file?


问:
How to get an oleObject's link location in Word using C# OpenXML
I just need to get the linked file's location instead of extracting the file.

In an Excel/Word/PowerPoint you can add an object as a link to another file, and I want to get the linked file's location.

In Excel I can use OpenXML to get the linked file's location by using ExternalRelationships. However it seems that PowerPoint and Word stores these file links differently and only in the oleObjects itself which are .bin files. I think the link is stored in the Ole10Native file after unzip the bin file but I don't think that is a great way to find the link. How can I get the link to the other file?

Example of getting the link from Excel

using (SpreadsheetDocument document = SpreadsheetDocument.Open(filePath, false))
{
    WorkbookPart workbook = document.WorkbookPart;
    foreach (ExternalWorkbookPart externalWorkbook in workbook.ExternalWorkbookParts)
    {
        foreach (ExternalRelationship link in externalWorkbook.ExternalRelationships)
        {
            // link.Uri.ToString() is the path to the linked file
        }
    }
}
```


Title: Why is this Binary Tree return true instead of false?

Body:
My goal is to use Binary Tree for Operation Room Booking. The problem is the return false, nil magically become return true, nil. I am not sure if this is a race condition or not. But I am confused.

The error print (full)

Running tool: /usr/local/go/bin/go test -timeout 30s -run ^TestInsert$ github.com/jasonrichdarmawan/cipta_integrasi_nusantara_backend/bookingkamaroperasi -count=1

=== RUN   TestInsert
2023/01/13 12:34:18 new          2022-01-01 10:00:00 +0700 WIB 2022-01-01 12:00:00 +0700 WIB
2023/01/13 12:34:18 SafeDB_v2.Insert true
2023/01/13 12:34:18
2023/01/13 12:34:18 node         2
2023/01/13 12:34:18 diff         3h0m0s false
2023/01/13 12:34:18 existing     2022-01-01 10:00:00 +0700 WIB 2022-01-01 12:00:00 +0700 WIB
2023/01/13 12:34:18 new          2022-01-01 15:00:00 +0700 WIB 2022-01-01 17:00:00 +0700 WIB
2023/01/13 12:34:18 BinaryTree.insert ok true <nil>
2023/01/13 12:34:18 SafeDB_v2.Insert true
2023/01/13 12:34:18
2023/01/13 12:34:18 node         2
2023/01/13 12:34:18 diff         6h0m0s false
2023/01/13 12:34:18 existing     2022-01-01 10:00:00 +0700 WIB 2022-01-01 12:00:00 +0700 WIB
2023/01/13 12:34:18 new          2022-01-01 18:00:00 +0700 WIB 2022-01-01 20:00:00 +0700 WIB
2023/01/13 12:34:18 node         2
2023/01/13 12:34:18 diff         1h0m0s true
2023/01/13 12:34:18 existing     2022-01-01 15:00:00 +0700 WIB 2022-01-01 17:00:00 +0700 WIB
2023/01/13 12:34:18 new          2022-01-01 18:00:00 +0700 WIB 2022-01-01 20:00:00 +0700 WIB
2023/01/13 12:34:18 BookingKamarOperasi_v2.isLessThanTwoHoursApart return 2, nil
2023/01/13 12:34:18 BinaryNode.ok 2 false
2023/01/13 12:34:18 BinaryTree.insert ok true <nil>
2023/01/13 12:34:18 SafeDB_v2.Insert true
2023/01/13 12:34:18
    /Volumes/T7Touch/Work/technical_test/cipta_integrasi_nusantara_backend/bookingkamaroperasi/db_v2_test.go:31: 01-01-2022 18:00-20:00 = true; want false; error <nil>
--- FAIL: TestInsert (0.00s)
FAIL
FAIL    github.com/jasonrichdarmawan/cipta_integrasi_nusantara_backend/bookingkamaroperasi      0.422s

The error print (focus)

2023/01/13 12:34:18 node         2
2023/01/13 12:34:18 diff         6h0m0s false
2023/01/13 12:34:18 existing     2022-01-01 10:00:00 +0700 WIB 2022-01-01 12:00:00 +0700 WIB
2023/01/13 12:34:18 new          2022-01-01 18:00:00 +0700 WIB 2022-01-01 20:00:00 +0700 WIB
2023/01/13 12:34:18 node         2
2023/01/13 12:34:18 diff         1h0m0s true
2023/01/13 12:34:18 existing     2022-01-01 15:00:00 +0700 WIB 2022-01-01 17:00:00 +0700 WIB
2023/01/13 12:34:18 new          2022-01-01 18:00:00 +0700 WIB 2022-01-01 20:00:00 +0700 WIB
2023/01/13 12:34:18 BookingKamarOperasi_v2.isLessThanTwoHoursApart return 2, nil
2023/01/13 12:34:18 BinaryNode.ok 2 false
2023/01/13 12:34:18 BinaryTree.insert ok true <nil>
2023/01/13 12:34:18 SafeDB_v2.Insert true

The code specific to the error print

            log.Println("BinaryNode.ok " + strconv.Itoa(isLess) + " " + strconv.FormatBool(false)) // line 126: BinaryNode.ok 2 false
            return false, nil // line 127

So, my expectation, BinaryTree.insert should return false, nil. Instead, it return true, nil

The code specific to the error print

        ok, err := t.root.insert(data) // line 58: BinaryTree.insert ok true <nil>
        log.Println("BinaryTree.insert ok", ok, err) // line 59

The code

package bookingkamaroperasi

import (
    "errors"
    "log"
    "strconv"
    "sync"
    "time"
)

type BookingKamarOperasi_v2 struct {
    startDate time.Time
    endDate   time.Time
}

// Return
// 0 = the startDate overlaps with an existing booking
// 1 = left
// 2 = right
func (n *BookingKamarOperasi_v2) leftOrRight(data BookingKamarOperasi_v2) (int, error) {
    if data.endDate.Before(n.startDate) {
        log.Println(data.endDate, n.startDate)
        // scenario 1: endDate n.startDate
        return 1, nil
    } else {
        // scenario 2: n.startDate endDate

        if data.startDate.Before(n.endDate) {
            // scenario 3: n.startDate startDate n.endDate
            return 0, errors.New("startDate overlaps with an existing booking")
        }

        return 2, nil
    }
}

type BinaryNode struct {
    left  *BinaryNode
    right *BinaryNode

    data BookingKamarOperasi_v2
}

type BinaryTree struct {
    root *BinaryNode
}

func (t *BinaryTree) insert(startDate, endDate time.Time) (bool, error) {
    data := BookingKamarOperasi_v2{startDate: startDate, endDate: endDate}

    if t.root == nil {
        t.root = &BinaryNode{
            left: nil, right: nil,
            data: data}
        log.Println("new", "\t", t.root.data.startDate, t.root.data.endDate)
        return true, nil
    } else {
        ok, err := t.root.insert(data)
        log.Println("BinaryTree.insert ok", ok, err)
        return ok, err
    }
}

// Return
// 0 = this method is not to be used directly
// 1 = false
// 2 = true
func (n *BookingKamarOperasi_v2) isLessThanTwoHoursApart(data BookingKamarOperasi_v2, node int) (int, error) {
    var diff time.Duration
    if node == 1 {
        // endDate n.startDate
        diff = n.startDate.Sub(data.endDate)
    } else if node == 2 {
        // n.startDate n.endDate startDate
        diff = data.startDate.Sub(n.endDate)
    } else {
        return 0, errors.New("this method is not to be used directly")
    }

    log.Println("node", "\t", node)
    log.Println("diff", "\t", diff, diff < 2*time.Hour)
    log.Println("existing", "\t", n.startDate, n.endDate)
    log.Println("new", "\t", data.startDate, data.endDate)

    if diff < 2*time.Hour {
        log.Println("BookingKamarOperasi_v2.isLessThanTwoHoursApart return 2, nil")
        return 2, nil
    } else {
        return 1, nil
    }

}

// This method is not to be used directly.
func (n *BinaryNode) insert(data BookingKamarOperasi_v2) (bool, error) {
    // error.
    if n == nil {
        return false, errors.New("this method is not to be used directly")
    }

    node, err := n.data.leftOrRight(data)
    if node == 0 {
        return false, err
    } else if node == 1 {
        if isLess, err := n.data.isLessThanTwoHoursApart(data, 1); isLess == 0 {
            return false, err
        } else if isLess == 2 {
            return false, nil
        } else if isLess == 1 {
            // continue
        } else {
            return false, errors.New("ok " + strconv.Itoa(isLess) + " is not implemented")
        }

        if n.left == nil {
            n.left = &BinaryNode{left: nil, right: nil, data: data}
        } else {
            n.left.insert(data)
        }

        return true, nil
    } else if node == 2 {
        if isLess, err := n.data.isLessThanTwoHoursApart(data, 2); isLess == 0 {
            return false, err
        } else if isLess == 2 {
            log.Println("BinaryNode.ok " + strconv.Itoa(isLess) + " " + strconv.FormatBool(false))
            return false, nil
        } else if isLess == 1 {
            // continue
        } else {
            return false, errors.New("ok " + strconv.Itoa(isLess) + " is not implemented")
        }

        if n.right == nil {
            n.right = &BinaryNode{left: nil, right: nil, data: data}
        } else {
            n.right.insert(data)
        }

        return true, nil
    } else {
        return false, errors.New("unknown error")
    }
}

type SafeDB_v2 struct {
    mu sync.Mutex
    v  BinaryTree
}

func (c *SafeDB_v2) Insert(startDate time.Time, duration time.Duration) (bool, error) {
    c.mu.Lock()
    ok, err := c.v.insert(startDate, startDate.Add(duration))
    log.Println("SafeDB_v2.Insert " + strconv.FormatBool(ok))
    log.Println()
    c.mu.Unlock()

    return ok, err
}

var C_v2 SafeDB_v2

func InitializeDB_v2() {
    C_v2 = SafeDB_v2{v: BinaryTree{}}
}

test.go

package bookingkamaroperasi_test

import (
    "testing"
    "time"

    "github.com/jasonrichdarmawan/cipta_integrasi_nusantara_backend/bookingkamaroperasi"
)

func TestInsert(t *testing.T) {
    bookingkamaroperasi.InitializeDB_v2()

    now, err := time.Parse("02-01-2006 15:04Z07:00", "01-01-2022 10:00+07:00")
    if err != nil {
        t.Error(err)
    }
    // A doctor books on 01/01/2022 10:00 for 2 hours
    if got, err := bookingkamaroperasi.C_v2.TryInsert(now, 2*time.Hour); !got {
        t.Errorf("%v-12:00 = %t; want true; error %v", now.Format("02-01-2006 15:04"), got, err)
    }

    // Another doctor books on 01/01/2022 15:00 for 2 hours
    today15 := now.Add(5 * time.Hour)
    if got, err := bookingkamaroperasi.C_v2.TryInsert(today15, 2*time.Hour); !got {
        t.Errorf("%v-17:00 = %t; want true; error %v", today15.Format("02-01-2006 15:04"), got, err)
    }

    // Another doctor books on 01/01/2022 18:00 for 2 hours
    today18 := now.Add(8 * time.Hour)
    if got, err := bookingkamaroperasi.C_v2.TryInsert(today18, 2*time.Hour); got {
        t.Errorf("%v-20:00 = %t; want false; error %v", today18.Format("02-01-2006 15:04"), got, err)
    }

    // Another doctor books on 01/01/2022 07:00 for 2 hours
    today07 := now.Add(-3 * time.Hour)
    if got, err := bookingkamaroperasi.C_v2.TryInsert(today07, 2*time.Hour); got {
        t.Errorf("%v-09:00 = %t; want false; error %v", today07.Format("02-01-2006 15:04"), got, err)
    }

    // out of scope
    // Another doctor books on 01/01/2022 02:00 for 2 hours
    today02 := now.Add(-8 * time.Hour)
    if got, err := bookingkamaroperasi.C_v2.TryInsert(today02, 2*time.Hour); !got {
        t.Errorf("%v-04:00 = %t; want false; error %v", today02.Format("02-01-2006 15:04"), got, err)
    }
    // Another doctor books on 31/12/2022 23:00 for 2 hours
    yesterday23_today01 := now.Add(-11 * time.Hour)
    if got, err := bookingkamaroperasi.C_v2.TryInsert(yesterday23_today01, 2*time.Hour); got {
        t.Errorf("%v - 01-01-2022 01:00 = %t; want false; error %v", yesterday23_today01.Format("02-01-2006 15:04"), got, err)
    }
}


问:
AWS SNS and load balancer
I'm currently facing a problem when thinking about a event driven arch using SNS to decouple some applications.

Imagine a SNS Topic, and I have application A producing messages to it and application B will listen and consume messages from this topic.

I want to consume the messages only once if I attach one more instance to application B so shall I use Load balancer for the same or not ?
I will subscribe the topic using load balancer URL and distribute the messages between the instances of application B.

Title: AWS SNS and load balancer


问:
Why does this happen when I try to install react-toastify

How do I fix this. the toast functionality doesn't work.

I was trying to install react-toastify


问:
Django ModelChoiceField with custom queryset not validating
My ModelChoiceField is not validating saying that the selected choice is not an instance.

I am passing a custom queryset to my modelChoiceField that uses a custom manager (objects_sys) to return extra entries that are archived and do not normally display with normal queries.  The entries are displayed and I can select them, but when the form posts and Django tries to validate, it must be using another query that filters out the archived items so those are not valid choices.

I'm using class based views - this vails in form_valid()

```<code>Models:
class Item(models.Model):
    name = UpperCaseCharField(max_length=10, primary_key=True)
    qty_on_hand = models.IntegerField()
    description = models.CharField(max_length=200)
    archive = models.BooleanField()

class ItemLoc(models.Model):
    item = models.ForeignKey(Item, on_delete=models.PROTECT)
    location = models.CharField(max_length=200)
</code>```

My Form:

```<code>class ItemForm(forms.ModelForm):
class Meta:
        model = ItemLoc
        fields = (
            'item',
            'location'
            )
    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)

        self.fields['item'].queryset = Item.objects_sys.filter(qty_on_hand__gt=0)
</code>```

Specifically, there is an existing entry in the Item table with name = "MULTIPLE" that has its archive field = True.  The objects manager returns only active records (archive=False)  The objects_sys manager returns all records including archived records (this was the original objects manager).  The error returned after attempted validation is: "Item instance with name 'MULTIPLE' does not exist."

Do I need to pass this custom query in again to the ModelChoiceField at some point (maybe during POST) so that the extra values are available for validation?

Body:
My ModelChoiceField is not validating saying that the selected choice is not an instance.

I am passing a custom queryset to my modelChoiceField that uses a custom manager (objects_sys) to return extra entries that are archived and do not normally display with normal queries.  The entries are displayed and I can select them, but when the form posts and Django tries to validate, it must be using another query that filters out the archived items so those are not valid choices.

I'm using class based views - this vails in form_valid()

Models:
class Item(models.Model):
    name = UpperCaseCharField(max_length=10, primary_key=True)
    qty_on_hand = models.IntegerField()
    description = models.CharField(max_length=200)
    archive = models.BooleanField()

class ItemLoc(models.Model):
    item = models.ForeignKey(Item, on_delete=models.PROTECT)
    location = models.CharField(max_length=200)

My Form:

class ItemForm(forms.ModelForm):
class Meta:
        model = ItemLoc
        fields = (
            'item',
            'location'
            )
    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)

        self.fields['item'].queryset = Item.objects_sys.filter(qty_on_hand__gt=0)

Specifically, there is an existing entry in the Item table with name = "MULTIPLE" that has its archive field = True.  The objects manager returns only active records (archive=False)  The objects_sys manager returns all records including archived records (this was the original objects manager).  The error returned after attempted validation is: "Item instance with name 'MULTIPLE' does not exist."

Do I need to pass this custom query in again to the ModelChoiceField at some point (maybe during POST) so that the extra values are available for validation?