问:
Trying to create a parent-child hierarchy in sql server
I have a data set that is sorted by account key. when coming to certain rows which have NULL as group key, it should add current account key as a parent key for all above rows which have NULL as parentkey. So when coming to the next row with null as group key, you would set the current account key as parent key for all rows above that have parent key like null.

I have tried to copy a dataset below as mark down table but as you see I can't say I succeeded very well, but I hope some of you can help with the t-sql syntax to create a parent-child hierarchy of this

```<code>| AccountKey | ParentKey | GroupKey | AccountNumber | Cat      | LineName                     | LineId                               |
|------------|-----------|----------|---------------|----------|------------------------------|--------------------------------------|
| 1          | NULL      | 7        | 3040          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 2          | NULL      | 7        | 3041          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 3          | NULL      | 7        | 3081          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 4          | NULL      | 7        | 3082          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 5          | NULL      | 7        | 3083          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 6          | NULL      | 7        | 3085          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 7          | NULL      | 7        | 3086          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 8          | NULL      | 7        | 3087          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 9          | NULL      | 2        | 3000          | Account  | Salg annet                   | 26AC86B2-0667-463E-B994-11A5C6D519A6 |
| 10         | NULL      | 2        | 3010          | Account  | Salg annet                   | 26AC86B2-0667-463E-B994-11A5C6D519A6 |
| 11         | NULL      | 2        | 3020          | Account  | Salg annet                   | 26AC86B2-0667-463E-B994-11A5C6D519A6 |
| 12         | NULL      | 2        | 3030          | Account  | Salg annet                   | 26AC86B2-0667-463E-B994-11A5C6D519A6 |
| 41         | NULL      | 11       | 3050          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 42         | NULL      | 11       | 3600          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 43         | NULL      | 11       | 3601          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 44         | NULL      | 11       | 3610          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 45         | NULL      | 11       | 3615          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 46         | NULL      | 11       | 3690          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 47         | NULL      | 11       | 3691          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 48         | NULL      | 11       | 3701          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 49         | NULL      | 11       | 3705          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 50         | NULL      | 11       | 3720          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 67         | NULL      | NULL     | NULL          | SubTotal | Sum inntekter                | NULL                                 |
| 68         | NULL      | 13       | 4120          | Account  | Innkjøp smolt/settefisk/rogn | F9EE1CE4-22C7-400B-BC9D-E2D3214A5113 |
| 69         | NULL      | 10       | 4010          | Account  | Vareforbruk fôr              | 04E63B6D-CA54-423D-8A44-A4ED99861975 |
| 70         | NULL      | 10       | 4901          | Account  | Vareforbruk fôr              | 04E63B6D-CA54-423D-8A44-A4ED99861975 |
| 71         | NULL      | 3        | 4000          | Account  | Andre varekostnader          | DB7FABAB-7ABA-4B9A-9720-1B538D99B3C8 |
| 72         | NULL      | 3        | 4020          | Account  | Andre varekostnader          | DB7FABAB-7ABA-4B9A-9720-1B538D99B3C8 |
| 73         | NULL      | 3        | 4030          | Account  | Andre varekostnader          | DB7FABAB-7ABA-4B9A-9720-1B538D99B3C8 |
| 133        | NULL      | 8        | 4925          | Account  | Beholdningsendring fisk      | A8BA6F19-A792-44A1-AA21-8F79DB24D224 |
| 134        | NULL      | NULL     | NULL          | SubTotal | Sum varekostnader            | NULL                                 |
| 135        | NULL      | 12       | 5000          | Account  | Lønn og sosiale kostnader    | 5C475EDE-3731-4D39-B11A-C8EE72213FF6 |
| 136        | NULL      | 12       | 5001          | Account  | Lønn og sosiale kostnader    | 5C475EDE-3731-4D39-B11A-C8EE72213FF6 |
| 137        | NULL      | 12       | 5005          | Account  | Lønn og sosiale kostnader    | 5C475EDE-3731-4D39-B11A-C8EE72213FF6 |
| 138        | NULL      | 12       | 5009          | Account  | Lønn og sosiale kostnader    | 5C475EDE-3731-4D39-B11A-C8EE72213FF6 |
| 263        | NULL      | NULL     | NULL          | SubTotal | Sum lønnskostnadern          | NULL                                 |
| 462        | NULL      | NULL     | NULL          | SubTotal | RESULTAT ETTER SKATT         | NULL
</code>```

答:
If I understood your question you could use:

```<code>SELECT  Accountkey, ParentKey,GroupKey,AccountNumber, NEW_PARID
FROM (
             SELECT Accountkey, ParentKey,GroupKey,AccountNumber, AccountKey AS NEW_PARID, LAG(ACCOUNTKEY) OVER (ORDER BY Accountkey) AS PREC
             FROM MYT
             WHERE  GroupKey IS NULL
             UNION ALL
             SELECT A.Accountkey, A.ParentKey,A.GroupKey,A.AccountNumber, B.Accountkey AS NEW_PARID, B.PREC
             FROM MYT A
             INNER JOIN ( SELECT Accountkey, ParentKey,GroupKey,AccountNumber, AccountKey AS NEW_PARID, LAG(ACCOUNTKEY) OVER (ORDER BY Accountkey) AS PREC
             FROM MYT
             WHERE  GroupKey IS NULL) B ON A.Accountkey < B.Accountkey  AND (B.PREC IS NULL OR B.PREC<A.accountKey)
             WHERE A.GroupKey IS NOT NULL
             AND B.GroupKey IS NULL
) X ORDER BY ACCOUNTKEY
</code>```

You can write it in this way too (it's the same query):

```<code>WITH X AS (SELECT Accountkey, ParentKey,GroupKey,AccountNumber, AccountKey AS NEW_PARID, LAG(ACCOUNTKEY) OVER (ORDER BY Accountkey) AS PREC
             FROM MYT
             WHERE  GroupKey IS NULL)
SELECT X.*
FROM X
UNION ALL
 SELECT A.Accountkey, A.ParentKey,A.GroupKey,A.AccountNumber, X.Accountkey AS NEW_PARID, X.PREC
 FROM MYT A
 INNER JOIN X  ON A.Accountkey < X.Accountkey  AND (X.PREC IS NULL OR X.PREC<A.accountKey)
 WHERE A.GroupKey IS NOT NULL
</code>```

Output (MYT is the name of the table, the new parentid column is NEW_PARID):

```<code>+------------+-----------+----------+---------------+-----------+
| Accountkey | ParentKey | GroupKey | AccountNumber | NEW_PARID |
+------------+-----------+----------+---------------+-----------+
|          1 | NULL      | 7        | 3040          |        67 |
|          2 | NULL      | 7        | 3041          |        67 |
|          3 | NULL      | 7        | 3081          |        67 |
|          4 | NULL      | 7        | 3082          |        67 |
|          5 | NULL      | 7        | 3083          |        67 |
|          6 | NULL      | 7        | 3085          |        67 |
|          7 | NULL      | 7        | 3086          |        67 |
|          8 | NULL      | 7        | 3087          |        67 |
|          9 | NULL      | 2        | 3000          |        67 |
|         10 | NULL      | 2        | 3010          |        67 |
|         11 | NULL      | 2        | 3020          |        67 |
|         12 | NULL      | 2        | 3030          |        67 |
|         41 | NULL      | 11       | 3050          |        67 |
|         42 | NULL      | 11       | 3600          |        67 |
|         43 | NULL      | 11       | 3601          |        67 |
|         44 | NULL      | 11       | 3610          |        67 |
|         45 | NULL      | 11       | 3615          |        67 |
|         46 | NULL      | 11       | 3690          |        67 |
|         47 | NULL      | 11       | 3691          |        67 |
|         48 | NULL      | 11       | 3701          |        67 |
|         49 | NULL      | 11       | 3705          |        67 |
|         50 | NULL      | 11       | 3720          |        67 |
|         67 | NULL      | NULL     | NULL          |        67 |
|         68 | NULL      | 13       | 4120          |       134 |
|         69 | NULL      | 10       | 4010          |       134 |
|         70 | NULL      | 10       | 4901          |       134 |
|         71 | NULL      | 3        | 4000          |       134 |
|         72 | NULL      | 3        | 4020          |       134 |
|         73 | NULL      | 3        | 4030          |       134 |
|        133 | NULL      | 8        | 4925          |       134 |
|        134 | NULL      | NULL     | NULL          |       134 |
|        135 | NULL      | 12       | 5000          |       263 |
|        136 | NULL      | 12       | 5001          |       263 |
|        137 | NULL      | 12       | 5005          |       263 |
|        138 | NULL      | 12       | 5009          |       263 |
|        263 | NULL      | NULL     | NULL          |       263 |
|        462 | NULL      | NULL     | NULL          |       462 |
+------------+-----------+----------+---------------+-----------+
</code>```

Updated 20171221 - for MSSQL 2008
You can try this (but pay attention for performance if you have a large dataset):

```<code> SELECT A.ACCOUNTKEY
    , A.PARENTKEY
    , (SELECT MIN(B.ACCOUNTKEY) FROM MYT B WHERE B.GROUPKEY IS NULL AND A.ACCOUNTKEY<=B.ACCOUNTKEY) AS NEW_PARID
FROM MYT A
/* WHERE A.GROUPKEY IS NOT NULL*/
</code>```

Body:
I have a data set that is sorted by account key. when coming to certain rows which have NULL as group key, it should add current account key as a parent key for all above rows which have NULL as parentkey. So when coming to the next row with null as group key, you would set the current account key as parent key for all rows above that have parent key like null.

I have tried to copy a dataset below as mark down table but as you see I can't say I succeeded very well, but I hope some of you can help with the t-sql syntax to create a parent-child hierarchy of this

| AccountKey | ParentKey | GroupKey | AccountNumber | Cat      | LineName                     | LineId                               |
|------------|-----------|----------|---------------|----------|------------------------------|--------------------------------------|
| 1          | NULL      | 7        | 3040          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 2          | NULL      | 7        | 3041          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 3          | NULL      | 7        | 3081          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 4          | NULL      | 7        | 3082          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 5          | NULL      | 7        | 3083          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 6          | NULL      | 7        | 3085          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 7          | NULL      | 7        | 3086          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 8          | NULL      | 7        | 3087          | Account  | Salg fisk                    | C6BCDFB2-1AAC-4D05-94F1-879CDC615D76 |
| 9          | NULL      | 2        | 3000          | Account  | Salg annet                   | 26AC86B2-0667-463E-B994-11A5C6D519A6 |
| 10         | NULL      | 2        | 3010          | Account  | Salg annet                   | 26AC86B2-0667-463E-B994-11A5C6D519A6 |
| 11         | NULL      | 2        | 3020          | Account  | Salg annet                   | 26AC86B2-0667-463E-B994-11A5C6D519A6 |
| 12         | NULL      | 2        | 3030          | Account  | Salg annet                   | 26AC86B2-0667-463E-B994-11A5C6D519A6 |
| 41         | NULL      | 11       | 3050          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 42         | NULL      | 11       | 3600          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 43         | NULL      | 11       | 3601          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 44         | NULL      | 11       | 3610          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 45         | NULL      | 11       | 3615          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 46         | NULL      | 11       | 3690          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 47         | NULL      | 11       | 3691          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 48         | NULL      | 11       | 3701          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 49         | NULL      | 11       | 3705          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 50         | NULL      | 11       | 3720          | Account  | Andre driftsinntekter        | 65FFB620-AE42-4BE5-A6E7-BF3339AA04DF |
| 67         | NULL      | NULL     | NULL          | SubTotal | Sum inntekter                | NULL                                 |
| 68         | NULL      | 13       | 4120          | Account  | Innkjøp smolt/settefisk/rogn | F9EE1CE4-22C7-400B-BC9D-E2D3214A5113 |
| 69         | NULL      | 10       | 4010          | Account  | Vareforbruk fôr              | 04E63B6D-CA54-423D-8A44-A4ED99861975 |
| 70         | NULL      | 10       | 4901          | Account  | Vareforbruk fôr              | 04E63B6D-CA54-423D-8A44-A4ED99861975 |
| 71         | NULL      | 3        | 4000          | Account  | Andre varekostnader          | DB7FABAB-7ABA-4B9A-9720-1B538D99B3C8 |
| 72         | NULL      | 3        | 4020          | Account  | Andre varekostnader          | DB7FABAB-7ABA-4B9A-9720-1B538D99B3C8 |
| 73         | NULL      | 3        | 4030          | Account  | Andre varekostnader          | DB7FABAB-7ABA-4B9A-9720-1B538D99B3C8 |
| 133        | NULL      | 8        | 4925          | Account  | Beholdningsendring fisk      | A8BA6F19-A792-44A1-AA21-8F79DB24D224 |
| 134        | NULL      | NULL     | NULL          | SubTotal | Sum varekostnader            | NULL                                 |
| 135        | NULL      | 12       | 5000          | Account  | Lønn og sosiale kostnader    | 5C475EDE-3731-4D39-B11A-C8EE72213FF6 |
| 136        | NULL      | 12       | 5001          | Account  | Lønn og sosiale kostnader    | 5C475EDE-3731-4D39-B11A-C8EE72213FF6 |
| 137        | NULL      | 12       | 5005          | Account  | Lønn og sosiale kostnader    | 5C475EDE-3731-4D39-B11A-C8EE72213FF6 |
| 138        | NULL      | 12       | 5009          | Account  | Lønn og sosiale kostnader    | 5C475EDE-3731-4D39-B11A-C8EE72213FF6 |
| 263        | NULL      | NULL     | NULL          | SubTotal | Sum lønnskostnadern          | NULL                                 |
| 462        | NULL      | NULL     | NULL          | SubTotal | RESULTAT ETTER SKATT         | NULL

Body:
If I understood your question you could use:

SELECT  Accountkey, ParentKey,GroupKey,AccountNumber, NEW_PARID
FROM (
             SELECT Accountkey, ParentKey,GroupKey,AccountNumber, AccountKey AS NEW_PARID, LAG(ACCOUNTKEY) OVER (ORDER BY Accountkey) AS PREC
             FROM MYT
             WHERE  GroupKey IS NULL
             UNION ALL
             SELECT A.Accountkey, A.ParentKey,A.GroupKey,A.AccountNumber, B.Accountkey AS NEW_PARID, B.PREC
             FROM MYT A
             INNER JOIN ( SELECT Accountkey, ParentKey,GroupKey,AccountNumber, AccountKey AS NEW_PARID, LAG(ACCOUNTKEY) OVER (ORDER BY Accountkey) AS PREC
             FROM MYT
             WHERE  GroupKey IS NULL) B ON A.Accountkey < B.Accountkey  AND (B.PREC IS NULL OR B.PREC<A.accountKey)
             WHERE A.GroupKey IS NOT NULL
             AND B.GroupKey IS NULL
) X ORDER BY ACCOUNTKEY

You can write it in this way too (it's the same query):

WITH X AS (SELECT Accountkey, ParentKey,GroupKey,AccountNumber, AccountKey AS NEW_PARID, LAG(ACCOUNTKEY) OVER (ORDER BY Accountkey) AS PREC
             FROM MYT
             WHERE  GroupKey IS NULL)
SELECT X.*
FROM X
UNION ALL
 SELECT A.Accountkey, A.ParentKey,A.GroupKey,A.AccountNumber, X.Accountkey AS NEW_PARID, X.PREC
 FROM MYT A
 INNER JOIN X  ON A.Accountkey < X.Accountkey  AND (X.PREC IS NULL OR X.PREC<A.accountKey)
 WHERE A.GroupKey IS NOT NULL

Output (MYT is the name of the table, the new parentid column is NEW_PARID):

+------------+-----------+----------+---------------+-----------+
| Accountkey | ParentKey | GroupKey | AccountNumber | NEW_PARID |
+------------+-----------+----------+---------------+-----------+
|          1 | NULL      | 7        | 3040          |        67 |
|          2 | NULL      | 7        | 3041          |        67 |
|          3 | NULL      | 7        | 3081          |        67 |
|          4 | NULL      | 7        | 3082          |        67 |
|          5 | NULL      | 7        | 3083          |        67 |
|          6 | NULL      | 7        | 3085          |        67 |
|          7 | NULL      | 7        | 3086          |        67 |
|          8 | NULL      | 7        | 3087          |        67 |
|          9 | NULL      | 2        | 3000          |        67 |
|         10 | NULL      | 2        | 3010          |        67 |
|         11 | NULL      | 2        | 3020          |        67 |
|         12 | NULL      | 2        | 3030          |        67 |
|         41 | NULL      | 11       | 3050          |        67 |
|         42 | NULL      | 11       | 3600          |        67 |
|         43 | NULL      | 11       | 3601          |        67 |
|         44 | NULL      | 11       | 3610          |        67 |
|         45 | NULL      | 11       | 3615          |        67 |
|         46 | NULL      | 11       | 3690          |        67 |
|         47 | NULL      | 11       | 3691          |        67 |
|         48 | NULL      | 11       | 3701          |        67 |
|         49 | NULL      | 11       | 3705          |        67 |
|         50 | NULL      | 11       | 3720          |        67 |
|         67 | NULL      | NULL     | NULL          |        67 |
|         68 | NULL      | 13       | 4120          |       134 |
|         69 | NULL      | 10       | 4010          |       134 |
|         70 | NULL      | 10       | 4901          |       134 |
|         71 | NULL      | 3        | 4000          |       134 |
|         72 | NULL      | 3        | 4020          |       134 |
|         73 | NULL      | 3        | 4030          |       134 |
|        133 | NULL      | 8        | 4925          |       134 |
|        134 | NULL      | NULL     | NULL          |       134 |
|        135 | NULL      | 12       | 5000          |       263 |
|        136 | NULL      | 12       | 5001          |       263 |
|        137 | NULL      | 12       | 5005          |       263 |
|        138 | NULL      | 12       | 5009          |       263 |
|        263 | NULL      | NULL     | NULL          |       263 |
|        462 | NULL      | NULL     | NULL          |       462 |
+------------+-----------+----------+---------------+-----------+

Updated 20171221 - for MSSQL 2008
You can try this (but pay attention for performance if you have a large dataset):

 SELECT A.ACCOUNTKEY
    , A.PARENTKEY
    , (SELECT MIN(B.ACCOUNTKEY) FROM MYT B WHERE B.GROUPKEY IS NULL AND A.ACCOUNTKEY<=B.ACCOUNTKEY) AS NEW_PARID
FROM MYT A
/* WHERE A.GROUPKEY IS NOT NULL*/


来源: stackexchange

问:
sed delete between lines with tree lines
I have several tomcat servers where I want to manage dynamically the context.xml file via some bash scripts and I want to delete resources by using sed. I know how do it but the file is formatted as shown below across several servers for sake of readability I suppose and I can't identify the resource to delete just with this:

sed '/PATTERN-1/,/PATTERN-2/d' context.xml

But on pattern-1 I need to get the second line to substitute part of name attribute as a bash script variable. And I tried several ways as escaping \s or \n

```<code><Context>
  ...
  <Resource
        name="jdbc/EmployeeDB" auth="Container"
        type="javax.sql.DataSource"
        description="Employees Database for HR Applications"
  />
  <Resource
        name="jdbc/SportDB" auth="Container"
        type="javax.sql.DataSource"
        description="Sport Database for HR Applications"
  />
  <Resource
        name="jdbc/BackupDB" auth="Container"
        type="javax.sql.DataSource"
        description="Backup Database for HR Applications"
  />
  ...
</Context>
</code>```

答:
i ended up doing like this

```<code>cat context.xml | sed ':a;N;$!ba;s/<Resource\n/<Resource\ /g;s/ \+/ /gp' | sed -i '/<Resource\ name=\"jdbc\/$2\"/,/\/>/d'
</code>```

The first sed turns

```<code><Resource
       name="jdbc/example"
       ...
/>
</code>```

into

```<code><Resource name="jdbc/example"
       ...
/>
</code>```

with that i can delete between lines with the second sed because i have the "identifier"

ContentLicense: CC BY-SA 3.0

Body:
I have several tomcat servers where I want to manage dynamically the context.xml file via some bash scripts and I want to delete resources by using sed. I know how do it but the file is formatted as shown below across several servers for sake of readability I suppose and I can't identify the resource to delete just with this:

sed '/PATTERN-1/,/PATTERN-2/d' context.xml

But on pattern-1 I need to get the second line to substitute part of name attribute as a bash script variable. And I tried several ways as escaping \s or \n

<Context>
  ...
  <Resource
        name="jdbc/EmployeeDB" auth="Container"
        type="javax.sql.DataSource"
        description="Employees Database for HR Applications"
  />
  <Resource
        name="jdbc/SportDB" auth="Container"
        type="javax.sql.DataSource"
        description="Sport Database for HR Applications"
  />
  <Resource
        name="jdbc/BackupDB" auth="Container"
        type="javax.sql.DataSource"
        description="Backup Database for HR Applications"
  />
  ...
</Context>

Body:
i ended up doing like this

cat context.xml | sed ':a;N;$!ba;s/<Resource\n/<Resource\ /g;s/ \+/ /gp' | sed -i '/<Resource\ name=\"jdbc\/$2\"/,/\/>/d'

The first sed turns

<Resource
       name="jdbc/example"
       ...
/>

into

<Resource name="jdbc/example"
       ...
/>

with that i can delete between lines with the second sed because i have the "identifier"


问:
Get the clicked element ID in javascript
I have a jQuery like :

```<code>jQuery("#id1,#id2").click(function(){
     //do stuff
});
</code>```

I am checking that either id1 or id2 is clicked then do something. But in the function I need to get which ID is clicked.
Can somebody help me in that?

答:
The simpler version is:</p>

```<code>var idClicked = this.id;
</code>```

Body:
I have a jQuery like :

jQuery("#id1,#id2").click(function(){
     //do stuff
});

I am checking that either id1 or id2 is clicked then do something. But in the function I need to get which ID is clicked.
Can somebody help me in that?

Body:
The simpler version is:

var idClicked = this.id;


问:
Python 3 pymysql insert with null datetime field
I have a table with name as a varchar(50) and ctime as a datetime.
If I execute in MySQL insert into atable (name, ctime) values ('aname', NULL) it works.

In Python 3 I've tried the following approaches (all generating errors):

```<code>conn = pymysql.connect(host='ahost', port=3306, user='auser', passwd='apasswd', db='adb')

cur = conn.cursor()
</code>```

[Attempt 1]

```<code>cur.execute("insert into atable (name, ctime) values (%s, '%s'), ('aname', '')

pymysql.err.InternalError: (1292, "Incorrect datetime value: '' for column 'ctime' at row 1")
</code>```

[Attempt 2]

```<code>cur.execute("insert into atable (name, ctime) values (%s, %s), ('aname', '')

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1")
</code>```

[Attempt 3]

```<code>cur.execute("insert into atable (name, ctime) values (%s, '%s'), ('aname', None)

pymysql.err.InternalError: (1292, "Incorrect datetime value: 'None' for column 'ctime' at row 1")
</code>```

[Attempt 4]

```<code>cur.execute("insert into atable (name, ctime) values (%s, %s), ('aname', None)

pymysql.err.InternalError: (1054, "Unknown column 'None' in 'field list'")
</code>```

Any assistance would be appreciated.

答:
In this case You don't need to pass ctime, just the values that You actually set.

```<code>sql = "INSERT INTO `atable` (`name`) VALUES (%s)"
rows = cursor.execute(sql, ('aname2'))
print("insert:", rows)
</code>```

I run the code and works as expected, full code:

```<code>import pymysql

def main():
    try:
        conn = pymysql.connect(
            host='localhost', user='@@', password='##',
            db='dn_name'
        )
        with conn.cursor() as cursor:
            sql = "INSERT INTO `atable` (`name`) VALUES (%s)"
            rows = cursor.execute(sql, ('aname2'))
            print("insert:", rows)

    except Exception as e:
        conn.rollback()
        raise e
    else:
        conn.commit()
    finally:
        conn.close()

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

Body:
I have a table with name as a varchar(50) and ctime as a datetime.
If I execute in MySQL insert into atable (name, ctime) values ('aname', NULL) it works.

In Python 3 I've tried the following approaches (all generating errors):

conn = pymysql.connect(host='ahost', port=3306, user='auser', passwd='apasswd', db='adb')

cur = conn.cursor()

[Attempt 1]

cur.execute("insert into atable (name, ctime) values (%s, '%s'), ('aname', '')

pymysql.err.InternalError: (1292, "Incorrect datetime value: '' for column 'ctime' at row 1")

[Attempt 2]

cur.execute("insert into atable (name, ctime) values (%s, %s), ('aname', '')

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1")

[Attempt 3]

cur.execute("insert into atable (name, ctime) values (%s, '%s'), ('aname', None)

pymysql.err.InternalError: (1292, "Incorrect datetime value: 'None' for column 'ctime' at row 1")

[Attempt 4]

cur.execute("insert into atable (name, ctime) values (%s, %s), ('aname', None)

pymysql.err.InternalError: (1054, "Unknown column 'None' in 'field list'")

Any assistance would be appreciated.

Body:
In this case You don't need to pass ctime, just the values that You actually set.

sql = "INSERT INTO `atable` (`name`) VALUES (%s)"
rows = cursor.execute(sql, ('aname2'))
print("insert:", rows)

I run the code and works as expected, full code:

import pymysql

def main():
    try:
        conn = pymysql.connect(
            host='localhost', user='@@', password='##',
            db='dn_name'
        )
        with conn.cursor() as cursor:
            sql = "INSERT INTO `atable` (`name`) VALUES (%s)"
            rows = cursor.execute(sql, ('aname2'))
            print("insert:", rows)

    except Exception as e:
        conn.rollback()
        raise e
    else:
        conn.commit()
    finally:
        conn.close()

if __name__ == '__main__':
    main()


问:
How to add CoverPage and TOC while generating document programmatically
Hi I am trying to generate report programmatically from EA using C#.

```<code>Project.RunReport
</code>```

By referring this.

But the problem is RunReport allows to choose only main template by passing the parameters

PackageGUID: String - the GUID of the Package
or master document to run the report on

TemplateName: String - the
document report template to use; if the PackageGUID has a stereotype
of MasterDocument, the template is not required

FileName: String - the
file name and path to store the generated report; the file extension
specified will determine the format of the generated document - for
example, RTF, PDF

How to set coverPage and TOC using this RunReport API call..?

答:
Your report should already have a Cover page and <s>TOC defined with it</s> Seems like you will need to use DocumentGenerator or add the TOC Manually after the document is generated as you cannot insert a TOC in a Report Template.

If you want to define those separately, use the DocumentGenerator facility

Document Generator Reference

Body:
Hi I am trying to generate report programmatically from EA using C#.

Project.RunReport

By referring this.

But the problem is RunReport allows to choose only main template by passing the parameters

PackageGUID: String - the GUID of the Package
or master document to run the report on

TemplateName: String - the
document report template to use; if the PackageGUID has a stereotype
of MasterDocument, the template is not required

FileName: String - the
file name and path to store the generated report; the file extension
specified will determine the format of the generated document - for
example, RTF, PDF

How to set coverPage and TOC using this RunReport API call..?


问:
execvp to sort contents
I'm trying to sort a file using execvp and here's my code.

```<code>char *argv1[]={ "sh", "-c", "sort input.txt > output.txt", NULL };
</code>```

The problem is this command sorts the contents in output file but I want sorting only on terminal output.

答:
You could refer the example of Using cat and execvp

Replace with below code.

```<code>char *cmd1[] = { "sort", "input.txt", 0 };
char *cmd2[] = { "tee", "output.txt", 0 };
</code>```

Title: execvp to sort contents

Body:
I'm trying to sort a file using execvp and here's my code.

char *argv1[]={ "sh", "-c", "sort input.txt > output.txt", NULL };

The problem is this command sorts the contents in output file but I want sorting only on terminal output.

Body:
You could refer the example of Using cat and execvp

Replace with below code.

char *cmd1[] = { "sort", "input.txt", 0 };
char *cmd2[] = { "tee", "output.txt", 0 };


问:
How to check a clicked button's second class?
If I have two button, one with an apple class and the other with an apple and and orange class:

```<code><button class="apple"/>
<button class="apple orange"/>
</code>```

In my button click event for an apple button, how can I tell if the clicked button also has an orange class?

```<code>$("button.apple").click(function(event)
{
 var hasOrange = // ???
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If I have two button, one with an apple class and the other with an apple and and orange class:

<button class="apple"/>
<button class="apple orange"/>

In my button click event for an apple button, how can I tell if the clicked button also has an orange class?

$("button.apple").click(function(event)
{
 var hasOrange = // ???
}

Body: $(this).hasClass('orange')


问:
Inserting values in the form of a table using div tags and DOM manipulation (javascript)
I have an array which contains employee details like name,id etc which are entered by user in the input form. I want to print these details in the form of table using div alone. kindly tell me the html part and javascript part.
I want to create elements in javascript and print the inputs. The table contains 5 columns and rows gets added as the user enter his input</p>

答:
Use the following code to add rows to a table using javascript</p>

```<code>// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");

// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);

// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);

// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
</code>```

Body:
Use the following code to add rows to a table using javascript

// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");

// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);

// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);

// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";


问:
How can I make my code more pythonic? Iterating through a list isn't acceptable?
I've been told that iterating over a list as such is not appropriately pythonic. How do I make this part...

```<code>for i in range(0, len(word)):
            if words[i] == guess:
                guessable_list[i] = guess
                letters_to_guess -= 1
</code>```

more pythonic.

Background

I'm working on a problem (the last problem called hangman) assigned MIT OC. I am working on this stuff by myself. So far the material is accessible and well taught. However, since I don't have a supervisor coupled with the awareness of how bad habits can develop when doing I would really appreciate it if anyone could look at my code and see if I'm doing anything wrong - from the use of idioms or my structuring of my code. Any feedback is appreciated.
Thank you all!

I have tried doing this...

```<code>for letter in words:
        if letter == guess:
            guessable_list[word.index(letter)] = guess
            letters_to_guess -= 1
</code>```

but I encountered trouble where if a letter appears twice in a word it isn't replaced.

答:
You can use enumerate here:

```<code>for index, word in enumerate(words):
    if word == guess:
        guessable_list[index] = guess
        letters_to_guess -= 1
</code>```

Body:
I've been told that iterating over a list as such is not appropriately pythonic. How do I make this part...

for i in range(0, len(word)):
            if words[i] == guess:
                guessable_list[i] = guess
                letters_to_guess -= 1

more pythonic.

Background

I'm working on a problem (the last problem called hangman) assigned MIT OC. I am working on this stuff by myself. So far the material is accessible and well taught. However, since I don't have a supervisor coupled with the awareness of how bad habits can develop when doing I would really appreciate it if anyone could look at my code and see if I'm doing anything wrong - from the use of idioms or my structuring of my code. Any feedback is appreciated.
Thank you all!

I have tried doing this...

for letter in words:
        if letter == guess:
            guessable_list[word.index(letter)] = guess
            letters_to_guess -= 1

but I encountered trouble where if a letter appears twice in a word it isn't replaced.

Body:
You can use enumerate here:

for index, word in enumerate(words):
    if word == guess:
        guessable_list[index] = guess
        letters_to_guess -= 1


问:
Add type definition for type not used in any api method
I have an api end point that takes a custom header.
This header is a object that looks like this:

```<code>User: {"UserId":"someguid"}
</code>```

If I have the type as a parameter in a api method I can do as follows:

```<code>public class AddFileParamTypes : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.operationId == "FileDelivery_Post")
        {

            operation.consumes.Add("multipart/form-data");
            operation.parameters.Add(new Parameter
            {
                name = "file",
                required = true,
                type = "file",
                @in = "formData"
            });
            operation.parameters.Add(new Parameter
            {
                name = "User",
                required = true,
                schema = new Schema() { @ref = "#/definitions/User" },
                @in = "header"
            });
        }
    }
}
</code>```

But the User type will not be a parameter for a method, so how do I add the definition to swashbuckle?

答:
Found out, it was simple but lacking in documentation:    </p>

```<code>public class AddFileParamTypes : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.operationId == "FileDelivery_Post")
        {

            operation.consumes.Add("multipart/form-data");
            operation.parameters.Add(new Parameter
            {
                name = "file",
                required = true,
                type = "file",
                @in = "formData"
            });
            operation.parameters.Add(new Parameter
            {
                name = "User",
                required = true,
                schema = schemaRegistry.GetOrRegister(typeof(User)),
                @in = "header"
            });
        }
    }
}
</code>```

Body:
I have an api end point that takes a custom header.
This header is a object that looks like this:

User: {"UserId":"someguid"}

If I have the type as a parameter in a api method I can do as follows:

public class AddFileParamTypes : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.operationId == "FileDelivery_Post")
        {

            operation.consumes.Add("multipart/form-data");
            operation.parameters.Add(new Parameter
            {
                name = "file",
                required = true,
                type = "file",
                @in = "formData"
            });
            operation.parameters.Add(new Parameter
            {
                name = "User",
                required = true,
                schema = new Schema() { @ref = "#/definitions/User" },
                @in = "header"
            });
        }
    }
}

But the User type will not be a parameter for a method, so how do I add the definition to swashbuckle?

Body:
Found out, it was simple but lacking in documentation:

public class AddFileParamTypes : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.operationId == "FileDelivery_Post")
        {

            operation.consumes.Add("multipart/form-data");
            operation.parameters.Add(new Parameter
            {
                name = "file",
                required = true,
                type = "file",
                @in = "formData"
            });
            operation.parameters.Add(new Parameter
            {
                name = "User",
                required = true,
                schema = schemaRegistry.GetOrRegister(typeof(User)),
                @in = "header"
            });
        }
    }
}


问:
Google Foobar: Bringing a Gun to a Guard Fight

My Situation

I've been working on this challenge on and off for about 9 days now, and I'm out of ideas. So far my solution passes 9 / 10 of the test cases. My optimized solution runs quickly enough, so the error is the actual solution, not that it runs out of time to compute. I would greatly appreciate it if someone could tell me what I'm missing or if my algorithm doesn't actually solve the problem given. Also, I realize some bits of my code aren't perfect - I plan to fix everything up once I have a working solution.

Problem

Uh-oh - you've been cornered by one of Commander Lambdas elite guards! Fortunately, you grabbed a beam weapon from an abandoned guardpost while you were running through the station, so you have a chance to fight your way out. But the beam weapon is potentially dangerous to you as well as to the elite guard: its beams reflect off walls, meaning you'll have to be very careful where you shoot to avoid bouncing a shot toward yourself!

Luckily, the beams can only travel a certain maximum distance before becoming too weak to cause damage. You also know that if a beam hits a corner, it will bounce back in exactly the same direction. And of course, if the beam hits either you or the guard, it will stop immediately (albeit painfully).

Write a function answer(dimensions, your_position, guard_position, distance) that gives an array of 2 integers of the width and height of the room, an array of 2 integers of your x and y coordinates in the room, an array of 2 integers of the guard's x and y coordinates in the room, and returns an integer of the number of distinct directions that you can fire to hit the elite guard, given the maximum distance that the beam can travel.

The room has integer dimensions [1 < x_dim <= 1000, 1 < y_dim <= 1000]. You and the elite guard are both positioned on the integer lattice at different distinct positions (x, y) inside the room such that [0 < x < x_dim, 0 < y < y_dim]. Finally, the maximum distance that the beam can travel before becoming harmless will be given as an integer 1 < distance <= 10000.

For example, if you and the elite guard were positioned in a room with dimensions [3, 2], you_position [1, 1], guard_position [2, 1], and a maximum shot distance of 4, you could shoot in seven different directions to hit the elite guard (given as vector bearings from your location): [1, 0], [1, 2], [1, -2], [3, 2], [3, -2], [-3, 2], and [-3, -2]. As specific examples, the shot at bearing [1, 0] is the straight line horizontal shot of distance 1, the shot at bearing [-3, -2] bounces off the left wall and then the bottom wall before hitting the elite guard with a total shot distance of sqrt(13), and the shot at bearing [1, 2] bounces off just the top wall before hitting the elite guard with a total shot distance of sqrt(5).

My Unfinished Solution (Java)

```<code>public class Answer {

public static int answer(int[] dimensions, int[] captain_position, int[] badguy_position, int distance) {

    int parallelDimensionX = (2 * (distance / dimensions[0])) + 1;
    int parallelDimensionY = (2 * (distance / dimensions[1])) + 1;
    int numDirections = 0;
    int distanceSquared = (int) Math.pow(distance, 2);
    ArrayList<ArrayList<Double>> directions = new ArrayList<ArrayList<Double>>();
    ArrayList<ArrayList<Double>> sourceDirections = new ArrayList<ArrayList<Double>>();
    ArrayList<ArrayList<int[]>> sourceTracker = new ArrayList<ArrayList<int[]>>();

    for(int i = 0; i < 4; i++) {

        directions.add(new ArrayList<Double>());
        sourceDirections.add(new ArrayList<Double>());
        sourceTracker.add(new ArrayList<int[]>());
    }

    ArrayList<ArrayList<int[]>> mirroredPlanes = MirroredPlanes(badguy_position, dimensions, new int[]{parallelDimensionX, parallelDimensionY});
    ArrayList<ArrayList<int[]>> mirroredSources = MirroredPlanes(captain_position, dimensions, new int[]{parallelDimensionX, parallelDimensionY});

    for(int i = 0; i < parallelDimensionX; i++) {

        for(int j = 0; j < parallelDimensionY; j++) {

            int[] sourcePoint = mirroredSources.get(j).get(i);

            if(sourcePoint[0] == captain_position[0] && sourcePoint[1] == captain_position[1]) {

                continue;
            }

            int[] vecA = new int[] {sourcePoint[0] - captain_position[0], sourcePoint[1] - captain_position[1]};

            double direction = Math.atan2(vecA[1], vecA[0]);
            int quadrant = 0;
            if(vecA[0] < 0) {

                quadrant++;
            }
            if(vecA[1] < 0) {

                quadrant += 2;
            }

            if(!sourceDirections.get(quadrant).contains(direction)) {

                sourceDirections.get(quadrant).add(direction);
                sourceTracker.get(quadrant).add(new int[]{j, i});
            } else {

                int sourceIndex = sourceDirections.get(quadrant).indexOf(direction);

                if((sourceTracker.get(quadrant).get(sourceIndex)[0] < j && j < parallelDimensionY / 2) || (sourceTracker.get(quadrant).get(sourceIndex)[0] > j && j > parallelDimensionY / 2)) {

                    sourceTracker.get(quadrant).get(sourceIndex)[0] = j;
                }

                if((sourceTracker.get(quadrant).get(sourceIndex)[1] < i && i < parallelDimensionX / 2) || (sourceTracker.get(quadrant).get(sourceIndex)[1] > i && i > parallelDimensionX / 2)) {

                    sourceTracker.get(quadrant).get(sourceIndex)[1] = i;
                }
            }
        }
    }

    for(int i = 0; i < parallelDimensionX; i++) {

        for(int j = 0; j < parallelDimensionY; j++) {

            int[] currPoint = mirroredPlanes.get(j).get(i);

            if(captain_position[0] == badguy_position[0] && currPoint[0] == captain_position[0] && currPoint[1] != badguy_position[1]) {

                continue;
            }

            if(captain_position[1] == badguy_position[1] && currPoint[1] == captain_position[1] && currPoint[0] != badguy_position[0]) {

                continue;
            }

            if(Math.pow(currPoint[0] - captain_position[0], 2) + Math.pow(currPoint[1] - captain_position[1], 2) <= distanceSquared) {

                int [] vecA = new int[] {currPoint[0] - captain_position[0], currPoint[1] - captain_position[1]};

                double direction = Math.atan2(vecA[1], vecA[0]);
                int quadrant = 0;
                if(vecA[0] < 0) {

                    quadrant++;
                }
                if(vecA[1] < 0) {

                    quadrant += 2;
                }

                if(directions.get(quadrant).contains(direction)) {

                    continue;
                } else {

                    directions.get(quadrant).add(direction);
                }

                if(sourceDirections.get(quadrant).contains(direction)) {

                    int index = sourceDirections.get(quadrant).indexOf(direction);

                    int[] sourceIndex = sourceTracker.get(quadrant).get(index);
                    int[] sourcePoint = mirroredSources.get(sourceIndex[0]).get(sourceIndex[1]);

                    if(Math.pow(sourcePoint[0], 2) + Math.pow(sourcePoint[1], 2) < Math.pow(currPoint[0], 2) + Math.pow(currPoint[1], 2)) {

                        continue;
                    }

                }

                numDirections++;
            }
        }
    }

    return numDirections;
}

public static ArrayList<ArrayList<int[]>> MirroredPlanes(int[] startingLocal, int[] planeDimensions, int[]mirrorDimensions) {

    ArrayList<ArrayList<int[]>> mirroredPlanes = new ArrayList<ArrayList<int[]>>();

    //int[][int[][]] mirroredPlanes = new int[mirrorDimensions[0]][mirrorDimensions[1]];
    int middleX = mirrorDimensions[0] / 2;
    int middleY = mirrorDimensions[1] / 2;

    for(int i = 0; i < mirrorDimensions[1]; i++) {

        ArrayList<int[]> curXList = new ArrayList<int[]>();
        mirroredPlanes.add(curXList);

        for(int j = 0; j < mirrorDimensions[0]; j++) {

            int[] curY = new int[2];

            int[] tempLocal = new int[]{startingLocal[0], startingLocal[1]};

            int modX = j - middleX;
            int modY = i - middleY;

            if(modX % 2 != 0) {

                tempLocal[0] = planeDimensions[0] - startingLocal[0];
            }

            curY[0] = tempLocal[0] + (modX * planeDimensions[0]);

            if(modY % 2 != 0) {

                tempLocal[1] = planeDimensions[1] - startingLocal[1];
            }

            curY[1] = tempLocal[1] + (modY * planeDimensions[1]);

            curXList.add(curY);
        }
    }

    return mirroredPlanes;
}
</code>```

}

Things I've tried that aren't currently in the code

Checking to see the if laser hits a corner

Checking to see if the laser hits the captain before the guard

Failed Test Case

```<code>int[] dimensions = new int[] {42, 59};
int[] captain_position = new int [] {34, 44};
int[] badguy_position = new int[] {6, 34};
int distance = 5000;
//Desired Output: ??? (Unknown)
//Actual Output: 31694 (Incorrect)
</code>```

答:
Here you take some more test cases

```<code>dimensions = [10,10]
captain_position = [4, 4]
badguy_position = [3,3]
distance = 5000
</code>```

I didn't use java. btw ans = 739323

```<code>dimensions = [23,10]
captain_position = [6, 4]
badguy_position = [3,2]
distance = 23

ans  = 8
</code>```

I won't post code or the logic. Hint: can you see enemy behind shadow? look around yourself

Body:
My Situation

I've been working on this challenge on and off for about 9 days now, and I'm out of ideas. So far my solution passes 9 / 10 of the test cases. My optimized solution runs quickly enough, so the error is the actual solution, not that it runs out of time to compute. I would greatly appreciate it if someone could tell me what I'm missing or if my algorithm doesn't actually solve the problem given. Also, I realize some bits of my code aren't perfect - I plan to fix everything up once I have a working solution.

Problem

Uh-oh - you've been cornered by one of Commander Lambdas elite guards! Fortunately, you grabbed a beam weapon from an abandoned guardpost while you were running through the station, so you have a chance to fight your way out. But the beam weapon is potentially dangerous to you as well as to the elite guard: its beams reflect off walls, meaning you'll have to be very careful where you shoot to avoid bouncing a shot toward yourself!

Luckily, the beams can only travel a certain maximum distance before becoming too weak to cause damage. You also know that if a beam hits a corner, it will bounce back in exactly the same direction. And of course, if the beam hits either you or the guard, it will stop immediately (albeit painfully).

Write a function answer(dimensions, your_position, guard_position, distance) that gives an array of 2 integers of the width and height of the room, an array of 2 integers of your x and y coordinates in the room, an array of 2 integers of the guard's x and y coordinates in the room, and returns an integer of the number of distinct directions that you can fire to hit the elite guard, given the maximum distance that the beam can travel.

The room has integer dimensions [1 < x_dim <= 1000, 1 < y_dim <= 1000]. You and the elite guard are both positioned on the integer lattice at different distinct positions (x, y) inside the room such that [0 < x < x_dim, 0 < y < y_dim]. Finally, the maximum distance that the beam can travel before becoming harmless will be given as an integer 1 < distance <= 10000.

For example, if you and the elite guard were positioned in a room with dimensions [3, 2], you_position [1, 1], guard_position [2, 1], and a maximum shot distance of 4, you could shoot in seven different directions to hit the elite guard (given as vector bearings from your location): [1, 0], [1, 2], [1, -2], [3, 2], [3, -2], [-3, 2], and [-3, -2]. As specific examples, the shot at bearing [1, 0] is the straight line horizontal shot of distance 1, the shot at bearing [-3, -2] bounces off the left wall and then the bottom wall before hitting the elite guard with a total shot distance of sqrt(13), and the shot at bearing [1, 2] bounces off just the top wall before hitting the elite guard with a total shot distance of sqrt(5).

My Unfinished Solution (Java)

public class Answer {

public static int answer(int[] dimensions, int[] captain_position, int[] badguy_position, int distance) {

    int parallelDimensionX = (2 * (distance / dimensions[0])) + 1;
    int parallelDimensionY = (2 * (distance / dimensions[1])) + 1;
    int numDirections = 0;
    int distanceSquared = (int) Math.pow(distance, 2);
    ArrayList<ArrayList<Double>> directions = new ArrayList<ArrayList<Double>>();
    ArrayList<ArrayList<Double>> sourceDirections = new ArrayList<ArrayList<Double>>();
    ArrayList<ArrayList<int[]>> sourceTracker = new ArrayList<ArrayList<int[]>>();

    for(int i = 0; i < 4; i++) {

        directions.add(new ArrayList<Double>());
        sourceDirections.add(new ArrayList<Double>());
        sourceTracker.add(new ArrayList<int[]>());
    }

    ArrayList<ArrayList<int[]>> mirroredPlanes = MirroredPlanes(badguy_position, dimensions, new int[]{parallelDimensionX, parallelDimensionY});
    ArrayList<ArrayList<int[]>> mirroredSources = MirroredPlanes(captain_position, dimensions, new int[]{parallelDimensionX, parallelDimensionY});

    for(int i = 0; i < parallelDimensionX; i++) {

        for(int j = 0; j < parallelDimensionY; j++) {

            int[] sourcePoint = mirroredSources.get(j).get(i);

            if(sourcePoint[0] == captain_position[0] && sourcePoint[1] == captain_position[1]) {

                continue;
            }

            int[] vecA = new int[] {sourcePoint[0] - captain_position[0], sourcePoint[1] - captain_position[1]};

            double direction = Math.atan2(vecA[1], vecA[0]);
            int quadrant = 0;
            if(vecA[0] < 0) {

                quadrant++;
            }
            if(vecA[1] < 0) {

                quadrant += 2;
            }

            if(!sourceDirections.get(quadrant).contains(direction)) {

                sourceDirections.get(quadrant).add(direction);
                sourceTracker.get(quadrant).add(new int[]{j, i});
            } else {

                int sourceIndex = sourceDirections.get(quadrant).indexOf(direction);

                if((sourceTracker.get(quadrant).get(sourceIndex)[0] < j && j < parallelDimensionY / 2) || (sourceTracker.get(quadrant).get(sourceIndex)[0] > j && j > parallelDimensionY / 2)) {

                    sourceTracker.get(quadrant).get(sourceIndex)[0] = j;
                }

                if((sourceTracker.get(quadrant).get(sourceIndex)[1] < i && i < parallelDimensionX / 2) || (sourceTracker.get(quadrant).get(sourceIndex)[1] > i && i > parallelDimensionX / 2)) {

                    sourceTracker.get(quadrant).get(sourceIndex)[1] = i;
                }
            }
        }
    }

    for(int i = 0; i < parallelDimensionX; i++) {

        for(int j = 0; j < parallelDimensionY; j++) {

            int[] currPoint = mirroredPlanes.get(j).get(i);

            if(captain_position[0] == badguy_position[0] && currPoint[0] == captain_position[0] && currPoint[1] != badguy_position[1]) {

                continue;
            }

            if(captain_position[1] == badguy_position[1] && currPoint[1] == captain_position[1] && currPoint[0] != badguy_position[0]) {

                continue;
            }

            if(Math.pow(currPoint[0] - captain_position[0], 2) + Math.pow(currPoint[1] - captain_position[1], 2) <= distanceSquared) {

                int [] vecA = new int[] {currPoint[0] - captain_position[0], currPoint[1] - captain_position[1]};

                double direction = Math.atan2(vecA[1], vecA[0]);
                int quadrant = 0;
                if(vecA[0] < 0) {

                    quadrant++;
                }
                if(vecA[1] < 0) {

                    quadrant += 2;
                }

                if(directions.get(quadrant).contains(direction)) {

                    continue;
                } else {

                    directions.get(quadrant).add(direction);
                }

                if(sourceDirections.get(quadrant).contains(direction)) {

                    int index = sourceDirections.get(quadrant).indexOf(direction);

                    int[] sourceIndex = sourceTracker.get(quadrant).get(index);
                    int[] sourcePoint = mirroredSources.get(sourceIndex[0]).get(sourceIndex[1]);

                    if(Math.pow(sourcePoint[0], 2) + Math.pow(sourcePoint[1], 2) < Math.pow(currPoint[0], 2) + Math.pow(currPoint[1], 2)) {

                        continue;
                    }

                }

                numDirections++;
            }
        }
    }

    return numDirections;
}

public static ArrayList<ArrayList<int[]>> MirroredPlanes(int[] startingLocal, int[] planeDimensions, int[]mirrorDimensions) {

    ArrayList<ArrayList<int[]>> mirroredPlanes = new ArrayList<ArrayList<int[]>>();

    //int[][int[][]] mirroredPlanes = new int[mirrorDimensions[0]][mirrorDimensions[1]];
    int middleX = mirrorDimensions[0] / 2;
    int middleY = mirrorDimensions[1] / 2;

    for(int i = 0; i < mirrorDimensions[1]; i++) {

        ArrayList<int[]> curXList = new ArrayList<int[]>();
        mirroredPlanes.add(curXList);

        for(int j = 0; j < mirrorDimensions[0]; j++) {

            int[] curY = new int[2];

            int[] tempLocal = new int[]{startingLocal[0], startingLocal[1]};

            int modX = j - middleX;
            int modY = i - middleY;

            if(modX % 2 != 0) {

                tempLocal[0] = planeDimensions[0] - startingLocal[0];
            }

            curY[0] = tempLocal[0] + (modX * planeDimensions[0]);

            if(modY % 2 != 0) {

                tempLocal[1] = planeDimensions[1] - startingLocal[1];
            }

            curY[1] = tempLocal[1] + (modY * planeDimensions[1]);

            curXList.add(curY);
        }
    }

    return mirroredPlanes;
}

}

Things I've tried that aren't currently in the code

Checking to see the if laser hits a corner

Checking to see if the laser hits the captain before the guard

Failed Test Case

int[] dimensions = new int[] {42, 59};
int[] captain_position = new int [] {34, 44};
int[] badguy_position = new int[] {6, 34};
int distance = 5000;
//Desired Output: ??? (Unknown)
//Actual Output: 31694 (Incorrect)

Body:
Here you take some more test cases

dimensions = [10,10]
captain_position = [4, 4]
badguy_position = [3,3]
distance = 5000

I didn't use java. btw ans = 739323

dimensions = [23,10]
captain_position = [6, 4]
badguy_position = [3,2]
distance = 23

ans  = 8

I won't post code or the logic. Hint: can you see enemy behind shadow? look around yourself

ContentLicense: CC BY-SA 4.0


问:
how to do addition In Sql Server using dynamic generated field?
I have table called "Cart". Fields are :

CartId

ClientId

ProductId

Qty

Now i am joining this table with ProductMaster to get ProductName and ProuctPrice

```<code>select cc.CartId,cc.ProductId,pm.ProductName,cc.Qty,
        (pm.ProductPrice * cc.Qty) As SubTotal
from ClientCart as cc
    inner join ProductMaster as pm on cc.ProductId = pm.ProductId
</code>```

Now I want to genrate GrandTotal using dynamic field SubTotal. How Can i do this?

答:
```<code>with CTE as
(
select cc.CartId,cc.ProductId,pm.ProductName,cc.Qty,
        (pm.ProductPrice * cc.Qty) As SubTotal
from ClientCart as cc
    inner join ProductMaster as pm on cc.ProductId = pm.ProductId
where cc.ClientId = @id
)
select *
from CTE
union
select null,null, null,null, sum(SubTotal) -- this is a grand total of all sub totals
from CTE
</code>```

It's not the proper Rollup method, but neither is yours so this will work fine

Body:
I have table called "Cart". Fields are :

CartId

ClientId

ProductId

Qty

Now i am joining this table with ProductMaster to get ProductName and ProuctPrice

select cc.CartId,cc.ProductId,pm.ProductName,cc.Qty,
        (pm.ProductPrice * cc.Qty) As SubTotal
from ClientCart as cc
    inner join ProductMaster as pm on cc.ProductId = pm.ProductId

Now I want to genrate GrandTotal using dynamic field SubTotal. How Can i do this?

Body:
with CTE as
(
select cc.CartId,cc.ProductId,pm.ProductName,cc.Qty,
        (pm.ProductPrice * cc.Qty) As SubTotal
from ClientCart as cc
    inner join ProductMaster as pm on cc.ProductId = pm.ProductId
where cc.ClientId = @id
)
select *
from CTE
union
select null,null, null,null, sum(SubTotal) -- this is a grand total of all sub totals
from CTE

It's not the proper Rollup method, but neither is yours so this will work fine


问:
In Java where do the static methods go during the creation of an object in java?
If there is a class with some methods, whenever we create a new object then that object gets created on the heap with the fields and methods. If we have a class with static and normal methods and we create an object of this class, the instance variables and normal methods still exist but how are the static methods created ?</p>

答:
All methods, both static and non-static, are part of the class, and classes are stored in non-heap memory.

All that resides in the heap is a structure containing:

a pointer to the class of which this object is an instance

The current values for each non-static field (references for object fields, values for primitive fields)

So for example:

```<code> public class Person {
     private String name;
     private int age;

     public String getName() {
         return name;
     }

     // ... etc.
 }
</code>```

One structure in non-heap memory contains:

Metadata about the class e.g. its name Person, a pointer to its superclass etc.

The bytecode for getName() and any other methods

JIT optimised versions of the bytecode

For each instance of Person, we get in the heap:

A reference to the class entry

An int value for age

A reference to a String object name

So, at least conceptually, you could see the runtime handling a call to aPerson.getName() as:

Look at the object's record in heap

Follow the reference to its class

In the class, find the method getName()

Run the method, using the object's record in the heap for fields

This means that if you have 1000 instances of Person, you still only have one copy of the code from the class, which is perfect because it does not change from one instance to the next.

If Doctor, Nurse, Patient are all subclasses of Person, and if none of them override getName(), then the code for getName() still only exists once in memory. (Conceptually) when you call aNurse.getName() the runtime will look in Nurse for getName(), if found, run that, otherwise look in the superclass Person, find it, and run that.

I've said "conceptually" a couple of times. In reality some of what I've described as happening dynamically may happen statically at compile time. This doesn't really matter as far as understanding the effect on memory and performance.

Body:
All methods, both static and non-static, are part of the class, and classes are stored in non-heap memory.

All that resides in the heap is a structure containing:

a pointer to the class of which this object is an instance

The current values for each non-static field (references for object fields, values for primitive fields)

So for example:

 public class Person {
     private String name;
     private int age;

     public String getName() {
         return name;
     }

     // ... etc.
 }

One structure in non-heap memory contains:

Metadata about the class e.g. its name Person, a pointer to its superclass etc.

The bytecode for getName() and any other methods

JIT optimised versions of the bytecode

For each instance of Person, we get in the heap:

A reference to the class entry

An int value for age

A reference to a String object name

So, at least conceptually, you could see the runtime handling a call to aPerson.getName() as:

Look at the object's record in heap

Follow the reference to its class

In the class, find the method getName()

Run the method, using the object's record in the heap for fields

This means that if you have 1000 instances of Person, you still only have one copy of the code from the class, which is perfect because it does not change from one instance to the next.

If Doctor, Nurse, Patient are all subclasses of Person, and if none of them override getName(), then the code for getName() still only exists once in memory. (Conceptually) when you call aNurse.getName() the runtime will look in Nurse for getName(), if found, run that, otherwise look in the superclass Person, find it, and run that.

I've said "conceptually" a couple of times. In reality some of what I've described as happening dynamically may happen statically at compile time. This doesn't really matter as far as understanding the effect on memory and performance.


问:
unique records by one column
I have been working on this for a long time now and cant get the answer.
I have a table with 4 columns. I need to return two of these columns, A and B.
However I need the data to be filtered by the first column A. A is not a primary key. How can I achieve this? If I can return all the columns its also ok, as long as the data is only filtered by column A.

```<code>A  B  C  D
1  e  f  r
1  e  f  r
1  e  k  t
2  c  f  r
2  c  f  r
3  l  f  r
</code>```

This should return

```<code>A  B  C  D
1  e  f  r
2  c  f  r
3  l  f  r
</code>```

Which query wil give me this result? Until now I have this but it does not work well:

```<code>SELECT DISTINCT A, B, FROM myTable WHERE C=f
</code>```

答:
Try </p>

```<code>SELECT A,B FROM myTable WHERE C='f' GROUP BY A,B
</code>```

Title: unique records by one column

Body:
I have been working on this for a long time now and cant get the answer.
I have a table with 4 columns. I need to return two of these columns, A and B.
However I need the data to be filtered by the first column A. A is not a primary key. How can I achieve this? If I can return all the columns its also ok, as long as the data is only filtered by column A.

A  B  C  D
1  e  f  r
1  e  f  r
1  e  k  t
2  c  f  r
2  c  f  r
3  l  f  r

This should return

A  B  C  D
1  e  f  r
2  c  f  r
3  l  f  r

Which query wil give me this result? Until now I have this but it does not work well:

SELECT DISTINCT A, B, FROM myTable WHERE C=f

Body:
Try

SELECT A,B FROM myTable WHERE C='f' GROUP BY A,B


问:
How use dynamic scheduler in spring framework?
I'm using Spring Security 4.2. I want to block user for 15 minutes after 3 login failure. For blocking user, change user status to BLOCK. I want to return it to ACTIVE after 15 minutes.

I need a dynamic task scheduler that run after 15 minutes and change user status.

Important: I don't want to run method every 15 minutes, I want to run method after 15 minutes if needed.

How do I implement it?

答:
You might have table defination for doing this. But this is how I do it generally.

Create a seprate table to maintain the failure count.

Then on basis of  this you can check in your service / controller layer.

```<code>    @Controller
    public Class LoginController{

        @Autowired
        private UserLoginFailureRepository userLoginFailureRepository;

        @Autowired
        private UserRepostory userRepository;

        @Transactional
        public void login(){

        UserLoginFailure loginFailure = userLoginFailureRepository.getUserLoginfailureDetails(username);
        if (loginFailure != null) {
        loginFailure.setFailureCount(1l + loginFailure.getFailureCount());

        if (loginFailure.getFailureCount() > loginFailureCount) {
        // block the user.
        User user = userRepository.getUser(username);
        user.setStatus(BLOCK);
        user.setModificationDate(LocalDateTime.now());
        }
    }
    }
    }
</code>```

Create a seprate Scheduled Job to check and update User Status and reset UserLoginFailure count.

```<code>    @Component
    public class userPasswordResetJob{

        @Autowired
        private UserLoginFailureRepository userLoginFailureRepository;

        @Autowired
        private UserRepostory userRepository;

        @Scheduled(cron = "${USER_STATUS_JOB}")
        public void loginDay() throws Exception{
            // Have your logic to update the User status and reset the failure count.

        }
    }
</code>```

Body:
You might have table defination for doing this. But this is how I do it generally.

Create a seprate table to maintain the failure count.

Then on basis of  this you can check in your service / controller layer.

    @Controller
    public Class LoginController{

        @Autowired
        private UserLoginFailureRepository userLoginFailureRepository;

        @Autowired
        private UserRepostory userRepository;

        @Transactional
        public void login(){

        UserLoginFailure loginFailure = userLoginFailureRepository.getUserLoginfailureDetails(username);
        if (loginFailure != null) {
        loginFailure.setFailureCount(1l + loginFailure.getFailureCount());

        if (loginFailure.getFailureCount() > loginFailureCount) {
        // block the user.
        User user = userRepository.getUser(username);
        user.setStatus(BLOCK);
        user.setModificationDate(LocalDateTime.now());
        }
    }
    }
    }

Create a seprate Scheduled Job to check and update User Status and reset UserLoginFailure count.

    @Component
    public class userPasswordResetJob{

        @Autowired
        private UserLoginFailureRepository userLoginFailureRepository;

        @Autowired
        private UserRepostory userRepository;

        @Scheduled(cron = "${USER_STATUS_JOB}")
        public void loginDay() throws Exception{
            // Have your logic to update the User status and reset the failure count.

        }
    }


问:
How to get last id in cakephp
I am using query in cakephp

```<code>$this->Menu->query("INSERT INTO frd_menus SET menuName= '".$_REQUEST['menuname']."'");
</code>```

How to get last insert id of this query in cakephp? Please advice.

答:
In CakePHP 3.x you can do it like:

```<code>$data = $this->model->save($data);
$data->id; // this will give the inserted id
</code>```

Title: How to get last id in cakephp

Body:
I am using query in cakephp

$this->Menu->query("INSERT INTO frd_menus SET menuName= '".$_REQUEST['menuname']."'");

How to get last insert id of this query in cakephp? Please advice.

Body:
In CakePHP 3.x you can do it like:

$data = $this->model->save($data);
$data->id; // this will give the inserted id


问:
Regex not working in Java while working otherwise
I made a regular expression: https://regex101.com/r/ToCwrE/2/

All it should do, is get out the function's parameters. I am trying with capture groups to achieve this.

[\s]*javascript:[\s]*m\((-?\d+)[\s]*,[\s]*(-?\d+)[\s]*,[\s]{0,}encodeURIComponent\(\'([^\']+)*\'\)[\s]*,[\s]*(-?\d+)\)[\s]*

Tried it on:

```<code>javascript:m(53009,2,encodeURIComponent('7711T'), 22)
javascript:m(52992,2,encodeURIComponent('3013'), 2)
javascript:m(10440,2,encodeURIComponent('F Series'), 11)
javascript:m(53022,2,encodeURIComponent('C 12045'), 85)
javascript:m(53045,2,encodeURIComponent('Prox 8441'), 16)
javascript:m(26016,2,encodeURIComponent('Vard   asd .ious'), 22)
</code>```

Using the site regex101 and a few similar ones, it correctly returns the matched groups. However when I am trying to use it in Java, it simply won't match the capture groups and only returns the whole text.

If I copy paste it with IDEA, It automatically gets escaped (replaces \ to \):

```<code>Pattern pattern = Pattern.compile("[\\s]*javascript:[\\s]*m\\((-?\\d+)[\\s]*,[\\s]*(-?\\d+)[\\s]*,[\\s]{0,}encodeURIComponent\\(\\'([^\\']+)*\\'\\)[\\s]*,[\\s]*(-?\\d+)\\)[\\s]*");
Matcher m = pattern.matcher("javascript:m(53022,2,encodeURIComponent('Cr 12045'), 85)");
List<String> groups = new ArrayList<>();
while (m.find()) {
    groups.add(m.group());
}
groups;
</code>```

What am I missing? How should the regex be converted to get it working in Java?

答:
To get content of each group you can use Matcher#group(number) or Matcher#group(name). In your case to get content of first group use m.group(1) and you will get 53022.

Problem with m.group() is that it is same as m.group(0) so it returns content of group 0, which holds match for whole pattern.

To iterate over all groups use simple for loop. To dynamically get amounts of groups in pattern use Matcher#groupCount.

So to put results from all groups you can use

```<code>Pattern p = Pattern.compile("[\\s]*javascript:[\\s]*m\\((-?\\d+)[\\s]*,[\\s]*(-?\\d+)[\\s]*,[\\s]{0,}encodeURIComponent\\(\\'([^\\']+)*\\'\\)[\\s]*,[\\s]*(-?\\d+)\\)[\\s]*");
Matcher m = p.matcher("javascript:m(53022,2,encodeURIComponent('Cr 12045'), 85)");
List<String> groups = new ArrayList<>();
while (m.find()) {
    for (int i=1; i<=m.groupCount(); i++){
        groups.add(m.group(i));
    }
}

System.out.println(groups); //[53022, 2, Cr 12045, 85]
</code>```

BTW

\s is already character class so it doesn't need to be nested in [..], so instead of [\\s]* you can write \\s*.

{0,} is same as * so I don't see any reason to mix those two, use * everywhere

' is not regex metacharacter so it doesn't need escaping

Body:
I made a regular expression: https://regex101.com/r/ToCwrE/2/

All it should do, is get out the function's parameters. I am trying with capture groups to achieve this.

[\s]*javascript:[\s]*m\((-?\d+)[\s]*,[\s]*(-?\d+)[\s]*,[\s]{0,}encodeURIComponent\(\'([^\']+)*\'\)[\s]*,[\s]*(-?\d+)\)[\s]*

Tried it on:

javascript:m(53009,2,encodeURIComponent('7711T'), 22)
javascript:m(52992,2,encodeURIComponent('3013'), 2)
javascript:m(10440,2,encodeURIComponent('F Series'), 11)
javascript:m(53022,2,encodeURIComponent('C 12045'), 85)
javascript:m(53045,2,encodeURIComponent('Prox 8441'), 16)
javascript:m(26016,2,encodeURIComponent('Vard   asd .ious'), 22)

Using the site regex101 and a few similar ones, it correctly returns the matched groups. However when I am trying to use it in Java, it simply won't match the capture groups and only returns the whole text.

If I copy paste it with IDEA, It automatically gets escaped (replaces \ to \):

Pattern pattern = Pattern.compile("[\\s]*javascript:[\\s]*m\\((-?\\d+)[\\s]*,[\\s]*(-?\\d+)[\\s]*,[\\s]{0,}encodeURIComponent\\(\\'([^\\']+)*\\'\\)[\\s]*,[\\s]*(-?\\d+)\\)[\\s]*");
Matcher m = pattern.matcher("javascript:m(53022,2,encodeURIComponent('Cr 12045'), 85)");
List<String> groups = new ArrayList<>();
while (m.find()) {
    groups.add(m.group());
}
groups;

What am I missing? How should the regex be converted to get it working in Java?

Body:
To get content of each group you can use Matcher#group(number) or Matcher#group(name). In your case to get content of first group use m.group(1) and you will get 53022.

Problem with m.group() is that it is same as m.group(0) so it returns content of group 0, which holds match for whole pattern.

To iterate over all groups use simple for loop. To dynamically get amounts of groups in pattern use Matcher#groupCount.

So to put results from all groups you can use

Pattern p = Pattern.compile("[\\s]*javascript:[\\s]*m\\((-?\\d+)[\\s]*,[\\s]*(-?\\d+)[\\s]*,[\\s]{0,}encodeURIComponent\\(\\'([^\\']+)*\\'\\)[\\s]*,[\\s]*(-?\\d+)\\)[\\s]*");
Matcher m = p.matcher("javascript:m(53022,2,encodeURIComponent('Cr 12045'), 85)");
List<String> groups = new ArrayList<>();
while (m.find()) {
    for (int i=1; i<=m.groupCount(); i++){
        groups.add(m.group(i));
    }
}

System.out.println(groups); //[53022, 2, Cr 12045, 85]

BTW

\s is already character class so it doesn't need to be nested in [..], so instead of [\\s]* you can write \\s*.

{0,} is same as * so I don't see any reason to mix those two, use * everywhere

' is not regex metacharacter so it doesn't need escaping


问:
What is the difference between Fetch and Query?
To me, PetaPoco's Database.Fetch and Database.Query seem to be doing the same thing.

For example,

```<code>var db = new PetaPoco.Database("myDB");
ProductList products = db.Fetch<ProductList>("SELECT * FROM ProductList");
ProductList products = db.Query<ProductList>("SELECT * FROM ProductList");
</code>```

Is there any significant difference between them?

答:
Fetch and query behave differently if you use them inside a transaction. I had a use case where I needed to update several tables in one transaction but I needed to retrieve some data from a reference table in the middle of the sequence.

When I retrieved the data with Query, and subsequent Inserts or Updates failed with an InvalidOperationException: "There is already an open DataReader associated with this Command which must be closed first"

The solution was to replace the Query with a Fetch and I was able to complete the sequence.

The pseudocode for this is:

BeginTransaction
  Update Tbl1
  Update Tbl2
  Query  RefTblA  ## Changed Query to Fetch to avoid: '...already an open DataReader..." exception
  Update Tbl3 using data from RefTblA
CompleteTransaction

Body:
To me, PetaPoco's Database.Fetch and Database.Query seem to be doing the same thing.

For example,

var db = new PetaPoco.Database("myDB");
ProductList products = db.Fetch<ProductList>("SELECT * FROM ProductList");
ProductList products = db.Query<ProductList>("SELECT * FROM ProductList");

Is there any significant difference between them?


问:
while loop with vector condition
I want to create a while loop which stops when one column equals to another (by element) but I got the following error:

the condition has length > 1 and only the first element will be used

For example:

```<code>y<-c(1,1)
z<-c(1,1)
x<-c(3,3)
while(y!=x){y=y+z}
</code>```

答:
You're close, just add an all statement to use the whole vector for the loop. Try looking at ?any and ?all for future vector by vector logical operations.

while(all(x != y)) {y <- y + z}

Title: while loop with vector condition

Body:
I want to create a while loop which stops when one column equals to another (by element) but I got the following error:

the condition has length > 1 and only the first element will be used

For example:

y<-c(1,1)
z<-c(1,1)
x<-c(3,3)
while(y!=x){y=y+z}


问:
how to pass json encoded php variable as parameter in onclick event function in codeigniter
I have my code like this but the jquery is not giving response which writen in the bottom of the page in

```<code>    <tr><th>Hindu</th>
        <td><a href="javascript:void(0)" onclick="getIdies('<?php echo json_encode(explode(",",
                     $count[1 ]->OBCHinduOBC)); ?>')"><?php echo $count[1 ]->HinduOBC;?>
            </a></td>
   </tr>
</code>```

This is my jquery

```<code><sript>
function getIdies(values){
    $.each(values,function(key,value){
        alert(value);
    });
}
</script>
</code>```

The below  line gives output like

```<code><?php echo json_encode(explode(",", $count[1 ]->OBCHinduOBC)); ?>
output:   ["200","500","700","675","54","567","678","867"]
</code>```

答:
You are not json decoding before use in our script,to decode the json you can use $.parseJSON

Just like this

```<code><script>
function getIdies(values) {
    $.each(values, function (key, val) {
        alert(val);
    });
}
</code>```

Modification:-

Just change your html to

```<code><tr><th>Hindu</th>
    <?php  $ids= json_encode(explode(",",$count[1]->OBCHinduOBC));?>
    <td><a href="javascript:void(0)" onclick="getIdies({{$ids}})"><?php echo $count[1 ]->HinduOBC;?>
        </a></td>
</tr>
</code>```

Try this it will work fine.

Body:
I have my code like this but the jquery is not giving response which writen in the bottom of the page in

Hindu
        <a href="javascript:void(0)" onclick="getIdies('<?php echo json_encode(explode(",",
                     $count[1 ]->OBCHinduOBC)); ?>')"><?php echo $count[1 ]->HinduOBC;?>

This is my jquery

<sript>
function getIdies(values){
    $.each(values,function(key,value){
        alert(value);
    });
}
</script>

The below  line gives output like

<?php echo json_encode(explode(",", $count[1 ]->OBCHinduOBC)); ?>
output:   ["200","500","700","675","54","567","678","867"]

Body:
You are not json decoding before use in our script,to decode the json you can use $.parseJSON

Just like this

<script>
function getIdies(values) {
    $.each(values, function (key, val) {
        alert(val);
    });
}

Modification:-

Just change your html to

<tr><th>Hindu</th>
    <?php  $ids= json_encode(explode(",",$count[1]->OBCHinduOBC));?>
    <td><a href="javascript:void(0)" onclick="getIdies({{$ids}})"><?php echo $count[1 ]->HinduOBC;?>
        </a></td>
</tr>

Try this it will work fine.


答:
You can use hasClass() like this:

```<code>$('button.apple').click(function(){
  if ($(this).hasClass('orange')){
    // it has orange class too
  }
  else{
    // it does not have orange class
  }
});
</code>```

You can make it a bit shorter:

```<code>$('button.apple').click(function(){
  var cls = $(this).hasClass('orange');
});
</code>```

Description: Determine whether any of
  the matched elements are assigned the
  given class.

More Info:

http://api.jquery.com/hasClass/

Title: How to check a clicked button's second class?

Body:
If I have two button, one with an apple class and the other with an apple and and orange class:

<button class="apple"/>
<button class="apple orange"/>

In my button click event for an apple button, how can I tell if the clicked button also has an orange class?

$("button.apple").click(function(event)
{
 var hasOrange = // ???
}

Body:
You can use hasClass() like this:

$('button.apple').click(function(){
  if ($(this).hasClass('orange')){
    // it has orange class too
  }
  else{
    // it does not have orange class
  }
});

You can make it a bit shorter:

$('button.apple').click(function(){
  var cls = $(this).hasClass('orange');
});

Description: Determine whether any of
  the matched elements are assigned the
  given class.

More Info:

http://api.jquery.com/hasClass/


问:
Certain files created from MemoryStream are corrupt
I have code that passes a list of objects containing the filename and binary data from the db to a loop that creates all the files. The problem that I have is the code below executes and appears to create the files correctly (filename & size is as expected) however, most files are "corrupt" when opened. The file types vary from images (jpg/png) to Word documents, Powerpoint presentations and PDF files. What is strange is that PDF files work perfectly, everything else is "corrupt"

My code is below (attachment is the object in the loop, the path is already created at this stage)

```<code>if(Directory.Exists(attachmentPath))
{
    string absolutePath = attachmentPath + "\\importfiles\\" + parentfolders + "\\";

    // no need to check if it exists as it will ignore if it does
    Directory.CreateDirectory(absolutePath);
    absolutePath += filename;
    try
    {
        byte[] byteStream = null;
        object objSave = null;

        objSave = attachment.Image;
        BinaryFormatter tmpBinF = new BinaryFormatter();
        MemoryStream tmpMemStrm = new MemoryStream();
        tmpBinF.Serialize(tmpMemStrm, objSave);
        byteStream = tmpMemStrm.ToArray();

        // Delete the file if it exists.
        if (File.Exists(absolutePath))
        {
            File.Delete(absolutePath);
        }

        // Create the file.
        using (FileStream fs = File.Create(absolutePath))
        {
            fs.Write(byteStream, 0, byteStream.Length);
            fs.Dispose();
        }

    }

    catch (Exception ex)
    {
        Exceptions.Text += ex.ToString();
    }
}
</code>```

I've used tips from MSDN and followed this tutorial but can't figure out why this is happening.

Thanks go to Amy for pointing out the issue with my approach, if anyone needs it, here's my updated code taking her answer into account. I've also extended it to add a log record on a table in the DB for later use.

```<code>if (Directory.Exists(attachmentPath))
{
    // build path from the parts
    string absolutePath = attachmentPath + "\\importfiles\\" + parentfolders + "\\";

    // no need to check if it exists as it will ignore if it does
    Directory.CreateDirectory(absolutePath);
    absolutePath += filename;
    byte[] file = attachment.Image;
    try
    {
        // Delete the file if it exists.
        if (File.Exists(absolutePath))
        {
            File.Delete(absolutePath);
        }

        // Create the file.
        using (FileStream fs = File.Create(absolutePath))
        {
            fs.Write(file, 0, file.Length);
        }

        // start logging to the database

        // add the Stored procedure
        string SP = "sp_add_attachment";

        // create the connection & command objects
        MySqlConnection myConnection1 = new MySqlConnection(WPConnectionString);
        MySqlCommand cmd1;
        try
        {
            // open the connection
            myConnection1.Open();

            cmd1 = myConnection1.CreateCommand();

            // assign the stored procedure string to the command
            cmd1.CommandText = SP;

            // define the command type
            cmd1.CommandType = CommandType.StoredProcedure;

            // pass the parameters to the Store Procedure
            cmd1.Parameters.AddWithValue("@AttachmentID", attachment.ID);
            cmd1.Parameters["@AttachmentID"].Direction = ParameterDirection.Input;

            cmd1.Parameters.AddWithValue("@subpath", parentfolders);
            cmd1.Parameters["@subpath"].Direction = ParameterDirection.Input;

            cmd1.Parameters.AddWithValue("@filename", filename);
            cmd1.Parameters["@filename"].Direction = ParameterDirection.Input;

            // execute the command
            int output = cmd1.ExecuteNonQuery();

            // close the connection
            myConnection1.Close();
        }
        catch (Exception ex)
        {
            Exceptions.Text += "MySQL Exception when logging:" + ex.ToString();
        }

    }

    catch (Exception ex)
    {
        Exceptions.Text += ex.ToString();
    }
}
</code>```

答:
I don't think using the BinaryFormatter is appropriate. If attachment.Image is a byte array, simply write it to the filestream. Forget the memory stream and the binary formatter entirely.

The Binary Formatter class is used to serialize a .Net class into a byte array.  You already have a byte array though, so that step is not needed and is the source of your problem.  Using the binary formatter would be appropriate only if the same binary formatter was used to create the blobs in the database.  But you're storing files, not .Net objects, so it isn't useful here.

I'm not sure why PDFs would load when other files won't.  You'd have to inspect the file using a hex editor to see what changed.

Body:
I have code that passes a list of objects containing the filename and binary data from the db to a loop that creates all the files. The problem that I have is the code below executes and appears to create the files correctly (filename & size is as expected) however, most files are "corrupt" when opened. The file types vary from images (jpg/png) to Word documents, Powerpoint presentations and PDF files. What is strange is that PDF files work perfectly, everything else is "corrupt"

My code is below (attachment is the object in the loop, the path is already created at this stage)

if(Directory.Exists(attachmentPath))
{
    string absolutePath = attachmentPath + "\\importfiles\\" + parentfolders + "\\";

    // no need to check if it exists as it will ignore if it does
    Directory.CreateDirectory(absolutePath);
    absolutePath += filename;
    try
    {
        byte[] byteStream = null;
        object objSave = null;

        objSave = attachment.Image;
        BinaryFormatter tmpBinF = new BinaryFormatter();
        MemoryStream tmpMemStrm = new MemoryStream();
        tmpBinF.Serialize(tmpMemStrm, objSave);
        byteStream = tmpMemStrm.ToArray();

        // Delete the file if it exists.
        if (File.Exists(absolutePath))
        {
            File.Delete(absolutePath);
        }

        // Create the file.
        using (FileStream fs = File.Create(absolutePath))
        {
            fs.Write(byteStream, 0, byteStream.Length);
            fs.Dispose();
        }

    }

    catch (Exception ex)
    {
        Exceptions.Text += ex.ToString();
    }
}

I've used tips from MSDN and followed this tutorial but can't figure out why this is happening.

Thanks go to Amy for pointing out the issue with my approach, if anyone needs it, here's my updated code taking her answer into account. I've also extended it to add a log record on a table in the DB for later use.

if (Directory.Exists(attachmentPath))
{
    // build path from the parts
    string absolutePath = attachmentPath + "\\importfiles\\" + parentfolders + "\\";

    // no need to check if it exists as it will ignore if it does
    Directory.CreateDirectory(absolutePath);
    absolutePath += filename;
    byte[] file = attachment.Image;
    try
    {
        // Delete the file if it exists.
        if (File.Exists(absolutePath))
        {
            File.Delete(absolutePath);
        }

        // Create the file.
        using (FileStream fs = File.Create(absolutePath))
        {
            fs.Write(file, 0, file.Length);
        }

        // start logging to the database

        // add the Stored procedure
        string SP = "sp_add_attachment";

        // create the connection & command objects
        MySqlConnection myConnection1 = new MySqlConnection(WPConnectionString);
        MySqlCommand cmd1;
        try
        {
            // open the connection
            myConnection1.Open();

            cmd1 = myConnection1.CreateCommand();

            // assign the stored procedure string to the command
            cmd1.CommandText = SP;

            // define the command type
            cmd1.CommandType = CommandType.StoredProcedure;

            // pass the parameters to the Store Procedure
            cmd1.Parameters.AddWithValue("@AttachmentID", attachment.ID);
            cmd1.Parameters["@AttachmentID"].Direction = ParameterDirection.Input;

            cmd1.Parameters.AddWithValue("@subpath", parentfolders);
            cmd1.Parameters["@subpath"].Direction = ParameterDirection.Input;

            cmd1.Parameters.AddWithValue("@filename", filename);
            cmd1.Parameters["@filename"].Direction = ParameterDirection.Input;

            // execute the command
            int output = cmd1.ExecuteNonQuery();

            // close the connection
            myConnection1.Close();
        }
        catch (Exception ex)
        {
            Exceptions.Text += "MySQL Exception when logging:" + ex.ToString();
        }

    }

    catch (Exception ex)
    {
        Exceptions.Text += ex.ToString();
    }
}


问:
Execute a method when a user navigates away from a page/route: Angular2
I'm trying to run a function whenever current route is changed. For example, if we are currently on "..../user/user-details", where user-details is a separate component. I want to execute a method whenever the route is changed (shouldn't matter if route changes from the UI or directly from the URL).
I did something in the user-details component:

```<code>constructor(private router: Router) {
  router.events.subscribe(() => {
    console.log('Route changed');
 });
}
</code>```

But the issue with this approach is, it runs on every route change (whether or not we are navigating to or from user-details page). So this is subscribing to app wide routes. I just want it to run whenever we are navigating away from user-details component. Is their a way to do that?

答:
If you want to just run code when leaving the user-details component then you need to create a CanDeactivate Guard on the route.

Setup the guard so that the UserDetailsComponent implments a interface with a method to call before the route gets deactivated. Then register the CanDeactivate Guard on the route and inside the guard call the method on the route.

interface BeforeUnload {
    beforeunload(): Observable<boolean>|Promise<boolean>|boolean;
}

@Component({ /* ... */})
class UserDetailsComponent implements BeforeUnload {
    beforeUnload() {
        /* ... custom code ... */
        return true;
    }
}

@Injectable()
class CanDeactivateComponent implements CanDeactivate<T extends BeforeUnload> {
  constructor() {}

  canDeactivate(
    component: T,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {
    return component.beforeUnload();
  }
}

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'user/user-details',
        component: UserDetailsComponent,
        canDeactivate: [CanDeactivateComponent]
      }
    ])
  ],
  providers: [CanDeactivateComponent]
})
class AppModule {}
```

In this example I set it up so that the route won't leave until the method on the component returns a response but you could immediately return true depending on if beforeUnload is synchronous or not.

Body:
I'm trying to run a function whenever current route is changed. For example, if we are currently on "..../user/user-details", where user-details is a separate component. I want to execute a method whenever the route is changed (shouldn't matter if route changes from the UI or directly from the URL).
I did something in the user-details component:

constructor(private router: Router) {
  router.events.subscribe(() => {
    console.log('Route changed');
 });
}

But the issue with this approach is, it runs on every route change (whether or not we are navigating to or from user-details page). So this is subscribing to app wide routes. I just want it to run whenever we are navigating away from user-details component. Is their a way to do that?

Body:
If you want to just run code when leaving the user-details component then you need to create a CanDeactivate Guard on the route.

Setup the guard so that the UserDetailsComponent implments a interface with a method to call before the route gets deactivated. Then register the CanDeactivate Guard on the route and inside the guard call the method on the route.

interface BeforeUnload {
    beforeunload(): Observable<boolean>|Promise<boolean>|boolean;
}

@Component({ /* ... */})
class UserDetailsComponent implements BeforeUnload {
    beforeUnload() {
        /* ... custom code ... */
        return true;
    }
}

@Injectable()
class CanDeactivateComponent implements CanDeactivate<T extends BeforeUnload> {
  constructor() {}

  canDeactivate(
    component: T,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {
    return component.beforeUnload();
  }
}

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'user/user-details',
        component: UserDetailsComponent,
        canDeactivate: [CanDeactivateComponent]
      }
    ])
  ],
  providers: [CanDeactivateComponent]
})
class AppModule {}

In this example I set it up so that the route won't leave until the method on the component returns a response but you could immediately return true depending on if beforeUnload is synchronous or not.


问:
Force code to execute after another method finishes executing
Here is what I want to do:

setSource is a function which executes about 3 seconds.

```<code> editor.setSource();

 setTimeout(function () {
      //do something, some commands
 }, 3000);
</code>```

I want the //do something, some commands part to be executed AFTER the last line of setSource() is executed. Now I'm doing it with setTimeout, but I think it's not very good solution, because sometimes setSource() will take maybe 5 seconds to execute. How to do this?

答:
I was also looking for solution where I want to execute my second function only after previous function gets executed completely, I tried callback function but still not getting the solution, finally I find the very easiest way to resolve this issue by using simple $.ajax({ }); method code which works for me :).

for example,

$.ajax({
  url: function1(),
  success: function(){
    //function 2 code here or just call function2() here
  }
});
```

that's all, in this code url parameter will call first function and only on the success of its execution function 2 will be called.

Body:
Here is what I want to do:

setSource is a function which executes about 3 seconds.

 editor.setSource();

 setTimeout(function () {
      //do something, some commands
 }, 3000);

I want the //do something, some commands part to be executed AFTER the last line of setSource() is executed. Now I'm doing it with setTimeout, but I think it's not very good solution, because sometimes setSource() will take maybe 5 seconds to execute. How to do this?

Body:
I was also looking for solution where I want to execute my second function only after previous function gets executed completely, I tried callback function but still not getting the solution, finally I find the very easiest way to resolve this issue by using simple $.ajax({ }); method code which works for me :).

for example,

$.ajax({
  url: function1(),
  success: function(){
    //function 2 code here or just call function2() here
  }
});

that's all, in this code url parameter will call first function and only on the success of its execution function 2 will be called.


问:
RabbitMq Direct reply-to aka Fast Rpc with 2 servers
Is it possible to configure 2 Rmq servers in order to use
direct reply-to across them?

e.g.

RpcClient connects Server 1 and makes call to RpcServer, which is connected
to Server 2.

Is it possible to shovel/federate pseudo queue amq.rabbitmq.reply-to

Thanks in advance!

答:
According to this
https://groups.google.com/forum/m/#!topic/rabbitmq-users/uFmMgZ91Ptc

This is not possible because amq.rabbitmq.reply-to
is not a real queue.


问:
how to override STL container function
It's possible, that override some function stl container with the same paremeters?
I want override exactly push_back with some if inside function.
I try but, always have error/information about that function is in vector.

答:
Overriding means that you are going to inherit from STL container. Don't do that! STL containers are not designed for inheriting from them.

As an option, you might encapsulate std::vector into some wrapper class and perform additional functionality before pushing, something like:

```<code>template<typename T>
class Wrapper
{
public:
    template<typename U>
    void push(U&& e)
    {
         // some additional processing
         data.push_back(std::forward<U>(e));
    }

private:
    std::vector<T> data;
};
</code>```

Title: how to override STL container function

Body:
Overriding means that you are going to inherit from STL container. Don't do that! STL containers are not designed for inheriting from them.

As an option, you might encapsulate std::vector into some wrapper class and perform additional functionality before pushing, something like:

template<typename T>
class Wrapper
{
public:
    template<typename U>
    void push(U&& e)
    {
         // some additional processing
         data.push_back(std::forward<U>(e));
    }

private:
    std::vector<T> data;
};