问:
Property derived from ICollection<T> will be persistent when using it in dependency injection? Notifications not being published
So I am very new to MediatR and I decided to handle business errors w/ notification pattern instead of throwing domain exceptions. But for some reason my notifications are not being published because when I force an error testing in swagger it's like the notification wasn't published. I'm using the following abstractions and implementations:

public interface IDomainNotificationHandler : INotificationHandler<DomainNotification>
{
    public bool HasNotifications();
    public DomainNotification? GetFirstPublishedNotification();
}

public class DomainNotificationHandler : IDomainNotificationHandler
{
    private List<DomainNotification> _notifications;
    public IReadOnlyCollection<DomainNotification> Notifications => _notifications;

    public DomainNotificationHandler()
    {
        _notifications = new();
    }

    public async Task Handle(DomainNotification notification, CancellationToken cancellationToken)
    {
        _notifications.Add(notification);
        await Task.CompletedTask;
    }

    public bool HasNotifications() =>
        _notifications.Any();

    public DomainNotification? GetFirstPublishedNotification() =>
        _notifications.FirstOrDefault();
}
```
<p>Using in controller:</p>
```[ApiController]
[Route("/[controller]")]
public class ApiControllerBase : ControllerBase
{
    private ISender _sender;
    public ISender Sender => _sender;

    private IDomainNotificationHandler _domainNotificationHandler;
    public IDomainNotificationHandler DomainNotificationHandler => _domainNotificationHandler;

    public ApiControllerBase(ISender sender, IDomainNotificationHandler domainNotificationHandler)
    {
        _sender = sender;
        _domainNotificationHandler = domainNotificationHandler;
    }
}
```

What am I missing? Can I use a derived type from ICollection<T> and expect that everything will work just fine?

Body:
So I am very new to MediatR and I decided to handle business errors w/ notification pattern instead of throwing domain exceptions. But for some reason my notifications are not being published because when I force an error testing in swagger it's like the notification wasn't published. I'm using the following abstractions and implementations:

public interface IDomainNotificationHandler : INotificationHandler<DomainNotification>
{
    public bool HasNotifications();
    public DomainNotification? GetFirstPublishedNotification();
}

public class DomainNotificationHandler : IDomainNotificationHandler
{
    private List<DomainNotification> _notifications;
    public IReadOnlyCollection<DomainNotification> Notifications => _notifications;

    public DomainNotificationHandler()
    {
        _notifications = new();
    }

    public async Task Handle(DomainNotification notification, CancellationToken cancellationToken)
    {
        _notifications.Add(notification);
        await Task.CompletedTask;
    }

    public bool HasNotifications() =>
        _notifications.Any();

    public DomainNotification? GetFirstPublishedNotification() =>
        _notifications.FirstOrDefault();
}

Using in controller:

[ApiController]
[Route("/[controller]")]
public class ApiControllerBase : ControllerBase
{
    private ISender _sender;
    public ISender Sender => _sender;

    private IDomainNotificationHandler _domainNotificationHandler;
    public IDomainNotificationHandler DomainNotificationHandler => _domainNotificationHandler;

    public ApiControllerBase(ISender sender, IDomainNotificationHandler domainNotificationHandler)
    {
        _sender = sender;
        _domainNotificationHandler = domainNotificationHandler;
    }
}

What am I missing? Can I use a derived type from ICollection<T> and expect that everything will work just fine?


来源: stackexchange

问:
How to use pytest with a database
I hope someone can suggest what might be wrong here. I'm new to pytest and have included the code for a single test below.

```<code>res = await createOrUpdateEvent(liveClient, authToken, contentType, createValue, createComment, security)
resBody = res.json()

assert res.status_code == 200
assert len(resBody["message"]) > 0

cursor = dbConn.cursor(dictionary=True)

query = """
    SELECT *
    FROM
    events
    WHERE matrix_id = %s
    AND value = %s
"""
cursor.execute(query, (matrixId, createValue))
rows = cursor.fetchall()

assert len(rows) == 1

res = await createOrUpdateEvent(liveClient, authToken, contentType, updateValue, updateComment, security)
resBody = res.json()

assert res.status_code == 200
assert len(resBody["message"]) > 0

query = """
    SELECT *
    FROM
    events
    WHERE matrix_id = %s
    AND value = %s
"""
cursor.execute(query, (matrixId, updateValue))
rows = cursor.fetchall()

assert len(rows) == 1
</code>```

This is supposed to do the following.

call createOrUpdateEvent with one of the parameters set to 'createValue'

the createOrUpdateEvent function will insert a row in a db table with the value column set to 1 ( the value of createValue ).

I then check the row has been correctly inserted (matrixId is a global and is set correctly) using the createValue to check. This assertion passes.

I then call createOrUpdateEvent again but with the value now set to 'updateValue' which is 0.

I then do the same test this time looking for the updateValue instead of createValue. Note that the way this works is that the original inserted row with 'createValue' will be replaced with a new row with the 'updateValue'. There should only be one row at any time with the same matrixId.

Whatever I try the second test always fails. ( len 0 != 1 ). If I change the second select to use createValue it passes. When I check the db the correctly updated row is present in the db so the test should pass.

Any ideas welcome thanks...

ContentLicense: CC BY-SA 4.0

Title: How to use pytest with a database

Body:
I hope someone can suggest what might be wrong here. I'm new to pytest and have included the code for a single test below.

res = await createOrUpdateEvent(liveClient, authToken, contentType, createValue, createComment, security)
resBody = res.json()

assert res.status_code == 200
assert len(resBody["message"]) > 0

cursor = dbConn.cursor(dictionary=True)

query = """
    SELECT *
    FROM
    events
    WHERE matrix_id = %s
    AND value = %s
"""
cursor.execute(query, (matrixId, createValue))
rows = cursor.fetchall()

assert len(rows) == 1

res = await createOrUpdateEvent(liveClient, authToken, contentType, updateValue, updateComment, security)
resBody = res.json()

assert res.status_code == 200
assert len(resBody["message"]) > 0

query = """
    SELECT *
    FROM
    events
    WHERE matrix_id = %s
    AND value = %s
"""
cursor.execute(query, (matrixId, updateValue))
rows = cursor.fetchall()

assert len(rows) == 1

This is supposed to do the following.

call createOrUpdateEvent with one of the parameters set to 'createValue'

the createOrUpdateEvent function will insert a row in a db table with the value column set to 1 ( the value of createValue ).

I then check the row has been correctly inserted (matrixId is a global and is set correctly) using the createValue to check. This assertion passes.

I then call createOrUpdateEvent again but with the value now set to 'updateValue' which is 0.

I then do the same test this time looking for the updateValue instead of createValue. Note that the way this works is that the original inserted row with 'createValue' will be replaced with a new row with the 'updateValue'. There should only be one row at any time with the same matrixId.

Whatever I try the second test always fails. ( len 0 != 1 ). If I change the second select to use createValue it passes. When I check the db the correctly updated row is present in the db so the test should pass.

Any ideas welcome thanks...


问:
Payload undefined in Nuxt.js full static generated page
I'm building a website with Nuxt.js 2 with static site generation (npm run generate).

I receive the data in my asyncData function and use it to generate the page.

nuxt.config.js

```<code> generate: {
    routes(){
      console.log("generate")
      let recettes = axios({
        url: process.env.GRAPHQL_ENDPOINT,
        method: "post",
        data: {
          query: queries.generateRecipes(),
        }
      }).then((result) => {
        return result.data.data.recettes.map(recette => {
          console.log(recette)
          return {
            route: `Recette/${recette.slug}/${recette.recipeId}`,
            payload: recette
          }
        })
      });

      return Promise.all([recettes]).then((values) => {
        console.log(values);
        return values[0];
      });
    },
    fallback: '404.html'
  }
</code>```

Recette\_slug\_id.vue

```<code>async asyncData({ params, error, payload, $axios, $config: { graphqlEndpoint } }){
        console.log("params",params)
        if (payload){
            console.log("payload",payload.name);
            let recipe = payload;
            if(recipe.compositions){
                recipe.compositions.sort((a,b) => b.quantity - a.quantity);
            }
            return { recipe: recipe, servings:recipe.yield };
        }
        else {
            if(params.id){
                console.log("fetchRecipe", params.id);
                const res = await $axios({
                        url: graphqlEndpoint,
                        method: "post",
                        data: {
                        query: queries.getRecipeDetails(params.id),
                        },
                    })
                if(res.data.data && res.data.data.recettes[0]){
                    let recipe = res.data.data && res.data.data.recettes[0];
                    if(recipe.compositions){
                        recipe.compositions.sort((a,b) => b.quantity - a.quantity);
                    }
                    return { recipe: recipe, servings:recipe.yield};
                }
                else{
                    error({ statusCode: 404, message: 'Page not found' })
                }
            }

            error({ statusCode: 404, message: 'Page not found' })
        }
    }

</code>```

It is correctly generated and the payload.js file too.
The payload.js is loaded by the browser when the page is loaded.

However, when my object is called client-side it fails because it's undefined. I get the following error: TypeError: this.recipe is undefined

I can't figure out why is undefined. In the created() hook I made a console log of this._data and indeed, my recipe object isn't there

```<code>created(){
        console.log(this._data);
        console.log(this.dummy);
        console.log(this.recipe);
    }
</code>```

My problem is similar to this one: Nuxt js full static dynamic page, payload undefined but no solution is provided

Source code is here: https://github.com/nbwns/fristouille

Body:
I'm building a website with Nuxt.js 2 with static site generation (npm run generate).

I receive the data in my asyncData function and use it to generate the page.

nuxt.config.js

 generate: {
    routes(){
      console.log("generate")
      let recettes = axios({
        url: process.env.GRAPHQL_ENDPOINT,
        method: "post",
        data: {
          query: queries.generateRecipes(),
        }
      }).then((result) => {
        return result.data.data.recettes.map(recette => {
          console.log(recette)
          return {
            route: `Recette/${recette.slug}/${recette.recipeId}`,
            payload: recette
          }
        })
      });

      return Promise.all([recettes]).then((values) => {
        console.log(values);
        return values[0];
      });
    },
    fallback: '404.html'
  }

Recette\_slug\_id.vue

async asyncData({ params, error, payload, $axios, $config: { graphqlEndpoint } }){
        console.log("params",params)
        if (payload){
            console.log("payload",payload.name);
            let recipe = payload;
            if(recipe.compositions){
                recipe.compositions.sort((a,b) => b.quantity - a.quantity);
            }
            return { recipe: recipe, servings:recipe.yield };
        }
        else {
            if(params.id){
                console.log("fetchRecipe", params.id);
                const res = await $axios({
                        url: graphqlEndpoint,
                        method: "post",
                        data: {
                        query: queries.getRecipeDetails(params.id),
                        },
                    })
                if(res.data.data && res.data.data.recettes[0]){
                    let recipe = res.data.data && res.data.data.recettes[0];
                    if(recipe.compositions){
                        recipe.compositions.sort((a,b) => b.quantity - a.quantity);
                    }
                    return { recipe: recipe, servings:recipe.yield};
                }
                else{
                    error({ statusCode: 404, message: 'Page not found' })
                }
            }

            error({ statusCode: 404, message: 'Page not found' })
        }
    }

It is correctly generated and the payload.js file too.
The payload.js is loaded by the browser when the page is loaded.

However, when my object is called client-side it fails because it's undefined. I get the following error: TypeError: this.recipe is undefined

I can't figure out why is undefined. In the created() hook I made a console log of this._data and indeed, my recipe object isn't there

created(){
        console.log(this._data);
        console.log(this.dummy);
        console.log(this.recipe);
    }

My problem is similar to this one: Nuxt js full static dynamic page, payload undefined but no solution is provided

Source code is here: https://github.com/nbwns/fristouille


问:
How to batch execute .Rmd files from the command line and save the output to the same .Rmd files
I have several dozens of .Rmd files that I want to execute programmatically from the CLI and save the output to the same files. Imagine that these are template analysis files that I want to populate with the various outputs and share these templates then with others in this executed state as runnable .Rmd files.

By execute I mean Run All Cells like I can do in RStudio.

How can I do that?

As far as I can see knitting doesn't solve my problem because .Rmd doesn't seem to be a viable output format. Rendering from the CLI just renders the file but doesn't save the outputs to the file itself.

I am working on macOs and have R available in a conda enviroment.

Thanks in advance for your help or any pointers in the right direction!

Example

A very much simplified version of my template looks like this:

```<code>---
title: "Sample doc"
output: html_document
date: "2023-01-02"
---

# Data analysis template for dataset 001

## Load packages
```{r}
library(tidyverse)
library(skimr)
```

## Load data
```{r}
# the dataset will change from template to template
df <- read.csv2("sample_dataset_001.csv")
```

## Analyze data
```{r}
# recipients should see output of e.g. skim, ggplot, summaries etc.
skim(df)
```

## Recipients will code from here
```{r}
# recipients will continue with their own code here
print()
```
</code>```

I generate these templates programmatically and insert metadata about the datasets and the respective data set links into these files.

I then want to execute these, so that recipients can see immediately the outputs, without executing the .Rmd files themselves.

Then they should be able to open the .Rmd files in RStudio and continue to work on the analysis.

Body:
I have several dozens of .Rmd files that I want to execute programmatically from the CLI and save the output to the same files. Imagine that these are template analysis files that I want to populate with the various outputs and share these templates then with others in this executed state as runnable .Rmd files.

By execute I mean Run All Cells like I can do in RStudio.

How can I do that?

As far as I can see knitting doesn't solve my problem because .Rmd doesn't seem to be a viable output format. Rendering from the CLI just renders the file but doesn't save the outputs to the file itself.

I am working on macOs and have R available in a conda enviroment.

Thanks in advance for your help or any pointers in the right direction!

Example

A very much simplified version of my template looks like this:

---
title: "Sample doc"
output: html_document
date: "2023-01-02"
---

# Data analysis template for dataset 001

## Load packages
```{r}
library(tidyverse)
library(skimr)
```

## Load data
```{r}
# the dataset will change from template to template
df <- read.csv2("sample_dataset_001.csv")
```

## Analyze data
```{r}
# recipients should see output of e.g. skim, ggplot, summaries etc.
skim(df)
```

## Recipients will code from here
```{r}
# recipients will continue with their own code here
print()
```

I generate these templates programmatically and insert metadata about the datasets and the respective data set links into these files.

I then want to execute these, so that recipients can see immediately the outputs, without executing the .Rmd files themselves.

Then they should be able to open the .Rmd files in RStudio and continue to work on the analysis.


问:
React setState counter function is acting strange
I'm having trouble implementing a simple counter update in react. I have a quantity state to update my shopify cart. There is an increment and decrement function. In the beginning, the quantity is set to 0. When the add button is clicked, it triggers increment function where the quantity variable updates correctly i.e shows 1. But when I console log it, it shows the initial 0 value, and also causes an error in the backend where 0 item gets added to the cart. However, if I add 2 or more items to the quantity and then click 'buy now' it updates the cart with correct identity and increment or decrement functions as normal. The issue just happens in the very first increment from 0 to 1. Why won't the console log show the updated value and why won't set state actually change the quantity in the backend? How do I go about solving this?

here is some of my code :
Component -

```<code>const Subblueminal = () => {
const { addItemToCheckout, updateCheckout, checkout } = useContext(Context);
const [quantity, setQuantity] = useState(0)

   function Decrement() {
      setQuantity(prevQuantity => prevQuantity - 1)
      if (checkout.lineItems.length > 0) {
         updateCheckout(checkout.lineItems[0].id, quantity)
      }
      console.log('sub: ' + quantity)
      }

   function Increment() {
      setQuantity(prevQuantity => prevQuantity + 1)
      addItemToCheckout(product.variants[0].id, quantity)
      setError(false)
      console.log('add: ' + quantity)
   }

  return (
   <div className="action">
            <div className="quantity-select">
               <button onClick={Decrement} className='sub'>-</button>
               <p className='quantity'>{quantity}</p>
               <button onClick={Increment} className='add'>+</button>
            </div>
            <button onClick={() => {
               if (quantity > 0) {
                  updateCheckout(checkout.lineItems[0].id, quantity)
                  openSizeUpdate()
               }
            }} className="buy">(BUY NOW)</button>
         </div>
)

}
</code>```

Context -

```<code> addItemToCheckout = async (variantID, quantity) => {
      const itemToAdd = [{
         variantId: variantID,
         quantity: parseInt(quantity)
      }]
      const checkout = await client.checkout.addLineItems(this.state.checkout.id, itemToAdd)
      this.setState({ checkout: checkout })
      console.log(checkout.lineItems);
   }

   updateCheckout = async (variantID, quantity) => {
      const lineItemsToUpdate = [
         {id: variantID, quantity: quantity}
       ];
      const checkout = await client.checkout.updateLineItems(this.state.checkout.id, lineItemsToUpdate)
      this.setState({ checkout: checkout })
      // console.log(checkout.lineItems);
   }
</code>```

Body:
I'm having trouble implementing a simple counter update in react. I have a quantity state to update my shopify cart. There is an increment and decrement function. In the beginning, the quantity is set to 0. When the add button is clicked, it triggers increment function where the quantity variable updates correctly i.e shows 1. But when I console log it, it shows the initial 0 value, and also causes an error in the backend where 0 item gets added to the cart. However, if I add 2 or more items to the quantity and then click 'buy now' it updates the cart with correct identity and increment or decrement functions as normal. The issue just happens in the very first increment from 0 to 1. Why won't the console log show the updated value and why won't set state actually change the quantity in the backend? How do I go about solving this?

here is some of my code :
Component -

const Subblueminal = () => {
const { addItemToCheckout, updateCheckout, checkout } = useContext(Context);
const [quantity, setQuantity] = useState(0)

   function Decrement() {
      setQuantity(prevQuantity => prevQuantity - 1)
      if (checkout.lineItems.length > 0) {
         updateCheckout(checkout.lineItems[0].id, quantity)
      }
      console.log('sub: ' + quantity)
      }

   function Increment() {
      setQuantity(prevQuantity => prevQuantity + 1)
      addItemToCheckout(product.variants[0].id, quantity)
      setError(false)
      console.log('add: ' + quantity)
   }

  return (

               <button onClick={Decrement} className='sub'>-</button>

{quantity}

               <button onClick={Increment} className='add'>+</button>

            <button onClick={() => {
               if (quantity > 0) {
                  updateCheckout(checkout.lineItems[0].id, quantity)
                  openSizeUpdate()
               }
            }} className="buy">(BUY NOW)</button>

)

}

Context -

 addItemToCheckout = async (variantID, quantity) => {
      const itemToAdd = [{
         variantId: variantID,
         quantity: parseInt(quantity)
      }]
      const checkout = await client.checkout.addLineItems(this.state.checkout.id, itemToAdd)
      this.setState({ checkout: checkout })
      console.log(checkout.lineItems);
   }

   updateCheckout = async (variantID, quantity) => {
      const lineItemsToUpdate = [
         {id: variantID, quantity: quantity}
       ];
      const checkout = await client.checkout.updateLineItems(this.state.checkout.id, lineItemsToUpdate)
      this.setState({ checkout: checkout })
      // console.log(checkout.lineItems);
   }


问:
Use own dataset in Denoising Diffusion Implicit Models
Can you tell me how I create and implement my own dataset in this code?

```<code>def prepare_dataset(split):
    # the validation dataset is shuffled as well, because data order matters
    # for the KID estimation
    return (
        tfds.load(dataset_name, split=split, shuffle_files=True)
        .map(preprocess_image, num_parallel_calls=tf.data.AUTOTUNE)
        .cache()
        .repeat(dataset_repetitions)
        .shuffle(10 * batch_size)
        .batch(batch_size, drop_remainder=True)
        .prefetch(buffer_size=tf.data.AUTOTUNE)
    )

# load dataset
train_dataset = prepare_dataset("train[:80%]+validation[:80%]+test[:80%]")
val_dataset = prepare_dataset("train[80%:]+validation[80%:]+test[80%:]")
</code>```

It always redirects me to use the TensorFlow datasets. It's from the Keras Notebook 'Denoising Diffusion Implicit Models'.

I tried following the keras guide on how to create your own dataset, but I'm not sure how to implement it in this code. I also tried this way of creating your own dataset, but I don't know if it's possible to implement it into the code above.

Body:
Can you tell me how I create and implement my own dataset in this code?

def prepare_dataset(split):
    # the validation dataset is shuffled as well, because data order matters
    # for the KID estimation
    return (
        tfds.load(dataset_name, split=split, shuffle_files=True)
        .map(preprocess_image, num_parallel_calls=tf.data.AUTOTUNE)
        .cache()
        .repeat(dataset_repetitions)
        .shuffle(10 * batch_size)
        .batch(batch_size, drop_remainder=True)
        .prefetch(buffer_size=tf.data.AUTOTUNE)
    )

# load dataset
train_dataset = prepare_dataset("train[:80%]+validation[:80%]+test[:80%]")
val_dataset = prepare_dataset("train[80%:]+validation[80%:]+test[80%:]")

It always redirects me to use the TensorFlow datasets. It's from the Keras Notebook 'Denoising Diffusion Implicit Models'.

I tried following the keras guide on how to create your own dataset, but I'm not sure how to implement it in this code. I also tried this way of creating your own dataset, but I don't know if it's possible to implement it into the code above.


问:
How to set up jest with webpack with a different config name?
Jest correctly sets up to work with webpack if I name my wepack config file: webpack.config.js. Which is the default file name that webpack will for its config. Problem that I have is that in my project I have 3 different webpack config files; weboack.common.js, webpack.dev.js and webpack.prod.js. For jest I would like to use webpack.common.js.

When running webpack from CLI I have the option to provide the --config parameter. For jest I do not see a parameter with which you can provide that information. I cannot find any examples of running jest tests with webpack in the project and the webpack config files do not have default names.


问:
Event Rate Timing - Events/time period and real-time
I need to create various rate timers of events across a timed period.  For example, 5 events/16 seconds, or real-time.  Akin to bandwidth calculations.

From what I can tell, this is something that would need to be written from scratch, as the timing functions I've seen are for performing an event every X seconds.

Questions:

Are there libraries for this type of thing, or would they need to be written from scratch?

I have a fair stab at some manual functions, for example for events over time_len:

```<code>    def time( self,quantity ):

        self.this_ts = c.time.time_ns()

        self.this_diff_ts = self.this_ts - self.last_ts

        if( self.this_diff_ts < self.time_len ):
            self.this_count += quantity
        else:
            self.this_rate = self.this_count
            self.this_count = quantity
            self.ticks = 0

            self.last_ts = self.this_ts
</code>```

Is that a reasonable approach?

How is a real-time rate actually calculated?  Would it be a count of events within a second averaged over seconds?

Thank you,

John

Body:
I need to create various rate timers of events across a timed period.  For example, 5 events/16 seconds, or real-time.  Akin to bandwidth calculations.

From what I can tell, this is something that would need to be written from scratch, as the timing functions I've seen are for performing an event every X seconds.

Questions:

Are there libraries for this type of thing, or would they need to be written from scratch?

I have a fair stab at some manual functions, for example for events over time_len:

    def time( self,quantity ):

        self.this_ts = c.time.time_ns()

        self.this_diff_ts = self.this_ts - self.last_ts

        if( self.this_diff_ts < self.time_len ):
            self.this_count += quantity
        else:
            self.this_rate = self.this_count
            self.this_count = quantity
            self.ticks = 0

            self.last_ts = self.this_ts

Is that a reasonable approach?

How is a real-time rate actually calculated?  Would it be a count of events within a second averaged over seconds?

Thank you,

John


问:
JavaFX WebView stuck on blank view for locally running Vuejs Application
I have a vue.js app running at http://localhost:8080. I could view the application in normal browser but it is blank on JavaFX WebView. Please help me if you can.

public void start(Stage primaryStage) throws Exception {

    WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();
    webEngine.setJavaScriptEnabled(true);
    Scene scene = new Scene(browser);
    primaryStage.setScene(scene);
    primaryStage.show();
    webEngine.load("http://localhost:8080");
}
```


问:
Cairo Remove Faint Line Between to Adjacent Paths / Combine Paths in Cairo
Is there a way to combine two closed paths in Cairo, so the group of paths is filled as a single solid shape, instead of two shapes sitting next to each other?

If I draw two paths next to each other, there is a faint blank line visible between the two shapes. For example, the below script draws a square and an adjacent half circle so they both share a line. There is a faint blank line visible between the two shapes. I want there to be no dividing line between the two shapes.

import math, cairo

def draw_path_1(ctx):
    ctx.rectangle(40, 55, 30, 30)
    ctx.fill()

def draw_path_2(ctx):
    ctx.arc(70, 70, 30, -math.pi / 2, math.pi / 2)
    ctx.fill()

with cairo.SVGSurface("two_path_shape.svg", 150, 150) as surface:
    ctx = cairo.Context(surface)
    draw_path_1(ctx)
    draw_path_2(ctx)
```
<p><img src="https://i.stack.imgur.com/JbjO1.png" alt="Two shape SVG with faint line" /></p>
<p>I want some way of drawing the SVG without the faint line between the two shapes.
I am not only looking for a solution specifically for this example of a square and a half circle, but some method of doing this for more complex paths.</p>
<p>I found that exporting the image as a png does remove this line, but that doesn't help me, as I want the final output as an SVG file.</p>
<pre class="lang-py prettyprint-override"><code>surface.write_to_png("two_path_shape.png")
</code>```

Body:
Is there a way to combine two closed paths in Cairo, so the group of paths is filled as a single solid shape, instead of two shapes sitting next to each other?

If I draw two paths next to each other, there is a faint blank line visible between the two shapes. For example, the below script draws a square and an adjacent half circle so they both share a line. There is a faint blank line visible between the two shapes. I want there to be no dividing line between the two shapes.

import math, cairo

def draw_path_1(ctx):
    ctx.rectangle(40, 55, 30, 30)
    ctx.fill()

def draw_path_2(ctx):
    ctx.arc(70, 70, 30, -math.pi / 2, math.pi / 2)
    ctx.fill()

with cairo.SVGSurface("two_path_shape.svg", 150, 150) as surface:
    ctx = cairo.Context(surface)
    draw_path_1(ctx)
    draw_path_2(ctx)

I want some way of drawing the SVG without the faint line between the two shapes.
I am not only looking for a solution specifically for this example of a square and a half circle, but some method of doing this for more complex paths.

I found that exporting the image as a png does remove this line, but that doesn't help me, as I want the final output as an SVG file.

surface.write_to_png("two_path_shape.png")


问:
How to change inter-layer hidden size in pretrained BERT and Pytorch?
For a research project, I need to be able to give input to say the third encoder layer of a pre-trained BERT model.

I know that things like these are done using hooks in PyTorch, but that works when I'm defining the model myself.

I was hoping for some frameworks that implement that sort of thing for popular pre-trained models. Or if there was a way to do this in huggingface itself.


问:
Function to sort list (array/slice) fields an any struct variable passed as input
I want to write a function that takes any struct variable as input and sorts the list fields in it. The list fields can be of simple type (int/string) or complex (structs) in which case they must implement some comparable interface which has getValue function returning an int and defines its order to be used for sorting.

Example -

```<code>type comparable interface {
    getValue() int
}

type innerStruct struct {
    x int
    y string
}

func (s innerStruct) getValue() int {
    return s.x
}

type outerStruct struct {
    a []innerStruct
    b []int
}

func sortListFields(in interface{}) {
    // Implement this
}

func main() {
    val := outerStruct{
        a: []innerStruct{
            {1, "abc"},
            {3, "pqr"},
            {2, "xyz"},
        },
        b: []int{9, 7, 8},
    }

    fmt.Println(sortListFields(val))
    // Should print - {[{1 abc} {2 xyz} {3 pqr}] [7 8 9]}
}
</code>```

I have been trying to implement it using reflection, but haven't been able to figure out how to sort the field, once I have determined its a slice/array.

```<code>func sortListFields(in interface{}) {
    v := reflect.ValueOf(in)
    for i := 0; i < v.NumField(); i++ {
        fk := v.Field(i).Type().Kind()
        if fk == reflect.Array || fk == reflect.Slice {
            fmt.Printf("%v field is a list\n", v.Type().Field(i).Name)
            // How to sort this field ???
        }
    }
}
</code>```

I have following questions with respect to this.

Firstly (as clear from the post), how to implement sorting for the fields ?

Are there any other simpler (or may be not so simple) ways with/without reflection of achieving the same ?

Body:
I want to write a function that takes any struct variable as input and sorts the list fields in it. The list fields can be of simple type (int/string) or complex (structs) in which case they must implement some comparable interface which has getValue function returning an int and defines its order to be used for sorting.

Example -

type comparable interface {
    getValue() int
}

type innerStruct struct {
    x int
    y string
}

func (s innerStruct) getValue() int {
    return s.x
}

type outerStruct struct {
    a []innerStruct
    b []int
}

func sortListFields(in interface{}) {
    // Implement this
}

func main() {
    val := outerStruct{
        a: []innerStruct{
            {1, "abc"},
            {3, "pqr"},
            {2, "xyz"},
        },
        b: []int{9, 7, 8},
    }

    fmt.Println(sortListFields(val))
    // Should print - {[{1 abc} {2 xyz} {3 pqr}] [7 8 9]}
}

I have been trying to implement it using reflection, but haven't been able to figure out how to sort the field, once I have determined its a slice/array.

func sortListFields(in interface{}) {
    v := reflect.ValueOf(in)
    for i := 0; i < v.NumField(); i++ {
        fk := v.Field(i).Type().Kind()
        if fk == reflect.Array || fk == reflect.Slice {
            fmt.Printf("%v field is a list\n", v.Type().Field(i).Name)
            // How to sort this field ???
        }
    }
}

I have following questions with respect to this.

Firstly (as clear from the post), how to implement sorting for the fields ?

Are there any other simpler (or may be not so simple) ways with/without reflection of achieving the same ?


问:
postman http get request with authentification fails with 401 reply
I have an IOT device (PV inverter). As with many of these there is an official API mostly for data retrival and some settings. However, given the right credentials (admin account) you can configure significantly more in the webinterface.

I would like to be able to do this from my home automation server directly (via node red finally). So I tried to have a look at the communication between the browser and the inverter via Wireshark.
I found some GET an POST calls, and wanted to start with the replication of a GET call via node-red or Postman first.

However, no matter what I tried so far I only get 401 replies.
Seemingly, I'm not able to setup the message with proper authentificaion. In wireshark the Postman and the original GET request are very close.

Here is the original (followed by a "200 OK" response):

Internet Protocol Version 4, Src: 192.168.0.64, Dst: 192.168.0.5

Transmission Control Protocol, Src Port: 56183, Dst Port: 80, Seq: 1, Ack: 1, Len: 601

Source Port: 56183

Destination Port: 80

[Stream index: 1]

[Conversation completeness: Incomplete (28)]

[TCP Segment Len: 601]

Sequence Number: 1    (relative sequence number)

Sequence Number (raw): 2463465501

[Next Sequence Number: 602    (relative sequence number)]

Acknowledgment Number: 1    (relative ack number)

Acknowledgment number (raw): 1894190984

0101 .... = Header Length: 20 bytes (5)

Flags: 0x018 (PSH, ACK)

[TCP Flags: ·······AP···]

Window: 512

[Calculated window size: 512]

[Window size scaling factor: -1 (unknown)]

Checksum: 0x8409 [unverified]

[Checksum Status: Unverified]

Urgent Pointer: 0

[Timestamps]

[SEQ/ACK analysis]

TCP payload (601 bytes)

Hypertext Transfer Protocol

GET /commands/StandbyState HTTP/1.1\r\n

Host: 192.168.0.5\r\n

Connection: keep-alive\r\n

Accept: application/json, text/plain, /\r\n

Authorization: Digest username="technician", realm="Webinterface area",

nonce="63af2777:24350f8b8a09fb90b82b6ac480d325cc", uri="/commands/StandbyState", response="a09ac5fe504563040d0ff8acfd68653e", qop=auth, nc=00000022, cnonce="NaN"\r\n

```<code>    username="technician"
    realm="Webinterface area"
    nonce="63af2777:24350f8b8a09fb90b82b6ac480d325cc"
    uri="/commands/StandbyState"
    response="a09ac5fe504563040d0ff8acfd68653e"
    qop=auth
    nc=00000022
</code>```

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)

Chrome/108.0.0.0 Safari/537.36\r\n

Referer: http://192.168.0.5/\r\n

Accept-Encoding: gzip, deflate\r\n

Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7\r\n

\r\n

[Full request URI: http://192.168.0.5/commands/StandbyState]

and here is the captured Postman packet

Internet Protocol Version 4, Src: 192.168.0.64, Dst: 192.168.0.5

Transmission Control Protocol, Src Port: 43404, Dst Port: 80, Seq: 1, Ack: 1, Len: 471

Source Port: 43404

Destination Port: 80

[Stream index: 5]

[Conversation completeness: Incomplete, DATA (15)]

[TCP Segment Len: 471]

Sequence Number: 1    (relative sequence number)

Sequence Number (raw): 990556558

[Next Sequence Number: 472    (relative sequence number)]

Acknowledgment Number: 1    (relative ack number)

Acknowledgment number (raw): 2175082347

0101 .... = Header Length: 20 bytes (5)

Flags: 0x018 (PSH, ACK)

[TCP Flags: ·······AP···]

Window: 513

[Calculated window size: 131328]

[Window size scaling factor: 256]

Checksum: 0x8387 [unverified]

[Checksum Status: Unverified]

Urgent Pointer: 0

[Timestamps]

[SEQ/ACK analysis]

TCP payload (471 bytes)

Hypertext Transfer Protocol

GET /commands/StandbyState HTTP/1.1\r\n

[truncated]Authorization: Digest username="technician", realm="Webinterface area", nonce="63af2777:24350f8b8a09fb90b82b6ac480d325cc", uri="/commands/StandbyState", algorithm="MD5", qop=auth, nc=00000022, cnonce="NaN", response="a09ac5fe5

```<code>    username="technician"
    realm="Webinterface area"
    nonce="63af2777:24350f8b8a09fb90b82b6ac480d325cc"
    uri="/commands/StandbyState"
    algorithm="MD5"
    qop=auth
    nc=00000022
    cnonce="NaN"
</code>```

User-Agent: PostmanRuntime/7.30.0\r\n

Accept: /\r\n

Postman-Token: e5d8ee2c-37fb-49ae-aa37-1cf05bfe8608\r\n

Host: 192.168.0.5\r\n

Accept-Encoding: gzip, deflate, br\r\n

Connection: keep-alive\r\n

\r\n

[Full request URI: http://192.168.0.5/commands/StandbyState]

[HTTP request 1/1]

Why does this not work?

Body:
I have an IOT device (PV inverter). As with many of these there is an official API mostly for data retrival and some settings. However, given the right credentials (admin account) you can configure significantly more in the webinterface.

I would like to be able to do this from my home automation server directly (via node red finally). So I tried to have a look at the communication between the browser and the inverter via Wireshark.
I found some GET an POST calls, and wanted to start with the replication of a GET call via node-red or Postman first.

However, no matter what I tried so far I only get 401 replies.
Seemingly, I'm not able to setup the message with proper authentificaion. In wireshark the Postman and the original GET request are very close.

Here is the original (followed by a "200 OK" response):

Internet Protocol Version 4, Src: 192.168.0.64, Dst: 192.168.0.5

Transmission Control Protocol, Src Port: 56183, Dst Port: 80, Seq: 1, Ack: 1, Len: 601

Source Port: 56183

Destination Port: 80

[Stream index: 1]

[Conversation completeness: Incomplete (28)]

[TCP Segment Len: 601]

Sequence Number: 1    (relative sequence number)

Sequence Number (raw): 2463465501

[Next Sequence Number: 602    (relative sequence number)]

Acknowledgment Number: 1    (relative ack number)

Acknowledgment number (raw): 1894190984

0101 .... = Header Length: 20 bytes (5)

Flags: 0x018 (PSH, ACK)

[TCP Flags: ·······AP···]

Window: 512

[Calculated window size: 512]

[Window size scaling factor: -1 (unknown)]

Checksum: 0x8409 [unverified]

[Checksum Status: Unverified]

Urgent Pointer: 0

[Timestamps]

[SEQ/ACK analysis]

TCP payload (601 bytes)

Hypertext Transfer Protocol

GET /commands/StandbyState HTTP/1.1\r\n

Host: 192.168.0.5\r\n

Connection: keep-alive\r\n

Accept: application/json, text/plain, /\r\n

Authorization: Digest username="technician", realm="Webinterface area",

nonce="63af2777:24350f8b8a09fb90b82b6ac480d325cc", uri="/commands/StandbyState", response="a09ac5fe504563040d0ff8acfd68653e", qop=auth, nc=00000022, cnonce="NaN"\r\n

    username="technician"
    realm="Webinterface area"
    nonce="63af2777:24350f8b8a09fb90b82b6ac480d325cc"
    uri="/commands/StandbyState"
    response="a09ac5fe504563040d0ff8acfd68653e"
    qop=auth
    nc=00000022

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)

Chrome/108.0.0.0 Safari/537.36\r\n

Referer: http://192.168.0.5/\r\n

Accept-Encoding: gzip, deflate\r\n

Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7\r\n

\r\n

[Full request URI: http://192.168.0.5/commands/StandbyState]

and here is the captured Postman packet

Internet Protocol Version 4, Src: 192.168.0.64, Dst: 192.168.0.5

Transmission Control Protocol, Src Port: 43404, Dst Port: 80, Seq: 1, Ack: 1, Len: 471

Source Port: 43404

Destination Port: 80

[Stream index: 5]

[Conversation completeness: Incomplete, DATA (15)]

[TCP Segment Len: 471]

Sequence Number: 1    (relative sequence number)

Sequence Number (raw): 990556558

[Next Sequence Number: 472    (relative sequence number)]

Acknowledgment Number: 1    (relative ack number)

Acknowledgment number (raw): 2175082347

0101 .... = Header Length: 20 bytes (5)

Flags: 0x018 (PSH, ACK)

[TCP Flags: ·······AP···]

Window: 513

[Calculated window size: 131328]

[Window size scaling factor: 256]

Checksum: 0x8387 [unverified]

[Checksum Status: Unverified]

Urgent Pointer: 0

[Timestamps]

[SEQ/ACK analysis]

TCP payload (471 bytes)

Hypertext Transfer Protocol

GET /commands/StandbyState HTTP/1.1\r\n

[truncated]Authorization: Digest username="technician", realm="Webinterface area", nonce="63af2777:24350f8b8a09fb90b82b6ac480d325cc", uri="/commands/StandbyState", algorithm="MD5", qop=auth, nc=00000022, cnonce="NaN", response="a09ac5fe5

    username="technician"
    realm="Webinterface area"
    nonce="63af2777:24350f8b8a09fb90b82b6ac480d325cc"
    uri="/commands/StandbyState"
    algorithm="MD5"
    qop=auth
    nc=00000022
    cnonce="NaN"

User-Agent: PostmanRuntime/7.30.0\r\n

Accept: /\r\n

Postman-Token: e5d8ee2c-37fb-49ae-aa37-1cf05bfe8608\r\n

Host: 192.168.0.5\r\n

Accept-Encoding: gzip, deflate, br\r\n

Connection: keep-alive\r\n

\r\n

[Full request URI: http://192.168.0.5/commands/StandbyState]

[HTTP request 1/1]

Why does this not work?


问:
Dynamic CSS class
I want to create a margin class in my custom CSS like margin-left-x and wish to have the left margin equal to that x value. Is this possible? More precisely I wish to do it as below:

```<code>.margin-left-x{
   margin-left: x%;
}
</code>```

Brute force approach is to create separate CSS classes for each margin value but it becomes tedious and difficult to maintain, like:

```<code>.margin-left-2{
   margin-left: 2%;
}

.margin-left-5{
   margin-left: 5%;
}

.margin-left-20{
   margin-left: 20%;
}
</code>```

Is there anyway I can make this dynamic with just a single CSS class?

In my HTML, I wish to use it in the class attribute directly, like below:

```<code><div class="col-sm-4 col-md-4 margin-left-20">
 <p> Hello </p>
</div>

</code>```

Title: Dynamic CSS class

Body:
I want to create a margin class in my custom CSS like margin-left-x and wish to have the left margin equal to that x value. Is this possible? More precisely I wish to do it as below:

.margin-left-x{
   margin-left: x%;
}

Brute force approach is to create separate CSS classes for each margin value but it becomes tedious and difficult to maintain, like:

.margin-left-2{
   margin-left: 2%;
}

.margin-left-5{
   margin-left: 5%;
}

.margin-left-20{
   margin-left: 20%;
}

Is there anyway I can make this dynamic with just a single CSS class?

In my HTML, I wish to use it in the class attribute directly, like below:

 Hello


问:
How to show multi views of source code, call stack and local variables automatically at hitting breakpoint?
I ran into a Youtube talking about kernel, he set GDB breakpoint, and upon hitting the breakpoint, his GDB shows this automatically:

This is so impressive, source code, call stack and local variables are all listed. Do you have a pointer how to make this?


问:
Convert CFRunLoopTimer to Windows API
I've been trying to convert a CFRunLoopTimer Function to a windows api (to make it work on windows). I've been trying to use SetTimer using the HWND, but haven't had luck with callback. Here is the unmodified original code:

use std::ffi::c_void;
use std::{ptr, mem};

use cacao::core_foundation::runloop::__CFRunLoopTimer;
use cacao::core_foundation::{runloop, date};

extern "C" fn callback(_timer: runloop::CFRunLoopTimerRef, info: *mut c_void) {
    unsafe {
        let timer = info as *mut Timer;
        ((*timer).func)();
    }
}

// Helper to run a timer on the UI thread.
pub struct Timer {
    timer: Option<*mut __CFRunLoopTimer>,
    func: Box<dyn FnMut()>
}

impl Timer {
    pub fn new(interval: f64, func: Box<dyn FnMut()>) -> Box<Self> {
        unsafe {
            let mut s = Box::new(Timer { timer: None, func });

            s.timer = Some(runloop::CFRunLoopTimerCreate(
                ptr::null(),
                date::CFAbsoluteTimeGetCurrent() + interval,
                interval,
                0,
                0,
                callback,
                &mut runloop::CFRunLoopTimerContext {
                    info: &mut *s as *mut _ as *mut c_void,
                    ..mem::zeroed()
                },
            ));

            runloop::CFRunLoopAddTimer(
                runloop::CFRunLoopGetCurrent(),
                s.timer.unwrap(),
                runloop::kCFRunLoopCommonModes,
            );

            s
        }
    }
}

impl Drop for Timer {
    fn drop(&mut self) {
        unsafe {
            runloop::CFRunLoopTimerInvalidate(self.timer.unwrap());
        }
    }
}

unsafe impl Sync for Timer {}
unsafe impl Send for Timer {}
```
<p>This is the existing code that I have.</p>
<pre class="lang-rust prettyprint-override"><code>use winapi::shared::windef::HWND;
use winapi::um::winuser::{ SetTimer, KillTimer }; // WM_TIMER
use winapi::shared::basetsd::{ UINT_PTR };
use winapi::shared::minwindef::{ UINT, DWORD };
const WIN_FRAME_TIMER: usize = 4242;
pub struct Timer {
handle: HWND,
idevent: usize,
func: Box<dyn FnMut()>
}
impl Timer {
pub fn new(handle: HWND, interval: f64, func: Box<dyn Fn()>) -> Box<Self> {
unsafe {
SetTimer(handle, 1234, 100, Some(callback));
}
Box::new(Self { handle: handle, idevent: 1234,  func:Box::new(|| {})})
}
}
impl Drop for Timer {
fn drop(&mut self) {
unsafe { KillTimer(self.handle, self.idevent); }
}
}
unsafe impl Sync for Timer {}
unsafe impl Send for Timer {}
extern "system" fn callback(hwnd: HWND, uMsg: UINT, idEvent: UINT_PTR, dwTime: DWORD){

}
type Callback = Box<dyn Fn(&str)>;

</code>```

Well, if you are up to a challenge, help is welcome

Title: Convert CFRunLoopTimer to Windows API

Body:
I've been trying to convert a CFRunLoopTimer Function to a windows api (to make it work on windows). I've been trying to use SetTimer using the HWND, but haven't had luck with callback. Here is the unmodified original code:

use std::ffi::c_void;
use std::{ptr, mem};

use cacao::core_foundation::runloop::__CFRunLoopTimer;
use cacao::core_foundation::{runloop, date};

extern "C" fn callback(_timer: runloop::CFRunLoopTimerRef, info: *mut c_void) {
    unsafe {
        let timer = info as *mut Timer;
        ((*timer).func)();
    }
}

// Helper to run a timer on the UI thread.
pub struct Timer {
    timer: Option<*mut __CFRunLoopTimer>,
    func: Box<dyn FnMut()>
}

impl Timer {
    pub fn new(interval: f64, func: Box<dyn FnMut()>) -> Box<Self> {
        unsafe {
            let mut s = Box::new(Timer { timer: None, func });

            s.timer = Some(runloop::CFRunLoopTimerCreate(
                ptr::null(),
                date::CFAbsoluteTimeGetCurrent() + interval,
                interval,
                0,
                0,
                callback,
                &mut runloop::CFRunLoopTimerContext {
                    info: &mut *s as *mut _ as *mut c_void,
                    ..mem::zeroed()
                },
            ));

            runloop::CFRunLoopAddTimer(
                runloop::CFRunLoopGetCurrent(),
                s.timer.unwrap(),
                runloop::kCFRunLoopCommonModes,
            );

            s
        }
    }
}

impl Drop for Timer {
    fn drop(&mut self) {
        unsafe {
            runloop::CFRunLoopTimerInvalidate(self.timer.unwrap());
        }
    }
}

unsafe impl Sync for Timer {}
unsafe impl Send for Timer {}

This is the existing code that I have.

use winapi::shared::windef::HWND;
use winapi::um::winuser::{ SetTimer, KillTimer }; // WM_TIMER
use winapi::shared::basetsd::{ UINT_PTR };
use winapi::shared::minwindef::{ UINT, DWORD };
const WIN_FRAME_TIMER: usize = 4242;
pub struct Timer {
handle: HWND,
idevent: usize,
func: Box<dyn FnMut()>
}
impl Timer {
pub fn new(handle: HWND, interval: f64, func: Box<dyn Fn()>) -> Box<Self> {
unsafe {
SetTimer(handle, 1234, 100, Some(callback));
}
Box::new(Self { handle: handle, idevent: 1234,  func:Box::new(|| {})})
}
}
impl Drop for Timer {
fn drop(&mut self) {
unsafe { KillTimer(self.handle, self.idevent); }
}
}
unsafe impl Sync for Timer {}
unsafe impl Send for Timer {}
extern "system" fn callback(hwnd: HWND, uMsg: UINT, idEvent: UINT_PTR, dwTime: DWORD){

}
type Callback = Box<dyn Fn(&str)>;

Well, if you are up to a challenge, help is welcome


问:
How to generate an orthogonal symmetric matrix?
I want to create an orthogonal symmetric matrix of size 5 and size 6. Is there a way for me to generate this type of matrix? An orthogonal symmetric matrix is when a matrix A is equal to its transpose and also its inverse.

I've tried searching for ways to do this but all I get is how to generate an orthogonal matrix or how to generate a symmetric matrix. Couldn't find a way to generate an orthogonal symmetric matrix.


问:
error when parsing wsdl : Parsing WSDL: No <binding> element with name xxxx
im trying to connect to a soap api but i get this error when i fees the wsdl address to my soap client

```<code>SOAP-ERROR: Parsing WSDL: No <binding> element with name 'SamsungEKPGetDataByUSServiceSoapBinding'
</code>```

i dont want to post the whole wsdl file it's long and private but here is the parts with the name in error

```<code>   <wsdl:binding name="trsekp:SamsungEKPGetDataByUSServiceSoapBinding" type="impl:SamsungEKPGetDataByUSService">

      <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>

      <wsdl:operation name="getModelBatch">

         <wsdlsoap:operation soapAction=""/>

         <wsdl:input name="getModelBatchRequest">

            <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://us.samsung.trs.com" use="encoded"/>

         </wsdl:input>

         <wsdl:output name="getModelBatchResponse">

            <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://test.samsung.com/ekp/services/trsekp:SamsungEKPGetDataByUSService" use="encoded"/>

         </wsdl:output>

         <wsdl:fault name="WCMException">

            <wsdlsoap:fault encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" name="WCMException" namespace="http://test.samsung.com/ekp/services/trsekp:SamsungEKPGetDataByUSService" use="encoded"/>

         </wsdl:fault>

      </wsdl:operation>

   </wsdl:binding>

   <wsdl:service name="SamsungEKPGetDataByUSServiceService">

      <wsdl:port binding="impl:trsekp:SamsungEKPGetDataByUSServiceSoapBinding" name="trsekp:SamsungEKPGetDataByUSService">

         <wsdlsoap:address location="http://test.samsung.com/ekp/services/trsekp:SamsungEKPGetDataByUSService"/>

      </wsdl:port>

   </wsdl:service>
</code>```

any idea what is causing this error ?

Body:
im trying to connect to a soap api but i get this error when i fees the wsdl address to my soap client

SOAP-ERROR: Parsing WSDL: No <binding> element with name 'SamsungEKPGetDataByUSServiceSoapBinding'

i dont want to post the whole wsdl file it's long and private but here is the parts with the name in error

   <wsdl:binding name="trsekp:SamsungEKPGetDataByUSServiceSoapBinding" type="impl:SamsungEKPGetDataByUSService">

      <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>

      <wsdl:operation name="getModelBatch">

         <wsdlsoap:operation soapAction=""/>

         <wsdl:input name="getModelBatchRequest">

            <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://us.samsung.trs.com" use="encoded"/>

         </wsdl:input>

         <wsdl:output name="getModelBatchResponse">

            <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://test.samsung.com/ekp/services/trsekp:SamsungEKPGetDataByUSService" use="encoded"/>

         </wsdl:output>

         <wsdl:fault name="WCMException">

            <wsdlsoap:fault encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" name="WCMException" namespace="http://test.samsung.com/ekp/services/trsekp:SamsungEKPGetDataByUSService" use="encoded"/>

         </wsdl:fault>

      </wsdl:operation>

   </wsdl:binding>

   <wsdl:service name="SamsungEKPGetDataByUSServiceService">

      <wsdl:port binding="impl:trsekp:SamsungEKPGetDataByUSServiceSoapBinding" name="trsekp:SamsungEKPGetDataByUSService">

         <wsdlsoap:address location="http://test.samsung.com/ekp/services/trsekp:SamsungEKPGetDataByUSService"/>

      </wsdl:port>

   </wsdl:service>

any idea what is causing this error ?


问:
how to capture old instagram request?
We try to capture the old Instagram apk requests, used  for sslpinning bypass in frida and objection
not capture the requests , it's showing

error message

An unknown network error has occurred

how to solve this  and  how to capture the request ???

frida command

frida --codeshare pcipolloni/universal-android-ssl-pinning-bypass-with-frida -U -f com.instagram.android

objection  command

objection -g com.instagram.android explore

tested apk:
https://androidapksfree.com/instagram/com-instagram-android/download-old/instagram-7-12-0-18187053-apk-download/

we want to test only older version to
like a Instagram 8.0.0  to 6.0.0

please help me .....

please help me .....

Title: how to capture old instagram request?


问:
how to find Interaction effect(by generating impulse response for low and high regimes) in non linear Structural VAR framework?
imagine we have five variable X1, X2, X3, X4, X5. what I am looking to find is the effect of X1 on X3,X4,X5 when the X2 is at its lowest and highest periods.

for this, I applied the TVAR function in TsDyn package in r

```<code>> data <-  cbind(X5,X4,X3,X2,X1)
> model <- TVAR(data, lag=1, nthresh=2, thDelay=1, trim=0.1, mTh=4, plot=TRUE)
> plot(irf(model, regime = "L", boot = TRUE))
> plot(irf(model, regime = "H", boot = TRUE))
> plot(irf(model, regime = "M", boot = TRUE))
</code>```

but i want modify the relationship among variables that X2,X3,X4,X5 affects X1 contemporously and X1 affects X3,X4,X5 in lag.

So what I am looking for is to model this effect X1 on other variables in the high and low regimes of X2(interaction effect) with the ability to modify the relationship between the other Variables in the system. is there any package that is able to do Structural Vector autoregression Method in a non-linear framework? or how can I find out the effect of X1 on others when interacted with X2(when x2 is in its lowest decile and the highest decile)

Body:
imagine we have five variable X1, X2, X3, X4, X5. what I am looking to find is the effect of X1 on X3,X4,X5 when the X2 is at its lowest and highest periods.

for this, I applied the TVAR function in TsDyn package in r

> data <-  cbind(X5,X4,X3,X2,X1)
> model <- TVAR(data, lag=1, nthresh=2, thDelay=1, trim=0.1, mTh=4, plot=TRUE)
> plot(irf(model, regime = "L", boot = TRUE))
> plot(irf(model, regime = "H", boot = TRUE))
> plot(irf(model, regime = "M", boot = TRUE))

but i want modify the relationship among variables that X2,X3,X4,X5 affects X1 contemporously and X1 affects X3,X4,X5 in lag.

So what I am looking for is to model this effect X1 on other variables in the high and low regimes of X2(interaction effect) with the ability to modify the relationship between the other Variables in the system. is there any package that is able to do Structural Vector autoregression Method in a non-linear framework? or how can I find out the effect of X1 on others when interacted with X2(when x2 is in its lowest decile and the highest decile)


问:
How to create count PivotTable with several data counts
I am trying to create a basic count PivotTable with a small twist.

My table looks something like the following

A
B

Toyota
2013

Honda
2013

Toyota
2013

Honda
2015

Toyota
2012

Honda
2014

Toyota
2016

Honda
2016

Honda
2016

Honda
2014

I want my PivotTable to have x amount of bar groups, where x is the number of different values in A, in this case, 2 (Honda, Toyota). Each group would then have y bars, where y is the number of different values in B for the corresponding A value (For Honda 2013, 2014, 2015, 2016. For Toyota 2012, 2013, 2016) and the size of each bar in each group would be the count, the amount of values in B for the corresponding A value.

Eventually I expect a graph that will represent something like this:

A
B
C

Toyota
2012
1

2013
2

2016
1

Honda
2013
1

2014
2

2015
1

2016
2

And this is how I would want the graph to look like:

Any help would be appreciated.


问:
Ansible cannot unarchive using 'root' username
I have the classic unarchive example in my playbook as follows:

```<code>  - name: Extract foo.tgz into /var/lib/foo
    ansible.builtin.unarchive:
      src: foo.tgz
      dest: /tmp
</code>```

I get the error:

```<code>"Commands \"gtar\" and \"tar\" not found. Command \"unzip\" not found."
</code>```

I did have a look at the answer here. However in my case, the issue is specifically with the 'root' user. With the user john, the unarchive is successful.

The following tests are successful for both the root and john:

```<code>ansible all -i hosts -m command -a "which tar"   -l hostname --user [root,john]
</code>```

... results in

```<code>hostname  | CHANGED | rc=0 >> /usr/local/bin/tar
</code>```

... and successfully finds the 'tar' binary.

What might be the issue?

Body:
I have the classic unarchive example in my playbook as follows:

  - name: Extract foo.tgz into /var/lib/foo
    ansible.builtin.unarchive:
      src: foo.tgz
      dest: /tmp

I get the error:

"Commands \"gtar\" and \"tar\" not found. Command \"unzip\" not found."

I did have a look at the answer here. However in my case, the issue is specifically with the 'root' user. With the user john, the unarchive is successful.

The following tests are successful for both the root and john:

ansible all -i hosts -m command -a "which tar"   -l hostname --user [root,john]

... results in

hostname  | CHANGED | rc=0 >> /usr/local/bin/tar

... and successfully finds the 'tar' binary.

What might be the issue?


问:
OpenAPI in Jetbrains Aqua fail to fetch
I have build a Openapi v3 specification for an api I have running locally. When I open up the GUI and select try it out an execute any request I always get Failed to Fetch.

I have tried accessing it from curl, a web browser as well as the HTTP Client in Aqua and have had no issues.

Title: OpenAPI in Jetbrains Aqua fail to fetch


问:
Word Add-in Word Count Excluding Tables & Headers
I'm VERY new to Word add-ins, but saw them in VS as (falsely) advertised as C# projects, and as someone who's dabbled in that for a while I thought I'd give it a go to save myself time instead of having to open up Notepad and doing the math by selecting various elements.

I then realised that pretty much all the functional code is in js, and we don't get along!

After trying and failing for the last day, I've decided to just ask.

My functional code for just trying to get the total wordcount is below, but even this doesn't seem to work.

function calcWordCount() {
        Word.run(function (context) {

            var range = context.document.body;

            var totalWC;

            context.load(range, 'text');

            var words = range.text.split(/\s+/);

            totalWC = words.length;

            context.load(totalWC, 'font');

            $("#fullWC").text(totalWC);

            return context.sync();
        })
        .catch(errorHandler);
    }```

I have absolutely no idea what I'm doing with this, but did find this vb macro do what what I am looking to do here:
https://answers.microsoft.com/en-us/msoffice/forum/all/excluding-words-from-the-word-count/e6f59014-66f2-4b43-83d2-df52f7b4da5b
Problem is, due to security I can't run macros for my work, so I need to be able to do this within an add-in.
Does anyone know what I'm doing wrong, and how I can:
A) count the total words
B) identify table and header word-count and minus that from the total

I'm completely lost here, the Office documentation for this seems to be VERY sparse.

Body:
I'm VERY new to Word add-ins, but saw them in VS as (falsely) advertised as C# projects, and as someone who's dabbled in that for a while I thought I'd give it a go to save myself time instead of having to open up Notepad and doing the math by selecting various elements.

I then realised that pretty much all the functional code is in js, and we don't get along!

After trying and failing for the last day, I've decided to just ask.

My functional code for just trying to get the total wordcount is below, but even this doesn't seem to work.

function calcWordCount() {
        Word.run(function (context) {

            var range = context.document.body;

            var totalWC;

            context.load(range, 'text');

            var words = range.text.split(/\s+/);

            totalWC = words.length;

            context.load(totalWC, 'font');

            $("#fullWC").text(totalWC);

            return context.sync();
        })
        .catch(errorHandler);
    }

I have absolutely no idea what I'm doing with this, but did find this vb macro do what what I am looking to do here:
https://answers.microsoft.com/en-us/msoffice/forum/all/excluding-words-from-the-word-count/e6f59014-66f2-4b43-83d2-df52f7b4da5b
Problem is, due to security I can't run macros for my work, so I need to be able to do this within an add-in.
Does anyone know what I'm doing wrong, and how I can:
A) count the total words
B) identify table and header word-count and minus that from the total

I'm completely lost here, the Office documentation for this seems to be VERY sparse.


问:
Mongodb compass UI unresponsive when a collection size is more than 30MB
Mongodb compass UI unresponsive when a collection size is more than 30MB, and average size of document could more than 5MB.

Is there any reason why it is slow, or is there any limitations on collection or document sizes.

Mongodb compass help


问:
How do I aggregate over percentile using cloudwatch metric insights?
I was looking for ways we can alarm over p90 & p99 percentiles when we use a cloud-watch metric insights SQL query to aggregate over statistics. The query takes in a "FUNCTION" value to aggregate over values. The valid values for FUNCTION are AVG, COUNT, MAX, MIN, and SUM. However I don't see percentile aggregations as a valid value. Is there a way we can alarm over percentile statistics when we use the metric insight?

To give more context I'm emitting a custom metric with batch jobId as a dimension. Batch JobId is not unique so I was planning on using metrics insights query builder to aggregate over all batch jobs and alarm over it but unfortunately i hit a roadblock while trying to create a p90 stastics alarm. Is there another way to solve this?


问:
PHP SQL Server Function not Returning Expected Results for Column Value Result
I am working on a function that checks if the user has saved their login credentials, but when checking and the SQL Server query returns count = 0, the variables results in "undefined array". I am not sure how to fix the issue, as I am new to PHP.

Bit of context to the process:

When a user logins to the website, I am setting the $_SESSION variable "logged_in" to 'true'. The user can decide to also "remember me" to save time in logging in if they close their browser. If the user checks the "remember me" box when logging in, I am saving a unique token "remToken" and the user's UserID (created on registration) "userID" as two cookies. These two values get inserted into the database.

The objective is that on each page of the website, I run a function that checks if the $_SESSION['logged_in'] is set and set to 'true'. If yes, $_SESSION['logged_in'] = true;, else $_SESSION['logged_in'] = false;

Next, check if the user has active remToken and userID cookies. If yes, check for a matching active remToken and UserID set in the database. If yes, set $_SESSION['logged_in'] = true;, else unset the remToken and userID cookies and set $_SESSION['logged_in'] = false;

Finally, return $_SESSION['logged_in'];

When running the SQL query in the database, it returns 0 (expected for this example, as I am testing the function). When echoing out "echo $returnCount;", it results in the error "UNDEFINED VARIABLE $RETURNCOUNT". When the count from the query is 1, it properly returns 1. $pdo variable is correctly set and works in other queries.

```<code>function cookie_RememberMeCheck($pdo) {
    //Function expectation:
    //If the session "logged_in" is not set and not true, set it to false
    //Next, check if the user has active "remember me" cookies. If they do, set the logged_in state to "true"
        //If the user has inactive "remember me" cookies, set "logged_in" to false

    //If the user has not logged in during this session, set the logged_in value to "false". If they have logged in, set the session to "true"
    if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] = true) {
        $_SESSION['logged_in'] = true;
    } else {
        $_SESSION['logged_in'] = false;
    }

    //Check if the cookies "remToken" and "userID" have been set
    if (isset($_COOKIE['remToken']) && isset($_COOKIE['userID'])) {

        //Set the values of the UserID and remToken so we can match them to the database
        $cookie_userID = $_COOKIE['userID'];
        $cookie_remToken = $_COOKIE['remToken'];

        $sqlStmt = 'select count(*) as RemCount from DessertBar..UserRemLogin rl with (nolock) where rl.UserID = :userID and rl.RemToken = :remToken and rl.isActive = 1';
        $sqlStmtPrepare = $pdo->prepare($sqlStmt);
        $sqlStmtPrepare->bindParam(':userID', $cookie_userID);
        $sqlStmtPrepare->bindParam(':remToken', $cookie_remToken);
        $sqlStmtPrepare->execute();
        $returnCount = $sqlStmtPrepare->fetchColumn();

        if ($returnCount > 0) {
            //If user has active cookies in database, set logged_in state to true
            $_SESSION['logged_in'] = true;
        } else {
            //If the user does not have active cookies in the database, destroy the cookies and logout the user
            unset($_COOKIE['userID']);
            unset($_COOKIE['remToken']);

            $_SESSION['logged_in'] = false;
        }

    }

    //Finally, return the result of the logged_in state for the user
    //return $_SESSION['logged_in'];
    echo $returnCount;
}
</code>```

The desired result is that if COUNT(*) in sqlStmt is 0, then the $returnCount variable would also be 0. The SQL script is working fine as far as I can tell, but PHP is not correctly pulling the value of the COUNT(*) statement is what I think.

Body:
I am working on a function that checks if the user has saved their login credentials, but when checking and the SQL Server query returns count = 0, the variables results in "undefined array". I am not sure how to fix the issue, as I am new to PHP.

Bit of context to the process:

When a user logins to the website, I am setting the $_SESSION variable "logged_in" to 'true'. The user can decide to also "remember me" to save time in logging in if they close their browser. If the user checks the "remember me" box when logging in, I am saving a unique token "remToken" and the user's UserID (created on registration) "userID" as two cookies. These two values get inserted into the database.

The objective is that on each page of the website, I run a function that checks if the $_SESSION['logged_in'] is set and set to 'true'. If yes, $_SESSION['logged_in'] = true;, else $_SESSION['logged_in'] = false;

Next, check if the user has active remToken and userID cookies. If yes, check for a matching active remToken and UserID set in the database. If yes, set $_SESSION['logged_in'] = true;, else unset the remToken and userID cookies and set $_SESSION['logged_in'] = false;

Finally, return $_SESSION['logged_in'];

When running the SQL query in the database, it returns 0 (expected for this example, as I am testing the function). When echoing out "echo $returnCount;", it results in the error "UNDEFINED VARIABLE $RETURNCOUNT". When the count from the query is 1, it properly returns 1. $pdo variable is correctly set and works in other queries.

function cookie_RememberMeCheck($pdo) {
    //Function expectation:
    //If the session "logged_in" is not set and not true, set it to false
    //Next, check if the user has active "remember me" cookies. If they do, set the logged_in state to "true"
        //If the user has inactive "remember me" cookies, set "logged_in" to false

    //If the user has not logged in during this session, set the logged_in value to "false". If they have logged in, set the session to "true"
    if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] = true) {
        $_SESSION['logged_in'] = true;
    } else {
        $_SESSION['logged_in'] = false;
    }

    //Check if the cookies "remToken" and "userID" have been set
    if (isset($_COOKIE['remToken']) && isset($_COOKIE['userID'])) {

        //Set the values of the UserID and remToken so we can match them to the database
        $cookie_userID = $_COOKIE['userID'];
        $cookie_remToken = $_COOKIE['remToken'];

        $sqlStmt = 'select count(*) as RemCount from DessertBar..UserRemLogin rl with (nolock) where rl.UserID = :userID and rl.RemToken = :remToken and rl.isActive = 1';
        $sqlStmtPrepare = $pdo->prepare($sqlStmt);
        $sqlStmtPrepare->bindParam(':userID', $cookie_userID);
        $sqlStmtPrepare->bindParam(':remToken', $cookie_remToken);
        $sqlStmtPrepare->execute();
        $returnCount = $sqlStmtPrepare->fetchColumn();

        if ($returnCount > 0) {
            //If user has active cookies in database, set logged_in state to true
            $_SESSION['logged_in'] = true;
        } else {
            //If the user does not have active cookies in the database, destroy the cookies and logout the user
            unset($_COOKIE['userID']);
            unset($_COOKIE['remToken']);

            $_SESSION['logged_in'] = false;
        }

    }

    //Finally, return the result of the logged_in state for the user
    //return $_SESSION['logged_in'];
    echo $returnCount;
}

The desired result is that if COUNT(*) in sqlStmt is 0, then the $returnCount variable would also be 0. The SQL script is working fine as far as I can tell, but PHP is not correctly pulling the value of the COUNT(*) statement is what I think.


问:
How can I generate a Choropleth map without defined geographic areas in Python?
Choropleth maps seem to typically be aggregated into well-known geographic units with defined geographical borders (e.g., states, neighborhoods). Instead I want to make a map where the pseudo-color that is overlaid has continuous spatial variability. Specifically, I want a map of my city where the color represents the distance to the nearest hockey rink.

Are there tools that let you define the color of each continuous location throughout the map?

I'm new to working with geographic data.


问:
How to make semi-transparent form supporting gradient images
hello in my project i have this form:

The transparenctkey of the form is set to Wheat, so it's backcolor.
But when i try to create pictureboxes with semi transparent images, the transparency key doesnt work in the gradient.

Is there any way i can make the wheat color disappear completely?
I just want the image to be visible

This is my current progress:


问:
Writing a cfg file into SSH for csr generation (with subject alt names )
I want to write a cfg file into SSH for csr generation ... And I am using the command : echo "cfg text content" > home/user/name.cfg . The problem is it's not generating the file with proper indentation(it's coming as a single line )  How can I do that?

also i want to know is there any way to generate csr with subject alt names without using a config file


问:
how to implement setInterval in array
i have an array

const arr = ['A', 'B', 'C', 'D', 'E']

how do i make that get every item from arr in console.log after 2sec of delay

```<code>const arr = ['A', 'B', 'C', 'D', 'E']

const func = () => {
  arr.forEach(item => {
    setInterval(() => {
      console.log(item)
    }, 2000)
  })
}
</code>```

Thanks for respond

Title: how to implement setInterval in array

Body:
i have an array

const arr = ['A', 'B', 'C', 'D', 'E']

how do i make that get every item from arr in console.log after 2sec of delay

const arr = ['A', 'B', 'C', 'D', 'E']

const func = () => {
  arr.forEach(item => {
    setInterval(() => {
      console.log(item)
    }, 2000)
  })
}

Thanks for respond


问:
req.user is undefined when going to other routes after authenticating
I'm working on the authentication portion of my application and have some issues routing to a few protected pages I set up. After a user is signed into the application and is redirected to the dashboard I begin having my issue.  When the user attempts to access another route they are signed.  I'm not really sure where my issue is or how to resolve it. I have read past questions stating that it could be an issue with my serializeUser and deserializeUser but from what I am seeing I have implemented this portion of my code correctly. I would appreciate any type of help.

server.js

```<code>// passport config
require('./config/localAuth')(passport)
// google auth config
require('./config/googleAuth')(passport)
// twitter auth config
require('./config/twitterAuth')(passport)
// microsoft auth config
require('./config/microsoftAuth')(passport)

app.use(session({
    secret: process.env.secret,
    resave: false,
    saveUninitialized: false,
    store: MongoStore.create({
        mongoUrl: mongoURI,
        collectionName: 'mySession'
    }),
    cookie: {
        maxAge: 10800000
    }
}))
// authenticate the session
app.use(passport.authenticate('session'));

app.use(passport.initialize())
app.use(passport.session())

</code>```

googleAuth.js

```<code>const mongoose = require('mongoose')
const GoogleStrategy = require('passport-google-oauth20').Strategy
const User = require('../models/GoogleUser')

module.exports = passport => {
    passport.use(
        new GoogleStrategy({
            clientID: process.env.ClientID,
            clientSecret: process.env.ClientSecret,
            callbackURL: "/auth/google/callback"
        },

            async (accessToken, refreshToken, profile, done) => {
                const newUser = {
                    googleId: profile.id,
                    displayName: profile.displayName,
                    firstName: profile.name.givenName,
                    lastName: profile.name.familyName,
                    image: profile.photos[0].value,
                }

                try {
                    console.log(profile)
                    let user = await User.findOne({ googleId: profile.id })

                    if (user) {
                        return done(null, user)
                    } else {
                        user = await User.create(newUser)
                        console.log(user)
                        return done(null, user)
                    }
                } catch (err) {
                    console.error(err)
                }
            }
        )
    )
    passport.serializeUser((user, done) => {
        done(null, user.id)
    })

    passport.deserializeUser((id, done) => {
        googleUser.findById(id, (err, user) => done(err, user))
    })

}
</code>```

auth.js

```<code>
router.get('/google', passport.authenticate('google', { scope: ['profile'] }))

router.get('/google/callback',
    passport.authenticate('google', { failureRedirect: '/login' }),
    (req, res) => {
        res.redirect('/dashboard')
    }
)
</code>```

random route.js

```<code>const express = require('express')
const router = express.Router()
const lookbookController = require('../controllers/lookbookController')

router.get('/', lookbookController.goToLookbook)
router.get('/microsoft_login', lookbookController.goToLookbookMS)

module.exports = router
</code>```

lookbookController.js

```<code>module.exports = {
    goToLookbook: (req, res) => {
        if (req.isAuthenticated()) {
            res.render('signedIn/lookbook')
        } else {
            res.redirect('/login')
        }
    },
    goToLookbookMS: (req, res) => {
        if (req.isAuthenticated()) {
            res.render('signedInMS/lookbook')
        } else {
            res.redirect('/login')
        }
    }
}
</code>```

Body:
I'm working on the authentication portion of my application and have some issues routing to a few protected pages I set up. After a user is signed into the application and is redirected to the dashboard I begin having my issue.  When the user attempts to access another route they are signed.  I'm not really sure where my issue is or how to resolve it. I have read past questions stating that it could be an issue with my serializeUser and deserializeUser but from what I am seeing I have implemented this portion of my code correctly. I would appreciate any type of help.

server.js

// passport config
require('./config/localAuth')(passport)
// google auth config
require('./config/googleAuth')(passport)
// twitter auth config
require('./config/twitterAuth')(passport)
// microsoft auth config
require('./config/microsoftAuth')(passport)

app.use(session({
    secret: process.env.secret,
    resave: false,
    saveUninitialized: false,
    store: MongoStore.create({
        mongoUrl: mongoURI,
        collectionName: 'mySession'
    }),
    cookie: {
        maxAge: 10800000
    }
}))
// authenticate the session
app.use(passport.authenticate('session'));

app.use(passport.initialize())
app.use(passport.session())

googleAuth.js

const mongoose = require('mongoose')
const GoogleStrategy = require('passport-google-oauth20').Strategy
const User = require('../models/GoogleUser')

module.exports = passport => {
    passport.use(
        new GoogleStrategy({
            clientID: process.env.ClientID,
            clientSecret: process.env.ClientSecret,
            callbackURL: "/auth/google/callback"
        },

            async (accessToken, refreshToken, profile, done) => {
                const newUser = {
                    googleId: profile.id,
                    displayName: profile.displayName,
                    firstName: profile.name.givenName,
                    lastName: profile.name.familyName,
                    image: profile.photos[0].value,
                }

                try {
                    console.log(profile)
                    let user = await User.findOne({ googleId: profile.id })

                    if (user) {
                        return done(null, user)
                    } else {
                        user = await User.create(newUser)
                        console.log(user)
                        return done(null, user)
                    }
                } catch (err) {
                    console.error(err)
                }
            }
        )
    )
    passport.serializeUser((user, done) => {
        done(null, user.id)
    })

    passport.deserializeUser((id, done) => {
        googleUser.findById(id, (err, user) => done(err, user))
    })

}

auth.js

router.get('/google', passport.authenticate('google', { scope: ['profile'] }))

router.get('/google/callback',
    passport.authenticate('google', { failureRedirect: '/login' }),
    (req, res) => {
        res.redirect('/dashboard')
    }
)

random route.js

const express = require('express')
const router = express.Router()
const lookbookController = require('../controllers/lookbookController')

router.get('/', lookbookController.goToLookbook)
router.get('/microsoft_login', lookbookController.goToLookbookMS)

module.exports = router

lookbookController.js

module.exports = {
    goToLookbook: (req, res) => {
        if (req.isAuthenticated()) {
            res.render('signedIn/lookbook')
        } else {
            res.redirect('/login')
        }
    },
    goToLookbookMS: (req, res) => {
        if (req.isAuthenticated()) {
            res.render('signedInMS/lookbook')
        } else {
            res.redirect('/login')
        }
    }
}


问:
std::filesystem::directory_iterator fails with cyrillic letters
I am trying to create a file retriever. It works fine so far, except for the fact that it quits if e.g. Cyrillic characters appear in the file or directory name. In the C++ description of directory_iterator, I didn't find any hints about this. I am puzzled by this, especially since the Windows OS has no difficulties with Cyrillic characters, and I did not find any hints in the corresponding cppreference docs. What's the issue? Which keywords do I have to deal with?

```<code>/** C++17 boost-less fileSubDirIteration, core from
https://www.cppstories.com/2019/04/dir-iterate/  */

/** mandatory */
#include <filesystem>
#include <fstream>
#include <stdio.h>
namespace fs = std::filesystem;
std::string dirList[100];
std::ofstream fp;
void DisplayPath(const fs::path&, int);

int main(int argc,char* argv[])
{
    if (argc < 3) { printf("fSDI.exe <startPath> <outFile>\n"); exit(0); }
    const fs::path toRetrieve(argv[1]);
    std::string out(argv[2]);
    fp.open(out, std::ios::out);
    fp << "retrieve: " << toRetrieve << std::endl;
    dirList[0] = fs::absolute(toRetrieve).string();
    DisplayPath(toRetrieve,0);
    fp.close();
}

void DisplayPath(const fs::path& pathToScan,int lv = 0)
{
    for (const auto& entry : fs::directory_iterator(pathToScan))
    {
        const auto file = entry.path().filename().string();
        if (entry.is_directory())
        {
            fp << "[" <<  entry.path().filename().string() << "]" << std::endl;
            dirList[lv+1] = entry.path().filename().string();
            DisplayPath(entry, lv + 1);
        }
        else if (entry.is_regular_file())
        {
            std::string fullPath;
            fullPath += dirList[0];
            if (!(dirList[0].compare(2, 1, "\\", 0, 1) == 0 && dirList[0].size() == 3))
                fullPath += "\\";
            for(int i=1;i<=lv;i++) fullPath += (dirList[i] + "\\" );
            fp << " " << fullPath << file << std::endl;
        }
        else;
    }
}
</code>```

Body:
I am trying to create a file retriever. It works fine so far, except for the fact that it quits if e.g. Cyrillic characters appear in the file or directory name. In the C++ description of directory_iterator, I didn't find any hints about this. I am puzzled by this, especially since the Windows OS has no difficulties with Cyrillic characters, and I did not find any hints in the corresponding cppreference docs. What's the issue? Which keywords do I have to deal with?

/** C++17 boost-less fileSubDirIteration, core from
https://www.cppstories.com/2019/04/dir-iterate/  */

/** mandatory */
#include <filesystem>
#include <fstream>
#include <stdio.h>
namespace fs = std::filesystem;
std::string dirList[100];
std::ofstream fp;
void DisplayPath(const fs::path&, int);

int main(int argc,char* argv[])
{
    if (argc < 3) { printf("fSDI.exe <startPath> <outFile>\n"); exit(0); }
    const fs::path toRetrieve(argv[1]);
    std::string out(argv[2]);
    fp.open(out, std::ios::out);
    fp << "retrieve: " << toRetrieve << std::endl;
    dirList[0] = fs::absolute(toRetrieve).string();
    DisplayPath(toRetrieve,0);
    fp.close();
}

void DisplayPath(const fs::path& pathToScan,int lv = 0)
{
    for (const auto& entry : fs::directory_iterator(pathToScan))
    {
        const auto file = entry.path().filename().string();
        if (entry.is_directory())
        {
            fp << "[" <<  entry.path().filename().string() << "]" << std::endl;
            dirList[lv+1] = entry.path().filename().string();
            DisplayPath(entry, lv + 1);
        }
        else if (entry.is_regular_file())
        {
            std::string fullPath;
            fullPath += dirList[0];
            if (!(dirList[0].compare(2, 1, "\\", 0, 1) == 0 && dirList[0].size() == 3))
                fullPath += "\\";
            for(int i=1;i<=lv;i++) fullPath += (dirList[i] + "\\" );
            fp << " " << fullPath << file << std::endl;
        }
        else;
    }
}


问:
Not giving the input labels while testing a CVAE network
I have succesfully trained a CVAE(Conditional variational autoencoder) where i am feeding the input labels at both the encoder and decoder end

My Encoder and Decoder model looks something like this

```<code>###Encoder###

input_img = Input(shape=original_dim, name='Inputs')
y_labels = Input(shape=label_shape, name='class_labels')
t = concatenate([input_img, y_labels], name='concatenate-1')

x = Dense(intermediate_dim, activation='relu')(t)
x = Dense(intermediate_dim, activation='relu')(x)
x = Dense(512, activation='relu')(x)
x = Dense(256, activation='relu')(x)
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)
</code>```
```<code>###Decoder###
z = Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])
decoder_input = Input(K.int_shape(z)[1:])
x = concatenate([decoder_input, y_labels])
x = Dense(256, activation='relu')(x)
x = Dense(512, activation='relu')(x)
x = Dense(intermediate_dim, activation='relu')(x)
x = Dense(intermediate_dim, activation='relu')(x)
outputs = Dense(image_size, activation='sigmoid')(x)
</code>```

During Inference i am calling the encoder and Decoder like this

```<code>encoder = Model([input_img, y_labels], z_mean)
X_valid_encoded = encoder.predict(X_test ,batch_size=batch_size)
</code>```
```<code>decoder = Model([decoder_input, y_labels], outputs)
z_decoded = decoder([z, y_labels])
</code>```

As can be seen from the encoder model information i have to pass the y_lables to get proper output from the encoder as i have concatenated the y_lables at the input of the encoder.

My question, is there any way in which i pass only the input image and not the y_labels to the encoder. As i dont have the label information during testing phase. I have tried by setting y_labels to None but it is not working.

Any kind of help would be greatly appreciated.

Thank You

Body:
I have succesfully trained a CVAE(Conditional variational autoencoder) where i am feeding the input labels at both the encoder and decoder end

My Encoder and Decoder model looks something like this

###Encoder###

input_img = Input(shape=original_dim, name='Inputs')
y_labels = Input(shape=label_shape, name='class_labels')
t = concatenate([input_img, y_labels], name='concatenate-1')

x = Dense(intermediate_dim, activation='relu')(t)
x = Dense(intermediate_dim, activation='relu')(x)
x = Dense(512, activation='relu')(x)
x = Dense(256, activation='relu')(x)
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)

###Decoder###
z = Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])
decoder_input = Input(K.int_shape(z)[1:])
x = concatenate([decoder_input, y_labels])
x = Dense(256, activation='relu')(x)
x = Dense(512, activation='relu')(x)
x = Dense(intermediate_dim, activation='relu')(x)
x = Dense(intermediate_dim, activation='relu')(x)
outputs = Dense(image_size, activation='sigmoid')(x)

During Inference i am calling the encoder and Decoder like this

encoder = Model([input_img, y_labels], z_mean)
X_valid_encoded = encoder.predict(X_test ,batch_size=batch_size)

decoder = Model([decoder_input, y_labels], outputs)
z_decoded = decoder([z, y_labels])

As can be seen from the encoder model information i have to pass the y_lables to get proper output from the encoder as i have concatenated the y_lables at the input of the encoder.

My question, is there any way in which i pass only the input image and not the y_labels to the encoder. As i dont have the label information during testing phase. I have tried by setting y_labels to None but it is not working.

Any kind of help would be greatly appreciated.

Thank You


问:
Parameterless constructor always invoked. Even if parameter is passed during class instantiation
I have a class Array2DBool. I am trying to change it's values on initialisation. I've tried different approaches but making a constructor for it seems to be the best one so far. Tried testing different parameters: strings, bools and ints. But all leads to the same result - when instantiating I always get "Here" in console and the second constructor just never gets invoked.

```<code>namespace Array2DEditor
{
    [System.Serializable]
    public class Array2DBool : Array2D<bool>
    {
        public Array2DBool () {
            Debug.Log("Here");
        }

        public Array2DBool (int gridSizeInt) {
            Debug.Log("Finally Here");
            GridSize = Vector2Int.one * gridSizeInt;
        }
    }
}

// This line is used in another file.
public Array2DBool exits = new Array2DBool(3);
</code>```

Also, Array2D is an abstract class but it does not have any constructors. So I believe it does no matter since whatever happens there will not affect the constructors here.

Body:
I have a class Array2DBool. I am trying to change it's values on initialisation. I've tried different approaches but making a constructor for it seems to be the best one so far. Tried testing different parameters: strings, bools and ints. But all leads to the same result - when instantiating I always get "Here" in console and the second constructor just never gets invoked.

namespace Array2DEditor
{
    [System.Serializable]
    public class Array2DBool : Array2D<bool>
    {
        public Array2DBool () {
            Debug.Log("Here");
        }

        public Array2DBool (int gridSizeInt) {
            Debug.Log("Finally Here");
            GridSize = Vector2Int.one * gridSizeInt;
        }
    }
}

// This line is used in another file.
public Array2DBool exits = new Array2DBool(3);

Also, Array2D is an abstract class but it does not have any constructors. So I believe it does no matter since whatever happens there will not affect the constructors here.