问:
Swift async/await in a for loop or map
I have this model:

```<code>struct ExactLocation {
    var coordinates: CLLocationCoordinate2D? {
        get async throws {
            let geocoder = CLGeocoder()
            let placemark = try await geocoder.geocodeAddressString(address)
            let mark = MKPlacemark(placemark: placemark.first!)
            return mark.coordinate
        }
    }
}
struct Property {
    let exactLocation: ExactLocation?
}
</code>```

I am trying to loop over an array of Property to fetch all the coordinates using Swift 5.5 async/await.

```<code>private func addAnnotations(for properties: [Property]) async {
    let exactLocations = try? properties.compactMap { try $0.exactLocation?.coordinates } <-- Error: 'async' property access in a function that does not support concurrency

    let annotations = await properties.compactMap { property -> MKPointAnnotation? in
        if let exactLocation = property.exactLocation {
            if let coordinates = try? await exactLocation.coordinates {

            }
        }
    } <-- Error: Cannot pass function of type '(Property) async -> MKPointAnnotation?' to parameter expecting synchronous function type

    properties.forEach({ property in
        if let exactLocation = property.exactLocation {
            if let coordinates = try? await exactLocation.coordinates {

            }
        }
    } <-- Error: Cannot pass function of type '(Property) async -> Void' to parameter expecting synchronous function type
}
</code>```

So how can I iterate over this array with an async function?
Do I need to create an AsyncIterator? The docs are quite confusing on this, how would I do this for this simple example?

答:
First, be careful about the number of requests that you perform. The docs say:

Send at most one geocoding request for any one user action.

If the user performs multiple actions that involve geocoding the same location, reuse the results from the initial geocoding request instead of starting individual requests for each action.

When you want to update the user’s current location automatically (such as when the user is moving), issue new geocoding requests only when the user has moved a significant distance and after a reasonable amount of time has passed. For example, in a typical situation, you should not send more than one geocoding request per minute.

And the old Location and Maps Programming Guide says:

The same CLGeocoder object can be used to initiate any number of geocoding requests but only one request at a time may be active for a given geocoder.

So, the whole idea of rapidly issuing a series of geolocation requests may be imprudent, and even if you were to do just a few, I would be inclined to avoid performing them concurrently. So, I would consider a simple for loop, e.g.:

func addAnnotations(for addresses: [String]) async throws {
    let geocoder = CLGeocoder()

    for address in addresses {
        if
            let placemark = try await geocoder.geocodeAddressString(address).first,
            let coordinate = placemark.location?.coordinate
        {
            let annotation = MKPointAnnotation()
            annotation.title = placemark.name
            annotation.coordinate = coordinate

            // ...

            // you might even want to throttle your requests, e.g.
            //
            // try await Task.sleep(nanoseconds: nanoseconds)
        }
    }
}
```
<hr />
<p>Technically, you could do the computed property approach. Now, I did not see <code>address</code> in your model anywhere, but let’s imagine:</p>
<pre class="lang-swift prettyprint-override"><code>struct Property {
    let address: String

    var coordinate: CLLocationCoordinate2D? {
        get async throws {
            try await CLGeocoder()
                .geocodeAddressString(address)
                .first?.location?.coordinate
        }
    }
}
</code>```

(Note the elimination of the forced unwrapping operator and the unnecessary instantiating of another placemark.)

Then you could do:

func addAnnotations(for properties: [Property]) async throws {
    for property in properties {
        if let coordinate = try await property.coordinate {
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate
            ...
        }
    }
}
```

I am not crazy about that approach (as we are hiding rate-limited CLGeocoder requests with all sorts of constraints inside a computed property; if you access the same property repeatedly, duplicate geocoder requests will be issued, which Apple explicitly advises that we avoid). But the async property technically works, too.

Often when dealing with annotations, we want to be able to interact with the annotation views on our map and know with which model object they are associated. For that reason, we would often keep some sort of cross reference between our annotations and our model objects.

If Property was a reference type, we might use a MKPointAnnotation subclass that kept a reference to the appropriate Property. Or we might just make our Property conform to MKAnnotation, itself, eliminating the need for references between annotations and separate model objects. There are lots of ways to tackle this requirement, and I’m not sure we have enough information to advise you on the correct pattern in your case.

Title: Swift async/await in a for loop or map

Body:
I have this model:

struct ExactLocation {
    var coordinates: CLLocationCoordinate2D? {
        get async throws {
            let geocoder = CLGeocoder()
            let placemark = try await geocoder.geocodeAddressString(address)
            let mark = MKPlacemark(placemark: placemark.first!)
            return mark.coordinate
        }
    }
}
struct Property {
    let exactLocation: ExactLocation?
}

I am trying to loop over an array of Property to fetch all the coordinates using Swift 5.5 async/await.

private func addAnnotations(for properties: [Property]) async {
    let exactLocations = try? properties.compactMap { try $0.exactLocation?.coordinates } <-- Error: 'async' property access in a function that does not support concurrency

    let annotations = await properties.compactMap { property -> MKPointAnnotation? in
        if let exactLocation = property.exactLocation {
            if let coordinates = try? await exactLocation.coordinates {

            }
        }
    } <-- Error: Cannot pass function of type '(Property) async -> MKPointAnnotation?' to parameter expecting synchronous function type

    properties.forEach({ property in
        if let exactLocation = property.exactLocation {
            if let coordinates = try? await exactLocation.coordinates {

            }
        }
    } <-- Error: Cannot pass function of type '(Property) async -> Void' to parameter expecting synchronous function type
}

So how can I iterate over this array with an async function?
Do I need to create an AsyncIterator? The docs are quite confusing on this, how would I do this for this simple example?

Body:
First, be careful about the number of requests that you perform. The docs say:

Send at most one geocoding request for any one user action.

If the user performs multiple actions that involve geocoding the same location, reuse the results from the initial geocoding request instead of starting individual requests for each action.

When you want to update the user’s current location automatically (such as when the user is moving), issue new geocoding requests only when the user has moved a significant distance and after a reasonable amount of time has passed. For example, in a typical situation, you should not send more than one geocoding request per minute.

And the old Location and Maps Programming Guide says:

The same CLGeocoder object can be used to initiate any number of geocoding requests but only one request at a time may be active for a given geocoder.

So, the whole idea of rapidly issuing a series of geolocation requests may be imprudent, and even if you were to do just a few, I would be inclined to avoid performing them concurrently. So, I would consider a simple for loop, e.g.:

func addAnnotations(for addresses: [String]) async throws {
    let geocoder = CLGeocoder()

    for address in addresses {
        if
            let placemark = try await geocoder.geocodeAddressString(address).first,
            let coordinate = placemark.location?.coordinate
        {
            let annotation = MKPointAnnotation()
            annotation.title = placemark.name
            annotation.coordinate = coordinate

            // ...

            // you might even want to throttle your requests, e.g.
            //
            // try await Task.sleep(nanoseconds: nanoseconds)
        }
    }
}

Technically, you could do the computed property approach. Now, I did not see address in your model anywhere, but let’s imagine:

struct Property {
    let address: String

    var coordinate: CLLocationCoordinate2D? {
        get async throws {
            try await CLGeocoder()
                .geocodeAddressString(address)
                .first?.location?.coordinate
        }
    }
}

(Note the elimination of the forced unwrapping operator and the unnecessary instantiating of another placemark.)

Then you could do:

func addAnnotations(for properties: [Property]) async throws {
    for property in properties {
        if let coordinate = try await property.coordinate {
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate
            ...
        }
    }
}

I am not crazy about that approach (as we are hiding rate-limited CLGeocoder requests with all sorts of constraints inside a computed property; if you access the same property repeatedly, duplicate geocoder requests will be issued, which Apple explicitly advises that we avoid). But the async property technically works, too.

Often when dealing with annotations, we want to be able to interact with the annotation views on our map and know with which model object they are associated. For that reason, we would often keep some sort of cross reference between our annotations and our model objects.

If Property was a reference type, we might use a MKPointAnnotation subclass that kept a reference to the appropriate Property. Or we might just make our Property conform to MKAnnotation, itself, eliminating the need for references between annotations and separate model objects. There are lots of ways to tackle this requirement, and I’m not sure we have enough information to advise you on the correct pattern in your case.


来源: stackexchange

问:
How to query multiple whereMonth in orWhere query for laravel
I'm newbie in Laravel and I need to do laravel query by getting result like below sql.

SQL

```<code>select * from `tb_project_participate`
where
    `project_id` = 20 and
    `department_id` = 1 and
    (
        month(`created_at`) = 10 or
        (month(`created_at`) = 11) or
        (month(`created_at`) = 12)
    )
</code>```

Below is Laravel code that I use.

```<code>$participate = ProjectParticipate::where('project_id' , $project->project_id)
            ->where('department_id', $auth->department_id)
            ->whereMonth('created_at' , 10)
            ->orWhere(function($query){$query->whereMonth('created_at',11); })
            ->orWhere(function($query1){$query1->whereMonth('created_at',12); })
            ->get();
</code>```

And I have result as below, that is not a query that I want.
SQL

```<code>select * from `tb_project_participate`
where
    `project_id` = 20 and
    `department_id` = 1 and
    month(`created_at`) = 10 or
    (month(`created_at`) = 11) or
    (month(`created_at`) = 12)
</code>```

Appreciated for advice how to write Laravel query to get result as whsh, And so sorry for my English. Thank you very much.

答:
the accepted answer that recommended should be whereIn instead of ->where(DB::RAW('month(created_at)'), $months)
Hope this helps others

ContentLicense: CC BY-SA 4.0

Body:
I'm newbie in Laravel and I need to do laravel query by getting result like below sql.

SQL

select * from `tb_project_participate`
where
    `project_id` = 20 and
    `department_id` = 1 and
    (
        month(`created_at`) = 10 or
        (month(`created_at`) = 11) or
        (month(`created_at`) = 12)
    )

Below is Laravel code that I use.

$participate = ProjectParticipate::where('project_id' , $project->project_id)
            ->where('department_id', $auth->department_id)
            ->whereMonth('created_at' , 10)
            ->orWhere(function($query){$query->whereMonth('created_at',11); })
            ->orWhere(function($query1){$query1->whereMonth('created_at',12); })
            ->get();

And I have result as below, that is not a query that I want.
SQL

select * from `tb_project_participate`
where
    `project_id` = 20 and
    `department_id` = 1 and
    month(`created_at`) = 10 or
    (month(`created_at`) = 11) or
    (month(`created_at`) = 12)

Appreciated for advice how to write Laravel query to get result as whsh, And so sorry for my English. Thank you very much.


问:
MatLab mad() vs SciPy.Stats median_abs_deviation() differences
I am converting some MatLab code to Python, and cannot solve why the results I am getting are different.

In MatLab, the mad function on the input x = [1, 2, 4, 3, 7, 2, 1, 3, 2, 1] yields a result of 1.32. However, when using the equiv function in SciPy.Stats, that is, median_abs_deviation, I get a different result of 1.0.

My code, exactly is:

Matlab:

x = [1, 2, 4, 3, 7, 2, 1, 3, 2, 1];
mdat = mad(x)
```
<p>Python:</p>
<pre class="lang-py prettyprint-override"><code>from scipy import stats

x = np.array([1, 2, 4, 3, 7, 2, 1, 3, 2, 1])
print(stats.median_abs_deviation(x))
</code>```

答:
The default in Matlab is to compute the mean absolute deviation. If you want the median absolute deviation, then the command is mad(x,1).

If you're interested in computing the mean absolute deviation in Python, see this post.

Body:
I am converting some MatLab code to Python, and cannot solve why the results I am getting are different.

In MatLab, the mad function on the input x = [1, 2, 4, 3, 7, 2, 1, 3, 2, 1] yields a result of 1.32. However, when using the equiv function in SciPy.Stats, that is, median_abs_deviation, I get a different result of 1.0.

My code, exactly is:

Matlab:

x = [1, 2, 4, 3, 7, 2, 1, 3, 2, 1];
mdat = mad(x)

Python:

from scipy import stats

x = np.array([1, 2, 4, 3, 7, 2, 1, 3, 2, 1])
print(stats.median_abs_deviation(x))


问:
Draft JS programmatically insert text as span
I am using Draft.js for its mentions plugin. Sometimes, I want users to add a mention not by selecting an item from a dropdown but by writing something like, for example, "@item" or "@item".

As you can see in the function below, if I type a word that starts with @* or ends with * it becomes a mention automatically.

export const replaceString = (editorState, setEditorState) => {
    const contentState = editorState.getCurrentContent();
    const selectionState = editorState.getSelection();
    const block = contentState.getBlockForKey(selectionState.getAnchorKey());

    const blockAsArray = block.getText().split(' ');
    const lastWord = blockAsArray.pop();
    if (lastWord.startsWith('@*') || lastWord.endsWith('*') ) {
        const currentSelectionState = editorState.getSelection();
        const currentContent = editorState.getCurrentContent();
        const contentStateWithEntity = currentContent.createEntity(
            "MENTION",
            "MUTABLE",
            { nature: 'remedy', lastWord}
        );

        const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
        const newContentState = Modifier.replaceText(
            contentState,
            selectionState.merge({
                anchorOffset: currentSelectionState.getEndOffset() - lastWord.length,
                focusOffset: currentSelectionState.getEndOffset()
            }),
            lastWord,
            editorState.getCurrentInlineStyle(),
            entityKey
        );

        setEditorState(EditorState.push(
            editorState,
            newContentState,
            'replace-text'
        ))
    } else {
        setEditorState(editorState)
    }
}```

What I would love to do now is to insert this mention as a span that I can style. Is there a way I can do that?

答:
https://draftjs.org/docs/advanced-topics-inline-styles/

Draftjs render to span from it's own model. You should control styles by entity.

Body:
I am using Draft.js for its mentions plugin. Sometimes, I want users to add a mention not by selecting an item from a dropdown but by writing something like, for example, "@item" or "@item".

As you can see in the function below, if I type a word that starts with @* or ends with * it becomes a mention automatically.

export const replaceString = (editorState, setEditorState) => {
    const contentState = editorState.getCurrentContent();
    const selectionState = editorState.getSelection();
    const block = contentState.getBlockForKey(selectionState.getAnchorKey());

    const blockAsArray = block.getText().split(' ');
    const lastWord = blockAsArray.pop();
    if (lastWord.startsWith('@*') || lastWord.endsWith('*') ) {
        const currentSelectionState = editorState.getSelection();
        const currentContent = editorState.getCurrentContent();
        const contentStateWithEntity = currentContent.createEntity(
            "MENTION",
            "MUTABLE",
            { nature: 'remedy', lastWord}
        );

        const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
        const newContentState = Modifier.replaceText(
            contentState,
            selectionState.merge({
                anchorOffset: currentSelectionState.getEndOffset() - lastWord.length,
                focusOffset: currentSelectionState.getEndOffset()
            }),
            lastWord,
            editorState.getCurrentInlineStyle(),
            entityKey
        );

        setEditorState(EditorState.push(
            editorState,
            newContentState,
            'replace-text'
        ))
    } else {
        setEditorState(editorState)
    }
}

What I would love to do now is to insert this mention as a span that I can style. Is there a way I can do that?


问:
Jquery SimpleDialog not loading
I am working with Jquery simpleDialog.  I am watching fidler and it is telling me that it is loading the js files successfully. I reference the files correctly in my view and I make correct calls.  I am at my wits end and I can't quite figure out what to do.  I have been looking at this code for the last couple of hours and I haven't been able to budge it.

```<code>    <asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
    <link href="<%=ResolveClientUrl("~/Content/simpleDialog/jquery.simpledialog.0.1.css")%>" rel="stylesheet" type="text/css" />
    <script src="<%=ResolveClientUrl("~/Scripts/simpleDialog/jquery.simpledialog.0.1.js")%>" type="text/javascript"></script>
    <script src="<%=ResolveClientUrl("~/Scripts/simpleDialog/jquery.form.js")%>" type="text/javascript"></script>
    <script type="text/javascript">

    $(document).ready(function () {

        $('a.tempDlg1').simpleDialog({
            opacity: 0.3,
            duration: 200,
            width: 950,
            useTitleAttr: true,
            closeLabel: '<img src="../../Content/simpleDialog/CloseButton2.gif" border="1"/>',
            showCloseLabel: true
        });
    </script>
</code>```

The simpleDialog window just won't open.  Does UIDialog work better?  I do have datePicker inside of this dialog.  Could that be affecting it?  I don't know, I have been working for 16 hours straight.  I need some sleep.

答:
You're missing a closing

```<code>});
</code>```

for the $(document).ready(function() { block.

ContentLicense: CC BY-SA 3.0

Title: Jquery SimpleDialog not loading

Body:
I am working with Jquery simpleDialog.  I am watching fidler and it is telling me that it is loading the js files successfully. I reference the files correctly in my view and I make correct calls.  I am at my wits end and I can't quite figure out what to do.  I have been looking at this code for the last couple of hours and I haven't been able to budge it.

    <asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
    <link href="<%=ResolveClientUrl("~/Content/simpleDialog/jquery.simpledialog.0.1.css")%>" rel="stylesheet" type="text/css" />

The simpleDialog window just won't open.  Does UIDialog work better?  I do have datePicker inside of this dialog.  Could that be affecting it?  I don't know, I have been working for 16 hours straight.  I need some sleep.

Body:
You're missing a closing

});

for the $(document).ready(function() { block.


问:
How do I attach multiple HTML files to a zip file in R?
I want to create a zip file which will contain multiple HTML (created from markdown) files. Here is an example of what I would like to do and the code:

Path of Files

```<code> [1] "C:/Users/SXC3GFL/Documents/Supplier_Ops_Parameterized_Reports/MVNDR_60457557.html"
 [2] "C:/Users/SXC3GFL/Documents/Supplier_Ops_Parameterized_Reports/MVNDR_60083983.html"
 [3] "C:/Users/SXC3GFL/Documents/Supplier_Ops_Parameterized_Reports/MVNDR_60009765.html"
</code>```

I then convert these three files to a variable. Let's call it attachments, how do I create a zip file where I can place the attachments?

What I tried attachments_markdown is the variable where all the path names of my files are.

```<code>zip("Drill_Down.zip", files = attachments_markdown)
</code>```

However, nothing showed up. See below

答:
You can use the zip function to create zip files. Something like this:

```<code>zip("name_of_your_zip_file.zip", files = normalizePath(attachments))
</code>```

Have a look at the ?zip help page for more details.

Note that Windows uses \ in file paths to indicate folders, but in R you will need to use either / or escape the backslash to \\ - so I added normalizePath() to the answer Mikael's suggestion which will take care of that for you in the attachments.

Body:
I want to create a zip file which will contain multiple HTML (created from markdown) files. Here is an example of what I would like to do and the code:

Path of Files

 [1] "C:/Users/SXC3GFL/Documents/Supplier_Ops_Parameterized_Reports/MVNDR_60457557.html"
 [2] "C:/Users/SXC3GFL/Documents/Supplier_Ops_Parameterized_Reports/MVNDR_60083983.html"
 [3] "C:/Users/SXC3GFL/Documents/Supplier_Ops_Parameterized_Reports/MVNDR_60009765.html"

I then convert these three files to a variable. Let's call it attachments, how do I create a zip file where I can place the attachments?

What I tried attachments_markdown is the variable where all the path names of my files are.

zip("Drill_Down.zip", files = attachments_markdown)

However, nothing showed up. See below

Body:
You can use the zip function to create zip files. Something like this:

zip("name_of_your_zip_file.zip", files = normalizePath(attachments))

Have a look at the ?zip help page for more details.

Note that Windows uses \ in file paths to indicate folders, but in R you will need to use either / or escape the backslash to \\ - so I added normalizePath() to the answer Mikael's suggestion which will take care of that for you in the attachments.


问:
How to stop variable re initializing in context
I have a variable in my context with the base url for my api and i add parameters to that base call to add parameters, the problem that i have is that i can't concatenate more than one parameter at a time, so if for example set my checkbox for one brand the url updates to that brand filter and the function adds the brand filter parameter, but if i search something the url re-initialites itself and deletes the other parameter.

Some images for more clarity:
If i make a search:

The url console logs like this, the line 87 logs the url before i concatenate the parameter and the 91 after i concatenate the parameter:

And if i check the Nike brand that should only show the Nike Air Yeezy product and url should be "http://localhost:5000/api/v1/products?name=Yeezy&company=Nike" is only "http://localhost:5000/api/v1/products?company=Nike&"

My theory is that as i declarate the base url parameter every time i do one function the context resets and that url var re initializes, but how can i stop this? I searched at how to make a string state and concatenating that state but couldn't find anything.

Here is the part of the context where i handle the new api calls, if something seems weird/missing is because i cut the context to make it more clear

```<code>  var url = "/api/v1/products?";
  const [productList, setProductList] = useState([]);
  const [brandFilter, setBrandFilter] = useState([]);
  const [search, setSearch] = useState({
    text: "",
  });

  const getProductList = async () => {
    const response = await fetch(url);
    const responseJson = await response.json();
    if (responseJson) {
      setProductList(responseJson.products);
    }
  };

  useEffect(() => {
    getProductList();
  }, []);

  useEffect(() => {
    setSearchUrl();
    getProductList();
  }, [search]);

  const setBrandUrl = () => {
    console.log(url);
    if (brandFilter.length > 0) {
      for (var i = 0; i < brandFilter.length; i++) {
        url += `company=${brandFilter[i]}&`;
      }
    }
    console.log(url);
  };

  const setSearchUrl = () => {
    console.log(url);
    if (search.text != "") {
      url += `name=${search.text}`;
    }
    console.log(url);
  };

  useEffect(() => {
    setBrandUrl();
    getProductList();
  }, [brandFilter]);
</code>```

答:
It's because you've got the useEffect split into two; one which is reacting to the search changing, and one which is reacting to the brands changing. You need to combine those into one.

If we look at the effect for when the search changes, and we reduce the code to what's actually running, your effect is doing this:

useEffect(() => {
  var url = "/api/v1/products?";

  if (search.text != "") {
    url += `name=${search.text}`;
  }

  getProductList();
}, [search]);
```
<p>i.e. it ignores <code>brandsFilter</code> completely. You need to have both the <code>brandsFilter</code> and the <code>search</code> as a dependency for a single effect:</p>
<pre class="lang-js prettyprint-override"><code>useEffect(() => {
  let url = "/api/v1/products?";

  if (search.text) {
    url += `name=${search.text}`;
  }

  if (brandsFilter.length) {
    const brands = brandsFilter.map(b => `&brand=${b}`).join('');
    url += search.text ? brands : brands.substr(1);
  }

  // NOTE: pass the 'url' to the get as a parameter here!
  getProductList(url);
}, [search, brandsFilter]);
</code>```

Note: this is easier if you use a library like query-string to do the heavy lifting for you:

import qs from 'query-string';

useEffect(() => {
  const url = qs.stringifyUrl({
    url: "/api/v1/products?",
    query: {
        name: search.text || undefined,
        brands: brandsFilter,
    }
  });

  getProductList(url);
}, [search, brandsFilter]);
```

Body:
I have a variable in my context with the base url for my api and i add parameters to that base call to add parameters, the problem that i have is that i can't concatenate more than one parameter at a time, so if for example set my checkbox for one brand the url updates to that brand filter and the function adds the brand filter parameter, but if i search something the url re-initialites itself and deletes the other parameter.

Some images for more clarity:
If i make a search:

The url console logs like this, the line 87 logs the url before i concatenate the parameter and the 91 after i concatenate the parameter:

And if i check the Nike brand that should only show the Nike Air Yeezy product and url should be "http://localhost:5000/api/v1/products?name=Yeezy&company=Nike" is only "http://localhost:5000/api/v1/products?company=Nike&"

My theory is that as i declarate the base url parameter every time i do one function the context resets and that url var re initializes, but how can i stop this? I searched at how to make a string state and concatenating that state but couldn't find anything.

Here is the part of the context where i handle the new api calls, if something seems weird/missing is because i cut the context to make it more clear

  var url = "/api/v1/products?";
  const [productList, setProductList] = useState([]);
  const [brandFilter, setBrandFilter] = useState([]);
  const [search, setSearch] = useState({
    text: "",
  });

  const getProductList = async () => {
    const response = await fetch(url);
    const responseJson = await response.json();
    if (responseJson) {
      setProductList(responseJson.products);
    }
  };

  useEffect(() => {
    getProductList();
  }, []);

  useEffect(() => {
    setSearchUrl();
    getProductList();
  }, [search]);

  const setBrandUrl = () => {
    console.log(url);
    if (brandFilter.length > 0) {
      for (var i = 0; i < brandFilter.length; i++) {
        url += `company=${brandFilter[i]}&`;
      }
    }
    console.log(url);
  };

  const setSearchUrl = () => {
    console.log(url);
    if (search.text != "") {
      url += `name=${search.text}`;
    }
    console.log(url);
  };

  useEffect(() => {
    setBrandUrl();
    getProductList();
  }, [brandFilter]);

Body:
It's because you've got the useEffect split into two; one which is reacting to the search changing, and one which is reacting to the brands changing. You need to combine those into one.

If we look at the effect for when the search changes, and we reduce the code to what's actually running, your effect is doing this:

useEffect(() => {
  var url = "/api/v1/products?";

  if (search.text != "") {
    url += `name=${search.text}`;
  }

  getProductList();
}, [search]);

i.e. it ignores brandsFilter completely. You need to have both the brandsFilter and the search as a dependency for a single effect:

useEffect(() => {
  let url = "/api/v1/products?";

  if (search.text) {
    url += `name=${search.text}`;
  }

  if (brandsFilter.length) {
    const brands = brandsFilter.map(b => `&brand=${b}`).join('');
    url += search.text ? brands : brands.substr(1);
  }

  // NOTE: pass the 'url' to the get as a parameter here!
  getProductList(url);
}, [search, brandsFilter]);

Note: this is easier if you use a library like query-string to do the heavy lifting for you:

import qs from 'query-string';

useEffect(() => {
  const url = qs.stringifyUrl({
    url: "/api/v1/products?",
    query: {
        name: search.text || undefined,
        brands: brandsFilter,
    }
  });

  getProductList(url);
}, [search, brandsFilter]);


问:
Angular - Can't assign null to File type
I have got an interface like this

export interface ReportFiles {
  ReportName: string;
  Log: number;
  MyFile: File;
}
```
<p>And in my component, I declared the object as</p>
<pre class="lang-js prettyprint-override"><code>export class MyComponent Implements OnInit {
  RF:  ReportFiles = { ReportName: "", Log: 0, MyFile: null }
  ...
  ...
}
</code>```

The error message shows

'null' is not assignable to File

How can I resolve this?

答:
Specify MyFile with nullable type.

interface ReportFiles {
  ReportName: string;
  Log: number;
  MyFile?: File | null;
}
```

Sample Demo on Typescript Playground

Body:
I have got an interface like this

export interface ReportFiles {
  ReportName: string;
  Log: number;
  MyFile: File;
}

And in my component, I declared the object as

export class MyComponent Implements OnInit {
  RF:  ReportFiles = { ReportName: "", Log: 0, MyFile: null }
  ...
  ...
}

The error message shows

'null' is not assignable to File

How can I resolve this?

Body:
Specify MyFile with nullable type.

interface ReportFiles {
  ReportName: string;
  Log: number;
  MyFile?: File | null;
}

Sample Demo on Typescript Playground


问:
PowerShell to remove all letters and dashes leaving UPC
I have about 1,800 .pdfs including a UPC with dashes and text that need to be removed to manage. I found a code to remove extra spaces and underscores.

How do I remove all text leaving just the UPCs?

```<code>01182232110_V1R1_CartonOL_KP_DNV15.pdf
</code>```

... to ...

```<code>01182232110.pdf
</code>```

答:
```<code># Targets .pdf files in the current dir.
# Add a -LiteralPath / -Path argument to target a different dir.
# Add -Recurse to target .pdf files in the target dir's entire *subtree*.
Get-ChildItem -Filter *.pdf |
  Rename-Item -NewName {  $_.Name -replace '_.+(?=\.)' } -WhatIf
</code>```

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf  once you're sure the operation will do what you want.

-replace  '_.+(?=\.)' in essence removes all characters starting with the first _ from the input file's base name (preserving the extension).

Body:
I have about 1,800 .pdfs including a UPC with dashes and text that need to be removed to manage. I found a code to remove extra spaces and underscores.

How do I remove all text leaving just the UPCs?

01182232110_V1R1_CartonOL_KP_DNV15.pdf

... to ...

01182232110.pdf

Body:
# Targets .pdf files in the current dir.
# Add a -LiteralPath / -Path argument to target a different dir.
# Add -Recurse to target .pdf files in the target dir's entire *subtree*.
Get-ChildItem -Filter *.pdf |
  Rename-Item -NewName {  $_.Name -replace '_.+(?=\.)' } -WhatIf

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf  once you're sure the operation will do what you want.

-replace  '_.+(?=\.)' in essence removes all characters starting with the first _ from the input file's base name (preserving the extension).


问:
Video playing in html div
I have following definition.

```<code><video controls="controls" autoplay="false" style="width:95%; height:300px;">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/mp4">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/ogg">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/webm">
    <object data="https://youtu.be/4aYVLpY5FYU" width="320" height="240">
          <embed src="https://youtu.be/4aYVLpY5FYU" width="320" height="240">
              Your browser does not support video
    </object>
</video>
</code>```

Video is not playing at all.

Note:

I have got a list of 200 videos to be shown which are pointing to different sources, in addition to Youtube. Also, I will not know the type of the video (ie: MP4 or AVI or webM, etc).

答:
You cannot always do it like this. Take a look at this:

```<code><!DOCTYPE html>
<html>
<body>

 <embed type="video/webm" src="https://www.youtube.com/embed/ZnuwB35GYMY" width="400" height="300">
</body>
</html>
</code>```

You have to maintain the specific format of the link. And also the owner of the video has to permit embedding of that video on external source.

Title: Video playing in html div

Body:
I have following definition.

<video controls="controls" autoplay="false" style="width:95%; height:300px;">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/mp4">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/ogg">
    <source src="https://youtu.be/4aYVLpY5FYU" type="video/webm">
    <object data="https://youtu.be/4aYVLpY5FYU" width="320" height="240">
          <embed src="https://youtu.be/4aYVLpY5FYU" width="320" height="240">
              Your browser does not support video
    </object>
</video>

Video is not playing at all.

Note:

I have got a list of 200 videos to be shown which are pointing to different sources, in addition to Youtube. Also, I will not know the type of the video (ie: MP4 or AVI or webM, etc).

Body:
You cannot always do it like this. Take a look at this:

<!DOCTYPE html>
<html>
<body>

 <embed type="video/webm" src="https://www.youtube.com/embed/ZnuwB35GYMY" width="400" height="300">
</body>
</html>

You have to maintain the specific format of the link. And also the owner of the video has to permit embedding of that video on external source.


问:
How can DPDK ACL library handle more than 16(RTE_ACL_MAX_CATEGORIES) categories?
I'm using DPDK 20.08 and I need to copy and distribute packets to many targets, which involves the multi-category parallel classification feature on DPDK ACL. But according to the documentation and source code, one can only set up to RTE_ACL_MAX_CATEGORIES categories, which is 16. If I want to set more than 16, do I have to use at least 2 ACL context and lookup one by one?</p>

答:
Question> I need to copy and distribute packets to many targets

Caution> If the original content of the Ethernet frame is not modified at all, then one can use mbuf->ref_cnt to circumvent the overhead of mbuf copy. But if packet content will be different on each interface (such as dstmac or valn or ip headers) the one has to duplicate the packet. If mbuf->ref_cnt is used one can not use the NIC offload RX_MBUF_FAST_FREE too.

Solution 1:
Depending upon the support of SIMD on the hardware (CPU) one can use RTE_ACL_CLASSIFY_AVX512X32. This allows 32 flow parallel lookup to be processed on CPU such skylake, cascadelake and icelake. refer Section 53.1.3 for more details.

Solution 2 (If there is no support for SIMD AVX512):
is it worth to run all 16 or 32 flow lookup then copy mbuf into multiple targets, then modify the contents for each interface?

My suggestion is to use the HW (NIC or ASIC) or using SW (rx bridge driver) to create mirror on ingress traffic and sent to separate RX queue. By using separate CPU threads smaller ACL tables can be used.

Solution 3 (If there is no support for SIMD AVX512):
One can start of modifying lib/acl/rte_acl.h for #define RTE_ACL_MAX_CATEGORIES  16 to #define RTE_ACL_MAX_CATEGORIES  32 as starting point of reference. There will be many other areas as mask which will also requires modification and support. Personally I do not recommend this option as it creates more out of tree dependency and needs to spend more time debugging the other issues.


问:
Extract multiple values from a string via regex
I have a number of strings from a 3rd party data source that are in various lengths that contain both underscore and spaces. Each portion of the string is important and I am trying to break it apart into various fields via python. The string does not have special characters (\n, \t, etc.) - should just be spaces, underscores,  and parentheses are used to break the data parts.

String
Year
State
ID
Sub ID
Extra1
Extra2

2022_UT_T1000_100 (Classification1 Classification2)
2022
UT
T1000
100
Classification1
Classification2

2021_TX_V999_005 (Classification1)
2021
TX
V999
005
Classification1

1999_GA_123456_7890
1999
GA
123456
7890

I could split the string by the underscore, then split the last field by a space but that seems error-prone. Regex is likely the best approach.

I can match the year using this: ^[1-9]\d{3,}$. However, when trying to add an OR operator, it will only find the underscore.

Is there a way to extract this data when I know a pattern exists?

答:
You could try using str.extract with the regex pattern:

^(\d{4})_([^_]+)_([^_]+)_([^_ ]+)(?: \((\S+)(?: (\S+))?\))?$
```
<p>Note that this pattern assumes that there would only be three variants in the string column, namely no extras, one extra, or at most two extras.  For arbitrary number of words in parentheses, we would need a different approach.</p>
<p>Python script:</p>
<pre class="lang-py prettyprint-override"><code>df[["Year", "State", "ID", "Sub ID", "Extra1", "Extra2"]] = df["String"].str.extract(r'^(\d{4})_([^_]+)_([^_]+)_([^_ ]+)(?: \((\S+)(?: (\S+))?\))?$')
</code>```

Here is a regex demo showing that the pattern is working for all variants of your string column.

Body:
You could try using str.extract with the regex pattern:

^(\d{4})_([^_]+)_([^_]+)_([^_ ]+)(?: \((\S+)(?: (\S+))?\))?$

Note that this pattern assumes that there would only be three variants in the string column, namely no extras, one extra, or at most two extras.  For arbitrary number of words in parentheses, we would need a different approach.

Python script:

df[["Year", "State", "ID", "Sub ID", "Extra1", "Extra2"]] = df["String"].str.extract(r'^(\d{4})_([^_]+)_([^_]+)_([^_ ]+)(?: \((\S+)(?: (\S+))?\))?$')

Here is a regex demo showing that the pattern is working for all variants of your string column.


问:
Map within a map in react, getting unexpected token expected ","
I'm trying to iterate through an array of objects and for each object also iterate through the nested array of specs. My data structure looks something like this:

```<code>export const jobList = [
    {
        name: "Death Knight",
        specs:  [{name: "Blood"},
                 {name: "FrostDK"},
                 {name:"Unholy"}]
    },

    {
        name: "Shaman",
        specs: [{name:"Elemental"},
                {name:"Enhancement"},
                {name:"RestoShaman"}]
    },
</code>```

My desired output is

Death Knight

Blood

FrostDK

Unholy

Shaman

Elemental

Enhancement

RestoShaman

Here's the problem code:

```<code>return(
<div className="col-sm">
   {jobList.map((job, i) =>
      <p>{job.name)</p>
      job.specs.map((spec, i) =>
         <img className="spec" src={window.location.origin + '/icons/' + spec.name + '.png'} alt={spec.name} onClick={this.handleClick.bind(this, i)} />
      )
   )}
</div>
)
</code>```

This is throwing a 'Parsing error: Unexpected token, expected ","' on job.specs.map. If I remove
{job.name)
 it lists all of the specs as expected. If I throw a comma after
{job.name)
 then I got "'job' is not defined" on job.specs.map. I'm not understanding why it can't call job.name for each job and then run job.specs.map() afterwards.

答:
```<code>As you are using Jsx(javascrit xml or extension) so always cover it with {} curly bracket or you can write javascript code before return and always use key after mapping else it gives error in console

  return(
        <div className="col-sm">
           {jobList.map((job, i) =>
    {
<React.Fragment key={i}>
              <p>{job.name)</p>
              job.specs.map((spec, i) =>
                 <img className="spec" src={window.location.origin + '/icons/' + spec.name + '.png'} alt={spec.name} onClick={this.handleClick.bind(this, i)} />
              )
           )}
<React.Fragment>
        </div>
        )
    }
</code>```

Body:
I'm trying to iterate through an array of objects and for each object also iterate through the nested array of specs. My data structure looks something like this:

export const jobList = [
    {
        name: "Death Knight",
        specs:  [{name: "Blood"},
                 {name: "FrostDK"},
                 {name:"Unholy"}]
    },

    {
        name: "Shaman",
        specs: [{name:"Elemental"},
                {name:"Enhancement"},
                {name:"RestoShaman"}]
    },

My desired output is

Death Knight

Blood

FrostDK

Unholy

Shaman

Elemental

Enhancement

RestoShaman

Here's the problem code:

return(

   {jobList.map((job, i) =>

{job.name)

      job.specs.map((spec, i) =>

      )
   )}

)

This is throwing a 'Parsing error: Unexpected token, expected ","' on job.specs.map. If I remove
{job.name)
 it lists all of the specs as expected. If I throw a comma after
{job.name)
 then I got "'job' is not defined" on job.specs.map. I'm not understanding why it can't call job.name for each job and then run job.specs.map() afterwards.


问:
try to reset edge developer tools
by mistake I emulated other device edge developer tool display

How can I reset default browser devveloper tool display

答:
If you need to reset the dev tools to restore the default in Edge, just follow the steps below:

Open Edge and press F12 to open the dev tools

Press F1 to open the settings panel when focus in dev tools

Scroll the Preference tab to the bottom

Click the option Restore default and refresh

Just like this:

Title: try to reset edge developer tools


问:
Intellisense not working with styled components extension installed
I use this extension normally until today. The auto-complete function is not working. Here is my code.

LoginStyle.js

```<code>import styled from "styled-components"

export const Container = styled.div`
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
`

export const GridContainer = styled.div`
    display: grid;
`
</code>```

My VS Code Version: 1.64.0
vscode-styled-components Version: v1.7.2

Here is screenshot

I tried to find it in the GitHub issue but I cannot fix it.

Very thanks if you can help

Extension Version:

package.json:

答:
This is a known issue.

There is no official solution for now. A temporary solution is to install the VSCode v1.63 until we get a fix as stated in this comment.

Had this issue myself today, the temporary solution worked.

Body:
I use this extension normally until today. The auto-complete function is not working. Here is my code.

LoginStyle.js

import styled from "styled-components"

export const Container = styled.div`
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
`

export const GridContainer = styled.div`
    display: grid;
`

My VS Code Version: 1.64.0
vscode-styled-components Version: v1.7.2

Here is screenshot

I tried to find it in the GitHub issue but I cannot fix it.

Very thanks if you can help

Extension Version:

package.json:


问:
How do I render a pug template on success and failure of authentication(passport.js) with variables from the pug template? (express, passport.js, pug)
I am working on the login system using passport.js and express with pug templates. I am trying to render the login page with a message on failure, and if on success I want to redirect the user back to the last page they have been to, of which URL is passed as hidden input inside the pug template. I want to then take that value of that hidden input and put it inside the successRedirect, however it says req is not defined:

```<code>router.post("/login", body('backurl').trim().escape(), passport.authenticate("local", {
    successRedirect: (req.body.backurl),
    failWithError: true
}), function(err, req, res, next) {
    return res.render('login', { message: 'Unable to login, the password or the username are wrong' })
}
</code>```

from my understanding, that happens because of it not having a req since there is no function with req, res, next, so I tried to wrap it with a function that has it:

```<code>router.post("/login",
    body('backurl').trim().escape(),
    function(req, res, next) {
        passport.authenticate("local", {
            successRedirect: (req.body.backurl),
            failWithError: true
        }), function(err, req, res, next) {
            return res.render('login', {message: 'Unable to login, the password or the username are wrong'})
        }
    }
);
</code>```

but it just keeps reloading and doesn't work and doesn't go to any URL.

can anybody help me fix this and move the user to the URL from the hidden input while rendering a pug template on failure with variables?

Thanks!

答:
You can render a view with a get() request.
With a post() request you should redirect and if you want to show a message to the user you could use the express-flash package.

```<code>router.post("/login", (req, res, next) => {
   passport.authenticate("local", (err, user) => {
        if (!user) {
          req.flash('error', { msg: 'Unable to login, the password or the username are wrong')
          return res.redirect('/login');
        }
        res.redirect(req.body.backurl);
   }
});
</code>```

This way you can have more details about what appened.

Body:
I am working on the login system using passport.js and express with pug templates. I am trying to render the login page with a message on failure, and if on success I want to redirect the user back to the last page they have been to, of which URL is passed as hidden input inside the pug template. I want to then take that value of that hidden input and put it inside the successRedirect, however it says req is not defined:

router.post("/login", body('backurl').trim().escape(), passport.authenticate("local", {
    successRedirect: (req.body.backurl),
    failWithError: true
}), function(err, req, res, next) {
    return res.render('login', { message: 'Unable to login, the password or the username are wrong' })
}

from my understanding, that happens because of it not having a req since there is no function with req, res, next, so I tried to wrap it with a function that has it:

router.post("/login",
    body('backurl').trim().escape(),
    function(req, res, next) {
        passport.authenticate("local", {
            successRedirect: (req.body.backurl),
            failWithError: true
        }), function(err, req, res, next) {
            return res.render('login', {message: 'Unable to login, the password or the username are wrong'})
        }
    }
);

but it just keeps reloading and doesn't work and doesn't go to any URL.

can anybody help me fix this and move the user to the URL from the hidden input while rendering a pug template on failure with variables?

Thanks!

Body:
You can render a view with a get() request.
With a post() request you should redirect and if you want to show a message to the user you could use the express-flash package.

router.post("/login", (req, res, next) => {
   passport.authenticate("local", (err, user) => {
        if (!user) {
          req.flash('error', { msg: 'Unable to login, the password or the username are wrong')
          return res.redirect('/login');
        }
        res.redirect(req.body.backurl);
   }
});

This way you can have more details about what appened.


问:
Problem with the HTTPS protocol (Delphi XE)
Doing so, I should get the public IP:

```<code>function TForm1.GetPublicIp: String;
begin
  IdHttp1.Request.Host := 'https://www.mio-ip.it';
  Result := IdHttp1.Get('https://www.mio-ip.it');
end;
</code>```

The problem is that even if I fill it out without errors, it raises an error when I press the button:

IOHandler value is not valid

答:
You are requesting an HTTPS url. In order to use HTTPS (HTTP over SSL/TLS) with TIdHTTP, you need to assign a TIdSSLIOHandlerSocketBase-derived component to the TIdHTTP.IOHandler property, such as TIdSSLIOHandlerSocketOpenSSL. Also see New HTTPS functionality for TIdHTTP on Indy's blog.

Using TIdSSLIOHandlerSocketOpenSSL, you will have to deploy the 2 OpenSSL binaries with your app, ssleay32.dll and libeay32.dll. You can get them from Indy's OpenSSL-Binaries GitHub repo. Just note that TIdSSLIOHandlerSocketOpenSSL supports up to OpenSSL 1.0.2u. If you need OpenSSL 1.1.x instead (for TLS 1.3, etc), you can use this Work-in-Progress SSLIOHandler instead.

Or, you can use any other SSL/TLS library you want, as long as you can find (or write) an SSLIOHandler for it. For example, SecureBlackbox provides an SSLIOHandler for its own SSL/TLS engine. And this GitHub repo has an SSLIOHandler for LibTLS.

Body:
Doing so, I should get the public IP:

function TForm1.GetPublicIp: String;
begin
  IdHttp1.Request.Host := 'https://www.mio-ip.it';
  Result := IdHttp1.Get('https://www.mio-ip.it');
end;

The problem is that even if I fill it out without errors, it raises an error when I press the button:

IOHandler value is not valid


问:
GKE AppArmor profile is unconfined eventhough the node has it defined and working
I am trying to load an apparmor profile I created using GKE and some of the following instructions.

To apply the created app armor profile I followed this instructions:

https://cloud.google.com/container-optimized-os/docs/how-to/secure-apparmor#creating_a_custom_security_profile

which is just the apparmor parser applied to the node[s], and some follow up instructions to apply this same profile creation during restart of the node.
Basically is running the following line:

```<code>/sbin/apparmor_parser --replace --write-cache /etc/apparmor.d/no_raw_net
</code>```

and testing that a container with this profile is secured as expected.

As a second step I defined an environment variable with the apparmor profile name inside of an environment variable of the pod. As explained in here:

https://cloud.google.com/migrate/anthos/docs/troubleshooting/app-armor-profile

Basically is defining the pod in this way:

```<code>spec:
  containers:
  - image: gcr.io/my-project/my-container:v1.0.0
    name: my-container
    env:
    - name: HC_APPARMOR_PROFILE
      value: "apparmor-profile-name"
    securityContext:
      privileged: true
</code>```

Inside of the host the apparmor profile works as expected. But I cannot provide this profile.

Also tried removing the security context section of the pod that is defined as true in the documentation for gke.

Last but not least I tried with k8s pod annotation which is a feature of k8s to set a profile to a given container as explained here:

https://kubernetes.io/docs/tutorials/security/apparmor/

with this the pod looks like this:

```<code>apiVersion: v1
kind: Pod
metadata:
  name: hello-apparmor-2
  annotations:
    container.apparmor.security.beta.kubernetes.io/hello: localhost/k8s-apparmor-example-allow-write
spec:
  containers:
  - name: hello
    image: busybox
    command: [ "sh", "-c", "echo 'Hello AppArmor!' && sleep 1h" ]
</code>```

but also had no good luck to apply the given profile.

Also tried to apply user-data config as a custom metadata for the cloud-init of the node instance, so it can add also the profile I created to app armor, and double check that the creation matters is not an issue but the edition of the cluster matadata is disable post creation of the cluster, and the creation of a new cluster node with the user-data is not allowed due to the fact that user-data is reserved for the container optimized os user data that will be defined by google.

No matter what I do I always end up either having unconfined profile for the current container or "cri-containerd.apparmor.d (enforce)" depending if the security context is set to true or not...

Do you have any advice on how can I provide the given profile to a pod in GKE?

答:
If I understood the question correctly, seems like you are mixing the profile's filename with the profile name.

```<code>annotations:
    container.apparmor.security.beta.kubernetes.io/<container-name>: localhost/<profile-name>
</code>```

Here, <profile-name> is the name of the profile, it's not the same as the filename of the profile. Eg: in the below example filename is no_raw_net and profile name is no-ping.

```<code>cat > /etc/apparmor.d/no_raw_net <<EOF
#include <tunables/global>

profile no-ping flags=(attach_disconnected,mediate_deleted) {
  #include <abstractions/base>

  network inet tcp,
  network inet udp,
  network inet icmp,

  deny network raw,
  deny network packet,
  file,
  mount,
}
EOF
</code>```

Body:
I am trying to load an apparmor profile I created using GKE and some of the following instructions.

To apply the created app armor profile I followed this instructions:

https://cloud.google.com/container-optimized-os/docs/how-to/secure-apparmor#creating_a_custom_security_profile

which is just the apparmor parser applied to the node[s], and some follow up instructions to apply this same profile creation during restart of the node.
Basically is running the following line:

/sbin/apparmor_parser --replace --write-cache /etc/apparmor.d/no_raw_net

and testing that a container with this profile is secured as expected.

As a second step I defined an environment variable with the apparmor profile name inside of an environment variable of the pod. As explained in here:

https://cloud.google.com/migrate/anthos/docs/troubleshooting/app-armor-profile

Basically is defining the pod in this way:

spec:
  containers:
  - image: gcr.io/my-project/my-container:v1.0.0
    name: my-container
    env:
    - name: HC_APPARMOR_PROFILE
      value: "apparmor-profile-name"
    securityContext:
      privileged: true

Inside of the host the apparmor profile works as expected. But I cannot provide this profile.

Also tried removing the security context section of the pod that is defined as true in the documentation for gke.

Last but not least I tried with k8s pod annotation which is a feature of k8s to set a profile to a given container as explained here:

https://kubernetes.io/docs/tutorials/security/apparmor/

with this the pod looks like this:

apiVersion: v1
kind: Pod
metadata:
  name: hello-apparmor-2
  annotations:
    container.apparmor.security.beta.kubernetes.io/hello: localhost/k8s-apparmor-example-allow-write
spec:
  containers:
  - name: hello
    image: busybox
    command: [ "sh", "-c", "echo 'Hello AppArmor!' && sleep 1h" ]

but also had no good luck to apply the given profile.

Also tried to apply user-data config as a custom metadata for the cloud-init of the node instance, so it can add also the profile I created to app armor, and double check that the creation matters is not an issue but the edition of the cluster matadata is disable post creation of the cluster, and the creation of a new cluster node with the user-data is not allowed due to the fact that user-data is reserved for the container optimized os user data that will be defined by google.

No matter what I do I always end up either having unconfined profile for the current container or "cri-containerd.apparmor.d (enforce)" depending if the security context is set to true or not...

Do you have any advice on how can I provide the given profile to a pod in GKE?

Body:
If I understood the question correctly, seems like you are mixing the profile's filename with the profile name.

annotations:
    container.apparmor.security.beta.kubernetes.io/<container-name>: localhost/<profile-name>

Here, <profile-name> is the name of the profile, it's not the same as the filename of the profile. Eg: in the below example filename is no_raw_net and profile name is no-ping.

cat > /etc/apparmor.d/no_raw_net <<EOF
#include <tunables/global>

profile no-ping flags=(attach_disconnected,mediate_deleted) {
  #include <abstractions/base>

  network inet tcp,
  network inet udp,
  network inet icmp,

  deny network raw,
  deny network packet,
  file,
  mount,
}
EOF


问:
Vs Code nx console generate command not working : This command has no flags to set
I'm have nx console extension installed in my Vs Code and upon trying to use the generate command (generate component, service, library etc.) its saying "ng generate @schematics/angular:component
This command has no flags to set" . I don't want to write the commands manually since it is time consuming. I have tried uninstalling and reinstalling the extension, closing my VsCode but i still get the same error.

答: version 17.14.0 of extension nx-console has problem. Just install another and wait for new fix</p>


问:
Tap back button twice to terminate application in Fragment
I am implementing a function which is to close the application by clicking back button twice. It shows the toast message when it is first clicked. However, the problem is it shows infinite loop error then is termiated. I do not really understand the reason after two days of browsing. Any help will be greatly appreciated.

My fragment code

```<code>    class RegisteredMainFragment : Fragment() {

    private lateinit var binding : FragmentRegisteredMainBinding
    private val viewModel : RegisteredMainViewModel by inject()

    private lateinit var mContext: MainActivity

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context as MainActivity
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_registered_main, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.viewModel = viewModel
        binding.lifecycleOwner = viewLifecycleOwner

        onBackPressedCallback()
    }

    private fun onBackPressedCallback() {
        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,
            object : OnBackPressedCallback(true ) {
                override fun handleOnBackPressed() {
                    if (doubleBackToExitPressedOnce) {
                        requireFragmentManager().popBackStack()
                        return
                    }
                    doubleBackToExitPressedOnce = true
                    Toast.makeText(requireContext(), "click back button again", Toast.LENGTH_SHORT).show()
                    Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
            }
        })
    }

    override fun onResume() {
        super.onResume()
        viewModel.onAuthExist()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        PushObserverService.unregisterObserver(this)
    }
}
</code>```

答:
I solved the problem by writing it in override fun onAttach
Please check the code below

```<code>    override fun onAttach(context: Context) {
    super.onAttach(context)
    mContext = context as MainActivity

    callback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            if (doubleBackToExitPressedOnce) {
                activity?.finish()
            }
            doubleBackToExitPressedOnce = true
            Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
            showSnackBar(
                context = mContext,
                layout = binding.layoutMain,
                type = Constants.SnackBarTypes.Warn,
                message = mContext.getString(R.string.tap_twice_to_terminate)
            )
        }
    }
    requireActivity().onBackPressedDispatcher.addCallback(this, callback)
}
</code>```

Body:
I am implementing a function which is to close the application by clicking back button twice. It shows the toast message when it is first clicked. However, the problem is it shows infinite loop error then is termiated. I do not really understand the reason after two days of browsing. Any help will be greatly appreciated.

My fragment code

    class RegisteredMainFragment : Fragment() {

    private lateinit var binding : FragmentRegisteredMainBinding
    private val viewModel : RegisteredMainViewModel by inject()

    private lateinit var mContext: MainActivity

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context as MainActivity
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_registered_main, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.viewModel = viewModel
        binding.lifecycleOwner = viewLifecycleOwner

        onBackPressedCallback()
    }

    private fun onBackPressedCallback() {
        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,
            object : OnBackPressedCallback(true ) {
                override fun handleOnBackPressed() {
                    if (doubleBackToExitPressedOnce) {
                        requireFragmentManager().popBackStack()
                        return
                    }
                    doubleBackToExitPressedOnce = true
                    Toast.makeText(requireContext(), "click back button again", Toast.LENGTH_SHORT).show()
                    Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
            }
        })
    }

    override fun onResume() {
        super.onResume()
        viewModel.onAuthExist()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        PushObserverService.unregisterObserver(this)
    }
}

Body:
I solved the problem by writing it in override fun onAttach
Please check the code below

    override fun onAttach(context: Context) {
    super.onAttach(context)
    mContext = context as MainActivity

    callback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            if (doubleBackToExitPressedOnce) {
                activity?.finish()
            }
            doubleBackToExitPressedOnce = true
            Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
            showSnackBar(
                context = mContext,
                layout = binding.layoutMain,
                type = Constants.SnackBarTypes.Warn,
                message = mContext.getString(R.string.tap_twice_to_terminate)
            )
        }
    }
    requireActivity().onBackPressedDispatcher.addCallback(this, callback)
}


问:
How does data get into the General Purpose and other registers so that the CPU can use it for computing values?
I know that registers serve as storage units for the CPU to access data from in order to execute an instruction. The assembly language for these instructions look something like ADD R2, R1, R3 essentially asking us to add contents in R1 and R3 and place it in R2. My question is, how does data get into the registers R1 and R3 so that the CPU can use those values to compute and store the result in R2? And if all registers get full, is data evicted to main memory from the registers using an LRU method similar to how data from caches are evicted?</p>

答:
General Purpose Registers are very similar in concept to variables in a programming language

```<code>R1 = 3
R3 = 5
R2 = R1 + R3
</code>```

How you get those values into the registers is specific to the architecture and the value.  Some instruction sets have variable length instructions and can support any possible value

```<code>mov r1,0x12345678
</code>```

Others can load half a register

```<code>lui r1,0x12340000
</code>```

Not proper syntax for a real processor, but the ISA would allow for control
over the top half then you would follow it with an

```<code>ori r1,0x5678
</code>```

And the end result is r1 = 0x12345678

Another solution is to load from a nearby location

```<code>ldr r1,hello
...
hello: .word 0x12345678
</code>```

This would use pc-relative addressing, the assembler would do the math for you when it generates the instruction, but for example the actual instruction would be something like load from memory at the address of pc+16 into the register r1.

Registers are discrete and there is a fixed number of them, they are not cached or a fifo or anything like that.

From a programmer or compiler perspective, you can run out of them if you only have say 8 registers, and you are managing more than 8 data items, variables, addresses, etc.  AND you are using an architecture that requires
you to use registers for everything, then you would typically use the stack to temporarily store variables.

```<code>r1 = 0x12345678  (variable hello)
r2 = 0x55443366  (variable world)
...
I need another variable as the programmer I decide that I can live with out hello for a while
push {r1}
r1 = r2+r3     (variable foo)
str r1,[r4]    (the computed value was generated to store in memory)
foo is no longer neaded, but I need hello back
pop {r1}
</code>```

Compilers that take a higher level language and generate a lower level language, often assembly language or machine code, will track variables through a function and select which registers to use when.  A particular
register may through the course of the execution of a function may hold several variables or addresses or other data...obviously only one thing
at a time.  The same thing we would do as humans by hand, but according to
an algorithm.

Body:
General Purpose Registers are very similar in concept to variables in a programming language

R1 = 3
R3 = 5
R2 = R1 + R3

How you get those values into the registers is specific to the architecture and the value.  Some instruction sets have variable length instructions and can support any possible value

mov r1,0x12345678

Others can load half a register

lui r1,0x12340000

Not proper syntax for a real processor, but the ISA would allow for control
over the top half then you would follow it with an

ori r1,0x5678

And the end result is r1 = 0x12345678

Another solution is to load from a nearby location

ldr r1,hello
...
hello: .word 0x12345678

This would use pc-relative addressing, the assembler would do the math for you when it generates the instruction, but for example the actual instruction would be something like load from memory at the address of pc+16 into the register r1.

Registers are discrete and there is a fixed number of them, they are not cached or a fifo or anything like that.

From a programmer or compiler perspective, you can run out of them if you only have say 8 registers, and you are managing more than 8 data items, variables, addresses, etc.  AND you are using an architecture that requires
you to use registers for everything, then you would typically use the stack to temporarily store variables.

r1 = 0x12345678  (variable hello)
r2 = 0x55443366  (variable world)
...
I need another variable as the programmer I decide that I can live with out hello for a while
push {r1}
r1 = r2+r3     (variable foo)
str r1,[r4]    (the computed value was generated to store in memory)
foo is no longer neaded, but I need hello back
pop {r1}

Compilers that take a higher level language and generate a lower level language, often assembly language or machine code, will track variables through a function and select which registers to use when.  A particular
register may through the course of the execution of a function may hold several variables or addresses or other data...obviously only one thing
at a time.  The same thing we would do as humans by hand, but according to
an algorithm.


问:
What is Inversion of Control?
Inversion of Control (IoC) can be quite confusing when it is first encountered.

What is it?

Which problem does it solve?

When is it appropriate to use and when not?

答:
I think of Inversion of Control in the context of using a library or a framework.

The traditional way of "control" is that we build a controller class (usually main, but it could be anything), import a library and then use your controller class to "control" the action of the software components. Like your first C/Python program (after Hello World).

```<code>import pandas as pd
df = new DataFrame()
# Now do things with the dataframe.
</code>```

In this case, we need to know what a Dataframe is in order to work with it. You need to know what methods to use, how values it takes and so on. If you add it to your own class through polymorphism or just calling it anew, your class will need the DataFrame library to work properly.

"Inversion of Control" means that the process is reversed. Instead of your classes controlling elements of a library, framework or engine, you register classes and send them back to the engine to be controlled. Worded another way, IoC can mean we are using our code to configuring a framework. You could also think of it as similar to the way we use functions in map or filter to deal with data in a list, except apply that to an entire application.

If you are the one who has built the engine, then you are probably using Dependency Injection approaches (described above) to make that happen. If you are the one using the engine (more common), then you should be able to just declare classes, add appropriate notations and let the framework do the rest of the work (e.g. creating routes, assigning servlets, setting events, outputting widgets etc.) for you.

Title: What is Inversion of Control?

Body:
I think of Inversion of Control in the context of using a library or a framework.

The traditional way of "control" is that we build a controller class (usually main, but it could be anything), import a library and then use your controller class to "control" the action of the software components. Like your first C/Python program (after Hello World).

import pandas as pd
df = new DataFrame()
# Now do things with the dataframe.

In this case, we need to know what a Dataframe is in order to work with it. You need to know what methods to use, how values it takes and so on. If you add it to your own class through polymorphism or just calling it anew, your class will need the DataFrame library to work properly.

"Inversion of Control" means that the process is reversed. Instead of your classes controlling elements of a library, framework or engine, you register classes and send them back to the engine to be controlled. Worded another way, IoC can mean we are using our code to configuring a framework. You could also think of it as similar to the way we use functions in map or filter to deal with data in a list, except apply that to an entire application.

If you are the one who has built the engine, then you are probably using Dependency Injection approaches (described above) to make that happen. If you are the one using the engine (more common), then you should be able to just declare classes, add appropriate notations and let the framework do the rest of the work (e.g. creating routes, assigning servlets, setting events, outputting widgets etc.) for you.


问:
Problems with the installation of VirtualBox on Ubuntu 20.04.1 LTS
just so you know I'm pretty new at Linux.

I just made the jump from Ubuntu 19.10 to Ubuntu 20.04.1 LTS because I thought there wouldn't be a problem with VirtualBox.
When the upgrade was finished I noticed VirtualBox was gone, I tried to install it following the instruction on the official website and other sites.

I don't know what you guys exactly need to help me solve the problem so here's some informations :

Here's what appears when I do sudo apt update :

```<code>Hit:1 http://archive.ubuntu.com/ubuntu focal InRelease
Get:2 http://archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]
Get:3 http://security.ubuntu.com/ubuntu focal-security InRelease [109 kB]
Hit:4 http://download.virtualbox.org/virtualbox/debian focal InRelease
Get:5 http://security.ubuntu.com/ubuntu focal-security/main i386 Packages [169 kB]
Get:6 http://security.ubuntu.com/ubuntu focal-security/main amd64 Packages [412 kB]
Get:7 http://security.ubuntu.com/ubuntu focal-security/main Translation-en [93,5 kB]
Get:8 http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages [724 kB]
Get:9 http://archive.ubuntu.com/ubuntu focal-updates/main i386 Packages [399 kB]
Get:10 http://archive.ubuntu.com/ubuntu focal-updates/main Translation-en [180 kB]
Get:11 http://archive.ubuntu.com/ubuntu focal-updates/main amd64 c-n-f Metadata [11,4 kB]
Get:12 http://archive.ubuntu.com/ubuntu focal-updates/restricted i386 Packages [13,4 kB]
Get:13 http://archive.ubuntu.com/ubuntu focal-updates/restricted amd64 Packages [110 kB]
Get:14 http://archive.ubuntu.com/ubuntu focal-updates/restricted Translation-en [16,5 kB]
Fetched 2 352 kB in 1s (2 345 kB/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
10 packages can be upgraded. Run 'apt list --upgradable' to see them.
</code>```

Now sudo apt install virtualbox virtualbox-ext-pack :

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Package virtualbox is a virtual package provided by:
  virtualbox-6.1 6.1.16-140961~Ubuntu~eoan
  virtualbox-6.0 6.0.24-139119~Ubuntu~eoan
You should explicitly select one to install.

Package virtualbox-ext-pack is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'virtualbox' has no installation candidate
E: Package 'virtualbox-ext-pack' has no installation candidate
</code>```

Or when I do sudo apt install virtualbox-6.0 :

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 virtualbox-6.0 : Depends: libqt5printsupport5 (>= 5.0.2) but it is not installable
                  Depends: python (< 2.8) but it is not installable
                  Depends: python (>= 2.7) but it is not installable
                  Depends: python:any (>= 2.6.6-7~)
                  Recommends: libsdl-ttf2.0-0 but it is not installable
                  Recommends: gcc but it is not going to be installed
                  Recommends: make but it is not going to be installed or
                              build-essential but it is not going to be installed or
                              dpkg-dev but it is not going to be installed
                  Recommends: binutils but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

I did

```<code>$ wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | sudo apt-key add -
$ wget -q https://www.virtualbox.org/download/oracle_vbox.asc -O- | sudo apt-key add -
</code>```

and

```<code>echo "deb [arch=amd64] http://download.virtualbox.org/virtualbox/debian $(lsb_release -cs) contrib" | \
     sudo tee -a /etc/apt/sources.list.d/virtualbox.list
</code>```

without any problems.

I hope everyone is having a good day :)

答:
I solved it in the following way

```<code>sudo add-apt-repository universe
sudo add-apt-repository multiverse
sudo add-apt-repository "deb http://download.virtualbox.org/virtualbox/debian bionic contrib"
sudo apt-get update
</code>```

If when doing apt-get update it appears:

N: Skipping acquire of configured file 'contrib/binary-i386/Packages'
as repository 'http://download.virtualbox.org/virtualbox/debian bionic
InRelease' doesn't support architecture 'i386'

then:

```<code>echo "deb [arch=amd64] http://download.virtualbox.org/virtualbox/debian $(lsb_release -sc) contrib" | sudo tee /etc/apt/sources.list
</code>```

continue:

```<code>sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get install libpng16-16 libqt5core5a libqt5printsupport5 libqt5widgets5 libqt5x11extras5
sudo apt-get install virtualbox-6.0 -y
</code>```

Body:
just so you know I'm pretty new at Linux.

I just made the jump from Ubuntu 19.10 to Ubuntu 20.04.1 LTS because I thought there wouldn't be a problem with VirtualBox.
When the upgrade was finished I noticed VirtualBox was gone, I tried to install it following the instruction on the official website and other sites.

I don't know what you guys exactly need to help me solve the problem so here's some informations :

Here's what appears when I do sudo apt update :

Hit:1 http://archive.ubuntu.com/ubuntu focal InRelease
Get:2 http://archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]
Get:3 http://security.ubuntu.com/ubuntu focal-security InRelease [109 kB]
Hit:4 http://download.virtualbox.org/virtualbox/debian focal InRelease
Get:5 http://security.ubuntu.com/ubuntu focal-security/main i386 Packages [169 kB]
Get:6 http://security.ubuntu.com/ubuntu focal-security/main amd64 Packages [412 kB]
Get:7 http://security.ubuntu.com/ubuntu focal-security/main Translation-en [93,5 kB]
Get:8 http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages [724 kB]
Get:9 http://archive.ubuntu.com/ubuntu focal-updates/main i386 Packages [399 kB]
Get:10 http://archive.ubuntu.com/ubuntu focal-updates/main Translation-en [180 kB]
Get:11 http://archive.ubuntu.com/ubuntu focal-updates/main amd64 c-n-f Metadata [11,4 kB]
Get:12 http://archive.ubuntu.com/ubuntu focal-updates/restricted i386 Packages [13,4 kB]
Get:13 http://archive.ubuntu.com/ubuntu focal-updates/restricted amd64 Packages [110 kB]
Get:14 http://archive.ubuntu.com/ubuntu focal-updates/restricted Translation-en [16,5 kB]
Fetched 2 352 kB in 1s (2 345 kB/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
10 packages can be upgraded. Run 'apt list --upgradable' to see them.

Now sudo apt install virtualbox virtualbox-ext-pack :

Reading package lists... Done
Building dependency tree
Reading state information... Done
Package virtualbox is a virtual package provided by:
  virtualbox-6.1 6.1.16-140961~Ubuntu~eoan
  virtualbox-6.0 6.0.24-139119~Ubuntu~eoan
You should explicitly select one to install.

Package virtualbox-ext-pack is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'virtualbox' has no installation candidate
E: Package 'virtualbox-ext-pack' has no installation candidate

Or when I do sudo apt install virtualbox-6.0 :

Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 virtualbox-6.0 : Depends: libqt5printsupport5 (>= 5.0.2) but it is not installable
                  Depends: python (< 2.8) but it is not installable
                  Depends: python (>= 2.7) but it is not installable
                  Depends: python:any (>= 2.6.6-7~)
                  Recommends: libsdl-ttf2.0-0 but it is not installable
                  Recommends: gcc but it is not going to be installed
                  Recommends: make but it is not going to be installed or
                              build-essential but it is not going to be installed or
                              dpkg-dev but it is not going to be installed
                  Recommends: binutils but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I did

$ wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | sudo apt-key add -
$ wget -q https://www.virtualbox.org/download/oracle_vbox.asc -O- | sudo apt-key add -

and

echo "deb [arch=amd64] http://download.virtualbox.org/virtualbox/debian $(lsb_release -cs) contrib" | \
     sudo tee -a /etc/apt/sources.list.d/virtualbox.list

without any problems.

I hope everyone is having a good day :)

Body:
I solved it in the following way

sudo add-apt-repository universe
sudo add-apt-repository multiverse
sudo add-apt-repository "deb http://download.virtualbox.org/virtualbox/debian bionic contrib"
sudo apt-get update

If when doing apt-get update it appears:

N: Skipping acquire of configured file 'contrib/binary-i386/Packages'
as repository 'http://download.virtualbox.org/virtualbox/debian bionic
InRelease' doesn't support architecture 'i386'

then:

echo "deb [arch=amd64] http://download.virtualbox.org/virtualbox/debian $(lsb_release -sc) contrib" | sudo tee /etc/apt/sources.list

continue:

sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get install libpng16-16 libqt5core5a libqt5printsupport5 libqt5widgets5 libqt5x11extras5
sudo apt-get install virtualbox-6.0 -y


问:
When using Pinia and TypeScript how do you use an Action to set the State?
I have a Pinia + TypeScript store named user.ts that looks like this:

```<code>import { User } from 'firebase/auth';
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
  state: () =>
    ({
      displayName: null,
      email: null,
      emailVerified: null,
      isAnonymous: null,
      metadata: null,
      multiFactor: null,
      phoneNumber: null,
      photoURL: null,
      providerData: null,
      providerId: null,
      refreshToken: null,
      tenantId: null,
      uid: null,
    } as unknown as User),
  actions: {
    setPhotoURL(photoURLData: string | null) {
      this.photoURL = photoURLData; //<-- ERROR HERE
    },
  },
});
</code>```

The state is a FireBase User object.

And I want to update photoURL using the setPhotoURL() action.

But photoURL has this TypeScript error:

```<code>Cannot assign to 'photoURL' because it is a read-only property. ts(2540)
</code>```

What am I doing wrong?

Is this the correct way to update state?

答:
You can remove the readonly modifier by mapping the type :

Mapping Modifiers

There are two additional modifiers which can be applied during mapping: readonly and ? which affect mutability and optionality respectively.

You can remove or add these modifiers by prefixing with - or +. If you don’t add a prefix, then + is assumed.

// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
  -readonly [Property in keyof Type]: Type[Property];
};
```
</blockquote>
<p>If the type has nested properties that you want to be writeable, map recursively:</p>
<pre class="lang-js prettyprint-override"><code>type CreateMutable<T> = { -readonly [P in keyof T]: CreateMutable<T[P]> }
</code>```

Then use it to type the store's user property:

import type { User } from 'firebase/auth'
import { defineStore } from 'pinia'

type CreateMutable<T> = { -readonly [P in keyof T]: CreateMutable<T[P]> }

export const useUserStore = defineStore('user', {
  state: () => ({ user: {} as CreateMutable<User> }),

  actions: {
    setPhotoURL(photoURLData: string | null) {
      this.user.photoURL = photoURLData
    },
  },
})
```

Body:
I have a Pinia + TypeScript store named user.ts that looks like this:

import { User } from 'firebase/auth';
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
  state: () =>
    ({
      displayName: null,
      email: null,
      emailVerified: null,
      isAnonymous: null,
      metadata: null,
      multiFactor: null,
      phoneNumber: null,
      photoURL: null,
      providerData: null,
      providerId: null,
      refreshToken: null,
      tenantId: null,
      uid: null,
    } as unknown as User),
  actions: {
    setPhotoURL(photoURLData: string | null) {
      this.photoURL = photoURLData; //<-- ERROR HERE
    },
  },
});

The state is a FireBase User object.

And I want to update photoURL using the setPhotoURL() action.

But photoURL has this TypeScript error:

Cannot assign to 'photoURL' because it is a read-only property. ts(2540)

What am I doing wrong?

Is this the correct way to update state?

Body:
You can remove the readonly modifier by mapping the type :

Mapping Modifiers

There are two additional modifiers which can be applied during mapping: readonly and ? which affect mutability and optionality respectively.

You can remove or add these modifiers by prefixing with - or +. If you don’t add a prefix, then + is assumed.

// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
  -readonly [Property in keyof Type]: Type[Property];
};

If the type has nested properties that you want to be writeable, map recursively:

type CreateMutable<T> = { -readonly [P in keyof T]: CreateMutable<T[P]> }

Then use it to type the store's user property:

import type { User } from 'firebase/auth'
import { defineStore } from 'pinia'

type CreateMutable<T> = { -readonly [P in keyof T]: CreateMutable<T[P]> }

export const useUserStore = defineStore('user', {
  state: () => ({ user: {} as CreateMutable<User> }),

  actions: {
    setPhotoURL(photoURLData: string | null) {
      this.user.photoURL = photoURLData
    },
  },
})


问:
Creating a script for a Telnet session?
Does anyone know of an easy way to create a script that can connect to a telnet server, do some usual telnet stuff, and then log off?  I am dealing with users who are not familiar with telnet and the commands they will need to run.  All I want is for them to double-click on a script, and have that script automatically execute the commands for them.

You're probably wondering, "What platform are the users on?"  They will be on both Windows and Linux.  Implementations in languages like Perl, Java, or Python are acceptable.  I see that Perl has a Net:: Telnet module.  Has anyone used that?

My ideal solution would be to create two script files. a BAT file for windows, and a shell script for Linux.  While this would make dual maintenance an issue, it would mean I wouldn't have to install Perl/Java/Python/etc... on every machine.  Unfortunately, I have not seen any way to automate a telnet session with batch files or shell scripts.

Thanks.

答:
Couple of questions:

Can you put stuff on the device that you're telnetting into?

Are the commands executed by the script the same or do they vary by machine/user?

Do you want the person clicking the icon to have to provide a userid and/or password?

That said, I wrote some Java a while ago to talk to a couple of IP-enabled power strips (BayTech RPC3s) which might be of use to you.  If you're interested I'll see if I can dig it up and post it someplace.

OwnerDisplayName: SpaceRook

Title: Creating a script for a Telnet session?

LastEditorDisplayName: curtisk

OwnerDisplayName: BonkaBonka

ContentLicense: CC BY-SA 2.5


问:
How to mark classes as Obsolete on UML
I have a few classes on my UML diagram which should not be used, but still available.
Is there any way to mark these classes as obsolete?

I've seen <> notation somewhere, but can not find how to use it in MS Visio 2003.

And another question. Should these classes be on UML diagram at all? I can imagine answer on this question would be on "per case" basis, but I'm interested in hearing general opinions. And if you put obsolete classes on your UML diagrams, why you did it? or why not?

Thanks!

答: I think if you're going to take the time to update the UML, the best idea is to remove it from the model.  Leaving a bunch of "obsolete" diagram elements hanging around makes as much sense as keeping commented code in a version control system.  Let the version control system manage the history.</p>

Title: How to mark classes as Obsolete on UML


问:
How filter array of objects based on objects exists in another array of objects?
I have

```<code>array1 = [{ name: sample1 }, { name: sample2 }, { name: sample3 }];
array2 = [{ name: sample1 }, { name: sample2 }];
</code>```

I want to filter objects of array1 which exists in array2.
So I need to have

```<code>[{ name: sample1 }, { name: sample2 }]
</code>```

How can I get it in javascript?

答:
You can use object destructuring, the map() and .includes() methods as shown below:

const array1 = [{ name: "sample1" }, { name: "sample2" }, { name: "sample3" }];
const array2 = [{ name: "sample1" }, { name: "sample2" }];

const filtered = array1.filter(
    ({name}) => array2.map(o => o.name).includes(name)
);

console.log( filtered );```

Body:
I have

array1 = [{ name: sample1 }, { name: sample2 }, { name: sample3 }];
array2 = [{ name: sample1 }, { name: sample2 }];

I want to filter objects of array1 which exists in array2.
So I need to have

[{ name: sample1 }, { name: sample2 }]

How can I get it in javascript?


问:
XPath for element with child X with no leading text, and no child Y
With this:

```<code><p>Some variable length text <abbr>abc</abbr> and more text.</p>
<p><abbr>abc</abbr>Some variable length text.</p>
<p><abbr>abc</abbr>Some variable length text. <a href="somelink">blah</a></p>
</code>```

I'm trying to build an Xpath that will find p elements that:

Have a child  with value of "abc", but that child has no intervening text between the parent and the child.

Does not have a child .

#1 means the first line should not match, because it has text between the parent
 and the child .
#2 means the third line should not match, because although there is a child  and no leading text, it also has a child .

Thus, only the second line,

```<code><p><abbr>abc</abbr>Some variable length text.</p>
</code>```

should match: no leading text, and no child .

I've played with an XPath testbed for an hour, and done quite a bit of searching, but haven't figured out how to handle both of those requirements, but especially #1.

答:
This XPath,

```<code>//p[node()[1][self::abbr]='abc'][not(a)]
</code>```

selects all p elements

with a first sibling abbr element that has a string value of "abc"1, and

without an a child,

as requested.

1 Note that #1 implies that abbr must be the first node, which prevents any node (text, another element, etc) from being a previous sibling to abbr.

Body:
With this:

Some variable length text abc and more text.

abcSome variable length text.

abcSome variable length text. blah

I'm trying to build an Xpath that will find p elements that:

Have a child  with value of "abc", but that child has no intervening text between the parent and the child.

Does not have a child .

#1 means the first line should not match, because it has text between the parent
 and the child .
#2 means the third line should not match, because although there is a child  and no leading text, it also has a child .

Thus, only the second line,

abcSome variable length text.

should match: no leading text, and no child .

I've played with an XPath testbed for an hour, and done quite a bit of searching, but haven't figured out how to handle both of those requirements, but especially #1.

Body:
This XPath,

//p[node()[1][self::abbr]='abc'][not(a)]

selects all p elements

with a first sibling abbr element that has a string value of "abc"1, and

without an a child,

as requested.

1 Note that #1 implies that abbr must be the first node, which prevents any node (text, another element, etc) from being a previous sibling to abbr.


问:
UNION works with CTE, but not without?
I'm using PostgreSQL 11.12.

I have this query:

```<code>select first_name, length(first_name)
from db_employee
where length(first_name) =
(select max(length(first_name)) from db_employee)
order by 1
limit 1
union
select first_name, length(first_name)
from db_employee
where length(first_name) =
(select min(length(first_name)) from db_employee)
order by 1
limit 1
</code>```

and when I run it I get this error:

```<code>syntax error at or near "union"
</code>```

If I use CTE it works:

```<code>with cte1 as
(select first_name, length(first_name)
from db_employee
where length(first_name) =
(select max(length(first_name)) from db_employee)
order by 1
limit 1),

cte2 as
(select first_name, length(first_name)
from db_employee
where length(first_name) =
(select min(length(first_name)) from db_employee)
order by 1
limit 1)

select * from cte1
union
select * from cte2;
</code>```

Why does the first query result in syntax error?  Is it possible to get it to work without using CTE?

答:
just put both the sql parts in separate brackets and keep union outside.

```<code>    (select first_name, length(first_name)
    from db_employee
    where length(first_name) =
    (select max(length(first_name)) from db_employee)
    order by 1
    limit 1)
    union
    (select first_name, length(first_name)
    from db_employee
    where length(first_name) =
    (select min(length(first_name)) from db_employee)
    order by 1
    limit 1);
</code>```

another way of doing the same thing:

```<code>    select * from (
    select first_name, l_fname
    ,row_number() over (order by l_fname) rn_min
    ,row_number() over (order by l_fname desc) rn_max
    from(
    select first_name,length(first_name) l_fname from db_employee
    ) A
    ) b where (rn_min = 1 or rn_max = 1);
</code>```

Title: UNION works with CTE, but not without?

Body:
I'm using PostgreSQL 11.12.

I have this query:

select first_name, length(first_name)
from db_employee
where length(first_name) =
(select max(length(first_name)) from db_employee)
order by 1
limit 1
union
select first_name, length(first_name)
from db_employee
where length(first_name) =
(select min(length(first_name)) from db_employee)
order by 1
limit 1

and when I run it I get this error:

syntax error at or near "union"

If I use CTE it works:

with cte1 as
(select first_name, length(first_name)
from db_employee
where length(first_name) =
(select max(length(first_name)) from db_employee)
order by 1
limit 1),

cte2 as
(select first_name, length(first_name)
from db_employee
where length(first_name) =
(select min(length(first_name)) from db_employee)
order by 1
limit 1)

select * from cte1
union
select * from cte2;

Why does the first query result in syntax error?  Is it possible to get it to work without using CTE?

Body:
just put both the sql parts in separate brackets and keep union outside.

    (select first_name, length(first_name)
    from db_employee
    where length(first_name) =
    (select max(length(first_name)) from db_employee)
    order by 1
    limit 1)
    union
    (select first_name, length(first_name)
    from db_employee
    where length(first_name) =
    (select min(length(first_name)) from db_employee)
    order by 1
    limit 1);

another way of doing the same thing:

    select * from (
    select first_name, l_fname
    ,row_number() over (order by l_fname) rn_min
    ,row_number() over (order by l_fname desc) rn_max
    from(
    select first_name,length(first_name) l_fname from db_employee
    ) A
    ) b where (rn_min = 1 or rn_max = 1);


问:
what is the regex pattern for a regex pattern?
What is the regex pattern for a regex pattern? I am using Ruby version 1.8.7, and have a requirement to determine if a given string is a regex pattern. What is the best pattern to use to determine this?

Thanks,
Anand

答:
There isn't one, since regexes themselves aren't a regular language (due to things like matching parentheses).

If you want to determine whether something is a valid regex, I'd recommend just trying to compile it as a regex and see if it fails.