问:
Spring boot Application Failed to Start in Linux
Spring boot project can be run in local eclipse and windows environment use -jar. However , in the Linux environment, here are some problems to cause the Application Failed to Start. But the Process is always Running.

Spring Version is 1.5.19 , this is multiple modules project , logs in the Linux server is :

```<code>The web application [ROOT] appears to have started a thread named [CleanCursors-2-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:

***************************
APPLICATION FAILED TO START
***************************

Description:

The Tomcat connector configured to listen on port 28081 failed to start. The port may already be in use or the connector may be misconfigured.

Action:

Verify the connector's configuration, identify and stop any process that's listening on port 28081, or configure this application to listen on another port.

</code>```

I'm sure the port has not been occupied by any other processes. It make me confused that in the local environment , everything is Ok.

Some code in Pom.xml

```<code><dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!--exclusions slf4j-log4j12-->
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- Spring db template -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- Spring db template -->
        <!-- ${environments.${env}.sslPWD} related -->
        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>1.18</version>
        </dependency>
        <!-- ${environments.${env}.sslPWD} related -->
        <!-- Spring boot security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!-- Spring boot security -->
        <!-- Monitor Spring boot app -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- Monitor Spring boot app -->
</code>```

Hope Linux server no errors.

答:
For my question , I found I set wrong location of key store and trust store, it can not find stores in the linux server. When I changed to the right location, everything is OK.
Application.properties

```<code>server.ssl.key-store=/opt/PFTestServices/etc/SSL-keystore.jks
server.ssl.trust-sotre=/opt/PFTestServices/etc/certs/SSLTrust.jks

</code>```

Thanks a lot for help about this question !

Body:
Spring boot project can be run in local eclipse and windows environment use -jar. However , in the Linux environment, here are some problems to cause the Application Failed to Start. But the Process is always Running.

Spring Version is 1.5.19 , this is multiple modules project , logs in the Linux server is :

The web application [ROOT] appears to have started a thread named [CleanCursors-2-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:

***************************
APPLICATION FAILED TO START
***************************

Description:

The Tomcat connector configured to listen on port 28081 failed to start. The port may already be in use or the connector may be misconfigured.

Action:

Verify the connector's configuration, identify and stop any process that's listening on port 28081, or configure this application to listen on another port.

I'm sure the port has not been occupied by any other processes. It make me confused that in the local environment , everything is Ok.

Some code in Pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>

            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>1.18</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

Hope Linux server no errors.

Body:
For my question , I found I set wrong location of key store and trust store, it can not find stores in the linux server. When I changed to the right location, everything is OK.
Application.properties

server.ssl.key-store=/opt/PFTestServices/etc/SSL-keystore.jks
server.ssl.trust-sotre=/opt/PFTestServices/etc/certs/SSLTrust.jks

Thanks a lot for help about this question !


来源: stackexchange

问:
Convert this JSON to a tree and find the path to parent
```<code>data= {
"saturn": [
        "planet",
        "american_car",
        "car"
    ],
    "american_car": [
        "car",
        "gas_driven_automobile"
    ],
    "planet": [
        "large_object",
        "celestial_body"
    ],
    "large_object": [],
    "gas_driven_automobile": [
        "gas_powered_road_vehicle",
        "car"
    ],
    "car": [
        "vehicle",
        "motor_vehicle"
    ],
"vehicle": [],
"motor_vehicle": [],
"gas_powered_road_vehicle": [],
"celestial_body": []
};
</code>```

I need to write an algorithm where if I give the input "saturn" I need to get all the possible paths from saturn to different parents. for example,

```<code>saturn ->planet ->large_object
saturn ->american_car->car->vehicle
saturn ->american_car->car->motor_vehicle
saturn ->american_car->gas_driven_automobile->gas_powered_road_vehicle
saturn ->american_car->gas_driven_automobile->car->vehicle
</code>```

and all the other possible paths.

I was thinking of somehow converting this to a tree and then using a library to calculate the path from the child to the parent.

Working on writing an algorithm, can't figure out how to start off on converting this to a tree.

答:
Using jq, you can simply define a recursive function:

```<code>def parents($key):
  if has($key)
  then if .[$key] == []  then [] else .[$key][] as $k | [$k] + parents($k) end
  else []
  end;
</code>```

To use it to produce the "->"-style output, invoke jq with the -r command-line option, and call the above function like so:

```<code>["saturn"] + parents("saturn")
| join(" -> ")
</code>```

More economically

```<code>def lineages($key):
  [$key] + (lineages(.[$key][]) // []);

lineages("saturn") | join(" -> ")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
data= {
"saturn": [
        "planet",
        "american_car",
        "car"
    ],
    "american_car": [
        "car",
        "gas_driven_automobile"
    ],
    "planet": [
        "large_object",
        "celestial_body"
    ],
    "large_object": [],
    "gas_driven_automobile": [
        "gas_powered_road_vehicle",
        "car"
    ],
    "car": [
        "vehicle",
        "motor_vehicle"
    ],
"vehicle": [],
"motor_vehicle": [],
"gas_powered_road_vehicle": [],
"celestial_body": []
};

I need to write an algorithm where if I give the input "saturn" I need to get all the possible paths from saturn to different parents. for example,

saturn ->planet ->large_object
saturn ->american_car->car->vehicle
saturn ->american_car->car->motor_vehicle
saturn ->american_car->gas_driven_automobile->gas_powered_road_vehicle
saturn ->american_car->gas_driven_automobile->car->vehicle

and all the other possible paths.

I was thinking of somehow converting this to a tree and then using a library to calculate the path from the child to the parent.

Working on writing an algorithm, can't figure out how to start off on converting this to a tree.

Body:
Using jq, you can simply define a recursive function:

def parents($key):
  if has($key)
  then if .[$key] == []  then [] else .[$key][] as $k | [$k] + parents($k) end
  else []
  end;

To use it to produce the "->"-style output, invoke jq with the -r command-line option, and call the above function like so:

["saturn"] + parents("saturn")
| join(" -> ")

More economically

def lineages($key):
  [$key] + (lineages(.[$key][]) // []);

lineages("saturn") | join(" -> ")


问:
windows batch to split string on first occurrence of a delimiter
I have a parameter string read from a properties file. One of the properties is as below:

```<code>"CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080"
</code>```

I need to split this string on the first occurrence of "=" and set a parameter with the value:

```<code>-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
</code>```

I am trying to split the string first on the = token and then remove the fist sub-string token from the original string.
In the below code %%G will be set to "CUSTOM_JAVA_OPTIONS" and I am trying to remove this from the original string "TESTSTR"

```<code>@echo off

set "TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com
-Dhttp.proxyPort=8080"

SETLOCAL ENABLEDELAYEDEXPANSION

FOR /F "tokens=1,2 delims==" %%G IN ("%TESTSTR%") DO (

  echo Name=%%G
  echo Value=%%H
  set removestr=%%G

  echo TESTSTR=!TESTSTR!
  echo removestr=!removestr!

  set "str=!TESTSTR:%removestr%=!"
  echo str=!str!
  )
pause
</code>```

The above does not seem to work, it produces:

```<code>Name=CUSTOM_JAVA_OPTIONS
Value=-Dhttp.proxyHost
TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
removestr=CUSTOM_JAVA_OPTIONS
str=TESTSTR:=
</code>```

Expected result needs to be:

```<code> str=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
</code>```

答:
This could be simplified to:

```<code>@echo off

set "TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080"

FOR /F "tokens=1* delims==" %%G IN ("%TESTSTR%") DO set "str=%%H"
echo TESTSTR=%TESTSTR%
echo.str=%str%
pause
</code>```

There are 2 tokens:

```<code>1. Text up to 1st delimiter
2. Everything else after first delimiter (*)
</code>```

Note that by echoing the variables outside of the FOR loop you don't need to enable delayed expansion.

Body:
I have a parameter string read from a properties file. One of the properties is as below:

"CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080"

I need to split this string on the first occurrence of "=" and set a parameter with the value:

-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080

I am trying to split the string first on the = token and then remove the fist sub-string token from the original string.
In the below code %%G will be set to "CUSTOM_JAVA_OPTIONS" and I am trying to remove this from the original string "TESTSTR"

@echo off

set "TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com
-Dhttp.proxyPort=8080"

SETLOCAL ENABLEDELAYEDEXPANSION

FOR /F "tokens=1,2 delims==" %%G IN ("%TESTSTR%") DO (

  echo Name=%%G
  echo Value=%%H
  set removestr=%%G

  echo TESTSTR=!TESTSTR!
  echo removestr=!removestr!

  set "str=!TESTSTR:%removestr%=!"
  echo str=!str!
  )
pause

The above does not seem to work, it produces:

Name=CUSTOM_JAVA_OPTIONS
Value=-Dhttp.proxyHost
TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
removestr=CUSTOM_JAVA_OPTIONS
str=TESTSTR:=

Expected result needs to be:

 str=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080

Body:
This could be simplified to:

@echo off

set "TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080"

FOR /F "tokens=1* delims==" %%G IN ("%TESTSTR%") DO set "str=%%H"
echo TESTSTR=%TESTSTR%
echo.str=%str%
pause

There are 2 tokens:

1. Text up to 1st delimiter
2. Everything else after first delimiter (*)

Note that by echoing the variables outside of the FOR loop you don't need to enable delayed expansion.


问:
Dynamic ROOT With SQL Server For JSON PATH
I have a keyword table that I want to render to a Json object:

```<code>ID  Keyword     Text    Value
4   Category    A       10
5   Category    B       20
1   Season      Winter  1
2   Season      Spring  2
3   Season      Summer  3
9   Season      Fall    4
6   UnitType    Ft      Feet
7   UnitType    Set     Set
8   UnitType    $   Dollar
</code>```

that groups each category into it's own object.

I've being able to create this:

```<code>{"Keywords":[
{"Keyword":"Category","Values":[{"Value":"10","Text":"A"},{"Value":"20","Text":"B"}]},
{"Keyword":"Season","Values":[{"Value":"1","Text":"Winter"},{"Value":"2","Text":"Spring"},{"Value":"3","Text":"Summer"},{"Value":"4","Text":"Fall"}]},
{"Keyword":"UnitType","Values":[{"Value":"Dollar","Text":"$"},{"Value":"Feet","Text":"Ft"},{"Value":"Set","Text":"Set"}]}
]}
</code>```

using:

```<code>SELECT T.Keyword AS 'Keyword',
(SELECT [subT].[Value] AS 'Value', [subT].[Text] AS 'Text'
FROM tblKeywords subT WHERE subT.Keyword=T.Keyword
ORDER BY [subT].[Value]
FOR JSON PATH) AS 'Values'
FROM tblKeywords T
GROUP BY T.Keyword
FOR JSON PATH, ROOT('Keywords')
</code>```

But I'd like to be able to set the ROOT for the sub query to be keyword itself. Is this even possible?

The desired result is:

```<code>{"Keywords":[
{"Category":[{"Value":"10","Text":"A"},{"Value":"20","Text":"B"}]},
{"Season":[{"Value":"1","Text":"Winter"},{"Value":"2","Text":"Spring"},{"Value":"3","Text":"Summer"},{"Value":"4","Text":"Fall"}]},
{"UnitType":[{"Value":"Dollar","Text":"$"},{"Value":"Feet","Text":"Ft"},{"Value":"Set","Text":"Set"}]}
]}
</code>```

答:
Another possible approach using combination of FOR JSON and string manipulation, but without dynamic statement:

Input:

```<code>CREATE TABLE #tblKeywords (
   Id int,
   [Keyword] nvarchar(50),
   [Text] nvarchar(50),
   [Value] nvarchar(50)
);
INSERT INTO #tblKeywords
   (ID, [Keyword], [Text], [Value])
VALUES
   (4, 'Category', 'A',      '10'),
   (5, 'Category', 'B',      '20'),
   (1, 'Season',   'Winter', '1'),
   (2, 'Season',   'Spring', '2'),
   (3, 'Season',   'Summer', '3'),
   (9, 'Season',   'Fall',   '4'),
   (6, 'UnitType', 'Ft',     'Feet'),
   (7, 'UnitType', 'Set',    'Set'),
   (8, 'UnitType', '$',      'Dollar')
</code>```

T-SQL:

```<code>SELECT CONCAT(
   N'{"Keywords":[',
   STUFF(
      (
      SELECT DISTINCT CONCAT(N',{"', k.[Keyword], '":', c.[Json], N'}')
      FROM #tblKeywords k
      CROSS APPLY (
         SELECT [Value], [Text]
         FROM #tblKeywords
         WHERE [Keyword] = k.[Keyword]
         FOR JSON PATH
      ) c([Json])
      FOR XML PATH('')
      ), 1, 1, N''
   ),
   N']}'
) AS JsonOutput
</code>```

Output:

```<code>JsonOutput

{"Keywords":[{"Category":[{"Value":"10","Text":"A"},{"Value":"20","Text":"B"}]},{"Season":[{"Value":"1","Text":"Winter"},{"Value":"2","Text":"Spring"},{"Value":"3","Text":"Summer"},{"Value":"4","Text":"Fall"}]},{"UnitType":[{"Value":"Feet","Text":"Ft"},{"Value":"Set","Text":"Set"},{"Value":"Dollar","Text":"$"}]}]}
</code>```

Body:
I have a keyword table that I want to render to a Json object:

ID  Keyword     Text    Value
4   Category    A       10
5   Category    B       20
1   Season      Winter  1
2   Season      Spring  2
3   Season      Summer  3
9   Season      Fall    4
6   UnitType    Ft      Feet
7   UnitType    Set     Set
8   UnitType    $   Dollar

that groups each category into it's own object.

I've being able to create this:

{"Keywords":[
{"Keyword":"Category","Values":[{"Value":"10","Text":"A"},{"Value":"20","Text":"B"}]},
{"Keyword":"Season","Values":[{"Value":"1","Text":"Winter"},{"Value":"2","Text":"Spring"},{"Value":"3","Text":"Summer"},{"Value":"4","Text":"Fall"}]},
{"Keyword":"UnitType","Values":[{"Value":"Dollar","Text":"$"},{"Value":"Feet","Text":"Ft"},{"Value":"Set","Text":"Set"}]}
]}

using:

SELECT T.Keyword AS 'Keyword',
(SELECT [subT].[Value] AS 'Value', [subT].[Text] AS 'Text'
FROM tblKeywords subT WHERE subT.Keyword=T.Keyword
ORDER BY [subT].[Value]
FOR JSON PATH) AS 'Values'
FROM tblKeywords T
GROUP BY T.Keyword
FOR JSON PATH, ROOT('Keywords')

But I'd like to be able to set the ROOT for the sub query to be keyword itself. Is this even possible?

The desired result is:

{"Keywords":[
{"Category":[{"Value":"10","Text":"A"},{"Value":"20","Text":"B"}]},
{"Season":[{"Value":"1","Text":"Winter"},{"Value":"2","Text":"Spring"},{"Value":"3","Text":"Summer"},{"Value":"4","Text":"Fall"}]},
{"UnitType":[{"Value":"Dollar","Text":"$"},{"Value":"Feet","Text":"Ft"},{"Value":"Set","Text":"Set"}]}
]}

Body:
Another possible approach using combination of FOR JSON and string manipulation, but without dynamic statement:

Input:

CREATE TABLE #tblKeywords (
   Id int,
   [Keyword] nvarchar(50),
   [Text] nvarchar(50),
   [Value] nvarchar(50)
);
INSERT INTO #tblKeywords
   (ID, [Keyword], [Text], [Value])
VALUES
   (4, 'Category', 'A',      '10'),
   (5, 'Category', 'B',      '20'),
   (1, 'Season',   'Winter', '1'),
   (2, 'Season',   'Spring', '2'),
   (3, 'Season',   'Summer', '3'),
   (9, 'Season',   'Fall',   '4'),
   (6, 'UnitType', 'Ft',     'Feet'),
   (7, 'UnitType', 'Set',    'Set'),
   (8, 'UnitType', '$',      'Dollar')

T-SQL:

SELECT CONCAT(
   N'{"Keywords":[',
   STUFF(
      (
      SELECT DISTINCT CONCAT(N',{"', k.[Keyword], '":', c.[Json], N'}')
      FROM #tblKeywords k
      CROSS APPLY (
         SELECT [Value], [Text]
         FROM #tblKeywords
         WHERE [Keyword] = k.[Keyword]
         FOR JSON PATH
      ) c([Json])
      FOR XML PATH('')
      ), 1, 1, N''
   ),
   N']}'
) AS JsonOutput

Output:

JsonOutput

{"Keywords":[{"Category":[{"Value":"10","Text":"A"},{"Value":"20","Text":"B"}]},{"Season":[{"Value":"1","Text":"Winter"},{"Value":"2","Text":"Spring"},{"Value":"3","Text":"Summer"},{"Value":"4","Text":"Fall"}]},{"UnitType":[{"Value":"Feet","Text":"Ft"},{"Value":"Set","Text":"Set"},{"Value":"Dollar","Text":"$"}]}]}


问:
Should I learn Swing before learning JavaFx?
Does it make sense to start learning JavaFx if I do not have any background in UI programming? Is it more advisable to learn Swing first and then move on to JavaFx ?

I tried the getting started tutorial on JavaFx website in Netbeans and the code looked extremely complicated to me. I am wondering if JavaFx is too advanced for a beginnner GUI developer.

答: I don't think knowing swing will give you much of an upper hand with JavaFX. JavaFX seems more like scripting rather than actual java programming. You can learn JavaFX fine without swing.</p>

OwnerDisplayName: Rahul

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: John T


问:
pointer & array conflict
let

```<code>int*p ,b = 5;
p = &b;
</code>```

denotes a ONE DIMENSIONAL array, then what is the output given by following statement

```<code>printf("%d",p);
</code>```

is it an address? if it is an address then tell me which element it belongs,please explain clearly

答:
```<code>int*p ,b = 5;
p = &b;
</code>```

is exactly equivalent to:

```<code>int b = 5;
int *p = &b;
</code>```

p ends up being a pointer to int. Now its true that this code will have much the same effect on what ends up in p (although b has a completely different type and value) as this:

```<code>int b[1] = {5};
int *p = b; // or int *p = &b[0];
</code>```

certainly in either case p points to an int which you may treat as a simple int, or as the first (and only) element in a one-dimensional array of size one. So, what follows is legal and gives meaningful results in both cases:

```<code>printf("%d is stored at %p\n", *p, p);
printf("%d\n",p[0]);
</code>```

but that's pretty much where the similarity ends.

ContentLicense: CC BY-SA 3.0

Title: pointer & array conflict

Body:
let

int*p ,b = 5;
p = &b;

denotes a ONE DIMENSIONAL array, then what is the output given by following statement

printf("%d",p);

is it an address? if it is an address then tell me which element it belongs,please explain clearly

Body:
int*p ,b = 5;
p = &b;

is exactly equivalent to:

int b = 5;
int *p = &b;

p ends up being a pointer to int. Now its true that this code will have much the same effect on what ends up in p (although b has a completely different type and value) as this:

int b[1] = {5};
int *p = b; // or int *p = &b[0];

certainly in either case p points to an int which you may treat as a simple int, or as the first (and only) element in a one-dimensional array of size one. So, what follows is legal and gives meaningful results in both cases:

printf("%d is stored at %p\n", *p, p);
printf("%d\n",p[0]);

but that's pretty much where the similarity ends.


问:
Update table cell value dynamically using angular6
I am working with an angular 6 application, in the HTML template I have some code as per below, just showing the table cell part of the array, also the table is built using divs.

```<code><div class='table_small'>
        <div class='table_cell'>Status</div>
        <div class='table_cell'>
          <p class="status" >{{incomingData.status}}</p>
        </div>
      </div>
</code>```

Please note here that "data" is an array (*ngFor) and is being used in row data and there are multiple data in the table.

Now I have a situation wherein there is a button inside the table rows to cancel the particular order, when the user clicks in, a pop up/modal asks for user confirmation, if the user opts for 'Yes' it would change the status field value to "cancellation is in process" temporarily before it hits the service, once there is a successful response from the customer it would change the station to "cancelled".

I am really not sure how to do the cancellation within the table cell here, if anyone can give insight on this please do.

Thanks

答:
You could pass the element to the function and edit its status:

```<code><div class='table_small'>
    <div class='table_cell'>Status</div>
    <div class='table_cell'>
      <p class="status" >{{incomingData.status}}</p>
    </div>
    <div class='table_cell'>
      <button (click)="showCancelModal(incomingData)"> Cancel</p>
    </div>
  </div>
</code>```

And then in the component something like this:

```<code>showCancelModal(incomingData) {
  // logic for showing modal and retrieving user response
  if( response === 'yes') {
    incomingData.status = 'Cancel in progress';
    yourService.cancel(incomingData)
    .pipe( finally(() => incomingData.status = 'Cancelled') )
     .subscribe();
  }
}
</code>```

Body:
I am working with an angular 6 application, in the HTML template I have some code as per below, just showing the table cell part of the array, also the table is built using divs.

Status

{{incomingData.status}}

Please note here that "data" is an array (*ngFor) and is being used in row data and there are multiple data in the table.

Now I have a situation wherein there is a button inside the table rows to cancel the particular order, when the user clicks in, a pop up/modal asks for user confirmation, if the user opts for 'Yes' it would change the status field value to "cancellation is in process" temporarily before it hits the service, once there is a successful response from the customer it would change the station to "cancelled".

I am really not sure how to do the cancellation within the table cell here, if anyone can give insight on this please do.

Thanks

Body:
You could pass the element to the function and edit its status:

<div class='table_small'>
    <div class='table_cell'>Status</div>
    <div class='table_cell'>
      <p class="status" >{{incomingData.status}}</p>
    </div>
    <div class='table_cell'>
      <button (click)="showCancelModal(incomingData)"> Cancel</p>
    </div>
  </div>

And then in the component something like this:

showCancelModal(incomingData) {
  // logic for showing modal and retrieving user response
  if( response === 'yes') {
    incomingData.status = 'Cancel in progress';
    yourService.cancel(incomingData)
    .pipe( finally(() => incomingData.status = 'Cancelled') )
     .subscribe();
  }
}


问:
How to overcome Error 1004 range of object _global failed
Here i am trying to copy data from one sheet to another, where i need to exclude one particular column from copy sheet

Like :
Think i have 2 sheets( with names as "Combined","HSR") from HSR i need to copy all the data to Combined sheet excluding column "D" values

```<code>Dim ws As Worksheet
Dim ColumnLetter As Variant
    Set ws = Sheets("HSR")
    Worksheets("HSR").Select
    lr = Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row
    lr2 = Sheets("Combined").Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row
    ColumnLetter = Split(ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Cells.Address(1, 0), "$")(0)
    Range("A2:C" & lr).Copy Sheets("Combined").Range("A" & lr2 + 1)
    Range("E2:ColumnLetter" & lr).Copy Sheets("Combined").Range("D" & lr2 + 1)
End Sub
</code>```

I expect the output as, in sheet Combined i shouldn't get the values that are in column D from HSR sheet

答:
ColumnLetter is a variable. You are using it as a String.

Change

```<code>Range("E2:ColumnLetter" & lr).Copy Sheets("Combined").Range("D" & lr2 + 1)
</code>```

to

```<code>Range("E2:" & ColumnLetter & lr).Copy Sheets("Combined").Range("D" & lr2 + 1)
</code>```

Also few tips

lr = Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row and lr2 = Sheets("Combined").Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row will give you error if .Find doesn't return anyting. Handle it as shown in .Find and .FindNext

Avoid the use of .Select. You may want to see How to avoid using Select in Excel VBA

Body:
Here i am trying to copy data from one sheet to another, where i need to exclude one particular column from copy sheet

Like :
Think i have 2 sheets( with names as "Combined","HSR") from HSR i need to copy all the data to Combined sheet excluding column "D" values

Dim ws As Worksheet
Dim ColumnLetter As Variant
    Set ws = Sheets("HSR")
    Worksheets("HSR").Select
    lr = Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row
    lr2 = Sheets("Combined").Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row
    ColumnLetter = Split(ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Cells.Address(1, 0), "$")(0)
    Range("A2:C" & lr).Copy Sheets("Combined").Range("A" & lr2 + 1)
    Range("E2:ColumnLetter" & lr).Copy Sheets("Combined").Range("D" & lr2 + 1)
End Sub

I expect the output as, in sheet Combined i shouldn't get the values that are in column D from HSR sheet

Body:
ColumnLetter is a variable. You are using it as a String.

Change

Range("E2:ColumnLetter" & lr).Copy Sheets("Combined").Range("D" & lr2 + 1)

to

Range("E2:" & ColumnLetter & lr).Copy Sheets("Combined").Range("D" & lr2 + 1)

Also few tips

lr = Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row and lr2 = Sheets("Combined").Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row will give you error if .Find doesn't return anyting. Handle it as shown in .Find and .FindNext

Avoid the use of .Select. You may want to see How to avoid using Select in Excel VBA


问:
PHP & Docker: script unable to write to /tmp
I have created a Docker image with Nginx & PHP 5 for my project, but i'm getting a runtime error due to lack of permissions on /tmp. Does it have to be a volume or is there a special Dockerfile configuration for this? </p>

```<code>fopen(/tmp/myerror.log): failed to open stream: Permission denied
</code>```

答:
```<code>chmod 777 (please no ! )
chown -R yourmachinename:yourmachinename /tmp
</code>```

Body:
I have created a Docker image with Nginx & PHP 5 for my project, but i'm getting a runtime error due to lack of permissions on /tmp. Does it have to be a volume or is there a special Dockerfile configuration for this?

fopen(/tmp/myerror.log): failed to open stream: Permission denied


问:
mysql 8 MyISAM "SHOW TABLE STATUS" row count
i recently upgraded from mySQL 5.6.34 -> 8.0.16 (on macOS 10.14.5) and i am noticing very strange behavior with the row counts returned from "SHOW TABLE STATUS" as well as the row counts in the "information_schema" table. consider this simple schema:

```<code>CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `test` (`id`, `name`) VALUES
(1, 'one'),
(2, 'two'),
(3, 'three'),
(4, 'four'),
(5, 'five');
</code>```

when i then run the following query i see the expected output:

```<code>SELECT * FROM test;
+----+-------+
| id | name  |
+----+-------+
|  1 | one   |
|  2 | two   |
|  3 | three |
|  4 | four  |
|  5 | five  |
+----+-------+
</code>```

likewise when i then run the following query i see the expected output:

```<code>SELECT COUNT(*) FROM test;
+----------+
| COUNT(*) |
+----------+
|        5 |
+----------+
</code>```

however when i then run the following query:

```<code>    SHOW TABLE STATUS \G
*************************** 1. row ***************************
           Name: test
         Engine: MyISAM
        Version: 10
     Row_format: Dynamic
           Rows: 0
 Avg_row_length: 0
    Data_length: 0
Max_data_length: 281474976710655
   Index_length: 1024
      Data_free: 0
 Auto_increment: 1
    Create_time: 2019-05-30 13:56:46
    Update_time: 2019-05-30 16:02:24
     Check_time: NULL
      Collation: utf8_unicode_ci
       Checksum: NULL
 Create_options:
        Comment:
</code>```

it appears that there are no rows (even though there are 5). likewise i see the same results when i run:

```<code>SELECT table_name, table_rows FROM information_schema.tables WHERE table_schema = 'test';
    +------------+------------+
    | TABLE_NAME | TABLE_ROWS |
    +------------+------------+
    | test       |          0 |
    +------------+------------+
</code>```

no rows? if i add/delete rows to the table the counts do not change. only after i run:

```<code>ANALYZE TABLE `test`
</code>```

...do i see all of the row counts as correct. i am only seeing this on mySQL 8. everything worked as expected on mySQL 5. i am aware of problems with accurate row counts using InnoDB tables, but these are all MyISAM tables, which should always show the correct row counts. any help is appreciated. thanks.

答:
The information schema tables underwent significant, incompatible changes in MySQL 8 with the introduction of the global data dictionary:

Previously, INFORMATION_SCHEMA queries for table statistics in the STATISTICS and TABLES tables retrieved statistics directly from storage engines. As of MySQL 8.0, cached table statistics are used by default.

The cache is controlled by the system variable information_schema_stats_expiry:

Some INFORMATION_SCHEMA tables contain columns that provide table statistics:

[...] TABLES.TABLE_ROWS [...]

Those columns represent dynamic table metadata; that is, information that changes as table contents change.

By default, MySQL retrieves cached values for those columns from the mysql.index_stats and mysql.table_stats dictionary tables when the columns are queried, which is more efficient than retrieving statistics directly from the storage engine. If cached statistics are not available or have expired, MySQL retrieves the latest statistics from the storage engine and caches them in the mysql.index_stats and mysql.table_stats dictionary tables. Subsequent queries retrieve the cached statistics until the cached statistics expire.

[...]

To update cached values at any time for a given table, use ANALYZE TABLE.

To always retrieve the latest statistics directly from the storage engine and bypass cached values, set information_schema_stats_expiry to 0.

This is consistent with your behaviour.

You can set information_schema_stats_expiry globally to 0, or per session whenever you need accurate statistics.

Body:
i recently upgraded from mySQL 5.6.34 -> 8.0.16 (on macOS 10.14.5) and i am noticing very strange behavior with the row counts returned from "SHOW TABLE STATUS" as well as the row counts in the "information_schema" table. consider this simple schema:

CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `test` (`id`, `name`) VALUES
(1, 'one'),
(2, 'two'),
(3, 'three'),
(4, 'four'),
(5, 'five');

when i then run the following query i see the expected output:

SELECT * FROM test;
+----+-------+
| id | name  |
+----+-------+
|  1 | one   |
|  2 | two   |
|  3 | three |
|  4 | four  |
|  5 | five  |
+----+-------+

likewise when i then run the following query i see the expected output:

SELECT COUNT(*) FROM test;
+----------+
| COUNT(*) |
+----------+
|        5 |
+----------+

however when i then run the following query:

    SHOW TABLE STATUS \G
*************************** 1. row ***************************
           Name: test
         Engine: MyISAM
        Version: 10
     Row_format: Dynamic
           Rows: 0
 Avg_row_length: 0
    Data_length: 0
Max_data_length: 281474976710655
   Index_length: 1024
      Data_free: 0
 Auto_increment: 1
    Create_time: 2019-05-30 13:56:46
    Update_time: 2019-05-30 16:02:24
     Check_time: NULL
      Collation: utf8_unicode_ci
       Checksum: NULL
 Create_options:
        Comment:

it appears that there are no rows (even though there are 5). likewise i see the same results when i run:

SELECT table_name, table_rows FROM information_schema.tables WHERE table_schema = 'test';
    +------------+------------+
    | TABLE_NAME | TABLE_ROWS |
    +------------+------------+
    | test       |          0 |
    +------------+------------+

no rows? if i add/delete rows to the table the counts do not change. only after i run:

ANALYZE TABLE `test`

...do i see all of the row counts as correct. i am only seeing this on mySQL 8. everything worked as expected on mySQL 5. i am aware of problems with accurate row counts using InnoDB tables, but these are all MyISAM tables, which should always show the correct row counts. any help is appreciated. thanks.


问:
Converting R code to Markdown or RNotebok
Hi I'm asked to do an assignment, which requests to submit RNotebook (or Markdown) as html files for grading. This is a machine learning assignment.
What I need to know it, I'm going to use RStudio for the assignment.  Can you please let me knwo is RNotebook / Markdown is another platform to use? Once the coding is done can I convert it to Markdown?</p>

答:
Within R studio, you can choose R markdown .
Navigate to File Option -> New File -> R Markdown

There are no changes in coding. All codes that you write in R would be as-is. Just with a flexibility that you can add comments and explain your code.
Make sure in .Rmd file, there are  {} clauses. don't make any changes to it while writing code.

You will observe below chunk in .Rmd file. Make sure you should not delete {} but you may write any heading within these brackets.Followed by these brackets, you can write your code.

```<code>```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
```
</code>```

Body:
Within R studio, you can choose R markdown .
Navigate to File Option -> New File -> R Markdown

There are no changes in coding. All codes that you write in R would be as-is. Just with a flexibility that you can add comments and explain your code.
Make sure in .Rmd file, there are  {} clauses. don't make any changes to it while writing code.

You will observe below chunk in .Rmd file. Make sure you should not delete {} but you may write any heading within these brackets.Followed by these brackets, you can write your code.

```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
```


问:
Listview's selected item not in sync with the selected state of an item unless my mouse pointer is released after selecting
I have a list view with few items. Whenever, I select my list view item, it's corresponding selected state is lagging behind until my key pad or mouse pointer is released. What should be done in order that the selection of item is immediately reflected when I just click on the item irrespective of whether the key/mouse pointer is released. I tried with the basic listview with items and it seems to be a default behavior... Just curious to know if this can be overridden

Attached below the sample image of the same where the pink color denotes an already selected item and grey color is the item that is about to be selected with my mouse/key still not released which gives an impression that it is still not yet selected and it is lagging behind. How can I make sure that the grey selection automatically turns to pink irrespective of my mouse/key release.

```<code><ListView x:Name="TestingList"
                              ItemsSource="{x:Bind TestListing.Details}"
                              SelectedItem="{x:Bind TestListing.DefaultSelected,Mode=TwoWay}"
                              SelectionChanged="TestList_SelectionChanged"
                               SelectionMode="Single">
                        <ListView.ItemContainerTransitions>
                            <TransitionCollection/>
                        </ListView.ItemContainerTransitions>
                        <ListView.ItemTemplate>
                            <DataTemplate x:DataType="test:TestingName">
                                <TextBlock Margin="42,5,0,0" Style="{StaticResource TextStyle}"
                                           Text="{x:Bind Name}" TextWrapping="Wrap"/>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
</code>```

Any thoughts?

答:
Whenever, I select my list view item, it's corresponding selected state is lagging behind until my key pad or mouse pointer is released.

I finally understand your question. The behavior you described is default behavior. Please follow my steps to understand the basic principles.

Click the 'Document Outline in visual studio' -> right click your ListView control -> Edit Additional Templates -> Edit Generated Item Container(ItemContainerStyle) -> Edit a Copy

You will get a style of ListViewItem. Find the ListViewItemPresenter in ControlTemplate. You will see PressedBackground="{ThemeResource ListViewItemBackgroundPressed}" and SelectedBackground="{ThemeResource ListViewItemBackgroundSelected}". If you change the PressedBackground to 'ThemeResource ListViewItemBackgroundSelected', it will be that you want.

```<code><Style x:Key="ListViewItemRevealStyle" TargetType="ListViewItem">
......
<Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListViewItem">
                    <ListViewItemPresenter x:Name="Root"  CheckBrush="{ThemeResource ListViewItemCheckBrush}" ContentMargin="{TemplateBinding Padding}" CheckBoxBrush="{ThemeResource ListViewItemCheckBoxBrush}" ContentTransitions="{TemplateBinding ContentTransitions}" CheckMode="{ThemeResource ListViewItemCheckMode}" DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}" DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}" DragBackground="{ThemeResource ListViewItemDragBackground}" DragForeground="{ThemeResource ListViewItemDragForeground}" FocusBorderBrush="{ThemeResource ListViewItemFocusBorderBrush}" FocusVisualMargin="{TemplateBinding FocusVisualMargin}" FocusSecondaryBorderBrush="{ThemeResource ListViewItemFocusSecondaryBorderBrush}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Control.IsTemplateFocusTarget="True"
                                           PressedBackground="{ThemeResource ListViewItemBackgroundPressed}" PlaceholderBackground="{ThemeResource ListViewItemPlaceholderBackground}" PointerOverForeground="{ThemeResource ListViewItemForegroundPointerOver}" PointerOverBackground="{ThemeResource ListViewItemBackgroundPointerOver}" RevealBorderThickness="{ThemeResource ListViewItemRevealBorderThemeThickness}" ReorderHintOffset="{ThemeResource ListViewItemReorderHintThemeOffset}" RevealBorderBrush="{ThemeResource ListViewItemRevealBorderBrush}" RevealBackground="{ThemeResource ListViewItemRevealBackground}" SelectedForeground="{ThemeResource ListViewItemForegroundSelected}" SelectionCheckMarkVisualEnabled="{ThemeResource ListViewItemSelectionCheckMarkVisualEnabled}"
                                           SelectedBackground="{ThemeResource ListViewItemBackgroundSelected}" SelectedPressedBackground="{ThemeResource ListViewItemBackgroundSelectedPressed}" SelectedPointerOverBackground="{ThemeResource ListViewItemBackgroundSelectedPointerOver}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}">
</code>```

Body:
I have a list view with few items. Whenever, I select my list view item, it's corresponding selected state is lagging behind until my key pad or mouse pointer is released. What should be done in order that the selection of item is immediately reflected when I just click on the item irrespective of whether the key/mouse pointer is released. I tried with the basic listview with items and it seems to be a default behavior... Just curious to know if this can be overridden

Attached below the sample image of the same where the pink color denotes an already selected item and grey color is the item that is about to be selected with my mouse/key still not released which gives an impression that it is still not yet selected and it is lagging behind. How can I make sure that the grey selection automatically turns to pink irrespective of my mouse/key release.

<ListView x:Name="TestingList"
                              ItemsSource="{x:Bind TestListing.Details}"
                              SelectedItem="{x:Bind TestListing.DefaultSelected,Mode=TwoWay}"
                              SelectionChanged="TestList_SelectionChanged"
                               SelectionMode="Single">
                        <ListView.ItemContainerTransitions>
                            <TransitionCollection/>
                        </ListView.ItemContainerTransitions>
                        <ListView.ItemTemplate>
                            <DataTemplate x:DataType="test:TestingName">
                                <TextBlock Margin="42,5,0,0" Style="{StaticResource TextStyle}"
                                           Text="{x:Bind Name}" TextWrapping="Wrap"/>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

Any thoughts?

Body:
Whenever, I select my list view item, it's corresponding selected state is lagging behind until my key pad or mouse pointer is released.

I finally understand your question. The behavior you described is default behavior. Please follow my steps to understand the basic principles.

Click the 'Document Outline in visual studio' -> right click your ListView control -> Edit Additional Templates -> Edit Generated Item Container(ItemContainerStyle) -> Edit a Copy

You will get a style of ListViewItem. Find the ListViewItemPresenter in ControlTemplate. You will see PressedBackground="{ThemeResource ListViewItemBackgroundPressed}" and SelectedBackground="{ThemeResource ListViewItemBackgroundSelected}". If you change the PressedBackground to 'ThemeResource ListViewItemBackgroundSelected', it will be that you want.

<Style x:Key="ListViewItemRevealStyle" TargetType="ListViewItem">
......
<Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListViewItem">
                    <ListViewItemPresenter x:Name="Root"  CheckBrush="{ThemeResource ListViewItemCheckBrush}" ContentMargin="{TemplateBinding Padding}" CheckBoxBrush="{ThemeResource ListViewItemCheckBoxBrush}" ContentTransitions="{TemplateBinding ContentTransitions}" CheckMode="{ThemeResource ListViewItemCheckMode}" DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}" DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}" DragBackground="{ThemeResource ListViewItemDragBackground}" DragForeground="{ThemeResource ListViewItemDragForeground}" FocusBorderBrush="{ThemeResource ListViewItemFocusBorderBrush}" FocusVisualMargin="{TemplateBinding FocusVisualMargin}" FocusSecondaryBorderBrush="{ThemeResource ListViewItemFocusSecondaryBorderBrush}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Control.IsTemplateFocusTarget="True"
                                           PressedBackground="{ThemeResource ListViewItemBackgroundPressed}" PlaceholderBackground="{ThemeResource ListViewItemPlaceholderBackground}" PointerOverForeground="{ThemeResource ListViewItemForegroundPointerOver}" PointerOverBackground="{ThemeResource ListViewItemBackgroundPointerOver}" RevealBorderThickness="{ThemeResource ListViewItemRevealBorderThemeThickness}" ReorderHintOffset="{ThemeResource ListViewItemReorderHintThemeOffset}" RevealBorderBrush="{ThemeResource ListViewItemRevealBorderBrush}" RevealBackground="{ThemeResource ListViewItemRevealBackground}" SelectedForeground="{ThemeResource ListViewItemForegroundSelected}" SelectionCheckMarkVisualEnabled="{ThemeResource ListViewItemSelectionCheckMarkVisualEnabled}"
                                           SelectedBackground="{ThemeResource ListViewItemBackgroundSelected}" SelectedPressedBackground="{ThemeResource ListViewItemBackgroundSelectedPressed}" SelectedPointerOverBackground="{ThemeResource ListViewItemBackgroundSelectedPointerOver}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}">


问:
500 internal server error for large JSON object
I have a website that displays a list of data from a database. I noticed the browser reporting a 500 Internal Server Error, but only in one case. Here's the controller method.

```<code>    [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult GetTouches(FormCollection collection)
    {
        try
        {
            List<p_SiteTouchSummary> pSiteTouchSummarys = ptsRepository.GetPSiteTouchSummarys().ToList();

            return Json(new { wasSuccess = true, pSiteTouchSummarys });
        }
        catch (Exception ex)
        {
            Log.Error(ex, Request.Path, UserHelper.GetEmployeeLogin());
            return Json(new { wasSuccess = false, message = "Error - Search failed" });
        }
    }
</code>```

In debugging I found that it would reach the return, exist the method, and then never return to the javascript file that called it. The browser only takes about 1 second to report the 500 error, and it's not consistent, so I don't think it's a timeout.

Also, I modified the returned list with Take statements, and it works at 150, but not at 200. And if I do a Skip(150).Take(50) that also works. It seems to be that ~200 entries is somehow breaking it, but it's not reporting it being too big to deserialize.

Anyone know what is going on and a good way to fix it?

答:
The JsonResult class does have a property(maxJsonLength),  try changing it:

```<code>    var jsonResult = Json(dataModel,
    JsonRequestBehavior.AllowGet);
    jsonResult.maxJsonLength = int.MaxValue;
    return jsonResult;
</code>```

or

```<code><appSettings>
  <add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>
</code>```

Body:
I have a website that displays a list of data from a database. I noticed the browser reporting a 500 Internal Server Error, but only in one case. Here's the controller method.

    [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult GetTouches(FormCollection collection)
    {
        try
        {
            List<p_SiteTouchSummary> pSiteTouchSummarys = ptsRepository.GetPSiteTouchSummarys().ToList();

            return Json(new { wasSuccess = true, pSiteTouchSummarys });
        }
        catch (Exception ex)
        {
            Log.Error(ex, Request.Path, UserHelper.GetEmployeeLogin());
            return Json(new { wasSuccess = false, message = "Error - Search failed" });
        }
    }

In debugging I found that it would reach the return, exist the method, and then never return to the javascript file that called it. The browser only takes about 1 second to report the 500 error, and it's not consistent, so I don't think it's a timeout.

Also, I modified the returned list with Take statements, and it works at 150, but not at 200. And if I do a Skip(150).Take(50) that also works. It seems to be that ~200 entries is somehow breaking it, but it's not reporting it being too big to deserialize.

Anyone know what is going on and a good way to fix it?

Body:
The JsonResult class does have a property(maxJsonLength),  try changing it:

    var jsonResult = Json(dataModel,
    JsonRequestBehavior.AllowGet);
    jsonResult.maxJsonLength = int.MaxValue;
    return jsonResult;

or

<appSettings>
  <add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>


问:
@objc' can only be applied to an extension of a class , calling extension method from swift to objective c
I am creating string extension like

```<code>@objc extension String {
static func className(_ aClass: AnyClass) -> String {
    return NSStringFromClass(aClass).components(separatedBy: ".").last!
}
    func localize() -> String
{
    return NSLocalizedString(self, comment: "")
}}
</code>```

I am using this in swift like

```<code>btnReferencePhoto.setTitle("ADD REFERENCE PHOTO".localize(), for: .normal)
</code>```

I want to use it in objective c
but I am able to access localize method in objective c file
for that I add @objc  in string extension, but it is giving error

I also tried

答:
You can't use String in Objective-C. Swift structs can't be used in Objective-C.

One solution is to mirror your String extension in an extension to NSString.

```<code>extension String {
    static func className(_ aClass: AnyClass) -> String {
        return NSStringFromClass(aClass).components(separatedBy: ".").last!
    }

    func localize() -> String {
        return NSLocalizedString(self, comment: "")
    }
}

@objc extension NSString {
    static func className(_ aClass: AnyClass) -> NSString {
        let res = String.className(aClass)

        return res as NSString
    }

    func localize() -> NSString {
        let str = self as String

        return str.localize() as NSString
    }
}
</code>```

The NSString extension calls the String extension implementation so you are not replicating the functionality, just the API.

Now in your Objective-C code you can do something like:

```<code>NSString *name = [NSString className:[SomeObjectiveCClass class]];
NSLog(@"name = %@", name);

NSString *localized = [@"test" localize];
</code>```

Body:
I am creating string extension like

@objc extension String {
static func className(_ aClass: AnyClass) -> String {
    return NSStringFromClass(aClass).components(separatedBy: ".").last!
}
    func localize() -> String
{
    return NSLocalizedString(self, comment: "")
}}

I am using this in swift like

btnReferencePhoto.setTitle("ADD REFERENCE PHOTO".localize(), for: .normal)

I want to use it in objective c
but I am able to access localize method in objective c file
for that I add @objc  in string extension, but it is giving error

I also tried

Body:
You can't use String in Objective-C. Swift structs can't be used in Objective-C.

One solution is to mirror your String extension in an extension to NSString.

extension String {
    static func className(_ aClass: AnyClass) -> String {
        return NSStringFromClass(aClass).components(separatedBy: ".").last!
    }

    func localize() -> String {
        return NSLocalizedString(self, comment: "")
    }
}

@objc extension NSString {
    static func className(_ aClass: AnyClass) -> NSString {
        let res = String.className(aClass)

        return res as NSString
    }

    func localize() -> NSString {
        let str = self as String

        return str.localize() as NSString
    }
}

The NSString extension calls the String extension implementation so you are not replicating the functionality, just the API.

Now in your Objective-C code you can do something like:

NSString *name = [NSString className:[SomeObjectiveCClass class]];
NSLog(@"name = %@", name);

NSString *localized = [@"test" localize];


问:
Python create_task does not work in running event loop
I have a simple piece of code driving me crazy for a while. I have posted this question some days ago asking create_task is not working with input. Now I have figured out something related to this. I am running event loop in a separate thread and pushing tasks in it. Very straight forward code.

```<code>import asyncio
import threading

async def printer(message):
    print(f'[printer] {message}')

def loop_runner(loop):
    loop.run_forever()

if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()
    t = threading.Thread(target=loop_runner, args=(event_loop,))
    t.start()

    for m in ['hello', 'world', 'foo', 'bar']:
        print(f'[loop running ?] {event_loop.is_running()}')
        event_loop.create_task(printer(m))
</code>```

Nothing gets printed but these log messages.

```<code>[loop running ?] True
[loop running ?] True
[loop running ?] True
[loop running ?] True
</code>```

Now if I block in event loop thread and let it run after a pause like this.

```<code>def loop_runner(loop):
    time.sleep(1 / 1000)
    loop.run_forever()
</code>```

Everything works and this gets printed

```<code>[loop running ?] False
[loop running ?] False
[loop running ?] False
[loop running ?] False
[printer] hello
[printer] world
[printer] foo
[printer] bar
</code>```

From surface it looks like tasks created in running event loop do not get executed. But why is that?

I have not seen anything regarding this in documentation. In most of the examples I have seen on internet people are creating tasks in loop from other coroutines and awaiting for them. But I think it is legal to use create tasks outside coroutine if you do not want to await for them.

答:
Your code behaves as expected:

It should be noted that calling this (run_forever()) causes our main thread to block
  indefinitely.

(https://tutorialedge.net/python/concurrency/asyncio-event-loops-tutorial/#the-run-forever-method)

see also Asyncio How do you use run_forever? for solutions (loop.call_soon_threadsafe() and asyncio.run_coroutine_threadsafe()).

Body:
I have a simple piece of code driving me crazy for a while. I have posted this question some days ago asking create_task is not working with input. Now I have figured out something related to this. I am running event loop in a separate thread and pushing tasks in it. Very straight forward code.

import asyncio
import threading

async def printer(message):
    print(f'[printer] {message}')

def loop_runner(loop):
    loop.run_forever()

if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()
    t = threading.Thread(target=loop_runner, args=(event_loop,))
    t.start()

    for m in ['hello', 'world', 'foo', 'bar']:
        print(f'[loop running ?] {event_loop.is_running()}')
        event_loop.create_task(printer(m))

Nothing gets printed but these log messages.

[loop running ?] True
[loop running ?] True
[loop running ?] True
[loop running ?] True

Now if I block in event loop thread and let it run after a pause like this.

def loop_runner(loop):
    time.sleep(1 / 1000)
    loop.run_forever()

Everything works and this gets printed

[loop running ?] False
[loop running ?] False
[loop running ?] False
[loop running ?] False
[printer] hello
[printer] world
[printer] foo
[printer] bar

From surface it looks like tasks created in running event loop do not get executed. But why is that?

I have not seen anything regarding this in documentation. In most of the examples I have seen on internet people are creating tasks in loop from other coroutines and awaiting for them. But I think it is legal to use create tasks outside coroutine if you do not want to await for them.


问:
how to store the primary key values to the foreign key at same time of save
I am new to the laravel and trying to store the primary key values of patientid to the foreign key of patient_id in address table

```<code>$patdet = $request->patdet;

foreach ($patdet as $patdets) {
    $pdet = new Patient();

    $pdet->fname = $patdets['fname'];
    $pdet->mname = $patdets['mname'];
    $pdet->lname = $patdets['lname'];
    $pdet->age = $patdets['age'];
    $pdet->blood_group = $patdets['bloodgroup'];
    $pdet->gender = $patdets['gender'];
    $ptid = $pdet->save();
}

$addr = $request->address[0];
$address = new Address;
$address->gps_lat = $addr['gps_lat'];
$address->gps_log = $addr['gps_long'];
$address->house_no = $addr['houseno'];
$address->zipcode = $addr['zip_code'];
$address->street = $addr['street'];
$address->chowk = $addr['chowk'];
$address->city = $addr['city'];
$address->patient_id = $patid->id;
$address->save();
</code>```

I know that $ptid is a local variable and cannot be used in address table,  so how can I store it in address table?

答:
Try the following and ask me if it doesn't work</p>

```<code>foreach($request->patdet as $key => $patdets)
{
    $pdet = new Patient();

    $pdet->fname = $patdets['fname'];
    $pdet->mname =  $patdets['mname'];
    $pdet->lname =  $patdets['lname'];
    $pdet->age   =  $patdets['age'];
    $pdet->blood_group = $patdets['bloodgroup'];
    $pdet->gender  = $patdets['gender'];
    $pdet->save();
    $addr = $request->address[$key];
    if($pdet->id > 0 && !empty($addr)){
        $addrss = new Address;
        $addrss->gps_lat = $addr['gps_lat'];
        $addrss->gps_log = $addr['gps_long'];
        $addrss->house_no  = $addr['houseno'];
        $addrss->zipcode    =  $addr['zip_code'];
        $addrss->street    = $addr['street'];
        $addrss->chowk  = $addr['chowk'];
        $addrss->city   = $addr['city'];
        $addrss->patient_id = $pdet->id;
        $addrss->save();
    }
}
</code>```

Body:
I am new to the laravel and trying to store the primary key values of patientid to the foreign key of patient_id in address table

$patdet = $request->patdet;

foreach ($patdet as $patdets) {
    $pdet = new Patient();

    $pdet->fname = $patdets['fname'];
    $pdet->mname = $patdets['mname'];
    $pdet->lname = $patdets['lname'];
    $pdet->age = $patdets['age'];
    $pdet->blood_group = $patdets['bloodgroup'];
    $pdet->gender = $patdets['gender'];
    $ptid = $pdet->save();
}

$addr = $request->address[0];
$address = new Address;
$address->gps_lat = $addr['gps_lat'];
$address->gps_log = $addr['gps_long'];
$address->house_no = $addr['houseno'];
$address->zipcode = $addr['zip_code'];
$address->street = $addr['street'];
$address->chowk = $addr['chowk'];
$address->city = $addr['city'];
$address->patient_id = $patid->id;
$address->save();

I know that $ptid is a local variable and cannot be used in address table,  so how can I store it in address table?

Body:
Try the following and ask me if it doesn't work

foreach($request->patdet as $key => $patdets)
{
    $pdet = new Patient();

    $pdet->fname = $patdets['fname'];
    $pdet->mname =  $patdets['mname'];
    $pdet->lname =  $patdets['lname'];
    $pdet->age   =  $patdets['age'];
    $pdet->blood_group = $patdets['bloodgroup'];
    $pdet->gender  = $patdets['gender'];
    $pdet->save();
    $addr = $request->address[$key];
    if($pdet->id > 0 && !empty($addr)){
        $addrss = new Address;
        $addrss->gps_lat = $addr['gps_lat'];
        $addrss->gps_log = $addr['gps_long'];
        $addrss->house_no  = $addr['houseno'];
        $addrss->zipcode    =  $addr['zip_code'];
        $addrss->street    = $addr['street'];
        $addrss->chowk  = $addr['chowk'];
        $addrss->city   = $addr['city'];
        $addrss->patient_id = $pdet->id;
        $addrss->save();
    }
}


问:
Compilation error: can't find crate for `core`
I'm using Rust 1.35.0 to try out some Rust examples and I could not get it to compile, as I keep getting the following message:

error[E0463]: can't find crate for `core`
```

<p>I ran <code>rustc --explain E0463</code> and I see the following message:</p>

<pre class="lang-none prettyprint-override"><code>You need to link your code to the relevant crate in order to be able to use it
(through Cargo or the `-L` option of rustc example). Plugins are crates as
well, and you link to them the same way.
</code>```

Here is my Cargo.toml:

```<code>[package]
name = "sensor-node"
version = "0.1.0"
authors = ["joesan <email@gmail.com>"]
edition = "2018"

[dependencies]
dwm1001 = "0.1.0"
panic-halt = "0.2.0"
nb = "0.1.1"
</code>```

Here is my main.rs:

```<code>fn main() {
    let s = String::from("hello");  // s comes into scope

    takes_ownership(s);             // s's value moves into the function...
                                    // ... and so is no longer valid here

    let x = 5;                      // x comes into scope

    makes_copy(x);                  // x would move into the function,
                                    // but i32 is Copy, so it’s okay to still
                                    // use x afterward

} // Here, x goes out of scope, then s. But because s's value was moved, nothing
  // special happens.

fn takes_ownership(some_string: String) { // some_string comes into scope
    println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
  // memory is freed.

fn makes_copy(some_integer: i32) { // some_integer comes into scope
    println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
</code>```

答:
Your code works fine on the Rust playground, so I recommend checking your Rust installation and environment settings.

You may want to use the preconfigured Rust Docker image to run your app. Have Docker installed, then:

docker pull rust
```

<p>Go to your project folder and run:</p>

<pre class="lang-none prettyprint-override"><code>docker run --rm --user "$(id -u)":"$(id -g)" -v "$PWD":/usr/src/myapp -w /usr/src/myapp rust cargo run
</code>```

Output:

hello
5
```

<hr>

<p>For your simple example on a PC, you don't need any of these dependencies:</p>

```[dependencies]
dwm1001 = "0.1.0"
panic-halt = "0.2.0"
nb = "0.1.1"
```

<p>Here are my steps to test your sample on Linux:</p>

<pre class="lang-none prettyprint-override"><code>cargo new hello
cd hello
code .
</code>```

Open main.rs and paste your sample main.rs and save:

fn main() {
    let s = String::from("hello"); // s comes into scope

    takes_ownership(s); // s's value moves into the function...
                        // ... and so is no longer valid here

    let x = 5; // x comes into scope

    makes_copy(x); // x would move into the function,
                   // but i32 is Copy, so it’s okay to still
                   // use x afterward
} // Here, x goes out of scope, then s. But because s's value was moved, nothing
  // special happens.

fn takes_ownership(some_string: String) {
    // some_string comes into scope
    println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
  // memory is freed.

fn makes_copy(some_integer: i32) {
    // some_integer comes into scope
    println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
```

<p>In a terminal inside the <code>hello</code> folder, run:</p>

<pre class="lang-none prettyprint-override"><code>cargo run
</code>```

And the output is good:

hello
5
```

<hr>

<p>This may help:  </p>

<ol>
<li><p>Shell command</p>

<pre class="lang-none prettyprint-override"><code>rustup component list --installed
</code>```

Output:

cargo-x86_64-unknown-linux-gnu
clippy-x86_64-unknown-linux-gnu
rls-x86_64-unknown-linux-gnu
rust-analysis-x86_64-unknown-linux-gnu
rust-docs-x86_64-unknown-linux-gnu
rust-src
rust-std-x86_64-unknown-linux-gnu
rustc-x86_64-unknown-linux-gnu
rustfmt-x86_64-unknown-linux-gnu
```</li>
<li><p>Shell command:</p>

<pre class="lang-none prettyprint-override"><code>rustup show
</code>```

Output:

Default host: x86_64-unknown-linux-gnu

installed toolchains
--------------------

stable-x86_64-unknown-linux-gnu (default)
nightly-x86_64-unknown-linux-gnu

active toolchain
----------------

stable-x86_64-unknown-linux-gnu (default)
rustc 1.35.0 (3c235d560 2019-05-20)
```

Body:
I'm using Rust 1.35.0 to try out some Rust examples and I could not get it to compile, as I keep getting the following message:

error[E0463]: can't find crate for `core`

I ran rustc --explain E0463 and I see the following message:

You need to link your code to the relevant crate in order to be able to use it
(through Cargo or the `-L` option of rustc example). Plugins are crates as
well, and you link to them the same way.

Here is my Cargo.toml:

[package]
name = "sensor-node"
version = "0.1.0"
authors = ["joesan <email@gmail.com>"]
edition = "2018"

[dependencies]
dwm1001 = "0.1.0"
panic-halt = "0.2.0"
nb = "0.1.1"

Here is my main.rs:

fn main() {
    let s = String::from("hello");  // s comes into scope

    takes_ownership(s);             // s's value moves into the function...
                                    // ... and so is no longer valid here

    let x = 5;                      // x comes into scope

    makes_copy(x);                  // x would move into the function,
                                    // but i32 is Copy, so it’s okay to still
                                    // use x afterward

} // Here, x goes out of scope, then s. But because s's value was moved, nothing
  // special happens.

fn takes_ownership(some_string: String) { // some_string comes into scope
    println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
  // memory is freed.

fn makes_copy(some_integer: i32) { // some_integer comes into scope
    println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.

Body:
Your code works fine on the Rust playground, so I recommend checking your Rust installation and environment settings.

You may want to use the preconfigured Rust Docker image to run your app. Have Docker installed, then:

docker pull rust

Go to your project folder and run:

docker run --rm --user "$(id -u)":"$(id -g)" -v "$PWD":/usr/src/myapp -w /usr/src/myapp rust cargo run

Output:

hello
5

For your simple example on a PC, you don't need any of these dependencies:

[dependencies]
dwm1001 = "0.1.0"
panic-halt = "0.2.0"
nb = "0.1.1"

Here are my steps to test your sample on Linux:

cargo new hello
cd hello
code .

Open main.rs and paste your sample main.rs and save:

fn main() {
    let s = String::from("hello"); // s comes into scope

    takes_ownership(s); // s's value moves into the function...
                        // ... and so is no longer valid here

    let x = 5; // x comes into scope

    makes_copy(x); // x would move into the function,
                   // but i32 is Copy, so it’s okay to still
                   // use x afterward
} // Here, x goes out of scope, then s. But because s's value was moved, nothing
  // special happens.

fn takes_ownership(some_string: String) {
    // some_string comes into scope
    println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
  // memory is freed.

fn makes_copy(some_integer: i32) {
    // some_integer comes into scope
    println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.

In a terminal inside the hello folder, run:

cargo run

And the output is good:

hello
5

This may help:

Shell command

rustup component list --installed

Output:

cargo-x86_64-unknown-linux-gnu
clippy-x86_64-unknown-linux-gnu
rls-x86_64-unknown-linux-gnu
rust-analysis-x86_64-unknown-linux-gnu
rust-docs-x86_64-unknown-linux-gnu
rust-src
rust-std-x86_64-unknown-linux-gnu
rustc-x86_64-unknown-linux-gnu
rustfmt-x86_64-unknown-linux-gnu

Shell command:

rustup show

Output:

Default host: x86_64-unknown-linux-gnu

installed toolchains
--------------------

stable-x86_64-unknown-linux-gnu (default)
nightly-x86_64-unknown-linux-gnu

active toolchain
----------------

stable-x86_64-unknown-linux-gnu (default)
rustc 1.35.0 (3c235d560 2019-05-20)


问:
I need to Undo my Redirection URL done by Redirection Plugin
I have used the REDIRECTION plugin and redirected the URL http://localhost/word/wordpress/product-category/sample/ to http://localhost/word/wordpress/sample/. The first thing it redirects all my product category page to destination URL. So, I need to undo this. But I couldn't find a solution for these. Kindly Suggest me some ideas.

I had tried to remove the redirects line from .htaccess, but nothing happened.

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /word/wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /word/wordpress/index.php [L]
</IfModule>
</code>```

END WordPress

If I remove the redirect lines, it displays like,

Object not found!
       The requested URL was not found on this server. The link on the
       referring page seems to be wrong or outdated. Please inform the author
       of that page about the error.

If you think this is a server error, please contact the webmaster.

Error 404

localhost

Apache/2.4.34 (Win32) OpenSSL/1.0.2o PHP/7.1.20

答: You can just deactivate the REDIRECTION plugin, which you are using it will work as like earlier.</p>

Body:
I have used the REDIRECTION plugin and redirected the URL http://localhost/word/wordpress/product-category/sample/ to http://localhost/word/wordpress/sample/. The first thing it redirects all my product category page to destination URL. So, I need to undo this. But I couldn't find a solution for these. Kindly Suggest me some ideas.

I had tried to remove the redirects line from .htaccess, but nothing happened.

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /word/wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /word/wordpress/index.php [L]
</IfModule>

END WordPress

If I remove the redirect lines, it displays like,

Object not found!
       The requested URL was not found on this server. The link on the
       referring page seems to be wrong or outdated. Please inform the author
       of that page about the error.

If you think this is a server error, please contact the webmaster.

Error 404

localhost

Apache/2.4.34 (Win32) OpenSSL/1.0.2o PHP/7.1.20


问:
PHP 5 second countdown (CLI, not JavaScript)
I am writing a PHP CLI (command line) script that will do some irreversible damage if it is run by accident. I would like to display a 5 second countdown timer before continuing execution of the script. How can I do this with PHP?</p>

答:
Even if I 1000% agree with jnpcl's comment stating to ask for confirmation instead of showing a countdown, here is a tested solution on Windows command line (hope it will work on *nix systems):</p>

```<code><?php

echo "countdown:";

for($i = 5; $i > 0; $i--)
{
  echo $i;
  sleep(1);
  echo chr(8); // backspace
}

echo "0\nkaboom!";
</code>```

Body:
Even if I 1000% agree with jnpcl's comment stating to ask for confirmation instead of showing a countdown, here is a tested solution on Windows command line (hope it will work on *nix systems):

<?php

echo "countdown:";

for($i = 5; $i > 0; $i--)
{
  echo $i;
  sleep(1);
  echo chr(8); // backspace
}

echo "0\nkaboom!";


问:
How does the value event work on updates with Firebase listeners?
Do event listeners guarantee that all data ever written to a path will be delivered to the client eventually?
For instance if I have a game client that pushes moves to the same path one after the other will the listening client receive all updates?
What would happen in this situation: client A pushes move 1 to game1/user1/move_data which client B is listening on; client A then immediately pushes another move updating the value at game1/user1/move_data.
Will the listening client be guaranteed to receive all moves pushed?

Currently I have a system that creates a new path per move and then I am calling single listeners on each move as each client reaches that move in it's state. It doesn't seem efficient as if the client A receives the most recent move that client B has made then client A begins listening on a path that doesn't exist yet.

The below quotes are from this link: https://firebase.google.com/docs/database/admin/retrieve-data

"The value event is used to read a static snapshot of the contents at a given database path, as they existed at the time of the read event. It is triggered once with the initial data and again every time the data changes. The event callback is passed a snapshot containing all data at that location, including child data. In the code example above, value returned all of the blog posts in your app. Everytime a new blog post is added, the callback function will return all of the posts."

The part about as they existed at the time of the read event causes me to think that if a listener is on a path then the client will receive all values ever on that path eventually.

There is also this line from the guarantees section which I am struggling to decipher:

"Value events are always triggered last and are guaranteed to contain updates from any other events which occurred before that snapshot was taken."

I am working with a language that does not have a Google based sdk and am asking this question, so I can further assess Firebases' suitability for my uses.

答:
try to this code to get update value from firebase database:- </p>

```<code> mFirebaseInstance = FirebaseDatabase.getInstance();
    mFirebaseDatabase = mFirebaseInstance.getReference();

    mFirebaseDatabase.child("new_title").setValue("Realtime Database");
    mFirebaseDatabase.child("new_title").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String appTitle = dataSnapshot.getValue().toString();
            Log.e("Hey", appTitle);
            title.setText(appTitle);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e("Hey", "Failed to read app title value.", error.toException());
        }
    });
</code>```

Body:
try to this code to get update value from firebase database:-

 mFirebaseInstance = FirebaseDatabase.getInstance();
    mFirebaseDatabase = mFirebaseInstance.getReference();

    mFirebaseDatabase.child("new_title").setValue("Realtime Database");
    mFirebaseDatabase.child("new_title").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String appTitle = dataSnapshot.getValue().toString();
            Log.e("Hey", appTitle);
            title.setText(appTitle);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e("Hey", "Failed to read app title value.", error.toException());
        }
    });


问:
Update table1.Col1 with Table2.Col1 when some charter in column match
I have two tables, I want to update Col1 in Tbl1 with Col1 in Tbl2. However I want to update for rows where only some characters of Col2.Tbl1 match with Col2.Tbl2

Table 1

```<code>PK  Col1    Col2
1   NULL    abc123xyz
2   NULL    3da234oaz
3   NULL    dbc567gyz
4   NULL    agc890hyz
5   NULL    adc012jyz
</code>```

Table 2

```<code>PK  Col1    Col2
1   001     123
2   002     234
3   003     567
4   004     890
5   005     012
</code>```

Current query:

```<code>Update A
set A.Col1 = B.Col1
from Table 1 A, Table 2 B
where A.Col2 like %B.Col1%
</code>```

But it didn't work.

答:
Try this</p>

```<code>Update A
set
A.Col1 = B.Col1
from
Table 1 A, Table 2 B
where
A.Col2 like '%' + B.Col1 + '%'
</code>```

Body:
I have two tables, I want to update Col1 in Tbl1 with Col1 in Tbl2. However I want to update for rows where only some characters of Col2.Tbl1 match with Col2.Tbl2

Table 1

PK  Col1    Col2
1   NULL    abc123xyz
2   NULL    3da234oaz
3   NULL    dbc567gyz
4   NULL    agc890hyz
5   NULL    adc012jyz

Table 2

PK  Col1    Col2
1   001     123
2   002     234
3   003     567
4   004     890
5   005     012

Current query:

Update A
set A.Col1 = B.Col1
from Table 1 A, Table 2 B
where A.Col2 like %B.Col1%

But it didn't work.

Body:
Try this

Update A
set
A.Col1 = B.Col1
from
Table 1 A, Table 2 B
where
A.Col2 like '%' + B.Col1 + '%'


问:
Selenium Duplicate Elements marked with ==$0
How to handle duplicate elements in selenium, where duplicate elements comes marked with ==$0 ?

Go to www.google.com and search for google search button, I have tried iterator and creating list, but, is this correct way of handling ==$0

```<code>driver.findElements(By.xpath("//input[@aria-label='Google Search']"));
</code>```

I want to select second element.

答:
The visible button that you would like to click is descendant of the div with "FPdoLc VlcLAe" class so you can select it with

```<code>driver.findElements(By.xpath("//div[@class='FPdoLc VlcLAe']//input[@name='btnK']"));
</code>```

The invisible one is descendant of a div that has class = "VlcLAe" but no "FPdoLc" so that's the difference.

Body:
How to handle duplicate elements in selenium, where duplicate elements comes marked with ==$0 ?

Go to www.google.com and search for google search button, I have tried iterator and creating list, but, is this correct way of handling ==$0

driver.findElements(By.xpath("//input[@aria-label='Google Search']"));

I want to select second element.

Body:
The visible button that you would like to click is descendant of the div with "FPdoLc VlcLAe" class so you can select it with

driver.findElements(By.xpath("//div[@class='FPdoLc VlcLAe']//input[@name='btnK']"));

The invisible one is descendant of a div that has class = "VlcLAe" but no "FPdoLc" so that's the difference.


问:
How to swap text based on patterns at once with sed?
Suppose I have 'abbc' string and I want to replace:

ab -> bc

bc -> ab

If I try two replaces the result is not what I want:

```<code>echo 'abbc' | sed 's/ab/bc/g;s/bc/ab/g'
abab
</code>```

So what sed command can I use to replace like below?

```<code>echo abbc | sed SED_COMMAND
bcab
</code>```

EDIT:
Actually the text could have more than 2 patterns and I don't know how many replaces I will need. Since there was a answer saying that sed is a stream editor and its replaces are greedily I think that I will need to use some script language for that.

答:
May be a simpler approach for single pattern occurrence you can try as below:
  echo 'abbc' | sed 's/ab/bc/;s/bc/ab/2'

My output:

```<code> ~# echo 'abbc' | sed 's/ab/bc/;s/bc/ab/2'
 bcab
</code>```

For multiple occurrences of pattern:

```<code>sed 's/\(ab\)\(bc\)/\2\1/g'
</code>```

Example

```<code>~# cat try.txt
abbc abbc abbc
bcab abbc bcab
abbc abbc bcab

~# sed 's/\(ab\)\(bc\)/\2\1/g' try.txt
bcab bcab bcab
bcab bcab bcab
bcab bcab bcab
</code>```

Hope this helps !!

Body:
Suppose I have 'abbc' string and I want to replace:

ab -> bc

bc -> ab

If I try two replaces the result is not what I want:

echo 'abbc' | sed 's/ab/bc/g;s/bc/ab/g'
abab

So what sed command can I use to replace like below?

echo abbc | sed SED_COMMAND
bcab

EDIT:
Actually the text could have more than 2 patterns and I don't know how many replaces I will need. Since there was a answer saying that sed is a stream editor and its replaces are greedily I think that I will need to use some script language for that.

Body:
May be a simpler approach for single pattern occurrence you can try as below:
  echo 'abbc' | sed 's/ab/bc/;s/bc/ab/2'

My output:

 ~# echo 'abbc' | sed 's/ab/bc/;s/bc/ab/2'
 bcab

For multiple occurrences of pattern:

sed 's/\(ab\)\(bc\)/\2\1/g'

Example

~# cat try.txt
abbc abbc abbc
bcab abbc bcab
abbc abbc bcab

~# sed 's/\(ab\)\(bc\)/\2\1/g' try.txt
bcab bcab bcab
bcab bcab bcab
bcab bcab bcab

Hope this helps !!


问:
Have I converted this php sample for Facebook authentication correctly into c#?
I'm trying to write a c# version of some php sample code for Facebook authentication which I found here: http://developers.facebook.com/docs/guides/web/ The php in the example is:

```<code>define('YOUR_APP_ID', 'your app id ');
define('YOUR_APP_SECRET', 'your app secret');

function get_facebook_cookie($app_id, $app_secret) {
  $args = array();
  parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
  ksort($args);
  $payload = '';
  foreach ($args as $key => $value) {
    if ($key != 'sig') {
      $payload .= $key . '=' . $value;
    }
  }
  if (md5($payload . $app_secret) != $args['sig']) {
    return null;
  }
  return $args;
}
</code>```

And my C# version is:

```<code>private bool CheckFacebookAuthentication()
{
    var appSecret = "??????????";
    var appId = "?????";
    var cookie = Request.Cookies["fbs_" + appId];

    var payload = "";
    foreach (var key in cookie.Values.AllKeys.OrderBy(x => x))
    {
        if (key != "sig")
        {
            payload += key.Trim("\"".ToCharArray()) + "=" + cookie.Values[key].Trim("\"".ToCharArray());
        }
    }

    if (cookie.Values["sig"] == FormsAuthentication.HashPasswordForStoringInConfigFile(payload + appSecret, "md5"))
    {
        return true;
    }
    return false;
}
</code>```

I appreciate that my c# version is not doing quite the same thing as the php i.e. it is just checking that the signature is valid and returning a boolean indicating this; whereas the php is returning an array if it is valid.

But the issue I have is that my c# version is not validating cookies that I would expect to be valid.  My experience of php is limited, so I expect I have misinterpreted something from the php example when writing my c# version.

Is there anything obviously wrong with my c# interpretation of this php?

答:
I would say it is not the corresponding translation. As far as I can see it boils down to this line:

```<code>parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
</code>```

Here in PHP the cookie string is trimmed by removing any '\' or '"' character (check the php manual for trim(...)) and then parsed whereas in C# you are currently trimming each value and key individually, try removing this.

Body:
I'm trying to write a c# version of some php sample code for Facebook authentication which I found here: http://developers.facebook.com/docs/guides/web/ The php in the example is:

define('YOUR_APP_ID', 'your app id ');
define('YOUR_APP_SECRET', 'your app secret');

function get_facebook_cookie($app_id, $app_secret) {
  $args = array();
  parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
  ksort($args);
  $payload = '';
  foreach ($args as $key => $value) {
    if ($key != 'sig') {
      $payload .= $key . '=' . $value;
    }
  }
  if (md5($payload . $app_secret) != $args['sig']) {
    return null;
  }
  return $args;
}

And my C# version is:

private bool CheckFacebookAuthentication()
{
    var appSecret = "??????????";
    var appId = "?????";
    var cookie = Request.Cookies["fbs_" + appId];

    var payload = "";
    foreach (var key in cookie.Values.AllKeys.OrderBy(x => x))
    {
        if (key != "sig")
        {
            payload += key.Trim("\"".ToCharArray()) + "=" + cookie.Values[key].Trim("\"".ToCharArray());
        }
    }

    if (cookie.Values["sig"] == FormsAuthentication.HashPasswordForStoringInConfigFile(payload + appSecret, "md5"))
    {
        return true;
    }
    return false;
}

I appreciate that my c# version is not doing quite the same thing as the php i.e. it is just checking that the signature is valid and returning a boolean indicating this; whereas the php is returning an array if it is valid.

But the issue I have is that my c# version is not validating cookies that I would expect to be valid.  My experience of php is limited, so I expect I have misinterpreted something from the php example when writing my c# version.

Is there anything obviously wrong with my c# interpretation of this php?

Body:
I would say it is not the corresponding translation. As far as I can see it boils down to this line:

parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);

Here in PHP the cookie string is trimmed by removing any '\' or '"' character (check the php manual for trim(...)) and then parsed whereas in C# you are currently trimming each value and key individually, try removing this.


问:
Copy file from source directory to binary directory using CMake
I'm trying to create a simple project on CLion. It uses CMake to generate Makefiles to build project (or some sort of it)

All I need to is transfer some non-project file (some sort of resource file) to binary directory each time when I run the my code.

That file contains test data and application open it to read them. I tried several ways to do so:

Via file(COPY ...

```<code>file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/input.txt
        DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/input.txt
</code>```

Looking good but it work just once and not recopy file after next run.

Via add_custom_command

OUTPUT version

```<code>add_custom_command(
        OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/input.txt
        COMMAND ${CMAKE_COMMAND} -E copy
                ${CMAKE_CURRENT_SOURCE_DIR}/input.txt
                ${CMAKE_CURRENT_BINARY_DIR}/input.txt)
</code>```

TARGET version

```<code>add_custom_target(foo)
add_custom_command(
        TARGET foo
        COMMAND ${CMAKE_COMMAND} copy
                ${CMAKE_CURRENT_BINARY_DIR}/test/input.txt
                ${CMAKE_SOURCE_DIR})
</code>```

But no one of it work.

What am I doing wrong?

答:
I would suggest TARGET_FILE_DIR if you want the file to be copied to the same folder as your .exe file.

$
  Directory of main file (.exe, .so.1.2, .a).

```<code>add_custom_command(
  TARGET ${PROJECT_NAME} POST_BUILD
  COMMAND ${CMAKE_COMMAND} -E copy
    ${CMAKE_CURRENT_SOURCE_DIR}/input.txt
    $<TARGET_FILE_DIR:${PROJECT_NAME}>)
</code>```

In VS, this cmake script will copy input.txt to the same file as your final exe, no matter it's debug or release.

Body:
I'm trying to create a simple project on CLion. It uses CMake to generate Makefiles to build project (or some sort of it)

All I need to is transfer some non-project file (some sort of resource file) to binary directory each time when I run the my code.

That file contains test data and application open it to read them. I tried several ways to do so:

Via file(COPY ...

file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/input.txt
        DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/input.txt

Looking good but it work just once and not recopy file after next run.

Via add_custom_command

OUTPUT version

add_custom_command(
        OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/input.txt
        COMMAND ${CMAKE_COMMAND} -E copy
                ${CMAKE_CURRENT_SOURCE_DIR}/input.txt
                ${CMAKE_CURRENT_BINARY_DIR}/input.txt)

TARGET version

add_custom_target(foo)
add_custom_command(
        TARGET foo
        COMMAND ${CMAKE_COMMAND} copy
                ${CMAKE_CURRENT_BINARY_DIR}/test/input.txt
                ${CMAKE_SOURCE_DIR})

But no one of it work.

What am I doing wrong?

Body:
I would suggest TARGET_FILE_DIR if you want the file to be copied to the same folder as your .exe file.

$
  Directory of main file (.exe, .so.1.2, .a).

add_custom_command(
  TARGET ${PROJECT_NAME} POST_BUILD
  COMMAND ${CMAKE_COMMAND} -E copy
    ${CMAKE_CURRENT_SOURCE_DIR}/input.txt
    $<TARGET_FILE_DIR:${PROJECT_NAME}>)

In VS, this cmake script will copy input.txt to the same file as your final exe, no matter it's debug or release.


问:
Powershell: How can I use an array or hashtable as an inline lookup
Using Powershell I am calling win32_computersystem. I want to list data about the machine including $_thermalstate - Here is my code

The code looks as though it should work but returns a empty value. I want to create an inline array or hash table that the value $_.thermalstate references.

```<code>Get-WmiObject win32_computersystem | select Name, Model, Caption, @{n="Timezone"; e={$_.currenttimezone}}, Description, DNShostname,Domain,@{n='Domain Role'; E={$_.domainrole}},Roles,Status,@{n='System Type'; e={$_.systemtype}},@{n='Thermal State'; e={$_.thermalstate[@{'3'='safe'}]}}
</code>```

Output

```<code>Name          : MYPC
Model         : Latitude E5470
Caption       : MYPC
Timezone      : 600
Description   : AT/AT COMPATIBLE
DNShostname   : MYPC
Domain        : work.biz
Domain Role   : 1
Roles         : {LM_Workstation, LM_Server, NT}
Status        : OK
System Type   : x64-based PC
Thermal State : Safe
</code>```

答:
Your code looks like you are trying to declare/initialize a hash table while also trying to use thermalstate as a hash array.
If you initialize the hash array first, the code looks like this:</p>

```<code>$h = @{'3'='safe'}; Get-WmiObject win32_computersystem | select Name, Model, Caption, @{n="Timezone"; e={$_.currenttimezone}}, Description, DNShostname,Domain,@{n='Domain Role';E={$_.domainrole}},Roles,Status,@{n='System Type'; e={$_.systemtype}},@{n='Thermal State'; e={$h[$_.thermalstate.toString()]}}
</code>```

Body:
Using Powershell I am calling win32_computersystem. I want to list data about the machine including $_thermalstate - Here is my code

The code looks as though it should work but returns a empty value. I want to create an inline array or hash table that the value $_.thermalstate references.

Get-WmiObject win32_computersystem | select Name, Model, Caption, @{n="Timezone"; e={$_.currenttimezone}}, Description, DNShostname,Domain,@{n='Domain Role'; E={$_.domainrole}},Roles,Status,@{n='System Type'; e={$_.systemtype}},@{n='Thermal State'; e={$_.thermalstate[@{'3'='safe'}]}}

Output

Name          : MYPC
Model         : Latitude E5470
Caption       : MYPC
Timezone      : 600
Description   : AT/AT COMPATIBLE
DNShostname   : MYPC
Domain        : work.biz
Domain Role   : 1
Roles         : {LM_Workstation, LM_Server, NT}
Status        : OK
System Type   : x64-based PC
Thermal State : Safe

Body:
Your code looks like you are trying to declare/initialize a hash table while also trying to use thermalstate as a hash array.
If you initialize the hash array first, the code looks like this:

$h = @{'3'='safe'}; Get-WmiObject win32_computersystem | select Name, Model, Caption, @{n="Timezone"; e={$_.currenttimezone}}, Description, DNShostname,Domain,@{n='Domain Role';E={$_.domainrole}},Roles,Status,@{n='System Type'; e={$_.systemtype}},@{n='Thermal State'; e={$h[$_.thermalstate.toString()]}}


问:
Errors Logcat Android Studio App No Longer Runs
Working on a photo app to practice in Android studio. I have been messing around with taking photo's and sorting them by date, tag, and geolocation. My code was working two days ago now whenever I attach my phone to computer Logcat blows up and my app won't even run just crashes. A number of classes I have never coded are appearing as errors in my code now like, Handler/Looper/HandlerThread?

This is the only error I can understand so far from my Logcat:

```<code>2019-02-23 09:37:38.014 4066-4066/? E/SportWatchProviderService: You need to install SAccessory package to use this application.
2019-02-23 09:37:38.019 4066-4116/? E/SAAgent: SA_SDK_ERROR: Binding to accessory framework failed
    com.samsung.android.sdk.accessory.b: Is the Samsung Accessory Service Framework installed?!
        at com.samsung.android.sdk.accessory.SAAdapter.a(Unknown Source:174)
        at com.samsung.android.sdk.accessory.SAAgent.a(Unknown Source:2)
        at com.samsung.android.sdk.accessory.SAAgent$a.handleMessage(Unknown Source:33)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.os.HandlerThread.run(HandlerThread.java:65)
2019-02-23 09:37:38.025 4066-4066/? E/SASdkConfig: Accessory Framework Not installed
2019-02-23 09:37:38.026 4066-4066/? E/SAAgent: SA_SDK_ERROR: exception: Accessory Framework Not installed
2019-02-23 09:37:38.026 4066-4066/? E/SAAgent: SA_SDK_ERROR: Samsung Accessory SDK cannot be initialized
</code>```

答:
If this relates to the Samsung Accessory Protocol, I had the same error:

```<code>com.samsung.android.sdk.accessory.b: Is the Samsung Accessory Service Framework installed?!
</code>```

In my case it was due to Proguard obfuscating everything in the namespace com.samsung.

As a fix, I added the following to my proguard file:

```<code>-keep class com.samsung.** { *; }
</code>```

You could be more specific with this, but for this issue just know you will need to keep more than just com.samsung.android.** as there are other namespaces needing to be kept for the SAP registration to suceed, such as com.samsung.api.

Body:
Working on a photo app to practice in Android studio. I have been messing around with taking photo's and sorting them by date, tag, and geolocation. My code was working two days ago now whenever I attach my phone to computer Logcat blows up and my app won't even run just crashes. A number of classes I have never coded are appearing as errors in my code now like, Handler/Looper/HandlerThread?

This is the only error I can understand so far from my Logcat:

2019-02-23 09:37:38.014 4066-4066/? E/SportWatchProviderService: You need to install SAccessory package to use this application.
2019-02-23 09:37:38.019 4066-4116/? E/SAAgent: SA_SDK_ERROR: Binding to accessory framework failed
    com.samsung.android.sdk.accessory.b: Is the Samsung Accessory Service Framework installed?!
        at com.samsung.android.sdk.accessory.SAAdapter.a(Unknown Source:174)
        at com.samsung.android.sdk.accessory.SAAgent.a(Unknown Source:2)
        at com.samsung.android.sdk.accessory.SAAgent$a.handleMessage(Unknown Source:33)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.os.HandlerThread.run(HandlerThread.java:65)
2019-02-23 09:37:38.025 4066-4066/? E/SASdkConfig: Accessory Framework Not installed
2019-02-23 09:37:38.026 4066-4066/? E/SAAgent: SA_SDK_ERROR: exception: Accessory Framework Not installed
2019-02-23 09:37:38.026 4066-4066/? E/SAAgent: SA_SDK_ERROR: Samsung Accessory SDK cannot be initialized

Body:
If this relates to the Samsung Accessory Protocol, I had the same error:

com.samsung.android.sdk.accessory.b: Is the Samsung Accessory Service Framework installed?!

In my case it was due to Proguard obfuscating everything in the namespace com.samsung.

As a fix, I added the following to my proguard file:

-keep class com.samsung.** { *; }

You could be more specific with this, but for this issue just know you will need to keep more than just com.samsung.android.** as there are other namespaces needing to be kept for the SAP registration to suceed, such as com.samsung.api.


问:
Kotlin - How do I concatenate a String to an Int value?
A very basic question, What is the right approach to concatenate String to an Int?

I'm new in Kotlin and want to print an Integer value preceding with String and getting the following error message.

```<code>for (i in 15 downTo 10){
  print(i + " "); //error: None of the following function can be called with the argument supplied:
  print(i); //It's Working but I need some space after the integer value.
}
</code>```

Expected Outcome

15 14 13 12 11 10

答:
Just cast to String:</p>

```<code>for (i in 15 downTo 10){
  print(i.toString() + " ");
}
</code>```

Body:
A very basic question, What is the right approach to concatenate String to an Int?

I'm new in Kotlin and want to print an Integer value preceding with String and getting the following error message.

for (i in 15 downTo 10){
  print(i + " "); //error: None of the following function can be called with the argument supplied:
  print(i); //It's Working but I need some space after the integer value.
}

Expected Outcome

15 14 13 12 11 10

Body:
Just cast to String:

for (i in 15 downTo 10){
  print(i.toString() + " ");
}


问:
unable to connect to sql server using jmeter 5.1.1 version
I'm unable to connect jmeter with sqlserver. Below mentioned are my configurations

JDBC Connection Configuration

JDBC Request

Results

NOTE

1)My firewall is off

2)I have added mysql-connector-java-5.1.47-bin in lib folder

3) I'm using Jmeter 5.1.1 version

Please help me to get out of this. Thanks in advance..

答:
This is mostly a Network problem linked to you Database. Just be sure you do not use Localhost in your Jmeter (If you do use 127.0.0.1 instead). If that is ok then the Jmeter configuration is correct.

Check #bind-address=127.0.0.1 in your mysql files.

Another thing to try is removing this attribute from the (Derby DB) resource tag
: validationQuery="select 1"


问:
Can one filter the events that are logged by Firebug?
Is it possible to filter which events are logged by the Log Events option in Firebug?

答:
Use the search bar towards the top right in the console? Works for me on FF4.

See also: How to debug JavaScript/jQuery event bindings with Firebug (or similar tool)


问:
Single Sign-On with spring session ID cookie?
I'm  working on an project that implements user authentication through Spring Security using a spring session ID stored in a cookie on the client's browser. There's no authentication server, the same server manages authentication and the whole app as a monolith.

So we are now in the need of implementing SSO with a third party system, so far everything I've read on the matter requires OAuth or some other implementation of token based authentication that supports an external identity provider. I would prefer not to migrate the authentication strategy as we are kinda on the clock.

I work on another project that has OAuth authentication so I'm not new on that topic (though not really an expert either).

Can someone throw some light on this? I just need to know if it is possible or there's no other way to migrate the authentication strategy.

答: Cookie based SSO is only possible (in an easy way) if you are using a so called 'domain cookie'. Technically all applications need to share the same 'cookie domain' then. However from security point of view this is highly discouraged, due to cookie hijacking being possible.</p>