问:
Setting up data for Mockito
I am unit testing my spring Rest API and I have had joy mocking my create and retrieve methods using the following structure.

```<code>    @Test
    public void getAllUsersReturnsAListOfAllTheUsersInJSONFormat() throws Exception {
        List<User> users = new ArrayList<>();
        users.add(new User("DelBoy"));
        users.add(new User("Rodney_Trotter"));
        users.add(new User("Uncle.Albert"));

        Mockito.when(service.getAllUsers()).thenReturn(users);

        mvc.perform(get("/api/users"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", Matchers.hasSize(3)))
                .andExpect(jsonPath("$[0].username", Matchers.equalTo("DelBoy")))
                .andExpect(jsonPath("$[1].username", Matchers.equalTo("Rodney_Trotter")))
                .andExpect(jsonPath("$[2].username", Matchers.equalTo("Uncle.Albert")));
    }
</code>```

However, I am trying to create a test for my Update and Delete methods. When I mock the methods they never behave as expected because there is no data to update or delete. After extensive research online I cannot find any information pointing to resolving this issue. My current attempt is the following code.

```<code>    @Test
    public void updateUserUpdatesAUserUponSuccess() throws Exception {

        User updatedUser = new User(UUID.fromString("da3f6cae-9126-407b-a1ea-093bdac72434"), "Trigger");

        Mockito.when(service.updateUser(updatedUser)).thenReturn(true);
        Mockito.when(validator.validateUsername(updatedUser.getUsername())).thenReturn(true);
        Mockito.when(validator.validateUUID(updatedUser.getUserId().toString())).thenReturn(true);

        String str = mvc.perform(put("/api/users/da3f6cae-9126-407b-a1ea-093bdac72434/TriggersBroom"))
                .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

        System.out.println(str);
    }
</code>```

I am not sure how to have user data mocked so that when I make a PUT request it can update the user at the hex Id specified to a different username ("trigger" being the username). How I would like this to work is to have a small set of user objects that I can update when I mock my updateUser function so I can test the update user route actually updates a record. Currently it returns false because nothing is being updated but it should return true as I have tested manually in my development environment outside of unit testing and it works.

Note:
The println was my was of checking what was actually returned and it was false.

答:
How I would like this to work is to have a small set of user objects that I can update when I mock my updateUser function so I can test the update user route actually updates a record

This is because you write:

```<code>        User updatedUser = new User(UUID.fromString("da3f6cae-9126-407b-a1ea-093bdac72434"), "Trigger");
        Mockito.when(service.updateUser(updatedUser)).thenReturn(true);
</code>```

Then you can see the updatedUser is not the same instance as the one you gonna call in the real service, it's just a instance you created above.

To mock this, you have 2 ways:

If you can get the exactly same instance as the one you gonna call in real service, it will return true for you.

You can use Mockito.eq(updatedUser) to mock. E.g. Mockito.when(service.updateUser(Mockito.eq(updatedUser))).thenReturn(true);
But then you need to remember to override the equals() method for class User. Then if you modify the method equals(), you need to update hashCode() as well

Title: Setting up data for Mockito

Body:
I am unit testing my spring Rest API and I have had joy mocking my create and retrieve methods using the following structure.

    @Test
    public void getAllUsersReturnsAListOfAllTheUsersInJSONFormat() throws Exception {
        List<User> users = new ArrayList<>();
        users.add(new User("DelBoy"));
        users.add(new User("Rodney_Trotter"));
        users.add(new User("Uncle.Albert"));

        Mockito.when(service.getAllUsers()).thenReturn(users);

        mvc.perform(get("/api/users"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", Matchers.hasSize(3)))
                .andExpect(jsonPath("$[0].username", Matchers.equalTo("DelBoy")))
                .andExpect(jsonPath("$[1].username", Matchers.equalTo("Rodney_Trotter")))
                .andExpect(jsonPath("$[2].username", Matchers.equalTo("Uncle.Albert")));
    }

However, I am trying to create a test for my Update and Delete methods. When I mock the methods they never behave as expected because there is no data to update or delete. After extensive research online I cannot find any information pointing to resolving this issue. My current attempt is the following code.

    @Test
    public void updateUserUpdatesAUserUponSuccess() throws Exception {

        User updatedUser = new User(UUID.fromString("da3f6cae-9126-407b-a1ea-093bdac72434"), "Trigger");

        Mockito.when(service.updateUser(updatedUser)).thenReturn(true);
        Mockito.when(validator.validateUsername(updatedUser.getUsername())).thenReturn(true);
        Mockito.when(validator.validateUUID(updatedUser.getUserId().toString())).thenReturn(true);

        String str = mvc.perform(put("/api/users/da3f6cae-9126-407b-a1ea-093bdac72434/TriggersBroom"))
                .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

        System.out.println(str);
    }

I am not sure how to have user data mocked so that when I make a PUT request it can update the user at the hex Id specified to a different username ("trigger" being the username). How I would like this to work is to have a small set of user objects that I can update when I mock my updateUser function so I can test the update user route actually updates a record. Currently it returns false because nothing is being updated but it should return true as I have tested manually in my development environment outside of unit testing and it works.

Note:
The println was my was of checking what was actually returned and it was false.

Body:
How I would like this to work is to have a small set of user objects that I can update when I mock my updateUser function so I can test the update user route actually updates a record

This is because you write:

        User updatedUser = new User(UUID.fromString("da3f6cae-9126-407b-a1ea-093bdac72434"), "Trigger");
        Mockito.when(service.updateUser(updatedUser)).thenReturn(true);

Then you can see the updatedUser is not the same instance as the one you gonna call in the real service, it's just a instance you created above.

To mock this, you have 2 ways:

If you can get the exactly same instance as the one you gonna call in real service, it will return true for you.

You can use Mockito.eq(updatedUser) to mock. E.g. Mockito.when(service.updateUser(Mockito.eq(updatedUser))).thenReturn(true);
But then you need to remember to override the equals() method for class User. Then if you modify the method equals(), you need to update hashCode() as well


来源: stackexchange

问:
Are C# events synchronous?
There are two parts to this question:

Does raising an event block the thread, or does it start execution of EventHandlers asynchronously and the thread goes continues on at the same time?

Are the individual EventHandlers (subscribed to the event) run synchronously one after another, or are they run asynchronously with no guarantee that others aren't running at the same time?

答:
Events are synchronous. This is why the event lifecycle works the way it does. Inits happen before loads, loads happen before renders etc.

If no handler is specified for an event, the cycle just blazes through. If more than one handler is specified, they will be called in order and one can't continue until the other is completely finished.

Even asynchronous calls are synchronous to a degree. It would be impossible to call the end before the begin is completed.

ContentLicense: CC BY-SA 4.0

Title: Are C# events synchronous?

ContentLicense: CC BY-SA 3.0


问:
How can I view the return value from Future<bool>
How can I view the return value from Future

 Future<bool> res;
 res = cancelDialog();
 print("res..........: ${res}");
 ```
</div>
</div>
</p>
<p>my cancel dialog:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Future<bool> cancelDialog(_formKey, context, cancelFn) async {
  var res = await showModalActionSheet(
      onWillPop: () async => false,
      context: context,
      actions: <SheetAction>[
        SheetAction(label: "Evet", key: "evet"),
        SheetAction(label: "Hayır", key: "hayir")
      ],
      title: "Tüm değişilikler geri alınacaktır.",
      message: "Devam etmek istediğinize emin misiniz?");
  if (res == "evet") {
    _formKey.currentState?.reset();
     cancelFn.call();
     //return true;
     return Future<bool>.value(true);

  } else {
   //retun false;
    return Future<bool>.value(false);
  }
}</code>```

output : res..........: Instance of 'Future'

The value I want to see in the res is true or false, how can I provide it?

Thank YOU!

答:
To get the value of Future you have to add await keyword before that as below:

```<code> Future<bool> res;
 res = await cancelDialog();
 print("res..........: ${res}");
</code>```

Check it out and do let me know if you face the problem.

Body:
How can I view the return value from Future

 Future<bool> res;
 res = cancelDialog();
 print("res..........: ${res}");

my cancel dialog:

Future<bool> cancelDialog(_formKey, context, cancelFn) async {
  var res = await showModalActionSheet(
      onWillPop: () async => false,
      context: context,
      actions: <SheetAction>[
        SheetAction(label: "Evet", key: "evet"),
        SheetAction(label: "Hayır", key: "hayir")
      ],
      title: "Tüm değişilikler geri alınacaktır.",
      message: "Devam etmek istediğinize emin misiniz?");
  if (res == "evet") {
    _formKey.currentState?.reset();
     cancelFn.call();
     //return true;
     return Future<bool>.value(true);

  } else {
   //retun false;
    return Future<bool>.value(false);
  }
}

output : res..........: Instance of 'Future'

The value I want to see in the res is true or false, how can I provide it?

Thank YOU!

Body:
To get the value of Future you have to add await keyword before that as below:

 Future<bool> res;
 res = await cancelDialog();
 print("res..........: ${res}");

Check it out and do let me know if you face the problem.


问:
Return the previous values in the form when the button is clicked (Javascript)
I have the following form shown below. I would like that when you click on the Cancel changes button the values of the fields return to the previous ones.

For example, if I have the word John and I delete hn (thus having Jo), clicking on the button I would like it to return to John.

How can I do this?

<form >
  First name:

  <input type="text" id="fname" name="fname">

  Last name:

  <input type="text" id="lname" name="lname">

  <input type="submit" value="Cancel changes">
</form> ```

答:
I'm not sure if this is the right question.

But if what you want is a semblance of "CTRL + Z", you can save the state of the form in an Object or in the LocalStorage at each user input and reassign these elements to the corresponding fields when we click on CANCEL.

There are plenty of solution out there like this one:
https://gist.github.com/shawnbot/89855705204494c6d8bf


问:
How to SELECT geometry data from a geoJson in MySQL
I want to get all the data from a geoJSON to insert it then in a table with a GEOMETRY type.

The file can be downloaded on opendata.arcgis.com.

Everything is ok except the geometry data returned is NULL from the following query.

```<code>SELECT
    x.UNIT_NAME,
    x.UNIT_CODE,
    x.geometry
FROM
    NPS
CROSS JOIN json_table(
    doc,
    '$.features[*]' columns (
        UNIT_NAME varchar(50) PATH '$.properties.UNIT_NAME',
        UNIT_CODE varchar(50) PATH '$.properties.UNIT_CODE',
        geometry geometry PATH '$.geometry'
    )
) x
</code>```

MySQL Result

```<code>UNIT_NAME|UNIT_CODE|geometry
Appalachian National Scenic Trail|APPA|NULL
White House|WHHO|NULL
</code>```

An abstract of the file is here:

```<code>{
    "type": "FeatureCollection",
    "name": "NPS_-_Land_Resources_Division_Boundary_and_Tract_Data_Service",
    "crs": {
        "type": "name",
        "properties": {
            "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
        }
    },
    "features": [{
            "type": "Feature",
            "properties": {
                "OBJECTID": 1,
                "UNIT_CODE": "APPA",
                "GIS_Notes": "Lands - http://landsnet.nps.gov/tractsnet/documents/APPA/Metadata/appa_metadata.xml",
                "UNIT_NAME": "Appalachian National Scenic Trail",
                "DATE_EDIT": "2021-12-07T00:00:00Z",
                "STATE": "ME",
                "REGION": "NE",
                "GNIS_ID": "2766084",
                "UNIT_TYPE": "National Scenic Trail",
                "CREATED_BY": "Lands",
                "METADATA": "https://irma.nps.gov/DataStore/Reference/Profile/2259619",
                "PARKNAME": "Appalachian",
                "CreationDate": "2022-01-06T10:43:45Z",
                "Creator": "WASO",
                "EditDate": "2022-01-06T10:43:45Z",
                "Editor": "WASO",
                "GlobalID": "3923bec4-1652-41ca-a444-84fead65aba5",
                "Shape__Area": 1483097401.5976601,
                "Shape__Length": 5738045.6635156097
            },
            "geometry": {
                "type": "MultiPolygon",
                "coordinates": [
                    [
                        [
                            [-84.2329423255553, 34.623125245778901],
                            [-69.029418383436607, 45.847784381666997],
                            [-69.029490112115397, 45.849869184805797],
                            [-69.029642890392395, 45.854309758604899]
                        ]
                    ]
                ]
            }
        },
        {
            "type": "Feature",
            "properties": {
                "OBJECTID": 2,
                "UNIT_CODE": "WHHO",
                "GIS_Notes": "Lands - http://landsnet.nps.gov/tractsnet/documents/WHHO/Metadata/whho_metadata.xml",
                "UNIT_NAME": "White House",
                "DATE_EDIT": "2010-05-28T00:00:00Z",
                "STATE": "DC",
                "REGION": "NC",
                "GNIS_ID": "2733430",
                "UNIT_TYPE": "Other Designation",
                "CREATED_BY": "Lands",
                "METADATA": "https://irma.nps.gov/DataStore/Reference/Profile/2165312",
                "PARKNAME": "President's Park (White House)",
                "CreationDate": "2022-01-06T10:44:35Z",
                "Creator": "WASO",
                "EditDate": "2022-01-06T10:44:35Z",
                "Editor": "WASO",
                "GlobalID": "c1455489-c4ea-40e8-b063-187c68391fac",
                "Shape__Area": 122787.890625,
                "Shape__Length": 1366.0892805429
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [-77.037852226846397, 38.8963431043125],
                        [-77.037852298711599, 38.8964779997699],
                        [-77.037853394656295, 38.8985426714681],
                        [-77.035259846141599, 38.898543483148799],
                        [-77.035258759180095, 38.896343916717498]
                    ]
                ]
            }
        }
    ]
}
</code>```

答:
There was 2 problems:

in the SELECT, if forgot to add ST_GeomFromGeoJson()

in the CROSS JOIN json_table(). I had the wrong data type for the "geometry: {}" json object. Instead of geometry geometry PATH '$.geometry', the correct data type is geometry json PATH '$.geometry'.

Full correct query below:

```<code>SELECT
    X.UNIT_NAME,
    X.UNIT_CODE,
    ST_GEOMFROMGEOJSON(X.GEOMETRY)
FROM
    NPS
CROSS JOIN json_table(
        doc,
        '$.features[*]' COLUMNS(
            UNIT_NAME VARCHAR(50) PATH '$.properties.UNIT_NAME',
            UNIT_CODE VARCHAR(50) PATH '$.properties.UNIT_CODE',
            GEOMETRY JSON PATH '$.geometry'
        )
    ) X
</code>```

Body:
I want to get all the data from a geoJSON to insert it then in a table with a GEOMETRY type.

The file can be downloaded on opendata.arcgis.com.

Everything is ok except the geometry data returned is NULL from the following query.

SELECT
    x.UNIT_NAME,
    x.UNIT_CODE,
    x.geometry
FROM
    NPS
CROSS JOIN json_table(
    doc,
    '$.features[*]' columns (
        UNIT_NAME varchar(50) PATH '$.properties.UNIT_NAME',
        UNIT_CODE varchar(50) PATH '$.properties.UNIT_CODE',
        geometry geometry PATH '$.geometry'
    )
) x

MySQL Result

UNIT_NAME|UNIT_CODE|geometry
Appalachian National Scenic Trail|APPA|NULL
White House|WHHO|NULL

An abstract of the file is here:

{
    "type": "FeatureCollection",
    "name": "NPS_-_Land_Resources_Division_Boundary_and_Tract_Data_Service",
    "crs": {
        "type": "name",
        "properties": {
            "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
        }
    },
    "features": [{
            "type": "Feature",
            "properties": {
                "OBJECTID": 1,
                "UNIT_CODE": "APPA",
                "GIS_Notes": "Lands - http://landsnet.nps.gov/tractsnet/documents/APPA/Metadata/appa_metadata.xml",
                "UNIT_NAME": "Appalachian National Scenic Trail",
                "DATE_EDIT": "2021-12-07T00:00:00Z",
                "STATE": "ME",
                "REGION": "NE",
                "GNIS_ID": "2766084",
                "UNIT_TYPE": "National Scenic Trail",
                "CREATED_BY": "Lands",
                "METADATA": "https://irma.nps.gov/DataStore/Reference/Profile/2259619",
                "PARKNAME": "Appalachian",
                "CreationDate": "2022-01-06T10:43:45Z",
                "Creator": "WASO",
                "EditDate": "2022-01-06T10:43:45Z",
                "Editor": "WASO",
                "GlobalID": "3923bec4-1652-41ca-a444-84fead65aba5",
                "Shape__Area": 1483097401.5976601,
                "Shape__Length": 5738045.6635156097
            },
            "geometry": {
                "type": "MultiPolygon",
                "coordinates": [
                    [
                        [
                            [-84.2329423255553, 34.623125245778901],
                            [-69.029418383436607, 45.847784381666997],
                            [-69.029490112115397, 45.849869184805797],
                            [-69.029642890392395, 45.854309758604899]
                        ]
                    ]
                ]
            }
        },
        {
            "type": "Feature",
            "properties": {
                "OBJECTID": 2,
                "UNIT_CODE": "WHHO",
                "GIS_Notes": "Lands - http://landsnet.nps.gov/tractsnet/documents/WHHO/Metadata/whho_metadata.xml",
                "UNIT_NAME": "White House",
                "DATE_EDIT": "2010-05-28T00:00:00Z",
                "STATE": "DC",
                "REGION": "NC",
                "GNIS_ID": "2733430",
                "UNIT_TYPE": "Other Designation",
                "CREATED_BY": "Lands",
                "METADATA": "https://irma.nps.gov/DataStore/Reference/Profile/2165312",
                "PARKNAME": "President's Park (White House)",
                "CreationDate": "2022-01-06T10:44:35Z",
                "Creator": "WASO",
                "EditDate": "2022-01-06T10:44:35Z",
                "Editor": "WASO",
                "GlobalID": "c1455489-c4ea-40e8-b063-187c68391fac",
                "Shape__Area": 122787.890625,
                "Shape__Length": 1366.0892805429
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [-77.037852226846397, 38.8963431043125],
                        [-77.037852298711599, 38.8964779997699],
                        [-77.037853394656295, 38.8985426714681],
                        [-77.035259846141599, 38.898543483148799],
                        [-77.035258759180095, 38.896343916717498]
                    ]
                ]
            }
        }
    ]
}

Body:
There was 2 problems:

in the SELECT, if forgot to add ST_GeomFromGeoJson()

in the CROSS JOIN json_table(). I had the wrong data type for the "geometry: {}" json object. Instead of geometry geometry PATH '$.geometry', the correct data type is geometry json PATH '$.geometry'.

Full correct query below:

SELECT
    X.UNIT_NAME,
    X.UNIT_CODE,
    ST_GEOMFROMGEOJSON(X.GEOMETRY)
FROM
    NPS
CROSS JOIN json_table(
        doc,
        '$.features[*]' COLUMNS(
            UNIT_NAME VARCHAR(50) PATH '$.properties.UNIT_NAME',
            UNIT_CODE VARCHAR(50) PATH '$.properties.UNIT_CODE',
            GEOMETRY JSON PATH '$.geometry'
        )
    ) X


问:
Laravel 7.x - How to remove 'public' from URL?
Stuck with this for a long time. I found similar questions but none of the answers are working for me!
.htaccess in root folder looks like this:</p>

```<code>RewriteEngine On
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,QSA]
</code>```

答:
below solution worked for me.

Create .htaccess file in root directory and place code something like below.
copy server.php file and paste it in root directory with named as index.php .

put below code in .htacess created file in root directory .

        Options -MultiViews

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
</code>```

Body:
Stuck with this for a long time. I found similar questions but none of the answers are working for me!
.htaccess in root folder looks like this:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,QSA]

Body:
below solution worked for me.

Create .htaccess file in root directory and place code something like below.
copy server.php file and paste it in root directory with named as index.php .

put below code in .htacess created file in root directory .

        Options -MultiViews

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php


问:
Use xmlstarlet in bash script to link xml nodes and extract elements
I am fairly familiar with XML but I've never had to delve into the complexities, and I'm a novice with XSL, XPATH, and with XMLSTARLET. I need a shell script that will extract a simple list from XML files which follow this kind of format..

<tv>
  <channel id="ffd49fe9acd778774b4933e10b6afb75">
    <display-name>ITV</display-name>
  </channel>
  <channel id="398fe9bc5ee3b47556d06f9b9cb95562">
    <display-name>BBC One</display-name>
  </channel>
  <channel id="3932fa4d11310596e0c3eba7dc8caf4c">
    <display-name>Channel 4</display-name>
  </channel>
  <programme channel="398fe9bc5ee3b47556d06f9b9cb95562">
    <title>Pointless</title>
  </programme>
  <programme channel="ffd49fe9acd778774b4933e10b6afb75">
    <title>The Chase</title>
  </programme>
  <programme channel="398fe9bc5ee3b47556d06f9b9cb95562">
    <title>BBC News</title>
  </programme>
  <programme channel="3932fa4d11310596e0c3eba7dc8caf4c">
    <title>Naked Attraction</title>
  </programme>
</tv>
```
<p>I picked up xmlstarlet (I'm using Cygwin) and I'm easily able to produce a list of channels or a list of programmes, but linking them together is beyond me although I've done a LOT of Googling.</p>
```#List of channels
xmlstarlet sel -t -m /tv/channel -v display-name -n

#List of Programmes
xmlstarlet sel -t -m /tv/programme -v title -n

#Filter a particular channel
sel -t -m "tv" -v 'channel[@id="398fe9bc5ee3b47556d06f9b9cb95562"]/display-name'  -n
```
<p>It would seem to me a simple thing to replace the square brackets in the last statement with something like [@id=programme/@channel] but it seems xpath doesn't work like that. I'm looking for results like this..</p>
```Pointless, BBC One
The Chase, ITV
BBC News, BBC One
Naked Attraction, Channel 4
```

Can someone point me in the right direction please?

答:
One way to circumvent the context would be to store the matching channel in a variable:

xmlstarlet sel -t -m '/tv/programme' --var ch='@channel' -v 'title' \
  -v '", "' -v '/tv/channel[@id=$ch]/display-name' -n
```
```Pointless, BBC One
The Chase, ITV
BBC News, BBC One
Naked Attraction, Channel 4
```

Body:
I am fairly familiar with XML but I've never had to delve into the complexities, and I'm a novice with XSL, XPATH, and with XMLSTARLET. I need a shell script that will extract a simple list from XML files which follow this kind of format..

<tv>
  <channel id="ffd49fe9acd778774b4933e10b6afb75">
    <display-name>ITV</display-name>
  </channel>
  <channel id="398fe9bc5ee3b47556d06f9b9cb95562">
    <display-name>BBC One</display-name>
  </channel>
  <channel id="3932fa4d11310596e0c3eba7dc8caf4c">
    <display-name>Channel 4</display-name>
  </channel>
  <programme channel="398fe9bc5ee3b47556d06f9b9cb95562">
    <title>Pointless</title>
  </programme>
  <programme channel="ffd49fe9acd778774b4933e10b6afb75">
    <title>The Chase</title>
  </programme>
  <programme channel="398fe9bc5ee3b47556d06f9b9cb95562">
    <title>BBC News</title>
  </programme>
  <programme channel="3932fa4d11310596e0c3eba7dc8caf4c">
    <title>Naked Attraction</title>
  </programme>
</tv>

I picked up xmlstarlet (I'm using Cygwin) and I'm easily able to produce a list of channels or a list of programmes, but linking them together is beyond me although I've done a LOT of Googling.

#List of channels
xmlstarlet sel -t -m /tv/channel -v display-name -n

#List of Programmes
xmlstarlet sel -t -m /tv/programme -v title -n

#Filter a particular channel
sel -t -m "tv" -v 'channel[@id="398fe9bc5ee3b47556d06f9b9cb95562"]/display-name'  -n

It would seem to me a simple thing to replace the square brackets in the last statement with something like [@id=programme/@channel] but it seems xpath doesn't work like that. I'm looking for results like this..

Pointless, BBC One
The Chase, ITV
BBC News, BBC One
Naked Attraction, Channel 4

Can someone point me in the right direction please?

Body:
One way to circumvent the context would be to store the matching channel in a variable:

xmlstarlet sel -t -m '/tv/programme' --var ch='@channel' -v 'title' \
  -v '", "' -v '/tv/channel[@id=$ch]/display-name' -n

Pointless, BBC One
The Chase, ITV
BBC News, BBC One
Naked Attraction, Channel 4


问:
Getting the second occurrence from charindex function in sql server
I need to get the second occurrence of the space for below text. It should be the space after the 56, but I'm getting 15th position before the 56 as the first one.</p>

```<code>select charindex(' ', 'Posted/edited: 56 days ago', 2)
</code>```

答:
Setting a start location is an excellent idea. However I would use the searchable character first occurrence +1 as a start location as situation may vary. So the solution would be:

Select charindex(' ','Posted/edited: 56 days ago',(charindex(' ', 'Posted/edited: 56 days ago') +1))

The output is ofc 18

Body:
I need to get the second occurrence of the space for below text. It should be the space after the 56, but I'm getting 15th position before the 56 as the first one.

select charindex(' ', 'Posted/edited: 56 days ago', 2)


问:
R to Python for loop translation
I want to translate the following R code:

k =5
Ret = as.data.frame(sapply(1:k, function(i) rnorm(k) ) )

deltas=NULL
for (i in 1:k) {
  y = Ret[,i]
  mvalue = mean(y)
  minvec = NULL
  for (j in 1:length(y))
  {
    minvechelp = min(0,(y[j]-mvalue))
    minvec[j] = minvechelp
  }
  delta=sqrt(sum(minvec^2)/length(y))
  deltas = cbind(deltas,delta)
}
deltas
```
<p>Which implements a collide mean of a data frame and then takes the length of the data frame to calculate a parameter delta which contains the min calculation but I think the df has been converted to vector.</p>
<p>In Python my effort is:</p>
<pre class="lang-py prettyprint-override"><code>k= 5
A = pd.DataFrame(
      [np.random.randn(k) for i in range(k)]
   )
A.size
deltas = []
for i in range(0,k):
    y = Ret.iloc[:,i]
    mvalue = np.mean(y)
    minvec = []
    for j in range(0,y.size):
        minvechelp = min(0,(y[j]-mvalue))
        minvec[j] = minvechelp

    delta=np.sqrt(sum(minvec**2)/y.size())
    deltas = np.hstack((deltas,delta))

deltas
</code>```

but I receive an error

```<code>KeyError: 0
</code>```

Where is my mistake and how can I fix it? Any help?

答:
After Oliver's help in the comments I find out that the answer is :</p>
```<code>mvalue = Ret.mean(axis=0);mvalue
Res = Ret - mvalue;Res
Res[Res>=0] = 0;Res
Res2 = Res**2
cs = Res2.sum(axis=0);cs
delta = np.sqrt(cs/Ret.shape[0])
delta
</code>```

Title: R to Python for loop translation

Body:
I want to translate the following R code:

k =5
Ret = as.data.frame(sapply(1:k, function(i) rnorm(k) ) )

deltas=NULL
for (i in 1:k) {
  y = Ret[,i]
  mvalue = mean(y)
  minvec = NULL
  for (j in 1:length(y))
  {
    minvechelp = min(0,(y[j]-mvalue))
    minvec[j] = minvechelp
  }
  delta=sqrt(sum(minvec^2)/length(y))
  deltas = cbind(deltas,delta)
}
deltas

Which implements a collide mean of a data frame and then takes the length of the data frame to calculate a parameter delta which contains the min calculation but I think the df has been converted to vector.

In Python my effort is:

k= 5
A = pd.DataFrame(
      [np.random.randn(k) for i in range(k)]
   )
A.size
deltas = []
for i in range(0,k):
    y = Ret.iloc[:,i]
    mvalue = np.mean(y)
    minvec = []
    for j in range(0,y.size):
        minvechelp = min(0,(y[j]-mvalue))
        minvec[j] = minvechelp

    delta=np.sqrt(sum(minvec**2)/y.size())
    deltas = np.hstack((deltas,delta))

deltas

but I receive an error

KeyError: 0

Where is my mistake and how can I fix it? Any help?

Body:
After Oliver's help in the comments I find out that the answer is :

mvalue = Ret.mean(axis=0);mvalue
Res = Ret - mvalue;Res
Res[Res>=0] = 0;Res
Res2 = Res**2
cs = Res2.sum(axis=0);cs
delta = np.sqrt(cs/Ret.shape[0])
delta


问:
Webpack external module in microfrontend/ multirepos angular gives an error on build
I have created a Angular project to call the microfrontend from other running angular project. I have import the module in my app by using webpack.config.js.
It is working well locally but failed on production build.

When I run ng build it throws exception:

```<code>An unhandled exception occurred: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
See "C:\Users\baps\AppData\Local\Temp\ng-8vJVWd\angular-errors.log" for further details.

[error] HookWebpackError: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
    at makeWebpackError (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\webpack\lib\HookWebpackError.js:48:9)
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\webpack\lib\Compilation.js:3057:12
    at eval (eval at create (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:98:1)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
-- inner error --
Error: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
    at failureErrorWithLog (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1557:15)
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1346:29
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:637:9
    at handleIncomingPacket (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:734:9)
    at Socket.readFromStdout (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:604:7)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:309:12)
    at readableAddChunk (_stream_readable.js:284:9)
    at Socket.Readable.push (_stream_readable.js:223:10)
    at Pipe.onStreamRead (internal/stream_base_commons.js:188:23)
</code>```

答:
I have just added

```<code>not ios_saf 15.2-15.3
not safari 15.2-15.3
</code>```

To the bottom of the .browserslist file after the not IE 11.
This is the only change that I had to do to make it work (build).

The resulting file is as follows:

```<code># This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries

# For the full list of supported browsers by the Angular framework, please see:
# https://angular.io/guide/browser-support

# You can see what browsers were selected by your queries by running:
#   npx browserslist

last 1 Chrome version
last 1 Firefox version
last 2 Edge major versions
last 2 Safari major versions
last 2 iOS major versions
Firefox ESR
not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line.
not ios_saf 15.2-15.3
not safari 15.2-15.3
</code>```

Hope this will be fixed in the next Angular version

Body:
I have created a Angular project to call the microfrontend from other running angular project. I have import the module in my app by using webpack.config.js.
It is working well locally but failed on production build.

When I run ng build it throws exception:

An unhandled exception occurred: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
See "C:\Users\baps\AppData\Local\Temp\ng-8vJVWd\angular-errors.log" for further details.

[error] HookWebpackError: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
    at makeWebpackError (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\webpack\lib\HookWebpackError.js:48:9)
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\webpack\lib\Compilation.js:3057:12
    at eval (eval at create (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:98:1)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
-- inner error --
Error: Transform failed with 1 error:
error: Invalid version: "15.2-15.3"
    at failureErrorWithLog (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1557:15)
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1346:29
    at D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:637:9
    at handleIncomingPacket (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:734:9)
    at Socket.readFromStdout (D:\sites\ccgsystems\Repos\UI-Menu-Template\menus\node_modules\ngx-build-plus\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:604:7)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:309:12)
    at readableAddChunk (_stream_readable.js:284:9)
    at Socket.Readable.push (_stream_readable.js:223:10)
    at Pipe.onStreamRead (internal/stream_base_commons.js:188:23)

Body:
I have just added

not ios_saf 15.2-15.3
not safari 15.2-15.3

To the bottom of the .browserslist file after the not IE 11.
This is the only change that I had to do to make it work (build).

The resulting file is as follows:

# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries

# For the full list of supported browsers by the Angular framework, please see:
# https://angular.io/guide/browser-support

# You can see what browsers were selected by your queries by running:
#   npx browserslist

last 1 Chrome version
last 1 Firefox version
last 2 Edge major versions
last 2 Safari major versions
last 2 iOS major versions
Firefox ESR
not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line.
not ios_saf 15.2-15.3
not safari 15.2-15.3

Hope this will be fixed in the next Angular version


问:
Global Object in singleton
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

```<code>class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};
</code>```

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?

答:
In the Singleton pattern why is that we have to use a static object
  and not a global object?

Static object is private member of your class and nobody has access to it except Singleton class. This is basic encapsulation principle in C++ and other OOP languages.

Title: Global Object in singleton

Body:
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?


问:
Trying to run more than one function onEdit - Google Sheets
I wrote a script that displays a browser message box whenever the word "Lost" is input on a particular column (I:I) on the sheet, and I also wrote another that inputs the date and time on (A:A) when cell (B:B) is actualised. But I'm struggling to merge them both since the onEdit function allows only a script.

My script is as it follows:

function onEdit(e) {
  myfunction1();
  myfunction2(event);
}

function myfunction1() {
  var ActiveSheet= SpreadsheetApp.getActiveSheet();
  var capture = ActiveSheet.getActiveCell();
  if(ActiveSheet.getName() == 'Template' && (capture.getColumn() == 2))  {
    var add = capture.offset(0, -1);
    var data = new Date();
    data = Utilities.formatDate(data, "GMT-03:00", "dd/MM/yyyy HH:mm:ss");
    add.setValue(data);
  }
}

function myfunction2(event) {
  var sheet = event.source.getActiveSheet().getName()
  var editedCell = event.range.getSheet().getActiveCell();
  if(sheet=="Template"){
     if(editedCell.getColumn()==9 && event.value=="Lost"){
        Browser.msgBox(' ⚠ Make sure you enter the reason for loss.');

        }
  }

};```

However, I keep getting error messages and can't find what I missed. I've also tried to separate all the variables above and open new functions, but no success.

The last execution log error I got was: "9:22:57 AM   Notice  Execution started
9:22:57 AM  Error

ReferenceError: event is not defined
onEdit  @ Untitled.gs:3"

答:
Try</p>
```<code>function onEdit(event) {
  myfunction1();
  myfunction2(event);
}
</code>```

Body:
I wrote a script that displays a browser message box whenever the word "Lost" is input on a particular column (I:I) on the sheet, and I also wrote another that inputs the date and time on (A:A) when cell (B:B) is actualised. But I'm struggling to merge them both since the onEdit function allows only a script.

My script is as it follows:

function onEdit(e) {
  myfunction1();
  myfunction2(event);
}

function myfunction1() {
  var ActiveSheet= SpreadsheetApp.getActiveSheet();
  var capture = ActiveSheet.getActiveCell();
  if(ActiveSheet.getName() == 'Template' && (capture.getColumn() == 2))  {
    var add = capture.offset(0, -1);
    var data = new Date();
    data = Utilities.formatDate(data, "GMT-03:00", "dd/MM/yyyy HH:mm:ss");
    add.setValue(data);
  }
}

function myfunction2(event) {
  var sheet = event.source.getActiveSheet().getName()
  var editedCell = event.range.getSheet().getActiveCell();
  if(sheet=="Template"){
     if(editedCell.getColumn()==9 && event.value=="Lost"){
        Browser.msgBox(' ⚠ Make sure you enter the reason for loss.');

        }
  }

};

However, I keep getting error messages and can't find what I missed. I've also tried to separate all the variables above and open new functions, but no success.

The last execution log error I got was: "9:22:57 AM   Notice  Execution started
9:22:57 AM  Error

ReferenceError: event is not defined
onEdit  @ Untitled.gs:3"

Body:
Try

function onEdit(event) {
  myfunction1();
  myfunction2(event);
}


问:
How to set a One To Many relationship in ONE model between different types
I have a table named categories and here is it's structure:

```<code>id              bigint(20)      AUTO_INCREMENT
name            varchar(255)
description     varchar(255)
short_name      varchar(255)
picture         varchar(255)
parent_category int(11)
category_type   tinyint(4)
</code>```

So each category has a category_type which can be one of these values:

1: Main Category

2: Superior Category

3: Secondary Category

4: Secondary Sub Category

Now I wanted to set a One To Many relationship between these categories.

For example: a main category has many superior categories and a superior category is related to one main category.

And this will apply to the rest of them as well.

But because I have only one Model which is Category, I don't know how to apply this relationship, so if you know, plz help me out...

Model Category.php:

```<code>class Category extends Model
{
    use HasFactory;
    protected $fillable = ['name','short_name','description','picture','category_type','parent_category'];

}
</code>```

答:
As I know, Laravel relationships work between models and not within one model. I would recommend you to use separate models (and separate tables).

If all other categories are on the same level and they all belong to one main category, you can make one model for the main category and all others can have one model.

Body:
I have a table named categories and here is it's structure:

id              bigint(20)      AUTO_INCREMENT
name            varchar(255)
description     varchar(255)
short_name      varchar(255)
picture         varchar(255)
parent_category int(11)
category_type   tinyint(4)

So each category has a category_type which can be one of these values:

1: Main Category

2: Superior Category

3: Secondary Category

4: Secondary Sub Category

Now I wanted to set a One To Many relationship between these categories.

For example: a main category has many superior categories and a superior category is related to one main category.

And this will apply to the rest of them as well.

But because I have only one Model which is Category, I don't know how to apply this relationship, so if you know, plz help me out...

Model Category.php:

class Category extends Model
{
    use HasFactory;
    protected $fillable = ['name','short_name','description','picture','category_type','parent_category'];

}


问:
Azure Data Factory schema mapping not working with SQL sink
I have a simple pipeline that loads data from a csv file to an Azure SQL db.

I have added a data flow where I have ensured all schema matches the SQL table. I have a specific field which contains numbers with leading zeros. The data type in the source - projection is set to string. The field is mapped to the SQL sink showing as string data-type. The field in SQL has nvarchar(50) data-type.

Once the pipeline is run, all the leading zeros are lost and the field appears to be treated as decimal:

```<code>Original data: 0012345
Inserted data: 12345.0
</code>```

The CSV data shown in the data preview is showing correctly, however for some reason it loses its formatting during insert.

Any ideas how I can get it to insert correctly?

答:
I had repro’d in my lab and was able to load as expected. Please see the below repro details.

Source file (CSV file):

Sink table (SQL table):

ADF:

Connect the data flow source to the CSV source file. As my file is in text format, all the source columns in the projection are in a string.

Source data preview:

Connect sink to Azure SQL database to load the data to the destination table.

Data in Azure SQL database table.

Note: You can all add derived columns before sink to convert the value to string as the sink data type is a string.

Body:
I have a simple pipeline that loads data from a csv file to an Azure SQL db.

I have added a data flow where I have ensured all schema matches the SQL table. I have a specific field which contains numbers with leading zeros. The data type in the source - projection is set to string. The field is mapped to the SQL sink showing as string data-type. The field in SQL has nvarchar(50) data-type.

Once the pipeline is run, all the leading zeros are lost and the field appears to be treated as decimal:

Original data: 0012345
Inserted data: 12345.0

The CSV data shown in the data preview is showing correctly, however for some reason it loses its formatting during insert.

Any ideas how I can get it to insert correctly?


问:
Change background-image with jQuery - doesn´t work
```<code>$('#areaView').css('background-image', 'url(/areaNr1.jpg)');
</code>```

I don´t know what to say, I have no idea why this code doesn´t work. The old background-image disappears, but the new one never appears.

I have checked and areaNr1.jpg exists in the same folder as the code. Allthough the function isn´t in the same folder as #areaView, but that should not matter, right?

Any ideas why this doesn´t work?

Thanks for your help!

答:
You need to quote the argument to url():</p>

```<code>$('#areaView').css('background-image', 'url("/areaNr1.jpg")');
</code>```

Body:
$('#areaView').css('background-image', 'url(/areaNr1.jpg)');

I don´t know what to say, I have no idea why this code doesn´t work. The old background-image disappears, but the new one never appears.

I have checked and areaNr1.jpg exists in the same folder as the code. Allthough the function isn´t in the same folder as #areaView, but that should not matter, right?

Any ideas why this doesn´t work?

Thanks for your help!

Body:
You need to quote the argument to url():

$('#areaView').css('background-image', 'url("/areaNr1.jpg")');


问:
How can I change the icons of cpp files in macOS?
Clion is a super great C++ IDE which is cross-platform, but when I install it on my Mac, something terrible happend. Look at this:

These icon looks terrible! How can I fix them? Maybe change to the default icon?
I works on macOS Catalina 10.15.7.
Thanks!

答:
On macOS the icon of each file type is determined by the application that opens it by default. You can't override this unless you actually modify the application.

Right click on CLion.app > Show package contents > Contents

There's a file Info.plist. If we open it and search for CFBundleTypeExtensions we can see the following (CLion 2021.3.2 on macOS Monterey) :

<key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeExtensions</key>
            <array>
                <string>c</string>
            </array>
            <key>CFBundleTypeIconFile</key>
            <string>clion.icns</string>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
        </dict>
        <dict>
            <key>CFBundleTypeExtensions</key>
            <array>
                <string>h</string>
            </array>
            <key>CFBundleTypeIconFile</key>
            <string>clion.icns</string>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
        </dict>
        ...
```

So for file extensions .c, .h, etc the icon used is clion.icns which can be found in the Resources folder. You can copy custom icns files there and modify those keys in Info.plist to force Finder to use your own custom icons.

Body:
On macOS the icon of each file type is determined by the application that opens it by default. You can't override this unless you actually modify the application.

Right click on CLion.app > Show package contents > Contents

There's a file Info.plist. If we open it and search for CFBundleTypeExtensions we can see the following (CLion 2021.3.2 on macOS Monterey) :

<key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeExtensions</key>
            <array>
                <string>c</string>
            </array>
            <key>CFBundleTypeIconFile</key>
            <string>clion.icns</string>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
        </dict>
        <dict>
            <key>CFBundleTypeExtensions</key>
            <array>
                <string>h</string>
            </array>
            <key>CFBundleTypeIconFile</key>
            <string>clion.icns</string>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
        </dict>
        ...

So for file extensions .c, .h, etc the icon used is clion.icns which can be found in the Resources folder. You can copy custom icns files there and modify those keys in Info.plist to force Finder to use your own custom icons.


问:
Why do I get different values when I extract data from netCDF files using CDO and ArcGIS for a same grid point?
details of the raw data (Mnth.nc)

```<code>netcdf Mnth {
dimensions:
        time = UNLIMITED ; // (480 currently)
        bnds = 2 ;
        longitude = 25 ;
        latitude = 33 ;
variables:
        double time(time) ;
                time:standard_name = "time" ;
                time:long_name = "verification time generated by wgrib2 function verftime()" ;
                time:bounds = "time_bnds" ;
                time:units = "seconds since 1970-01-01 00:00:00.0 0:00" ;
                time:calendar = "standard" ;
                time:axis = "T" ;
        double time_bnds(time, bnds) ;
        double longitude(longitude) ;
                longitude:standard_name = "longitude" ;
                longitude:long_name = "longitude" ;
                longitude:units = "degrees_east" ;
                longitude:axis = "X" ;
        double latitude(latitude) ;
                latitude:standard_name = "latitude" ;
                latitude:long_name = "latitude" ;
                latitude:units = "degrees_north" ;
                latitude:axis = "Y" ;
        float APCP_sfc(time, latitude, longitude) ;
                APCP_sfc:long_name = "Total Precipitation" ;
                APCP_sfc:units = "kg/m^2" ;
                APCP_sfc:_FillValue = 9.999e+20f ;
                APCP_sfc:missing_value = 9.999e+20f ;
                APCP_sfc:cell_methods = "time: sum" ;
                APCP_sfc:short_name = "APCP_surface" ;
                APCP_sfc:level = "surface" ;
}
</code>```

Detail information of the raw data (Mnth.nc)

```<code>File format : NetCDF4 classic
    -1 : Institut Source   T Steptype Levels Num    Points Num Dtype : Parameter ID
     1 : unknown  unknown  v instant       1   1       825   1  F32  : -1
   Grid coordinates :
     1 : lonlat                   : points=825 (25x33)
                        longitude : 87 to 89.88 by 0.12 degrees_east
                         latitude : 25.08 to 28.92 by 0.12 degrees_north
   Vertical coordinates :
     1 : surface                  : levels=1
   Time coordinate :  480 steps
     RefTime =  1970-01-01 00:00:00  Units = seconds  Calendar = standard  Bounds = true
  YYYY-MM-DD hh:mm:ss  YYYY-MM-DD hh:mm:ss  YYYY-MM-DD hh:mm:ss  YYYY-MM-DD hh:mm:ss
  1980-01-16 12:30:00  1980-02-15 12:30:00  1980-03-16 12:30:00  1980-04-16 00:30:00
  1980-05-16 12:30:00  1980-06-16 00:30:00  1980-07-16 12:30:00  1980-08-16 12:30:00
  1980-09-16 00:30:00  1980-10-16 12:30:00  1980-11-16 00:30:00  1980-12-16 12:30:00
  1981-01-16 12:30:00  1981-02-15 00:30:00  1981-03-16 12:30:00  1981-04-16 00:30:00
  1981-05-16 12:30:00  1981-06-16 00:30:00  1981-07-16 12:30:00  1981-08-16 12:30:00
  1981-09-16 00:30:00  1981-10-16 12:30:00  1981-11-16 00:30:00  1981-12-16 12:30:00
  1982-01-16 12:30:00  1982-02-15 00:30:00  1982-03-16 12:30:00  1982-04-16 00:30:00
  1982-05-16 12:30:00  1982-06-16 00:30:00  1982-07-16 12:30:00  1982-08-16 12:30:00
  1982-09-16 00:30:00  1982-10-16 12:30:00  1982-11-16 00:30:00  1982-12-16 12:30:00
  1983-01-16 12:30:00  1983-02-15 00:30:00  1983-03-16 12:30:00  1983-04-16 00:30:00
  1983-05-16 12:30:00  1983-06-16 00:30:00  1983-07-16 12:30:00  1983-08-16 12:30:00
  1983-09-16 00:30:00  1983-10-16 12:30:00  1983-11-16 00:30:00  1983-12-16 12:30:00
  1984-01-16 12:30:00  1984-02-15 12:30:00  1984-03-16 12:30:00  1984-04-16 00:30:00
  1984-05-16 12:30:00  1984-06-16 00:30:00  1984-07-16 12:30:00  1984-08-16 12:30:00
  1984-09-16 00:30:00  1984-10-16 12:30:00  1984-11-16 00:30:00  1984-12-16 12:30:00
   ................................................................................
   ............................
  2016-01-16 12:30:00  2016-02-15 12:30:00  2016-03-16 12:30:00  2016-04-16 00:30:00
  2016-05-16 12:30:00  2016-06-16 00:30:00  2016-07-16 12:30:00  2016-08-16 12:30:00
  2016-09-16 00:30:00  2016-10-16 12:30:00  2016-11-16 00:30:00  2016-12-16 12:30:00
  2017-01-16 12:30:00  2017-02-15 00:30:00  2017-03-16 12:30:00  2017-04-16 00:30:00
  2017-05-16 12:30:00  2017-06-16 00:30:00  2017-07-16 12:30:00  2017-08-16 12:30:00
  2017-09-16 00:30:00  2017-10-16 12:30:00  2017-11-16 00:30:00  2017-12-16 12:30:00
  2018-01-16 12:30:00  2018-02-15 00:30:00  2018-03-16 12:30:00  2018-04-16 00:30:00
  2018-05-16 12:30:00  2018-06-16 00:30:00  2018-07-16 12:30:00  2018-08-16 12:30:00
  2018-09-16 00:30:00  2018-10-16 12:30:00  2018-11-16 00:30:00  2018-12-16 12:30:00
  2019-01-16 12:30:00  2019-02-15 00:30:00  2019-03-16 12:30:00  2019-04-16 00:30:00
  2019-05-16 12:30:00  2019-06-16 00:30:00  2019-07-16 12:30:00  2019-08-16 12:30:00
  2019-09-16 00:30:00  2019-10-16 12:30:00  2019-11-16 00:30:00  2019-12-16 12:30:00
  2020-01-16 12:30:00  2020-02-15 12:30:00  2020-03-16 12:30:00  2020-04-16 00:30:00
  2020-05-16 12:30:00  2020-06-16 00:30:00  2020-07-16 12:30:00  2020-08-16 12:30:00
  2020-09-16 00:30:00  2020-10-16 12:30:00  2020-11-16 00:30:00  2020-12-16 12:30:00
cdo    sinfo: Processed 1 variable over 480 timesteps [0.50s 30MB].
</code>```

I extracted monthly rainfall values from the Mnth.nc file for a location (lon: 88.44; lat: 27.12)using the following command

```<code>cdo remapnn,lon=88.44-lat=27.12 Mnth.nc Mnth1.nc
cdo outputtab,year, month, value Mnth1.nc > Mnth.csv
</code>```

The output is as follows ()

```<code>Year    month   Value
1980    1   31.74219
1980    2   54.60938
1980    3   66.94531
1980    4   149.4062
1980    5   580.7227
1980    6   690.1328
1980    7   1146.305
1980    8   535.8164
1980    9   486.4688
1980    10  119.5391
1980    11  82.10547
1980    12  13.95703
</code>```

Then I extracted the rainfall values from the same data (Mnth.nc) for the same location (lon: 88.44; lat: 27.12) using the features of the multidimensional toolbox provided in ArcGIS. The result is as follows-

```<code>year    month   Value
1980    1   38.8125
1980    2   58.6542969
1980    3   71.7382813
1980    4   148.6367188
1980    5   564.7070313
1980    6   653.0390625
1980    7   1026.832031
1980    8   501.3164063
1980    9   458.5429688
1980    10  113.078125
1980    11  74.0976563
1980    12  24.2265625
</code>```

Why I'm getting different results in two different software for the same location and for the same variable? Any help will highly be appreciated.

Thanks in advance.

答:
I think I ended up in the same issues. I used CDO to extract a point and also used ArcGIS for cross checking. I found out that the values were different.
Just to be sure, I recorded the location extent of one particular cell and tried extracting values for different locations within the cell boundary extent. CDO seemed to have been giving the same results as expected because it uses nearest neighbour resampling method.
Then I tried the same with ArcGIS. Interestingly, in my case, I found out that ArcGIS also gave me same results sometimes within the same cell boundary extent and sometimes different. I checked the values by also using 'Panoply' and I realised that CDO gave accurate results, while ArcGIS was sometimes giving offset results,i.e., it was giving the values of the nearby cells. This was confirmed by cross-checking with Panoply. As @Robert Wilson mentioned that ArcGIS must be using different resampling method, I figured out in the results section after using the tool 'Netcdf to table view' that it also uses Nearest neighbour method. This is not an answer to your question, but just something I found.</p>

Body:
details of the raw data (Mnth.nc)

netcdf Mnth {
dimensions:
        time = UNLIMITED ; // (480 currently)
        bnds = 2 ;
        longitude = 25 ;
        latitude = 33 ;
variables:
        double time(time) ;
                time:standard_name = "time" ;
                time:long_name = "verification time generated by wgrib2 function verftime()" ;
                time:bounds = "time_bnds" ;
                time:units = "seconds since 1970-01-01 00:00:00.0 0:00" ;
                time:calendar = "standard" ;
                time:axis = "T" ;
        double time_bnds(time, bnds) ;
        double longitude(longitude) ;
                longitude:standard_name = "longitude" ;
                longitude:long_name = "longitude" ;
                longitude:units = "degrees_east" ;
                longitude:axis = "X" ;
        double latitude(latitude) ;
                latitude:standard_name = "latitude" ;
                latitude:long_name = "latitude" ;
                latitude:units = "degrees_north" ;
                latitude:axis = "Y" ;
        float APCP_sfc(time, latitude, longitude) ;
                APCP_sfc:long_name = "Total Precipitation" ;
                APCP_sfc:units = "kg/m^2" ;
                APCP_sfc:_FillValue = 9.999e+20f ;
                APCP_sfc:missing_value = 9.999e+20f ;
                APCP_sfc:cell_methods = "time: sum" ;
                APCP_sfc:short_name = "APCP_surface" ;
                APCP_sfc:level = "surface" ;
}

Detail information of the raw data (Mnth.nc)

File format : NetCDF4 classic
    -1 : Institut Source   T Steptype Levels Num    Points Num Dtype : Parameter ID
     1 : unknown  unknown  v instant       1   1       825   1  F32  : -1
   Grid coordinates :
     1 : lonlat                   : points=825 (25x33)
                        longitude : 87 to 89.88 by 0.12 degrees_east
                         latitude : 25.08 to 28.92 by 0.12 degrees_north
   Vertical coordinates :
     1 : surface                  : levels=1
   Time coordinate :  480 steps
     RefTime =  1970-01-01 00:00:00  Units = seconds  Calendar = standard  Bounds = true
  YYYY-MM-DD hh:mm:ss  YYYY-MM-DD hh:mm:ss  YYYY-MM-DD hh:mm:ss  YYYY-MM-DD hh:mm:ss
  1980-01-16 12:30:00  1980-02-15 12:30:00  1980-03-16 12:30:00  1980-04-16 00:30:00
  1980-05-16 12:30:00  1980-06-16 00:30:00  1980-07-16 12:30:00  1980-08-16 12:30:00
  1980-09-16 00:30:00  1980-10-16 12:30:00  1980-11-16 00:30:00  1980-12-16 12:30:00
  1981-01-16 12:30:00  1981-02-15 00:30:00  1981-03-16 12:30:00  1981-04-16 00:30:00
  1981-05-16 12:30:00  1981-06-16 00:30:00  1981-07-16 12:30:00  1981-08-16 12:30:00
  1981-09-16 00:30:00  1981-10-16 12:30:00  1981-11-16 00:30:00  1981-12-16 12:30:00
  1982-01-16 12:30:00  1982-02-15 00:30:00  1982-03-16 12:30:00  1982-04-16 00:30:00
  1982-05-16 12:30:00  1982-06-16 00:30:00  1982-07-16 12:30:00  1982-08-16 12:30:00
  1982-09-16 00:30:00  1982-10-16 12:30:00  1982-11-16 00:30:00  1982-12-16 12:30:00
  1983-01-16 12:30:00  1983-02-15 00:30:00  1983-03-16 12:30:00  1983-04-16 00:30:00
  1983-05-16 12:30:00  1983-06-16 00:30:00  1983-07-16 12:30:00  1983-08-16 12:30:00
  1983-09-16 00:30:00  1983-10-16 12:30:00  1983-11-16 00:30:00  1983-12-16 12:30:00
  1984-01-16 12:30:00  1984-02-15 12:30:00  1984-03-16 12:30:00  1984-04-16 00:30:00
  1984-05-16 12:30:00  1984-06-16 00:30:00  1984-07-16 12:30:00  1984-08-16 12:30:00
  1984-09-16 00:30:00  1984-10-16 12:30:00  1984-11-16 00:30:00  1984-12-16 12:30:00
   ................................................................................
   ............................
  2016-01-16 12:30:00  2016-02-15 12:30:00  2016-03-16 12:30:00  2016-04-16 00:30:00
  2016-05-16 12:30:00  2016-06-16 00:30:00  2016-07-16 12:30:00  2016-08-16 12:30:00
  2016-09-16 00:30:00  2016-10-16 12:30:00  2016-11-16 00:30:00  2016-12-16 12:30:00
  2017-01-16 12:30:00  2017-02-15 00:30:00  2017-03-16 12:30:00  2017-04-16 00:30:00
  2017-05-16 12:30:00  2017-06-16 00:30:00  2017-07-16 12:30:00  2017-08-16 12:30:00
  2017-09-16 00:30:00  2017-10-16 12:30:00  2017-11-16 00:30:00  2017-12-16 12:30:00
  2018-01-16 12:30:00  2018-02-15 00:30:00  2018-03-16 12:30:00  2018-04-16 00:30:00
  2018-05-16 12:30:00  2018-06-16 00:30:00  2018-07-16 12:30:00  2018-08-16 12:30:00
  2018-09-16 00:30:00  2018-10-16 12:30:00  2018-11-16 00:30:00  2018-12-16 12:30:00
  2019-01-16 12:30:00  2019-02-15 00:30:00  2019-03-16 12:30:00  2019-04-16 00:30:00
  2019-05-16 12:30:00  2019-06-16 00:30:00  2019-07-16 12:30:00  2019-08-16 12:30:00
  2019-09-16 00:30:00  2019-10-16 12:30:00  2019-11-16 00:30:00  2019-12-16 12:30:00
  2020-01-16 12:30:00  2020-02-15 12:30:00  2020-03-16 12:30:00  2020-04-16 00:30:00
  2020-05-16 12:30:00  2020-06-16 00:30:00  2020-07-16 12:30:00  2020-08-16 12:30:00
  2020-09-16 00:30:00  2020-10-16 12:30:00  2020-11-16 00:30:00  2020-12-16 12:30:00
cdo    sinfo: Processed 1 variable over 480 timesteps [0.50s 30MB].

I extracted monthly rainfall values from the Mnth.nc file for a location (lon: 88.44; lat: 27.12)using the following command

cdo remapnn,lon=88.44-lat=27.12 Mnth.nc Mnth1.nc
cdo outputtab,year, month, value Mnth1.nc > Mnth.csv

The output is as follows ()

Year    month   Value
1980    1   31.74219
1980    2   54.60938
1980    3   66.94531
1980    4   149.4062
1980    5   580.7227
1980    6   690.1328
1980    7   1146.305
1980    8   535.8164
1980    9   486.4688
1980    10  119.5391
1980    11  82.10547
1980    12  13.95703

Then I extracted the rainfall values from the same data (Mnth.nc) for the same location (lon: 88.44; lat: 27.12) using the features of the multidimensional toolbox provided in ArcGIS. The result is as follows-

year    month   Value
1980    1   38.8125
1980    2   58.6542969
1980    3   71.7382813
1980    4   148.6367188
1980    5   564.7070313
1980    6   653.0390625
1980    7   1026.832031
1980    8   501.3164063
1980    9   458.5429688
1980    10  113.078125
1980    11  74.0976563
1980    12  24.2265625

Why I'm getting different results in two different software for the same location and for the same variable? Any help will highly be appreciated.

Thanks in advance.


问:
refactoring problem with one of my classes
i wrote a program and i named my class StatusListActivity which extend Activity  and is the launcher and main class. I tried refactoring it by  changing the name to something else and whenever i tried to run the application, it closes please do you have an idea of what the problem was.

答:
Try to change the name of the Activity class in your AndroidManifest.xml file

<activity android:name="activityNewName">

EDIT

Also if activity located in com.example.myproject.activities.MyActivity

and in manifest file <manifest package="com.example.myproject" ...>

than in manifest must be <activity android:name=".activities.MyActivity">

this also true for all other classes that must be in AndroidManifest.xml


问:
can not connect to private nexus registry
I'm using docker-desktop (version: Docker version 20.10.12, build e91ed57) on macOS

My problem: Can not connect and push image to the nexus registry container

Here is my steps & errors:

Pull & Start nexus container

docker volume create --name nexus-data

docker run -d -p 8081:8081 --name nexus -v nexus-data:/nexus-dasonatype/nexus3:3.37.3

Connect to the 0.0.0.0:8081

Then i connect to the 0.0.0.0:8081 and create a docker-hosted repository and in HTTP section i add the 8083 port.

then i create a user (ali) and assigned to it a password and a role

add insecure-registries to the docker engine

then according to this documentation i added this line to the docker engine:

```<code>"insecure-registries": ["0.0.0.0:8083"]
</code>```

restart the docker and container

try to login

then i tried to login via this command:

```<code>docker login 0.0.0.0:8083
</code>```

but it return an error:

```<code>Error response from daemon: Get "http://0.0.0.0:8083/v2/": dial tcp 0.0.0.0:8083: connect: connection refused
</code>```

Why i get this error?!

i tried many things to solve my problem including:

Open port 8083 on my machine

add the 0.0.0.0 to my host file

open port 8083 on my container too

but nothing works at all!

what should i do?!

答:
To access a port in the container from the host, it needs to be published. So the run command should be</p>
```<code>docker run -d -p 8081:8081 -p 8083:8083 --name nexus -v nexus-data:/nexus-dasonatype/nexus3:3.37.3
</code>```

Body:
I'm using docker-desktop (version: Docker version 20.10.12, build e91ed57) on macOS

My problem: Can not connect and push image to the nexus registry container

Here is my steps & errors:

Pull & Start nexus container

docker volume create --name nexus-data

docker run -d -p 8081:8081 --name nexus -v nexus-data:/nexus-dasonatype/nexus3:3.37.3

Connect to the 0.0.0.0:8081

Then i connect to the 0.0.0.0:8081 and create a docker-hosted repository and in HTTP section i add the 8083 port.

then i create a user (ali) and assigned to it a password and a role

add insecure-registries to the docker engine

then according to this documentation i added this line to the docker engine:

"insecure-registries": ["0.0.0.0:8083"]

restart the docker and container

try to login

then i tried to login via this command:

docker login 0.0.0.0:8083

but it return an error:

Error response from daemon: Get "http://0.0.0.0:8083/v2/": dial tcp 0.0.0.0:8083: connect: connection refused

Why i get this error?!

i tried many things to solve my problem including:

Open port 8083 on my machine

add the 0.0.0.0 to my host file

open port 8083 on my container too

but nothing works at all!

what should i do?!

Body:
To access a port in the container from the host, it needs to be published. So the run command should be

docker run -d -p 8081:8081 -p 8083:8083 --name nexus -v nexus-data:/nexus-dasonatype/nexus3:3.37.3


问:
In Julia, after A = B, changing elements of B will modify A as well. Is it so?
While reading Julia documentation in the section "Noteworthy differences from C/C++":

"Julia arrays are not copied when assigned to another variable. After A = B, changing elements of B will modify A as well. Updating operators like += do not operate in-place, they are equivalent to A = A + B which rebinds the left-hand side to the result of the right-hand side expression."

But I tried this, it is not happening i.e. changing B is not changing A. (I tried with 2x2 Matrix)

Can someone explain what this para means?

i tried the following code:

```<code>julia> m=Array(zeros(2,2))
2×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0

julia> k=m
2×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0

julia> k
2×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0

julia> m=Array(ones(2,2))
2×2 Matrix{Float64}:
 1.0  1.0
 1.0  1.0

julia> k
2×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0
</code>```

答:
As it is explained

```<code>changing elements of B will modify A as well
</code>```

So you can use the dotted version of assignment to change elements:

```<code>julia> m .= Array(ones(2,2))

</code>```

Body:
While reading Julia documentation in the section "Noteworthy differences from C/C++":

"Julia arrays are not copied when assigned to another variable. After A = B, changing elements of B will modify A as well. Updating operators like += do not operate in-place, they are equivalent to A = A + B which rebinds the left-hand side to the result of the right-hand side expression."

But I tried this, it is not happening i.e. changing B is not changing A. (I tried with 2x2 Matrix)

Can someone explain what this para means?

i tried the following code:

julia> m=Array(zeros(2,2))
2×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0

julia> k=m
2×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0

julia> k
2×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0

julia> m=Array(ones(2,2))
2×2 Matrix{Float64}:
 1.0  1.0
 1.0  1.0

julia> k
2×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0

Body:
As it is explained

changing elements of B will modify A as well

So you can use the dotted version of assignment to change elements:

julia> m .= Array(ones(2,2))


问:
FTX API to create order
It show error {"success":false,"error":"Missing parameter market"}

```<code>import time
import hmac
from requests import Request
import requests
import json
api_key=''
api_secret=''
payload = json.dumps({
    "market": 'XRP/USDT',
    "side": 'BUY',
    "price": 0.7,
    "size": 1,
    "type": "limit",
    "reduceOnly": False,
    "ioc": False,
    "postOnly": False,
    "clientId": None
    })
ts = int(time.time() * 1000)
request = Request('POST', 'https://ftx.com/api/orders')
prepared = request.prepare()
signature_payload = f'{ts}{prepared.method}{prepared.path_url}{payload}'.encode()
print(signature_payload)
signature = hmac.new(api_secret.encode(), signature_payload, 'sha256').hexdigest()
prepared.headers['FTX-KEY'] = api_key
prepared.headers['FTX-SIGN'] = signature
prepared.headers['FTX-TS'] = str(ts)
url='https://ftx.com/api/orders'
response = requests.request("POST", url,headers=prepared.headers,data=payload)
print(response.text)
</code>```

Can you please recommend how to fix ? I have try many way but it doesn't work

答:
You may try</p>
```<code>prepared.headers['Content-Type'] = 'application/json'
</code>```

Title: FTX API to create order

Body:
It show error {"success":false,"error":"Missing parameter market"}

import time
import hmac
from requests import Request
import requests
import json
api_key=''
api_secret=''
payload = json.dumps({
    "market": 'XRP/USDT',
    "side": 'BUY',
    "price": 0.7,
    "size": 1,
    "type": "limit",
    "reduceOnly": False,
    "ioc": False,
    "postOnly": False,
    "clientId": None
    })
ts = int(time.time() * 1000)
request = Request('POST', 'https://ftx.com/api/orders')
prepared = request.prepare()
signature_payload = f'{ts}{prepared.method}{prepared.path_url}{payload}'.encode()
print(signature_payload)
signature = hmac.new(api_secret.encode(), signature_payload, 'sha256').hexdigest()
prepared.headers['FTX-KEY'] = api_key
prepared.headers['FTX-SIGN'] = signature
prepared.headers['FTX-TS'] = str(ts)
url='https://ftx.com/api/orders'
response = requests.request("POST", url,headers=prepared.headers,data=payload)
print(response.text)

Can you please recommend how to fix ? I have try many way but it doesn't work

Body:
You may try

prepared.headers['Content-Type'] = 'application/json'


问:
Making a simple car game with HTML5 canvas
I'm having a play with HTML5 canvas, and for my first experiment I decided to try make a simple car animation with basic user input. I think I'm most of the way there with basic input and movement, but I just wanted to see if I could take it a bit further.

Demo: http://jsfiddle.net/mpxML/20/
(use arrow keys)

I have an image loading in, you can also see a black square which moves, that is the translate point, or where the car is steering from. I wanted to somehow create a drift effect which can be achieved at higher speeds etc. It also can turn when it's not moving, that isn't right.

Anyway, I just don't know what logic I need to make the car feel more semi-realistic.

Thanks

答:
To fix the turning you have to do something like this:

```<code>car.angle = car.angle - (car.handeling * car.speed/car.topSpeed);
</code>```

this will prevent from turning when speed is 0 and will fix the reverse turning

To get drift effects you should move the car's rotation center forward and allow the car to rotate over it self without really turning

Body:
To fix the turning you have to do something like this:

car.angle = car.angle - (car.handeling * car.speed/car.topSpeed);

this will prevent from turning when speed is 0 and will fix the reverse turning

To get drift effects you should move the car's rotation center forward and allow the car to rotate over it self without really turning


问:
Vuetify: how to just apply border to component without the rest of stuff when using e.g. card
I have a component, rendered using v-row and v-col that needs an unintrusive divider before the next v-row.

the idea is to render the divider using Vuetify styles, not my own due to consistency.

So I wanted to apply same styles as are used for v-card by specifying class="v-card v-sheet" and I got the border, with box-shadow.

But I also got all the other CSS, like margins and padding.

I looked in documentation trying to find something that would give me what I want, but I couldn't.

So, does Vuetify provide a CSS class that would ONLY declare box-shadow and border-radius?

答:
Vuetify does provide Border-Radius and Elevation utility classes. This allows you to compose a look similar to a v-card but without any other styles.

<v-row class="rounded elevation-1">
</v-row>
```


问:
how do i create a variable from the output of another in bash
Here's an example script that doesn't work the way I expect:

```<code>#!/bin/bash
for dynamic in a b c; do
  myvar=$dynamic

  export $myvar="hi"

  echo $(eval "$myvar")
  echo $dynamic
done
</code>```

I want the output would be:

```<code>hi

a

hi

b

hi

c
</code>```

Any ideas?  I'm willing to stray away from this method, but I definitely want to be able to create a variable named from the output of an algorithm.  In this case it's just a for loop.

答:
eval has a tendency to cause bugs, so avoid it whenever possible; in this case it's much cleaner to use indirect expansion with ${!metavariable}:

```<code>#!/bin/bash
for dynamic in a b c; do
  myvar=$dynamic

  export $myvar="hi"

  echo ${!myvar}
  echo $dynamic
done
</code>```

Body:
Here's an example script that doesn't work the way I expect:

#!/bin/bash
for dynamic in a b c; do
  myvar=$dynamic

  export $myvar="hi"

  echo $(eval "$myvar")
  echo $dynamic
done

I want the output would be:

hi

a

hi

b

hi

c

Any ideas?  I'm willing to stray away from this method, but I definitely want to be able to create a variable named from the output of an algorithm.  In this case it's just a for loop.

Body:
eval has a tendency to cause bugs, so avoid it whenever possible; in this case it's much cleaner to use indirect expansion with ${!metavariable}:

#!/bin/bash
for dynamic in a b c; do
  myvar=$dynamic

  export $myvar="hi"

  echo ${!myvar}
  echo $dynamic
done


问:
Unable to update access_tokens using the Google Analytics > Reporting> Embed API with Service Accounts
I am using the Google Analytics Embed API to create a report in a Vue App.

I am following this documentation: https://developers.google.com/analytics/devguides/reporting/embed/v1/component-reference#auth
Everything works until the access token expires.  I catch the error get a new access_token from the back end and call authorize to reauthenticate the embed api client

```<code>await window.gapi.analytics.auth.authorize({
  serverAuth: {
    access_token: <my token>
  }
})
const isAuthorized = await window.gapi.analytics.auth.isAuthorized()
// isAuthorized returns true
// however getAuthResponse() still returns the old expired token.
console.log('getAccessToken', await window.gapi.analytics.auth.getAuthResponse().access_token)
// and the call to get the reporting data fails as the authorization header is the old expired header
const data = new window.gapi.analytics.report.Data({ query: params })
</code>```

How do I update the access_token once it has expired in my spa app so the embed api reauthenticates for the service account?

答:
The google analytics embeded api is Javascript based.  It is built upon the Google apis js client library in the backend.

JavaScript is implicit flow which means you will not get a refresh token returned to you.  Service accounts also do not work with JavaScript.

Out of the box your only option is to request that the user login to your app again when the access token expires.

I have seen / heard of a few developers who have managed to hack a server sided authorization component into it which would for example use node.js to use oauth2 or a service account to enable the authorization to be refreshed. This is something you would need to code yourself its not officially supported by the api.

Body:
I am using the Google Analytics Embed API to create a report in a Vue App.

I am following this documentation: https://developers.google.com/analytics/devguides/reporting/embed/v1/component-reference#auth
Everything works until the access token expires.  I catch the error get a new access_token from the back end and call authorize to reauthenticate the embed api client

await window.gapi.analytics.auth.authorize({
  serverAuth: {
    access_token: <my token>
  }
})
const isAuthorized = await window.gapi.analytics.auth.isAuthorized()
// isAuthorized returns true
// however getAuthResponse() still returns the old expired token.
console.log('getAccessToken', await window.gapi.analytics.auth.getAuthResponse().access_token)
// and the call to get the reporting data fails as the authorization header is the old expired header
const data = new window.gapi.analytics.report.Data({ query: params })

How do I update the access_token once it has expired in my spa app so the embed api reauthenticates for the service account?


问:
Return a yes or no if a value is matched on another column on a different sheet
I have an excel workbook with 2 sheets. One sheet is called Roster and sheet 2 is called Safety Meeting. On sheet 2(Safety Meeting) is a column with [Id#-name] for those who attended. How do I get “Yes” or “No”return on sheet 1(Roster) for those who attended on sheet 2(Safety Meeting). Also, Roster sheet only has ID# and on Safety Meeting sheet it has ID#andName, but I only need to match the ID number.
I was trying IF and MATCH functions, but having a column with ID numbers and name is throwing me off.</p>

答:
So something like:

```<code>if(iferror(match(id_num,range_safety_meeting,0),0)>0,"Yes","No")
</code>```

As you don't show what any of the data looks like I have just shown the structure.

Match has two compulsory arguments, while the third is optional, however I always set 0 for an exact match or 1 for a descending or -1 for an ascending result.

Body:
So something like:

if(iferror(match(id_num,range_safety_meeting,0),0)>0,"Yes","No")

As you don't show what any of the data looks like I have just shown the structure.

Match has two compulsory arguments, while the third is optional, however I always set 0 for an exact match or 1 for a descending or -1 for an ascending result.


问:
Can you avoid the pod to be restarted after kubectl attach?
I have an ubuntu image that I use for debugging.
I do kubectl attach my-app -c my-app -it and then many apt-get install and other configurations I need.

The problem is when I exit ctrl+c the pod seems to get restarted and I loose all what I did

Is there a way like --restart=never to avoid the container to be recreated

答:
Run another shell session kubectl exec my-app -c my-app -it -- bash to prepare your container. Alternately, if your pod spec has the following set to true:

```<code>stdin: true
tty: true
</code>```

You use the escape sequence Ctrl+P followed by Ctrl+Q to detach from the container after kubectl attach -it to the container.

Body:
Run another shell session kubectl exec my-app -c my-app -it -- bash to prepare your container. Alternately, if your pod spec has the following set to true:

stdin: true
tty: true

You use the escape sequence Ctrl+P followed by Ctrl+Q to detach from the container after kubectl attach -it to the container.


问:
two question about python regular expressions
Q1. why we can not use word boundary and back reference without using r at start of regex?
e.g. '\b[a-z]{5}\d{3}\b' this not works but this r'\b[a-z]{5}\d{3}\b' works

Q2. why python does not support variable length negative look behind assertions while it supports variable length negative look ahead assertion, c# support both and i think it is an excellent feature to have also variable length negative look behind in python.

please clear these two concepts. thanks

答:
It does work without raw strings:

```<code>'\\b[a-z]{5}\\d{3}\\b'
</code>```

You just need to double escape the special chars (actually, what you do is escape all backslashes).

Variable length assertions are one of those features that some implementations support and some don't. Check out the regex module on PyPI for a version with more features and better unicode support, which may eventually replace the standard library re.

Edit: To make the version from your comment work without raw strings, use:

```<code>re.sub('[a-z]+(\d+)', '\\1', string)
</code>```

Again, Python interprets backslashes. it thinks \1 means a byte value of 1. If you actually mean \1, you need to escape the backslash by doing \\1, or use raw strings.

Edit 2: Adding the link from @Nate's comment to the list of Python escape sequences.

Body:
It does work without raw strings:

'\\b[a-z]{5}\\d{3}\\b'

You just need to double escape the special chars (actually, what you do is escape all backslashes).

Variable length assertions are one of those features that some implementations support and some don't. Check out the regex module on PyPI for a version with more features and better unicode support, which may eventually replace the standard library re.

Edit: To make the version from your comment work without raw strings, use:

re.sub('[a-z]+(\d+)', '\\1', string)

Again, Python interprets backslashes. it thinks \1 means a byte value of 1. If you actually mean \1, you need to escape the backslash by doing \\1, or use raw strings.

Edit 2: Adding the link from @Nate's comment to the list of Python escape sequences.


问:
tkinter having different titles for two windows
I want to use tkinter to create an application that has two windows with different titles.

Here's my code.

```<code>import tkinter as tk

class Demo1:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
        self.button1.pack()
        self.frame.pack()
        self.new_window()

    def new_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = Demo2(self.newWindow)

class Demo2:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()

def main():
    root = tk.Tk()
    root.wm_title('title1') # How can I set different titles for Demo1 and Demo2?
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()
</code>```

If you run it, you can see two windows having the same title namedtitle1.

How can I reorgganize my code so that Demo1 and Demo2 have different titles?

答:
Simply you can apply this:

```<code>def new_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.newWindow.title("title2")
        self.app = Demo2(self.newWindow)
</code>```

Here You set the title for the new TopLevel window so it's different than the main window

Body:
I want to use tkinter to create an application that has two windows with different titles.

Here's my code.

import tkinter as tk

class Demo1:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
        self.button1.pack()
        self.frame.pack()
        self.new_window()

    def new_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = Demo2(self.newWindow)

class Demo2:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()

def main():
    root = tk.Tk()
    root.wm_title('title1') # How can I set different titles for Demo1 and Demo2?
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

If you run it, you can see two windows having the same title namedtitle1.

How can I reorgganize my code so that Demo1 and Demo2 have different titles?

Body:
Simply you can apply this:

def new_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.newWindow.title("title2")
        self.app = Demo2(self.newWindow)

Here You set the title for the new TopLevel window so it's different than the main window


问:
Whats the process to adding a Public Key for the merchant?
Good day, we are creating a Vodacom product mini-app, we have created our public and private keys.. We don't see an option to view merchant details. Could you assist us with the process needed to add our public key for our merchant app.</p>

答: You can send an email to miniprogramsupport@vodacom.co.za to get your public key configured on the VodaPay systems.</p>


问:
Microsoft VisualStudio TestTools UITest dll
I need to find

Microsoft.VisualStudio.TestTools.UITest.Common.dll
  Microsoft.VisualStudio.TestTools.UITest.Extension.dll
  Microsoft.VisualStudio.TestTools.UITest.Extension.Firefox.dll
  Microsoft.VisualStudio.TestTools.UITest.Extension.Silverlight.dll
  Microsoft.VisualStudio.TestTools.UITesting.dll
  Microsoft.VisualStudio.QualityTools.CodedUITestFramework.dll

Where are these dll located so I can reference it on my project  and i am using visual studio 2010 professional.

答:
For Visual Studio 2013, CodedUI is only available in the premium and ultimate editions.

For Visual Studio 2015, it's only available in the enterprise edition.


问:
Create random CGPoint with Swift
So, I'm trying to develop a simple game written in Swift, but I'm having trouble doing a pretty simple thing. I can't manage to create a random CGPoint... When using arc4random, a compiler error shows up telling me that I can't use Int32 in a CGPoint. So, Is there any way to do this? Any workaround? Thanks!</p>

答:
Here is an extension on CGPoint to generate random point based on your x,y closed range.</p>
```<code>extension CGPoint {
    static func randPoint(xRange: ClosedRange<CGFloat>, yRange: ClosedRange<CGFloat>) -> Self {
        let x = CGFloat.random(in: xRange)
        let y = CGFloat.random(in: yRange)
        return .init(x: x, y: y)
    }

}
</code>```

Title: Create random CGPoint with Swift

Body:
Here is an extension on CGPoint to generate random point based on your x,y closed range.

extension CGPoint {
    static func randPoint(xRange: ClosedRange<CGFloat>, yRange: ClosedRange<CGFloat>) -> Self {
        let x = CGFloat.random(in: xRange)
        let y = CGFloat.random(in: yRange)
        return .init(x: x, y: y)
    }

}


问:
Problem executing regex with a shell command inside Python program
I am trying to write a Python script to automate some tasks while the event of high inbound connections to the server.

So a portion of it is to collect all the IPv4 addresses on the server.

The command helps to list out that.

```<code># ip a s eth0 | egrep -o 'inet [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | cut -d' ' -f2
198.168.1.2
198.168.1.3
198.168.1.4
</code>```

The problem I am facing when executing the shell regex part inside the python script.

```<code>#!/usr/bin/env python3
import os
ipv4_regex='[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = 'ip a s eth0 | egrep -o 'inet ipv4_regex' | cut -d' ' -f2'
os.system(os_cmd)
</code>```

But the output is error:

```<code># ./dos_fix.py
  File "./dos_fix.py", line 4
    os_cmd = 'ip a s eth0 | egrep -o 'inet ipv4_regex' | cut -d' ' -f2'
                                     ^
</code>```

To see if it was due to any whitespace interrupting between the egrep and pipe, I tried to escape those quotes with backslashes, but no luck.

```<code>#!/usr/bin/env python3
import os
ipv4_regex='[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = 'ip a s eth0 | egrep -o \'inet ipv4_regex\' | cut -d\' \' -f2'
os.system(os_cmd)
</code>```

What am I missing here?.

答:
The subprocess you are trying to execute has no idea that ipv4_regex is a Python variable, or what its value might be. You are simply searching for that string literally, i p v 4 etc.

A much better solution anyway is to do as much of the processing as possible in Python.

```<code>import subprocess
import re

ipv4_regex=re.compile(r'inet [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')

for line in subprocess.run(
    ['ip', 'a', 's', 'eth0'],
    capture_output=True, text=True,
    check=True
).stdout.split('\n'):
    m = ipv4_regex.search(line)
    if m:
        print(line.split()[1])
</code>```

(I had to guess a bit what your script is supposed to do, since the syntax you used is invalid.)

Like the os.system documentation already tells you, subprocess is much more versatile, and generally recommended over the bare legacy os.system. In particular, if you want the output of the subprocess to be made available to Python, and not just displayed on the console, you need to use subprocess. It also gives you more control over the subprocess, including the ability to not use a shell when you don't need one. (See also Actual meaning of shell=True in subprocess)

Notice the use or a "raw" string to get the actual backslashes into the regex; Python does its own backslash processing on strings in source code, so you have to double the backslashes to put in a literal backslash in a string if you don't use the r'...' syntax.

If your target platform is Linux, probably a better solution still is to extract the information directly in machine-readable format from the /proc filesystem.

Body:
I am trying to write a Python script to automate some tasks while the event of high inbound connections to the server.

So a portion of it is to collect all the IPv4 addresses on the server.

The command helps to list out that.

# ip a s eth0 | egrep -o 'inet [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | cut -d' ' -f2
198.168.1.2
198.168.1.3
198.168.1.4

The problem I am facing when executing the shell regex part inside the python script.

#!/usr/bin/env python3
import os
ipv4_regex='[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = 'ip a s eth0 | egrep -o 'inet ipv4_regex' | cut -d' ' -f2'
os.system(os_cmd)

But the output is error:

# ./dos_fix.py
  File "./dos_fix.py", line 4
    os_cmd = 'ip a s eth0 | egrep -o 'inet ipv4_regex' | cut -d' ' -f2'
                                     ^

To see if it was due to any whitespace interrupting between the egrep and pipe, I tried to escape those quotes with backslashes, but no luck.

#!/usr/bin/env python3
import os
ipv4_regex='[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = 'ip a s eth0 | egrep -o \'inet ipv4_regex\' | cut -d\' \' -f2'
os.system(os_cmd)

What am I missing here?.

Body:
The subprocess you are trying to execute has no idea that ipv4_regex is a Python variable, or what its value might be. You are simply searching for that string literally, i p v 4 etc.

A much better solution anyway is to do as much of the processing as possible in Python.

import subprocess
import re

ipv4_regex=re.compile(r'inet [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')

for line in subprocess.run(
    ['ip', 'a', 's', 'eth0'],
    capture_output=True, text=True,
    check=True
).stdout.split('\n'):
    m = ipv4_regex.search(line)
    if m:
        print(line.split()[1])

(I had to guess a bit what your script is supposed to do, since the syntax you used is invalid.)

Like the os.system documentation already tells you, subprocess is much more versatile, and generally recommended over the bare legacy os.system. In particular, if you want the output of the subprocess to be made available to Python, and not just displayed on the console, you need to use subprocess. It also gives you more control over the subprocess, including the ability to not use a shell when you don't need one. (See also Actual meaning of shell=True in subprocess)

Notice the use or a "raw" string to get the actual backslashes into the regex; Python does its own backslash processing on strings in source code, so you have to double the backslashes to put in a literal backslash in a string if you don't use the r'...' syntax.

If your target platform is Linux, probably a better solution still is to extract the information directly in machine-readable format from the /proc filesystem.


问:
Visualisation in RMarkdown file
Could anyone give me an advice or some articles how to visualize KPIs like most visited sections in a website, most read blogs, number of unique visits weekly and monthly, and similar graphs. I'm working with RMarkdown dashboard. Which packages would be best to use? I would be grateful for any tips and sources.</p>

答:
The librarys that I've been using are:

```<code>library(tidyverse)
library(lubridate)
library(readxl)
library(highcharter)
library(tidyquant)
library(tibbletime)
library(quantmod)
library(PerformanceAnalytics)
library(scales)
library(timetk)
library(here)
library(tinytex)
</code>```

The quantmod library is the best one to create interactive graphics.
Lastly, I recommend you to read the chapter 3 of this book: https://r4ds.had.co.nz/ "Data Visualisation"

Title: Visualisation in RMarkdown file

Body:
The librarys that I've been using are:

library(tidyverse)
library(lubridate)
library(readxl)
library(highcharter)
library(tidyquant)
library(tibbletime)
library(quantmod)
library(PerformanceAnalytics)
library(scales)
library(timetk)
library(here)
library(tinytex)

The quantmod library is the best one to create interactive graphics.
Lastly, I recommend you to read the chapter 3 of this book: https://r4ds.had.co.nz/ "Data Visualisation"


问:
COVERAGE=true bundle exec rspec --color --profile --format documentation taking too much to process
I have to run this command COVERAGE=true bundle exec rspec --color --profile --format documentation  as final test for my ruby rail application on github actions but only this command is taking more than 15 minutes to complete , is there any way to make it faster ?

答:
There are ways to run it faster. Locally, you can use Spring instead of bundle exec. In your CI, you can always split your specs in difference tasks and merge result in the next step.

Here is a good one to achieve so on Gitlab-CI: getting-started-with-simplecov-in-gitlab-ci