问:
Time difference problems when using FROM_UNIXTIME() - localhost vs. server - php / MySQL
I am trying to create an appointment booking system for a hairdresser.

The conception is that they open at 9:00 and close at 15:30. This is my timeframe.

Steps of booking:

choosing the service (it contains the duration of the service is seconds)

choosing the desired date (will be passed to a function when checking dates)

select date

I loop through the day and use the duration of the service to create timeslots, comparing if it the calendar has enough time to book before next scheduled appointment.

My problem is that we want to go live and the timestamps for the bookable slots are different.

Let's say I want to book for 2022-12-15 09:00:00.

On my local machine the timestamp is 1671091200.

And on the server for same card I get a value of 1671094800.

The problem is coming from here I guess:

```<code>$Date = "2022-12-15"; //this is a date coming from a dropdown
$DayStart = strtotime($Date." 09:00:00");
</code>```

After converting to time, I have the time mentioned above: 1671091200

I discovered, that they are due to different time zone settings and most probably my machine is using UTC and the server CET.

I am based in Hungary and the website will go live in Germany and somehow I have to make sure that if I book for 09:00:00, it won't be registered as 10:00:00.

And of course for future developments I need to know how to avoid this.

One more important thing. I am using the same remote database from the server. I open localhost, connect to db on server and works good - then open domain, connect to exact same db on same server and everything is shifted +1 hour,

Maybe if there is another option to maintain this without unix time, I am open to everything but calculations with duration seconds are done this way.

Currently I am using this query but I may have to prepare time data in php instead of MySQL:

INSERT INTO `timetable.appointments` (Name, Phone, Email, AppDate, AppStart, AppEnd, Duration, ServiceID) VALUES (?,?,?,?,from_unixtime(?),from_unixtime(?),?,?)

EDIT: Maybe the problem is not inserting a wrong value with unixtime but the strtotime should work as timezone would be same I guess (?)

Thanks for reading and thinking along!

Have a nice day!

Body:
I am trying to create an appointment booking system for a hairdresser.

The conception is that they open at 9:00 and close at 15:30. This is my timeframe.

Steps of booking:

choosing the service (it contains the duration of the service is seconds)

choosing the desired date (will be passed to a function when checking dates)

select date

I loop through the day and use the duration of the service to create timeslots, comparing if it the calendar has enough time to book before next scheduled appointment.

My problem is that we want to go live and the timestamps for the bookable slots are different.

Let's say I want to book for 2022-12-15 09:00:00.

On my local machine the timestamp is 1671091200.

And on the server for same card I get a value of 1671094800.

The problem is coming from here I guess:

$Date = "2022-12-15"; //this is a date coming from a dropdown
$DayStart = strtotime($Date." 09:00:00");

After converting to time, I have the time mentioned above: 1671091200

I discovered, that they are due to different time zone settings and most probably my machine is using UTC and the server CET.

I am based in Hungary and the website will go live in Germany and somehow I have to make sure that if I book for 09:00:00, it won't be registered as 10:00:00.

And of course for future developments I need to know how to avoid this.

One more important thing. I am using the same remote database from the server. I open localhost, connect to db on server and works good - then open domain, connect to exact same db on same server and everything is shifted +1 hour,

Maybe if there is another option to maintain this without unix time, I am open to everything but calculations with duration seconds are done this way.

Currently I am using this query but I may have to prepare time data in php instead of MySQL:

INSERT INTO `timetable.appointments` (Name, Phone, Email, AppDate, AppStart, AppEnd, Duration, ServiceID) VALUES (?,?,?,?,from_unixtime(?),from_unixtime(?),?,?)

EDIT: Maybe the problem is not inserting a wrong value with unixtime but the strtotime should work as timezone would be same I guess (?)

Thanks for reading and thinking along!

Have a nice day!


来源: stackexchange

问:
XML to JSON Array Conversion using XSLT
I have a scenario where in I am trying to convert the following XML:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<root>
    <ClientId>1023</ClientId>
    <PackageId>1542</PackageId>
    <LegalEntityId>30</LegalEntityId>
    <title>Mr</title>
    <firstName>kumar</firstName>
    <middleName></middleName>
    <lastName>kumar</lastName>
    <contactDetails>
        <emailIds>
            <emailIdType>Primary</emailIdType>
            <emailId>kumar90@kumarte.com</emailId>
        </emailIds>
        <contactNumber>
            <contactType>Mobile</contactType>
            <candidateContact>9999999999</candidateContact>
        </contactNumber>
    </contactDetails>
    <EICCaseDocuments>
        <DocumentType>AuthorizationForm</DocumentType>
        <fileContent>PDF URL</fileContent>
        <fileType>1</fileType>
    </EICCaseDocuments>
    <checks>
        <CheckId>28</CheckId>
        <Source>Graduation</Source>
        <checkFields>
            <Name>Registration number/Seat number </Name>
            <Value>Value</Value>
        </checkFields>
        <checkFields>
            <Name>Mode of Study: Full time / Part time / Distance learning course</Name>
            <Value>Value</Value>
        </checkFields>
        <files>
            <DocumentName>Document Name</DocumentName>
            <fileContent>PDF URL</fileContent>
            <fileType>1</fileType>
        </files>
    </checks>
    <checks>
        <CheckId>30</CheckId>
        <Source>Previous</Source>
        <checkFields>
            <Name>Employee code</Name>
            <Value>Value</Value>
        </checkFields>
        <checkFields>
            <Name>Designation</Name>
            <Value>Value</Value>
        </checkFields>
        <files>
            <DocumentName>Document Name</DocumentName>
            <fileContent>PDF URL</fileContent>
            <fileType>1</fileType>
        </files>
    </checks>
</root>
</code>```

Into a JSON Payload that looks like the following:

```<code>{
  "ClientId": 1023,
  "PackageId": 1542,
  "LegalEntityId": 30,
  "title": "Mr",
  "firstName": "kumar",
  "middleName": "",
  "lastName": "kumar",
  "contactDetails": {
    "emailIds": [
      {
        "emailIdType": "Primary",
        "emailId": "kumar0@kumarte.com"
      }
    ],
    "contactNumber": [
      {
        "contactType": "Mobile",
        "candidateContact": "9999999999"
      }
    ]
  },
    "EICCaseDocuments": [
        {
            "DocumentType": "AuthorizationForm",
            "fileContent": "<PDF URL>",
            "fileType": "1"
        }
    ],
  "checks": [
    {
      "CheckId": 28,
      "Source": "Graduation",
      "checkFields": [
        {
          "Name": "Registration number/Seat number ",
          "Value": "Value"
        },
        {
          "Name": "Mode of Study: Full time / Part time / Distance learning course",
          "Value": "Value"
        }
      ],
      "files": [{
          "DocumentName": "<Document Name>",
          "fileContent": "<PDF URL>",
          "fileType": "1"
        }]
    },
    {
      "CheckId": 30,
      "Source": "Previous",
      "checkFields": [
        {
          "Name": "Employee code",
          "Value": "Value"
        },
        {
          "Name": "Designation",
          "Value": "Value"
        }
      ],
      "files": [{
          "DocumentName": "<Document Name>",
          "fileContent": "<PDF URL>",
          "fileType": "1"
        }]
    }
  ]
}
</code>```

As you can see, every node is an array and there are even some fields whose values are not enclosed in quotes.

I am trying to achieve this on SAP CPI using XSLT Mapping. I have played around with the following code but I am not getting the desired output. Please find my code below:

```<code><?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns0="http://use your namespace">
<xsl:output method="text"/>
<xsl:template match="/root">{
    <xsl:apply-templates select="*"/> }
</xsl:template>

<!-- Object or Element Property-->
<xsl:template match="*">

    "<xsl:value-of select="name()"/>" : <xsl:call-template name="Properties"/>

</xsl:template>

<!-- Array Element -->
<xsl:template match="*" mode="ArrayElement">
    <xsl:call-template name="Properties"/>
</xsl:template>

<!-- Object Properties -->
<xsl:template name="Properties">
    <xsl:variable name="childName" select="name(*[1])"/>
    <xsl:choose>
        <xsl:when test="not(*|@*)">"<xsl:value-of select="."/>"</xsl:when>
        <xsl:otherwise>{
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates select="*"/>
}</xsl:otherwise>
    </xsl:choose>
    <xsl:if test="following-sibling::*">,</xsl:if>
</xsl:template>

<!-- Attribute Property -->
<xsl:template match="@*">"<xsl:value-of select="name()"/>" : "<xsl:value-of select="."/>",
</xsl:template>
</xsl:stylesheet>
</code>```

Through this code, I am getting "checks" and "checkFields" the way i require.

However, I am unable to enclose "emailIds","contactNumber","EICCaseDocuments" and any "files" nodes in an array.
Also, how can i remove the quotes enclosing ClientId, Packageid, LegalEntity and CheckId?

I understand that this is a generic code. But really need some guidance on how to achieve the answers to both my queries above.

Could really use some help on this.

Thanks!

ContentLicense: CC BY-SA 4.0

Title: XML to JSON Array Conversion using XSLT

Body:
I have a scenario where in I am trying to convert the following XML:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <ClientId>1023</ClientId>
    <PackageId>1542</PackageId>
    <LegalEntityId>30</LegalEntityId>
    <title>Mr</title>
    <firstName>kumar</firstName>
    <middleName></middleName>
    <lastName>kumar</lastName>
    <contactDetails>
        <emailIds>
            <emailIdType>Primary</emailIdType>
            <emailId>kumar90@kumarte.com</emailId>
        </emailIds>
        <contactNumber>
            <contactType>Mobile</contactType>
            <candidateContact>9999999999</candidateContact>
        </contactNumber>
    </contactDetails>
    <EICCaseDocuments>
        <DocumentType>AuthorizationForm</DocumentType>
        <fileContent>PDF URL</fileContent>
        <fileType>1</fileType>
    </EICCaseDocuments>
    <checks>
        <CheckId>28</CheckId>
        <Source>Graduation</Source>
        <checkFields>
            <Name>Registration number/Seat number </Name>
            <Value>Value</Value>
        </checkFields>
        <checkFields>
            <Name>Mode of Study: Full time / Part time / Distance learning course</Name>
            <Value>Value</Value>
        </checkFields>
        <files>
            <DocumentName>Document Name</DocumentName>
            <fileContent>PDF URL</fileContent>
            <fileType>1</fileType>
        </files>
    </checks>
    <checks>
        <CheckId>30</CheckId>
        <Source>Previous</Source>
        <checkFields>
            <Name>Employee code</Name>
            <Value>Value</Value>
        </checkFields>
        <checkFields>
            <Name>Designation</Name>
            <Value>Value</Value>
        </checkFields>
        <files>
            <DocumentName>Document Name</DocumentName>
            <fileContent>PDF URL</fileContent>
            <fileType>1</fileType>
        </files>
    </checks>
</root>

Into a JSON Payload that looks like the following:

{
  "ClientId": 1023,
  "PackageId": 1542,
  "LegalEntityId": 30,
  "title": "Mr",
  "firstName": "kumar",
  "middleName": "",
  "lastName": "kumar",
  "contactDetails": {
    "emailIds": [
      {
        "emailIdType": "Primary",
        "emailId": "kumar0@kumarte.com"
      }
    ],
    "contactNumber": [
      {
        "contactType": "Mobile",
        "candidateContact": "9999999999"
      }
    ]
  },
    "EICCaseDocuments": [
        {
            "DocumentType": "AuthorizationForm",
            "fileContent": "<PDF URL>",
            "fileType": "1"
        }
    ],
  "checks": [
    {
      "CheckId": 28,
      "Source": "Graduation",
      "checkFields": [
        {
          "Name": "Registration number/Seat number ",
          "Value": "Value"
        },
        {
          "Name": "Mode of Study: Full time / Part time / Distance learning course",
          "Value": "Value"
        }
      ],
      "files": [{
          "DocumentName": "<Document Name>",
          "fileContent": "<PDF URL>",
          "fileType": "1"
        }]
    },
    {
      "CheckId": 30,
      "Source": "Previous",
      "checkFields": [
        {
          "Name": "Employee code",
          "Value": "Value"
        },
        {
          "Name": "Designation",
          "Value": "Value"
        }
      ],
      "files": [{
          "DocumentName": "<Document Name>",
          "fileContent": "<PDF URL>",
          "fileType": "1"
        }]
    }
  ]
}

As you can see, every node is an array and there are even some fields whose values are not enclosed in quotes.

I am trying to achieve this on SAP CPI using XSLT Mapping. I have played around with the following code but I am not getting the desired output. Please find my code below:

<?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns0="http://use your namespace">
<xsl:output method="text"/>
<xsl:template match="/root">{
    <xsl:apply-templates select="*"/> }
</xsl:template>

<xsl:template match="*">

    "<xsl:value-of select="name()"/>" : <xsl:call-template name="Properties"/>

</xsl:template>

<xsl:template match="*" mode="ArrayElement">
    <xsl:call-template name="Properties"/>
</xsl:template>

<xsl:template name="Properties">
    <xsl:variable name="childName" select="name(*[1])"/>
    <xsl:choose>
        <xsl:when test="not(*|@*)">"<xsl:value-of select="."/>"</xsl:when>
        <xsl:otherwise>{
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates select="*"/>
}</xsl:otherwise>
    </xsl:choose>
    <xsl:if test="following-sibling::*">,</xsl:if>
</xsl:template>

<xsl:template match="@*">"<xsl:value-of select="name()"/>" : "<xsl:value-of select="."/>",
</xsl:template>
</xsl:stylesheet>

Through this code, I am getting "checks" and "checkFields" the way i require.

However, I am unable to enclose "emailIds","contactNumber","EICCaseDocuments" and any "files" nodes in an array.
Also, how can i remove the quotes enclosing ClientId, Packageid, LegalEntity and CheckId?

I understand that this is a generic code. But really need some guidance on how to achieve the answers to both my queries above.

Could really use some help on this.

Thanks!


问:
How to set up Auth0 with NextJS to use a custom domain for login?
I've added a custom domain to Auth0: auth.mydomain.com and verified it. In the Universal Login config I enabled the Customize Login Page option and I added my domain to the issuer config there:

```<code>var lock = new Auth0Lock(config.clientID, config.auth0Domain, {
      auth: {
        redirectUrl: config.callbackURL,
        responseType: (config.internalOptions || {}).response_type ||
          (config.callbackOnLocationHash ? 'token' : 'code'),
        params: config.internalOptions
      },
      configurationBaseUrl: config.clientConfigurationBaseUrl,
      overrides: {
        __tenant: config.auth0Tenant,
        // __token_issuer: config.authorizationServer.issuer
        __token_issuer: 'auth.mydomain.com'
      },
      ...
    });
</code>```

I'm not sure what else I need to change to make it working with my application so users will be redirected to auth.mydomain.com for login instead of using the Auth0 tenant domain.

Body:
I've added a custom domain to Auth0: auth.mydomain.com and verified it. In the Universal Login config I enabled the Customize Login Page option and I added my domain to the issuer config there:

var lock = new Auth0Lock(config.clientID, config.auth0Domain, {
      auth: {
        redirectUrl: config.callbackURL,
        responseType: (config.internalOptions || {}).response_type ||
          (config.callbackOnLocationHash ? 'token' : 'code'),
        params: config.internalOptions
      },
      configurationBaseUrl: config.clientConfigurationBaseUrl,
      overrides: {
        __tenant: config.auth0Tenant,
        // __token_issuer: config.authorizationServer.issuer
        __token_issuer: 'auth.mydomain.com'
      },
      ...
    });

I'm not sure what else I need to change to make it working with my application so users will be redirected to auth.mydomain.com for login instead of using the Auth0 tenant domain.


问:
How do I view / edit FBX animations in python? using py-fbx
I'm looking to edit or create new animation data from a FBX file, downloaded from mixamo,

untill now, I found the py-fbx library, I also found the documentation but its only for c/c++ and I'm having a tough time translating(?)

My goal is, to view / edit the animation data from a fbx file, say I downloaded a humanoid animation from mixamo, and for it, I want to change the animation data for the 'HEAD' or something or completely remove it.

docs: http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/index.html


问:
Which is the best database for accessing big time-based data?
we need some help, choosing the best database for the following upcoming situation:

Write:
We'll get a huge number of data each minute (round about one million entries) and need to save them in a database. One of the unique identifiers of the entries are timestamps.

Read:
The software should be able to load the stored data for an user-defined time range. The loading process should be as fast as possible.

Currently, we are using the Microsoft SQL Server in our application. I'm not sure, if this is the right technology for our new requirements.

Which database should we use? Do we need to replace MSSQL with something or is another database able to run simultaneously with it?

Thank you!


问:
getting wrong answer for finding largest of 2 numbers using readline-sync in js
if I enter 55 and 23, it shows correct output as 'Largest number is 55'
But if I enter 12 and 3, it shows incorrect output as 'Largest number is 3' (i guess the program is reading only the first letter of the input value)

```<code>var read=require("readline-sync")
var a=read.question("Enter 2 Numbers: ")
var b=read.question()
if(a>b){
    console.log("Largest number is "+a)
}else{
    console.log("Largest number is "+b)
}

</code>```

This is what i'm getting

Body:
if I enter 55 and 23, it shows correct output as 'Largest number is 55'
But if I enter 12 and 3, it shows incorrect output as 'Largest number is 3' (i guess the program is reading only the first letter of the input value)

var read=require("readline-sync")
var a=read.question("Enter 2 Numbers: ")
var b=read.question()
if(a>b){
    console.log("Largest number is "+a)
}else{
    console.log("Largest number is "+b)
}

This is what i'm getting


问:
When I'm using a service as an adapter can I stub said service for my tests or should I use it with its own stubs?
So the situation is as follows, we have an adapter that was complex enough to make it a full service (Service B) (ie. decouple the call to the external dependencies to another adapter and test the logic with stubs).

Now if I want to make tests in the domain logic of another service (Service A) that has a port that Service B implements, should I use Service B with its own stubs or should I stub Service B entirely? Pic related below:


问:
Java Memory barrier on CPU level
I am wondering about the mechanism for Memory Barrier on the CPU level, not compile level. Is it possible in Java? The synchronized keyword introduces a memory barrier and different to consider like happens-before, etc.
w

Title: Java Memory barrier on CPU level


问:
Component inside auto configuration application not getting registered
I have created a simple spring boot starter configuration.
Along with other files I have Interceptor which should auto-register.

My Configuration is registered in the file is as follow:

```<code>/resource/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports=DynamicDataSourceAutoConfiguration
</code>```

Autoconfiguration kicks in but the components inside this are not initialized.
My default component inside auto configuration is as follow;

@Component
public class AppWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CommonHeadersInterceptor());
    }
}
```
<p>This starter I am using in multiple micro-service.</p>
<p>Since it is not registered automatically. I have to re-create this <code>AppWebMvcConfigurer</code> file in each of my micro-services.
Please help me if there is some other configuration I need to do for AutoConfiguration to kick in.</p>
<p>FYI: Other files include</p>
<ul>
<li>Properties</li>
<li>Configuration</li>
<li>DataSources</li>
</ul>
<p><strong>EDIT:1</strong></p>
<p>I created config file and added the same path in .imports file metioned above. For time being this seems solved.</p>
```@Configuration
public class HeaderTenantMvcConfiguration {

    @Bean
    public AppWebMvcConfigurer webMvcConfigurer() {
        return new AppWebMvcConfigurer();
    }
}
```
<p>My <code>org.springframework.boot.autoconfigure.AutoConfiguration.imports</code> now looks something like this:</p>
```com.silentsudo.data.DataSourceAutoConfig
com.silentsudo.web.mvc.AppWebMvcConfigurer
```

Body:
I have created a simple spring boot starter configuration.
Along with other files I have Interceptor which should auto-register.

My Configuration is registered in the file is as follow:

/resource/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports=DynamicDataSourceAutoConfiguration

Autoconfiguration kicks in but the components inside this are not initialized.
My default component inside auto configuration is as follow;

@Component
public class AppWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CommonHeadersInterceptor());
    }
}

This starter I am using in multiple micro-service.

Since it is not registered automatically. I have to re-create this AppWebMvcConfigurer file in each of my micro-services.
Please help me if there is some other configuration I need to do for AutoConfiguration to kick in.

FYI: Other files include

Properties

Configuration

DataSources

EDIT:1

I created config file and added the same path in .imports file metioned above. For time being this seems solved.

@Configuration
public class HeaderTenantMvcConfiguration {

    @Bean
    public AppWebMvcConfigurer webMvcConfigurer() {
        return new AppWebMvcConfigurer();
    }
}

My org.springframework.boot.autoconfigure.AutoConfiguration.imports now looks something like this:

com.silentsudo.data.DataSourceAutoConfig
com.silentsudo.web.mvc.AppWebMvcConfigurer


问:
Apache AliasMatch Creating Infinite 301 Redirects
while trying out AliasMatch I found a curious behaviour of it.

Let's say you have rules like this in the httpd.conf:

```<code>AliasMatch "/goinfinite/" "C:/test/"
<Directory "C:/test">
    Require all granted
</Directory>
</code>```

The directory contains an index.php. However, said php file is not used as directory index. Instead, a 301 redirect is created to http://localhost/goinfinite/index.php/. From that page a redirect is created to http://localhost/goinfinite/index.php/index.php/ and so on.

My goal was to just forward any URL that contains /goinfinite in its path to C:/test and use its index.php file, however I created an infinity loop of 301 redirects. I am unsure what causes these explicit redirects which then trigger the AliasMatch rule again.

I have read the Apache documentation. This is what would be needed for AliasMatch to work like Alias:

```<code>AliasMatch "^/image/(.*)$" "/ftp/pub/image/$1"
</code>```

In my case, I could do something like

```<code>AliasMatch "/goinfinite/(.*)" "C:/test/$1"
</code>```

However, if the path is simply /goinfinite/ $1 would not contain anything. So why would it work in this case?

My question is an academic one, I would like to understand why the directory index is not used, but a redirect triggered instead.

Body:
while trying out AliasMatch I found a curious behaviour of it.

Let's say you have rules like this in the httpd.conf:

AliasMatch "/goinfinite/" "C:/test/"
<Directory "C:/test">
    Require all granted
</Directory>

The directory contains an index.php. However, said php file is not used as directory index. Instead, a 301 redirect is created to http://localhost/goinfinite/index.php/. From that page a redirect is created to http://localhost/goinfinite/index.php/index.php/ and so on.

My goal was to just forward any URL that contains /goinfinite in its path to C:/test and use its index.php file, however I created an infinity loop of 301 redirects. I am unsure what causes these explicit redirects which then trigger the AliasMatch rule again.

I have read the Apache documentation. This is what would be needed for AliasMatch to work like Alias:

AliasMatch "^/image/(.*)$" "/ftp/pub/image/$1"

In my case, I could do something like

AliasMatch "/goinfinite/(.*)" "C:/test/$1"

However, if the path is simply /goinfinite/ $1 would not contain anything. So why would it work in this case?

My question is an academic one, I would like to understand why the directory index is not used, but a redirect triggered instead.


问:
Getting too many redirect issue while using following plugin
I am using "nuxt": "^2.15.8", installed the package successfully but it is redirecting too many times :(

Any suggestions?

I just want to check if a user is coming from non-https my application should redirect back to https.

Installed a package from npm but not working as expected.


问:
Add own custom Validator to registerOptions from react-hook-form
I'd like to add a custom validator to RegisterOptions from react-hook-form. Just like valueAsNumber and valueAsDate. I'd like to create it globally, so I have the option everywhere in my code. I'm using TypeScript. Now I'd like to use it like this:

register("name", { valueAsNullableString: true }
```
<p>Where <code>valueAsNullableString</code> is:</p>
<pre class="lang-ts prettyprint-override"><code>function valueAsNullableString(value: string): string | null {
    return value ? value : null;
}
</code>```

Body:
I'd like to add a custom validator to RegisterOptions from react-hook-form. Just like valueAsNumber and valueAsDate. I'd like to create it globally, so I have the option everywhere in my code. I'm using TypeScript. Now I'd like to use it like this:

register("name", { valueAsNullableString: true }

Where valueAsNullableString is:

function valueAsNullableString(value: string): string | null {
    return value ? value : null;
}


问:
pyautogui.pixelMatchesColor cant use Value from ConfigParser config.ini
I Made a config.ini for my Python project
now i be able to save values and put them as print or something inside my Code
This is working for all Statik things like Device= str....ConfigParser and is shown in print (Device)

But it is not working when i give that code or Variable to PixelmatchesColor if i do this for X,Y Cords its get an error cant read or cant use is no right parameter. When i use this inside Print all works well and shown inside Promt

If there is no Way to make a Config File that works with pyautogui pixel match color i will try this code How can pyautogui.pixelMatchesColor not work properly?. It looks for an Image and then it uses pixelmatch to verify. i only need to look at a Bell and check if they is on Screen if it is found (Color or IMG) all is fine if not restart after time Browser


问:
Hebbian learning in ANN with Keras
I would like to implement an artificial neural network via Hebbian learning for MNIST multiclass classification.
Is there a way to set or change learning rules in Keras for define an Hebbian ANN?
Or a method to change the update of the weights of the network based on a rule decided by me instead of the classic Keras settings?</p>
```<code>Otherwise I would have thought of defining a neural network without the aid of the libraries but there would certainly be less accuracy and I would not have the practicality given by the libraries
</code>```

Title: Hebbian learning in ANN with Keras

Body:
I would like to implement an artificial neural network via Hebbian learning for MNIST multiclass classification.
Is there a way to set or change learning rules in Keras for define an Hebbian ANN?
Or a method to change the update of the weights of the network based on a rule decided by me instead of the classic Keras settings?

Otherwise I would have thought of defining a neural network without the aid of the libraries but there would certainly be less accuracy and I would not have the practicality given by the libraries


问:
ConstraintLayout inside Row with IntrinsicSize.Min height
i have an issue in placing ConstraintLayout as Row's Child (Compose Version : 1.1.1). when set the height of Row to IntrinsicSize.Min, the content of ConstraintLayout gets corrupted, ie it's width gets narrow and all children are placed in that narrow width.
here's the code

```<code> Row(modifier = Modifier.height(IntrinsicSize.Min) ) {
       ConstraintLayout(modifier = Modifier){
          .
          .
          .
        }
}
</code>```

and here are screenshots

before putting inside Box:

after :

here's  ConstraintLayout Content:

```<code>  Surface(
        modifier = modifier,
        shape = RoundedCornerShape(roundedCornerSize),
        border = BorderStroke(width = 1.dp,
            color = Color.Gray),
        color = Color.Green,
        elevation = elevation) {

        ConstraintLayout(modifier = Modifier
            .fillMaxWidth()
            .background(color = Color.Blue)
            .padding(16.dp)) {
            val (dragIconRef, imageRef, nameRef, updateTimeRef, priceRef, changeRef) = createRefs()
            val endMarginFromImageStart = 8.dp

            Icon(modifier = Modifier.constrainAs(dragIconRef) {
                end.linkTo(parent.end)
                linkTo(top = parent.top, bottom = parent.bottom)

            }, painter = painterResource(id = R.drawable.ic_drag_indicator),
                contentDescription = null)

            Image(
                modifier = Modifier
                    .constrainAs(imageRef) {
                        end.linkTo(dragIconRef.start, margin = 16.dp)
                        linkTo(top = parent.top, bottom = parent.bottom)

                    }
                    .size(36.dp),
                painter = painterResource(id = R.drawable.ic_notify),
                contentDescription = null
            )

            Text(
                modifier = Modifier.constrainAs(nameRef) {
                    top.linkTo(imageRef.top)
                    end.linkTo(imageRef.start, margin = endMarginFromImageStart)
                },
                text = itemModel.name,
            )

            Text(
                modifier = Modifier.constrainAs(updateTimeRef) {
                    bottom.linkTo(imageRef.bottom)
                    end.linkTo(imageRef.start, margin = endMarginFromImageStart)
                },
                text = itemModel.updateTime,
            )

            Text(
                modifier = Modifier.constrainAs(priceRef) {
                    baseline.linkTo(nameRef.baseline)
                    end.linkTo(changeRef.end)
                },
                text = itemModel.price,
            )

            Text(
                modifier = Modifier.constrainAs(changeRef) {
                    baseline.linkTo(updateTimeRef.baseline)
                    start.linkTo(parent.start)
                },
                text = itemModel.change.toString(),
            )

        }
    }
</code>```

Body:
i have an issue in placing ConstraintLayout as Row's Child (Compose Version : 1.1.1). when set the height of Row to IntrinsicSize.Min, the content of ConstraintLayout gets corrupted, ie it's width gets narrow and all children are placed in that narrow width.
here's the code

 Row(modifier = Modifier.height(IntrinsicSize.Min) ) {
       ConstraintLayout(modifier = Modifier){
          .
          .
          .
        }
}

and here are screenshots

before putting inside Box:

after :

here's  ConstraintLayout Content:

  Surface(
        modifier = modifier,
        shape = RoundedCornerShape(roundedCornerSize),
        border = BorderStroke(width = 1.dp,
            color = Color.Gray),
        color = Color.Green,
        elevation = elevation) {

        ConstraintLayout(modifier = Modifier
            .fillMaxWidth()
            .background(color = Color.Blue)
            .padding(16.dp)) {
            val (dragIconRef, imageRef, nameRef, updateTimeRef, priceRef, changeRef) = createRefs()
            val endMarginFromImageStart = 8.dp

            Icon(modifier = Modifier.constrainAs(dragIconRef) {
                end.linkTo(parent.end)
                linkTo(top = parent.top, bottom = parent.bottom)

            }, painter = painterResource(id = R.drawable.ic_drag_indicator),
                contentDescription = null)

            Image(
                modifier = Modifier
                    .constrainAs(imageRef) {
                        end.linkTo(dragIconRef.start, margin = 16.dp)
                        linkTo(top = parent.top, bottom = parent.bottom)

                    }
                    .size(36.dp),
                painter = painterResource(id = R.drawable.ic_notify),
                contentDescription = null
            )

            Text(
                modifier = Modifier.constrainAs(nameRef) {
                    top.linkTo(imageRef.top)
                    end.linkTo(imageRef.start, margin = endMarginFromImageStart)
                },
                text = itemModel.name,
            )

            Text(
                modifier = Modifier.constrainAs(updateTimeRef) {
                    bottom.linkTo(imageRef.bottom)
                    end.linkTo(imageRef.start, margin = endMarginFromImageStart)
                },
                text = itemModel.updateTime,
            )

            Text(
                modifier = Modifier.constrainAs(priceRef) {
                    baseline.linkTo(nameRef.baseline)
                    end.linkTo(changeRef.end)
                },
                text = itemModel.price,
            )

            Text(
                modifier = Modifier.constrainAs(changeRef) {
                    baseline.linkTo(updateTimeRef.baseline)
                    start.linkTo(parent.start)
                },
                text = itemModel.change.toString(),
            )

        }
    }


问:
Increase utilization of GPU for Sentence Transformer inference
We'are using a Sentence Transformer model to calculate 1024-dim vectors for the purpose of similarity search. The model is served by a FastAPI web server exposing an API for other services to request a vector for a given text.

So we are planning to calculate vectors for a large document set (about 10_000_000 documents) and are running some tests.

Using a CPU, we're getting encoding speed of about 0.1 second per a sentence.

Using a GTX 1650 card we're getting about 0.01 second per a sentence with an average GPU  utilization of about 50-60%

So we decided to see if we could get further improvements by renting out a VPS with Tesla T4 card. The results are somewhat disappointing:

We're still getting the same 0.01 seconds per one sentence but with average GPU utilization of only 10-15%. So it looks like the card is heavily under-utilized.

We tried increasing the number of workers, but it did not have any effect.

What can I do to improve utilization of the GPU and get faster performance.

The embeddings are calculated using this line of code:

model.encode(text, device='cuda', normalize_embeddings=True).tolist()
```
<p>I'm using this command to monitor GPU performance</p>
```watch -d -n 0.5 nvidia-smi
```

and watching this column GPU-Util

Body:
We'are using a Sentence Transformer model to calculate 1024-dim vectors for the purpose of similarity search. The model is served by a FastAPI web server exposing an API for other services to request a vector for a given text.

So we are planning to calculate vectors for a large document set (about 10_000_000 documents) and are running some tests.

Using a CPU, we're getting encoding speed of about 0.1 second per a sentence.

Using a GTX 1650 card we're getting about 0.01 second per a sentence with an average GPU  utilization of about 50-60%

So we decided to see if we could get further improvements by renting out a VPS with Tesla T4 card. The results are somewhat disappointing:

We're still getting the same 0.01 seconds per one sentence but with average GPU utilization of only 10-15%. So it looks like the card is heavily under-utilized.

We tried increasing the number of workers, but it did not have any effect.

What can I do to improve utilization of the GPU and get faster performance.

The embeddings are calculated using this line of code:

model.encode(text, device='cuda', normalize_embeddings=True).tolist()

I'm using this command to monitor GPU performance

watch -d -n 0.5 nvidia-smi

and watching this column GPU-Util


问:
PostgresSQL: How to insert datetime exact as it is being sent by user?
I have a Postgrest DB which is using Prisma.I am sending the data from front end as below which is inserted into the DB.

```<code>{
  "name": "Play Football",
  "datetime" : "2022-12-01 01:00:00"
}
</code>```

However when I save it to DB it is getting converted to server datetime.
For e.g.

```<code>2022-12-01 07:20:14
</code>```

How can I ensure that the date that is inserted stays same as what has been entered.I dont mind it getting converted for other tables but need this functionality for only this table.

Body:
I have a Postgrest DB which is using Prisma.I am sending the data from front end as below which is inserted into the DB.

{
  "name": "Play Football",
  "datetime" : "2022-12-01 01:00:00"
}

However when I save it to DB it is getting converted to server datetime.
For e.g.

2022-12-01 07:20:14

How can I ensure that the date that is inserted stays same as what has been entered.I dont mind it getting converted for other tables but need this functionality for only this table.


问:
How can get the count of Active live actors?
I'm using akka cluster sharding 2.5.23. For my case i want to know the current live active actors count.I have read many articles saying use Lightbend telemetry which is paid.And Cinnamonor or kamon which i don't need that much of metrics.I only need to know current active actors. Any way to achieve this easy?</p>


问:
how to add file manager to my flutter IOS app
im working on both IOS and Android . for android i used the file_manager package now what i want to is that file manager for IOS also but unfortunately the file_manager package is not support for IOS so can someone guide me or same package like this.</p>


问:
How to use navigation inside ModalBottomSheet in Flutter?
I want to show a Webview inside a ModalBottomSheet. The behavior I want is that the back button should navigate the webview till it can go back. I was able to achieve that using WillPopScope.

But this also disables the closing of ModalBottomSheet on tapping outside it in the grey area. How can I achieve both the behaviors?


问:
Cut layout_height fromt the top
I tried to reduce the height of my app. But when I remove "fill_parent" and change it wih 8dp, it cuts the app from below, how can I cut it from Above?

```<code><?xml version="1.0" encoding="utf-8"?>
<com.lion.multiTabApp.ui.views.WebContent
    android:id="@id/webViewPane"
    android:visibility="visible"
    android:layout_width="fill_parent"
    "android:layout_height="8dp"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <com.lion.multiTabApp.ui.views.BrowserWebView
        android:id="@id/webView"
        android:visibility="visible"
        android:layout_width="fill_parent"
        android:layout_height="8dp" />
    <RelativeLayout
        android:id="@id/progressbarPanel"
        android:visibility="gone"
        android:layout_width="fill_parent"
        "android:layout_height="8dp"
        android:layout_alignParentTop="true">
        <TextView
            android:textSize="18.0sp"
            android:textColor="#ffffffff"
            android:gravity="center"
            android:id="@id/loadingCurtainDefault"
            android:background="#ee000000"
            android:visibility="gone"
            android:clickable="true"
            android:layout_width="fill_parent"
            android:layout_height="8dip"
            android:text="@string/loadingPaneTitle"
            android:editable="false"
            android:layout_below="@id/progressbar"
            android:layout_centerInParent="true" />
    </RelativeLayout>
    <RelativeLayout
        android:id="@id/errorDialogPanel"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:color="#55000000" />
</com.lion.multiTabApp.ui.views.WebContent>
</code>```

I tried to modify layout_height and I was expecting to cut the height from the top but it cuts it from the bottom

Title: Cut layout_height fromt the top

Body:
I tried to reduce the height of my app. But when I remove "fill_parent" and change it wih 8dp, it cuts the app from below, how can I cut it from Above?

<?xml version="1.0" encoding="utf-8"?>
<com.lion.multiTabApp.ui.views.WebContent
    android:id="@id/webViewPane"
    android:visibility="visible"
    android:layout_width="fill_parent"
    "android:layout_height="8dp"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <com.lion.multiTabApp.ui.views.BrowserWebView
        android:id="@id/webView"
        android:visibility="visible"
        android:layout_width="fill_parent"
        android:layout_height="8dp" />
    <RelativeLayout
        android:id="@id/progressbarPanel"
        android:visibility="gone"
        android:layout_width="fill_parent"
        "android:layout_height="8dp"
        android:layout_alignParentTop="true">
        <TextView
            android:textSize="18.0sp"
            android:textColor="#ffffffff"
            android:gravity="center"
            android:id="@id/loadingCurtainDefault"
            android:background="#ee000000"
            android:visibility="gone"
            android:clickable="true"
            android:layout_width="fill_parent"
            android:layout_height="8dip"
            android:text="@string/loadingPaneTitle"
            android:editable="false"
            android:layout_below="@id/progressbar"
            android:layout_centerInParent="true" />
    </RelativeLayout>
    <RelativeLayout
        android:id="@id/errorDialogPanel"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:color="#55000000" />
</com.lion.multiTabApp.ui.views.WebContent>

I tried to modify layout_height and I was expecting to cut the height from the top but it cuts it from the bottom


问:
Streamlit st.button Loop
i have some issue with st.button used inside a an enumerate lopp.

I have st.button inside a dataframe, on click i want the value of the button to be changed and a dataframe to be updated. Except that when i click i have multiple loop on my callback function.

To simplify here i take a say_hello function. here when I click i have 3 lines printed. But i can't figure out why. Thnks

```<code>def say_hello(x):
     print("hello : " + x)

user_table = {
'N' : [1,2,3],
'email' : ["aa@gmail.fr","bb@gmail.fr","cc@gmail.fr"],
'uid' : [1,2,3],
'verified' : ["yes","no","yes/no"],
'disabled' : ["hh","pp","kak"]
}

colms = st.columns((1, 2, 2, 1, 1))
fields = ["№", 'email', 'uid', 'verified', "action"]
for col, field_name in zip(colms, fields):
    # header
    col.write(field_name)

for x, email in enumerate(user_table['email']):
    col1, col2, col3, col4, col5 = st.columns((1, 2, 2, 1, 1))
    col1.write(x)  # index
    col2.write(user_table['email'][x])  # email
    col3.write(user_table['uid'][x])  # unique ID
    col4.write(user_table['verified'][x])   # email status
    disable_status = user_table['disabled'][x]  # flexible type of button
    button_type = "Unblock" if disable_status else "Block"
    button_phold = col5.empty()  # create a placeholder
    do_action = button_phold.button(button_type, key=x,on_click=say_hello(user_table['email'][x]))
    if do_action:
         pass # do some action with a row's data
         button_phold.empty()
</code>```

Title: Streamlit st.button Loop

Body:
i have some issue with st.button used inside a an enumerate lopp.

I have st.button inside a dataframe, on click i want the value of the button to be changed and a dataframe to be updated. Except that when i click i have multiple loop on my callback function.

To simplify here i take a say_hello function. here when I click i have 3 lines printed. But i can't figure out why. Thnks

def say_hello(x):
     print("hello : " + x)

user_table = {
'N' : [1,2,3],
'email' : ["aa@gmail.fr","bb@gmail.fr","cc@gmail.fr"],
'uid' : [1,2,3],
'verified' : ["yes","no","yes/no"],
'disabled' : ["hh","pp","kak"]
}

colms = st.columns((1, 2, 2, 1, 1))
fields = ["№", 'email', 'uid', 'verified', "action"]
for col, field_name in zip(colms, fields):
    # header
    col.write(field_name)

for x, email in enumerate(user_table['email']):
    col1, col2, col3, col4, col5 = st.columns((1, 2, 2, 1, 1))
    col1.write(x)  # index
    col2.write(user_table['email'][x])  # email
    col3.write(user_table['uid'][x])  # unique ID
    col4.write(user_table['verified'][x])   # email status
    disable_status = user_table['disabled'][x]  # flexible type of button
    button_type = "Unblock" if disable_status else "Block"
    button_phold = col5.empty()  # create a placeholder
    do_action = button_phold.button(button_type, key=x,on_click=say_hello(user_table['email'][x]))
    if do_action:
         pass # do some action with a row's data
         button_phold.empty()


问:
vue-docgen: how to show sub-components?
I'm using vue-docgen-cli to document my components. These are Vue3 using composition API and script setup under Vite.

Few of my components use some other component like this (filename: MyComponent.vue):

```<code><script setup lang="ts">

import SearchField from "@/components/SearchField.vue";
import SearchFieldTags from "@/components/SearchFieldTags.vue";
import Pager from "@/widgets/Pager.vue";
import FragmentWithContext from "@/components/FragmentWithContext.vue";

. . .
</code>```

How is it possible to add in the MyComponent documentation that it is using these four components?

In the function set in template.component of docgen.config.js there are isSubComponent and hasSubComponents arguments, but how to set them?

Thanks for enlighten me!
mario

Title: vue-docgen: how to show sub-components?


问:
fetch api CORS invocation throws (failed to fetch) exception
I'm trying to invoke an API call to an api published in an external machine, the api uses flask and has the annotation @crossOrigin, and I can reach it from my machine using postman, but when I try to call it from my code, I get the exception (failed to fetch), here's the code

```<code>    let  options ={
  method: 'POST',
  mode: 'cors',
  headers: {
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Headers' : 'Origin, X-Requested-With, Content-Type, Accept'
  },
  body: data
};

const resp = await fetch('http://1.2.3.4:8555/api/v1/upload', options);
</code>```

I also get the following syntax error in VSCode

```<code>Argument of type '{ method: string; mode: string; headers: { 'Access-Control-Allow-Origin': string; 'Access-Control-Allow-Headers': string; }; body: FormData; }' is not assignable to parameter of type 'RequestInit'.
</code>```

Types of property 'mode' are incompatible.
Type 'string' is not assignable to type 'RequestMode'.ts(2345)

Body:
I'm trying to invoke an API call to an api published in an external machine, the api uses flask and has the annotation @crossOrigin, and I can reach it from my machine using postman, but when I try to call it from my code, I get the exception (failed to fetch), here's the code

    let  options ={
  method: 'POST',
  mode: 'cors',
  headers: {
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Headers' : 'Origin, X-Requested-With, Content-Type, Accept'
  },
  body: data
};

const resp = await fetch('http://1.2.3.4:8555/api/v1/upload', options);

I also get the following syntax error in VSCode

Argument of type '{ method: string; mode: string; headers: { 'Access-Control-Allow-Origin': string; 'Access-Control-Allow-Headers': string; }; body: FormData; }' is not assignable to parameter of type 'RequestInit'.

Types of property 'mode' are incompatible.
Type 'string' is not assignable to type 'RequestMode'.ts(2345)


问:
Convert Antd menu to version >4.20
I'm trying to convert the old version of menu.Items into the new one with the items array.

This is what I currently have:

```<code>      <Menu defaultSelectedKeys={[selectedKey]} mode="inline" inlineIndent={13}>
        {items.map((item, index) => (
          <Menu.Item
            key={`SideMenu_${index}`}
            icon={item.icon}
            disabled={item.disabled}
          >
            <Link className={styles.sideMenuLink} to={item.href}>
              {item.title}
            </Link>
          </Menu.Item>
        ))}
      </Menu>
</code>```

And this is what I'm trying atm:

```<code>
  let menuItem;
  items.map((item, index) => {
    console.log(item);
    menuItem = [
      {
        key: `SideMenu_${index}`,
        icon: item.icon,
        disabled: item.disabled,
        link: (
          <Link className={styles.sideMenuLink} to={item.href}>
            {item.title}
          </Link>
        ),
      },
    ];
    return menuItem;
  });

      <Menu
        items={menuItem}
        defaultSelectedKeys={[selectedKey]}
        mode="inline"
        inlineIndent={13}
      />
</code>```

The map threw me off a little to implement it with the newer version.
Wondering what's the best approach for this?

Thanks

Title: Convert Antd menu to version >4.20

Body:
I'm trying to convert the old version of menu.Items into the new one with the items array.

This is what I currently have:

      <Menu defaultSelectedKeys={[selectedKey]} mode="inline" inlineIndent={13}>
        {items.map((item, index) => (
          <Menu.Item
            key={`SideMenu_${index}`}
            icon={item.icon}
            disabled={item.disabled}
          >
            <Link className={styles.sideMenuLink} to={item.href}>
              {item.title}
            </Link>
          </Menu.Item>
        ))}
      </Menu>

And this is what I'm trying atm:

  let menuItem;
  items.map((item, index) => {
    console.log(item);
    menuItem = [
      {
        key: `SideMenu_${index}`,
        icon: item.icon,
        disabled: item.disabled,
        link: (
          <Link className={styles.sideMenuLink} to={item.href}>
            {item.title}
          </Link>
        ),
      },
    ];
    return menuItem;
  });

      <Menu
        items={menuItem}
        defaultSelectedKeys={[selectedKey]}
        mode="inline"
        inlineIndent={13}
      />

The map threw me off a little to implement it with the newer version.
Wondering what's the best approach for this?

Thanks


问:
React. How to get actual values from a state inside an asyn function?
I'm beginner and I'm not sure if I solved the problem in a proper way.

I have a form with controlled components and I have to get values from these components in an async function to send them to a rest api backend. But If I'm trying to do it from an async function, I have got just empty values, because I don't have access to actual state of these component in async function (onSubmit).

I have tried to use a hook useEffect to solve this problem, it works, but I'm not sure if it a proper to do it?

```<code>  const [comment1, setComment1] = useState('');
  const [comment2, setComment2] = useState('');
  const [comment3, setComment3] = useState('');
  const [imageS3URL1, setImageS3URL1] = useState('');
  const [imageS3URL2, setImageS3URL2] = useState('');
  const [imageS3URL3, setImageS3URL3] = useState('');

  const [submitData, setSubmitData] = useState(false);

  const dataToSubmit = () => {
    const data = {
      comment1: comment1,
      image1: imageS3URL1,
      comment2: comment2,
      image2: imageS3URL2,
      comment3: comment3,
      image3: imageS3URL3,
    };
    console.log('submitData', data);
  };

  useEffect(() => {
    setSubmitData(false);
    submitData && dataToSubmit();
  }, [submitData]);

  const onSubmit = async (e: any) => {
    e.preventDefault();
    Promise.all([
      //@ts-ignore
      refS3Uploader1.current.uploadFile(),
      //@ts-ignore
      refS3Uploader2.current.uploadFile(),
      //@ts-ignore
      refS3Uploader3.current.uploadFile(),
    ]).then(values => {
      setSubmitData(true);
    });
  };
</code>```

A second approach without useEffect, it works too.

```<code>  ...
  const [submitData, setSubmitData] = useState(false);

  const onSubmit = async (e: any) => {
    e.preventDefault();
    Promise.all([
      //@ts-ignore
      refS3Uploader1.current.uploadFile(),
      //@ts-ignore
      refS3Uploader2.current.uploadFile(),
      //@ts-ignore
      refS3Uploader3.current.uploadFile(),
    ]).then(values => {
      setSubmitData(true);
    });
  };

  const dataToSubmit = () => {
    const data = {
      comment1: comment1,
      image1: imageS3URL1,
      comment2: comment2,
      image2: imageS3URL2,
      comment3: comment3,
      image3: imageS3URL3,
    };
    console.log('submitData', data);
  };

  if (submitData === true) {
    setSubmitData(false);
    dataToSubmit();
  }

</code>```

Maybe I completely wrong and there is another, more proper way to solve it?

================
full code

```<code>    import * as React from 'react';
    import { useState, useRef, useEffect } from 'react';
    import { ImageS3Upload } from '../src';

    const Example4 = () => {
      const URL_GENERATE_S3_URLKEY = 'http://127.0.0.1:8000/api/citytree/s3/generate_signed_url/';
      const SERVER_PHOTO = 'https://urbangis.s3.eu-central-1.amazonaws.com/';

      const resizerOptions = {
        enabled: true,
        autoResize: true, // otherwise resizing will be preform before uploading
        maxWidth: 1280,
        maxHeight: 1280,
        compressFormat: 'JPEG',
        quality: 70,
        rotation: 0, // rotation is limited to multiples of 90 degrees
      };

      const refS3Uploader1 = useRef(); // to be able to call method uploadFile
      const refS3Uploader2 = useRef(); // to be able to call method uploadFile
      const refS3Uploader3 = useRef(); // to be able to call method uploadFile

      const [comment1, setComment1] = useState('');
      const [comment2, setComment2] = useState('');
      const [comment3, setComment3] = useState('');
      const [imageS3URL1, setImageS3URL1] = useState('');
      const [imageS3URL2, setImageS3URL2] = useState('');
      const [imageS3URL3, setImageS3URL3] = useState('');

      const [submitButtonDisabled, setSubmitButtonDisabled] = useState(false);
      const [submitData, setSubmitData] = useState(false);

      useEffect(() => {
         setSubmitData(false);
         submitData && dataToSubmit();
      }, [submitData]);

      const onSubmit = async (e: any) => {
        e.preventDefault();
        setSubmitButtonDisabled(true);
        Promise.all([
          //@ts-ignore
          refS3Uploader1.current.uploadFile(),
          //@ts-ignore
          refS3Uploader2.current.uploadFile(),
          //@ts-ignore
          refS3Uploader3.current.uploadFile(),
        ]).then(values => {
          setSubmitButtonDisabled(false);
          let result = true;
          values.forEach(value => {
            if (!value) result = false;
          });
          result && setSubmitData(true);

          //if I call dataToSubmit from here, I will get empty values
          dataToSubmit();

        });
      };

      const dataToSubmit = () => {
        const data = {
          comment1: comment1,
          image1: imageS3URL1,
          comment2: comment2,
          image2: imageS3URL2,
          comment3: comment3,
          image3: imageS3URL3,
        };
        console.log('submitData', data);
      };

      // if (submitData === true) {
      //   setSubmitData(false);
      //   dataToSubmit();
      // }

      const onResizeStart1 = () => {
        setSubmitButtonDisabled(true);
      };
      const onResizeStart2 = () => {
        setSubmitButtonDisabled(true);
      };
      const onResizeStart3 = () => {
        setSubmitButtonDisabled(true);
      };

      const onResizeFinish1 = () => {
        setSubmitButtonDisabled(false);
      };
      const onResizeFinish2 = () => {
        setSubmitButtonDisabled(false);
      };
      const onResizeFinish3 = () => {
        setSubmitButtonDisabled(false);
      };

      return (
        <>
          <form
            onSubmit={onSubmit}
            style={{ margin: '10px', padding: '10px', border: 'solid 1px black' }}
          >

            <p><b>4. Form, multiple components, autoUpload=False</b></p>

            <div style={{ display: 'flex' }}>
              <div style={{ maxWidth: '200px', margin: '10px' }}>
                <label htmlFor="id_comment1">Comment</label>
                <input
                  type="text"
                  id="id_comment1"
                  value={comment1}
                  onChange={e => setComment1(e.target.value)}
                />
                <br />
                <br />
                <ImageS3Upload
                  signingUrl={URL_GENERATE_S3_URLKEY}
                  autoUpload={false}
                  serverPhoto={SERVER_PHOTO}
                  resizer={resizerOptions}
                  onResizeStart={onResizeStart1}
                  onResizeFinish={onResizeFinish1}
                  ref={refS3Uploader1}
                  value={imageS3URL1}
                  onChange={(e: any) => setImageS3URL1(e.target.value)}
                />
              </div>

              <div style={{ maxWidth: '200px', margin: '10px' }}>
                <label htmlFor="id_comment4">Comment</label>
                <input
                  type="text"
                  id="id_comment4"
                  value={comment2}
                  onChange={e => setComment2(e.target.value)}
                />
                <br />
                <br />
                <ImageS3Upload
                  signingUrl={URL_GENERATE_S3_URLKEY}
                  autoUpload={false}
                  serverPhoto={SERVER_PHOTO}
                  resizer={resizerOptions}
                  onResizeStart={onResizeStart2}
                  onResizeFinish={onResizeFinish2}
                  ref={refS3Uploader2}
                  value={imageS3URL2}
                  onChange={(e: any) => setImageS3URL2(e.target.value)}
                />
              </div>

              <div style={{ maxWidth: '200px', margin: '10px' }}>
                <label htmlFor="id_comment5">Comment</label>
                <input
                  type="text"
                  id="id_comment5"
                  value={comment3}
                  onChange={e => setComment3(e.target.value)}
                />
                <br />
                <br />
                <ImageS3Upload
                  signingUrl={URL_GENERATE_S3_URLKEY}
                  autoUpload={false}
                  serverPhoto={SERVER_PHOTO}
                  resizer={resizerOptions}
                  onResizeStart={onResizeStart3}
                  onResizeFinish={onResizeFinish3}
                  ref={refS3Uploader3}
                  value={imageS3URL3}
                  onChange={(e: any) => setImageS3URL3(e.target.value)}
                />
              </div>
            </div>
            <input
              type="submit"
              value="Submit"
              style={{ width: '100%' }}
              className="button"
              disabled={submitButtonDisabled}
            ></input>
          </form>
        </>
      );
    }

    export default Example4
</code>```

Body:
I'm beginner and I'm not sure if I solved the problem in a proper way.

I have a form with controlled components and I have to get values from these components in an async function to send them to a rest api backend. But If I'm trying to do it from an async function, I have got just empty values, because I don't have access to actual state of these component in async function (onSubmit).

I have tried to use a hook useEffect to solve this problem, it works, but I'm not sure if it a proper to do it?

  const [comment1, setComment1] = useState('');
  const [comment2, setComment2] = useState('');
  const [comment3, setComment3] = useState('');
  const [imageS3URL1, setImageS3URL1] = useState('');
  const [imageS3URL2, setImageS3URL2] = useState('');
  const [imageS3URL3, setImageS3URL3] = useState('');

  const [submitData, setSubmitData] = useState(false);

  const dataToSubmit = () => {
    const data = {
      comment1: comment1,
      image1: imageS3URL1,
      comment2: comment2,
      image2: imageS3URL2,
      comment3: comment3,
      image3: imageS3URL3,
    };
    console.log('submitData', data);
  };

  useEffect(() => {
    setSubmitData(false);
    submitData && dataToSubmit();
  }, [submitData]);

  const onSubmit = async (e: any) => {
    e.preventDefault();
    Promise.all([
      //@ts-ignore
      refS3Uploader1.current.uploadFile(),
      //@ts-ignore
      refS3Uploader2.current.uploadFile(),
      //@ts-ignore
      refS3Uploader3.current.uploadFile(),
    ]).then(values => {
      setSubmitData(true);
    });
  };

A second approach without useEffect, it works too.

  ...
  const [submitData, setSubmitData] = useState(false);

  const onSubmit = async (e: any) => {
    e.preventDefault();
    Promise.all([
      //@ts-ignore
      refS3Uploader1.current.uploadFile(),
      //@ts-ignore
      refS3Uploader2.current.uploadFile(),
      //@ts-ignore
      refS3Uploader3.current.uploadFile(),
    ]).then(values => {
      setSubmitData(true);
    });
  };

  const dataToSubmit = () => {
    const data = {
      comment1: comment1,
      image1: imageS3URL1,
      comment2: comment2,
      image2: imageS3URL2,
      comment3: comment3,
      image3: imageS3URL3,
    };
    console.log('submitData', data);
  };

  if (submitData === true) {
    setSubmitData(false);
    dataToSubmit();
  }

Maybe I completely wrong and there is another, more proper way to solve it?

================
full code

    import * as React from 'react';
    import { useState, useRef, useEffect } from 'react';
    import { ImageS3Upload } from '../src';

    const Example4 = () => {
      const URL_GENERATE_S3_URLKEY = 'http://127.0.0.1:8000/api/citytree/s3/generate_signed_url/';
      const SERVER_PHOTO = 'https://urbangis.s3.eu-central-1.amazonaws.com/';

      const resizerOptions = {
        enabled: true,
        autoResize: true, // otherwise resizing will be preform before uploading
        maxWidth: 1280,
        maxHeight: 1280,
        compressFormat: 'JPEG',
        quality: 70,
        rotation: 0, // rotation is limited to multiples of 90 degrees
      };

      const refS3Uploader1 = useRef(); // to be able to call method uploadFile
      const refS3Uploader2 = useRef(); // to be able to call method uploadFile
      const refS3Uploader3 = useRef(); // to be able to call method uploadFile

      const [comment1, setComment1] = useState('');
      const [comment2, setComment2] = useState('');
      const [comment3, setComment3] = useState('');
      const [imageS3URL1, setImageS3URL1] = useState('');
      const [imageS3URL2, setImageS3URL2] = useState('');
      const [imageS3URL3, setImageS3URL3] = useState('');

      const [submitButtonDisabled, setSubmitButtonDisabled] = useState(false);
      const [submitData, setSubmitData] = useState(false);

      useEffect(() => {
         setSubmitData(false);
         submitData && dataToSubmit();
      }, [submitData]);

      const onSubmit = async (e: any) => {
        e.preventDefault();
        setSubmitButtonDisabled(true);
        Promise.all([
          //@ts-ignore
          refS3Uploader1.current.uploadFile(),
          //@ts-ignore
          refS3Uploader2.current.uploadFile(),
          //@ts-ignore
          refS3Uploader3.current.uploadFile(),
        ]).then(values => {
          setSubmitButtonDisabled(false);
          let result = true;
          values.forEach(value => {
            if (!value) result = false;
          });
          result && setSubmitData(true);

          //if I call dataToSubmit from here, I will get empty values
          dataToSubmit();

        });
      };

      const dataToSubmit = () => {
        const data = {
          comment1: comment1,
          image1: imageS3URL1,
          comment2: comment2,
          image2: imageS3URL2,
          comment3: comment3,
          image3: imageS3URL3,
        };
        console.log('submitData', data);
      };

      // if (submitData === true) {
      //   setSubmitData(false);
      //   dataToSubmit();
      // }

      const onResizeStart1 = () => {
        setSubmitButtonDisabled(true);
      };
      const onResizeStart2 = () => {
        setSubmitButtonDisabled(true);
      };
      const onResizeStart3 = () => {
        setSubmitButtonDisabled(true);
      };

      const onResizeFinish1 = () => {
        setSubmitButtonDisabled(false);
      };
      const onResizeFinish2 = () => {
        setSubmitButtonDisabled(false);
      };
      const onResizeFinish3 = () => {
        setSubmitButtonDisabled(false);
      };

      return (
        <>
          <form
            onSubmit={onSubmit}
            style={{ margin: '10px', padding: '10px', border: 'solid 1px black' }}
          >

4. Form, multiple components, autoUpload=False

                Comment
                <input
                  type="text"
                  id="id_comment1"
                  value={comment1}
                  onChange={e => setComment1(e.target.value)}
                />

                <ImageS3Upload
                  signingUrl={URL_GENERATE_S3_URLKEY}
                  autoUpload={false}
                  serverPhoto={SERVER_PHOTO}
                  resizer={resizerOptions}
                  onResizeStart={onResizeStart1}
                  onResizeFinish={onResizeFinish1}
                  ref={refS3Uploader1}
                  value={imageS3URL1}
                  onChange={(e: any) => setImageS3URL1(e.target.value)}
                />

                Comment
                <input
                  type="text"
                  id="id_comment4"
                  value={comment2}
                  onChange={e => setComment2(e.target.value)}
                />

                <ImageS3Upload
                  signingUrl={URL_GENERATE_S3_URLKEY}
                  autoUpload={false}
                  serverPhoto={SERVER_PHOTO}
                  resizer={resizerOptions}
                  onResizeStart={onResizeStart2}
                  onResizeFinish={onResizeFinish2}
                  ref={refS3Uploader2}
                  value={imageS3URL2}
                  onChange={(e: any) => setImageS3URL2(e.target.value)}
                />

                Comment
                <input
                  type="text"
                  id="id_comment5"
                  value={comment3}
                  onChange={e => setComment3(e.target.value)}
                />

                <ImageS3Upload
                  signingUrl={URL_GENERATE_S3_URLKEY}
                  autoUpload={false}
                  serverPhoto={SERVER_PHOTO}
                  resizer={resizerOptions}
                  onResizeStart={onResizeStart3}
                  onResizeFinish={onResizeFinish3}
                  ref={refS3Uploader3}
                  value={imageS3URL3}
                  onChange={(e: any) => setImageS3URL3(e.target.value)}
                />

            <input
              type="submit"
              value="Submit"
              style={{ width: '100%' }}
              className="button"
              disabled={submitButtonDisabled}
            ></input>
          </form>
        </>
      );
    }

    export default Example4


问:
I have Xampp installed. In a php file, if I run "error_log("aãa");" it outputs "a\xc3\xa3a". Please help me fix it
The error_log problem isn't my actual problem, though. I'm trying to figure out the following problem:

I have quilljs running on a page.

I type accents, like "aãa" above.

I grab it with getText, send it to php with $.post (ajax, I believe)

Whatever I try to do with it, it comes out garbled like that.

Specifically what I'm trying to do is this: array_count_values(str_word_count($text, 1));

To find repeated words and later highlight them in the text, basic stuff, only the character encoding problem is making it harder than it should be.

I've made sure php.ini, my.ini and the html file all have utf-8 encoding.

Encoding in base64 with jQuery and then decoding it back to a normal string with php also didn't solve it (after all, even a direct error_log of a text with accents is enough to garble it).


问:
How to embed external programs in tkinter?
When working, some employees need to use 4 different external programs
Sometimes it's messy to have four different programs
I need to develop a software to control the 4 different softwares in a single window

1 software is only Internet Explorer to control an IP camera

Another program is to control an ROV

The third connects to a sensor on the ROV and displays it

The latest software is a script that collects certain information

What I want to know is if there is a way to embed third party software in my python code.
It is not enough for me to only execute the programs with a sub process.
My idea is that by means of shortcuts you can comfortably navigate between the four programs

I've tried embedding threads in tkinter, but haven't managed to find anything about it.
I also used tkinterweb to open an embedded browser, however this doesn't work for me as the IP camera works exclusively with Internet Explore.


问:
How to get accurate <1seconds measurements utilizing std::chrono
I'm trying to compute the amount of time an algorithm runs in my program, and display that amount in differents meausures such as seconds, miliseconds, microseconds...

This is how I've been approaching it:

```<code>auto start = high_resolution_clock::now();
myFunction();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<seconds>(stop - start);

const auto hrs = duration_cast<hours>(duration);
const auto mins = duration_cast<minutes>(duration - hrs);
const auto secs = duration_cast<seconds>(duration - hrs - mins);
const auto ms = duration_cast<milliseconds>(duration - hrs - mins - secs);
std::cout << "Time needed: "<<hrs.count()<<" hours "<<mins.count()<<" mins "<<secs.count()<<" secs " <<ms.count()<<" milisecs "
</code>```

What I intend it to do (invented example):

```<code>Time needed: 0 hours 1 mins 30 seconds 2400miliseconds
</code>```

BUt for some reasons it prints all 0s (even miliseconds) when times are <1secs, and when times are 1secs or more, it does not prints the exact time either, it does something like

```<code>    Time needed: 0 hours 0 mins 1 seconds 1000miliseconds
</code>```

it just print a whole seconds and then it converts it to the others meausures, but the actual time that I took the function to works is not exactly 1 second, how can I get that? (if theres better ways to do that other than std::chrono I'll be interested too)

Body:
I'm trying to compute the amount of time an algorithm runs in my program, and display that amount in differents meausures such as seconds, miliseconds, microseconds...

This is how I've been approaching it:

auto start = high_resolution_clock::now();
myFunction();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<seconds>(stop - start);

const auto hrs = duration_cast<hours>(duration);
const auto mins = duration_cast<minutes>(duration - hrs);
const auto secs = duration_cast<seconds>(duration - hrs - mins);
const auto ms = duration_cast<milliseconds>(duration - hrs - mins - secs);
std::cout << "Time needed: "<<hrs.count()<<" hours "<<mins.count()<<" mins "<<secs.count()<<" secs " <<ms.count()<<" milisecs "

What I intend it to do (invented example):

Time needed: 0 hours 1 mins 30 seconds 2400miliseconds

BUt for some reasons it prints all 0s (even miliseconds) when times are <1secs, and when times are 1secs or more, it does not prints the exact time either, it does something like

    Time needed: 0 hours 0 mins 1 seconds 1000miliseconds

it just print a whole seconds and then it converts it to the others meausures, but the actual time that I took the function to works is not exactly 1 second, how can I get that? (if theres better ways to do that other than std::chrono I'll be interested too)


问:
sharedpreference value lost of App restart
Shared prefernces value being cleared after app restart...</p>
```<code>SharedPreferences prefs = await SharedPreferences.getInstance();
SharedPreferences.setMockInitialValues({});
prefs.setString("mobileNumber", mobileController.text);
prefs.setString('isAuthenticated', 'true');
var login = prefs.getString("isAuthenticated");
</code>```

Body:
Shared prefernces value being cleared after app restart...

SharedPreferences prefs = await SharedPreferences.getInstance();
SharedPreferences.setMockInitialValues({});
prefs.setString("mobileNumber", mobileController.text);
prefs.setString('isAuthenticated', 'true');
var login = prefs.getString("isAuthenticated");


问:
Kettle environment variable identifier '$' conflict with MySQL JSON Path '$'
Kettle execute MySQL Scripts：

```<code>update qt_check_plan_group_item
set linked_defective_item = JSON_SET(linked_defective_item,'$[0]',@var_defective_item_id)
where @var_defective_item_id is not null and  id = @var_group_item_id;
</code>```

Kettle environment variable identifier '$' conflict with MySQL JSON Path '$'

How to solve？

Kettle replace '$[0]' to Kettle env varialbe, not MySQL json path

Body:
Kettle execute MySQL Scripts：

update qt_check_plan_group_item
set linked_defective_item = JSON_SET(linked_defective_item,'$[0]',@var_defective_item_id)
where @var_defective_item_id is not null and  id = @var_group_item_id;

Kettle environment variable identifier '$' conflict with MySQL JSON Path '$'

How to solve？

Kettle replace '$[0]' to Kettle env varialbe, not MySQL json path


问:
Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package name 'com.artemtchernomorsky.raddiokansk'
I needed apps for my radio. I took the left template and started doing everything on it. As a result, I did not succeed and gives such an error.

Before when I changed the name everything is fine and everything works

enter image description here

After I changed it to my own, here's the problem

enter image description here

(also if it helps)
enter image description here

I've been roaming all over the great internet if you find or come up with a solution, thank you anyway


问:
Typo3 v10 image metadata translation issue
I'm developing a multi language website with Typo3 v10.4.32.
Everything works fine. Except image metadata translation feature.

I uploaded an image, and I added translation for metadata (German is default)

After then I added page translation. In backend I see that images have default language metadata in both languages

If I click the image element to edit I see the correct behaviour: Typo3 is aware that the image has translation of metadata

In frontend unfortunately I see the problem: the default language metadata is shown

Typoscript template is simple:

```<code>config {
    linkVars = L
    sys_language_mode = content_fallback
    sys_language_overlay = 1
    sys_language_softExclude = tt_content:image
    sys_language_softMergeIfNotBlank = tt_content:image
    sys_language_uid = 0
}

# Default PAGE object:
page = PAGE
page.10 = TEXT
page.10.value = HELLO WORLD!

page.20 = CONTENT
page.20.table = tt_content
page.20.select {
    orderBy = sorting
    where = {#colPos} = 0
}
[siteLanguage("languageId") == 1]
    config.sys_language_uid = 1
    config.htmlTag_langKey = en
    config.language = en
    config.locale_all = en_US
[end]
</code>```

Is the code below necessary ? since it is configured in yaml file

```<code>config.sys_language_uid = 1
config.htmlTag_langKey = en
config.language = en
config.locale_all = en_US
</code>```

I could add translation in content elements, but images are supposed to be used in many places, so it becomes annoying to add the same text

I tried to search a solution, but I found very old similar issue with Typo3 v7 and the issue was supposed to be fixed in the next version Typo3 v8.

I suppose that the problem does not connect to NGINX ?

Maybe I need to add some code in LocalConfiguration ?

Body:
I'm developing a multi language website with Typo3 v10.4.32.
Everything works fine. Except image metadata translation feature.

I uploaded an image, and I added translation for metadata (German is default)

After then I added page translation. In backend I see that images have default language metadata in both languages

If I click the image element to edit I see the correct behaviour: Typo3 is aware that the image has translation of metadata

In frontend unfortunately I see the problem: the default language metadata is shown

Typoscript template is simple:

config {
    linkVars = L
    sys_language_mode = content_fallback
    sys_language_overlay = 1
    sys_language_softExclude = tt_content:image
    sys_language_softMergeIfNotBlank = tt_content:image
    sys_language_uid = 0
}

# Default PAGE object:
page = PAGE
page.10 = TEXT
page.10.value = HELLO WORLD!

page.20 = CONTENT
page.20.table = tt_content
page.20.select {
    orderBy = sorting
    where = {#colPos} = 0
}
[siteLanguage("languageId") == 1]
    config.sys_language_uid = 1
    config.htmlTag_langKey = en
    config.language = en
    config.locale_all = en_US
[end]

Is the code below necessary ? since it is configured in yaml file

config.sys_language_uid = 1
config.htmlTag_langKey = en
config.language = en
config.locale_all = en_US

I could add translation in content elements, but images are supposed to be used in many places, so it becomes annoying to add the same text

I tried to search a solution, but I found very old similar issue with Typo3 v7 and the issue was supposed to be fixed in the next version Typo3 v8.

I suppose that the problem does not connect to NGINX ?

Maybe I need to add some code in LocalConfiguration ?


问:
React Native crashing on launch after targeting Android API 33 (android 13)
Thanks in advance!

My React Native app seems to be crashing on launch only for Android 13.

I've attached the stacktrace from the Play Store below.

```<code>Exception com.facebook.react.common.JavascriptException:
  at com.facebook.react.modules.core.ExceptionsManagerModule.reportException (ExceptionsManagerModule.java:83)
  at java.lang.reflect.Method.invoke
  at com.facebook.react.bridge.JavaMethodWrapper.invoke (JavaMethodWrapper.java:372)
  at com.facebook.react.bridge.JavaModuleWrapper.invoke (JavaModuleWrapper.java:151)
  at com.facebook.react.bridge.queue.NativeRunnable.run
  at android.os.Handler.handleCallback (Handler.java:942)
  at android.os.Handler.dispatchMessage (Handler.java:99)
  at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage (MessageQueueThreadHandler.java:27)
  at android.os.Looper.loopOnce (Looper.java:226)
  at android.os.Looper.loop (Looper.java:313)
  at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run (MessageQueueThreadImpl.java:226)
  at java.lang.Thread.run (Thread.java:1012)
</code>```

Our build.gradle:

```<code>buildscript {
    ext.kotlin_version = '1.4.10'
    ext {
        buildToolsVersion = "29.0.3"
        minSdkVersion = 21
        compileSdkVersion = 33
        targetSdkVersion = 33
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.google.gms:google-services:4.3.3'
        classpath("com.android.tools.build:gradle:4.1.0")
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
</code>```

We've tried googling for this stacktrace but cannot seem to find anything that corresponds to our problem.

Body:
Thanks in advance!

My React Native app seems to be crashing on launch only for Android 13.

I've attached the stacktrace from the Play Store below.

Exception com.facebook.react.common.JavascriptException:
  at com.facebook.react.modules.core.ExceptionsManagerModule.reportException (ExceptionsManagerModule.java:83)
  at java.lang.reflect.Method.invoke
  at com.facebook.react.bridge.JavaMethodWrapper.invoke (JavaMethodWrapper.java:372)
  at com.facebook.react.bridge.JavaModuleWrapper.invoke (JavaModuleWrapper.java:151)
  at com.facebook.react.bridge.queue.NativeRunnable.run
  at android.os.Handler.handleCallback (Handler.java:942)
  at android.os.Handler.dispatchMessage (Handler.java:99)
  at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage (MessageQueueThreadHandler.java:27)
  at android.os.Looper.loopOnce (Looper.java:226)
  at android.os.Looper.loop (Looper.java:313)
  at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run (MessageQueueThreadImpl.java:226)
  at java.lang.Thread.run (Thread.java:1012)

Our build.gradle:

buildscript {
    ext.kotlin_version = '1.4.10'
    ext {
        buildToolsVersion = "29.0.3"
        minSdkVersion = 21
        compileSdkVersion = 33
        targetSdkVersion = 33
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.google.gms:google-services:4.3.3'
        classpath("com.android.tools.build:gradle:4.1.0")
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

We've tried googling for this stacktrace but cannot seem to find anything that corresponds to our problem.


问:
firebase-integration with react admin
I am making an admin panel in order to manage data that is present in firebase. The admin panel is made with the help of the react-admin framework. I go through the documentation of connecting react admin framework with the real-time firebase database but got stuck in the line I pointed out below. Please explain me the significance of line.

```<code>import { Admin, Resource } from 'react-admin'
import firebaseDataProvider from 'ra-data-firebase-client'
import firebase from 'firebase/app'
import "firebase/database";

firebase.initializeApp({
  apiKey: '**************',
  authDomain: '**************',
  databaseURL: 'https://myrealtimedatabase.firebaseio.com',
  projectId: 'myrealtimedatabase',
  storageBucket: 'myrealtimedatabase.appspot.com',
  messagingSenderId: '**************',
  appId: '**************',,
  measurementId: '**************'
})

const settings = {context: 'dev', imagekey: "images", filekey: "files"} //

export default () =>
        <Admin dataProvider={firebaseDataProvider(firebase, settings)}>
          <Resource
            name='posts'
            list={PostList}
            edit={PostEdit}
            create={PostCreate} />
        </Admin>
</code>```

I want to display the result/data retrieved from firebase in tabular form.

Title: firebase-integration with react admin

Body:
I am making an admin panel in order to manage data that is present in firebase. The admin panel is made with the help of the react-admin framework. I go through the documentation of connecting react admin framework with the real-time firebase database but got stuck in the line I pointed out below. Please explain me the significance of line.

import { Admin, Resource } from 'react-admin'
import firebaseDataProvider from 'ra-data-firebase-client'
import firebase from 'firebase/app'
import "firebase/database";

firebase.initializeApp({
  apiKey: '**************',
  authDomain: '**************',
  databaseURL: 'https://myrealtimedatabase.firebaseio.com',
  projectId: 'myrealtimedatabase',
  storageBucket: 'myrealtimedatabase.appspot.com',
  messagingSenderId: '**************',
  appId: '**************',,
  measurementId: '**************'
})

const settings = {context: 'dev', imagekey: "images", filekey: "files"} //

export default () =>
        <Admin dataProvider={firebaseDataProvider(firebase, settings)}>
          <Resource
            name='posts'
            list={PostList}
            edit={PostEdit}
            create={PostCreate} />
        </Admin>

I want to display the result/data retrieved from firebase in tabular form.


问:
Javascript code to print queued jobs respecting the job's timestamp
Our printer releases all the jobs when putting the badge BUT - does not respect the printing order (chronologic order - oldest print should sort first etc)

I checked the driver and printer is set to "print after last page is spooled" so no "immediate print" setup, alltough it prints in a sequence that looks like "print the smallest file first".

What I look for - if anyone of you ever had to do with this kind of thing - is a javascript snippet telling the machine "on release" what the timestamp of the job is considered for the printing sequence and not the file size or any other priority.

The web interface the printer uses is "papercut" - maybe this helps.

I'm thankful for any suggestion.

Many thanks in advance & kind regards

Tom

```<code>
I found a command called
// printPQ()  and added this to the jacascript command shell and we're doing some tryouts right now. But as I have absolutely NO idea if this command needs more parameters to function - I'm open for any suggestion. I'll update this post If ever the results would return the requested result.

Tom
</code>```

Body:
Our printer releases all the jobs when putting the badge BUT - does not respect the printing order (chronologic order - oldest print should sort first etc)

I checked the driver and printer is set to "print after last page is spooled" so no "immediate print" setup, alltough it prints in a sequence that looks like "print the smallest file first".

What I look for - if anyone of you ever had to do with this kind of thing - is a javascript snippet telling the machine "on release" what the timestamp of the job is considered for the printing sequence and not the file size or any other priority.

The web interface the printer uses is "papercut" - maybe this helps.

I'm thankful for any suggestion.

Many thanks in advance & kind regards

Tom

I found a command called
// printPQ()  and added this to the jacascript command shell and we're doing some tryouts right now. But as I have absolutely NO idea if this command needs more parameters to function - I'm open for any suggestion. I'll update this post If ever the results would return the requested result.

Tom


问:
What does TypeError: stream.listeeners is not a function mean?
I am unit testing firebase onRequest cloud function with jest

This is the test code:

```<code>const index = require ('./index')

describe ('test function', () => {
  it('positive case', async () => {
    let req = { "usn": "cmu2010"}
    let res = { "response": "hi cmu"}
    index.myCloudFunction(req, res)
  });
});
</code>```

This is my index.js file:

```<code>const admin = require('firebase-admin')
admin.initializeApp();
const importFile = require('./myCloudFunction')
exports.myCloudFunction = importFile.myCloudFunction
</code>```

Inside myCloudFunction.js, I have my cloud function written in express

```<code>const functions = require ("firebase-functions")
myCloudFunction.post("/", async(request, response) => {
  //
})
exports.myCloudFunction = functions.https.onRequest(myCloudFunction)
</code>```

I am getting TypeError: stream.listeners is not a function
What does it mean and where am I going wrong? I have searched for this error but there aren't any good explanation available.

Body:
I am unit testing firebase onRequest cloud function with jest

This is the test code:

const index = require ('./index')

describe ('test function', () => {
  it('positive case', async () => {
    let req = { "usn": "cmu2010"}
    let res = { "response": "hi cmu"}
    index.myCloudFunction(req, res)
  });
});

This is my index.js file:

const admin = require('firebase-admin')
admin.initializeApp();
const importFile = require('./myCloudFunction')
exports.myCloudFunction = importFile.myCloudFunction

Inside myCloudFunction.js, I have my cloud function written in express

const functions = require ("firebase-functions")
myCloudFunction.post("/", async(request, response) => {
  //
})
exports.myCloudFunction = functions.https.onRequest(myCloudFunction)

I am getting TypeError: stream.listeners is not a function
What does it mean and where am I going wrong? I have searched for this error but there aren't any good explanation available.


问:
Reboot host while inside one of the containers
I am trying to reboot the host while I am inside one of the docker containers

a simple

```<code>systemctl reboot or sudo reboot
</code>```

gives "System has not been booted with systemd as init system (PID 1). Can't operate.
"

I tried adding

```<code>/var/run/systemd: docker run  --name nw -it --rm  -v /var/run/systemd:/var/run/systemd debian:18.04
</code>```

to my docker run in the specific container I trying to reboot the host from but still no luck

Body:
I am trying to reboot the host while I am inside one of the docker containers

a simple

systemctl reboot or sudo reboot

gives "System has not been booted with systemd as init system (PID 1). Can't operate.
"

I tried adding

/var/run/systemd: docker run  --name nw -it --rm  -v /var/run/systemd:/var/run/systemd debian:18.04

to my docker run in the specific container I trying to reboot the host from but still no luck


问:
Pandas is creating an additional unwanted column
Any ideas why this pandas dataframe is getting a two latitude columns? Looking at the dataframe before running this line everything appears fine so not sure why this is happening. Any thoughts?

Thanks

```<code>    def set_geolocation(self,key,col):
        unique_locations = list(set(self.raw_data_frames[key][col].unique()))
        #generate empty columns in dataframe
        self.raw_data_frames[key]["Longitude"] = np.nan
        self.raw_data_frames[key]["latitude"] = np.nan
        location_dict = {}
        unfound_locations = []

        for unique_location in unique_locations:
            #to minimise time get location for each unique location then apply individually after
            try:
                location = self.geolocator.geocode(unique_location, timeout=20)
                #poulate dictionary with dictionaries
                location_dict[unique_location] = {'Longitude': location.longitude, 'Latitude': location.latitude}
                print(f'found {unique_location} at long:{location.longitude} lat:{location.latitude} as type: {type(location.latitude)}')
            except:
                unfound_locations.append(unique_location)
                print(f'{len(unfound_locations): could not find {unique_location}}')

        #map longitude and latitude to new columns with respect to the string location
        for ukey in list(location_dict.keys()):
            print(ukey)
            self.raw_data_frames[key].loc[self.raw_data_frames[key][col] == ukey, ["Longitude"]] = location_dict[ukey]["Longitude"]
            self.raw_data_frames[key].loc[self.raw_data_frames[key][col] == ukey, ["Latitude"]] = location_dict[ukey]["Latitude"]
        unfound_locations = list(set(unfound_locations))
        return unfound_locations
</code>```

Body:
Any ideas why this pandas dataframe is getting a two latitude columns? Looking at the dataframe before running this line everything appears fine so not sure why this is happening. Any thoughts?

Thanks

    def set_geolocation(self,key,col):
        unique_locations = list(set(self.raw_data_frames[key][col].unique()))
        #generate empty columns in dataframe
        self.raw_data_frames[key]["Longitude"] = np.nan
        self.raw_data_frames[key]["latitude"] = np.nan
        location_dict = {}
        unfound_locations = []

        for unique_location in unique_locations:
            #to minimise time get location for each unique location then apply individually after
            try:
                location = self.geolocator.geocode(unique_location, timeout=20)
                #poulate dictionary with dictionaries
                location_dict[unique_location] = {'Longitude': location.longitude, 'Latitude': location.latitude}
                print(f'found {unique_location} at long:{location.longitude} lat:{location.latitude} as type: {type(location.latitude)}')
            except:
                unfound_locations.append(unique_location)
                print(f'{len(unfound_locations): could not find {unique_location}}')

        #map longitude and latitude to new columns with respect to the string location
        for ukey in list(location_dict.keys()):
            print(ukey)
            self.raw_data_frames[key].loc[self.raw_data_frames[key][col] == ukey, ["Longitude"]] = location_dict[ukey]["Longitude"]
            self.raw_data_frames[key].loc[self.raw_data_frames[key][col] == ukey, ["Latitude"]] = location_dict[ukey]["Latitude"]
        unfound_locations = list(set(unfound_locations))
        return unfound_locations


问:
Wordpress Migration
I hope you're doing well. I am currently working on a wordpress site and I have a problem. I want to migrate a Drupal site to Wordpress. I managed to migrate to wordpress using the FG Drupal to WordPress plugin.
Everything went well during the migration, only that the articles are not categorized. So I will have to manually categorize all 12000 articles. So I wanted to ask you if it was possible to do the migration and the categorization at the same time

I have already tried the migration and all went well, but the articles are not categorized. which means that the articles are not displayed on the site. so I'm looking for a way to categorize articles manually

enter image description here

Title: Wordpress Migration


问:
Can I use MARS with EF Core to retrieve details on in a foreach
I'm not sure that the current implementation of our DAL is correct and I think that the number of connections to the DB is low with respect to what it should be.

I've noticed that there's no MARS inside the connection string

and when I try to perform multple calls on the same repository I got

System.InvalidOperationException:A second operation was started on
this context instance before a previous operation completed. This is
usually caused by different threads concurrently using the same
instance of DbContext. For more information on how to avoid threading
issues with DbContext, see
https://go.microsoft.com/fwlink/?linkid=2097913.

This means that I cannot open use the same repository for example executing an operation in parallel (for example getting some details?)

for example

```<code>foreach(var i in mainProducts) // retrieved from EF with a .ToListAsync
{
    i.Details = await repo.GetDetailsFromIdAsync(i.Id);
}
</code>```

I know that sometime i can just return a single object from the query, but there're some cases where I can't

Thanks

Body:
I'm not sure that the current implementation of our DAL is correct and I think that the number of connections to the DB is low with respect to what it should be.

I've noticed that there's no MARS inside the connection string

and when I try to perform multple calls on the same repository I got

System.InvalidOperationException:A second operation was started on
this context instance before a previous operation completed. This is
usually caused by different threads concurrently using the same
instance of DbContext. For more information on how to avoid threading
issues with DbContext, see
https://go.microsoft.com/fwlink/?linkid=2097913.

This means that I cannot open use the same repository for example executing an operation in parallel (for example getting some details?)

for example

foreach(var i in mainProducts) // retrieved from EF with a .ToListAsync
{
    i.Details = await repo.GetDetailsFromIdAsync(i.Id);
}

I know that sometime i can just return a single object from the query, but there're some cases where I can't

Thanks