问:
How to wait for animation to finish if it's more than 50% done?
I have a state machine to control my character's state. The walking state look like this (Some code omitted)

```<code>// This gets called every frame to check if the state should change
public override void ChangeState()
{
    if (_groundCheck.Check())
    {
        if (_jump) controller.SetState(typeof(JumpState));
        else if (_rb.velocity.x == 0 && _xDirection == 0) controller.SetState(typeof(IdleState));
    }
}

public override void Update()
{
    _animator.MovingAnimation(_groundCheck.Check());
    _animator.CorrectRotation(_xDirection);
}

// This gets called from "controller.SetState()" before changing to the new state
public override void Exit()
{
    controller.Animator.MovingAnimation(false);
}

</code>```

This works just fine. However, when the character stops moving the animation gets interrupted and transitions directly to the idle state. I want this to happen only if the animation is less than halfway done. If it's more than 50% done I want it to finish playing before changing the state.

I know I can check for the current loop progress like this _animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1 > 0.5f but I don't know how to suspend the transition until the animation actually finishes. Any ideas?

Body:
I have a state machine to control my character's state. The walking state look like this (Some code omitted)

// This gets called every frame to check if the state should change
public override void ChangeState()
{
    if (_groundCheck.Check())
    {
        if (_jump) controller.SetState(typeof(JumpState));
        else if (_rb.velocity.x == 0 && _xDirection == 0) controller.SetState(typeof(IdleState));
    }
}

public override void Update()
{
    _animator.MovingAnimation(_groundCheck.Check());
    _animator.CorrectRotation(_xDirection);
}

// This gets called from "controller.SetState()" before changing to the new state
public override void Exit()
{
    controller.Animator.MovingAnimation(false);
}

This works just fine. However, when the character stops moving the animation gets interrupted and transitions directly to the idle state. I want this to happen only if the animation is less than halfway done. If it's more than 50% done I want it to finish playing before changing the state.

I know I can check for the current loop progress like this _animator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1 > 0.5f but I don't know how to suspend the transition until the animation actually finishes. Any ideas?


来源: stackexchange

问:
asciidoctor-maven-plugin - add generated resources to classpath?
I have the 'asciidoctor-maven-plugin' conifugured in a standard fashion to process an adoc file and include a puml diagram. My 'index.adoc' file contains

```<code>== PlantUML Diagram
[plantuml,Text,png]
----
include::./generated/structurizr-Containers.puml[]
</code>```

I am then using another plugin to generate the content of the './generated/structurizr-Containers.puml' file as part of the maven 'generate-sources' phase.

The structure of project and the generated folder is like this

```<code>src/main/resources/asciidoc/index.adoc
target/generated/structurizr-Containers.puml
</code>```

I'm wondering how i can inform the 'asciidoctor-maven-plugin' to include the content of the 'generated' folder when its generating the html5/pdf report.
Thanks

ContentLicense: CC BY-SA 4.0

Body:
I have the 'asciidoctor-maven-plugin' conifugured in a standard fashion to process an adoc file and include a puml diagram. My 'index.adoc' file contains

== PlantUML Diagram
[plantuml,Text,png]
----
include::./generated/structurizr-Containers.puml[]

I am then using another plugin to generate the content of the './generated/structurizr-Containers.puml' file as part of the maven 'generate-sources' phase.

The structure of project and the generated folder is like this

src/main/resources/asciidoc/index.adoc
target/generated/structurizr-Containers.puml

I'm wondering how i can inform the 'asciidoctor-maven-plugin' to include the content of the 'generated' folder when its generating the html5/pdf report.
Thanks


问:
SQL parent child list all fullNames slower than list all FullIDS
Can someone explain this behavior?

I have a temp table variable with 15000 rows:

```<code>declare @sampleitems table
                     (
                         id nvarchar(255),
                         parentid nvarchar(255),
                         Name nvarchar(255)
                     )

insert into @sampleitems
values ('F76265C3-AAE1-4472-8F15-C866B33A6CCC', NULL, 'MASTER')

declare @count int = 15000

while @count <> 0
begin
    insert into @sampleitems
    values (NEWID(), 'F76265C3-AAE1-4472-8F15-C866B33A6CCC', 'sample name ' + cast(@count as nvarchar(255)))

    set @count = @count -1
end
</code>```

When I write a CTE query to list all fullids from above table the query takes approximately 1 second.

When I try to list fullnames query takes almost 30 seconds and maybe more.

All columns are equal data type of nvarchar(255) but I cannot understand why listing FullNames takes so much longer than FullIDs.

Executing this query will finish in less than 2 seconds:

```<code>with CTE (ID, FullID) as
(
    select
        id, cast(id as nvarchar(max))
    from
        @sampleitems
    where
        parentid is null

    union all

    select
        t.id, FullID + ' : ' + t.id
    from
        @sampleitems as T
    inner join
        CTE as c on c.ID = t.parentid
)
select *
from CTE
</code>```

but listing fullnames will take almost 30 seconds or more

```<code>with CTE1 (ID, FullName) as
(
    select
        id, cast(Name as nvarchar(max))
    from
        @sampleitems
    where
        parentid is null

    union all

    select
        t.id, c.FullName  + ' : ' + cast(t.Name as nvarchar(max))
    from
        @sampleitems as T
    inner join
        CTE1 as c on c.ID = t.parentid
)
select *
from CTE1
</code>```

Body:
Can someone explain this behavior?

I have a temp table variable with 15000 rows:

declare @sampleitems table
                     (
                         id nvarchar(255),
                         parentid nvarchar(255),
                         Name nvarchar(255)
                     )

insert into @sampleitems
values ('F76265C3-AAE1-4472-8F15-C866B33A6CCC', NULL, 'MASTER')

declare @count int = 15000

while @count <> 0
begin
    insert into @sampleitems
    values (NEWID(), 'F76265C3-AAE1-4472-8F15-C866B33A6CCC', 'sample name ' + cast(@count as nvarchar(255)))

    set @count = @count -1
end

When I write a CTE query to list all fullids from above table the query takes approximately 1 second.

When I try to list fullnames query takes almost 30 seconds and maybe more.

All columns are equal data type of nvarchar(255) but I cannot understand why listing FullNames takes so much longer than FullIDs.

Executing this query will finish in less than 2 seconds:

with CTE (ID, FullID) as
(
    select
        id, cast(id as nvarchar(max))
    from
        @sampleitems
    where
        parentid is null

    union all

    select
        t.id, FullID + ' : ' + t.id
    from
        @sampleitems as T
    inner join
        CTE as c on c.ID = t.parentid
)
select *
from CTE

but listing fullnames will take almost 30 seconds or more

with CTE1 (ID, FullName) as
(
    select
        id, cast(Name as nvarchar(max))
    from
        @sampleitems
    where
        parentid is null

    union all

    select
        t.id, c.FullName  + ' : ' + cast(t.Name as nvarchar(max))
    from
        @sampleitems as T
    inner join
        CTE1 as c on c.ID = t.parentid
)
select *
from CTE1


问:
Trying to filter twitter accounts that are less than 30 days old
I've been trying to find a way to also filter my search results to only print twitter accounts less than 30 days old but i'm having a hard time with it. Can someone give me a hand adding this to my query? I'm not sure if I can do created_at or since_id to make this work. Would really appreciate some guidance.</p>
```<code>def get_keywords(yaml_path):
    # Open the YAML file
    with open(yaml_path, 'r') as f:
        # Parse the YAML file
        data = yaml.safe_load(f)

    # Retrieve the list of keywords from the YAML file
    keywords = data['keywords']

    # Return the keywords
    return keywords

# Get the keywords from the YAML file
keywords = get_keywords(yaml_path)

# Set the starting page number
page = 1

# Set the maximum number of pages to retrieve
max_pages = 1

# Set a flag to indicate when to stop paginating
done = False

results = []

for word in keywords:
    # Create a cursor for the search
    cursor = tweepy.Cursor(api.search_users, q=word, count=20)

    # Iterate through the pages of the search results
    for page in cursor.pages(max_pages):
        # Iterate through the search results and print the screen name and biography of each profile
        for user in page:
            # Check the number of followers
            if user.followers_count < 2000:
                    screen_name = user.screen_name.encode('utf-8')
                    biography = user.description.encode('utf-8')
                    # Print the screen name and biography
                    print(f'Screen name: {repr(screen_name)}')
                    print(f'Biography: {repr(biography)}')

                    # Add the data to the list of dictionaries
                    results.append({'Screen name': screen_name, 'Biography': biography})

# Create a pandas dataframe from the results list
df = pd.DataFrame(results)

# Convert the dataframe to an HTML table
html = df.to_html()

# Open a file in write mode
with open('results.html', 'w') as f:
    # Write the HTML table to the file
    f.write(html)
</code>```

Body:
I've been trying to find a way to also filter my search results to only print twitter accounts less than 30 days old but i'm having a hard time with it. Can someone give me a hand adding this to my query? I'm not sure if I can do created_at or since_id to make this work. Would really appreciate some guidance.

def get_keywords(yaml_path):
    # Open the YAML file
    with open(yaml_path, 'r') as f:
        # Parse the YAML file
        data = yaml.safe_load(f)

    # Retrieve the list of keywords from the YAML file
    keywords = data['keywords']

    # Return the keywords
    return keywords

# Get the keywords from the YAML file
keywords = get_keywords(yaml_path)

# Set the starting page number
page = 1

# Set the maximum number of pages to retrieve
max_pages = 1

# Set a flag to indicate when to stop paginating
done = False

results = []

for word in keywords:
    # Create a cursor for the search
    cursor = tweepy.Cursor(api.search_users, q=word, count=20)

    # Iterate through the pages of the search results
    for page in cursor.pages(max_pages):
        # Iterate through the search results and print the screen name and biography of each profile
        for user in page:
            # Check the number of followers
            if user.followers_count < 2000:
                    screen_name = user.screen_name.encode('utf-8')
                    biography = user.description.encode('utf-8')
                    # Print the screen name and biography
                    print(f'Screen name: {repr(screen_name)}')
                    print(f'Biography: {repr(biography)}')

                    # Add the data to the list of dictionaries
                    results.append({'Screen name': screen_name, 'Biography': biography})

# Create a pandas dataframe from the results list
df = pd.DataFrame(results)

# Convert the dataframe to an HTML table
html = df.to_html()

# Open a file in write mode
with open('results.html', 'w') as f:
    # Write the HTML table to the file
    f.write(html)


问:
add output to see api result
I'm wondering why the max foods is capped out at 10k foods?  There are well over 1 million foods in their DB and no matter how I hit that API it maxes out at 10k for for each type (branded, foundation, legacy).  Here is my code to prove it:

```<code>dataType = 'Branded'
pageNumber = '200'
pageSize = '50'
url = f'https://api.nal.usda.gov/fdc/v1/foods/list?api_key={api_key}&dataType={dataType}&pageNumber={pageNumber}&pageSize={pageSize}'
r = requests.get(url)
print(r.status_code, len(r.json()), r)

dataType = 'Branded'
pageNumber = '201'
pageSize = '50'
url = f'https://api.nal.usda.gov/fdc/v1/foods/list?api_key={api_key}&dataType={dataType}&pageNumber={pageNumber}&pageSize={pageSize}'
r = requests.get(url)
print(r.status_code, len(r.json()), r)
</code>```

200 50 <Response [200]>

500 5 <Response [500]>

Title: add output to see api result

Body:
I'm wondering why the max foods is capped out at 10k foods?  There are well over 1 million foods in their DB and no matter how I hit that API it maxes out at 10k for for each type (branded, foundation, legacy).  Here is my code to prove it:

dataType = 'Branded'
pageNumber = '200'
pageSize = '50'
url = f'https://api.nal.usda.gov/fdc/v1/foods/list?api_key={api_key}&dataType={dataType}&pageNumber={pageNumber}&pageSize={pageSize}'
r = requests.get(url)
print(r.status_code, len(r.json()), r)

dataType = 'Branded'
pageNumber = '201'
pageSize = '50'
url = f'https://api.nal.usda.gov/fdc/v1/foods/list?api_key={api_key}&dataType={dataType}&pageNumber={pageNumber}&pageSize={pageSize}'
r = requests.get(url)
print(r.status_code, len(r.json()), r)

200 50 <Response [200]>

500 5 <Response [500]>


问:
nlminb Error in objective(.par, ...) : argument "k" is missing, with no default
I am trying to build a function that will estimate parameters of a burr distribution. I am having an issue when I use stats::nlminb I am expecting output but am getting an error that I did not specify a value for k which I believe I did.

Here is what I wrote:

library(TidyDensity)

logL <- function(alpha, c, k, data) {
  n <- length(data)
  logL <- -n * log(k) - n * log(c) - sum((alpha+1) * log(data/c) - (k+1) * log(1 + (data/c)^(-alpha)))
  return(logL)
}

# Generate some synthetic data from a Burr distribution
# with true parameter values alpha = 1, c = 2, k = 3
data <- tidy_burr(.n = 1000, 1, 2, 3)$y

# Estimate the parameters of the Burr distribution using maximum likelihood
fit <- stats::nlminb(start = c(1,2,3), objective = logL, data = data)
```
<p>Here is the failure message:</p>
<pre class="lang-r prettyprint-override"><code>> fit <- stats::nlminb(start = c(1,2,3), objective = logL, data = data)
Error in objective(.par, ...) : argument "k" is missing, with no default
</code>```

Body:
I am trying to build a function that will estimate parameters of a burr distribution. I am having an issue when I use stats::nlminb I am expecting output but am getting an error that I did not specify a value for k which I believe I did.

Here is what I wrote:

library(TidyDensity)

logL <- function(alpha, c, k, data) {
  n <- length(data)
  logL <- -n * log(k) - n * log(c) - sum((alpha+1) * log(data/c) - (k+1) * log(1 + (data/c)^(-alpha)))
  return(logL)
}

# Generate some synthetic data from a Burr distribution
# with true parameter values alpha = 1, c = 2, k = 3
data <- tidy_burr(.n = 1000, 1, 2, 3)$y

# Estimate the parameters of the Burr distribution using maximum likelihood
fit <- stats::nlminb(start = c(1,2,3), objective = logL, data = data)

Here is the failure message:

> fit <- stats::nlminb(start = c(1,2,3), objective = logL, data = data)
Error in objective(.par, ...) : argument "k" is missing, with no default


问:
react RTK query how to remove some cache by logout?
React RTK query how to remove some cache by logout?

I want to remove some cache which I use when Client is auth

```<code>    builder.mutation({
            query: () => ({ url: 'auth/logout', method: 'GET' }),
            invalidatesTags: ['user'], // I think that help me to remove cache but now I don't think more
        })
</code>```

Body:
React RTK query how to remove some cache by logout?

I want to remove some cache which I use when Client is auth

    builder.mutation({
            query: () => ({ url: 'auth/logout', method: 'GET' }),
            invalidatesTags: ['user'], // I think that help me to remove cache but now I don't think more
        })


问:
mapbox gl js feature Id and properties.id not always static and different
In mapbox-gl-js version: 2.10.0 I click on a point on a map and get all the features from 2 vector layers (application/vnd.mapbox-vector-tile) and one geojson layer data: 'http://localhost:8080/geoserver/mydata/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=mydata%3Acontexts&outputFormat=application%2Fjson' , , all served from GeoServer

In Geoserver's store I have Expose primary keys enabled, so in the features properties I have their IDs , coming from the database

I try to remove the duplicates that may created by mapbox based on their properties.id (sometimes mapbox creates duplicates of the same feature in vector and geojson, depending on zoom level)

Then I want to check if I have multiple features in the first vector layer. If I do, I create some objects, including data from other layers. To see what belongs to what feature from the first layer, I do it based on their properties.id , but sometimes its the same for both features, while feature id is different. I thought that properties.id always stays the same and its not duplicated on multiple features.

here is my code

```<code>map.current.on('click', (e) => {
    //get point
    const point = e.point;
    //get all features from all layers from that point
    let features = map.current.queryRenderedFeatures(point);

    //separate features by layer
    let excavations = features.filter(f => f.layer.id === 'excavations-layer');
    let parts = features.filter(f => f.layer.id === 'excavation_parts-layer');
    let contexts = features.filter(f => f.layer.id === 'contexts-layer');

    //removing duplicates
    excavations = excavations.filter((value, index, self) =>
      index === self.findIndex((et) => (
        et.properties.id === value.properties.id
      ))
    )
    parts = parts.filter((value, index, self) =>
      index === self.findIndex((pt) => (
        pt.properties.id === value.properties.id
      ))
    )
    contexts = contexts.filter((value, index, self) =>
      index === self.findIndex((ct) => (
        ct.properties.id === value.properties.id
      ))
    )
      //organize data per excavation, based on ids
      excavations.forEach(e => {
        ex_excavations = excavations.filter((value) =>
          e.properties.id == value.properties.id
        )
        ex_parts = parts.filter((value) =>
          e.properties.id = value.properties.excavation_id
        )
        ex_contexts = contexts.filter((value) =>
          turf.booleanIntersects(value,e)
        )
        exgroupArray.push(
          {
            name:e.properties.name,
            excavations:ex_excavations,
            parts:ex_parts,
            contexts:ex_contexts
          }
        )
        console.log('e id  loop ', e.id);
        console.log('exgroupArray ', exgroupArray);
        console.log('====================');
      });
</code>```

The original excavations array where I do the first forEach excavations.forEach(e => { has different feature ids (12,13) , but the same properties.id (12,12)

Other times has the same feature ids (12,12) , but different properties.id (12,13)

Check image

I though that properties.id comes from the Geoserver and should always be the different for each feature.

I try to base my code on that, but because it changes, it messes up my final exgroupArray and cannot loop it correctly in the HTML.

Any help how to fix this?

Thanks

Edit : It seems like if I am fully zoomed out, I get same feature id, different properties.id, check second image

Body:
In mapbox-gl-js version: 2.10.0 I click on a point on a map and get all the features from 2 vector layers (application/vnd.mapbox-vector-tile) and one geojson layer data: 'http://localhost:8080/geoserver/mydata/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=mydata%3Acontexts&outputFormat=application%2Fjson' , , all served from GeoServer

In Geoserver's store I have Expose primary keys enabled, so in the features properties I have their IDs , coming from the database

I try to remove the duplicates that may created by mapbox based on their properties.id (sometimes mapbox creates duplicates of the same feature in vector and geojson, depending on zoom level)

Then I want to check if I have multiple features in the first vector layer. If I do, I create some objects, including data from other layers. To see what belongs to what feature from the first layer, I do it based on their properties.id , but sometimes its the same for both features, while feature id is different. I thought that properties.id always stays the same and its not duplicated on multiple features.

here is my code

map.current.on('click', (e) => {
    //get point
    const point = e.point;
    //get all features from all layers from that point
    let features = map.current.queryRenderedFeatures(point);

    //separate features by layer
    let excavations = features.filter(f => f.layer.id === 'excavations-layer');
    let parts = features.filter(f => f.layer.id === 'excavation_parts-layer');
    let contexts = features.filter(f => f.layer.id === 'contexts-layer');

    //removing duplicates
    excavations = excavations.filter((value, index, self) =>
      index === self.findIndex((et) => (
        et.properties.id === value.properties.id
      ))
    )
    parts = parts.filter((value, index, self) =>
      index === self.findIndex((pt) => (
        pt.properties.id === value.properties.id
      ))
    )
    contexts = contexts.filter((value, index, self) =>
      index === self.findIndex((ct) => (
        ct.properties.id === value.properties.id
      ))
    )
      //organize data per excavation, based on ids
      excavations.forEach(e => {
        ex_excavations = excavations.filter((value) =>
          e.properties.id == value.properties.id
        )
        ex_parts = parts.filter((value) =>
          e.properties.id = value.properties.excavation_id
        )
        ex_contexts = contexts.filter((value) =>
          turf.booleanIntersects(value,e)
        )
        exgroupArray.push(
          {
            name:e.properties.name,
            excavations:ex_excavations,
            parts:ex_parts,
            contexts:ex_contexts
          }
        )
        console.log('e id  loop ', e.id);
        console.log('exgroupArray ', exgroupArray);
        console.log('====================');
      });

The original excavations array where I do the first forEach excavations.forEach(e => { has different feature ids (12,13) , but the same properties.id (12,12)

Other times has the same feature ids (12,12) , but different properties.id (12,13)

Check image

I though that properties.id comes from the Geoserver and should always be the different for each feature.

I try to base my code on that, but because it changes, it messes up my final exgroupArray and cannot loop it correctly in the HTML.

Any help how to fix this?

Thanks

Edit : It seems like if I am fully zoomed out, I get same feature id, different properties.id, check second image


问:
Implement while file >> event with custom classes in C++
I've to read a binary file coming from a data acquisition system. The binary file I want to read is made of many blocks, each of them starts with a specific tag, let's say they are all TIME in the first part, then all VOLT.

To do this I've created many different classes, the base class containing the file is the following:

class MyFile
{
public:
    // many methods...
private:
    std::ifstream in_;
};
```
<p>I have done the overload of the operators >> and <<, I'm able to write something like:</p>
<pre class="lang-cpp prettyprint-override"><code>MyFile file("filename.dat");
MyTimeEvent tEvent;
MyVoltEvent vEvent;
file >> tEvent;
cout << tEvent << endl;
// file >> tEvent; as many times as I know the TIME blocks are in this specific file.
file >>vEvent;
...
</code>```

what I want to achieve is something like this:

MyFile file("filename.dat");
MyTimeEvent tEvent;

while (file >> tEvent)
{
    // do stuff...
}
// Now I'm sure next block is a VOLT block.
```
<p>With the code I have, the compiler says me:</p>
```error: value of type 'MyFile' is not contextually convertible to 'bool'
```

What do I have to implement? Is it possible?

Body:
I've to read a binary file coming from a data acquisition system. The binary file I want to read is made of many blocks, each of them starts with a specific tag, let's say they are all TIME in the first part, then all VOLT.

To do this I've created many different classes, the base class containing the file is the following:

class MyFile
{
public:
    // many methods...
private:
    std::ifstream in_;
};

I have done the overload of the operators >> and <<, I'm able to write something like:

MyFile file("filename.dat");
MyTimeEvent tEvent;
MyVoltEvent vEvent;
file >> tEvent;
cout << tEvent << endl;
// file >> tEvent; as many times as I know the TIME blocks are in this specific file.
file >>vEvent;
...

what I want to achieve is something like this:

MyFile file("filename.dat");
MyTimeEvent tEvent;

while (file >> tEvent)
{
    // do stuff...
}
// Now I'm sure next block is a VOLT block.

With the code I have, the compiler says me:

error: value of type 'MyFile' is not contextually convertible to 'bool'

What do I have to implement? Is it possible?


问:
Redirect using useNavigate not working in form submission
I have been on this for quite some time now, and I can't seem to figure out why react useNavigate isn't working as expected.

After a user submits a post, its supposed to redirect the profile page, but instead, the window.location changes to
http://localhost:3000/share?topic=Lets+talk+about+a+town+hall&body=A+townhall+different+from+Balablu.+blu+blu%2C+bulaba
It appends the title and post to the address and refreshes.

This is my code

```<code> const post = axios.post(`${url}/thoughts/post`,  {...newPost} ,  { headers: {
                        'Authorization': `Bearer ${token}`
                        }} )
                        .then((res) => {
                            if(res.status === 200){
                                navigate('/profile', { replace: true })
                                setLoading(false)
                            }
                        })
                        .catch(err =>
                            console.log(err)
                        )
            return post
</code>```

I'm using a similar code in several other parts of the application, including the login page, and they all work fine, except here.
Someone pls help find what I'm missing.

Body:
I have been on this for quite some time now, and I can't seem to figure out why react useNavigate isn't working as expected.

After a user submits a post, its supposed to redirect the profile page, but instead, the window.location changes to
http://localhost:3000/share?topic=Lets+talk+about+a+town+hall&body=A+townhall+different+from+Balablu.+blu+blu%2C+bulaba
It appends the title and post to the address and refreshes.

This is my code

 const post = axios.post(`${url}/thoughts/post`,  {...newPost} ,  { headers: {
                        'Authorization': `Bearer ${token}`
                        }} )
                        .then((res) => {
                            if(res.status === 200){
                                navigate('/profile', { replace: true })
                                setLoading(false)
                            }
                        })
                        .catch(err =>
                            console.log(err)
                        )
            return post

I'm using a similar code in several other parts of the application, including the login page, and they all work fine, except here.
Someone pls help find what I'm missing.


问:
Is there a way to persist the search filter in AWS codecommit or codepipeline page?
There are several pages of these repositories and pipelines. It's good that it uses prefixes when naming but I have to type the prefix or the search criteria every time I visit the page. I would like to persist the search criteria and bookmark it. I can see it is doing an ajax call so I was hoping to see some urls/filters that I can use in the main url but was not successful.
Any suggestions?</p>


问:
How to reshow the parent window when the child window is closed in PyQt5 if you can only use .py files
I have the following code for a PyQt5 login page:

```<code># -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'login.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

from PyQt5 import QtCore, QtGui, QtWidgets
from pages import Ui_ModulesWindow

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(525, 466)
        MainWindow.setStyleSheet("\n"
"")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.username = QtWidgets.QLineEdit(self.centralwidget)
        self.username.setGeometry(QtCore.QRect(230, 220, 161, 20))
        self.username.setAutoFillBackground(False)
        self.username.setText("")
        self.username.setObjectName("username")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(100, 200, 161, 201))
        self.label_2.setText("")
        self.label_2.setPixmap(QtGui.QPixmap("../Downloads/key-icon-26600.png"))
        self.label_2.setScaledContents(True)
        self.label_2.setObjectName("label_2")
        self.password = QtWidgets.QLineEdit(self.centralwidget)
        self.password.setGeometry(QtCore.QRect(230, 290, 161, 20))
        self.password.setText("")
        self.password.setEchoMode(QtWidgets.QLineEdit.Password)
        self.password.setObjectName("password")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(190, 10, 161, 151))
        self.label_3.setLineWidth(-4)
        self.label_3.setText("")
        self.label_3.setTextFormat(QtCore.Qt.MarkdownText)
        self.label_3.setPixmap(QtGui.QPixmap("../Downloads/1398566.png"))
        self.label_3.setScaledContents(True)
        self.label_3.setObjectName("label_3")
        self.login = QtWidgets.QPushButton(self.centralwidget)
        self.login.setGeometry(QtCore.QRect(230, 370, 71, 41))
        font = QtGui.QFont()
        font.setFamily("Felix Titling")
        font.setPointSize(14)
        font.setBold(False)
        font.setWeight(50)
        self.login.setFont(font)
        self.login.setAutoFillBackground(False)
        self.login.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("../Downloads/kisspng-padlock-computer-icons-font-5ade28b87eab58.9482178615245088565189.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.login.setIcon(icon)
        self.login.setCheckable(False)
        self.login.setChecked(False)
        self.login.setObjectName("login")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(150, 200, 61, 61))
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap("kisspng-computer-icons-user-login-gender-5ac29ccdd316d3.9363446215227035658646.png"))
        self.label.setScaledContents(True)
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 525, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.login.clicked.connect(self.openModules)
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Login"))

    def openModules(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_ModulesWindow()
        self.ui.setupUi(self.window)
        self.window.show()
        MainWindow.hide()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

It has the following function mapped to the login button to show another window:

```<code>def openModules(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_ModulesWindow()
        self.ui.setupUi(self.window)
        self.window.show()
        MainWindow.hide()
</code>```

I want to know when I close the child window (it is a similar .py file), how can I reshow this login page. The issue is I have only .py files and I don't have access to ui files. It would be great if you can tell me a solution within what I have.

Body:
I have the following code for a PyQt5 login page:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'login.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

from PyQt5 import QtCore, QtGui, QtWidgets
from pages import Ui_ModulesWindow

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(525, 466)
        MainWindow.setStyleSheet("\n"
"")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.username = QtWidgets.QLineEdit(self.centralwidget)
        self.username.setGeometry(QtCore.QRect(230, 220, 161, 20))
        self.username.setAutoFillBackground(False)
        self.username.setText("")
        self.username.setObjectName("username")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(100, 200, 161, 201))
        self.label_2.setText("")
        self.label_2.setPixmap(QtGui.QPixmap("../Downloads/key-icon-26600.png"))
        self.label_2.setScaledContents(True)
        self.label_2.setObjectName("label_2")
        self.password = QtWidgets.QLineEdit(self.centralwidget)
        self.password.setGeometry(QtCore.QRect(230, 290, 161, 20))
        self.password.setText("")
        self.password.setEchoMode(QtWidgets.QLineEdit.Password)
        self.password.setObjectName("password")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(190, 10, 161, 151))
        self.label_3.setLineWidth(-4)
        self.label_3.setText("")
        self.label_3.setTextFormat(QtCore.Qt.MarkdownText)
        self.label_3.setPixmap(QtGui.QPixmap("../Downloads/1398566.png"))
        self.label_3.setScaledContents(True)
        self.label_3.setObjectName("label_3")
        self.login = QtWidgets.QPushButton(self.centralwidget)
        self.login.setGeometry(QtCore.QRect(230, 370, 71, 41))
        font = QtGui.QFont()
        font.setFamily("Felix Titling")
        font.setPointSize(14)
        font.setBold(False)
        font.setWeight(50)
        self.login.setFont(font)
        self.login.setAutoFillBackground(False)
        self.login.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("../Downloads/kisspng-padlock-computer-icons-font-5ade28b87eab58.9482178615245088565189.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.login.setIcon(icon)
        self.login.setCheckable(False)
        self.login.setChecked(False)
        self.login.setObjectName("login")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(150, 200, 61, 61))
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap("kisspng-computer-icons-user-login-gender-5ac29ccdd316d3.9363446215227035658646.png"))
        self.label.setScaledContents(True)
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 525, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.login.clicked.connect(self.openModules)
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Login"))

    def openModules(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_ModulesWindow()
        self.ui.setupUi(self.window)
        self.window.show()
        MainWindow.hide()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

It has the following function mapped to the login button to show another window:

def openModules(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_ModulesWindow()
        self.ui.setupUi(self.window)
        self.window.show()
        MainWindow.hide()

I want to know when I close the child window (it is a similar .py file), how can I reshow this login page. The issue is I have only .py files and I don't have access to ui files. It would be great if you can tell me a solution within what I have.


问:
How to implement a PUK kernel into a Gaussian Process Regression in sklearn
I'm trying to implement a custom kernel, in this case a PUK kernel, into the GPR library of sklearn. The code of this kernel is located in this GitHub repository: https://github.com/rlphilli/sklearn-PUK-kernel/blob/master/PUK_kernel.py , so I've got that covered, but after having looked at the documentation of sklearn about kernels, I'm not able to implement this one so when I do this:

kernel = RBF(1) gpr = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=3) gpr.fit(X_train, y_train)

Instead of using the RBF kernel I just call my custom PUK kernel.

My input data is made up of 7 dimensions, and I'm trying to predict a numerical value.
Thanks!


问:
How i save multiple request.POST.get() in form.save()
I wanna get data with request.POST.get() and then save in form.save(). How I can solve that?

def example(request):
        form = addform()
        if (request.method == 'POST'):
            form = addform(request.POST)
            question = request.POST.get('question')
            answer = request.POST.get('answer')
            explain = request.POST.get('explain')

            if (form.is_valid()):
                form.save() # i wann save all (question + answer + explain) here in form.

        context = {'form': form}
        return render(request, 'Example_fragenkatalog.html', context)
```

I hope someone can help me! Thank you!

Body:
I wanna get data with request.POST.get() and then save in form.save(). How I can solve that?

def example(request):
        form = addform()
        if (request.method == 'POST'):
            form = addform(request.POST)
            question = request.POST.get('question')
            answer = request.POST.get('answer')
            explain = request.POST.get('explain')

            if (form.is_valid()):
                form.save() # i wann save all (question + answer + explain) here in form.

        context = {'form': form}
        return render(request, 'Example_fragenkatalog.html', context)

I hope someone can help me! Thank you!


问:
Syntax error in graph mermaid version 9.2.0
I'm trying to learn how to use mermaid to generate a class diagram but I'm facing this issue: Syntax error in graph mermaid version 9.2.0

The code I have added I took from the mermaid docs.

Exactly the BankAccount class:

```<code>---
title: Bank example
---
classDiagram
    class BankAccount
    BankAccount : +String owner
    BankAccount : +Bigdecimal balance
    BankAccount : +deposit(amount)
    BankAccount : +withdrawal(amount)
</code>```

Has anyone had the same issue before?

Body:
I'm trying to learn how to use mermaid to generate a class diagram but I'm facing this issue: Syntax error in graph mermaid version 9.2.0

The code I have added I took from the mermaid docs.

Exactly the BankAccount class:

---
title: Bank example
---
classDiagram
    class BankAccount
    BankAccount : +String owner
    BankAccount : +Bigdecimal balance
    BankAccount : +deposit(amount)
    BankAccount : +withdrawal(amount)

Has anyone had the same issue before?


问:
SQL - Increment based on above rows content
I'm not sure if this is even possible in SQL but I'm trying to give it a go.

Here are my requirements:

If a user has "Sick" (in Paycode) that is where the Instance and Occurence starts

If the user has 1 day "Sick" (in Paycode) then returns (null) then off "Sick" again then the Instance increments again, whilst the Occurence stays the same

If the user returns for 2 days or more days (null) then is "Sick" (in Paycode) again, this is a new Occurence, so the Occurance Increments and the Instance resets to 1

So basically my desired Output would look like this:

Date
ID
Paycode
Occurrence
Instance

01/12/2022
12345
Sick
1
1

02/12/2022
12345
Sick
1
2

03/12/2022
12345
null
null
null

04/12/2022
12345
Sick
1
3

05/12/2022
12345
null
null
null

06/12/2022
12345
null
null
null

07/12/2022
12345
Sick
2
1

08/12/2022
12345
Sick
2
2

But what I have in the minute is this:

Date
ID
Paycode
Occurrence
Instance

01/12/2022
12345
Sick
null
1

02/12/2022
12345
Sick
null
2

03/12/2022
12345
null
null
null

04/12/2022
12345
Sick
null
3

05/12/2022
12345
null
null
null

06/12/2022
12345
null
null
null

07/12/2022
12345
Sick
null
4

08/12/2022
12345
Sick
null
5

Partly becuase I'm unsure how to approach the Occurnence Column logic and partly because I'm unsure how to use lag() or sum() to check the two above rows

My code is as follows:

```<code>Select *
    , null as 'Occurrence'
    ,sum(case when a.Paycode is null then 0 else 1 end) over (order by a.Date) as 'Instance'
FROM MyTable
</code>```

So I've got so far using the Over() but I need to know how to reset this if the two rows above are null and also setup the Occurrence.

All of the dates are in ascending order by default, so you can always "check if the above two rows are null, is so do x"

Any help would really be appreciated, I've spent days trying to find a solution with no luck.

Thanks,
Chris

Body:
I'm not sure if this is even possible in SQL but I'm trying to give it a go.

Here are my requirements:

If a user has "Sick" (in Paycode) that is where the Instance and Occurence starts

If the user has 1 day "Sick" (in Paycode) then returns (null) then off "Sick" again then the Instance increments again, whilst the Occurence stays the same

If the user returns for 2 days or more days (null) then is "Sick" (in Paycode) again, this is a new Occurence, so the Occurance Increments and the Instance resets to 1

So basically my desired Output would look like this:

Date
ID
Paycode
Occurrence
Instance

01/12/2022
12345
Sick
1
1

02/12/2022
12345
Sick
1
2

03/12/2022
12345
null
null
null

04/12/2022
12345
Sick
1
3

05/12/2022
12345
null
null
null

06/12/2022
12345
null
null
null

07/12/2022
12345
Sick
2
1

08/12/2022
12345
Sick
2
2

But what I have in the minute is this:

Date
ID
Paycode
Occurrence
Instance

01/12/2022
12345
Sick
null
1

02/12/2022
12345
Sick
null
2

03/12/2022
12345
null
null
null

04/12/2022
12345
Sick
null
3

05/12/2022
12345
null
null
null

06/12/2022
12345
null
null
null

07/12/2022
12345
Sick
null
4

08/12/2022
12345
Sick
null
5

Partly becuase I'm unsure how to approach the Occurnence Column logic and partly because I'm unsure how to use lag() or sum() to check the two above rows

My code is as follows:

Select *
    , null as 'Occurrence'
    ,sum(case when a.Paycode is null then 0 else 1 end) over (order by a.Date) as 'Instance'
FROM MyTable

So I've got so far using the Over() but I need to know how to reset this if the two rows above are null and also setup the Occurrence.

All of the dates are in ascending order by default, so you can always "check if the above two rows are null, is so do x"

Any help would really be appreciated, I've spent days trying to find a solution with no luck.

Thanks,
Chris


问:
Navigate to Home page after save in handlerowactions LWC
```<code>case 'logacall':
                this[NavigationMixin.Navigate]({
                    type: 'standard__objectPage',
                    attributes: {
                        objectApiName: 'task',
                        actionName: 'new'
                    },
     state : {
              defaultFieldValues:"WhatId=" + this.Id}
                });
                break;
</code>```

How to navigate to the Homepage after that save of new task, right now this takes to the new task record

Tried the Return URL

Body:
case 'logacall':
                this[NavigationMixin.Navigate]({
                    type: 'standard__objectPage',
                    attributes: {
                        objectApiName: 'task',
                        actionName: 'new'
                    },
     state : {
              defaultFieldValues:"WhatId=" + this.Id}
                });
                break;

How to navigate to the Homepage after that save of new task, right now this takes to the new task record

Tried the Return URL


问:
How can I add more then two knobs into ion-range?
I have made a timeline by ion-range, so user can choose time for whatever by moving knobs, and I need somehow disable some areas like it's already taken, so user could not choose time in that area.

I've been trying this by ion-range, but there's only two knobs and no options to configure it. If you have any suggestions how to make it work in that way, I'd be very appreciated, may be you know other way to do this, not by ion-range, it would be great if compatible with ionic 5

https://i.stack.imgur.com/hqL43.png


问:
Debugging namespace imports in Javascript
In Javascript there is what is called namespace imports that take the following form:

import * as myModule from "/modules/my-module.js";

myModule represents a namespace object where all exports are properties of myModule. myModule is also a sealed object.

Is there anyway at runtime to  interrogate the properties of myModule? As I understand it, a sealed object means that the object is immutable. However, it seems that one should be able to still see the properties of myModule. But when I set a breakpoint in my code (in VS Code) and try to examine myModule with the debugger, I get the following message (in this instance myModule is called cornerstoneTools:

Here is the import statement:

import * as cornerstoneTools from “cornerstone-tools”;

Here is the error when I try to examine cornerstoneTools with VS Code:

```<code>Uncaught ReferenceError ReferenceError: cornerstoneTools is not defined at eval (repl:1:1)
</code>```

Was wondering if anyone has any thoughts about this? Is there a way to determine the exports from a module?

I tried interrogating namespace imports using the VS Code debugger but was not successful. I tried finding alternative ways to discover the exports from a JavaScript module.

Body:
In Javascript there is what is called namespace imports that take the following form:

import * as myModule from "/modules/my-module.js";

myModule represents a namespace object where all exports are properties of myModule. myModule is also a sealed object.

Is there anyway at runtime to  interrogate the properties of myModule? As I understand it, a sealed object means that the object is immutable. However, it seems that one should be able to still see the properties of myModule. But when I set a breakpoint in my code (in VS Code) and try to examine myModule with the debugger, I get the following message (in this instance myModule is called cornerstoneTools:

Here is the import statement:

import * as cornerstoneTools from “cornerstone-tools”;

Here is the error when I try to examine cornerstoneTools with VS Code:

Uncaught ReferenceError ReferenceError: cornerstoneTools is not defined at eval (repl:1:1)

Was wondering if anyone has any thoughts about this? Is there a way to determine the exports from a module?

I tried interrogating namespace imports using the VS Code debugger but was not successful. I tried finding alternative ways to discover the exports from a JavaScript module.


问:
Geospatial database SQL
I need to create a database with geospatial information, but when I save the coordinates the SQL returns an error with ST_GeomFromGeoJSON.
I tested with :

```<code>SELECT * FROM `detections`;

SELECT ST_AsText(ST_GeomFromGeoJson(
'{
  "`type`: `Feature`,
    "properties": {"location": "Oracle HQ"},
    { "geometry":
    {
    "type": 'Polygon',
            "coordinates": [-122.262289, 37.530518]
    }
    }'
    ));

SELECT ST_AsText(ST_GeomFromGeoJSON(@json));
</code>```

And the following:

```<code>SELECT * FROM `detections`;

SELECT ST_AsText(ST_GeomFromGeoJson(
'{
  "type": "Feature",
    "properties": {"location": "CHILE"},
    "geometry":
    {
    "type": "polygon",
            "coordinates":[
          [
            [
              -73.57764512241732,
              -37.155938029154186
            ],
            [
              -73.55017930210506,
              -37.199705574431235
            ],
            [
              -73.46228867710494,
              -37.21720549166924
            ],
            [
              -73.4073570364798,
              -37.25656546485393
            ],
            [
              -73.30848008335487,
              -37.25656546485393
            ],
            [
              -73.32495957554237,
              -37.19532996103442
            ],
            [
              -73.40186387241769,
              -37.1033835117005
            ],
            [
              -73.55017930210506,
              -37.1033835117005
            ],
            [
              -73.57764512241732,
              -37.155938029154186
            ]
          ]
    }
    }'
    ));

SELECT ST_AsText(ST_GeomFromGeoJSON(@json));
</code>```

I tried to add the coordinates to my detections table but it returns NULL as st_geofromjson error (it is empty) and I hope I can show those coordinates of the polygon in an interface.

Title: Geospatial database SQL

Body:
I need to create a database with geospatial information, but when I save the coordinates the SQL returns an error with ST_GeomFromGeoJSON.
I tested with :

SELECT * FROM `detections`;

SELECT ST_AsText(ST_GeomFromGeoJson(
'{
  "`type`: `Feature`,
    "properties": {"location": "Oracle HQ"},
    { "geometry":
    {
    "type": 'Polygon',
            "coordinates": [-122.262289, 37.530518]
    }
    }'
    ));

SELECT ST_AsText(ST_GeomFromGeoJSON(@json));

And the following:

SELECT * FROM `detections`;

SELECT ST_AsText(ST_GeomFromGeoJson(
'{
  "type": "Feature",
    "properties": {"location": "CHILE"},
    "geometry":
    {
    "type": "polygon",
            "coordinates":[
          [
            [
              -73.57764512241732,
              -37.155938029154186
            ],
            [
              -73.55017930210506,
              -37.199705574431235
            ],
            [
              -73.46228867710494,
              -37.21720549166924
            ],
            [
              -73.4073570364798,
              -37.25656546485393
            ],
            [
              -73.30848008335487,
              -37.25656546485393
            ],
            [
              -73.32495957554237,
              -37.19532996103442
            ],
            [
              -73.40186387241769,
              -37.1033835117005
            ],
            [
              -73.55017930210506,
              -37.1033835117005
            ],
            [
              -73.57764512241732,
              -37.155938029154186
            ]
          ]
    }
    }'
    ));

SELECT ST_AsText(ST_GeomFromGeoJSON(@json));

I tried to add the coordinates to my detections table but it returns NULL as st_geofromjson error (it is empty) and I hope I can show those coordinates of the polygon in an interface.


问:
How to find longest palendromic substring?
For example you have string, where you need to find longest palindromic(symmetrical) substring with the best Big-O, how would you do that?

Example 1

```<code>Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
</code>```

Here is my solution, but it is too slow for this type of problem.

```<code>public String longestPalindrome(String s) {
    if (s == null || s.length() == 0)
        return s;
    String longest = s.substring(0, 1);
    for (int i = 0; i < s.length(); i++) {
        if(s.length()-i <longest.length()/2)
            break;
        String oddPal = findLengthofPalindrome(s, i, i);
        if (longest.length() < oddPal.length()) {
            longest = oddPal;
        }

        String evenPal = findLengthofPalindrome(s, i, i + 1);
        if (longest.length() < evenPal.length()) {
            longest = evenPal;
        }
    }
    return longest;

}

private String findLengthofPalindrome(String s, int left, int right) {
    while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
        left--;
        right++;
    }
    return s.substring(left + 1, right);
}
</code>```

Body:
For example you have string, where you need to find longest palindromic(symmetrical) substring with the best Big-O, how would you do that?

Example 1

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.

Here is my solution, but it is too slow for this type of problem.

public String longestPalindrome(String s) {
    if (s == null || s.length() == 0)
        return s;
    String longest = s.substring(0, 1);
    for (int i = 0; i < s.length(); i++) {
        if(s.length()-i <longest.length()/2)
            break;
        String oddPal = findLengthofPalindrome(s, i, i);
        if (longest.length() < oddPal.length()) {
            longest = oddPal;
        }

        String evenPal = findLengthofPalindrome(s, i, i + 1);
        if (longest.length() < evenPal.length()) {
            longest = evenPal;
        }
    }
    return longest;

}

private String findLengthofPalindrome(String s, int left, int right) {
    while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
        left--;
        right++;
    }
    return s.substring(left + 1, right);
}


问:
pytest assert if method inside of context manager was called
I have implemented interface for InfluxDB, based on theirs examples. It uses writting to DB inside context_manager:

```<code>from influxdb_client import InfluxDBClient, Point, WriteOptions

class InfluxInterface:

    def __init__(self):
        self.__client = None
        self.bucket_name = 'bucket_name'

    def connect(self, url=IFDB_URL, token=IFDB_TOKEN, org=IFDB_ORG, timeout=IFDB_TIMEOUT, debug=False):
        self.__client = InfluxDBClient(url=url, token=token, org=org, timeout=timeout, debug=debug)

    def is_connected(self):
        return self.__client is not None

    def insert_stuff(self, stuff: List[Tag]):
        if not self.is_connected():
            return

        points = []

        for item in stuff:
            point = Point('measurment_name').time(item.item_ts).tag('tag_name', item.tag).field('field_name', item.field)
            points.append(point)

        with self.__client.write_api(write_options=WriteOptions(batch_size=5000, flush_interval=5000),
                                     success_callback=self.batch_write_success,
                                     error_callback=self.batch_write_error,
                                     retry_callback=self.batch_write_retry) as write_api:
            write_api.write(bucket=self.bucket_name, record=points)
            # Write is not returning anything (returning None)
</code>```

Now, I want to unittest it using pytest, but I am failing..

First thing I want to do is, to mock is_connected(), to allways return True. I do it this way:

```<code>mocker.patch.object(InfluxInterface, "is_connected").return_value = True
</code>```

My goal is to mock write_api.write(bucket=self.bucket_name, record=points), because I do not want to wrtite into DB, or connect to DB, or even have the need to have DB as a predispositon to unittest this stuff. I only want to assert if write_api.write was called with correct arguments.  So I have prepared this test method:

```<code>import pytest
from my_lib.influx_lib import InfluxInterface

class TestInfluxInterface:
    def test_insert_stuff(self, mocker):
        # influx_client = mocker.patch('my_lib.influx_lib.InfluxDBClient', autospec=True)
        # Is connected, return True
        fake_is_connected = mocker.patch.object(InfluxInterface, "is_connected").return_value = True

        # fake_client = mocker.patch.object(InfluxInterface, '__client', autospec=True)

        fake_write_api = mocker.patch.object(InfluxInterface, '_InfluxInterface__client').return_value.__enter__.write

        test_connector = InfluxInterface()
        test_list = [test_item_1, test_item_2, test_item_3]
        result = test_connector.insert_stuff(test_list)
        fake_write_api.assert_called_once_with(bucket=self.bucket_name, record=points)
</code>```

As you can see in the comments of the code above, I have been trying various different approaches to mock the context manager and write_api.write method properly. But none of that works.

Edit:

This is, how far I managed to get so far:

```<code>def test_insert_tags(self, mocker):
    influx_client = mocker.patch('my_lib.influx_lib.InfluxDBClient')  # , autospec=True)
    # Is connected, return Status.ok
    mocker.patch.object(InfluxInterface, "is_connected").return_value = True

    test_connector = InfluxInterface()
    fake_write_api = mocker.MagicMock()
    test_connector._InfluxInterface__client = influx_client
    # test_connector._InfluxInterface__client.write_api.return_value = mocker.Mock(w_api=fake_write_api, __enter__=influx_client, __exit__=mocker.Mock())
    # test_connector._InfluxInterface__client.write_api.return_value = mocker.Mock(__enter__=fake_write_api, __exit__=mocker.Mock())
    # test_connector._InfluxInterface__client.write_api.return_value.__enter__.w_api.write = fake_write_api

    test_taglist = [analog_test_tag, discrete_test_tag, string_test_tag]
    result = test_connector.insert_tags(test_taglist, RecordType.all_values)

    print(f'influx_client has calls: {influx_client.write_api.mock_calls}')
    print(f'fake_write_api has calls: {fake_write_api.mock_calls}')
    print(f'fake_write_api.write has calls: {fake_write_api.write.mock_calls}')

    fake_write_api.write.assert_called_once()
    assert result.result_status.status_code == Tconf.status_ok.status_code
</code>```

And the code is actually run, only assert is not meet. (All 3 commented calls to set return_value pass, but fake_write_api is not called in each of those cases.)

This is the result of test when it is run as the code above.

```<code>influx_client has calls:
 [call(write_options=<influxdb_client.client.write_api.WriteOptions object at 0x7f8d9e3bf580>, success_callback=<bound method InfluxInterface.batch_write_success of <my_lib.influx_lib.InfluxInterface object at 0x7f8d9e34d6c0>>, error_callback=<bound method InfluxInterface.batch_write_error of <my_lib.influx_lib.InfluxInterface object at 0x7f8d9e34d6c0>>, retry_callback=<bound method InfluxInterface.batch_write_retry of <my_lib.influx_lib.InfluxInterface object at 0x7f8d9e34d6c0>>),
  call().__enter__(),
  call().__enter__().write(bucket='bucket_name', record=[<influxdb_client.client.write.point.Point object at 0x7f8d9e3bd690>, <influxdb_client.client.write.point.Point object at 0x7f8d9e3bd6f0>]),
  call().__exit__(None, None, None)]
fake_write_api has calls: []
fake_write_api.write has calls: []
</code>```

Body:
I have implemented interface for InfluxDB, based on theirs examples. It uses writting to DB inside context_manager:

from influxdb_client import InfluxDBClient, Point, WriteOptions

class InfluxInterface:

    def __init__(self):
        self.__client = None
        self.bucket_name = 'bucket_name'

    def connect(self, url=IFDB_URL, token=IFDB_TOKEN, org=IFDB_ORG, timeout=IFDB_TIMEOUT, debug=False):
        self.__client = InfluxDBClient(url=url, token=token, org=org, timeout=timeout, debug=debug)

    def is_connected(self):
        return self.__client is not None

    def insert_stuff(self, stuff: List[Tag]):
        if not self.is_connected():
            return

        points = []

        for item in stuff:
            point = Point('measurment_name').time(item.item_ts).tag('tag_name', item.tag).field('field_name', item.field)
            points.append(point)

        with self.__client.write_api(write_options=WriteOptions(batch_size=5000, flush_interval=5000),
                                     success_callback=self.batch_write_success,
                                     error_callback=self.batch_write_error,
                                     retry_callback=self.batch_write_retry) as write_api:
            write_api.write(bucket=self.bucket_name, record=points)
            # Write is not returning anything (returning None)

Now, I want to unittest it using pytest, but I am failing..

First thing I want to do is, to mock is_connected(), to allways return True. I do it this way:

mocker.patch.object(InfluxInterface, "is_connected").return_value = True

My goal is to mock write_api.write(bucket=self.bucket_name, record=points), because I do not want to wrtite into DB, or connect to DB, or even have the need to have DB as a predispositon to unittest this stuff. I only want to assert if write_api.write was called with correct arguments.  So I have prepared this test method:

import pytest
from my_lib.influx_lib import InfluxInterface

class TestInfluxInterface:
    def test_insert_stuff(self, mocker):
        # influx_client = mocker.patch('my_lib.influx_lib.InfluxDBClient', autospec=True)
        # Is connected, return True
        fake_is_connected = mocker.patch.object(InfluxInterface, "is_connected").return_value = True

        # fake_client = mocker.patch.object(InfluxInterface, '__client', autospec=True)

        fake_write_api = mocker.patch.object(InfluxInterface, '_InfluxInterface__client').return_value.__enter__.write

        test_connector = InfluxInterface()
        test_list = [test_item_1, test_item_2, test_item_3]
        result = test_connector.insert_stuff(test_list)
        fake_write_api.assert_called_once_with(bucket=self.bucket_name, record=points)

As you can see in the comments of the code above, I have been trying various different approaches to mock the context manager and write_api.write method properly. But none of that works.

Edit:

This is, how far I managed to get so far:

def test_insert_tags(self, mocker):
    influx_client = mocker.patch('my_lib.influx_lib.InfluxDBClient')  # , autospec=True)
    # Is connected, return Status.ok
    mocker.patch.object(InfluxInterface, "is_connected").return_value = True

    test_connector = InfluxInterface()
    fake_write_api = mocker.MagicMock()
    test_connector._InfluxInterface__client = influx_client
    # test_connector._InfluxInterface__client.write_api.return_value = mocker.Mock(w_api=fake_write_api, __enter__=influx_client, __exit__=mocker.Mock())
    # test_connector._InfluxInterface__client.write_api.return_value = mocker.Mock(__enter__=fake_write_api, __exit__=mocker.Mock())
    # test_connector._InfluxInterface__client.write_api.return_value.__enter__.w_api.write = fake_write_api

    test_taglist = [analog_test_tag, discrete_test_tag, string_test_tag]
    result = test_connector.insert_tags(test_taglist, RecordType.all_values)

    print(f'influx_client has calls: {influx_client.write_api.mock_calls}')
    print(f'fake_write_api has calls: {fake_write_api.mock_calls}')
    print(f'fake_write_api.write has calls: {fake_write_api.write.mock_calls}')

    fake_write_api.write.assert_called_once()
    assert result.result_status.status_code == Tconf.status_ok.status_code

And the code is actually run, only assert is not meet. (All 3 commented calls to set return_value pass, but fake_write_api is not called in each of those cases.)

This is the result of test when it is run as the code above.

influx_client has calls:
 [call(write_options=<influxdb_client.client.write_api.WriteOptions object at 0x7f8d9e3bf580>, success_callback=<bound method InfluxInterface.batch_write_success of <my_lib.influx_lib.InfluxInterface object at 0x7f8d9e34d6c0>>, error_callback=<bound method InfluxInterface.batch_write_error of <my_lib.influx_lib.InfluxInterface object at 0x7f8d9e34d6c0>>, retry_callback=<bound method InfluxInterface.batch_write_retry of <my_lib.influx_lib.InfluxInterface object at 0x7f8d9e34d6c0>>),
  call().__enter__(),
  call().__enter__().write(bucket='bucket_name', record=[<influxdb_client.client.write.point.Point object at 0x7f8d9e3bd690>, <influxdb_client.client.write.point.Point object at 0x7f8d9e3bd6f0>]),
  call().__exit__(None, None, None)]
fake_write_api has calls: []
fake_write_api.write has calls: []


问:
How to rename a property in redux toolkit when it may already exist with it's "old" name
I'm looking to update a property name within a Redux Toolkit slice.

The problem is, users may already have the old property stored in the slice.  Is there a way to migrate that property data from the old property name to the new property name?

I'm finding that if I just straight up rename the prop, and then try to do something with it (someData.newPropName.trim()), an error is thrown because the prior "old" prop name exists in the store and the "new" one isn't initialized or anything.  Hence, you get a good ol' undefined error.


问:
Find the rotation matrix from one 3d coordinate system to another
I have been given 2 3d coordinate systems. How do I find the rotation matrix from one coordinate system to the other and vice versa?
Can we use Eulers angles?</p>


问:
Private class in python package
I'm writing a python library to interface to a rest server.
I would like to be able to add classes inside the library, which I would like to be hidden once the library is installed via pip and imported into any project.

Example of the library structure:

```<code>.
├── my_library
    ├── __init__.py
    ├── controller
    |   ├──OtherClass.py
    |   └──Client.py
    └── models
        ├── __init__.py
        └── MyModel.py
</code>```

Content of __init__.py in root folder.

```<code>from .controller.Client import Client

</code>```

setup.py:

```<code>from setuptools import find_packages, setup

setup(
    name='my_library',
    packages=find_packages(include=['my_library']),
    version='0.1.0',
    description='My library',
    author='Pasini Matteo',
    setup_requires=['pytest-runner'],
    license='MIT',
    tests_require=['pytest==4.4.1'],
    test_suite='tests',
)
</code>```

what I would like not to be able to do those who use the library:

```<code>from my_library.controller.OtherClass import OtherClass
</code>```

python version >= 3.6

Title: Private class in python package

Body:
I'm writing a python library to interface to a rest server.
I would like to be able to add classes inside the library, which I would like to be hidden once the library is installed via pip and imported into any project.

Example of the library structure:

.
├── my_library
    ├── __init__.py
    ├── controller
    |   ├──OtherClass.py
    |   └──Client.py
    └── models
        ├── __init__.py
        └── MyModel.py

Content of __init__.py in root folder.

from .controller.Client import Client

setup.py:

from setuptools import find_packages, setup

setup(
    name='my_library',
    packages=find_packages(include=['my_library']),
    version='0.1.0',
    description='My library',
    author='Pasini Matteo',
    setup_requires=['pytest-runner'],
    license='MIT',
    tests_require=['pytest==4.4.1'],
    test_suite='tests',
)

what I would like not to be able to do those who use the library:

from my_library.controller.OtherClass import OtherClass

python version >= 3.6


问:
How do I reconstruct a mesh starting from ground truth poses and depth maps in Open3D?
I'm trying to test a custom 3D reconstruction pipeline that receives ground truth depth maps as input:

To see the full code you can proceed to the end of the question, now I will just outline my approach without getting into the details.

Suppose I have a mesh

```<code>bunny_mesh = o3d.data.BunnyMesh()
mesh = o3d.io.read_triangle_mesh(bunny_mesh.path)
</code>```

And I extract some poses using the p key while visualizing the mesh with o3d.visualization.draw_geometries([mesh]).

Then I create a trajectory by linearly interpolating subsequent poses.
Then, at each pose I extract the depth information through depth = np.array(vis.capture_depth_float_buffer(True)) and I save it to create a dataset that looks like this:

(this is just a portion of the dataset)

Finally, the code to reconstruct the mesh looks like the following

```<code>VOLUME_SIZE = 0.5
N_VOXELS_PER_SIDE = 1440
SDF_TRUNC = 3 * VOLUME_SIZE / N_VOXELS_PER_SIDE # 3

volume = o3d.pipelines.integration.ScalableTSDFVolume(
    voxel_length= VOLUME_SIZE / N_VOXELS_PER_SIDE,
    sdf_trunc=SDF_TRUNC,
    color_type=o3d.pipelines.integration.TSDFVolumeColorType.RGB8
)

for depth,pose in zip(depth_maps, poses):
  color = ... # Create dummy rgb image
  rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth(
              o3d.geometry.Image(color),
              o3d.geometry.Image(depth),
              depth_trunc=1.0,
              convert_rgb_to_intensity=False,
              depth_scale = 1.0
          )
  volume.integrate(
    rgbd,
    intrinsics, # the intrinsics were retrieved from the previously loaded poses
    pose,
  )
</code>```

And this is what I obtain:

My question is:
How can I obtain an output mesh that is as similar as possible to the original one? Why the poses extracted from the visualizer seem to not work when trying to integrate the TSDF volume?

FULL CODE

Load mesh and create key poses

```<code>bunny_mesh = o3d.data.BunnyMesh()
mesh = o3d.io.read_triangle_mesh(bunny_mesh.path)
o3d.visualization.draw_geometries([mesh])
# create poses by pressing 'p' in correspondence of different views of the mesh
</code>```

Create trajectory from poses

```<code>
TRAJECTORY_PATH = "path/to/output/trajectory.json"
FPS = 30
NUM_FRAMES_BETWEEN_POSES = FPS * 5

poses = ... # Ordered list of poses paths (obtained with the 'p' key in the visualizer)

fx = 935.3074360871938
fy = 935.3074360871938
cx = 959.5
cy = 539.5
width = 1920
height = 1080
intrinsic = o3d.camera.PinholeCameraIntrinsic(
    width,
    height,
    fx,
    fy,
    cx,
    cy
)

for i in tqdm(range(1, len(poses))):
    pose_a = poses[i-1]
    pose_b = poses[i]
    with open(pose_a) as f_a:
        x = json.load(f_a)
        extrinsic_matrix_a = np.array(x["extrinsic"])
    with open(pose_b) as f_b:
        x = json.load(f_b)
        extrinsic_matrix_b = np.array(x["extrinsic"])

    extrinsic_matrix_list = np.linspace(extrinsic_matrix_a,extrinsic_matrix_b,N_FRAMES_BETWEEN_POSES)

    for j in range(len(extrinsic_matrix_list)):
        p = o3d.camera.PinholeCameraParameters()
        p.intrinsic = intrinsic
        p.extrinsic = np.array(extrinsic_matrix_list[j]).reshape((4,4)).T
        params.append(p)

trajectory.parameters = params

if os.path.isfile(TRAJECTORY_PATH):
    os.remove(TRAJECTORY_PATH)
o3d.io.write_pinhole_camera_trajectory(TRAJECTORY_PATH, trajectory)

print(f"Traejctory saved @ {TRAJECTORY_PATH}")
</code>```

Create depth maps

```<code>
EXTENSIONS = "pfm"
OUTPUT_DEPTH_MAPS_FOLDER = "path/to/an/empty/folder/"
MINIMUM_DEPTH_VALUE = 0.0008
MAXIMUM_DEPTH_VALUE = 0.25

def custom_draw_geometry_with_camera_trajectory(pcd):

    custom_draw_geometry_with_camera_trajectory.index = -1
    custom_draw_geometry_with_camera_trajectory.trajectory = o3d.io.read_pinhole_camera_trajectory(TRAJECTORY_PATH)
    custom_draw_geometry_with_camera_trajectory.vis = o3d.visualization.Visualizer()

    if os.path.isdir(OUTPUT_DEPTH_MAPS_FOLDER):
        print("Removing old depth maps...")
        for pth in tqdm(glob.glob(os.path.join(OUTPUT_DEPTH_MAPS_FOLDER,f"*.{EXTENSION}"))):
            os.remove(pth)
    else:
        os.makedirs(OUTPUT_DEPTH_MAPS_FOLDER)

    def move_forward(vis):
        ctr = vis.get_view_control()
        glb = custom_draw_geometry_with_camera_trajectory
        if glb.index >= 0:
            depth = np.array(vis.capture_depth_float_buffer(True))
            depth[depth < MINIMUM_DEPTH_VALUE] = 0.0
            depth[depth > MAXIMUM_DEPTH_VALUE] = 0.0
            f_name = os.path.join(OUTPUT_DEPTH_MAPS_FOLDER,"{:06d}_d".format(glb.index) + f".{EXTENSION}")
            res = cv2.imwrite(f_name,depth.astype(np.float32))
            assert res
        glb.index = glb.index + 1

        if glb.index < len(glb.trajectory.parameters):
            ctr.convert_from_pinhole_camera_parameters(
                glb.trajectory.parameters[glb.index]
            )
        else:
            custom_draw_geometry_with_camera_trajectory.vis.\
                    register_animation_callback(None)
        return False

    vis = custom_draw_geometry_with_camera_trajectory.vis
    vis.create_window(width = width, height = height)
    vis.add_geometry(pcd)
    vis.register_animation_callback(move_forward)
    print("Running...")
    vis.run()
    vis.destroy_window()
</code>```
```<code>custom_draw_geometry_with_camera_trajectory(mesh)
</code>```

Create a video for a visual check

```<code>def create_video(paths: List[str], output_path: str, fps: int = 24):
    # paths should be already sorted.
    assert "." in output_path and output_path.split(".")[-1] == "mp4"
    shape = cv2.imread(paths[0], cv2.IMREAD_UNCHANGED).shape
    if len(shape) == 3:
        height, width, channels = shape
    elif len(shape) == 2:
        height, width = shape
        channels = 1
    else:
        raise ValueError("Wrong shape")
    # choose codec according to format needed
    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
    video = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
    for path in tqdm(paths):
        img = cv2.imread(path,cv2.IMREAD_UNCHANGED)/SCALING_FACTOR
        img = img / MAXIMUM_DEPTH_VALUE
        img = img.reshape(HEIGHT,WIDTH,1)*255
        img = img.astype(np.uint8)
        if channels==1:
            img  = cv2.cvtColor(img,cv2.COLOR_GRAY2RGB)
        video.write(img)
    video.release()
</code>```
```<code>paths = sorted(glob.glob(os.path.join(OUTPUT_DEPTH_MAPS_FOLDER,f"*.{EXTENSION}")))
create_video(paths,OUTPUT_VIDEO_PATH,FPS)
</code>```

Create TSDF Volume and extract mesh

```<code># Retrieve GT poses
with open(TRAJECTORY_PATH) as f:
    gt_json = json.load(f)
poses_gt = []
for param in tqdm(gt_json["parameters"]):
    p = np.array(param["extrinsic"]).reshape((4,4)).T
    poses_gt.append(p)
print(f"Retrieved {len(poses_gt)} poses for {TARGET_NAME}")

# Initialize TSDF Volume
VOLUME_SIZE = 0.5

N_VOXELS_PER_SIDE = 1440
SDF_TRUNC = 3 * VOLUME_SIZE / N_VOXELS_PER_SIDE

volume = o3d.pipelines.integration.ScalableTSDFVolume(
    voxel_length= VOLUME_SIZE / N_VOXELS_PER_SIDE,
    sdf_trunc=SDF_TRUNC,
    color_type=o3d.pipelines.integration.TSDFVolumeColorType.RGB8
)

n = len(poses_gt)
assert len(depth_map_paths) == n

for i in tqdm(range(n)):

    path = depth_map_paths[i]
    depth = cv2.imread(path,cv2.IMREAD_UNCHANGED)
    pose = poses_gt[i]

    color = np.zeros((depth.shape[0], depth.shape[1], 3)).astype(np.uint8)
    color[depth > 0.0 ] = 100

    rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth(
            o3d.geometry.Image(color),
            o3d.geometry.Image(depth),
            depth_trunc=1.0,
            convert_rgb_to_intensity=False,
            depth_scale = 1.0
        )

    if USE_GT_POSES:
        extr = pose
    else:
        extr = np.linalg.inv(pose)

    volume.integrate(
        rgbd,
        INTRINSICS, # o3d.camera.PinholeCameraIntrinsic(o3d.camera.PinholeCameraIntrinsicParameters.PrimeSenseDefault),
        extr,
    )
    old_depth = depth
</code>```
```<code># Extract mesh
output_mesh = volume.extract_triangle_mesh()
output_mesh.compute_vertex_normals()
o3d.io.write_triangle_mesh("output.ply", output_mesh)
</code>```

Body:
I'm trying to test a custom 3D reconstruction pipeline that receives ground truth depth maps as input:

To see the full code you can proceed to the end of the question, now I will just outline my approach without getting into the details.

Suppose I have a mesh

bunny_mesh = o3d.data.BunnyMesh()
mesh = o3d.io.read_triangle_mesh(bunny_mesh.path)

And I extract some poses using the p key while visualizing the mesh with o3d.visualization.draw_geometries([mesh]).

Then I create a trajectory by linearly interpolating subsequent poses.
Then, at each pose I extract the depth information through depth = np.array(vis.capture_depth_float_buffer(True)) and I save it to create a dataset that looks like this:

(this is just a portion of the dataset)

Finally, the code to reconstruct the mesh looks like the following

VOLUME_SIZE = 0.5
N_VOXELS_PER_SIDE = 1440
SDF_TRUNC = 3 * VOLUME_SIZE / N_VOXELS_PER_SIDE # 3

volume = o3d.pipelines.integration.ScalableTSDFVolume(
    voxel_length= VOLUME_SIZE / N_VOXELS_PER_SIDE,
    sdf_trunc=SDF_TRUNC,
    color_type=o3d.pipelines.integration.TSDFVolumeColorType.RGB8
)

for depth,pose in zip(depth_maps, poses):
  color = ... # Create dummy rgb image
  rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth(
              o3d.geometry.Image(color),
              o3d.geometry.Image(depth),
              depth_trunc=1.0,
              convert_rgb_to_intensity=False,
              depth_scale = 1.0
          )
  volume.integrate(
    rgbd,
    intrinsics, # the intrinsics were retrieved from the previously loaded poses
    pose,
  )

And this is what I obtain:

My question is:
How can I obtain an output mesh that is as similar as possible to the original one? Why the poses extracted from the visualizer seem to not work when trying to integrate the TSDF volume?

FULL CODE

Load mesh and create key poses

bunny_mesh = o3d.data.BunnyMesh()
mesh = o3d.io.read_triangle_mesh(bunny_mesh.path)
o3d.visualization.draw_geometries([mesh])
# create poses by pressing 'p' in correspondence of different views of the mesh

Create trajectory from poses

TRAJECTORY_PATH = "path/to/output/trajectory.json"
FPS = 30
NUM_FRAMES_BETWEEN_POSES = FPS * 5

poses = ... # Ordered list of poses paths (obtained with the 'p' key in the visualizer)

fx = 935.3074360871938
fy = 935.3074360871938
cx = 959.5
cy = 539.5
width = 1920
height = 1080
intrinsic = o3d.camera.PinholeCameraIntrinsic(
    width,
    height,
    fx,
    fy,
    cx,
    cy
)

for i in tqdm(range(1, len(poses))):
    pose_a = poses[i-1]
    pose_b = poses[i]
    with open(pose_a) as f_a:
        x = json.load(f_a)
        extrinsic_matrix_a = np.array(x["extrinsic"])
    with open(pose_b) as f_b:
        x = json.load(f_b)
        extrinsic_matrix_b = np.array(x["extrinsic"])

    extrinsic_matrix_list = np.linspace(extrinsic_matrix_a,extrinsic_matrix_b,N_FRAMES_BETWEEN_POSES)

    for j in range(len(extrinsic_matrix_list)):
        p = o3d.camera.PinholeCameraParameters()
        p.intrinsic = intrinsic
        p.extrinsic = np.array(extrinsic_matrix_list[j]).reshape((4,4)).T
        params.append(p)

trajectory.parameters = params

if os.path.isfile(TRAJECTORY_PATH):
    os.remove(TRAJECTORY_PATH)
o3d.io.write_pinhole_camera_trajectory(TRAJECTORY_PATH, trajectory)

print(f"Traejctory saved @ {TRAJECTORY_PATH}")

Create depth maps

EXTENSIONS = "pfm"
OUTPUT_DEPTH_MAPS_FOLDER = "path/to/an/empty/folder/"
MINIMUM_DEPTH_VALUE = 0.0008
MAXIMUM_DEPTH_VALUE = 0.25

def custom_draw_geometry_with_camera_trajectory(pcd):

    custom_draw_geometry_with_camera_trajectory.index = -1
    custom_draw_geometry_with_camera_trajectory.trajectory = o3d.io.read_pinhole_camera_trajectory(TRAJECTORY_PATH)
    custom_draw_geometry_with_camera_trajectory.vis = o3d.visualization.Visualizer()

    if os.path.isdir(OUTPUT_DEPTH_MAPS_FOLDER):
        print("Removing old depth maps...")
        for pth in tqdm(glob.glob(os.path.join(OUTPUT_DEPTH_MAPS_FOLDER,f"*.{EXTENSION}"))):
            os.remove(pth)
    else:
        os.makedirs(OUTPUT_DEPTH_MAPS_FOLDER)

    def move_forward(vis):
        ctr = vis.get_view_control()
        glb = custom_draw_geometry_with_camera_trajectory
        if glb.index >= 0:
            depth = np.array(vis.capture_depth_float_buffer(True))
            depth[depth < MINIMUM_DEPTH_VALUE] = 0.0
            depth[depth > MAXIMUM_DEPTH_VALUE] = 0.0
            f_name = os.path.join(OUTPUT_DEPTH_MAPS_FOLDER,"{:06d}_d".format(glb.index) + f".{EXTENSION}")
            res = cv2.imwrite(f_name,depth.astype(np.float32))
            assert res
        glb.index = glb.index + 1

        if glb.index < len(glb.trajectory.parameters):
            ctr.convert_from_pinhole_camera_parameters(
                glb.trajectory.parameters[glb.index]
            )
        else:
            custom_draw_geometry_with_camera_trajectory.vis.\
                    register_animation_callback(None)
        return False

    vis = custom_draw_geometry_with_camera_trajectory.vis
    vis.create_window(width = width, height = height)
    vis.add_geometry(pcd)
    vis.register_animation_callback(move_forward)
    print("Running...")
    vis.run()
    vis.destroy_window()

custom_draw_geometry_with_camera_trajectory(mesh)

Create a video for a visual check

def create_video(paths: List[str], output_path: str, fps: int = 24):
    # paths should be already sorted.
    assert "." in output_path and output_path.split(".")[-1] == "mp4"
    shape = cv2.imread(paths[0], cv2.IMREAD_UNCHANGED).shape
    if len(shape) == 3:
        height, width, channels = shape
    elif len(shape) == 2:
        height, width = shape
        channels = 1
    else:
        raise ValueError("Wrong shape")
    # choose codec according to format needed
    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
    video = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
    for path in tqdm(paths):
        img = cv2.imread(path,cv2.IMREAD_UNCHANGED)/SCALING_FACTOR
        img = img / MAXIMUM_DEPTH_VALUE
        img = img.reshape(HEIGHT,WIDTH,1)*255
        img = img.astype(np.uint8)
        if channels==1:
            img  = cv2.cvtColor(img,cv2.COLOR_GRAY2RGB)
        video.write(img)
    video.release()

paths = sorted(glob.glob(os.path.join(OUTPUT_DEPTH_MAPS_FOLDER,f"*.{EXTENSION}")))
create_video(paths,OUTPUT_VIDEO_PATH,FPS)

Create TSDF Volume and extract mesh

# Retrieve GT poses
with open(TRAJECTORY_PATH) as f:
    gt_json = json.load(f)
poses_gt = []
for param in tqdm(gt_json["parameters"]):
    p = np.array(param["extrinsic"]).reshape((4,4)).T
    poses_gt.append(p)
print(f"Retrieved {len(poses_gt)} poses for {TARGET_NAME}")

# Initialize TSDF Volume
VOLUME_SIZE = 0.5

N_VOXELS_PER_SIDE = 1440
SDF_TRUNC = 3 * VOLUME_SIZE / N_VOXELS_PER_SIDE

volume = o3d.pipelines.integration.ScalableTSDFVolume(
    voxel_length= VOLUME_SIZE / N_VOXELS_PER_SIDE,
    sdf_trunc=SDF_TRUNC,
    color_type=o3d.pipelines.integration.TSDFVolumeColorType.RGB8
)

n = len(poses_gt)
assert len(depth_map_paths) == n

for i in tqdm(range(n)):

    path = depth_map_paths[i]
    depth = cv2.imread(path,cv2.IMREAD_UNCHANGED)
    pose = poses_gt[i]

    color = np.zeros((depth.shape[0], depth.shape[1], 3)).astype(np.uint8)
    color[depth > 0.0 ] = 100

    rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth(
            o3d.geometry.Image(color),
            o3d.geometry.Image(depth),
            depth_trunc=1.0,
            convert_rgb_to_intensity=False,
            depth_scale = 1.0
        )

    if USE_GT_POSES:
        extr = pose
    else:
        extr = np.linalg.inv(pose)

    volume.integrate(
        rgbd,
        INTRINSICS, # o3d.camera.PinholeCameraIntrinsic(o3d.camera.PinholeCameraIntrinsicParameters.PrimeSenseDefault),
        extr,
    )
    old_depth = depth

# Extract mesh
output_mesh = volume.extract_triangle_mesh()
output_mesh.compute_vertex_normals()
o3d.io.write_triangle_mesh("output.ply", output_mesh)


问:
Format data data coming from MYSQL
```<code>const Fornecedor = require("../model/Fornecedor")
const Aluguel = require("../model/Aluguel")

router.get('/admin/rent',(req,res)=\>{
Aluguel.findAll().then((alugueis)=\>{
res.render("aluguel/index", {alugueis: alugueis})
</code>```

Como faço para formatar a data, para que apareça: DD/MM/YYYY

Title: Format data data coming from MYSQL

Body:
const Fornecedor = require("../model/Fornecedor")
const Aluguel = require("../model/Aluguel")

router.get('/admin/rent',(req,res)=\>{
Aluguel.findAll().then((alugueis)=\>{
res.render("aluguel/index", {alugueis: alugueis})

Como faço para formatar a data, para que apareça: DD/MM/YYYY


问:
VSCode: How to open terminal in editor area to the bottom instead of the side?
In VSCode, I would like to get the following layout with the Code editor on top and the Terminals on the bottom as tabs.

When I press Cmd+Shift+T, I would like to get a new terminal tab opening under (and not aside) the active editor. And then I'd like to press Cmd+T to open a new terminal as a tab.

I did the following bindings.

[
    // Terminal
    {
        "key": "cmd+t",
        "command": "-workbench.action.showAllSymbols"
    },
    {
        "key": "shift+cmd+t",
        "command": "-workbench.action.reopenClosedEditor"
    },
    {
        "key": "shift+cmd+t",
        "command": "workbench.action.createTerminalEditorSide"
    },
    {
        "key": "cmd+t",
        "command": "workbench.action.createTerminalEditor"
    },

]
```

It almost works: Shift+T opens a new Terminal tab editor, and Shift+Cmd+T opens a new terminal

But:

Shift+Cmd+T opens a terminal tab at the right instead of bottom of the active editor

Shift+T systematically opens a tab in the upper tabs list, even if the active editor is a terminal

Please note I know about the Terminals tabs in Panels, but the nesting is too deep to me and I prefer dealing with tabs.

Body:
In VSCode, I would like to get the following layout with the Code editor on top and the Terminals on the bottom as tabs.

When I press Cmd+Shift+T, I would like to get a new terminal tab opening under (and not aside) the active editor. And then I'd like to press Cmd+T to open a new terminal as a tab.

I did the following bindings.

[
    // Terminal
    {
        "key": "cmd+t",
        "command": "-workbench.action.showAllSymbols"
    },
    {
        "key": "shift+cmd+t",
        "command": "-workbench.action.reopenClosedEditor"
    },
    {
        "key": "shift+cmd+t",
        "command": "workbench.action.createTerminalEditorSide"
    },
    {
        "key": "cmd+t",
        "command": "workbench.action.createTerminalEditor"
    },

]

It almost works: Shift+T opens a new Terminal tab editor, and Shift+Cmd+T opens a new terminal

But:

Shift+Cmd+T opens a terminal tab at the right instead of bottom of the active editor

Shift+T systematically opens a tab in the upper tabs list, even if the active editor is a terminal

Please note I know about the Terminals tabs in Panels, but the nesting is too deep to me and I prefer dealing with tabs.


问:
How to debug memory write performance on linux?
I have two almost identical processes communicating through shared memory. Every time a process receives message from the other one, it increments a 8 byte usize integer in its own memory mapped file. (Each process have its own file, they don't share it)

For some strange reason, one process is able to perfom the increment operation in 16ns, while the other one needs something like 140ns.

I have no idea how to profile this.

I have a following piece of (rust) code:

```<code>let t1 = Instant::now();
let offset_ptr = self.index.as_mut_ptr::<AtomicUsize>();
(*offset_ptr).store(self.topic.offset, Ordering::Relaxed);
let t2 = Instant::now();
</code>```

And I measure difference between t2 and t1 with following results:

Process 1

```<code>p50: 15.00 ns, p90: 16.00 ns, p99: 94.00 ns, p99.9: 142.00 ns, p99.99: 422.00 ns, p99.999: 504.00 ns
max: 11.97 μs, avg: 16.00 ns
</code>```

Process 2

```<code>p50: 114.00 ns, p90: 320.00 ns, p99: 664.00 ns, p99.9: 1.07 μs, p99.99: 1.45 μs, p99.999: 4.45 μs
max: 10.69 μs, avg: 137.00 ns
</code>```

Any idea what might be causing such a huge discrepancy in a simple memory write access? And how to debug it?

Body:
I have two almost identical processes communicating through shared memory. Every time a process receives message from the other one, it increments a 8 byte usize integer in its own memory mapped file. (Each process have its own file, they don't share it)

For some strange reason, one process is able to perfom the increment operation in 16ns, while the other one needs something like 140ns.

I have no idea how to profile this.

I have a following piece of (rust) code:

let t1 = Instant::now();
let offset_ptr = self.index.as_mut_ptr::<AtomicUsize>();
(*offset_ptr).store(self.topic.offset, Ordering::Relaxed);
let t2 = Instant::now();

And I measure difference between t2 and t1 with following results:

Process 1

p50: 15.00 ns, p90: 16.00 ns, p99: 94.00 ns, p99.9: 142.00 ns, p99.99: 422.00 ns, p99.999: 504.00 ns
max: 11.97 μs, avg: 16.00 ns

Process 2

p50: 114.00 ns, p90: 320.00 ns, p99: 664.00 ns, p99.9: 1.07 μs, p99.99: 1.45 μs, p99.999: 4.45 μs
max: 10.69 μs, avg: 137.00 ns

Any idea what might be causing such a huge discrepancy in a simple memory write access? And how to debug it?


问:
How to embed the SAPUI5 Graph component into my ui5 typescript/npm project?
How would I properly integrate the graph component of SAPUI5 into my typescript application to make use of the graph type? I guess I need at least the Dijkstra, Tooltip and Graph types. The graph component should be placed in a xml view.

One specific problem is the transpile error

Cannot find module 'sap/suite/ui/commons/networkgraph/Graph' or its corresponding type declarations.ts(2307)

on the following line:

```<code>import Graph from "sap/suite/ui/commons/networkgraph/Graph";
</code>```

Using this import it seems to render but the transpiler shows the error. Removing this line in the controller the view does not render properly.

In the package.json there is a dependency to "@sap/graph-toolkit": "^3.0.8".

Has anyone used the network graph library with typescript and npm before?
I only used OPENUI5 components so far.

Body:
How would I properly integrate the graph component of SAPUI5 into my typescript application to make use of the graph type? I guess I need at least the Dijkstra, Tooltip and Graph types. The graph component should be placed in a xml view.

One specific problem is the transpile error

Cannot find module 'sap/suite/ui/commons/networkgraph/Graph' or its corresponding type declarations.ts(2307)

on the following line:

import Graph from "sap/suite/ui/commons/networkgraph/Graph";

Using this import it seems to render but the transpiler shows the error. Removing this line in the controller the view does not render properly.

In the package.json there is a dependency to "@sap/graph-toolkit": "^3.0.8".

Has anyone used the network graph library with typescript and npm before?
I only used OPENUI5 components so far.


问:
GroupedList component in Fluent UI collapses after I click header of the component
I am using groupedList on Fluent UI, this list includes some children items as on the documentation :
https://developer.microsoft.com/en-us/fluentui#/controls/web/groupedlist

When I click a title on groupHeader, I need to update selected item's id so that I can show children items on detailsList.

The problem is, when I click groupedHeader, all items on groupedList component are collapse. But when I remove setSelectedItemId(group.key), I am not facing with this problem.

Is there any way to get rid of these collapses?

```<code>const groupProps: IGroupRenderProps = {
    onRenderHeader: (props?: IGroupHeaderProps): JSX.Element => {
      return (
        <GroupHeader
          {...props}
          //https://github.com/microsoft/fluentui/issues/6676
          styles={{ headerCount: { display: 'none' } }}
          onGroupHeaderClick={(group) => {
            setSelectedItemId(group.key); // Having the problem here.
          }}
          onToggleCollapse={(group) => {
            if (props?.onToggleCollapse) {
              props?.onToggleCollapse(group);
            }
          }}
        />
      );
    },
  };

return (
    <GroupedList
      items={items}
      onRenderCell={() => null}
      selectionMode={SelectionMode.none}
      groups={groups}
      groupProps={groupProps}
    />
  );
</code>```

Body:
I am using groupedList on Fluent UI, this list includes some children items as on the documentation :
https://developer.microsoft.com/en-us/fluentui#/controls/web/groupedlist

When I click a title on groupHeader, I need to update selected item's id so that I can show children items on detailsList.

The problem is, when I click groupedHeader, all items on groupedList component are collapse. But when I remove setSelectedItemId(group.key), I am not facing with this problem.

Is there any way to get rid of these collapses?

const groupProps: IGroupRenderProps = {
    onRenderHeader: (props?: IGroupHeaderProps): JSX.Element => {
      return (
        <GroupHeader
          {...props}
          //https://github.com/microsoft/fluentui/issues/6676
          styles={{ headerCount: { display: 'none' } }}
          onGroupHeaderClick={(group) => {
            setSelectedItemId(group.key); // Having the problem here.
          }}
          onToggleCollapse={(group) => {
            if (props?.onToggleCollapse) {
              props?.onToggleCollapse(group);
            }
          }}
        />
      );
    },
  };

return (
    <GroupedList
      items={items}
      onRenderCell={() => null}
      selectionMode={SelectionMode.none}
      groups={groups}
      groupProps={groupProps}
    />
  );


问:
How to sort likert heatmap (likert package) by descending order one answer
I have problems with the solution posted by useRj on Nov 15, 2017 at 16:59

"Likert package does not allow to do such manipulation. Heatmap is ALWAYS ordered by alphabetically sorted text. So I suggest a workaround by forcing the text to be previously sorted by the column you think the most likely to be like bar chart sorting. A bit nasty but works:

```<code>library(magrittr)
library(dplyr)

# Get the results data frame out of the list
# and sort by last column ("Strongly agree")
# padding with zeros to avoid alphabetical ordering

l24.results <- l24.reverse$results %>%
      dplyr::arrange(desc(`Strongly agree`)) %>%
      dplyr::mutate(Item = paste(str_pad(row_number(),2, pad = "0"), Item, sep = ' '))

# create a likert object again from the summary feature

mylikert <- likert(summary = l24.results)

# plot again

plot(mylikert, type = "heat")
</code>```

When I try with my own dataset, I have the following error:

```<code>Error in data.frame(Item = results[, 1], low = low, neutral = neutral,  :
  object 'neutral' not found
</code>```

this is the plot without sorting:

thanks

Body:
I have problems with the solution posted by useRj on Nov 15, 2017 at 16:59

"Likert package does not allow to do such manipulation. Heatmap is ALWAYS ordered by alphabetically sorted text. So I suggest a workaround by forcing the text to be previously sorted by the column you think the most likely to be like bar chart sorting. A bit nasty but works:

library(magrittr)
library(dplyr)

# Get the results data frame out of the list
# and sort by last column ("Strongly agree")
# padding with zeros to avoid alphabetical ordering

l24.results <- l24.reverse$results %>%
      dplyr::arrange(desc(`Strongly agree`)) %>%
      dplyr::mutate(Item = paste(str_pad(row_number(),2, pad = "0"), Item, sep = ' '))

# create a likert object again from the summary feature

mylikert <- likert(summary = l24.results)

# plot again

plot(mylikert, type = "heat")

When I try with my own dataset, I have the following error:

Error in data.frame(Item = results[, 1], low = low, neutral = neutral,  :
  object 'neutral' not found

this is the plot without sorting:

thanks