问:
c++ vector with strict ownership semantics
This is not a question about putting std::auto_ptr into std::vector.

Is there some vector equivalent of std::auto_ptr in std::, std::tr1:: or boost::? I use std::auto_ptr in function parameters and return values to decalre ownership semantics of these functions. But this way I can pass only single objects. As a temporary solution for vectors I have this:

```<code>std::auto_ptr<std::vector<std::tr1::shared_ptr<ClassExample> > > fx(....);
</code>```

which, I suppose, by introducing boost, I will be able to change into this:

```<code>std::auto_ptr<std::vectro<boost::unique_ptr<ClassExample> > >f(...);
</code>```

in order to define strict ownership passing, but it seems to be quite complicated. To simplify it, I can use

```<code>std::vector<boost::unique_ptr<ClassExample> > f(...);
</code>```

as the price for deep copy of the vector is not high, but I am still curious if there is something that I can use like this:

```<code>auto_vector<ClassExample> f(...);
</code>```

meaning that the function is releasing ownership of all the objects and the vector internal data array is not deeply copied.

答:
There's a C++11 solution - it requires an implementation that provides r-value references and has a standard library updated to include move constructors and std::unique_ptr.

Just return std::vector<std::unique_ptr<T>> - that type can't be copied, as std::unique_ptr<T> isn't copyable. The compiler will either use the move constructor when returning, which will not invoke a deep copy or will apply the RVO and elide the construction of a new object.

Body:
This is not a question about putting std::auto_ptr into std::vector.

Is there some vector equivalent of std::auto_ptr in std::, std::tr1:: or boost::? I use std::auto_ptr in function parameters and return values to decalre ownership semantics of these functions. But this way I can pass only single objects. As a temporary solution for vectors I have this:

std::auto_ptr<std::vector<std::tr1::shared_ptr<ClassExample> > > fx(....);

which, I suppose, by introducing boost, I will be able to change into this:

std::auto_ptr<std::vectro<boost::unique_ptr<ClassExample> > >f(...);

in order to define strict ownership passing, but it seems to be quite complicated. To simplify it, I can use

std::vector<boost::unique_ptr<ClassExample> > f(...);

as the price for deep copy of the vector is not high, but I am still curious if there is something that I can use like this:

auto_vector<ClassExample> f(...);

meaning that the function is releasing ownership of all the objects and the vector internal data array is not deeply copied.


来源: stackexchange

问:
Can prometheus don't resolve alert when metric data missing?
There is my Prometheus alert rule

avg_over_time(metricName[1m]) > 100

After alert fired, when the metrci data missing for more than 1 minute, the alert will resolved.

Is there any way to stop the change of alert status?

答:
You can do this by leveraging last_over_time() as in my answer here.

(Answering this old question because it's still a high ranking Google result)

ContentLicense: CC BY-SA 4.0


问:
Append a row above the last row in an excel file using powershell
I have the following code which inserts a row below the row A1000 in my excel file. How could I modify this to insert a row above the last row (will be different each time).</p>
```<code>$xlShiftDown = -4121
$File = Get-ChildItem C:\Test.xls
$XL = New-Object -ComObject Excel.Application
$WB = $XL.Workbooks.Open($File.Fullname)
$XL.Visible = $true
$Sheet = $WB.Worksheets.Item('clients')
$objRange = $XL.Range("A1000").EntireRow
[void]$objRange.Insert($xlShiftDown)
</code>```

答:
Using the Excel ComObject the WorkSheet will have a property called UsedRange that works nicely for things like this.

```<code>$objRange = $($Sheet.UsedRange.Rows)[-1]
</code>```

That should get you the last row of your sheet.

I realized that's probably slow if you have a lot of data. You can instead use the .count property of the UsedRange.Rows, and then just grab that row on the sheet like this:

```<code>$objRange = $Sheet.Rows.Item($Sheet.UsedRange.Rows.Count)
</code>```

Body:
I have the following code which inserts a row below the row A1000 in my excel file. How could I modify this to insert a row above the last row (will be different each time).

$xlShiftDown = -4121
$File = Get-ChildItem C:\Test.xls
$XL = New-Object -ComObject Excel.Application
$WB = $XL.Workbooks.Open($File.Fullname)
$XL.Visible = $true
$Sheet = $WB.Worksheets.Item('clients')
$objRange = $XL.Range("A1000").EntireRow
[void]$objRange.Insert($xlShiftDown)

Body:
Using the Excel ComObject the WorkSheet will have a property called UsedRange that works nicely for things like this.

$objRange = $($Sheet.UsedRange.Rows)[-1]

That should get you the last row of your sheet.

I realized that's probably slow if you have a lot of data. You can instead use the .count property of the UsedRange.Rows, and then just grab that row on the sheet like this:

$objRange = $Sheet.Rows.Item($Sheet.UsedRange.Rows.Count)


问:
SICP The Picture Language Exercise Lambda Argument
```<code>(define (segments->painter segment-list)
  (lambda (frame)
    (for-each
      (lambda (segment)
        (draw-line
          ((frame-coord-map frame)
           (start-segment segment))
          ((frame-coord-map frame)
           (end-segment segment))))
      segment-list)))
</code>```

Some of you have already seen this sicp example before but for the first timers a brief explanation: segments->painter procedure takes arguments from segment list which has values are segments made up from vectors. for-each procedure acts like map but instead returns a list of value, it does operations like printing or in this code it draws lines. frame-coord-map scales frames according to unit square frame. What I don't understand in this code is where does first lambda function takes its argument (frame) from.

答:
Here is a case of currying.

In your code

```<code>(define (segments->painter segment-list)
  (lambda (frame)
     ...))
</code>```

when you call segments->painter, scheme will return an object of some type, let us call figure.  When you apply a graphical frame on this object, scheme will be able to draw your object.

```<code>(define obj1 (segments->painter seg1))
</code>```

obj1 is an object of type figure and this object is able to receive frames.  It is able to do only one action when it receives a frame, namely to get drawn in that frame: (obj1 frame1), (obj1 frame2), etc are actions you can do on that object.

Before to apply the graphical data on some object, it does make sense to talk about that object but it does not make sense to talk about a real representation of that object.  In your case, the object can do one single action: to get drawn.

Between calling the contructor for the figure object and drawing the object you can do some (static) preprocessing, such that in the moment when you call the drawing method, you have already precomputed something.

This is how types are implemented in programming languages.  This Peter Henderson's language is a first introduction to types and to combinators.  This will be developped further in the 4th chapter, where the interpreter uses some precomputed data to execute (it converts the list input format to internal format).

Body:
(define (segments->painter segment-list)
  (lambda (frame)
    (for-each
      (lambda (segment)
        (draw-line
          ((frame-coord-map frame)
           (start-segment segment))
          ((frame-coord-map frame)
           (end-segment segment))))
      segment-list)))

Some of you have already seen this sicp example before but for the first timers a brief explanation: segments->painter procedure takes arguments from segment list which has values are segments made up from vectors. for-each procedure acts like map but instead returns a list of value, it does operations like printing or in this code it draws lines. frame-coord-map scales frames according to unit square frame. What I don't understand in this code is where does first lambda function takes its argument (frame) from.

Body:
Here is a case of currying.

In your code

(define (segments->painter segment-list)
  (lambda (frame)
     ...))

when you call segments->painter, scheme will return an object of some type, let us call figure.  When you apply a graphical frame on this object, scheme will be able to draw your object.

(define obj1 (segments->painter seg1))

obj1 is an object of type figure and this object is able to receive frames.  It is able to do only one action when it receives a frame, namely to get drawn in that frame: (obj1 frame1), (obj1 frame2), etc are actions you can do on that object.

Before to apply the graphical data on some object, it does make sense to talk about that object but it does not make sense to talk about a real representation of that object.  In your case, the object can do one single action: to get drawn.

Between calling the contructor for the figure object and drawing the object you can do some (static) preprocessing, such that in the moment when you call the drawing method, you have already precomputed something.

This is how types are implemented in programming languages.  This Peter Henderson's language is a first introduction to types and to combinators.  This will be developped further in the 4th chapter, where the interpreter uses some precomputed data to execute (it converts the list input format to internal format).


问:
PostgreSQL: How to change log_min_duration_statement so that the change takes effect?
I'm not able to change log_min_duration_statement setting. I connected to postges and tried:

```<code>select setting from pg_settings where name = 'log_min_duration_statement';
-1
alter system set log_min_duration_statement = 0;
select setting from pg_settings where name = 'log_min_duration_statement';
-1
</code>```

Obviously nothing changed; what am I doing wrong?
Thank you, Michael

答:
If you have been unable to solve this with alter system then try to change directly in postgresql.conf. I have previously tried with alter, update, restart server but nothing.

When I've tried directly editing postgresql.conf and restarting I've seen in pg_settings 0 (was -1 previously).

Just remove # before line log_min_duration_statement and change -1 to 0.

In file is this #log_min_duration_statement = -1  and should be this
log_min_duration_statement = 0.

I am not sure why you made this change but take care because some other settings are linked to this one. e.g. log_statement is probably none and should be ddl or all.

Body:
I'm not able to change log_min_duration_statement setting. I connected to postges and tried:

select setting from pg_settings where name = 'log_min_duration_statement';
-1
alter system set log_min_duration_statement = 0;
select setting from pg_settings where name = 'log_min_duration_statement';
-1

Obviously nothing changed; what am I doing wrong?
Thank you, Michael


问:
Angular: render numerous components on (click)
I do not want to render a new component or go to a new route, this is not my intention. I cannot use a single variable with an *ngIf to handle rendering the component as I cannot predict the amount of variables I will need to render.

Here is the situation.

```<code><div ngFor="let stuff of lotsOfStuff">
    <div (click)="generateAnotherComponent()">
         <span>some basic info</span>
         <my-child-component></my-child-component> //component to render on click
    </div>
    <div (click)="generateAnotherComponent()">
          <span>some basic info</span>
          <my-child-component></my-child-component> //component to render on click
    </div>
</div>
</code>```

答:
You can generate the component dynamically.

There are various ways to achieve this, but one would be to use a template variable placed on an element, for example

```
<p>And then targeting this "insertion point" as where you'll place the newly generated components by using <code>ViewContainerRef</code>:</p>
```@ViewChild('ChildInsertionPoint', { read: ViewContainerRef })
    childInsertionPoint: ViewContainerRef;

generateAnotherComponent() {
    this.childInsertionPoint.createComponent(ChildComponent);
}
```

Dynamic component generation became a lot easier with Angular 13 (that's what I've assumed you're using). But if not
Finally, I'm assuming that you will bind your click event to a button instead of the div element itself.

Here's a small example on Stackblitz

Body:
I do not want to render a new component or go to a new route, this is not my intention. I cannot use a single variable with an *ngIf to handle rendering the component as I cannot predict the amount of variables I will need to render.

Here is the situation.

         some basic info
         <my-child-component></my-child-component> //component to render on click

          some basic info
          <my-child-component></my-child-component> //component to render on click

Body:
You can generate the component dynamically.

There are various ways to achieve this, but one would be to use a template variable placed on an element, for example

<div #ChildInsertionPoint></div>

And then targeting this "insertion point" as where you'll place the newly generated components by using ViewContainerRef:

@ViewChild('ChildInsertionPoint', { read: ViewContainerRef })
    childInsertionPoint: ViewContainerRef;

generateAnotherComponent() {
    this.childInsertionPoint.createComponent(ChildComponent);
}

Dynamic component generation became a lot easier with Angular 13 (that's what I've assumed you're using). But if not
Finally, I'm assuming that you will bind your click event to a button instead of the div element itself.

Here's a small example on Stackblitz


问:
python regex for a letter must be surrounded by a another letter
I'm trying to write a regex that only matches a string that includes lowercase a & b  such that each a has the letter b immediately before it and after it.

e.g., the Regex should match the string 'bbbabbababbbbab' but not 'abbbbaabbab'

I have written an expression that does satisfy the example however, the regex should also match a string such as 'bab' but it does not.

My current expression is ^[b]+(ab)+[ab]*[b]$

Anyone have any advice on what I'm doing wrong?

答:
You are repeating single chars ab in the group (ab)+

You can repeat the a's and the b's as well:

```<code>^b+(?:a+b+)*$
</code>```

Regex demo

If you only want to match a single a and the a should be there at least once:

```<code>^b+(?:ab+)+$
</code>```

Regex demo

Body:
You are repeating single chars ab in the group (ab)+

You can repeat the a's and the b's as well:

^b+(?:a+b+)*$

Regex demo

If you only want to match a single a and the a should be there at least once:

^b+(?:ab+)+$

Regex demo


问:
Maven: How to configure native2ascii-maven-plugin
Im firing this question at you guys since the project-page itself has not a lot of information.
Basicly im setting up the native2ascii-maven-plugin to process some of my resources. It works fine for processing the files in root directory. But now i have files under subdirectory: /template/email/ and would like them to be included in the processing. Can you guys please help me out?

```<code>    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>native2ascii-maven-plugin</artifactId>
        <version>1.0-alpha-1</version>
        <configuration>
            <dest>target/resources</dest>
            <src>src/main/resources</src>
        </configuration>
        <executions>
            <execution>
                <id>native2ascii-utf8</id>
                <goals>
                    <goal>native2ascii</goal>
                </goals>
                <configuration>
                    <encoding>UTF8</encoding>
                    <includes>ApplicationResources*.properties, errors.properties, /template/email/newBooking*.ftl</includes>
                </configuration>
            </execution>
        </executions>
    </plugin>
</code>```

Thanks a bunch!!

答:
You need to define a execution section for every folder you want to process and move the src and dest to the execution part: </p>

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>native2ascii-maven-plugin</artifactId>
    <version>1.0-alpha-1</version>
    <executions>
        <execution>
            <id>native2ascii-utf8-resources</id>
            <goals>
                <goal>native2ascii</goal>
            </goals>
            <configuration>
                <dest>target/resources</dest>
                <src>src/main/resources</src>
                <encoding>UTF8</encoding>
                <includes>ApplicationResources*.properties, errors.properties, /template/email/newBooking*.ftl</includes>
            </configuration>
        </execution>
        <execution>
            <id>native2ascii-utf8-email</id>
            <goals>
                <goal>native2ascii</goal>
            </goals>
            <configuration>
                <dest>target/resources/email</dest>
                <src>src/main/templates/email</src>
                <encoding>UTF8</encoding>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im firing this question at you guys since the project-page itself has not a lot of information.
Basicly im setting up the native2ascii-maven-plugin to process some of my resources. It works fine for processing the files in root directory. But now i have files under subdirectory: /template/email/ and would like them to be included in the processing. Can you guys please help me out?

    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>native2ascii-maven-plugin</artifactId>
        <version>1.0-alpha-1</version>
        <configuration>
            <dest>target/resources</dest>
            <src>src/main/resources</src>
        </configuration>
        <executions>
            <execution>
                <id>native2ascii-utf8</id>
                <goals>
                    <goal>native2ascii</goal>
                </goals>
                <configuration>
                    <encoding>UTF8</encoding>
                    <includes>ApplicationResources*.properties, errors.properties, /template/email/newBooking*.ftl</includes>
                </configuration>
            </execution>
        </executions>
    </plugin>

Thanks a bunch!!

Body:
You need to define a execution section for every folder you want to process and move the src and dest to the execution part:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>native2ascii-maven-plugin</artifactId>
    <version>1.0-alpha-1</version>
    <executions>
        <execution>
            <id>native2ascii-utf8-resources</id>
            <goals>
                <goal>native2ascii</goal>
            </goals>
            <configuration>
                <dest>target/resources</dest>
                <src>src/main/resources</src>
                <encoding>UTF8</encoding>
                <includes>ApplicationResources*.properties, errors.properties, /template/email/newBooking*.ftl</includes>
            </configuration>
        </execution>
        <execution>
            <id>native2ascii-utf8-email</id>
            <goals>
                <goal>native2ascii</goal>
            </goals>
            <configuration>
                <dest>target/resources/email</dest>
                <src>src/main/templates/email</src>
                <encoding>UTF8</encoding>
            </configuration>
        </execution>
    </executions>
</plugin>


问:
How can i replace a value in a specific row and column in a csv file
I need to replace a value in correspondence of an ID in a .csv file:

```<code>ChatId,Color
805525230,black
</code>```

So if the ID in input is equal to the one in the file my program will replace the Color "black" with the new one. I tried this:

for idx, row in enumerate(df.ChatId):
    if str(row) == str(CHAT_ID):
        df.loc[1,idx] = BGc
        df.to_csv("path")
```

答:
Assuming you loaded the csv on a dataframe, you could you use some of its functions.

For example: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html

Alternatively, you could use the loc function:

```<code>df.loc[df['ChatId'=='SomeId'], 'Color'] = 'ValueToReplace'
</code>```

If you need to apply it to a different column, you can 'Color' with the appropriate name.

I think you could even include a list of column names, though I haven't tested it

Body:
I need to replace a value in correspondence of an ID in a .csv file:

ChatId,Color
805525230,black

So if the ID in input is equal to the one in the file my program will replace the Color "black" with the new one. I tried this:

for idx, row in enumerate(df.ChatId):
    if str(row) == str(CHAT_ID):
        df.loc[1,idx] = BGc
        df.to_csv("path")

Body:
Assuming you loaded the csv on a dataframe, you could you use some of its functions.

For example: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html

Alternatively, you could use the loc function:

df.loc[df['ChatId'=='SomeId'], 'Color'] = 'ValueToReplace'

If you need to apply it to a different column, you can 'Color' with the appropriate name.

I think you could even include a list of column names, though I haven't tested it


问:
Evaluate polynomials with imaginary numbers
I'm trying to calculate 19v^2 + 49v + 8 to the 67th power over the finite field Z/67Z using Sage where v = sqrt(-2).

Here's what I have so far (using t instead of v):

```<code>R.<t> = PolynomialRing(GF(67))
poly = (19 * (t^2) + 49*t + 8)
poly^67
</code>```

This works fine.
But now, I want to evaluate the resulting polynomial with the value sqrt(-2).

I'm not sure how to proceed. Any ideas?

答:
Computing with a square root of -2 amounts to working modulo
the polynomial t^2 + 2.

The function power_mod can be used for that.

Instead of first powering and then reducing modulo t^2 + 2,
which would be wasteful, it performs the whole powering
process modulo t^2 + 2, which is a lot more efficient.

Here are two ways to write the (same) computation.

sage: t = polygen(GF(67))
sage: p = 19 * t^2 + 49 * t + 8
sage: power_mod(p, 67, t^2 + 2)
```
<pre class="lang-py prettyprint-override"><code>sage: R.<t> = GF(67)[]
sage: p = R([8, 49, 19])
sage: power_mod(p, 67, R([2, 0, 1]))
</code>```

Body:
I'm trying to calculate 19v^2 + 49v + 8 to the 67th power over the finite field Z/67Z using Sage where v = sqrt(-2).

Here's what I have so far (using t instead of v):

R.<t> = PolynomialRing(GF(67))
poly = (19 * (t^2) + 49*t + 8)
poly^67

This works fine.
But now, I want to evaluate the resulting polynomial with the value sqrt(-2).

I'm not sure how to proceed. Any ideas?

Body:
Computing with a square root of -2 amounts to working modulo
the polynomial t^2 + 2.

The function power_mod can be used for that.

Instead of first powering and then reducing modulo t^2 + 2,
which would be wasteful, it performs the whole powering
process modulo t^2 + 2, which is a lot more efficient.

Here are two ways to write the (same) computation.

sage: t = polygen(GF(67))
sage: p = 19 * t^2 + 49 * t + 8
sage: power_mod(p, 67, t^2 + 2)

sage: R.<t> = GF(67)[]
sage: p = R([8, 49, 19])
sage: power_mod(p, 67, R([2, 0, 1]))


问:
function invoked for each element in array, in time intervals
Trying to write a function, that does work for one element in the array - and after time, repeats the same work for the next element (for each element in the array). Array consists of  elements.

Current function does work for all the elements in  the same time.

const wordIntroGroup = document.getElementsByClassName("word");
const forwardBut = document.getElementById("forward");

forwardBut.addEventListener("click", forward);

function forward() {

  const y = wordIntroGroup;

  for (let i = 0; i < y.length; i++) {
    setTimeout(function() {
      console.log(y[i]);
    }, 2000)
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  <span class="word">Naw,</span>
  <span class="word">while</span>
  <span class="word">you're</span>
  <span class="word">here</span>
</p>

<span id="forward" class="material-icons">
  fast_forward
</span></code>```

答:
Your for loop runs every call of your setTimeout function at the same time. So everything will occur 2000ms after the for loop runs. The simplest solution would be to extend the setTimout duration by that of the current location in the array.

```<code>setTimeout(function (){
     console.log(y[i]);
}, 2000*i) // multiply your duration by i, the index of your current element in the array
</code>```

Also your syntax error is you didn't close the function forward at the end of your script

Body:
Trying to write a function, that does work for one element in the array - and after time, repeats the same work for the next element (for each element in the array). Array consists of  elements.

Current function does work for all the elements in  the same time.

const wordIntroGroup = document.getElementsByClassName("word");
const forwardBut = document.getElementById("forward");

forwardBut.addEventListener("click", forward);

function forward() {

  const y = wordIntroGroup;

  for (let i = 0; i < y.length; i++) {
    setTimeout(function() {
      console.log(y[i]);
    }, 2000)
  }
}

  Naw,
  while
  you're
  here

  fast_forward

Body:
Your for loop runs every call of your setTimeout function at the same time. So everything will occur 2000ms after the for loop runs. The simplest solution would be to extend the setTimout duration by that of the current location in the array.

setTimeout(function (){
     console.log(y[i]);
}, 2000*i) // multiply your duration by i, the index of your current element in the array

Also your syntax error is you didn't close the function forward at the end of your script


问:
Jquery loading div before page starts actually loads
I have a page that has to do quite a bit of work (5-6 seconds) of loading data from all over the place on the initial connection.  It is slow because of the api endpoints I am calling, I have no control over it.

Is there a way to get a loading div to show before it starts doing all of its data collection?

The below doesnt do anything. I believe its because the page already starts gathering data before it gets to the jquery.  I could be wrong.  myjs.js is the file name and it is the first thing loaded on my page.

```<code>$('body').on('load', function(){
    $body.addClass("loading");
});
</code>```

and does the same thing

```<code>  $(document).ready(function() {
      $body.addClass("loading");
   });
</code>```

In layman's terms:

User goes to https://somewebsite.com

Jquery loading div shows

other functions run to gather data

jquery loading div is removed.

This is in the laravel framework if that affects anything.

答:
There is actually a pretty simple way to do this. I recently experienced something similar.

I did something like this:

window.addEventListener('load', (event) => {
  setTimeout(() => {
    $('.jumping-dots-loader').slideUp(650);
  }, 1000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.jumping-dots-loader {
  width: 100vw !important;
  height: 100vh !important;
  background-color: white;
  z-index: 99999999999999999999999;
  display: block;
  border: none;
  border-radius: 0;
  margin: 0;
  position: fixed;
  padding: 20% 35%;
  text-align: center;
}

.jumping-dots-loader span {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 100%;
  background-color: rgba(147, 194, 61, 1);
  margin: 35px 0.85rem;
}

/* Add in animation */</code>```

  Howsit going?

```

If you go through Mozilla's docs about the document.readystatechange event, you will see how the browser handles the loading order and can use this to your advantage. In my example, I add a container div which will cover the user's viewport. Then style some dots (add your own animation to them) which will be displayed while the document is loading. When the load state is reached, the placeholder div will be hidden and the loaded page is displayed.

Body:
I have a page that has to do quite a bit of work (5-6 seconds) of loading data from all over the place on the initial connection.  It is slow because of the api endpoints I am calling, I have no control over it.

Is there a way to get a loading div to show before it starts doing all of its data collection?

The below doesnt do anything. I believe its because the page already starts gathering data before it gets to the jquery.  I could be wrong.  myjs.js is the file name and it is the first thing loaded on my page.

$('body').on('load', function(){
    $body.addClass("loading");
});

and does the same thing

  $(document).ready(function() {
      $body.addClass("loading");
   });

In layman's terms:

User goes to https://somewebsite.com

Jquery loading div shows

other functions run to gather data

jquery loading div is removed.

This is in the laravel framework if that affects anything.

Body:
There is actually a pretty simple way to do this. I recently experienced something similar.

I did something like this:

window.addEventListener('load', (event) => {
  setTimeout(() => {
    $('.jumping-dots-loader').slideUp(650);
  }, 1000);
});

.jumping-dots-loader {
  width: 100vw !important;
  height: 100vh !important;
  background-color: white;
  z-index: 99999999999999999999999;
  display: block;
  border: none;
  border-radius: 0;
  margin: 0;
  position: fixed;
  padding: 20% 35%;
  text-align: center;
}

.jumping-dots-loader span {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 100%;
  background-color: rgba(147, 194, 61, 1);
  margin: 35px 0.85rem;
}

/* Add in animation */

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="jumping-dots-loader">
  <span></span>
  <span></span>
  <span></span>
</div>

<h1>
  Howsit going?
</h1>

If you go through Mozilla's docs about the document.readystatechange event, you will see how the browser handles the loading order and can use this to your advantage. In my example, I add a container div which will cover the user's viewport. Then style some dots (add your own animation to them) which will be displayed while the document is loading. When the load state is reached, the placeholder div will be hidden and the loaded page is displayed.


问:
CSS grid layout, 2 items sharing 3 rows?

I want the vertical space for the 4 and 5 blocks to be shared exactly 50%.

I currently have the code configured like:

```<code>  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas:
    "side1 main1"
    "side2 main1"
    "side3 main2";
</code>```

Is it possible to somehow have the main1/main2 to share the space each as 50%?

答:
If you think of it as a grid with 6 rows then side elements can take 2 rows each height and main elements can take 3 rows each height.

* {
  margin: 0;
  padding: 0;
}

.grid {
  display: grid;
  grid-template-areas: "side1 main1" "side1 main1" "side2 main1" "side2 main2" "side3 main2" "side3 main2";
  width: 50vmin;
  /* added just for demo */
  aspect-ratio: 2 / 3;
  gap: 1vmin;
}

.grid>div {
  background: red;
  font-size: 40px;
}

.grid>div:nth-child(1) {
  grid-area: side1;
}

.grid :nth-child(2) {
  grid-area: side2;
}

.grid :nth-child(3) {
  grid-area: side3;
}

.grid :nth-child(4) {
  grid-area: main1;
}

.grid :nth-child(5) {
  grid-area: main2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div></code>```

And as you want the side elements to be squares you can set the overall aspect ratio 2 / 3 and drop the 1fr row and column settings.

Body:
I want the vertical space for the 4 and 5 blocks to be shared exactly 50%.

I currently have the code configured like:

  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas:
    "side1 main1"
    "side2 main1"
    "side3 main2";

Is it possible to somehow have the main1/main2 to share the space each as 50%?

Body:
If you think of it as a grid with 6 rows then side elements can take 2 rows each height and main elements can take 3 rows each height.

* {
  margin: 0;
  padding: 0;
}

.grid {
  display: grid;
  grid-template-areas: "side1 main1" "side1 main1" "side2 main1" "side2 main2" "side3 main2" "side3 main2";
  width: 50vmin;
  /* added just for demo */
  aspect-ratio: 2 / 3;
  gap: 1vmin;
}

.grid>div {
  background: red;
  font-size: 40px;
}

.grid>div:nth-child(1) {
  grid-area: side1;
}

.grid :nth-child(2) {
  grid-area: side2;
}

.grid :nth-child(3) {
  grid-area: side3;
}

.grid :nth-child(4) {
  grid-area: main1;
}

.grid :nth-child(5) {
  grid-area: main2;
}

<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

And as you want the side elements to be squares you can set the overall aspect ratio 2 / 3 and drop the 1fr row and column settings.


问:
activerecord-import gem NoMethodError: undefined method 'import'
I'm trying to use the activerecord-import gem and I've followed the directions on the wiki to a tee but I'm getting a NoMethodError: undefined method 'import' for  #<Class:0x8b009b0>.  Here's my code (basically the same as the example from the wiki)

```<code>    class ExampleCode
      def self.testing
        orders = []
        10.times do |i|
          orders << Order.new(:raw_data => "order #{i}")
        end

        Order.import orders

      end
    end
</code>```

I call the method like so:

```<code>ExampleCode.testing
</code>```

I've tried on windows, linux, with a sqlite database, a mysql database and still no luck.  And I'm certain I have the gem installed:

```<code>actionmailer (3.2.6, 3.2.3, 3.2.1, 3.2.0)
actionpack (3.2.6, 3.2.3, 3.2.1, 3.2.0)
activemodel (3.2.6, 3.2.3, 3.2.1, 3.2.0)
activerecord (3.2.6, 3.2.3, 3.2.1, 3.2.0)
activerecord-import (0.2.10)
activerecord-oracle_enhanced-adapter (1.4.1)
activerecord-sqlserver-adapter (3.2.1)....
</code>```

I even tried to use require (which shouldn't be necessary when the gem is installed.  I haven't seen this come up anywhere else so I fear I must to missing something very obvious

答: I ran into the same thing; turns out that for me at least I had the gem included within a test block in the gemfile. make sure that when you include it it's not just limited to one app environment in the gem file.</p>

Body:
I'm trying to use the activerecord-import gem and I've followed the directions on the wiki to a tee but I'm getting a NoMethodError: undefined method 'import' for  #<Class:0x8b009b0>.  Here's my code (basically the same as the example from the wiki)

    class ExampleCode
      def self.testing
        orders = []
        10.times do |i|
          orders << Order.new(:raw_data => "order #{i}")
        end

        Order.import orders

      end
    end

I call the method like so:

ExampleCode.testing

I've tried on windows, linux, with a sqlite database, a mysql database and still no luck.  And I'm certain I have the gem installed:

actionmailer (3.2.6, 3.2.3, 3.2.1, 3.2.0)
actionpack (3.2.6, 3.2.3, 3.2.1, 3.2.0)
activemodel (3.2.6, 3.2.3, 3.2.1, 3.2.0)
activerecord (3.2.6, 3.2.3, 3.2.1, 3.2.0)
activerecord-import (0.2.10)
activerecord-oracle_enhanced-adapter (1.4.1)
activerecord-sqlserver-adapter (3.2.1)....

I even tried to use require (which shouldn't be necessary when the gem is installed.  I haven't seen this come up anywhere else so I fear I must to missing something very obvious


问:
step progress bar with android compose
Currently I'm trying to find an easy way to implement a step progress bar with compose like this:

Does anyone have experience with that? Is there maybe a good library?

答:
I don't think you need a library from this one, a simple and quick 'do it yourself' solution could be something like this:

```<code>@Composable
fun StepsProgressBar(modifier: Modifier = Modifier, numberOfSteps: Int, currentStep: Int) {
    Row(
        modifier = modifier,
        verticalAlignment = Alignment.CenterVertically
    ) {
        for (step in 0..numberOfSteps) {
            Step(
                modifier = Modifier.weight(1F),
                isCompete = step < currentStep,
                isCurrent = step == currentStep
            )
        }
    }
}

@Composable
fun Step(modifier: Modifier = Modifier, isCompete: Boolean, isCurrent: Boolean) {
    val color = if (isCompete || isCurrent) Color.Red else Color.LightGray
    val innerCircleColor = if (isCompete) Color.Red else Color.LightGray

    Box(modifier = modifier) {

        //Line
        Divider(
            modifier = Modifier.align(Alignment.CenterStart),
            color = color,
            thickness = 2.dp
        )

        //Circle
        Canvas(modifier = Modifier
            .size(15.dp)
            .align(Alignment.CenterEnd)
            .border(
                shape = CircleShape,
                width = 2.dp,
                color = color
            ),
            onDraw = {
                drawCircle(color = innerCircleColor)
            }
        )
    }
}

@Preview
@Composable
fun StepsProgressBarPreview() {
    val currentStep = remember { mutableStateOf(1) }
    StepsProgressBar(modifier = Modifier.fillMaxWidth(), numberOfSteps = 5, currentStep = currentStep.value)
}
</code>```

This will be the result:

Title: step progress bar with android compose

Body:
I don't think you need a library from this one, a simple and quick 'do it yourself' solution could be something like this:

@Composable
fun StepsProgressBar(modifier: Modifier = Modifier, numberOfSteps: Int, currentStep: Int) {
    Row(
        modifier = modifier,
        verticalAlignment = Alignment.CenterVertically
    ) {
        for (step in 0..numberOfSteps) {
            Step(
                modifier = Modifier.weight(1F),
                isCompete = step < currentStep,
                isCurrent = step == currentStep
            )
        }
    }
}

@Composable
fun Step(modifier: Modifier = Modifier, isCompete: Boolean, isCurrent: Boolean) {
    val color = if (isCompete || isCurrent) Color.Red else Color.LightGray
    val innerCircleColor = if (isCompete) Color.Red else Color.LightGray

    Box(modifier = modifier) {

        //Line
        Divider(
            modifier = Modifier.align(Alignment.CenterStart),
            color = color,
            thickness = 2.dp
        )

        //Circle
        Canvas(modifier = Modifier
            .size(15.dp)
            .align(Alignment.CenterEnd)
            .border(
                shape = CircleShape,
                width = 2.dp,
                color = color
            ),
            onDraw = {
                drawCircle(color = innerCircleColor)
            }
        )
    }
}

@Preview
@Composable
fun StepsProgressBarPreview() {
    val currentStep = remember { mutableStateOf(1) }
    StepsProgressBar(modifier = Modifier.fillMaxWidth(), numberOfSteps = 5, currentStep = currentStep.value)
}

This will be the result:


问:
Image not taking full width of page
So I have the following html code

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.logo {
  max-width: 60px;
  padding: 5px;
}

.navigation {
  align-self: flex-end;
}

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: #c5f3f7;
}

.banner {
  margin-top: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

<head>
  <title>HTML Layout</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <header>
    <div class="logo">
      <img src="logo.png">
    </div>
    <nav class="navigation">
      <ul>
        <li>Home</li>
        <li>Products</li>
        <li>About</li>
        <li>News</li>
        <li>Contact</li>
      </ul>
    </nav>
  </header>
  <div class="banner">
    <img src="pagebanner.png" alt="page banner">
  </div>
</body>

</html></code>```

However the banner image does not take up the full width of the page. Instead, it is very small. I have tried doing width = 100% but this does not fix it. What can I do to make the banner image full width?

答:
This is an easy fix. All you need is a little CSS in the img link itself.

```<code>    <!doctype html>
    <html>
    <head>
    <title>HTML Layout</title>
    <link rel="stylesheet" href="style.css">
    </head>
    <body>
    <header>
    <div class="logo">
    <img src="logo.png">
    </div>
    <nav class="navigation">
    <ul>
    <li><a href="index.html">Home</a></li>
    <li><a href="products.html">Products</a></li>
    <li><a href="about.html">About</a></li>
    <li><a href="news.html">News</a></li>
    <li><a href="contact.html">Contact</a></li>
    </ul>
    </nav>
    </header>
    <div class="banner">
    <img src="pagebanner.png" alt="page banner" style="width:100%;">
    </div>
    </body>
    </html>
</code>```

And if you want it to fit the entire page and not just left and right, paste this to where the img link is

```<code>    <img src="pagebanner.png" alt="page banner.png" alt="page banner" style="width:100%;hight:100%;">
</code>```

Remove the banner style from the css code and you should be good to go

Title: Image not taking full width of page

Body:
So I have the following html code

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.logo {
  max-width: 60px;
  padding: 5px;
}

.navigation {
  align-self: flex-end;
}

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: #c5f3f7;
}

.banner {
  margin-top: 30px;
}

<!doctype html>

  <title>HTML Layout</title>
  <link rel="stylesheet" href="style.css">

Home

Products

About

News

Contact

However the banner image does not take up the full width of the page. Instead, it is very small. I have tried doing width = 100% but this does not fix it. What can I do to make the banner image full width?

Body:
This is an easy fix. All you need is a little CSS in the img link itself.

    <!doctype html>
    <html>
    <head>
    <title>HTML Layout</title>
    <link rel="stylesheet" href="style.css">
    </head>
    <body>
    <header>
    <div class="logo">
    <img src="logo.png">
    </div>
    <nav class="navigation">
    <ul>
    <li><a href="index.html">Home</a></li>
    <li><a href="products.html">Products</a></li>
    <li><a href="about.html">About</a></li>
    <li><a href="news.html">News</a></li>
    <li><a href="contact.html">Contact</a></li>
    </ul>
    </nav>
    </header>
    <div class="banner">
    <img src="pagebanner.png" alt="page banner" style="width:100%;">
    </div>
    </body>
    </html>

And if you want it to fit the entire page and not just left and right, paste this to where the img link is

    <img src="pagebanner.png" alt="page banner.png" alt="page banner" style="width:100%;hight:100%;">

Remove the banner style from the css code and you should be good to go


问:
Bad state: field does not exist within the DocumentSnapshotPlatform Flutter Firebase Firestore
I want to show a data string from firebase firestore in my flutter app. This should be an info text. I want that this text gets realtime updated. My problem is with this code that i'm getting this error:

StateError (Bad state: field does not exist within the DocumentSnapshotPlatform)

I've searched trough the entire internet but i haven't found any solutions for this... i hope someone can help me. If you need more code just ask in the comments section :)

```<code>Expanded(
                            child: Container(
                                height: 30,
                                width: 295,
                                child: StreamBuilder(
                                    stream: FirebaseFirestore.instance
                                        .collection('texts')
                                        .snapshots(),
                                    builder: (BuildContext context,
                                        AsyncSnapshot<QuerySnapshot> snapshot) {
                                      if (!snapshot.hasData) {
                                        return Center(
                                          child: Marquee(
                                              text:
                                                  "Info wird geladen        "),
                                        );
                                      }

                                      return ListView(
                                        children:
                                            snapshot.data!.docs.map((document) {
                                          return Container(
                                            child: Center(
                                                child: Text(document['text1'])),
                                          );
                                        }).toList(),
                                      );
                                    })))
</code>```

Cloud Firestore Snapshot:

答: Try: Text(document['startpage'])) instead of Text(document['text1'])),

Body:
I want to show a data string from firebase firestore in my flutter app. This should be an info text. I want that this text gets realtime updated. My problem is with this code that i'm getting this error:

StateError (Bad state: field does not exist within the DocumentSnapshotPlatform)

I've searched trough the entire internet but i haven't found any solutions for this... i hope someone can help me. If you need more code just ask in the comments section :)

Expanded(
                            child: Container(
                                height: 30,
                                width: 295,
                                child: StreamBuilder(
                                    stream: FirebaseFirestore.instance
                                        .collection('texts')
                                        .snapshots(),
                                    builder: (BuildContext context,
                                        AsyncSnapshot<QuerySnapshot> snapshot) {
                                      if (!snapshot.hasData) {
                                        return Center(
                                          child: Marquee(
                                              text:
                                                  "Info wird geladen        "),
                                        );
                                      }

                                      return ListView(
                                        children:
                                            snapshot.data!.docs.map((document) {
                                          return Container(
                                            child: Center(
                                                child: Text(document['text1'])),
                                          );
                                        }).toList(),
                                      );
                                    })))

Cloud Firestore Snapshot:


问:
Access Outlook office mailbox(mails in inbox) using python code through EWS
I was reading the Outlook mails through EWS using python exchangelib module

credentials I was using for authentication: email & app password

Due to some security reasons the platform team have disabled the App password feature and I ended up accessing the mail box as am not sure how to access mail box without App password ???

If there is any alternative to App password please suggest me..

Note: My python script was running in Linux VM

答: When you use an email & app password this is using Basic Authentication which is why your platform team has disabled it. You need to move to using oAuth https://ecederstrand.github.io/exchangelib/#oauth-authentication and make use of the client_credentials flow https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow. So you then use a client secret or certificate rather then username & pword. When using this flow you need to make sure you impersonate the Mailbox your trying to access and also don't use Autodiscover because that will fail with that flow. By default this will give you access to all mailboxes in a tenant so if this is a problem you can scope it down to just the mailboxes you need to access https://techcommunity.microsoft.com/t5/exchange-team-blog/application-access-policy-support-in-ews/ba-p/2110361</p>


问:
Is it possible to arrange only maximum limit of graph in Matlab?
I want to give a maximum value to my ylimit in a graph.

I know ylim command takes minimum and maximum value.

How to arrange maximum limit for y axis, without changing mimimum?

答:
You can't do that directly, but it's easy:

```<code>new_upper = 10; % desired new upper limit
yl = ylim; % store current limits
ylim([yl(1) new_upper]) % set current lower and new upper
</code>```

If you prefer a single line you can use min (you can't index directly into the output of ylim):

```<code>ylim([min(ylim) new_upper])
</code>```

Body:
You can't do that directly, but it's easy:

new_upper = 10; % desired new upper limit
yl = ylim; % store current limits
ylim([yl(1) new_upper]) % set current lower and new upper

If you prefer a single line you can use min (you can't index directly into the output of ylim):

ylim([min(ylim) new_upper])


问:
Storage in laravel says symlink - no such file
I deployed laravel app on shared hosting in public_html/app folder. Here is everything from public folder. In /../../files I have rest of files. When I do php artisan storage:link in files folder my console says

```<code>[ErrorException]
  symlink(): No such file or directory
</code>```

On localhost I upload files to storage/uploads folder. What to do now? I tried to change links but nothing works for me...

答:
more instant i improve the answer of @suresh-pangeni

```<code>mv storage storage.bak // just for backup
</code>```
```<code>mkdir -p storage/{app/public,framework/{cache,data,sessions,testing,views},logs}
</code>```
```<code>php artisan storage:link
</code>```

now its work
dont forget to
Go to /public directory and run:
then
rm storage before run on above command.

☺  pa storage:link

production 9999 ✗ The [public/storage] directory has been linked.

Body:
I deployed laravel app on shared hosting in public_html/app folder. Here is everything from public folder. In /../../files I have rest of files. When I do php artisan storage:link in files folder my console says

[ErrorException]
  symlink(): No such file or directory

On localhost I upload files to storage/uploads folder. What to do now? I tried to change links but nothing works for me...

Body:
more instant i improve the answer of @suresh-pangeni

mv storage storage.bak // just for backup

mkdir -p storage/{app/public,framework/{cache,data,sessions,testing,views},logs}

php artisan storage:link

now its work
dont forget to
Go to /public directory and run:
then
rm storage before run on above command.

☺  pa storage:link

production 9999 ✗ The [public/storage] directory has been linked.


问:
Why are Blazor pages not firing in my ASP.Net app
I'm writing an ASP.Net Core app based on Freeman's book.
And while adding Blazor pages, I got a problem. When you try to go to pages that Blazor is connected to, nothing is displayed on them.

The browser console shows these errors:

Error: System.NullReferenceException: Object reference not set to an
instance of an object.    at
Microsoft.AspNetCore.Components.Routing.Router.Refresh(Boolean
isNavigationIntercepted)    at
Microsoft.AspNetCore.Components.Routing.Router.SetParametersAsync(ParameterView
parameters)

My Routed.razor file:

```<code><Router AppAssembly="@typeof(Program).Assembly"
    AdditionalAssemblies="new[]{typeof(Program).Assembly}">
<Found>
    <RouteView RouteData="@context" DefaultLayout="typeof(AdminLayout)" />
</Found>
<NotFound>
    <h4 class="bg-danger text-white text-center p-2">
        No Matching Route Found
    </h4>
</NotFound>
</code>```

What could be the problem?

I also add a link to the repository of my project:

https://github.com/itehnoviking/CoinStore

答:
I had to "Hack" your Program to get your solution running.  Here's my version:

```<code>using CoinStore.Models;
using Microsoft.EntityFrameworkCore;

namespace CoinStore
{
    public class Program
    {

        public static void Main(string[] args)
        {

            var builder = WebApplication.CreateBuilder(args);

            var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

            builder.Services.AddDbContext<StoreDbContext>(opt => opt.UseSqlServer(connectionString));

            builder.Services.AddScoped<IStoreRepository, EFStoreRepository>();
            builder.Services.AddScoped<IOrderRepository, EFOrderRepository>();
            builder.Services.AddRazorPages();
            builder.Services.AddDistributedMemoryCache();
            builder.Services.AddSession();
            builder.Services.AddScoped<Cart>(sp => SessionCart.GetCart(sp));
            builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //builder.Services.AddServerSideBlazor();

            //builder.Services.AddServerSideBlazor().AddCircuitOptions(o => {
            //    o.DetailedErrors = _env.IsDevelopment;
            //}).AddHubOptions(opt => {
            //    opt.MaximumReceiveMessageSize = 10 * 1024 * 1024; // 10MB
            //});

            builder.Services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseDeveloperExceptionPage();
            //app.UseStatusCodePages();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();
            app.UseRouting();

            app.UseAuthorization();

            //app.UseEndpoints(endpoints => {
            //    endpoints.MapControllerRoute("catpage",
            //        "{category}/Page{productPage:int}",
            //        new { Controller = "Home", action = "Index" });

            //    endpoints.MapControllerRoute("page", "Page{productPage:int}",
            //        new { Controller = "Home", action = "Index", productPage = 1 });

            //    endpoints.MapControllerRoute("category", "{category}",
            //        new { Controller = "Home", action = "Index", productPage = 1 });

            //    endpoints.MapControllerRoute("pagination",
            //        "Products/Page{productPage}",
            //        new { Controller = "Home", action = "Index", productPage = 1 });
            //    endpoints.MapDefaultControllerRoute();
            //    endpoints.MapRazorPages();
            //    endpoints.MapBlazorHub();
            //    endpoints.MapFallbackToPage("/admin/{*catchall}", "/Admin/Index");
            //});

            //app.MapControllerRoute("catpage", "{category}/Page{productPage:int}", new { controller = "Home", action = "index" });
            //app.MapControllerRoute("page", "Page{productPage:int}", new { controller = "Home", action = "index", productPage = 1 });
            //app.MapControllerRoute("category", "{category}", new { controller = "Home", action = "index", productPage = 1 });
            //app.MapControllerRoute("pagination", "Products/Page{productPage}", new { controller = "Home", action = "index", productPage = 1 });

            //app.MapControllerRoute(
            //    name: "default",
            //    pattern: "{controller=Home}/{action=Index}/{id?}");

            //app.MapDefaultControllerRoute();
            app.MapRazorPages();
            app.MapBlazorHub();
            app.MapFallbackToPage("/admin/{*catchall}", "/Admin/Index");

            //SeedData.EnsurePopulated(app);

            app.Run();

        }
    }
}
</code>```

I then update Routed.razor - no duplication of assemblies any more which was the main issue.

```<code><Router AppAssembly="@typeof(Program).Assembly">
    <Found>
        <RouteView RouteData="@context" DefaultLayout="typeof(AdminLayout)" />
    </Found>
    <NotFound>
        <h4 class="bg-danger text-white text-center p-2">
            No Matching Route Found
        </h4>
    </NotFound>
</Router>
</code>```

And a quick fix to Index to get the references correct:

```<code>@page "/admin"
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
    <head>
        <title>CoinStore Admin</title>
        <link href="/lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
        <base href="~/" />
    </head>
    <body>
        <component type="typeof(Routed)" render-mode="Server" />
        <script src="/_framework/blazor.server.js"></script>
    </body>
</html>
</code>```

And I get:

Body:
I'm writing an ASP.Net Core app based on Freeman's book.
And while adding Blazor pages, I got a problem. When you try to go to pages that Blazor is connected to, nothing is displayed on them.

The browser console shows these errors:

Error: System.NullReferenceException: Object reference not set to an
instance of an object.    at
Microsoft.AspNetCore.Components.Routing.Router.Refresh(Boolean
isNavigationIntercepted)    at
Microsoft.AspNetCore.Components.Routing.Router.SetParametersAsync(ParameterView
parameters)

My Routed.razor file:

<Router AppAssembly="@typeof(Program).Assembly"
    AdditionalAssemblies="new[]{typeof(Program).Assembly}">
<Found>
    <RouteView RouteData="@context" DefaultLayout="typeof(AdminLayout)" />
</Found>
<NotFound>

        No Matching Route Found

</NotFound>

What could be the problem?

I also add a link to the repository of my project:

https://github.com/itehnoviking/CoinStore

Body:
I had to "Hack" your Program to get your solution running.  Here's my version:

using CoinStore.Models;
using Microsoft.EntityFrameworkCore;

namespace CoinStore
{
    public class Program
    {

        public static void Main(string[] args)
        {

            var builder = WebApplication.CreateBuilder(args);

            var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

            builder.Services.AddDbContext<StoreDbContext>(opt => opt.UseSqlServer(connectionString));

            builder.Services.AddScoped<IStoreRepository, EFStoreRepository>();
            builder.Services.AddScoped<IOrderRepository, EFOrderRepository>();
            builder.Services.AddRazorPages();
            builder.Services.AddDistributedMemoryCache();
            builder.Services.AddSession();
            builder.Services.AddScoped<Cart>(sp => SessionCart.GetCart(sp));
            builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //builder.Services.AddServerSideBlazor();

            //builder.Services.AddServerSideBlazor().AddCircuitOptions(o => {
            //    o.DetailedErrors = _env.IsDevelopment;
            //}).AddHubOptions(opt => {
            //    opt.MaximumReceiveMessageSize = 10 * 1024 * 1024; // 10MB
            //});

            builder.Services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseDeveloperExceptionPage();
            //app.UseStatusCodePages();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();
            app.UseRouting();

            app.UseAuthorization();

            //app.UseEndpoints(endpoints => {
            //    endpoints.MapControllerRoute("catpage",
            //        "{category}/Page{productPage:int}",
            //        new { Controller = "Home", action = "Index" });

            //    endpoints.MapControllerRoute("page", "Page{productPage:int}",
            //        new { Controller = "Home", action = "Index", productPage = 1 });

            //    endpoints.MapControllerRoute("category", "{category}",
            //        new { Controller = "Home", action = "Index", productPage = 1 });

            //    endpoints.MapControllerRoute("pagination",
            //        "Products/Page{productPage}",
            //        new { Controller = "Home", action = "Index", productPage = 1 });
            //    endpoints.MapDefaultControllerRoute();
            //    endpoints.MapRazorPages();
            //    endpoints.MapBlazorHub();
            //    endpoints.MapFallbackToPage("/admin/{*catchall}", "/Admin/Index");
            //});

            //app.MapControllerRoute("catpage", "{category}/Page{productPage:int}", new { controller = "Home", action = "index" });
            //app.MapControllerRoute("page", "Page{productPage:int}", new { controller = "Home", action = "index", productPage = 1 });
            //app.MapControllerRoute("category", "{category}", new { controller = "Home", action = "index", productPage = 1 });
            //app.MapControllerRoute("pagination", "Products/Page{productPage}", new { controller = "Home", action = "index", productPage = 1 });

            //app.MapControllerRoute(
            //    name: "default",
            //    pattern: "{controller=Home}/{action=Index}/{id?}");

            //app.MapDefaultControllerRoute();
            app.MapRazorPages();
            app.MapBlazorHub();
            app.MapFallbackToPage("/admin/{*catchall}", "/Admin/Index");

            //SeedData.EnsurePopulated(app);

            app.Run();

        }
    }
}

I then update Routed.razor - no duplication of assemblies any more which was the main issue.

<Router AppAssembly="@typeof(Program).Assembly">
    <Found>
        <RouteView RouteData="@context" DefaultLayout="typeof(AdminLayout)" />
    </Found>
    <NotFound>
        <h4 class="bg-danger text-white text-center p-2">
            No Matching Route Found
        </h4>
    </NotFound>
</Router>

And a quick fix to Index to get the references correct:

@page "/admin"
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
    <head>
        <title>CoinStore Admin</title>
        <link href="/lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
        <base href="~/" />
    </head>
    <body>
        <component type="typeof(Routed)" render-mode="Server" />
        <script src="/_framework/blazor.server.js"></script>
    </body>
</html>

And I get:


问:
Smart cast to 'USER' is impossible, because 'whoIfollow' is a mutable property that could have been changed by this time
So I am learnign kotlin, classes.
I get this error in the title.
I create a class called USER, within this class there is the field whoIfollow, and his type is USER. Within the USER class there is the whoHeFollows() function, which checks if whoIfollow is null or not.

I did it in 4 different ways, and in two of them it worked, in two of them I got the error. I would like to understand why this is, the theory that explains it. Thanks.

What I found strange is that in my opinion the first and third way should be identical(alsop the others.. but idk i have the feeling these 2 are more similar ), however one generates the error and the other does not... please someone clarify this for me. Thanks in advance.

The code:

```<code>fun main(){

    class USER(var name: String, val age: Int, var whoIfollow: USER? = null){

/*
               These 2 ways work:
==========================================
         fun whoHeFollows(): String{
           val x =  whoIfollow?.nome ?: "nobody"
           return "$name follows $x"
           }
==========================================
          fun whoHeFollows(): String{
          val whoIfollow2 = quemEuSigo
          if(whoIfollow2!=null){
          val x = whoIfollow2.nome
          return "$name follows $x"
           }
           else{return "$name follows nobody"}
          }
          }

             These 2 does not work:
==========================================
             fun whoHeFollows(): String{
             whoIfollow?.let{
                val x = whoIfollow.nome
                return "$name follows nobody"
            }
            }
==========================================
            fun whoHeFollows(): String{
            if(whoIfollow!=null){
               val x = whoIfollow.name
               return "$name segue $x"
           }
           else{return "$name follows nobody"}
          }

==========================================
                  WHY?
*/

                                                    }

    val x = USER("luiz",25)
    val y = USER("joao", 15)
    //x.whoIfollow = y
    y.whoIfollow = x

    println(x.whoHeFollows())
    println(y.whoHeFollows())

}
</code>```

答:
Error message basically explains what is happening here. whoIfollow property is mutable, so after you checked it is not null, some other thread might change it to null and then whoIfollow.nome would result in NullPointerException.

First example works, because ?. operator passes not-null value to the next step. It does not access the property twice. It acquires the property value, checks this value for null and if it is not null then it invokes name on exactly the same value it already checked.

Second example works, because local variable whoIfollow2 can't be modified by anyone, so if it was checked for null already, then it can't change.

Third example would work if you would use it.name instead of whoIfollow.nome. It would be similar to the first example: it acquires the property once and if it is not null, then use the same value again to acquire name.

Fourth can't work. Value of whoIfollow property may change between hoIfollow!=null check and whoIfollow.name.

Body:
So I am learnign kotlin, classes.
I get this error in the title.
I create a class called USER, within this class there is the field whoIfollow, and his type is USER. Within the USER class there is the whoHeFollows() function, which checks if whoIfollow is null or not.

I did it in 4 different ways, and in two of them it worked, in two of them I got the error. I would like to understand why this is, the theory that explains it. Thanks.

What I found strange is that in my opinion the first and third way should be identical(alsop the others.. but idk i have the feeling these 2 are more similar ), however one generates the error and the other does not... please someone clarify this for me. Thanks in advance.

The code:

fun main(){

    class USER(var name: String, val age: Int, var whoIfollow: USER? = null){

/*
               These 2 ways work:
==========================================
         fun whoHeFollows(): String{
           val x =  whoIfollow?.nome ?: "nobody"
           return "$name follows $x"
           }
==========================================
          fun whoHeFollows(): String{
          val whoIfollow2 = quemEuSigo
          if(whoIfollow2!=null){
          val x = whoIfollow2.nome
          return "$name follows $x"
           }
           else{return "$name follows nobody"}
          }
          }

             These 2 does not work:
==========================================
             fun whoHeFollows(): String{
             whoIfollow?.let{
                val x = whoIfollow.nome
                return "$name follows nobody"
            }
            }
==========================================
            fun whoHeFollows(): String{
            if(whoIfollow!=null){
               val x = whoIfollow.name
               return "$name segue $x"
           }
           else{return "$name follows nobody"}
          }

==========================================
                  WHY?
*/

                                                    }

    val x = USER("luiz",25)
    val y = USER("joao", 15)
    //x.whoIfollow = y
    y.whoIfollow = x

    println(x.whoHeFollows())
    println(y.whoHeFollows())

}


问:
what is the difference between Update & FixedUpdate in Unity?
What is the difference between the Update and FixedUpdate methods, and when should these methods be used?

答:
I found this answer by OncaLupe to be the best explanation:

For others that may not know the difference: Update runs at the same
frequency as the game's framerate. If you're getting 100 FPS, then
Update() runs 100 times per second. FixedUpdate() runs at a constant
50 FPS to match the physics engine.

There's nothing inherently wrong with only using FixedUpdate, and it
is where physics calculations and changes should go since it matches
the physics engine. However if you're doing things like manually
moving non physics objects around and your game runs at a higher
framerate, you may notice the movement stutters since there's frames
where nothing moves. Using Update makes sure the movement happens
every visual frame.

Also, if you need to use inputs that only trigger when a button is
pressed down and not when being held (jumps, single fire weapons,
etc), you will likely miss them in FixedUpdate. Things like
GetButtonDown/GetButtonUp are only set for one frame of the game when
the user presses the button, and go back to false the next frame.

In the end though, it all depends on your game and how you set it up
or program it. If only using FixedUpdate works for you, then you're
free to stick with it. Just realize that there are some limitations
like missing one frame triggers and possible movement stuttering with
non-physics movements.


问:
unzip -j -o not working through Ansible, but working directly on host
I am trying to grab one file from app.war called test.properties, this command works perfectly on a RHEL host when I run it directly on it:

unzip -j -o /home/test/app.war "*test.properties*"
```
<p><strong>But</strong>, when I run the same thing in Ansible, it does not work, it does not extract anything, there is no change:</p>
<pre class="lang-yaml prettyprint-override"><code>- name: Extract test.properties file
  shell: 'unzip -j -o /home/test/app.war "*test.properties*"'
</code>```

FYI, I CANNOT use Unarchive Module due to Ansible being version 2.9 . Am I doing anything wrong Ansible side? Maybe I am missing something extra like sudo or quotes?

答:
It would actually be a better idea to get what you learned in your previous question and to feed it back in the proper Ansible module: unarchive, as it does allow you to feed the -j option in the extra_opts parameter.

Given the task:

- unarchive:
    src: /home/test/app.war
    dest: /tmp
    include:
      - '*test.properties'
    extra_opts:
      - -j
```
<p>You will get any file ending in <em>test.properties</em> only, thanks to the <code>include</code> parameter, extracted in the <em>/tmp</em> folder without any of its original path structure, thanks to the option <code>-j</code> given to <code>extra_opts</code>.</p>
<hr />
<p>Since you are on a 2.9 version of Ansible — which I really recommend you to upgrade, due to its end of life being 31 December 2021 — what you can do it to use the trick raised in this comment from Ansible issue tracker:</p>
<blockquote>
<p>The <code>extra_opt</code>s are placed before the module arguments, with the .zip file before the filename to extract. The error resulting from the .zip file argument placed by the module may then be ignored by <code>ignore_errors: yes</code></p>
</blockquote>
<p><em>Source: @ossm1db comment on Ansible issue tracker</em></p>
<p>But, we can try to have a better hack, with the usage of <code>failed_when</code> in order to have as less false positive as possible, something like:</p>
<pre class="lang-yaml prettyprint-override"><code>- unarchive:
    src: /home/test/app.war
    dest: /tmp
    extra_opts:
      - -j
      - /home/test/app.war
      - '*test.properties'
  register: _unarchive
  failed_when:
    - "not _unarchive.extract_results.out is search(
        'extracting: .*/test.properties'
      )"
    - _unarchive.extract_results.rc != 0
</code>```

Two things to note here:

Mind that, the path to the WAR file have to be repeated in the src parameter and the extra_opts one, that is what makes it a ugly solution that called for the addition of include in later version.

There are false positive that might arise here, with the usage of failed_when, namely the command could fail behind the scene, but Ansible will still marks it as ok, as long as the regex extracting: .*/test.properties is matched in the extraction output. This is actually what @ossm1db is raising in their comment in the issue tracker quoted above.

Body:
I am trying to grab one file from app.war called test.properties, this command works perfectly on a RHEL host when I run it directly on it:

unzip -j -o /home/test/app.war "*test.properties*"

But, when I run the same thing in Ansible, it does not work, it does not extract anything, there is no change:

- name: Extract test.properties file
  shell: 'unzip -j -o /home/test/app.war "*test.properties*"'

FYI, I CANNOT use Unarchive Module due to Ansible being version 2.9 . Am I doing anything wrong Ansible side? Maybe I am missing something extra like sudo or quotes?

Body:
It would actually be a better idea to get what you learned in your previous question and to feed it back in the proper Ansible module: unarchive, as it does allow you to feed the -j option in the extra_opts parameter.

Given the task:

- unarchive:
    src: /home/test/app.war
    dest: /tmp
    include:
      - '*test.properties'
    extra_opts:
      - -j

You will get any file ending in test.properties only, thanks to the include parameter, extracted in the /tmp folder without any of its original path structure, thanks to the option -j given to extra_opts.

Since you are on a 2.9 version of Ansible — which I really recommend you to upgrade, due to its end of life being 31 December 2021 — what you can do it to use the trick raised in this comment from Ansible issue tracker:

The extra_opts are placed before the module arguments, with the .zip file before the filename to extract. The error resulting from the .zip file argument placed by the module may then be ignored by ignore_errors: yes

Source: @ossm1db comment on Ansible issue tracker

But, we can try to have a better hack, with the usage of failed_when in order to have as less false positive as possible, something like:

- unarchive:
    src: /home/test/app.war
    dest: /tmp
    extra_opts:
      - -j
      - /home/test/app.war
      - '*test.properties'
  register: _unarchive
  failed_when:
    - "not _unarchive.extract_results.out is search(
        'extracting: .*/test.properties'
      )"
    - _unarchive.extract_results.rc != 0

Two things to note here:

Mind that, the path to the WAR file have to be repeated in the src parameter and the extra_opts one, that is what makes it a ugly solution that called for the addition of include in later version.

There are false positive that might arise here, with the usage of failed_when, namely the command could fail behind the scene, but Ansible will still marks it as ok, as long as the regex extracting: .*/test.properties is matched in the extraction output. This is actually what @ossm1db is raising in their comment in the issue tracker quoted above.


问:
Python if statement optimisation
I am making a pretty basic password generator which asks the user for certain things they want in the password (e.g. the user can choose whether or not they want punctuation ). I've completed the program, and it runs perfectly fine, but it includes a section of if and statements:

```<code>if p == "N" and ucl == "N" and lcl == "N":
    print("Invalid requirements ")
if p == "N" and ucl == "N" and lcl == "Y":
    x = lclList
    generate(x)
if p == "N" and ucl == "Y" and lcl == "N":
    x = uclList
    generate(x)
if p == "N" and ucl == "Y" and lcl == "Y":
    x = uclList + lclList
    generate(x)
if p == "Y" and ucl == "Y" and lcl == "Y":
    x = pList + uclList + lclList
    generate(x)
if p == "Y" and ucl == "N" and lcl == "Y":
    x = pList + lclList
    generate(x)
if p == "Y" and ucl == "Y" and lcl == "N":
    x = pList + uclList
    generate(x)
if p == "Y" and ucl == "N" and lcl == "N":
    x = pList
    generate(x)
</code>```

As I said, it runs fine, but looks real messy and inefficient - I can already imagine how convoluted it would have to be if I used 4 requirements, and god forbid any more. Is there another way of programming this that would make it repeatable and more efficient?

Side note, this is pretty much the first fully functioning program I've wrote, so don't be shocked if I've broken some programming Geneva convention.

答:
This is your first fully functioning program, so i will give you some tips:

Use boolean (True/False) to determine the status of Yes or No (currently a string).

When you are nesting if statements that are exclusive, use elif.

Your code (corrected) should look like this (assuming p, lcl and ucl are booleans, instead of strings):

```<code># Init empty list.
x = []

# Append elements to your list.
if lcl:
    x += lclList
if ucl:
    x += uclList
if p:
    x += pList

# Check if selections are valid (x won't be an empty list, you can use if statement too) or print error message.
if x:
    generate(x)
else:
    print("Invalid requirements ")
</code>```

Hope this helps you to improve your coding!

Title: Python if statement optimisation

Body:
I am making a pretty basic password generator which asks the user for certain things they want in the password (e.g. the user can choose whether or not they want punctuation ). I've completed the program, and it runs perfectly fine, but it includes a section of if and statements:

if p == "N" and ucl == "N" and lcl == "N":
    print("Invalid requirements ")
if p == "N" and ucl == "N" and lcl == "Y":
    x = lclList
    generate(x)
if p == "N" and ucl == "Y" and lcl == "N":
    x = uclList
    generate(x)
if p == "N" and ucl == "Y" and lcl == "Y":
    x = uclList + lclList
    generate(x)
if p == "Y" and ucl == "Y" and lcl == "Y":
    x = pList + uclList + lclList
    generate(x)
if p == "Y" and ucl == "N" and lcl == "Y":
    x = pList + lclList
    generate(x)
if p == "Y" and ucl == "Y" and lcl == "N":
    x = pList + uclList
    generate(x)
if p == "Y" and ucl == "N" and lcl == "N":
    x = pList
    generate(x)

As I said, it runs fine, but looks real messy and inefficient - I can already imagine how convoluted it would have to be if I used 4 requirements, and god forbid any more. Is there another way of programming this that would make it repeatable and more efficient?

Side note, this is pretty much the first fully functioning program I've wrote, so don't be shocked if I've broken some programming Geneva convention.

Body:
This is your first fully functioning program, so i will give you some tips:

Use boolean (True/False) to determine the status of Yes or No (currently a string).

When you are nesting if statements that are exclusive, use elif.

Your code (corrected) should look like this (assuming p, lcl and ucl are booleans, instead of strings):

# Init empty list.
x = []

# Append elements to your list.
if lcl:
    x += lclList
if ucl:
    x += uclList
if p:
    x += pList

# Check if selections are valid (x won't be an empty list, you can use if statement too) or print error message.
if x:
    generate(x)
else:
    print("Invalid requirements ")

Hope this helps you to improve your coding!


问:
Why is Softmax applied at axis=0 for Policy Gradient methods(REINFORCE algorithm)
I am going through the fourth chapter of the book - Deep Reinforcement Learning in Action(Manning Publication). This chapter explains the code to apply reinforcement learning to Cart-Pole game. There are only 2 actions possible - left,right. The model accepts state encoded as a vector and outputs probabilities corresponding to 2 actions.
The model(developed in pytorch) has been defined as -

```<code>l1 = 4
l2 = 150
l3 = 2

model = torch.nn.Sequential(
    torch.nn.Linear(l1, l2),
    torch.nn.LeakyReLU(),
    torch.nn.Linear(l2, l3),
    torch.nn.Softmax(dim=0)
)
</code>```

The Softmax layer at the end has been applied at axis=0. I can understand this as a means of creating probability distribution between 2 actions(left or right). So, when a state is given to this model it outputs a 2 dimensional vector of probabilities.For example - [0.25,0.75]
However, what is puzzling me is that when a batch of states would be given to this model then the softmax(since it is applied on axis=0) would be applied across the first action set of the batch and then it would be applied to the second action set of the batch rather than getting applied to each action pair of the batch.So, the sum of first actions of the batch would be 1 and the sum of second actions of the batch would be 1. One sample of output of the model is shown below-

```<code>tensor([[0.0541, 0.0580],
        [0.0542, 0.0556],
        [0.0542, 0.0579],
        [0.0555, 0.0592],
        [0.0578, 0.0597],
        [0.0556, 0.0590],
        [0.0578, 0.0596],
        [0.0603, 0.0598],
        [0.0616, 0.0595],
        [0.0602, 0.0596],
        [0.0616, 0.0594],
        [0.0600, 0.0594],
        [0.0614, 0.0592],
        [0.0622, 0.0585],
        [0.0611, 0.0589],
        [0.0617, 0.0582],
        [0.0606, 0.0585]], grad_fn=<SoftmaxBackward>)
</code>```

The sum of the first actions is 1 and same is the case for second action.
Why is the softmax applied like this in Policy Gradient method?

答:
you need to be using softmax on the second dimension so that it will calculate the probability distribution in every step. Just change the following line to:

```<code>torch.nn.Softmax(dim=1)
</code>```

In general you will be applying the softmax as such in most cases in policy gradient. We always care about probalitly distrubution of the actions we can take in that state.

Body:
I am going through the fourth chapter of the book - Deep Reinforcement Learning in Action(Manning Publication). This chapter explains the code to apply reinforcement learning to Cart-Pole game. There are only 2 actions possible - left,right. The model accepts state encoded as a vector and outputs probabilities corresponding to 2 actions.
The model(developed in pytorch) has been defined as -

l1 = 4
l2 = 150
l3 = 2

model = torch.nn.Sequential(
    torch.nn.Linear(l1, l2),
    torch.nn.LeakyReLU(),
    torch.nn.Linear(l2, l3),
    torch.nn.Softmax(dim=0)
)

The Softmax layer at the end has been applied at axis=0. I can understand this as a means of creating probability distribution between 2 actions(left or right). So, when a state is given to this model it outputs a 2 dimensional vector of probabilities.For example - [0.25,0.75]
However, what is puzzling me is that when a batch of states would be given to this model then the softmax(since it is applied on axis=0) would be applied across the first action set of the batch and then it would be applied to the second action set of the batch rather than getting applied to each action pair of the batch.So, the sum of first actions of the batch would be 1 and the sum of second actions of the batch would be 1. One sample of output of the model is shown below-

tensor([[0.0541, 0.0580],
        [0.0542, 0.0556],
        [0.0542, 0.0579],
        [0.0555, 0.0592],
        [0.0578, 0.0597],
        [0.0556, 0.0590],
        [0.0578, 0.0596],
        [0.0603, 0.0598],
        [0.0616, 0.0595],
        [0.0602, 0.0596],
        [0.0616, 0.0594],
        [0.0600, 0.0594],
        [0.0614, 0.0592],
        [0.0622, 0.0585],
        [0.0611, 0.0589],
        [0.0617, 0.0582],
        [0.0606, 0.0585]], grad_fn=<SoftmaxBackward>)

The sum of the first actions is 1 and same is the case for second action.
Why is the softmax applied like this in Policy Gradient method?

Body:
you need to be using softmax on the second dimension so that it will calculate the probability distribution in every step. Just change the following line to:

torch.nn.Softmax(dim=1)

In general you will be applying the softmax as such in most cases in policy gradient. We always care about probalitly distrubution of the actions we can take in that state.


问:
How to import a stack if the VPCID for the InstanceSecurityGroup is String
```<code>MySecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allow http to client host
      SecurityGroupIngress:
          - IpProtocol: tcp
            FromPort: 80
            ToPort: 80
            CidrIp: !Ref SSHLocation
      SecurityGroupIngress:
          - IpProtocol: tcp
            FromPort: 443
            ToPort: 443
            CidrIp: !Ref SSHLocation
      SecurityGroupIngress:
          - IpProtocol: tcp
            FromPort: 22
            ToPort: 22
            CidrIp: !Ref SSHLocation
      VpcId:
          - Fn::ImportValue: !Sub ${ExportVPCStack}-VPC
</code>```

I'm getting an error that VPCId for Instance Security group is String.

How can i do this to avoid getting an error?

答:
You are creating VpcId as a list due to -. It should be:

```<code>      VpcId:
         Fn::ImportValue: !Sub ${ExportVPCStack}-VPC
</code>```

Body:
MySecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allow http to client host
      SecurityGroupIngress:
          - IpProtocol: tcp
            FromPort: 80
            ToPort: 80
            CidrIp: !Ref SSHLocation
      SecurityGroupIngress:
          - IpProtocol: tcp
            FromPort: 443
            ToPort: 443
            CidrIp: !Ref SSHLocation
      SecurityGroupIngress:
          - IpProtocol: tcp
            FromPort: 22
            ToPort: 22
            CidrIp: !Ref SSHLocation
      VpcId:
          - Fn::ImportValue: !Sub ${ExportVPCStack}-VPC

I'm getting an error that VPCId for Instance Security group is String.

How can i do this to avoid getting an error?

Body:
You are creating VpcId as a list due to -. It should be:

      VpcId:
         Fn::ImportValue: !Sub ${ExportVPCStack}-VPC


问:
C++0x thread interruption
According to the C++0x final draft, there's no way to request a thread to terminate. That said, if required we need to implement a do-it-yourself solution.

On the other hand boost::thread provides a mechanism to interrupt a thread in a safe manner.

In your opinion, what's the best solution? Designing your own cooperative 'interruption mechanism' or going native?

答:
Here is my humble implementation of a thread canceller (for C++0x).
I hope it will be useful.</p>

```<code>// Class cancellation_point
#include <mutex>
#include <condition_variable>

struct cancelled_error {};

class cancellation_point
{
public:
    cancellation_point(): stop_(false) {}

    void cancel() {
        std::unique_lock<std::mutex> lock(mutex_);
        stop_ = true;
        cond_.notify_all();
    }

    template <typename P>
    void wait(const P& period) {
        std::unique_lock<std::mutex> lock(mutex_);
        if (stop_ || cond_.wait_for(lock, period) == std::cv_status::no_timeout) {
            stop_ = false;
            throw cancelled_error();
        }
    }
private:
    bool stop_;
    std::mutex mutex_;
    std::condition_variable cond_;
};

// Usage example
#include <thread>
#include <iostream>

class ThreadExample
{
public:
    void start() {
        thread_ = std::unique_ptr<std::thread>(
            new std::thread(std::bind(&ThreadExample::run, this)));
    }
    void stop() {
        cpoint_.cancel();
        thread_->join();
    }
private:
    void run() {
        std::cout << "thread started\n";
        try {
            while (true) {
                cpoint_.wait(std::chrono::seconds(1));
            }
        } catch (const cancelled_error&) {
            std::cout << "thread cancelled\n";
        }
    }
    std::unique_ptr<std::thread> thread_;
    cancellation_point cpoint_;
};

int main() {
    ThreadExample ex;
    ex.start();
    ex.stop();
    return 0;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: C++0x thread interruption

Body:
Here is my humble implementation of a thread canceller (for C++0x).
I hope it will be useful.

// Class cancellation_point
#include <mutex>
#include <condition_variable>

struct cancelled_error {};

class cancellation_point
{
public:
    cancellation_point(): stop_(false) {}

    void cancel() {
        std::unique_lock<std::mutex> lock(mutex_);
        stop_ = true;
        cond_.notify_all();
    }

    template <typename P>
    void wait(const P& period) {
        std::unique_lock<std::mutex> lock(mutex_);
        if (stop_ || cond_.wait_for(lock, period) == std::cv_status::no_timeout) {
            stop_ = false;
            throw cancelled_error();
        }
    }
private:
    bool stop_;
    std::mutex mutex_;
    std::condition_variable cond_;
};

// Usage example
#include <thread>
#include <iostream>

class ThreadExample
{
public:
    void start() {
        thread_ = std::unique_ptr<std::thread>(
            new std::thread(std::bind(&ThreadExample::run, this)));
    }
    void stop() {
        cpoint_.cancel();
        thread_->join();
    }
private:
    void run() {
        std::cout << "thread started\n";
        try {
            while (true) {
                cpoint_.wait(std::chrono::seconds(1));
            }
        } catch (const cancelled_error&) {
            std::cout << "thread cancelled\n";
        }
    }
    std::unique_ptr<std::thread> thread_;
    cancellation_point cpoint_;
};

int main() {
    ThreadExample ex;
    ex.start();
    ex.stop();
    return 0;
}


问:
Within snowflake stored procedure set variable and use it within the same procedure as a copy pattern
I am trying to create a stored procedure to copy from the external stage (s3 bucket) and use a pattern for the file name. The pattern is based on the concatenated current date but I need to set a variable to use as a pattern. Is it possible to do something like this?</p>
```<code>    CREATE OR REPLACE PROCEDURE test_copy()
    RETURNS STRING
    LANGUAGE JAVASCRIPT
    EXECUTE AS CALLER
    AS
    $$
    SET my_Date=(select concat('.*', regexp_replace(current_date(),'-',''), '.*.parquet' );
    var sql_command = '
    COPY INTO table1
    FROM '@s3bucket'
    (file_format  => PARQUET, pattern=>$my_Date)
);
    '
    snowflake.execute(
        {
        sqlText: sql_command
        });
    return "Successfully executed.";
    $$;
</code>```

答:
As you can generate the current date in javascript, why not create my_Date purely in javascript?

You then need to create sql_command by concatenating the required strings and variables together

Body:
I am trying to create a stored procedure to copy from the external stage (s3 bucket) and use a pattern for the file name. The pattern is based on the concatenated current date but I need to set a variable to use as a pattern. Is it possible to do something like this?

    CREATE OR REPLACE PROCEDURE test_copy()
    RETURNS STRING
    LANGUAGE JAVASCRIPT
    EXECUTE AS CALLER
    AS
    $$
    SET my_Date=(select concat('.*', regexp_replace(current_date(),'-',''), '.*.parquet' );
    var sql_command = '
    COPY INTO table1
    FROM '@s3bucket'
    (file_format  => PARQUET, pattern=>$my_Date)
);
    '
    snowflake.execute(
        {
        sqlText: sql_command
        });
    return "Successfully executed.";
    $$;


问:
Flexbox Gallery With Wrapping
I am trying to create a responsive image gallery for my website using a flexbox. However, I am trying to make it wrap to the next line and stay in order, which I am having trouble with. For example:

Desktop

1,2,3

4,5,6 etc

Tablet

1,2

3,4 etc

Mobile

1

2 etc

Please see the example code I included.

.row {
  display: flex;
  flex-wrap: wrap;
}

.column {
  flex: 33%;
  max-width: 33%;
}

.column img {
  vertical-align: middle;
  width: 100%;
}

@media screen and (max-width: 800px) {
  .column {
    flex: 50%;
    max-width: 50%;
  }
}

@media screen and (max-width: 600px) {
  .column {
    flex: 100%;
    max-width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="column">
    <figure>
      <img src="https://img.webnots.com/2014/04/112.png">
      <figcaption>Caption 1</figcaption>
    </figure>
    <figure>
      <img src="https://img.webnots.com/2014/04/42.png">
      <figcaption>Caption 4</figcaption>
    </figure>
  </div>
  <div class="column">
    <figure>
      <img src="https://img.webnots.com/2014/04/22.png">
      <figcaption>Caption 2</figcaption>
    </figure>
    <figure>
      <img src="https://img.webnots.com/2014/04/52.png">
      <figcaption>Caption 5</figcaption>
    </figure>
  </div>
  <div class="column">
    <figure>
      <img src="https://img.webnots.com/2014/04/32.png">
      <figcaption>Caption 3</figcaption>
    </figure>
    <figure>
      <img src="https://img.webnots.com/2014/04/62.png">
      <figcaption>Caption 6</figcaption>
    </figure>
  </div>
</div></code>```

答:
Your HTML elements are set up incorrectly. To achieve what you want, you shouldn't put in the same  element "first" and "fourth". While it looks good on desktop, you won't be able to put element "second" or "third" between them. You will only be able to change the position of those elements inside of the . Very basic HTML and CSS stuff.

I would advise you to rename class "column" to "cell" and put them in order:

Caption 1

Caption 2

Caption 3

Caption 4

Caption 5

Caption 6

```

And of course in your CSS file change the .column to .cell

This way you will achieve your wanted responsive look on tablet and mobile.

Title: Flexbox Gallery With Wrapping

Body:
I am trying to create a responsive image gallery for my website using a flexbox. However, I am trying to make it wrap to the next line and stay in order, which I am having trouble with. For example:

Desktop

1,2,3

4,5,6 etc

Tablet

1,2

3,4 etc

Mobile

1

2 etc

Please see the example code I included.

.row {
  display: flex;
  flex-wrap: wrap;
}

.column {
  flex: 33%;
  max-width: 33%;
}

.column img {
  vertical-align: middle;
  width: 100%;
}

@media screen and (max-width: 800px) {
  .column {
    flex: 50%;
    max-width: 50%;
  }
}

@media screen and (max-width: 600px) {
  .column {
    flex: 100%;
    max-width: 100%;
  }
}

Caption 1

Caption 4

Caption 2

Caption 5

Caption 3

Caption 6

Body:
Your HTML elements are set up incorrectly. To achieve what you want, you shouldn't put in the same  element "first" and "fourth". While it looks good on desktop, you won't be able to put element "second" or "third" between them. You will only be able to change the position of those elements inside of the . Very basic HTML and CSS stuff.

I would advise you to rename class "column" to "cell" and put them in order:

<div class="row">
  <div class="cell">
    <figure>
      <img src="https://img.webnots.com/2014/04/112.png">
      <figcaption>Caption 1</figcaption>
    </figure>
   </div>
   <div class="cell">
    <figure>
      <img src="https://img.webnots.com/2014/04/112.png">
      <figcaption>Caption 2</figcaption>
    </figure>
   </div>
   <div class="cell">
    <figure>
      <img src="https://img.webnots.com/2014/04/112.png">
      <figcaption>Caption 3</figcaption>
    </figure>
   </div>
   <div class="cell">
    <figure>
      <img src="https://img.webnots.com/2014/04/112.png">
      <figcaption>Caption 4</figcaption>
    </figure>
   </div>
   <div class="cell">
    <figure>
      <img src="https://img.webnots.com/2014/04/112.png">
      <figcaption>Caption 5</figcaption>
    </figure>
   </div>
   <div class="cell">
    <figure>
      <img src="https://img.webnots.com/2014/04/112.png">
      <figcaption>Caption 6</figcaption>
    </figure>
   </div>
</div>

And of course in your CSS file change the .column to .cell

This way you will achieve your wanted responsive look on tablet and mobile.