问:
Serilog Filter Expression is not working to exclude the given endpoint logs
I've a healthcheck endpoint in my .NetCore(2.2) WebAPI project for which I don't want to generate and write any logs. I'm writing the logs to WindowsEventLog. For that, I'm using a separate config file just for the logging purpose which I'm loading in my startup.

This is the endpoint that I've in the controller for healthcheck:

```<code>[Route("healthcheck")]
[AllowAnonymous]
public IActionResult Get()
{
    return Ok("");
}
</code>```

This is how I'm loading the config file (SeriLogSettings.json) that I created for holding my Serilog configuration:

```<code> public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
               .AddJsonFile("SeriLogSettings.json", optional: false)
               .AddEnvironmentVariables();

            Configuration = builder.Build();
        }
</code>```

And this is how my SerilogSettings.json looks like:

```<code>{
  "Serilog": {
    "Using": [ "Serilog.Settings.Configuration", "Serilog.Sinks.EventLog" ],
    "Filter": [
      {
        "Name": "ByExcluding",
        "Args": {
          "expression": "EndsWith(RequestPath, '%/healthcheck')"
        }
      }
    ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext" ],
    "WriteTo": [
      {
        "Name": "EventLog",
        "Args": {
          "source": "WebAPI",
          "logName": "Application",
          "managedEventSource": true
        }
      }
    ],
    "Properties": {
      "Application": "ApplicationAPI"
    }
  }
}
</code>```

Despite using the ByExcluding expression to exclude the logs for /healthcheck endpoint, I'm getting the logs in the WindowsEventLog.
I'm not able to fix why this is happening and not sure what am I doing wrong?

答:
may be simple -
"EndsWith(RequestPath, '/healthcheck')" should become
"StartsWith(RequestPath, '/healthcheck')"
Because your requst may by
/healthcheck/live, /healthcheck/ready

Or more puzzle situation
You did not show packages for your project.
Maybe you are using package Serilog.Expressions instead of package Serilog.Filters.Expressions(deprecated)

Those packages use different formats for string 'expression'

```<code>Old
"expression": "EndsWith(RequestPath, '/healthcheck')"
New
"expression": "RequestPath like '/healthcheck%')"
</code>```

The documentation

Body:
I've a healthcheck endpoint in my .NetCore(2.2) WebAPI project for which I don't want to generate and write any logs. I'm writing the logs to WindowsEventLog. For that, I'm using a separate config file just for the logging purpose which I'm loading in my startup.

This is the endpoint that I've in the controller for healthcheck:

[Route("healthcheck")]
[AllowAnonymous]
public IActionResult Get()
{
    return Ok("");
}

This is how I'm loading the config file (SeriLogSettings.json) that I created for holding my Serilog configuration:

 public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
               .AddJsonFile("SeriLogSettings.json", optional: false)
               .AddEnvironmentVariables();

            Configuration = builder.Build();
        }

And this is how my SerilogSettings.json looks like:

{
  "Serilog": {
    "Using": [ "Serilog.Settings.Configuration", "Serilog.Sinks.EventLog" ],
    "Filter": [
      {
        "Name": "ByExcluding",
        "Args": {
          "expression": "EndsWith(RequestPath, '%/healthcheck')"
        }
      }
    ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext" ],
    "WriteTo": [
      {
        "Name": "EventLog",
        "Args": {
          "source": "WebAPI",
          "logName": "Application",
          "managedEventSource": true
        }
      }
    ],
    "Properties": {
      "Application": "ApplicationAPI"
    }
  }
}

Despite using the ByExcluding expression to exclude the logs for /healthcheck endpoint, I'm getting the logs in the WindowsEventLog.
I'm not able to fix why this is happening and not sure what am I doing wrong?

Body:
may be simple -
"EndsWith(RequestPath, '/healthcheck')" should become
"StartsWith(RequestPath, '/healthcheck')"
Because your requst may by
/healthcheck/live, /healthcheck/ready

Or more puzzle situation
You did not show packages for your project.
Maybe you are using package Serilog.Expressions instead of package Serilog.Filters.Expressions(deprecated)

Those packages use different formats for string 'expression'

Old
"expression": "EndsWith(RequestPath, '/healthcheck')"
New
"expression": "RequestPath like '/healthcheck%')"

The documentation


来源: stackexchange

问:
React useState: Always rerenders when state is an array
I have a React app where I have an array as a state. Then I have a timer that reads an array. Now I want to rerender only if there is a difference between the array I read and my state array.

But when I do as in the following code example it always rerenders. If I instead have a state with just a number, and set the same number, it will not rerender. Is there a way to achieve the same thing with an array? Or do I have to compare the arrays first, and then call setMeasData only if they are different?

A second question is why the rerenders variable is always increased by two the code sandbox? This does not happen in my real application, so that is not a big deal. Just curious.

Thanks!

```<code>let rerenders = 0;

function getMeas() {
  return [{ name: "Measurement 1", value: 0 }];
}

export default function App() {
  const [measData, setMeasData] = React.useState([
    { name: "Measurement 1", value: 0 }
  ]);

  rerenders++;

  console.log("Rerenders: " + rerenders);

  React.useEffect(() => {
    console.log("In useEffect");
    const timer = setInterval(() => {
      console.log("Timer triggered");
      let newMeasData = getMeas();
      // Want this to trigger rerender only if newMeasData is not the same as measData
      setMeasData(newMeasData);
    }, 10 * 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>No of rerenders: {rerenders} </h2>
      <p>
        {" "}
        {measData[0].name}: {measData[0].value}{" "}
      </p>
    </div>
  );
}
</code>```

Code sandbox

答:
That's because on every interval you're setting a new value to the setMeasData and you can check this by using this operation:

```<code>console.log(getMeas() === getMeas()) // which always logs false
</code>```

everytime getMeas function is called it will return a new instance and in React when the state is changed we're going to have a rerender

if you want to have just something to set the initialValue you could do so by storing the value in a variable like below so you're instance always will be the same and you won't have extera rerenders:

```<code>let rerenders = 0;

const initialValue = [{ name: "Measurement 1", value: 0 }];

export default function App() {
  const [measData, setMeasData] = React.useState(initialValue);

  rerenders++;

  console.log("Rerenders: " + rerenders);

  React.useEffect(() => {
    console.log("In useEffect");
    const timer = setInterval(() => {
      console.log("Timer triggered");
      let newMeasData = initialValue;
      // Want this to trigger rerender only if newMeasData is not the same as measData
      setMeasData(newMeasData);
    }, 1 * 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <div className="App">
      <h1>Example</h1>
      <h2>
        No of rerenders: {rerenders} {`${initialValue === initialValue}`}{" "}
      </h2>
      <p>
        {" "}
        {measData[0].name}: {measData[0].value}{" "}
      </p>
    </div>
  );
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a React app where I have an array as a state. Then I have a timer that reads an array. Now I want to rerender only if there is a difference between the array I read and my state array.

But when I do as in the following code example it always rerenders. If I instead have a state with just a number, and set the same number, it will not rerender. Is there a way to achieve the same thing with an array? Or do I have to compare the arrays first, and then call setMeasData only if they are different?

A second question is why the rerenders variable is always increased by two the code sandbox? This does not happen in my real application, so that is not a big deal. Just curious.

Thanks!

let rerenders = 0;

function getMeas() {
  return [{ name: "Measurement 1", value: 0 }];
}

export default function App() {
  const [measData, setMeasData] = React.useState([
    { name: "Measurement 1", value: 0 }
  ]);

  rerenders++;

  console.log("Rerenders: " + rerenders);

  React.useEffect(() => {
    console.log("In useEffect");
    const timer = setInterval(() => {
      console.log("Timer triggered");
      let newMeasData = getMeas();
      // Want this to trigger rerender only if newMeasData is not the same as measData
      setMeasData(newMeasData);
    }, 10 * 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  return (

Hello CodeSandbox

No of rerenders: {rerenders}

        {" "}
        {measData[0].name}: {measData[0].value}{" "}

  );
}

Code sandbox

Body:
That's because on every interval you're setting a new value to the setMeasData and you can check this by using this operation:

console.log(getMeas() === getMeas()) // which always logs false

everytime getMeas function is called it will return a new instance and in React when the state is changed we're going to have a rerender

if you want to have just something to set the initialValue you could do so by storing the value in a variable like below so you're instance always will be the same and you won't have extera rerenders:

let rerenders = 0;

const initialValue = [{ name: "Measurement 1", value: 0 }];

export default function App() {
  const [measData, setMeasData] = React.useState(initialValue);

  rerenders++;

  console.log("Rerenders: " + rerenders);

  React.useEffect(() => {
    console.log("In useEffect");
    const timer = setInterval(() => {
      console.log("Timer triggered");
      let newMeasData = initialValue;
      // Want this to trigger rerender only if newMeasData is not the same as measData
      setMeasData(newMeasData);
    }, 1 * 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <div className="App">
      <h1>Example</h1>
      <h2>
        No of rerenders: {rerenders} {`${initialValue === initialValue}`}{" "}
      </h2>
      <p>
        {" "}
        {measData[0].name}: {measData[0].value}{" "}
      </p>
    </div>
  );
}


问:
Specify fallback font sizes in CSS?
Is there any way to specify different font sizes for fallback fonts in CSS? I want to do something like this (which obviously does not work):

```
div {
    font-family: "Arial Narrow", Arial, Helvetica, sans-serif;
    font-size: 20px, 18px, 18px, 18px;
}
```

The idea being that Arial Narrow would display at 20px if the user has it installed; if not, the browser would fall back to Arial at 18px, then Helvetica at 18px, etc.

Or, could I use JS to achieve a similar effect?

答:
The @font-face size-adjust descriptor in CSS Fonts Module Level 5 "defines a multiplier for glyph outlines and metrics associated with this font, to allow the author to harmonize the designs of various fonts when rendered at the same font-size". css-fonts-5 is a Working Draft (as at Feb 2022), but many browsers have support 'size-adjust' since late 2021.

In the example below, size-adjust is used to make 'courier-new 12pt' and 'Consolas 12pt' render with near-identical width; normally 'Courier New 11pt' is required to match the width of 'Consolas 12pt'.

@font-face {
  font-family: courier-new;
  src: local(Courier New);
  size-adjust: 91.6%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p style="font-family: 'Courier New'; font-size: 11pt">ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 abcdefghijklmnopqrstuvwxyz</p>
<p style="font-family: courier-new; font-size: 12pt">ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 abcdefghijklmnopqrstuvwxyz</p>
<p style="font-family: Consolas; font-size: 12pt">ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 abcdefghijklmnopqrstuvwxyz</p></code>```

ContentLicense: CC BY-SA 3.0

Title: Specify fallback font sizes in CSS?

Body:
Is there any way to specify different font sizes for fallback fonts in CSS? I want to do something like this (which obviously does not work):

div {
    font-family: "Arial Narrow", Arial, Helvetica, sans-serif;
    font-size: 20px, 18px, 18px, 18px;
}

The idea being that Arial Narrow would display at 20px if the user has it installed; if not, the browser would fall back to Arial at 18px, then Helvetica at 18px, etc.

Or, could I use JS to achieve a similar effect?

Body:
The @font-face size-adjust descriptor in CSS Fonts Module Level 5 "defines a multiplier for glyph outlines and metrics associated with this font, to allow the author to harmonize the designs of various fonts when rendered at the same font-size". css-fonts-5 is a Working Draft (as at Feb 2022), but many browsers have support 'size-adjust' since late 2021.

In the example below, size-adjust is used to make 'courier-new 12pt' and 'Consolas 12pt' render with near-identical width; normally 'Courier New 11pt' is required to match the width of 'Consolas 12pt'.

@font-face {
  font-family: courier-new;
  src: local(Courier New);
  size-adjust: 91.6%
}

<p style="font-family: 'Courier New'; font-size: 11pt">ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 abcdefghijklmnopqrstuvwxyz</p>
<p style="font-family: courier-new; font-size: 12pt">ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 abcdefghijklmnopqrstuvwxyz</p>
<p style="font-family: Consolas; font-size: 12pt">ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 abcdefghijklmnopqrstuvwxyz</p>


问:
Calculate Euclidean distance between multiple pairs of points in dataframe in R
I'm trying to calculate the Euclidean distance between pairs of points in a dataframe in R, and there's an ID for each pair:

```<code>ID <- sample(1:10, 10, replace=FALSE)
P <- runif(10, min=1, max=3)
S <- runif(10, min=1, max=3)

testdf <- data.frame(ID, P, S)

</code>```

I found several ways to calculate the Euclidean distance in R, but I'm either getting an error, returning only 1 value (so it's computing the distance between the entire vector), or I end up with a matrix when all I need is a 4th column with the distance between each pair (columns 'P' and 'S.') I'm a bit confused by matrices so I'm not sure how to work with that result.

Tried making a function and applying it to the 2 columns but I get an error:

```<code>testdf$V <- apply(testdf[ , c('P', 'S')], 1, function(P, S) sqrt(sum((P^2, S^2)))

 # Error in FUN(newX[, i], ...) : argument "S" is missing, with no default
</code>```

Then tried using the dist() function in the stats package but it only returns 1 value:
(Same problem if I follow the method here: https://www.statology.org/euclidean-distance-in-r/)

```<code>P <- testdf$P
S <- testdf$S
testProbMatrix <- rbind(P, S)
stats::dist(testProbMatrix, method = "euclidean")
# returns only 1 distance
</code>```

Returns a matrix
(Here's a nice explanation why: Calculate the distances between pairs of points in r)

```<code>stats::dist(cbind(P, S), method = "euclidean")
</code>```

But I'm confused how to pull the distances out of the matrix and attach them to the correct ID for each pair of points. I don't understand why I have to make a matrix instead of just applying the function to the dataframe - matrices have always confused me.
I think this is the same question as here (Finding euclidean distance between all pair of points) but for R instead of Python

Thanks for the help!

答:
Try this out if you would just like to add another column to your dataframe</p>
```<code>testdf$distance <- sqrt((P^2 + S^2))
</code>```

Body:
I'm trying to calculate the Euclidean distance between pairs of points in a dataframe in R, and there's an ID for each pair:

ID <- sample(1:10, 10, replace=FALSE)
P <- runif(10, min=1, max=3)
S <- runif(10, min=1, max=3)

testdf <- data.frame(ID, P, S)

I found several ways to calculate the Euclidean distance in R, but I'm either getting an error, returning only 1 value (so it's computing the distance between the entire vector), or I end up with a matrix when all I need is a 4th column with the distance between each pair (columns 'P' and 'S.') I'm a bit confused by matrices so I'm not sure how to work with that result.

Tried making a function and applying it to the 2 columns but I get an error:

testdf$V <- apply(testdf[ , c('P', 'S')], 1, function(P, S) sqrt(sum((P^2, S^2)))

 # Error in FUN(newX[, i], ...) : argument "S" is missing, with no default

Then tried using the dist() function in the stats package but it only returns 1 value:
(Same problem if I follow the method here: https://www.statology.org/euclidean-distance-in-r/)

P <- testdf$P
S <- testdf$S
testProbMatrix <- rbind(P, S)
stats::dist(testProbMatrix, method = "euclidean")
# returns only 1 distance

Returns a matrix
(Here's a nice explanation why: Calculate the distances between pairs of points in r)

stats::dist(cbind(P, S), method = "euclidean")

But I'm confused how to pull the distances out of the matrix and attach them to the correct ID for each pair of points. I don't understand why I have to make a matrix instead of just applying the function to the dataframe - matrices have always confused me.
I think this is the same question as here (Finding euclidean distance between all pair of points) but for R instead of Python

Thanks for the help!

Body:
Try this out if you would just like to add another column to your dataframe

testdf$distance <- sqrt((P^2 + S^2))


问:
Susy: positioning of element in root context
This is my first time using Susy. I really like what I'm seeing in the docs / tutorials, but I've encountered some unexpected results with some of my first layout attempts.

Version info:

```<code>>gem install compass-susy-plugin
Successfully installed sass-3.1.2
Successfully installed chunky_png-1.2.0
Successfully installed fssm-0.2.7
Successfully installed compass-0.11.1
Successfully installed compass-susy-plugin-0.9

>ruby --version
ruby 1.9.2p136 (2010-12-25 revision 30365) [x86_64-darwin10.5.0]
</code>```

The image below shows the result I'm getting using the tutorial html and screen.scss verbatim:

As you can see, inspecting the h1 element shows it sitting just off the grid. Is this normal?

答:
If I slowly expand the browser window in Chrome vs Firefox, the grid and text jump around more in Chrome than Firefox.  It appears Firefox is more precise with the layout (which may impose a rendering speed penalty).

In Firefox, everything always lines up perfectly and moves together -- the text areas and the grid -- as I resize.  In Chrome, I can see the footer text moving at different times vs the article text vs the grid vs etc., as I resize.

Here's an example where the text and the grid were off by quite a few pixels in Chrome:

Body:
This is my first time using Susy. I really like what I'm seeing in the docs / tutorials, but I've encountered some unexpected results with some of my first layout attempts.

Version info:

>gem install compass-susy-plugin
Successfully installed sass-3.1.2
Successfully installed chunky_png-1.2.0
Successfully installed fssm-0.2.7
Successfully installed compass-0.11.1
Successfully installed compass-susy-plugin-0.9

>ruby --version
ruby 1.9.2p136 (2010-12-25 revision 30365) [x86_64-darwin10.5.0]

The image below shows the result I'm getting using the tutorial html and screen.scss verbatim:

As you can see, inspecting the h1 element shows it sitting just off the grid. Is this normal?


问:
not able to navigate between events of a object with dropdown box like visual studio 2019 in VS 2022 >
I am not sure did they change it the way we can do it or is there any simpler way or they actually removed the option and limited us to use code instead

in vs 2019 if we double click the button we directly went to click event of a button and then from the upper right dropdown box we can easily move to any other event of a current object like double click or mouse over etc which automatically created the event handling SUB
but I am not able to do it in the VS 2022 so what happened with it?
as you can see in the attached images

答:
Go to Options->Text Editor->(your language) and enable "Navigation Bar".

Previously answered here:
Visual Studio window which shows list of methods


问:
How to remove 1 item in a list in Django?
This is the HTML code:

```<code>             <div class="col-sm-2 col-md-2 col-lg-2 col-xl-2 text-center">
                {% if show_follow_button %}
                    <button id="follow-btn" class="btn btn-primary" type="button" name="follow"
                        {% if already_follow %}disabled{% endif %}>
                        Follow
                    </button>
                    <button id="unfollow-btn" class="btn btn-primary" type="button" name="unFollow"
                        {% if already_unFollow %}disabled{% endif %}>
                        Unfollow
                    </button>
                {% endif %}
            </div>
</code>```

So I have 1 button each for following and unfollowing a user.
I'm trying to make the unfollow button remove that specific user in the list of users I've already followed.

In my views.py I have this code in 1 of my methods:

```<code>    show_follow_button = False
    if user_id is not None and user_id != request.user.id:
        show_follow_button = True

    already_follow = False
    already_unFollow = False
    if show_follow_button:
        already_follow = user_id in [x.user.id for x in UserExtended.objects.get(user__id=request.user.id).following.all()]
        already_unFollow = user_id in [x.user.id for x in UserExtended.objects.get(user__id=request.user.id).following.all().delete()]
</code>```

I'm having a hard time making the last line of code work HAHA. Am confused. I don't know how to remove 1 loool. Help

答:
You can remove a object from the list by doing:
UserExtended.objects.get(user__id=request.user.id).following.remove(user.id)

Body:
This is the HTML code:

                {% if show_follow_button %}
                    <button id="follow-btn" class="btn btn-primary" type="button" name="follow"
                        {% if already_follow %}disabled{% endif %}>
                        Follow
                    </button>
                    <button id="unfollow-btn" class="btn btn-primary" type="button" name="unFollow"
                        {% if already_unFollow %}disabled{% endif %}>
                        Unfollow
                    </button>
                {% endif %}

So I have 1 button each for following and unfollowing a user.
I'm trying to make the unfollow button remove that specific user in the list of users I've already followed.

In my views.py I have this code in 1 of my methods:

    show_follow_button = False
    if user_id is not None and user_id != request.user.id:
        show_follow_button = True

    already_follow = False
    already_unFollow = False
    if show_follow_button:
        already_follow = user_id in [x.user.id for x in UserExtended.objects.get(user__id=request.user.id).following.all()]
        already_unFollow = user_id in [x.user.id for x in UserExtended.objects.get(user__id=request.user.id).following.all().delete()]

I'm having a hard time making the last line of code work HAHA. Am confused. I don't know how to remove 1 loool. Help


问:
How to fix position image on another image
I have the following code (also pasted below), where I want to make a layout of two columns. In the first one I am putting two images, and in the second displaying some text.

In the first column, I want to have the first image with width:70% and the second one with position:absolute on it. The final result should be like this

As you see the second image partially located in first one in every screens above to 768px.

I can partially locate second image on first one, but that is not dynamic, if you change screen dimensions you can see how that collapse.

But no matter how hard I try, I can not achieve this result.

.checkoutWrapper {
  display: grid;
  grid-template-columns: 50% 50%;
}

.coverIMGLast {
  width: 70%;
  height: 100vh;
}

/* this .phone class should be dynamically  located partially on first image */
.phone {
  position: absolute;
  height: 90%;
  top: 5%;
  bottom: 5%;
  margin-left: 18%;
}

.CheckoutProcess {
  padding: 5.8rem 6.4rem;
}

.someContent {
  border: 1px solid red;
}

/* removing for demo purposes
@media screen and (max-width: 768px) {
  .checkoutWrapper {
    display: grid;
    grid-template-columns: 100%;
  }
  img {
    display: none;
  }
  .CheckoutProcess {
    padding: 0;
  }
}
*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="checkoutWrapper">
  <img src="https://via.placeholder.com/300" class="coverIMGLast" />
  <img src="https://via.placeholder.com/300/ff0000" class="phone" />

  <div class="CheckoutProcess">
    <Content />
  </div>
</div></code>```

答:
You can use transform and aspect-ratio to achieve the result:

.checkoutWrapper {
  display: grid;
  grid-template-columns: 30% 70%;
  height: 100vh;
}

.left {
  background-color: #baafa0;
  position: relative;

  background-image: url('https://picsum.photos/id/1028/200/300');
  background-size: cover;
}

.phone {
  height: 60%;
  aspect-ratio: 1/2;

  position: absolute;
  top: 50%;
  left: 100%;
  transform: translate(-50%, -50%);

  border-radius: 15%;
}

.right {
  padding-left: calc(15vh + 1rem);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="checkoutWrapper">
  <div class="left">
    <img class="phone" src="https://via.placeholder.com/300/444" />
  </div>
  <div class="right CheckoutProcess">
    <Content>
      <h1>Check Out</h1>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Assumenda consectetur ducimus officiis dicta vero distinctio odio sit explicabo illum dolorem quasi facilis repellendus sapiente fuga corporis, iure dolore ad, quis quisquam? Dolorum nostrum, veritatis
        molestiae culpa maiores exercitationem cumque qui harum, unde est ratione doloremque necessitatibus et numquam itaque neque!
      </p>
    </Content>
  </div>
</div></code>```

Body:
I have the following code (also pasted below), where I want to make a layout of two columns. In the first one I am putting two images, and in the second displaying some text.

In the first column, I want to have the first image with width:70% and the second one with position:absolute on it. The final result should be like this

As you see the second image partially located in first one in every screens above to 768px.

I can partially locate second image on first one, but that is not dynamic, if you change screen dimensions you can see how that collapse.

But no matter how hard I try, I can not achieve this result.

.checkoutWrapper {
  display: grid;
  grid-template-columns: 50% 50%;
}

.coverIMGLast {
  width: 70%;
  height: 100vh;
}

/* this .phone class should be dynamically  located partially on first image */
.phone {
  position: absolute;
  height: 90%;
  top: 5%;
  bottom: 5%;
  margin-left: 18%;
}

.CheckoutProcess {
  padding: 5.8rem 6.4rem;
}

.someContent {
  border: 1px solid red;
}

/* removing for demo purposes
@media screen and (max-width: 768px) {
  .checkoutWrapper {
    display: grid;
    grid-template-columns: 100%;
  }
  img {
    display: none;
  }
  .CheckoutProcess {
    padding: 0;
  }
}
*/

    <Content />

Body:
You can use transform and aspect-ratio to achieve the result:

.checkoutWrapper {
  display: grid;
  grid-template-columns: 30% 70%;
  height: 100vh;
}

.left {
  background-color: #baafa0;
  position: relative;

  background-image: url('https://picsum.photos/id/1028/200/300');
  background-size: cover;
}

.phone {
  height: 60%;
  aspect-ratio: 1/2;

  position: absolute;
  top: 50%;
  left: 100%;
  transform: translate(-50%, -50%);

  border-radius: 15%;
}

.right {
  padding-left: calc(15vh + 1rem);
}

<div class="checkoutWrapper">
  <div class="left">
    <img class="phone" src="https://via.placeholder.com/300/444" />
  </div>
  <div class="right CheckoutProcess">
    <Content>
      <h1>Check Out</h1>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Assumenda consectetur ducimus officiis dicta vero distinctio odio sit explicabo illum dolorem quasi facilis repellendus sapiente fuga corporis, iure dolore ad, quis quisquam? Dolorum nostrum, veritatis
        molestiae culpa maiores exercitationem cumque qui harum, unde est ratione doloremque necessitatibus et numquam itaque neque!
      </p>
    </Content>
  </div>
</div>


问:
Cant find solution for angularx-social-login with LinkedIn login Support
I try to implement angular 10 application with linkedin login. But it can't support this.</p>

答:
```<code>Here I have provided a sample code for linked in login in angular for your reference.
App.module.ts
 import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { FormsModule } from '@angular/forms';
import { AuthComponent } from './auth/auth.component';
import { ReactiveFormsModule } from '@angular/forms';
import { SocialLoginModule, SocialAuthServiceConfig } from 'angularx-social-login';
import { GoogleLoginProvider } from 'angularx-social-login';
import { NavbarComponent } from './navbar/navbar.component';
import { MyChannelComponent } from './my-channel/my-channel.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AuthComponent,
    NavbarComponent,
    MyChannelComponent

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    SocialLoginModule
  ],
  providers: [
    {
      provide: 'SocialAuthServiceConfig',
      useValue: {
        autoLogin: false,
        providers: [
          {
            id: GoogleLoginProvider.PROVIDER_ID,
            provider: new GoogleLoginProvider(
              'client id'
            )
          },
           {
            id: LinkedinLoginProvider.PROVIDER_ID,
            provider: new LinkedinLoginProvider("1098828800522-m2ig6bieilc3tpqvmlcpdvrpvn86q4ks.apps.googleusercontent.com")
          },
        ]
      } as SocialAuthServiceConfig,
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Auth.ts:

```<code>    import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { GoogleLoginProvider, SocialAuthService, SocialUser } from 'angularx-social-login';
import { YoutubeService } from '../youtube.service';

@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.css']
})
export class AuthComponent implements OnInit {
  loginForm!: FormGroup;
  public socialUser!: SocialUser;
  public username:any;
  isLoggedin: boolean=false;
  subscription:any;

  constructor(private formBuilder: FormBuilder,
    private socialAuthService: SocialAuthService,private service:YoutubeService) { }

  ngOnInit(): void {
    this.loginForm = this.formBuilder.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });

    this.socialAuthService.authState.subscribe((user) => {
      this.socialUser = user;
      this.username=this.socialUser.firstName;
      this.isLoggedin = (user != null);
      console.log(this.socialUser);
      //this.GetChannel(this.username);
    });
  }

  loginWithGoogle(): void {
    this.socialAuthService.signIn(GoogleLoginProvider.PROVIDER_ID);
  }
loginWithGoogle(): void {
    this.socialAuthService.signIn(LinkedinLoginProvider.PROVIDER_ID);
  }

  logOut(): void {
    this.socialAuthService.signOut();
  }

}
</code>```

Body:
Here I have provided a sample code for linked in login in angular for your reference.
App.module.ts
 import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { FormsModule } from '@angular/forms';
import { AuthComponent } from './auth/auth.component';
import { ReactiveFormsModule } from '@angular/forms';
import { SocialLoginModule, SocialAuthServiceConfig } from 'angularx-social-login';
import { GoogleLoginProvider } from 'angularx-social-login';
import { NavbarComponent } from './navbar/navbar.component';
import { MyChannelComponent } from './my-channel/my-channel.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AuthComponent,
    NavbarComponent,
    MyChannelComponent

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    SocialLoginModule
  ],
  providers: [
    {
      provide: 'SocialAuthServiceConfig',
      useValue: {
        autoLogin: false,
        providers: [
          {
            id: GoogleLoginProvider.PROVIDER_ID,
            provider: new GoogleLoginProvider(
              'client id'
            )
          },
           {
            id: LinkedinLoginProvider.PROVIDER_ID,
            provider: new LinkedinLoginProvider("1098828800522-m2ig6bieilc3tpqvmlcpdvrpvn86q4ks.apps.googleusercontent.com")
          },
        ]
      } as SocialAuthServiceConfig,
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Auth.ts:

    import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { GoogleLoginProvider, SocialAuthService, SocialUser } from 'angularx-social-login';
import { YoutubeService } from '../youtube.service';

@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.css']
})
export class AuthComponent implements OnInit {
  loginForm!: FormGroup;
  public socialUser!: SocialUser;
  public username:any;
  isLoggedin: boolean=false;
  subscription:any;

  constructor(private formBuilder: FormBuilder,
    private socialAuthService: SocialAuthService,private service:YoutubeService) { }

  ngOnInit(): void {
    this.loginForm = this.formBuilder.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });

    this.socialAuthService.authState.subscribe((user) => {
      this.socialUser = user;
      this.username=this.socialUser.firstName;
      this.isLoggedin = (user != null);
      console.log(this.socialUser);
      //this.GetChannel(this.username);
    });
  }

  loginWithGoogle(): void {
    this.socialAuthService.signIn(GoogleLoginProvider.PROVIDER_ID);
  }
loginWithGoogle(): void {
    this.socialAuthService.signIn(LinkedinLoginProvider.PROVIDER_ID);
  }

  logOut(): void {
    this.socialAuthService.signOut();
  }

}


问:
GA Event tracking - Event being sent but not registered
I am doing an A/B/C-test at an e-commerce and I am trying to send an event tracking to Google Analytics depending on wich version is being used.
The JavaScript (with the event tracking code) is being triggered when the page is loaded. I can see in "Developer Tools -> Network" that the event tracking is being sent to Google Analytics, but it is not registrered there. I've been looking both at "Real-time -> Events" and "Behaviour -> Events -> Overview" and nothing seems to work.

This is the code for the event tracking I am using:

```<code>ga('send', {
  hitType: 'event',
  eventCategory: 'frameWithPoster',
  eventAction: 'Original',
  eventLabel: 'No frames'
});
</code>```

I've tried to change the "hitType" to "pageview" aswell and also tried to wrap it with a click event like so:

```<code>$("html").on("click", ".Knapp_Kop a", function() {
 ga('send', {
  hitType: 'event',
  eventCategory: 'frameWithPoster',
  eventAction: 'Original',
  eventLabel: 'No frames'
 });
})
</code>```

Does anyone know what I can be doing wrong?

答:
I hit this problem and found another reason, not mentioned elsewhere - event can be send but not registered if eventAction is EMPTY STRING.

In my case it was general method, that coalesced labels/ etc into empty strings and executed send via "ga('xxx.send', 'event', ea, eb, ec, ed);"
xhr request was properly generated with call, Tag Assystent addon properly count it (https://chrome.google.com/webstore/detail/tag-assistant-legacy-by-g/kejbdjndbnbjgmefkgdddjlbokphdefk/related), but nothing in GA realtime report was triggered.

After changing send to "ga('xxx.send', 'event', ea);" for empty action/label - it started to work as expected

Body:
I am doing an A/B/C-test at an e-commerce and I am trying to send an event tracking to Google Analytics depending on wich version is being used.
The JavaScript (with the event tracking code) is being triggered when the page is loaded. I can see in "Developer Tools -> Network" that the event tracking is being sent to Google Analytics, but it is not registrered there. I've been looking both at "Real-time -> Events" and "Behaviour -> Events -> Overview" and nothing seems to work.

This is the code for the event tracking I am using:

ga('send', {
  hitType: 'event',
  eventCategory: 'frameWithPoster',
  eventAction: 'Original',
  eventLabel: 'No frames'
});

I've tried to change the "hitType" to "pageview" aswell and also tried to wrap it with a click event like so:

$("html").on("click", ".Knapp_Kop a", function() {
 ga('send', {
  hitType: 'event',
  eventCategory: 'frameWithPoster',
  eventAction: 'Original',
  eventLabel: 'No frames'
 });
})

Does anyone know what I can be doing wrong?


问:
How to handle the deployment of microservices which listen to message queues
I have a microservice that listens on rabbit MQ for background tasks. Assume that each task takes around 1 minute to complete. During deployment when the service is restarted the processing is done twice sometimes because before restart the message is not acknowledged. How do you generally handle this scenario during deployment ??

One solution I can think of is adding a flag in DB and stop consuming messages and flipping the flag once done.

答:
In the stop for deployment case, letting the queue drain before actually stopping the service is likely to be viable:

Send a signal to the service that it will be redeployed soon

Service stops consuming messages from MQ

In-flight tasks are completed and acknowledged

When all in-flight tasks are completed, service stops (note that this delay may be arbitrarily long)

Deploy, causing service to begin consuming anew

Setting a flag in a DB which the service is regularly querying would qualify as a signal.

This doesn't, of course, guarantee you that tasks are performed exactly once, unless you can guarantee that, say, an OS crash has the common decency to signal the service that it will be stopped soon and then wait for the service to drain.

So, assuming that it's important that the task get done, you'll still need to think about what happens if it gets done twice.  For that, you generally need to either:

Have a means of detecting when a task has been performed multiple times and then have some means of compensating for that

Define (or at least interpret) the task in such a way that doing it twice is effectively the same as doing it once


问:
How to access the selected value of a combobox for a comparision in PowerApps?
I have a form that connects to a SharePoint list, and some of the DataCards are comboboxes with two text options. I'm trying to use two of them inside an If to display a warning if the combination is wrong. I have tried the following:

DataCardValue3.Selected = "string", the error here is that I'd be trying to compare Record to String

DataCardValue3.Selected.Value = "string", I believe this should work but it doesn't, not because of an error but because it says the selection is "empty", like nothing was selected yet but even when I select an option the warning doesn't show

DataCardValue3.SelectedItems within a concat with "" as separator, this to extract the elements of the table that SelectedItems would get me, still came up empty

DataCardValue3.Selected.NameOfColumn, this because a combobox can apparently have data from more than one column but since this is a form connected to sharepoint automatic field in my case it doesn't, and it just gives me an error. My "column name" appears to be Value, but see point two.

DataCardValue3.Selected.Result, I've seen this in apps other people from my organization have made, it just gives me an error

I'd appreciate any guidance

答:
It really depends on how the ComboBox is set up. If multiselect is allowed, Selected would always come empty. Same with the Default and DefaultSelectedItems properties.

I think you were really close, it would have worked this way as per my experience:

Concat(ComboBox1.SelectedItems,Field1 & Field2,"")

This gives you a string with the combinations. Alternatively you could make single-column table of the combinations with:

ShowColumns(AddColumns(ComboBox1.SelectedItems,"MyColumn",Field1 & Field2),"MyColumn")

Then you can use in, exactin, etc.


问:
Remove array based on index from other array
I want to remove array arr based on index from other array arr2. arr2 can have any length.

Expected Output

```<code>["test9495","test93992"]
</code>```

var arr = ["test234", "test9495", "test234", "test93992", "test234"];

var arr2 = [0, 2, 4];

console.log(arr.splice(arr2,arr2.length))
console.log(arr)```

答:
```<code>const arr = ["test234", "test9495", "test234", "test93992", "test234"];
const arr2 = [0, 2, 4];
const arr3 = arr.filter((item, index) => arr2.indexOf(index) === -1);
console.log(arr3);
</code>```

Body:
I want to remove array arr based on index from other array arr2. arr2 can have any length.

Expected Output

["test9495","test93992"]

var arr = ["test234", "test9495", "test234", "test93992", "test234"];

var arr2 = [0, 2, 4];

console.log(arr.splice(arr2,arr2.length))
console.log(arr)


问:
How to create a column in Pandas with distance from coordinates using GeoPy
I have this df:

```<code>    latitude_1  longitude_1
0   -25.294871  -56.992654
1   -24.946374  -57.384543
2   -24.835273  -53.825342
3   -24.153553  -54.363844
</code>```

And the following coordinates:

```<code>coords_2 = (-25.236632,  -56.835262)
</code>```

So I want to create a 3rd column in the df that shows the distance between each row with coords_2.

If I try to do it without using Dataframes, it works (here I'm using random numbers):

```<code>import geopy.distance

coords_1 = (52.2296756, 21.0122287)
coords_2 = (43.263845, -42.2637377)

print(geopy.distance.distance(coords_1, coords_2).km)
</code>```

Output:

```<code>4691.07078306837
</code>```

So I want to apply this same logic to a Dataframe.

Thanks

答:
You can do that also without using geopandas:</p>
```<code>import pandas as pd
import geopy
import geopy.distance

def distance_from_custom_point(row):
    start = geopy.Point(-25.236632,  -56.835262)
    end = geopy.Point(row['longitude'], row['latitude'])
    row['dist'] = geopy.distance.distance(start, end).km
    return row

df = pd.DataFrame({'latitude': [-25.294871, -24.946374, -24.835273, -24.153553],
                  'longitude': [-56.992654, -57.384543, -53.825342, -54.363844]})

df = df.apply(distance_from_custom_point, axis=1)

print(df)
</code>```

Body:
I have this df:

    latitude_1  longitude_1
0   -25.294871  -56.992654
1   -24.946374  -57.384543
2   -24.835273  -53.825342
3   -24.153553  -54.363844

And the following coordinates:

coords_2 = (-25.236632,  -56.835262)

So I want to create a 3rd column in the df that shows the distance between each row with coords_2.

If I try to do it without using Dataframes, it works (here I'm using random numbers):

import geopy.distance

coords_1 = (52.2296756, 21.0122287)
coords_2 = (43.263845, -42.2637377)

print(geopy.distance.distance(coords_1, coords_2).km)

Output:

4691.07078306837

So I want to apply this same logic to a Dataframe.

Thanks

Body:
You can do that also without using geopandas:

import pandas as pd
import geopy
import geopy.distance

def distance_from_custom_point(row):
    start = geopy.Point(-25.236632,  -56.835262)
    end = geopy.Point(row['longitude'], row['latitude'])
    row['dist'] = geopy.distance.distance(start, end).km
    return row

df = pd.DataFrame({'latitude': [-25.294871, -24.946374, -24.835273, -24.153553],
                  'longitude': [-56.992654, -57.384543, -53.825342, -54.363844]})

df = df.apply(distance_from_custom_point, axis=1)

print(df)


问:
How to get Image Url from local Json file in React.js
I want to be able to display images from a local folder by getting the URL from JSON file. So far I've tried :

src={require(blog.imUrl)}
src={blog.imgUrl}
src={require(${blog.imgUrl})}

Errors i am getting when I use require :

Error: Cannot find module '../../images/safe-image.jpeg'

```<code>import { useHistory } from 'react-router-dom';
import { Col, Row, Container, Image } from 'react-bootstrap';
import blogArticles from './blog.json';
import './BlogCard.css';

export default function BlogCard() {
  const history = useHistory();

  function handleClick() {
    history.push('/`${blog.id}`');
  }

  return blogArticles.map((blog) => {
    return (
      <Container key={blog.id} className="blogContainer">
        <Row>
          <Col xs={6} md={6} lg={8}>
            <h3 className="blogTitle">{blog.title}</h3>
            <span className="blogBody">{blog.body.substring(0, 250)}...</span>
            <button onClick={handleClick} className="readMoreButton">
              Read More
            </button>
          </Col>
          <Col xs={4} md={4} lg={3} className="imageContainer">
            <Image src={require(blog.imgUrl)} roundedCircle />
          </Col>
        </Row>
      </Container>
    );
  });
}```

Here is my JSON File structure :

{
    "id": 3,
    "title": "abc",
    "body": "abcdefg",
    "author": "as",
    "imgUrl": "../../images/leon-biss.jpg"
}

```

答:
Bro, I was working on this problem and eventually figure it out:

1- All you need to do is changing the path of the image from your JSON file. That means the path should be related to your react component (BlogCard).

2- Next thing, instead of using

```<code><MyComponent
    image={release.imageURL}  // ==> WRONG
/>
</code>```

Just go with:

```<code><MyComponent
    image={`${release.imageURL}`} // ===> CORRECT
/>
</code>```

Good Luck !!

Body:
I want to be able to display images from a local folder by getting the URL from JSON file. So far I've tried :

src={require(blog.imUrl)}
src={blog.imgUrl}
src={require(${blog.imgUrl})}

Errors i am getting when I use require :

Error: Cannot find module '../../images/safe-image.jpeg'

import { useHistory } from 'react-router-dom';
import { Col, Row, Container, Image } from 'react-bootstrap';
import blogArticles from './blog.json';
import './BlogCard.css';

export default function BlogCard() {
  const history = useHistory();

  function handleClick() {
    history.push('/`${blog.id}`');
  }

  return blogArticles.map((blog) => {
    return (
      <Container key={blog.id} className="blogContainer">
        <Row>
          <Col xs={6} md={6} lg={8}>

{blog.title}

            {blog.body.substring(0, 250)}...
            <button onClick={handleClick} className="readMoreButton">
              Read More
            </button>
          </Col>
          <Col xs={4} md={4} lg={3} className="imageContainer">
            <Image src={require(blog.imgUrl)} roundedCircle />
          </Col>
        </Row>
      </Container>
    );
  });
}```

Here is my JSON File structure :

{
    "id": 3,
    "title": "abc",
    "body": "abcdefg",
    "author": "as",
    "imgUrl": "../../images/leon-biss.jpg"
}

Body:
Bro, I was working on this problem and eventually figure it out:

1- All you need to do is changing the path of the image from your JSON file. That means the path should be related to your react component (BlogCard).

2- Next thing, instead of using

<MyComponent
    image={release.imageURL}  // ==> WRONG
/>

Just go with:

<MyComponent
    image={`${release.imageURL}`} // ===> CORRECT
/>

Good Luck !!


问:
Vue Router 4 with nested children and params-only
I'd like to make my Vue 3 app, using Vue Router 4, to follow a pattern with nested children. This is my list of routes:

```<code>export default VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes: [
        {
            name: 'booking-start',
            path: '/',
            component: BookingStep1Component,
            children: [
                {
                    name: 'booking-step-1',
                    path: '/:from_gid/:to_gid',
                    component: BookingStep1Component,
                    children: [
                        {
                            name: 'booking-step-2',
                            path: ':date_from/:date_to',
                            component: BookingStep2Component,
                            children: [
                                {
                                    name: 'booking-step-3',
                                    path: ':time_from/:time_to',
                                    component: BookingStep3Component
                                },
                            ]
                        }
                    ]
                }
            ]
        }
    ]
})
</code>```

So if I go the the url /# I would like to get the BookingStep1Component displayed, same goes with /#123/456. If I go to /#123/456/2022-01-01/2022-02-28, I'd like to see BookingStep2Component, and if I go to /#123/456/2022-01-01/2022-02-28/10:00/13:00, I'd like to see BookingStep3Component. But things get mixed up somewhere and I do not see the right component at some stage.

Is there anything obvious I am missing here?

答:
Not sure, but I do not use a "/" at the beginning of childs like at booking-step-1.
Although I have not used paths, beginning with a param ... should work, but I would try it out.

Body:
I'd like to make my Vue 3 app, using Vue Router 4, to follow a pattern with nested children. This is my list of routes:

export default VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes: [
        {
            name: 'booking-start',
            path: '/',
            component: BookingStep1Component,
            children: [
                {
                    name: 'booking-step-1',
                    path: '/:from_gid/:to_gid',
                    component: BookingStep1Component,
                    children: [
                        {
                            name: 'booking-step-2',
                            path: ':date_from/:date_to',
                            component: BookingStep2Component,
                            children: [
                                {
                                    name: 'booking-step-3',
                                    path: ':time_from/:time_to',
                                    component: BookingStep3Component
                                },
                            ]
                        }
                    ]
                }
            ]
        }
    ]
})

So if I go the the url /# I would like to get the BookingStep1Component displayed, same goes with /#123/456. If I go to /#123/456/2022-01-01/2022-02-28, I'd like to see BookingStep2Component, and if I go to /#123/456/2022-01-01/2022-02-28/10:00/13:00, I'd like to see BookingStep3Component. But things get mixed up somewhere and I do not see the right component at some stage.

Is there anything obvious I am missing here?


问:
state inside function not updating
Does anyone know why the state inside a function isn't updating and sometimes the btnRef in Ss file always null so the addEventListener not working</p>
```<code>//App.tsx

import { useRef } from "react";
import "./styles.css";
import Ss from "./Ss";

export default function App() {
  const btnRef = useRef<any>(null);
  return (
    <div className="App">
      <Ss btnRef={btnRef.current} />
      <div ref={btnRef}>click</div>
    </div>
  );
}
</code>```
```<code>//Ss.tsx
import { useEffect, useState } from "react";

export default function Ss({ btnRef }: { btnRef?: Element }) {
  const [current, setCurrent] = useState(0);
  function asd() {
    console.log("current:", current);
    setCurrent((prev) => prev + 1);
  }
  useEffect(() => {
    btnRef?.addEventListener("click", asd);
  }, [btnRef]);

  return <></>;
}

</code>```

答:
btnRef.current in <Ss btnRef={btnRef.current} /> will be null because you are passing it to Ss before the div is even mounted on the DOM.

```<code><Ss btnRef={btnRef.current} />
<div ref={btnRef}>click</div>
</code>```

Since the App is not re-rendered after that , btnRef prop in Ss is still null.

Solution:

Instead of passing btnRef.current to Ss , pass the btnRef directly current property in btnRef will be updated when div is mounted.

```<code><Ss btnRef={btnRef} />
<div ref={btnRef}>click</div>
</code>```

Ss.tsx

```<code>  useEffect(() => {
    const el = btnRef.current;
    el.addEventListener("click", asd);
    return () => el.removeEventListener("click", asd);
  }, [btnRef, current]);
</code>```

Add the current counter state to useEffect deps if you want console.log("current:", current); to log the correct state value and don't forget to cleanup the click listener.

CodeSandbox Link

Title: state inside function not updating

Body:
Does anyone know why the state inside a function isn't updating and sometimes the btnRef in Ss file always null so the addEventListener not working

//App.tsx

import { useRef } from "react";
import "./styles.css";
import Ss from "./Ss";

export default function App() {
  const btnRef = useRef<any>(null);
  return (

      <Ss btnRef={btnRef.current} />

click

  );
}

//Ss.tsx
import { useEffect, useState } from "react";

export default function Ss({ btnRef }: { btnRef?: Element }) {
  const [current, setCurrent] = useState(0);
  function asd() {
    console.log("current:", current);
    setCurrent((prev) => prev + 1);
  }
  useEffect(() => {
    btnRef?.addEventListener("click", asd);
  }, [btnRef]);

  return <></>;
}

Body:
btnRef.current in <Ss btnRef={btnRef.current} /> will be null because you are passing it to Ss before the div is even mounted on the DOM.

<Ss btnRef={btnRef.current} />
<div ref={btnRef}>click</div>

Since the App is not re-rendered after that , btnRef prop in Ss is still null.

Solution:

Instead of passing btnRef.current to Ss , pass the btnRef directly current property in btnRef will be updated when div is mounted.

<Ss btnRef={btnRef} />
<div ref={btnRef}>click</div>

Ss.tsx

  useEffect(() => {
    const el = btnRef.current;
    el.addEventListener("click", asd);
    return () => el.removeEventListener("click", asd);
  }, [btnRef, current]);

Add the current counter state to useEffect deps if you want console.log("current:", current); to log the correct state value and don't forget to cleanup the click listener.

CodeSandbox Link


问:
How do I create folders in ASP.NET in code behind?
I want to create dynamic folders at run time.  Folder names with be input via a TextBox and output will be displayed in a TreeView.

The form will submit if I enter the first folder name into textbox1 and click the "Add Folder" button.  When I submit multiple folders with the same name the output should be an indexed increment of the name. Eg. FooFolder, FooFolder(2), FooFolder(3), etc.

If I delete FooFolder(2) and then recreate a folder with the name FooFolder, the folder should be FooFolder(2), and if I create one more folder then it should be FooFolder(4).

For deletion one can select the particular folder from the TreeView which will be displayed in TextBox2 and click the "Remove Folder" button.

Here is my presentation code:

```<code><asp:Button ID="btnAddFolder" runat="server" Height="24px" Text="Add Folder"
        Width="148px" onclick="btnAddFolder_Click" />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br />
    <asp:Button ID="btnRemoveFolder" runat="server" Text="Remove Folder" />
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <br />
    <br />
    <asp:TreeView ID="TreeView1" runat="server" ImageSet="XPFileExplorer"
        NodeIndent="15">
        <ParentNodeStyle Font-Bold="False" />
        <HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
        <SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False"
            HorizontalPadding="0px" VerticalPadding="0px" />
        <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black"
            HorizontalPadding="2px" NodeSpacing="0px" VerticalPadding="2px" />
    </asp:TreeView>
</code>```

Now how do I write the code to do the work?

答:
Your question is a bit unclear, but I'll try to get you a little ways there anyway.

First of all be sure that you are importing/using (depending on language) the System.IO namespace for this to work.  But what you can do is something like this.

```<code>string pathToCreate = "~/UserFolders/" + TextBox1.Text;
if(Directory.Exists(Server.MapPath(pathToCreate))
{
   //In here, start looping and modify the path to create to add a number
   //until you get the value needed
}

//Now you know it is ok, create it
Directory.CreateDirectory(Server.MapPath(pathToCreate));
</code>```

This should help get you going with the folder creation anyway.

ContentLicense: CC BY-SA 2.5

Body:
I want to create dynamic folders at run time.  Folder names with be input via a TextBox and output will be displayed in a TreeView.

The form will submit if I enter the first folder name into textbox1 and click the "Add Folder" button.  When I submit multiple folders with the same name the output should be an indexed increment of the name. Eg. FooFolder, FooFolder(2), FooFolder(3), etc.

If I delete FooFolder(2) and then recreate a folder with the name FooFolder, the folder should be FooFolder(2), and if I create one more folder then it should be FooFolder(4).

For deletion one can select the particular folder from the TreeView which will be displayed in TextBox2 and click the "Remove Folder" button.

Here is my presentation code:

<asp:Button ID="btnAddFolder" runat="server" Height="24px" Text="Add Folder"
        Width="148px" onclick="btnAddFolder_Click" />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    <asp:Button ID="btnRemoveFolder" runat="server" Text="Remove Folder" />
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

    <asp:TreeView ID="TreeView1" runat="server" ImageSet="XPFileExplorer"
        NodeIndent="15">
        <ParentNodeStyle Font-Bold="False" />
        <HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
        <SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False"
            HorizontalPadding="0px" VerticalPadding="0px" />
        <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black"
            HorizontalPadding="2px" NodeSpacing="0px" VerticalPadding="2px" />
    </asp:TreeView>

Now how do I write the code to do the work?

LastEditorDisplayName: LFSR Consulting

Body:
Your question is a bit unclear, but I'll try to get you a little ways there anyway.

First of all be sure that you are importing/using (depending on language) the System.IO namespace for this to work.  But what you can do is something like this.

string pathToCreate = "~/UserFolders/" + TextBox1.Text;
if(Directory.Exists(Server.MapPath(pathToCreate))
{
   //In here, start looping and modify the path to create to add a number
   //until you get the value needed
}

//Now you know it is ok, create it
Directory.CreateDirectory(Server.MapPath(pathToCreate));

This should help get you going with the folder creation anyway.

OwnerDisplayName: Mitchel Sellers


问:
How to implement file picker android 11
Can anyone please share complete solution for File Picker in Android 11 for both Internal and External Storage</p>

答:
Here Code For Android 11 File Upload using Intent and also you dont have to mention MANAGE_EXTERNAL_STORAGE Permission in AndroidManifest.xml file i have implemented without this permission.

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
                    chooseFile.setType("application/pdf");
                    chooseFile = Intent.createChooser(chooseFile, "Choose a file");
                    startActivityForResult(chooseFile, Constants.REQUEST_PICK_FILE);
                }else{
String[] types = new String[]{"pdf"};
    FilePickerBuilder.getInstance().setMaxCount(UPLOAD_LIMIT - attachmentModelList.size())
            .setActivityTheme(R.style.AppTheme)
            .setActivityTitle(mActivity.getString(R.string.select_documents))
            /*.sortDocumentsBy(SortingTypes.NAME)*/
            .enableDocSupport(false)
            .addFileSupport("PDF", types)
            /*.setSelectedFiles(masterList !!)*/
            .pickFile(this);
}
</code>```

here is onActivityResult Code Pick File Name and other information

```<code>    if (requestCode == Constants.REQUEST_PICK_FILE &&
                        resultCode == Activity.RESULT_OK) {

                    Uri uri = data.getData();
                    String mimeType = getActivity().getContentResolver().getType(uri);
                    String filename;
                    if (mimeType == null) {
                        String path = CommonMethod.getPath(getActivity(), uri);
    //                    if (path == null) {
    //                        filename = FilenameUtils.getName(uri.toString());
    //                    } else {
                        File file = new File(path);
                        filename = file.getName();
    //                    }
                    } else {
                        Uri returnUri = data.getData();
                        Cursor returnCursor = getActivity().getContentResolver().query(returnUri, null, null, null, null);
                        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                        returnCursor.moveToFirst();
                        filename = returnCursor.getString(nameIndex);
                        String size = Long.toString(returnCursor.getLong(sizeIndex));
                    }
                    File fileSave = getActivity().getExternalFilesDir(null);
                    String sourcePath = getActivity().getExternalFilesDir(null).toString();
                    File targetFile = null;
                    try {
                        targetFile = new File(sourcePath + "/" + filename);
                        boolean success = CommonMethod.copyFileStream(new File(sourcePath + "/" + filename), uri, getActivity());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (targetFile != null) {
                        String fileName = Utils.getFileName(getActivity(),Uri.fromFile(targetFile));
 String filePath = targetFile.getPath();

                }
</code>```

Title: How to implement file picker android 11

Body:
Here Code For Android 11 File Upload using Intent and also you dont have to mention MANAGE_EXTERNAL_STORAGE Permission in AndroidManifest.xml file i have implemented without this permission.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
                    chooseFile.setType("application/pdf");
                    chooseFile = Intent.createChooser(chooseFile, "Choose a file");
                    startActivityForResult(chooseFile, Constants.REQUEST_PICK_FILE);
                }else{
String[] types = new String[]{"pdf"};
    FilePickerBuilder.getInstance().setMaxCount(UPLOAD_LIMIT - attachmentModelList.size())
            .setActivityTheme(R.style.AppTheme)
            .setActivityTitle(mActivity.getString(R.string.select_documents))
            /*.sortDocumentsBy(SortingTypes.NAME)*/
            .enableDocSupport(false)
            .addFileSupport("PDF", types)
            /*.setSelectedFiles(masterList !!)*/
            .pickFile(this);
}

here is onActivityResult Code Pick File Name and other information

    if (requestCode == Constants.REQUEST_PICK_FILE &&
                        resultCode == Activity.RESULT_OK) {

                    Uri uri = data.getData();
                    String mimeType = getActivity().getContentResolver().getType(uri);
                    String filename;
                    if (mimeType == null) {
                        String path = CommonMethod.getPath(getActivity(), uri);
    //                    if (path == null) {
    //                        filename = FilenameUtils.getName(uri.toString());
    //                    } else {
                        File file = new File(path);
                        filename = file.getName();
    //                    }
                    } else {
                        Uri returnUri = data.getData();
                        Cursor returnCursor = getActivity().getContentResolver().query(returnUri, null, null, null, null);
                        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                        returnCursor.moveToFirst();
                        filename = returnCursor.getString(nameIndex);
                        String size = Long.toString(returnCursor.getLong(sizeIndex));
                    }
                    File fileSave = getActivity().getExternalFilesDir(null);
                    String sourcePath = getActivity().getExternalFilesDir(null).toString();
                    File targetFile = null;
                    try {
                        targetFile = new File(sourcePath + "/" + filename);
                        boolean success = CommonMethod.copyFileStream(new File(sourcePath + "/" + filename), uri, getActivity());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (targetFile != null) {
                        String fileName = Utils.getFileName(getActivity(),Uri.fromFile(targetFile));
 String filePath = targetFile.getPath();

                }


问:
How could I make this LINQ query more efficient?
Any suggestions on how to make this LINQ query more efficient? I recently created the formattedDate variable as previously I was calling the GetDateInFormat multiple times.

```<code>    if (customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null)
          .Any())
    {
        var date = customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .OrderBy(d => d.ActualDate)
          .FirstOrDefault(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null)
          .ActualDate;

        if (date != null)
        {
            var formattedDate = _dateHelper.GetDateInFormat("DD/MM/YYYY", date);
            order.ArriveDate = formattedDate;
            order.EarliestShipDate = formattedDate;
            order.EarliestDeliveryDate = formattedDate;
            order.EarliestApptTime = _dateHelper.GetDateInFormat("HHMM", date);
        }
    }
</code>```

The customerOrder is a customer Order class.

```<code>public class Order
{
    public Order();

    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public OrderLine();

    public List<OrderDate> OrderDates { get; set; }
}

public class OrderDate
{
    public OrderDate();

    public DateTimeOffset? ActualDate { get; set; }
    public string DateTypeId { get; set; }
}
</code>```

答:
Well,

First of all let's get rid of two Linq queries in a row: Any() and then FirstOrDefault. We can execute just FirstOrDefault (or its equivalent) and if we get null we'll know that Any returns false
(i.e. we have no items).

Second, with OrderBy we sort the entire enumerable and then we drop all but one item. We are wasting resources. Aggregate is more economic way: we have no need to sort but scan the enumeration and return either null or smallest ActualDate.

Code:

```<code>var date = customerOrder
  .OrderLines
  .SelectMany(ol => ol.OrderDates)
  .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null)
  .Select(ol => ol.ActualDate)
  .Aggregate((DateTimeOffset?) null,
     (s, a) => !s.HasValue || s.Value > a ? a : s);

if (date.HasValue) {
  var formattedDate = _dateHelper.GetDateInFormat("DD/MM/YYYY", date);

  order.ArriveDate = formattedDate;
  order.EarliestShipDate = formattedDate;
  order.EarliestDeliveryDate = formattedDate;
  order.EarliestApptTime = _dateHelper.GetDateInFormat("HHMM", date);
}
</code>```

Body:
Any suggestions on how to make this LINQ query more efficient? I recently created the formattedDate variable as previously I was calling the GetDateInFormat multiple times.

    if (customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null)
          .Any())
    {
        var date = customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .OrderBy(d => d.ActualDate)
          .FirstOrDefault(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null)
          .ActualDate;

        if (date != null)
        {
            var formattedDate = _dateHelper.GetDateInFormat("DD/MM/YYYY", date);
            order.ArriveDate = formattedDate;
            order.EarliestShipDate = formattedDate;
            order.EarliestDeliveryDate = formattedDate;
            order.EarliestApptTime = _dateHelper.GetDateInFormat("HHMM", date);
        }
    }

The customerOrder is a customer Order class.

public class Order
{
    public Order();

    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public OrderLine();

    public List<OrderDate> OrderDates { get; set; }
}

public class OrderDate
{
    public OrderDate();

    public DateTimeOffset? ActualDate { get; set; }
    public string DateTypeId { get; set; }
}

Body:
Well,

First of all let's get rid of two Linq queries in a row: Any() and then FirstOrDefault. We can execute just FirstOrDefault (or its equivalent) and if we get null we'll know that Any returns false
(i.e. we have no items).

Second, with OrderBy we sort the entire enumerable and then we drop all but one item. We are wasting resources. Aggregate is more economic way: we have no need to sort but scan the enumeration and return either null or smallest ActualDate.

Code:

var date = customerOrder
  .OrderLines
  .SelectMany(ol => ol.OrderDates)
  .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null)
  .Select(ol => ol.ActualDate)
  .Aggregate((DateTimeOffset?) null,
     (s, a) => !s.HasValue || s.Value > a ? a : s);

if (date.HasValue) {
  var formattedDate = _dateHelper.GetDateInFormat("DD/MM/YYYY", date);

  order.ArriveDate = formattedDate;
  order.EarliestShipDate = formattedDate;
  order.EarliestDeliveryDate = formattedDate;
  order.EarliestApptTime = _dateHelper.GetDateInFormat("HHMM", date);
}


问:
Strange Error while creating ImagePullSecret with kubectl in gitlab ci job
I am trying to deploy an image from a private gitlab registry to a self-hosted kubernets cluster that is connected and managed by gitlab. As far as I understood it, I need a ImagePullSecret created and referenced in my Deployment-Config for this to work. Gitlab is creating a namespace per project so I am trying to create a secret at the start of my CI-Job. Strangely I always get the error, that an argument is missing, despite all of the required arguments being present. What am I doing wrong?

Here is the CI-Job out of my gitlab-ci.yml

```<code>deploy-app:
  stage: deploy
  image:
    name: bitnami/kubectl:latest
    entrypoint: [""]
  script:
    - kubectl create secret docker-registry gitlab-registry --docker-username=$CI_DEPLOY_USER --docker-password=$CI_DEPLOY_PASSWORD --docker-server=$CI_REGISTRY --dry-run=client -o yaml | kubectl apply -f -
    - kubectl apply -f k8s/configmap.yaml
    - kubectl apply -f k8s/deployment.yaml
    - kubectl apply -f k8s/service.yaml
    - kubectl apply -f k8s/ingress.yaml
  environment:
    name: production
    url: <my-url>
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
</code>```

The CI-Job always runs into the following error:

```<code>error: either --from-file or the combination of --docker-username, --docker-password and --docker-server is required
</code>```

I tried to run the command directly on the server without an error, so this has something to do with this specific environment. Has someone an idea for another approach? I am a bit lost right now.

答:
Had the same issue. Fixed by using proper CI variable names:
$CI_REGISTRY_USER and $CI_REGISTRY_PASSWORD.

Looks like $CI_DEPLOY_USER and $CI_DEPLOY_PASSWORD variables from GitLab documentation are just an example, and are not actually defined.

Check actual variable names here: https://docs.gitlab.com/ee/ci/variables/

Body:
I am trying to deploy an image from a private gitlab registry to a self-hosted kubernets cluster that is connected and managed by gitlab. As far as I understood it, I need a ImagePullSecret created and referenced in my Deployment-Config for this to work. Gitlab is creating a namespace per project so I am trying to create a secret at the start of my CI-Job. Strangely I always get the error, that an argument is missing, despite all of the required arguments being present. What am I doing wrong?

Here is the CI-Job out of my gitlab-ci.yml

deploy-app:
  stage: deploy
  image:
    name: bitnami/kubectl:latest
    entrypoint: [""]
  script:
    - kubectl create secret docker-registry gitlab-registry --docker-username=$CI_DEPLOY_USER --docker-password=$CI_DEPLOY_PASSWORD --docker-server=$CI_REGISTRY --dry-run=client -o yaml | kubectl apply -f -
    - kubectl apply -f k8s/configmap.yaml
    - kubectl apply -f k8s/deployment.yaml
    - kubectl apply -f k8s/service.yaml
    - kubectl apply -f k8s/ingress.yaml
  environment:
    name: production
    url: <my-url>
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

The CI-Job always runs into the following error:

error: either --from-file or the combination of --docker-username, --docker-password and --docker-server is required

I tried to run the command directly on the server without an error, so this has something to do with this specific environment. Has someone an idea for another approach? I am a bit lost right now.


问:
Wrong exit condition in recursive solution
There are a 2D char-array and a search word. The task is to find out if there's the word in the array.
The word can be placed in the array in any curve with 4 directions: up, down, left, right.
You can't reuse the letters. For example, from an array [a, b, c] you can't get a word "ababc".
See the examples below.

```<code>function findWord(puzzle, word) {

}

const puzzle = [
  'ANGULAR',
  'REDNCAE',
  'RFIDTCL',
  'AGNEGSA',
  'YTIRTSP',
];

console.log(findWord(puzzle, 'ANGULAR')); // true
console.log(findWord(puzzle, 'REACT')); // true
console.log(findWord(puzzle, 'ARRAY')); // true
console.log(findWord(puzzle, 'UNDEFINED')); // true
console.log(findWord(puzzle, 'RED')); // true
console.log(findWord(puzzle, 'STRING')); // true
console.log(findWord(puzzle, 'CLASS')); // true
console.log(findWord(puzzle, 'FUNCTION')); // false
console.log(findWord(puzzle, 'NULL')); // false
</code>```

My solution:

```<code>function findWord(puzzle, word) {
  puzzle = puzzle.map(e => e.split(""));
  const current = [];
  const clear = [];
  for (let y = 0; y < puzzle.length; y++) {
    for (let x = 0; x < puzzle[y].length; x++) {
      if (puzzle[y][x] === word[0]) {
        clear.push({x, y});
        current.push(...getSurround(x, y, puzzle));
      }
    }
  }
  return nextTurn(puzzle, word.slice(1), clear, current);
}

function nextTurn(puzzle, word, clear, current) {
  const next = [];
  if (word.length === 0) return true;

  for (let v of clear) {puzzle[v.y][v.x] = "-"}
  clear.length = 0;

  for (let v of current) {
    if (v === null) continue;
    if (v.letter === word[0]) {
      clear.push({x: v.x, y: v.y});
      next.push(...getSurround(v.x, v.y, puzzle));
    }
  }
  if (next.length === 0) return false;
  return nextTurn(puzzle, word.slice(1), clear, next);
}

function getSurround(x, y, puzzle) {
  const surround = [];
  const u = (y !== 0) ? {x, y: y - 1, letter: puzzle[y - 1][x]} : null;
  const r = (x !== puzzle[y].length - 1) ? {x: x + 1, y, letter: puzzle[y][x + 1]} : null;
  const d = (y !== puzzle.length - 1) ? {x, y: y + 1, letter: puzzle[y + 1][x]} : null;
  const l = (x !== 0) ? {x: x - 1, y, letter: puzzle[y][x - 1]} : null;
  surround.push(u, r, d, l);
  return surround;
}
</code>```

It seems that solution works for finding the word, but the problem is in the recursion exit.
I made a guess, that true is when the word is done, and false is when the word is not done and there is no other appropriate letter to end the word.

答:
Your issue seems to be with:

for (let v of clear) {puzzle[v.y][v.x] = "-"}
clear.length = 0;
```
<p>for the word <code>"angular"</code>, this will set all "a"s to "-", which you shouldn't be doing, you should only be setting <code>"a"</code> to blank if/when you use it. Currently you're setting all "a" characters to <code>"-"</code> which means that you wont be able to use <code>"a"</code> again (so the second <code>a</code> in "angul<strong>a</strong>r" wont be found).</p>
<p>I suggest removing the idea of your <code>clear</code> array, and instead updating your <code>nextTurn</code> function:</p>
<pre class="lang-js prettyprint-override"><code>function nextTurn(puzzle, word, current) {
  if (word.length === 0) return true;

  for (const v of current) {
    if (v.letter === word[0]) {
      const nextCandidates = getSurround(v.x, v.y, puzzle);
      puzzle[v.y][v.x] = '-'; // mark letter as we're using it
      const turnResult = nextTurn(puzzle, word.slice(1), nextCandidates);
      if(turnResult) // recursive call returned true
        return turnResult;
      // If using the letter at x,y didn't work, "un-mark" it
      puzzle[v.y][v.x] = v.letter;
    }
  }

  return false;
}
</code>```

The idea is to mark the current letter as "used" ("-") right before we recurse and call nextTurn(). This allows us to use the current letter right before we search its surrounding letters in the next call to nextTurn(). If searching that particular letter doesn't work, we backtrack and set the letter in the puzzle back to "available" by setting the letter back to its original value so that we can search the other possible options (and possible reuse this letter at some further point in the word).

In the below snippet I've also updated your findWord() function so that it converts your 2d puzzle array of letters to an array of vertices ({x, y, letter} objects), which can then be used by nextTurn() to calculate the next possible solution for each letter. Lastly, I've also updated your getSurround function to avoid the unneeded null values. This helps remove iterations over values which you know you won't be processing:

function findWord(puzzle, word) {
  puzzle = puzzle.map(str => Array.from(str));
  const candidates = puzzle.flatMap((row, y) => row.map((letter, x) => toVertex(x, y, letter)));
  return nextTurn(puzzle, word, candidates);
}

function nextTurn(puzzle, word, current) {
  if (word.length === 0) return true;

  for (const v of current) {
    if (v.letter === word[0]) {
      const nextCandidates = getSurround(v.x, v.y, puzzle);
      //console.log(v.y, v.x, puzzle[v.y]);
      puzzle[v.y][v.x] = '-'; // mark letter as we're using it
      const turnResult = nextTurn(puzzle, word.slice(1), nextCandidates);
      if(turnResult) // recursive call returned true
        return turnResult;
      // If using the letter at x,y didn't work, "un-mark" it
      puzzle[v.y][v.x] = v.letter;
    }
  }

  return false;
}

function getSurround(x, y, puzzle) {
  const surround = [];
  if(y !== 0)
    surround.push(toVertex(x, y-1, puzzle[y - 1][x]));

  if(x !== puzzle[y].length - 1)
    surround.push(toVertex(x+1, y, puzzle[y][x + 1]));

  if(y !== puzzle.length - 1)
    surround.push(toVertex(x, y+1, puzzle[y + 1][x]));

  if(x !== 0)
    surround.push(toVertex(x - 1, y, puzzle[y][x - 1]));

  return surround;
}

function toVertex(x, y, letter) {
  return {x, y, letter};
}

const puzzle = [
  'ANGULAR',
  'REDNCAE',
  'RFIDTCL',
  'AGNEGSA',
  'YTIRTSP',
];

console.log('ANGULAR', findWord(puzzle, 'ANGULAR')); // true
console.log('REACT', findWord(puzzle, 'REACT')); // true
console.log('ARRAY', findWord(puzzle, 'ARRAY')); // true
console.log('UNDEFINED', findWord(puzzle, 'UNDEFINED')); // true
console.log('RED', findWord(puzzle, 'RED')); // true
console.log('STRING', findWord(puzzle, 'STRING')); // true
console.log('CLASS', findWord(puzzle, 'CLASS')); // true
console.log('FUNCTION', findWord(puzzle, 'FUNCTION')); // false
console.log('NULL', findWord(puzzle, 'NULL')); // false
console.log('RANER', findWord(puzzle, 'RANER')); // false (additional test to try re-use)```

Body:
There are a 2D char-array and a search word. The task is to find out if there's the word in the array.
The word can be placed in the array in any curve with 4 directions: up, down, left, right.
You can't reuse the letters. For example, from an array [a, b, c] you can't get a word "ababc".
See the examples below.

function findWord(puzzle, word) {

}

const puzzle = [
  'ANGULAR',
  'REDNCAE',
  'RFIDTCL',
  'AGNEGSA',
  'YTIRTSP',
];

console.log(findWord(puzzle, 'ANGULAR')); // true
console.log(findWord(puzzle, 'REACT')); // true
console.log(findWord(puzzle, 'ARRAY')); // true
console.log(findWord(puzzle, 'UNDEFINED')); // true
console.log(findWord(puzzle, 'RED')); // true
console.log(findWord(puzzle, 'STRING')); // true
console.log(findWord(puzzle, 'CLASS')); // true
console.log(findWord(puzzle, 'FUNCTION')); // false
console.log(findWord(puzzle, 'NULL')); // false

My solution:

function findWord(puzzle, word) {
  puzzle = puzzle.map(e => e.split(""));
  const current = [];
  const clear = [];
  for (let y = 0; y < puzzle.length; y++) {
    for (let x = 0; x < puzzle[y].length; x++) {
      if (puzzle[y][x] === word[0]) {
        clear.push({x, y});
        current.push(...getSurround(x, y, puzzle));
      }
    }
  }
  return nextTurn(puzzle, word.slice(1), clear, current);
}

function nextTurn(puzzle, word, clear, current) {
  const next = [];
  if (word.length === 0) return true;

  for (let v of clear) {puzzle[v.y][v.x] = "-"}
  clear.length = 0;

  for (let v of current) {
    if (v === null) continue;
    if (v.letter === word[0]) {
      clear.push({x: v.x, y: v.y});
      next.push(...getSurround(v.x, v.y, puzzle));
    }
  }
  if (next.length === 0) return false;
  return nextTurn(puzzle, word.slice(1), clear, next);
}

function getSurround(x, y, puzzle) {
  const surround = [];
  const u = (y !== 0) ? {x, y: y - 1, letter: puzzle[y - 1][x]} : null;
  const r = (x !== puzzle[y].length - 1) ? {x: x + 1, y, letter: puzzle[y][x + 1]} : null;
  const d = (y !== puzzle.length - 1) ? {x, y: y + 1, letter: puzzle[y + 1][x]} : null;
  const l = (x !== 0) ? {x: x - 1, y, letter: puzzle[y][x - 1]} : null;
  surround.push(u, r, d, l);
  return surround;
}

It seems that solution works for finding the word, but the problem is in the recursion exit.
I made a guess, that true is when the word is done, and false is when the word is not done and there is no other appropriate letter to end the word.

Body:
Your issue seems to be with:

for (let v of clear) {puzzle[v.y][v.x] = "-"}
clear.length = 0;

for the word "angular", this will set all "a"s to "-", which you shouldn't be doing, you should only be setting "a" to blank if/when you use it. Currently you're setting all "a" characters to "-" which means that you wont be able to use "a" again (so the second a in "angular" wont be found).

I suggest removing the idea of your clear array, and instead updating your nextTurn function:

function nextTurn(puzzle, word, current) {
  if (word.length === 0) return true;

  for (const v of current) {
    if (v.letter === word[0]) {
      const nextCandidates = getSurround(v.x, v.y, puzzle);
      puzzle[v.y][v.x] = '-'; // mark letter as we're using it
      const turnResult = nextTurn(puzzle, word.slice(1), nextCandidates);
      if(turnResult) // recursive call returned true
        return turnResult;
      // If using the letter at x,y didn't work, "un-mark" it
      puzzle[v.y][v.x] = v.letter;
    }
  }

  return false;
}

The idea is to mark the current letter as "used" ("-") right before we recurse and call nextTurn(). This allows us to use the current letter right before we search its surrounding letters in the next call to nextTurn(). If searching that particular letter doesn't work, we backtrack and set the letter in the puzzle back to "available" by setting the letter back to its original value so that we can search the other possible options (and possible reuse this letter at some further point in the word).

In the below snippet I've also updated your findWord() function so that it converts your 2d puzzle array of letters to an array of vertices ({x, y, letter} objects), which can then be used by nextTurn() to calculate the next possible solution for each letter. Lastly, I've also updated your getSurround function to avoid the unneeded null values. This helps remove iterations over values which you know you won't be processing:

function findWord(puzzle, word) {
  puzzle = puzzle.map(str => Array.from(str));
  const candidates = puzzle.flatMap((row, y) => row.map((letter, x) => toVertex(x, y, letter)));
  return nextTurn(puzzle, word, candidates);
}

function nextTurn(puzzle, word, current) {
  if (word.length === 0) return true;

  for (const v of current) {
    if (v.letter === word[0]) {
      const nextCandidates = getSurround(v.x, v.y, puzzle);
      //console.log(v.y, v.x, puzzle[v.y]);
      puzzle[v.y][v.x] = '-'; // mark letter as we're using it
      const turnResult = nextTurn(puzzle, word.slice(1), nextCandidates);
      if(turnResult) // recursive call returned true
        return turnResult;
      // If using the letter at x,y didn't work, "un-mark" it
      puzzle[v.y][v.x] = v.letter;
    }
  }

  return false;
}

function getSurround(x, y, puzzle) {
  const surround = [];
  if(y !== 0)
    surround.push(toVertex(x, y-1, puzzle[y - 1][x]));

  if(x !== puzzle[y].length - 1)
    surround.push(toVertex(x+1, y, puzzle[y][x + 1]));

  if(y !== puzzle.length - 1)
    surround.push(toVertex(x, y+1, puzzle[y + 1][x]));

  if(x !== 0)
    surround.push(toVertex(x - 1, y, puzzle[y][x - 1]));

  return surround;
}

function toVertex(x, y, letter) {
  return {x, y, letter};
}

const puzzle = [
  'ANGULAR',
  'REDNCAE',
  'RFIDTCL',
  'AGNEGSA',
  'YTIRTSP',
];

console.log('ANGULAR', findWord(puzzle, 'ANGULAR')); // true
console.log('REACT', findWord(puzzle, 'REACT')); // true
console.log('ARRAY', findWord(puzzle, 'ARRAY')); // true
console.log('UNDEFINED', findWord(puzzle, 'UNDEFINED')); // true
console.log('RED', findWord(puzzle, 'RED')); // true
console.log('STRING', findWord(puzzle, 'STRING')); // true
console.log('CLASS', findWord(puzzle, 'CLASS')); // true
console.log('FUNCTION', findWord(puzzle, 'FUNCTION')); // false
console.log('NULL', findWord(puzzle, 'NULL')); // false
console.log('RANER', findWord(puzzle, 'RANER')); // false (additional test to try re-use)


问:
Why is the SOAP XML attribute not being set?
When creating SOAP with SOAP::Lite

```<code>#!/usr/bin/perl
use 5.006;
use strict;
use warnings;
use SOAP::Lite +trace => [ 'debug' ];

my $req1 = SOAP::Lite->new(
    readable => 1,
    autotype => 0,
    proxy    => 'https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor',
);

# req1 does not generate the XML attribute <item id="0"> it just generates
# <item>
$req1->requestMessage(
    \SOAP::Data->new(
        name => 'item',
        attr => { id => '0' },
        value => \SOAP::Data->new(
            name => 'foo',
            value => 1,
        ),
     ),
);
</code>```

I get this XML (note: well this is the important part)

```<code><item>
  <foo>1</foo>
</item>
</code>```

I do not understand why I am not getting this XML

```<code><item id="0">
   <foo>1</foo>
</item>
</code>```

can anyone tell me how to get the attribute to be generated?

note: this near identical (instead of naming the attribute id it's named foo)  code works. so I think this may be a bug

```<code>$req->requestMessage(
    \SOAP::Data->new(
        name => 'item',
        attr => { foo => '0' },
        value => \SOAP::Data->new(
            name => 'foo',
            value => 1,
        ),
     ),
);
</code>```

答: Can you try putting quotes around id? Maybe that'll work.

Body:
When creating SOAP with SOAP::Lite

#!/usr/bin/perl
use 5.006;
use strict;
use warnings;
use SOAP::Lite +trace => [ 'debug' ];

my $req1 = SOAP::Lite->new(
    readable => 1,
    autotype => 0,
    proxy    => 'https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor',
);

# req1 does not generate the XML attribute <item id="0"> it just generates
# <item>
$req1->requestMessage(
    \SOAP::Data->new(
        name => 'item',
        attr => { id => '0' },
        value => \SOAP::Data->new(
            name => 'foo',
            value => 1,
        ),
     ),
);

I get this XML (note: well this is the important part)

<item>
  <foo>1</foo>
</item>

I do not understand why I am not getting this XML

<item id="0">
   <foo>1</foo>
</item>

can anyone tell me how to get the attribute to be generated?

note: this near identical (instead of naming the attribute id it's named foo)  code works. so I think this may be a bug

$req->requestMessage(
    \SOAP::Data->new(
        name => 'item',
        attr => { foo => '0' },
        value => \SOAP::Data->new(
            name => 'foo',
            value => 1,
        ),
     ),
);


问:
Gutenberg InnerBlocks predefined block supports
I am using a template for InnerBlocks and adding predefined attributes like heading level and paragraph placeholder:

```<code>const MY_TEMPLATE = [
    [ 'core/image', {} ],
    [ 'core/heading', { level: 3 } ],
    [ 'core/paragraph', { placeholder: 'Summary' } ],
];

//...

    edit: () => {
        return (
            <InnerBlocks
                template={ MY_TEMPLATE }
                templateLock="all"
            />
        );
    },
</code>```

This works well but how can we add predefined values for block supports?

For example when registering a block I can set support values:

```<code>supports: {
    className: false // Remove the support for the generated className.
    color: { // Text UI control is enabled.
        background: false, // Disable background UI control.
        gradients: true // Enable gradients UI control.
    }
}
</code>```

How can I set values for supports through InnerBlocks templates? For example I want to remove the default wp-block- class name from a block. I tried:

```<code>const MY_TEMPLATE = [
  [ 'my-block/icon', { supports: { classname: false } } ],
  [ 'core/heading', {} ]
];
</code>```

The supports is not passed to the block. How can I make this work? Or is there another way.

答:
Your template for InnerBlocks has a small typo in supports: { classname: false } (it's case-sensitive) and should be className:

```<code>const MY_TEMPLATE = [
  [ 'my-block/icon', { supports: { className: false } } ],
  ...
];
</code>```

The supports definition is correct in your my-block/icon block registration. Assuming your save() function handles <InnerBlocks.Content>correctly, with the className typo fixed, it should work.

When in the Editor view and inspecting the classes applied to your block, there will still be many more classes (eg. "wp-block-my-block etc") applied to your block - they are needed to enable the Editors functionality. To confirm if the supports on the inner blocks are working, check the classes applied on the frontend once the post/page is published.

Body:
I am using a template for InnerBlocks and adding predefined attributes like heading level and paragraph placeholder:

const MY_TEMPLATE = [
    [ 'core/image', {} ],
    [ 'core/heading', { level: 3 } ],
    [ 'core/paragraph', { placeholder: 'Summary' } ],
];

//...

    edit: () => {
        return (
            <InnerBlocks
                template={ MY_TEMPLATE }
                templateLock="all"
            />
        );
    },

This works well but how can we add predefined values for block supports?

For example when registering a block I can set support values:

supports: {
    className: false // Remove the support for the generated className.
    color: { // Text UI control is enabled.
        background: false, // Disable background UI control.
        gradients: true // Enable gradients UI control.
    }
}

How can I set values for supports through InnerBlocks templates? For example I want to remove the default wp-block- class name from a block. I tried:

const MY_TEMPLATE = [
  [ 'my-block/icon', { supports: { classname: false } } ],
  [ 'core/heading', {} ]
];

The supports is not passed to the block. How can I make this work? Or is there another way.

Body:
Your template for InnerBlocks has a small typo in supports: { classname: false } (it's case-sensitive) and should be className:

const MY_TEMPLATE = [
  [ 'my-block/icon', { supports: { className: false } } ],
  ...
];

The supports definition is correct in your my-block/icon block registration. Assuming your save() function handles <InnerBlocks.Content>correctly, with the className typo fixed, it should work.

When in the Editor view and inspecting the classes applied to your block, there will still be many more classes (eg. "wp-block-my-block etc") applied to your block - they are needed to enable the Editors functionality. To confirm if the supports on the inner blocks are working, check the classes applied on the frontend once the post/page is published.


问:
How to copy artifacts between projects in Google Artifact Registry
Previously using Container Registry one could copy a container between projects using this method

However I am unable to get this working using Artifact Registry. If I try

```<code>gcloud artifacts docker tags add \
        us-east4-docker.pkg.dev/source-proj/my-repo/my-image:latest \
        us-east4-docker.pkg.dev/dest-proj/my-repo/my-image:latest

</code>```

It gives the error

```<code>ERROR: (gcloud.artifacts.docker.tags.add) Image us-east4-docker.pkg.dev/source-proj/my-repo/my-image
does not match image us-east4-docker.pkg.dev/dest-proj/my-repo/my-image

</code>```

I have searched and can not find any examples or documentation on how to do this.

答:
You can use the gcrane tool to copy images in Artifact Registry.

For example, the following command copies image my-image:latest from the repository my-repo in the project source-proj to the repository my-repo in another project called dest-proj.

```<code>gcrane cp \
    us-east4-docker.pkg.dev/source-proj/my-repo/my-image:latest \
    us-east4-docker.pkg.dev/dest-proj/my-repo/my-image:latest
</code>```

Here is the link to the Google Cloud official documentation.

Body:
Previously using Container Registry one could copy a container between projects using this method

However I am unable to get this working using Artifact Registry. If I try

gcloud artifacts docker tags add \
        us-east4-docker.pkg.dev/source-proj/my-repo/my-image:latest \
        us-east4-docker.pkg.dev/dest-proj/my-repo/my-image:latest

It gives the error

ERROR: (gcloud.artifacts.docker.tags.add) Image us-east4-docker.pkg.dev/source-proj/my-repo/my-image
does not match image us-east4-docker.pkg.dev/dest-proj/my-repo/my-image

I have searched and can not find any examples or documentation on how to do this.

Body:
You can use the gcrane tool to copy images in Artifact Registry.

For example, the following command copies image my-image:latest from the repository my-repo in the project source-proj to the repository my-repo in another project called dest-proj.

gcrane cp \
    us-east4-docker.pkg.dev/source-proj/my-repo/my-image:latest \
    us-east4-docker.pkg.dev/dest-proj/my-repo/my-image:latest

Here is the link to the Google Cloud official documentation.