问:
Can you join three tables on the same key if that key could be missing from one or more of the tables?
I'm taking three tables and joining them all together using the same primary key, but with no guarantee that all values exist across all three tables, and I want every value to end up in the final join.

For example, there's a TableA, TableB, and TableC, each with only one column (we'll just call the columns colA, colB, and colC). Value 10 is present in TableA and TableC, but not TableB.

```<code>SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     FULL OUTER JOIN TableC ON TableB.colB = TableC.colC;

+--------+  +--------+  +--------+
|  colA  |  |  colB  |  |  colC  |
+--------+  +--------+  +--------+
|      5 |  |      5 |  |      5 |
|     10 |  |     15 |  |     10 |
|     15 |  +--------+  |     15 |
+--------+              +--------+
</code>```

In the above example, I end up with something like this after the joins:

```<code>+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
| 5      | 5      | 5      |
| null   | null   | 10     |
| 15     | 15     | 15     |
| 10     | null   | null   |
+--------+--------+--------+
</code>```

My expected result is this:

```<code>+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
|      5 | 5      |      5 |
|     10 | null   |     10 |
|     15 | 15     |     15 |
+--------+--------+--------+
</code>```

The logic for my join is to first join TableA and TableB, then join the result with TableC. In this specific scenario, the join does not work. The join can try to match on the column passed through from TableA or the column from TableB, but I'm not sure how to make it check both.

Because I first joined TableA and TableB, there was no matching value in TableB. When I try to join TableC on TableB, it also finds no match, even though the key exists in TableA.

The closest I've gotten to my desired result is by using this query:

```<code>SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     RIGHT OUTER JOIN TableC ON TableC.colC IN (TableA.colA, TableB.colB);

+------+  +------+  +------+     +------+------+------+
| colA |  | colB |  | colC |     | colA | colB | colC |
+------+  +------+  +------+     +------+------+------+
|    5 |  |    5 |  |    5 |     | 5    | 5    |    5 |
|   10 |  |   15 |  |   10 | --> | 10   | null |   10 |
|   15 |  |   25 |  |   15 |     | 15   | 15   |   15 |
+------+  +------+  |   20 |     | null | null |   20 |
                    +------+     +------+------+------+
</code>```

Expected result:

```<code>+------+------+------+
| colA | colB | colC |
+------+------+------+
| 5    | 5    | 5    |
| 10   | null | 10   |
| 15   | 15   | 15   |
| null | null | 20   |
| null | 25   | null |
+------+------+------+
</code>```

This, unfortunately, does not include values that only exist in TableA or TableB in the final joined table, which is why I was using the FULL OUTER JOIN in the first place. With the FULL OUTER JOIN, I can't use the IN clause. Is there a solution that gives me what I want?

DB Fiddle: https://www.db-fiddle.com/f/faMLh4EAAKfBotXbaDofaQ/1

答:
Here's a version that demonstrates a fully three way full outer join.  A successful query will return seven rows:

```
+------+  +------+  +------+     +------+------+------+
| colA |  | colB |  | colC |     | colA | colB | colC |
+------+  +------+  +------+     +------+------+------+
|    1 |  |    2 |  |    4 |     |    1 | null | null |
|    3 |  |    3 |  |    5 | --> | null |    2 | null |
|    5 |  |    6 |  |    6 |     |    3 |    3 | null |
|    7 |  |    7 |  |    7 |     | null | null |    4 |
+------+  +------+  +------+     |    5 | null |    5 |
                                 | null |    6 |    6 |
                                 |    7 |    7 |    7 |
                                 +------+------+------+```

```<code>select ColA, ColB, ColC
  from TableA
  full join TableB
    on ColA=ColB
  full join TableC
    on ColC=coalesce(ColA, ColB)
order by coalesce(ColA, ColB, ColC);
</code>```

The secret is to coalesce the prior table keys in the join condition of each additional table.

You can see it in action here

Body:
I'm taking three tables and joining them all together using the same primary key, but with no guarantee that all values exist across all three tables, and I want every value to end up in the final join.

For example, there's a TableA, TableB, and TableC, each with only one column (we'll just call the columns colA, colB, and colC). Value 10 is present in TableA and TableC, but not TableB.

SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     FULL OUTER JOIN TableC ON TableB.colB = TableC.colC;

+--------+  +--------+  +--------+
|  colA  |  |  colB  |  |  colC  |
+--------+  +--------+  +--------+
|      5 |  |      5 |  |      5 |
|     10 |  |     15 |  |     10 |
|     15 |  +--------+  |     15 |
+--------+              +--------+

In the above example, I end up with something like this after the joins:

+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
| 5      | 5      | 5      |
| null   | null   | 10     |
| 15     | 15     | 15     |
| 10     | null   | null   |
+--------+--------+--------+

My expected result is this:

+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
|      5 | 5      |      5 |
|     10 | null   |     10 |
|     15 | 15     |     15 |
+--------+--------+--------+

The logic for my join is to first join TableA and TableB, then join the result with TableC. In this specific scenario, the join does not work. The join can try to match on the column passed through from TableA or the column from TableB, but I'm not sure how to make it check both.

Because I first joined TableA and TableB, there was no matching value in TableB. When I try to join TableC on TableB, it also finds no match, even though the key exists in TableA.

The closest I've gotten to my desired result is by using this query:

SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     RIGHT OUTER JOIN TableC ON TableC.colC IN (TableA.colA, TableB.colB);

+------+  +------+  +------+     +------+------+------+
| colA |  | colB |  | colC |     | colA | colB | colC |
+------+  +------+  +------+     +------+------+------+
|    5 |  |    5 |  |    5 |     | 5    | 5    |    5 |
|   10 |  |   15 |  |   10 | --> | 10   | null |   10 |
|   15 |  |   25 |  |   15 |     | 15   | 15   |   15 |
+------+  +------+  |   20 |     | null | null |   20 |
                    +------+     +------+------+------+

Expected result:

+------+------+------+
| colA | colB | colC |
+------+------+------+
| 5    | 5    | 5    |
| 10   | null | 10   |
| 15   | 15   | 15   |
| null | null | 20   |
| null | 25   | null |
+------+------+------+

This, unfortunately, does not include values that only exist in TableA or TableB in the final joined table, which is why I was using the FULL OUTER JOIN in the first place. With the FULL OUTER JOIN, I can't use the IN clause. Is there a solution that gives me what I want?

DB Fiddle: https://www.db-fiddle.com/f/faMLh4EAAKfBotXbaDofaQ/1

Body:
Here's a version that demonstrates a fully three way full outer join.  A successful query will return seven rows:

+------+  +------+  +------+     +------+------+------+
| colA |  | colB |  | colC |     | colA | colB | colC |
+------+  +------+  +------+     +------+------+------+
|    1 |  |    2 |  |    4 |     |    1 | null | null |
|    3 |  |    3 |  |    5 | --> | null |    2 | null |
|    5 |  |    6 |  |    6 |     |    3 |    3 | null |
|    7 |  |    7 |  |    7 |     | null | null |    4 |
+------+  +------+  +------+     |    5 | null |    5 |
                                 | null |    6 |    6 |
                                 |    7 |    7 |    7 |
                                 +------+------+------+

select ColA, ColB, ColC
  from TableA
  full join TableB
    on ColA=ColB
  full join TableC
    on ColC=coalesce(ColA, ColB)
order by coalesce(ColA, ColB, ColC);

The secret is to coalesce the prior table keys in the join condition of each additional table.

You can see it in action here


来源: stackexchange

问:
Pasting into contentedittable results in random tag insertion
I am using a contentedittable field as user input so that I can exploit text formatting. Unfortunately I have found that when a user pastes into the field a massive amound of unnessessary html comes with it. I only want the plain text from the clipboard.

Why is this happening?!

A Truncated Example:

```<code><div><br></div><div><span class="Apple-style-span" style="font-family: Arial, 'Liberation Sans', 'DejaVu Sans', sans-serif; font-size: 13px; line-height: 12px; color: rgb(0, 0, 0); "><table style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; border-collapse: collapse; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; background-position: initial initial; background-repeat: initial initial; "><tbody style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; background-position: initial initial; background-repeat: initial initial; "><tr style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; background-position: initial initial; background-repeat: initial initial; "><td class="votecell" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: top; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; width: 60px; background-position: initial initial; background-repeat: initial initial; "><div class="vote" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; text-align: center; background-position: initial initial; background-repeat: initial initial; "><span class="vote-count-post" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 31px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; display: block; color: rgb(128, 129, 133); font-weight: bold; background-position: initial initial; background-repeat: initial initial; ">1</span><a class="vote-down-off" title="This question does not show any research effort; it is unclear or not useful (click again to undo)" style="margin-top: 0px; margin-right: auto; margin-bottom: 0px; margin-left: auto; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 1px; vertical-align: baseline; background-image: url(http://sstatic.net/stackoverflow/img/sprites.png?v=3); background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; color: rgb(0, 119, 204); text-decoration: none; cursor: pointer; overflow-x: hidden; overflow-y: hidden; display: block; width: 41px; height: 25px; text-indent: -9999em; background-position: 0px -300px; background-repeat: no-repeat no-repeat; ">...
</code>```

答:
You can only get the plain text using a hack. Recent versions of both TinyMCE and CKEditor use this technique on their iframe-based editors:

Detect a Ctrl-v / Shift-Insert event using a keypress event handler

In that handler, save the current user selection, add a textarea element off-screen (say at left -1000px) to the document, turn contentEditable off and call focus() on the textarea, thus moving the caret and effectively redirecting the paste

Set a very brief timer (say 1 millisecond) in the event handler to call another function that stores the textarea value, removes the textarea from the document, turns contentEditable back on, restores the user selection and pastes the text in.

Note that this will only work for keyboard paste events and not pastes from the context or edit menus. The paste event would be better but by the time it fires, it's too late to redirect the caret into the textarea in most browsers.

ContentLicense: CC BY-SA 3.0

Body:
I am using a contentedittable field as user input so that I can exploit text formatting. Unfortunately I have found that when a user pastes into the field a massive amound of unnessessary html comes with it. I only want the plain text from the clipboard.

Why is this happening?!

A Truncated Example:

<table style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; border-collapse: collapse; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; background-position: initial initial; background-repeat: initial initial; "><tbody style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; background-position: initial initial; background-repeat: initial initial; "><tr style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; background-position: initial initial; background-repeat: initial initial; "><td class="votecell" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: top; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; width: 60px; background-position: initial initial; background-repeat: initial initial; "><div class="vote" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 13px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; text-align: center; background-position: initial initial; background-repeat: initial initial; "><span class="vote-count-post" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 31px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; display: block; color: rgb(128, 129, 133); font-weight: bold; background-position: initial initial; background-repeat: initial initial; ">1<a class="vote-down-off" title="This question does not show any research effort; it is unclear or not useful (click again to undo)" style="margin-top: 0px; margin-right: auto; margin-bottom: 0px; margin-left: auto; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; font-size: 1px; vertical-align: baseline; background-image: url(http://sstatic.net/stackoverflow/img/sprites.png?v=3); background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; color: rgb(0, 119, 204); text-decoration: none; cursor: pointer; overflow-x: hidden; overflow-y: hidden; display: block; width: 41px; height: 25px; text-indent: -9999em; background-position: 0px -300px; background-repeat: no-repeat no-repeat; ">...


问:
Why is this Recursion not getting its base case?
I am trying to implement a merge sort function. Here is my code:

```<code>void
merge_sort(int a[], int l, int u)
{
  int mid = (l + u) / 2;
  if (mid) {
    merge_sort(a, l, mid);
    merge_sort(a, mid + 1, u);
    merge(a, l, mid, u);
  }
}
</code>```

I checked that mid gets value 0 but then again gets its initial value and Turns into an infinite loop.

答:
You must check if the range has at least 2 elements:

/* sort a range of elements from `l` to `u` inclusively */
void merge_sort(int a[], int l, int u) {
    if (l < u) {
        int mid = l + (u - l) / 2;
        merge_sort(a, l, mid);
        merge_sort(a, mid + 1, u);
        merge(a, l, mid, u);
    }
}
```

<p>If the upper bound <code>u</code> is not included in the range, the code should be changed to:</p>

<pre class="lang-c prettyprint-override"><code>/* sort a range of elements from `l` included to `u` excluded */
void merge_sort(int a[], int l, int u) {
    if (u - l >= 2) {
        int mid = l + (u - l) / 2;
        merge_sort(a, l, mid);
        merge_sort(a, mid, u);
        merge(a, l, mid, u);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to implement a merge sort function. Here is my code:

void
merge_sort(int a[], int l, int u)
{
  int mid = (l + u) / 2;
  if (mid) {
    merge_sort(a, l, mid);
    merge_sort(a, mid + 1, u);
    merge(a, l, mid, u);
  }
}

I checked that mid gets value 0 but then again gets its initial value and Turns into an infinite loop.

Body:
You must check if the range has at least 2 elements:

/* sort a range of elements from `l` to `u` inclusively */
void merge_sort(int a[], int l, int u) {
    if (l < u) {
        int mid = l + (u - l) / 2;
        merge_sort(a, l, mid);
        merge_sort(a, mid + 1, u);
        merge(a, l, mid, u);
    }
}

If the upper bound u is not included in the range, the code should be changed to:

/* sort a range of elements from `l` included to `u` excluded */
void merge_sort(int a[], int l, int u) {
    if (u - l >= 2) {
        int mid = l + (u - l) / 2;
        merge_sort(a, l, mid);
        merge_sort(a, mid, u);
        merge(a, l, mid, u);
    }
}


问:
How do i fix "npm does not support Node.js v12.14.1" when they came from the same LTS download?
Truthfully this has never happened with me on any development environment
My node version: 12.14.1
My npm version: 6.13.4

I was building a Gatsby Site using Sanity.io as a CRM and Im getting this error:

```<code>ahinds$ npm run dev

> sanity-gatsby-blog@1.0.7 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt
> lerna run dev --parallel

lerna notice cli v3.20.2
lerna info Executing command in 2 packages: "npm run dev"
sanity-gatsby-blog-web: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-web: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-web: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-web: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-web: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-studio: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-studio: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-studio: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-studio: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-studio: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-web: > sanity-gatsby-blog-web@1.0.1 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/web
sanity-gatsby-blog-web: > npm run clean-cache && gatsby develop
sanity-gatsby-blog-studio: > sanity-gatsby-blog-studio@1.0.5 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/studio
sanity-gatsby-blog-studio: > sanity start
sanity-gatsby-blog-web: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-web: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-web: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-web: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-web: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-studio: Error occured trying to resolve project root:
sanity-gatsby-blog-studio: Unexpected token ] in JSON at position 425
sanity-gatsby-blog-studio: npm ERR! code ELIFECYCLE
sanity-gatsby-blog-studio: npm ERR! errno 1
sanity-gatsby-blog-studio: npm ERR! sanity-gatsby-blog-studio@1.0.5 dev: `sanity start`
sanity-gatsby-blog-studio: npm ERR! Exit status 1
sanity-gatsby-blog-studio: npm ERR!
sanity-gatsby-blog-studio: npm ERR! Failed at the sanity-gatsby-blog-studio@1.0.5 dev script.
sanity-gatsby-blog-studio: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
sanity-gatsby-blog-web: > sanity-gatsby-blog-web@1.0.1 clean-cache /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/web
sanity-gatsby-blog-web: > gatsby clean
sanity-gatsby-blog-studio: npm ERR! A complete log of this run can be found in:
sanity-gatsby-blog-studio: npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_015Z-debug.log
lerna ERR! npm run dev exited 1 in 'sanity-gatsby-blog-studio'
lerna ERR! npm run dev stdout:

> sanity-gatsby-blog-studio@1.0.5 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/studio
> sanity start

lerna ERR! npm run dev stderr:
npm WARN npm npm does not support Node.js v12.14.1
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
npm WARN npm You can find the latest version at https://nodejs.org/
Error occured trying to resolve project root:
Unexpected token ] in JSON at position 425
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sanity-gatsby-blog-studio@1.0.5 dev: `sanity start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sanity-gatsby-blog-studio@1.0.5 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_015Z-debug.log

lerna ERR! npm run dev exited 1 in 'sanity-gatsby-blog-studio'
lerna WARN complete Waiting for 1 child process to exit. CTRL-C to exit immediately.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sanity-gatsby-blog@1.0.7 dev: `lerna run dev --parallel`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sanity-gatsby-blog@1.0.7 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_097Z-debug.log
</code>```

Any idea why this version of node wouldn't work with this version of npm? I installed both from the NOde.js website so they were packaged together.

Here is my Repo

答:
Based on the details from here, they should be compatible with each other.

I suggest you to uninstall npm using 'npm uninstall -g npm' and nodejs. Then reinstalling nodejs might fix the issue.

Body:
Truthfully this has never happened with me on any development environment
My node version: 12.14.1
My npm version: 6.13.4

I was building a Gatsby Site using Sanity.io as a CRM and Im getting this error:

ahinds$ npm run dev

> sanity-gatsby-blog@1.0.7 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt
> lerna run dev --parallel

lerna notice cli v3.20.2
lerna info Executing command in 2 packages: "npm run dev"
sanity-gatsby-blog-web: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-web: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-web: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-web: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-web: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-studio: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-studio: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-studio: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-studio: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-studio: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-web: > sanity-gatsby-blog-web@1.0.1 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/web
sanity-gatsby-blog-web: > npm run clean-cache && gatsby develop
sanity-gatsby-blog-studio: > sanity-gatsby-blog-studio@1.0.5 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/studio
sanity-gatsby-blog-studio: > sanity start
sanity-gatsby-blog-web: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-web: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-web: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-web: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-web: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-studio: Error occured trying to resolve project root:
sanity-gatsby-blog-studio: Unexpected token ] in JSON at position 425
sanity-gatsby-blog-studio: npm ERR! code ELIFECYCLE
sanity-gatsby-blog-studio: npm ERR! errno 1
sanity-gatsby-blog-studio: npm ERR! sanity-gatsby-blog-studio@1.0.5 dev: `sanity start`
sanity-gatsby-blog-studio: npm ERR! Exit status 1
sanity-gatsby-blog-studio: npm ERR!
sanity-gatsby-blog-studio: npm ERR! Failed at the sanity-gatsby-blog-studio@1.0.5 dev script.
sanity-gatsby-blog-studio: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
sanity-gatsby-blog-web: > sanity-gatsby-blog-web@1.0.1 clean-cache /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/web
sanity-gatsby-blog-web: > gatsby clean
sanity-gatsby-blog-studio: npm ERR! A complete log of this run can be found in:
sanity-gatsby-blog-studio: npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_015Z-debug.log
lerna ERR! npm run dev exited 1 in 'sanity-gatsby-blog-studio'
lerna ERR! npm run dev stdout:

> sanity-gatsby-blog-studio@1.0.5 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/studio
> sanity start

lerna ERR! npm run dev stderr:
npm WARN npm npm does not support Node.js v12.14.1
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
npm WARN npm You can find the latest version at https://nodejs.org/
Error occured trying to resolve project root:
Unexpected token ] in JSON at position 425
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sanity-gatsby-blog-studio@1.0.5 dev: `sanity start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sanity-gatsby-blog-studio@1.0.5 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_015Z-debug.log

lerna ERR! npm run dev exited 1 in 'sanity-gatsby-blog-studio'
lerna WARN complete Waiting for 1 child process to exit. CTRL-C to exit immediately.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sanity-gatsby-blog@1.0.7 dev: `lerna run dev --parallel`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sanity-gatsby-blog@1.0.7 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_097Z-debug.log

Any idea why this version of node wouldn't work with this version of npm? I installed both from the NOde.js website so they were packaged together.

Here is my Repo


问:
How to fill dictionaries values by using the for loop?
I have three lists, each contains a unique ID of the employee. For example,

```<code>bug = [1,2,3,4,4,4,4,4,5,6,7,8,8,8]
task = [1,1,1,1,2,9]
subtask = [10, 11, 11, 11, 8, 8, 8, 8 ,8 , 8, 6]
</code>```

The number of references of employee ID shows, how many issues were solved by the employee. For example, employee with ID=1 solved 1 bug, 4 tasks and 0 subtasks. I want to create a dictionary, which has the next structure: keys are IDs of employees and values are list of size 3, each value of list shows how much bugs, tasks and subtasks employee with ID = something solved. For example, in my case I have to obtain the next dictionary:

```<code>all_employees = {1:[1, 4, 0], 2:[1, 1, 0], 3:[1, 0, 0], 4:[5, 0, 0], 5:[1, 0, 0], 6:[1, 0, 1], \
                 7:[1, 0, 1], 8:[3, 0, 6], 9:[0, 1, 0], 10:[0, 0, 1], 11:[0, 0, 3]}
</code>```

This is my code:

```<code>from collections import defaultdict, Counter
bug = [1,2,3,4,4,4,4,4,5,6,7,8,8,8]
task = [1,1,1,1,2,9]
subtask = [10, 11, 11, 11, 8, 8, 8, 8 ,8 , 8, 6]
all_issues = bug + task + subtask
all_emlpoyees = dict.fromkeys(all_issues, [0, 0, 0])
bug_d = dict(Counter(bug))
task_d = dict(Counter(task))
subtask_d = dict(Counter(subtask))
for i in all_employees.keys():
    try:
        print("value = ", bug_d[i])
        print ("key = ", i)

        all_employees[i][0] = bug_d[i]
    except Exception as e:
        pass
print (all_assignees)
</code>```

In my opinion, this code should produce the same dictionary, as mentioned above, but only with one, first, non-zero value at its lists, but my output looks like:

```<code>{1: [3, 0, 0], 2: [3, 0, 0], 3: [3, 0, 0], 4: [3, 0, 0], 5: [3, 0, 0], 6: [3, 0, 0], 7: [3, 0, 0], 8: [3, 0, 0], 9: [3, 0, 0], 10: [3, 0, 0], 11: [3, 0, 0]}
</code>```

in spite of two prints at the for loop shows correct values.
Any ideas, what am I doing wrong?

Thanks for help, issue solved.

Body:
I have three lists, each contains a unique ID of the employee. For example,

bug = [1,2,3,4,4,4,4,4,5,6,7,8,8,8]
task = [1,1,1,1,2,9]
subtask = [10, 11, 11, 11, 8, 8, 8, 8 ,8 , 8, 6]

The number of references of employee ID shows, how many issues were solved by the employee. For example, employee with ID=1 solved 1 bug, 4 tasks and 0 subtasks. I want to create a dictionary, which has the next structure: keys are IDs of employees and values are list of size 3, each value of list shows how much bugs, tasks and subtasks employee with ID = something solved. For example, in my case I have to obtain the next dictionary:

all_employees = {1:[1, 4, 0], 2:[1, 1, 0], 3:[1, 0, 0], 4:[5, 0, 0], 5:[1, 0, 0], 6:[1, 0, 1], \
                 7:[1, 0, 1], 8:[3, 0, 6], 9:[0, 1, 0], 10:[0, 0, 1], 11:[0, 0, 3]}

This is my code:

from collections import defaultdict, Counter
bug = [1,2,3,4,4,4,4,4,5,6,7,8,8,8]
task = [1,1,1,1,2,9]
subtask = [10, 11, 11, 11, 8, 8, 8, 8 ,8 , 8, 6]
all_issues = bug + task + subtask
all_emlpoyees = dict.fromkeys(all_issues, [0, 0, 0])
bug_d = dict(Counter(bug))
task_d = dict(Counter(task))
subtask_d = dict(Counter(subtask))
for i in all_employees.keys():
    try:
        print("value = ", bug_d[i])
        print ("key = ", i)

        all_employees[i][0] = bug_d[i]
    except Exception as e:
        pass
print (all_assignees)

In my opinion, this code should produce the same dictionary, as mentioned above, but only with one, first, non-zero value at its lists, but my output looks like:

{1: [3, 0, 0], 2: [3, 0, 0], 3: [3, 0, 0], 4: [3, 0, 0], 5: [3, 0, 0], 6: [3, 0, 0], 7: [3, 0, 0], 8: [3, 0, 0], 9: [3, 0, 0], 10: [3, 0, 0], 11: [3, 0, 0]}

in spite of two prints at the for loop shows correct values.
Any ideas, what am I doing wrong?

Thanks for help, issue solved.

Body:
here is one line of code:

bug = [1,2,3,4,4,4,4,4,5,6,7,8,8,8]
task = [1,1,1,1,2,9]
subtask = [10, 11, 11, 11, 8, 8, 8, 8 ,8 , 8, 6]

{i:[bug.count(i), task.count(i), subtask.count(i)] for i in set(bug+task+subtask)}

Out[1]:
{1: [1, 4, 0],
 2: [1, 1, 0],
 3: [1, 0, 0],
 4: [5, 0, 0],
 5: [1, 0, 0],
 6: [1, 0, 1],
 7: [1, 0, 0],
 8: [3, 0, 6],
 9: [0, 1, 0],
10: [0, 0, 1],
11: [0, 0, 3]}

it's the same like using loop:

for i in set(bug+task+subtask):
    a[i] = [bug.count(i), task.count(i), subtask.count(i)]

print(a)


问:
onClick not firing, event IS a function
I realize there are 400 questions with the same title here, but for every one, the issue is that the onClick method was NOT a function. Mine is.

```<code><button
    type="button"
    key={level}
    onClick={() => {
      console.log("Why Can't You See Me?")
      props.onSelected(item)
    }}
  >
    {title()}
  </button>
</code>```

I selected the button that I am clicking with chrome developer tools to show that it is 100% the correct button. I'm so confused as to why the onClick isn't firing.

The button is positioned "absolute", if that helps. Could there be anything intercepting the onClick event? I'm relatively new to frontend, but I'm assuming that the issue is with something over top of it, but i dont see it at all.

I'm using https://github.com/mlaursen/react-dd-menu, I basically copied their example code. Any thoughts?

Edit: Added a video demonstrating this: https://youtu.be/qnsp4XTAKzI ... something else it taking priority perhaps?

Edit 2: Here is a picture demonstrating the result of jsejcksn's command.. undefined:

Edit 3: Replaced {title()} with {"This button does not work"} and it still does not accept clicks.

Edit 4: Reproduced on Codepen: https://codesandbox.io/s/adoring-wozniak-r6vct?fontsize=14&hidenavigation=1&theme=dark

答:
The problem stems from this line: https://github.com/mlaursen/react-dd-menu/blob/master/src/js/NestedDropdownMenu.js#L45. It's intercepting all clicks and stopping propagation. Removing this line: https://github.com/mlaursen/react-dd-menu/blob/master/src/js/NestedDropdownMenu.js#L54, fixes the issue.

Working example:

That said, the react-dd-menu package is extremely dated. I'd recommend looking for other alternatives (or developing your own drop menu!).

Title: onClick not firing, event IS a function

Body:
I realize there are 400 questions with the same title here, but for every one, the issue is that the onClick method was NOT a function. Mine is.

<button
    type="button"
    key={level}
    onClick={() => {
      console.log("Why Can't You See Me?")
      props.onSelected(item)
    }}
  >
    {title()}
  </button>

I selected the button that I am clicking with chrome developer tools to show that it is 100% the correct button. I'm so confused as to why the onClick isn't firing.

The button is positioned "absolute", if that helps. Could there be anything intercepting the onClick event? I'm relatively new to frontend, but I'm assuming that the issue is with something over top of it, but i dont see it at all.

I'm using https://github.com/mlaursen/react-dd-menu, I basically copied their example code. Any thoughts?

Edit: Added a video demonstrating this: https://youtu.be/qnsp4XTAKzI ... something else it taking priority perhaps?

Edit 2: Here is a picture demonstrating the result of jsejcksn's command.. undefined:

Edit 3: Replaced {title()} with {"This button does not work"} and it still does not accept clicks.

Edit 4: Reproduced on Codepen: https://codesandbox.io/s/adoring-wozniak-r6vct?fontsize=14&hidenavigation=1&theme=dark


问:
Where do old dated commits come from in AOSP?
I'm following the commits to master branch of Messaging app in AOSP. Sometimes I see very old dated commits appear at the top in its logs:

How do I find where these commits come from? If they're on a separate branch, how do I find that branch and the initial original commit into the repository?

答:
That is the latest commit on master. The date is when the author made the change, but it was committed recently (2 days ago).

The author and committer need not be the same.


问:
How to use the "source" command in Zsh
I'm working inside a Zsh terminal on a Mac.

I'm trying to use the source command so that I can just call my script by name, rather than typing the path to the ".sh" script. The source command does not return any errors, but once I try calling the ".sh" file by name it returns "command not found."

I've also tried typing in the absolute path when using the source command, but with no luck.

Terminal commands:

```<code>source ~/Documents/marco.sh
marco
zsh: command not found: marco
</code>```

marco.sh

```<code>#!/usr/bin/env bash
touch ~/Documents/marco.txt
echo $(pwd) > ~/Documents/marco.txt
</code>```

答:
To do it exactly the way you want to, you can make a marco function:

```<code># marco.sh
marco () {
  touch ~/Documents/marco.txt
  echo $(pwd) > ~/Documents/marco.txt
}
</code>```

Then you source it and run marco. If you're going to use this a lot, I suggest putting the function in .zshrc or another file that will be sourced by your shell automatically.

And as suggested in comments, you could also put your original marco.sh in your path. I like to use ~/bin for these types of personal executables:

```<code>$ mkdir ~/bin
$ mv ~/Documents/marco.sh ~/bin
$ export PATH="$HOME/bin:$PATH"
$ marco.sh
</code>```

Again, put the export PATH line in your .zshrc or similar file.

Title: How to use the "source" command in Zsh

Body:
I'm working inside a Zsh terminal on a Mac.

I'm trying to use the source command so that I can just call my script by name, rather than typing the path to the ".sh" script. The source command does not return any errors, but once I try calling the ".sh" file by name it returns "command not found."

I've also tried typing in the absolute path when using the source command, but with no luck.

Terminal commands:

source ~/Documents/marco.sh
marco
zsh: command not found: marco

marco.sh

#!/usr/bin/env bash
touch ~/Documents/marco.txt
echo $(pwd) > ~/Documents/marco.txt

Body:
To do it exactly the way you want to, you can make a marco function:

# marco.sh
marco () {
  touch ~/Documents/marco.txt
  echo $(pwd) > ~/Documents/marco.txt
}

Then you source it and run marco. If you're going to use this a lot, I suggest putting the function in .zshrc or another file that will be sourced by your shell automatically.

And as suggested in comments, you could also put your original marco.sh in your path. I like to use ~/bin for these types of personal executables:

$ mkdir ~/bin
$ mv ~/Documents/marco.sh ~/bin
$ export PATH="$HOME/bin:$PATH"
$ marco.sh

Again, put the export PATH line in your .zshrc or similar file.


问:
In C# (or any language) what is/are your favourite way of removing repetition?
I've just coded a 700 line class. Awful. I hang my head in shame.  It's as opposite to DRY as a British summer.

It's full of cut and paste with minor tweaks here and there.  This makes it's a prime candidate for refactoring.  Before I embark on this, I'd thought I'd ask when you have lots of repetition, what are the first refactoring opportunities you look for?

For the record, mine are probably using:

Generic classes and methods

Method overloading/chaining.

What are yours?

答:
I might go something like this:

Create custom (private) types for data structures and put all the related logic in there. Dictionary<string, List<int>> etc.

Make inner functions or properties that guarantee behaviour. If you’re continually checking conditions from a publically accessible property then create an private getter method with all of the checking baked in.

Split methods apart that have too much going on. If you can’t put something succinct into the  or give it a good name, then start breaking the function apart until the code is (even if these “child” functions aren’t used anywhere else).

If all else fails, slap a [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] on it and comment why.

OwnerDisplayName: IainMH

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Ant


问:
Wordpress adding -1 to url even when page is a child page
My title may be confusing, but hopefully a simple problem.  I have a page "Classes", and another page "Account / Classes".  I'd like both pages to have slug "classes".

site.com/classes

site.com/account/classes

For some reason it's detecting a conflict and renaming it to /account/classes-1.  There are no other "classes" pages.  I know it will do this if 2 pages are on the same hierarchy, but shouldn't with subpages, I would think.

Any suggestions?  Thank you!

答: It was a slug modifier plugin causing the issue.  Marking this solved.  Thanks for looking!</p>


问:
split on multiple characters in string
I have a list of filenames that I need to sort based on a section within the string. However, it only works if I make the file extension part of my sorting dictionary. I want this to work if the file is a .jpg or a .png, so I am trying to split on both the '_' and the '.' character.

```<code>sorting = ['FRONT', 'BACK', 'LEFT', 'RIGHT', 'INGREDIENTS', 'INSTRUCTIONS', 'INFO', 'NUTRITION', 'PRODUCT']

filelist = ['3006345_2234661_ENG_PRODUCT.jpg', '3006345_2234661_ENG_FRONT.jpg', '3006345_2234661_ENG_LEFT.jpg', '3006345_2234661_ENG_RIGHT.jpg', '3006345_2234661_ENG_BACK.jpg', '3006345_2234661_ENG_INGREDIENTS.jpg', '3006345_2234661_ENG_NUTRITION.jpg', '3006345_2234661_ENG_INSTRUCTIONS.jpg', '3006345_2234661_ENG_INFO.jpg']

sort = sorted(filelist, key = lambda x : sorting.index(x.re.split('_|.')[3]))

print(sort)
</code>```

This returns the error "AttributeError: 'str' object has no attribute 're'"

What do I need to do to split on both the _ and . when splitting out my strings for sorting? I only want to use the split for the sorting, not for re-forming the strings.

答:
Here's the fixed code:

```<code>sorted_output = sorted(filelist,key=lambda x: sorting.index(re.split(r'_|\.',x)[3]))
</code>```

The string input to re.split() should be passed as the second argument to the function; you do not call re.split() on a string. The first argument is the regular expression itself which you had correct.

Also: you need to escape the . with a \ because the full-stop or period is a special character in regular expressions which matches everything.

Output:

```<code>In [13]: sorted(filelist,key=lambda x: sorting.index(re.split(r'_|\.',x)[3]))
Out[13]:
['3006345_2234661_ENG_FRONT.jpg',
 '3006345_2234661_ENG_BACK.jpg',
 '3006345_2234661_ENG_LEFT.jpg',
 '3006345_2234661_ENG_RIGHT.jpg',
 '3006345_2234661_ENG_INGREDIENTS.jpg',
 '3006345_2234661_ENG_INSTRUCTIONS.jpg',
 '3006345_2234661_ENG_INFO.jpg',
 '3006345_2234661_ENG_NUTRITION.jpg',
 '3006345_2234661_ENG_PRODUCT.jpg']
</code>```

Edit: as @Todd mentions in the comments, if you want to additionally ensure that the strings are sorted by the numeric part after the first sort takes place then use:

```<code>sorted(filelist,key=lambda x: [sorting.index(re.split(r'_|\.',x)[3]),x])
</code>```

Title: split on multiple characters in string

Body:
I have a list of filenames that I need to sort based on a section within the string. However, it only works if I make the file extension part of my sorting dictionary. I want this to work if the file is a .jpg or a .png, so I am trying to split on both the '_' and the '.' character.

sorting = ['FRONT', 'BACK', 'LEFT', 'RIGHT', 'INGREDIENTS', 'INSTRUCTIONS', 'INFO', 'NUTRITION', 'PRODUCT']

filelist = ['3006345_2234661_ENG_PRODUCT.jpg', '3006345_2234661_ENG_FRONT.jpg', '3006345_2234661_ENG_LEFT.jpg', '3006345_2234661_ENG_RIGHT.jpg', '3006345_2234661_ENG_BACK.jpg', '3006345_2234661_ENG_INGREDIENTS.jpg', '3006345_2234661_ENG_NUTRITION.jpg', '3006345_2234661_ENG_INSTRUCTIONS.jpg', '3006345_2234661_ENG_INFO.jpg']

sort = sorted(filelist, key = lambda x : sorting.index(x.re.split('_|.')[3]))

print(sort)

This returns the error "AttributeError: 'str' object has no attribute 're'"

What do I need to do to split on both the _ and . when splitting out my strings for sorting? I only want to use the split for the sorting, not for re-forming the strings.

Body:
Here's the fixed code:

sorted_output = sorted(filelist,key=lambda x: sorting.index(re.split(r'_|\.',x)[3]))

The string input to re.split() should be passed as the second argument to the function; you do not call re.split() on a string. The first argument is the regular expression itself which you had correct.

Also: you need to escape the . with a \ because the full-stop or period is a special character in regular expressions which matches everything.

Output:

In [13]: sorted(filelist,key=lambda x: sorting.index(re.split(r'_|\.',x)[3]))
Out[13]:
['3006345_2234661_ENG_FRONT.jpg',
 '3006345_2234661_ENG_BACK.jpg',
 '3006345_2234661_ENG_LEFT.jpg',
 '3006345_2234661_ENG_RIGHT.jpg',
 '3006345_2234661_ENG_INGREDIENTS.jpg',
 '3006345_2234661_ENG_INSTRUCTIONS.jpg',
 '3006345_2234661_ENG_INFO.jpg',
 '3006345_2234661_ENG_NUTRITION.jpg',
 '3006345_2234661_ENG_PRODUCT.jpg']

Edit: as @Todd mentions in the comments, if you want to additionally ensure that the strings are sorted by the numeric part after the first sort takes place then use:

sorted(filelist,key=lambda x: [sorting.index(re.split(r'_|\.',x)[3]),x])


问:
Alternatives to the Gradle Gretty Plugin
I’m trying to upgrade some old code that used the Jetty plugin in Gradle. I would like to upgrade the Gradle version beyond Gradle v3.5, but Gradle v4.0 and above has the Jetty plugin removed. Unfortunately, we are now required to use Gretty.

I’m using IntelliJ. My problems with the newer Gretty plugin are:

JVM Args and System properties specified on the commandline have to be manually put into the Gretty configuration.

At least in IntelliJ, I could do out of the box debugging with the Jetty plugin, but need to run two executions including the app and the Remote, and use a different Gradle task for debugging (e.g. jettyRunDebug) with Gretty.

What are the alternatives to Gretty? Anything that can substitute for the old  Jetty plugin.

答:
How about just skipping the Gretty plugin entirely and just using Unit testing?

See: https://stackoverflow.com/a/29759263/775715


问:
python3 pandas get specific row and specific column
The goal is to take a data frame that prints like this:

```<code>     Tag  Posts
0  metal  27323
1 plastic 11192
</code>```

But only get the value:

```<code>27323
</code>```

IMPORTANT: I CAN NOT USE A NUMERICAL VALUE TO FIND THE ROW. THE ROW MUST BE LOCATED BY TAG NAME THEN COLUMN "POSTS" RETRIEVED FROM THAT ROW TO RETURN 27323

Here is what I have been trying:

```<code>tag = ['metal', 'plastic']
num = ['27323', '11192']

df = pd.DataFrame(
    {
        'Tag': tag,
        'Posts': num,
    })

# Then write data to csv file
df.to_csv('tag_data.csv', index=False)

# Read that csv file but only retrieve the row for 'metal'
read_csv = pd.read_csv('tag_data.csv', names='metal')

# Then retrieve the column for 'num'
print(read_csv.loc[0,'Posts'])
</code>```

This returns this error:

```<code>"cannot do {form} indexing on {type(self)} with these "
TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <class 'int'>
</code>```

Thanks for taking the time to help me if you can.

答:
You read the file incorrectly. Do not pass the names='metal' option, it makes one of the columns have the name "metal" rather than "Tag". Once you fix that, here's the answer:

```<code>read_csv.loc[read_csv.Tag == 'metal', 'Posts']
# 0    27323
</code>```

Body:
The goal is to take a data frame that prints like this:

     Tag  Posts
0  metal  27323
1 plastic 11192

But only get the value:

27323

IMPORTANT: I CAN NOT USE A NUMERICAL VALUE TO FIND THE ROW. THE ROW MUST BE LOCATED BY TAG NAME THEN COLUMN "POSTS" RETRIEVED FROM THAT ROW TO RETURN 27323

Here is what I have been trying:

tag = ['metal', 'plastic']
num = ['27323', '11192']

df = pd.DataFrame(
    {
        'Tag': tag,
        'Posts': num,
    })

# Then write data to csv file
df.to_csv('tag_data.csv', index=False)

# Read that csv file but only retrieve the row for 'metal'
read_csv = pd.read_csv('tag_data.csv', names='metal')

# Then retrieve the column for 'num'
print(read_csv.loc[0,'Posts'])

This returns this error:

"cannot do {form} indexing on {type(self)} with these "
TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <class 'int'>

Thanks for taking the time to help me if you can.

Body:
You read the file incorrectly. Do not pass the names='metal' option, it makes one of the columns have the name "metal" rather than "Tag". Once you fix that, here's the answer:

read_csv.loc[read_csv.Tag == 'metal', 'Posts']
# 0    27323


问:
Update table based on another table
I'm trying to update a column in a table based on another column in another table.

```<code>UPDATE eval e
   SET rank = (SELECT p.desc
                 FROM Position p
                WHERE p.id = e.faculty
                  AND p.date >= '2011-05-20'
              )
</code>```

p.id and e.faculty correspond. I want to update rank with p.desc if the id's are the same. (e.faculty and p.id)

Any help will be great! :)

答:
Try this for SQL Server:

```<code>UPDATE dbo.eval
SET rank = p.desc
FROM dbo.Position p
WHERE p.id = eval.faculty and p.date >= '2011-05-20'
</code>```

or if you need an alias on the base table (for whatever reason), you need to do this:

```<code>UPDATE dbo.eval
SET rank = p.desc
FROM dbo.eval e
INNER JOIN dbo.Position p ON p.id = e.faculty
WHERE p.date >= '2011-05-20'
</code>```

Title: Update table based on another table

Body:
I'm trying to update a column in a table based on another column in another table.

UPDATE eval e
   SET rank = (SELECT p.desc
                 FROM Position p
                WHERE p.id = e.faculty
                  AND p.date >= '2011-05-20'
              )

p.id and e.faculty correspond. I want to update rank with p.desc if the id's are the same. (e.faculty and p.id)

Any help will be great! :)

Body:
Try this for SQL Server:

UPDATE dbo.eval
SET rank = p.desc
FROM dbo.Position p
WHERE p.id = eval.faculty and p.date >= '2011-05-20'

or if you need an alias on the base table (for whatever reason), you need to do this:

UPDATE dbo.eval
SET rank = p.desc
FROM dbo.eval e
INNER JOIN dbo.Position p ON p.id = e.faculty
WHERE p.date >= '2011-05-20'


问:
Fill column in pandas based on prior row data until change
I have a data frame:

df = pd.DataFrame({'player':['John Adams', 'Mark Capone', 'Cecil Milton', 'Hector James', 'Hector James', 'Luke Valentine', 'Luke Valentine'], 'action':['Starts at PG', 'Dribbles', 'Passes', 'receives pass', 'Travels', 'Subs in at PG', 'Passes']})

The first column is the player. The second column is the action the player takes.

I want to create a third column that tracks who is in at PG.  I add the column:

df['PG'] = " "

I then write the following to populate the PG column with the name of the player:

df.loc[(df.action == 'Starts at PG'), 'PG'] = df['player']

df.loc[(df.action == 'Subs in at PG'), 'PG'] = df['player']

The issue I cannot figure out is how to forward fill the PG column until it is changed at row 5, and then fill with the new value from 5 to the end.  I've used ffill on numeric columns before, but this is different because it is a string I'm working with. Any help is greatly appreciated.

To be clear, I'm trying to get "John Adams" in the PG column for rows 0 through 4 and "Luke Valentine" for rows 5 and 6.

答:
Try ffill, which means forward fill all nan values:

```<code> df['PG'] = df.player.where(df.action.str.contains('PG')).ffill()
</code>```

Output:

```<code>           player         action              PG
0      John Adams   Starts at PG      John Adams
1     Mark Capone       Dribbles      John Adams
2    Cecil Milton         Passes      John Adams
3    Hector James  receives pass      John Adams
4    Hector James        Travels      John Adams
5  Luke Valentine  Subs in at PG  Luke Valentine
6  Luke Valentine         Passes  Luke Valentine
</code>```

Body:
Try ffill, which means forward fill all nan values:

 df['PG'] = df.player.where(df.action.str.contains('PG')).ffill()

Output:

           player         action              PG
0      John Adams   Starts at PG      John Adams
1     Mark Capone       Dribbles      John Adams
2    Cecil Milton         Passes      John Adams
3    Hector James  receives pass      John Adams
4    Hector James        Travels      John Adams
5  Luke Valentine  Subs in at PG  Luke Valentine
6  Luke Valentine         Passes  Luke Valentine


答:
You can map the lists as a list of Counter first, so that you can create the desired dict by iterating over a set of all the keys:

```<code>counts = list(map(Counter, (bug, task, subtask)))
all_employees = {id: [c[id] for c in counts] for id in {id for c in counts for id in c}}
</code>```

all_employees becomes:

```<code>{1: [1, 4, 0], 2: [1, 1, 0], 3: [1, 0, 0], 4: [5, 0, 0], 5: [1, 0, 0], 6: [1, 0, 1], 7: [1, 0, 0], 8: [3, 0, 6], 9: [0, 1, 0], 10: [0, 0, 1], 11: [0, 0, 3]}
</code>```

Title: How to fill dictionaries values by using the for loop?

Body:
You can map the lists as a list of Counter first, so that you can create the desired dict by iterating over a set of all the keys:

counts = list(map(Counter, (bug, task, subtask)))
all_employees = {id: [c[id] for c in counts] for id in {id for c in counts for id in c}}

all_employees becomes:

{1: [1, 4, 0], 2: [1, 1, 0], 3: [1, 0, 0], 4: [5, 0, 0], 5: [1, 0, 0], 6: [1, 0, 1], 7: [1, 0, 0], 8: [3, 0, 6], 9: [0, 1, 0], 10: [0, 0, 1], 11: [0, 0, 3]}


问:
Confusion regarding comparison operators in std::min, std::max
std::min and std::max allows custom comparators, but I am a bit confused on how the ordering works.

Consider the following:

```<code>   int i = 1;
   int j = 2;

   auto min_val = min(i, j, [](const auto val1, const auto val2){
      if(val1 < val2) return true;
      return false;
   });

</code>```

This returns the minimum value, which is i. But I don't understand why we use the < instead of the >, and why val1 and val2 appear on the left and right of the operand, respectively.

Consider the following:

```<code>   int i = 1;
   int j = 2;

   auto max_val = max(i, j, [](const auto val1, const auto val2){
      if(val1 > val2) return true;
      return false;
   });
</code>```

I was thinking that this would return the maximum value, but it actually returns the minimum value, and again, we must use the < operand. Could someone explain what is going on beneath the hood?

I've run into this issue on some other stuff too, I think with std::priority_queue and std::map, where the ordering and comparison operators aren't very intuitive to me, and most times I have to guess and check to get what I want.

答:
That basically boils down to how those functions are defined in the standard. std::max, for example, defines the comparer (your lambda) as follows:

comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if a is less than b.

Usually, when it comes to the order of values within the c++ standard library, it's (almost?) always std::less that is used as a default comparer, which does exactly left < right.

As to why it's always a < b that has to be satisfied I think it's simply to reduce coding overhead if you were to write it yourself. Imagine having a comparer like this:

```<code>struct MyComp
{
    bool operator()(MyType a, MyType b) const
    {
        return a.getValue() < b.getValue();
    }
};
</code>```

Since all the constructs in the standard library require your comparer to return true, if a < b, you can use one simple comparer for a multitude of constructs. E.g.

```<code>auto maxVal = std::max(a, b, MyComp{});
auto minVal = std::min(a, b, MyComp{});
std::map<MyType, MyComp> myMap;
</code>```

will all just work with one comparer.

Body:
std::min and std::max allows custom comparators, but I am a bit confused on how the ordering works.

Consider the following:

   int i = 1;
   int j = 2;

   auto min_val = min(i, j, [](const auto val1, const auto val2){
      if(val1 < val2) return true;
      return false;
   });

This returns the minimum value, which is i. But I don't understand why we use the < instead of the >, and why val1 and val2 appear on the left and right of the operand, respectively.

Consider the following:

   int i = 1;
   int j = 2;

   auto max_val = max(i, j, [](const auto val1, const auto val2){
      if(val1 > val2) return true;
      return false;
   });

I was thinking that this would return the maximum value, but it actually returns the minimum value, and again, we must use the < operand. Could someone explain what is going on beneath the hood?

I've run into this issue on some other stuff too, I think with std::priority_queue and std::map, where the ordering and comparison operators aren't very intuitive to me, and most times I have to guess and check to get what I want.

Body:
That basically boils down to how those functions are defined in the standard. std::max, for example, defines the comparer (your lambda) as follows:

comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if a is less than b.

Usually, when it comes to the order of values within the c++ standard library, it's (almost?) always std::less that is used as a default comparer, which does exactly left < right.

As to why it's always a < b that has to be satisfied I think it's simply to reduce coding overhead if you were to write it yourself. Imagine having a comparer like this:

struct MyComp
{
    bool operator()(MyType a, MyType b) const
    {
        return a.getValue() < b.getValue();
    }
};

Since all the constructs in the standard library require your comparer to return true, if a < b, you can use one simple comparer for a multitude of constructs. E.g.

auto maxVal = std::max(a, b, MyComp{});
auto minVal = std::min(a, b, MyComp{});
std::map<MyType, MyComp> myMap;

will all just work with one comparer.


答:
```<code>tag = ['metal', 'plastic']
num = ['27323', '11192']

df = pd.DataFrame(
    {
        'num': num,

    },index=tag)

print(df.loc['plastic','num'])
</code>```

This will give you what you need.

Title: python3 pandas get specific row and specific column

Body:
tag = ['metal', 'plastic']
num = ['27323', '11192']

df = pd.DataFrame(
    {
        'num': num,

    },index=tag)

print(df.loc['plastic','num'])

This will give you what you need.


问:
How to compile a library without Ivy?
I'm publishing a library and when I cd to dist/my-library I get the message:

ERROR: Trying to publish a package that has been compiled by Ivy. This is not allowed.
  Please delete and rebuild the package, without compiling with Ivy, before attempting to publish.

How do we rebuild without Ivy?

答:
Fix for angular 9.x.x

If you migrated your app to angular 9 and you see this kind of error, make sure to build your library with --prod option it will not build with IVY

```<code>ng build yourLibraryName --prod
</code>```

When you will pass --prod it will build without the ivy option and it will be allowed to be published.

As part of the migration, angular CLI create tsconfig.lib.prod.json and configure to not use IVY and you are all set

Title: How to compile a library without Ivy?

Body:
Fix for angular 9.x.x

If you migrated your app to angular 9 and you see this kind of error, make sure to build your library with --prod option it will not build with IVY

ng build yourLibraryName --prod

When you will pass --prod it will build without the ivy option and it will be allowed to be published.

As part of the migration, angular CLI create tsconfig.lib.prod.json and configure to not use IVY and you are all set


问:
Display data from SQLite as dynamic cards with Android Studio
Right now I get the usernames a string array from my database. I want to display it like that layout: enter image description here

It should be dynamic, if the name is long, only one name per row,... Sometimes there will be 20 names and sometimes there will be only one name, so it needs to be flexible. I am new to Android Studio and not sure if it makes sence to use a listview or maybe even Text Views? Or maybe something else?

Thank you so much in advance!

答:
Use a Recyclerview with Flexbox Layout manager https://github.com/google/flexbox-layout

with flexWrap set.

FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(context);
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        RecyclerView.setLayoutManager(layoutManager);

        // Create Custom RecyclerAdapter for data
        RecyclerViewAdapter adapter = new CustomAdapter(context,stringArrayList);
        RecyclerView.setAdapter(adapter);
```

RecyclerView is like listview but better performing.

Use an ArrayList not array as this is more flexible.

In the adapter each item is "drawn" in the onBinViewHolder and you can use a textbox for each name or your example looks like it uses Chips.

More details on RecyclerView at https://developer.android.com/guide/topics/ui/layout/recyclerview

Body:
Use a Recyclerview with Flexbox Layout manager https://github.com/google/flexbox-layout

with flexWrap set.

FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(context);
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        RecyclerView.setLayoutManager(layoutManager);

        // Create Custom RecyclerAdapter for data
        RecyclerViewAdapter adapter = new CustomAdapter(context,stringArrayList);
        RecyclerView.setAdapter(adapter);

RecyclerView is like listview but better performing.

Use an ArrayList not array as this is more flexible.

In the adapter each item is "drawn" in the onBinViewHolder and you can use a textbox for each name or your example looks like it uses Chips.

More details on RecyclerView at https://developer.android.com/guide/topics/ui/layout/recyclerview


问:
RabbitMQ - How to Dead-letter / Process Messages in Expired Queues?
I have an a queue that has x-expires set. The issue I am having is that I need to do further processing on the messages that are in the queue IF the queue expires. My initial idea was to set x-dead-letter-exchange on the queue. But, when the queue expires, the messages just vanish without making it to the dead-letter exchange.

How can I dead-letter, or otherwise process, messages that are in a queue that expires?

答:
As suggested in the comments, you cannot do this by relying only on the x-expire feature. But a solution that worked in a similar case I had was to:

Use x-message-ttl to make sure messages die if not consumed in a timely manner,

Assign a dead letter exchange to the queue where all those messages will be routed,

Use x-expires to set the queue expiration to a value higher than the TTL of the messages,

(and this is the tricky part) Assuming you have control over your consumers, before the last consumer goes offline, delete the binding to your "dying" queue, potentially through a REST API call - this will prevent new messages from being routed to the queue.

This way the messages that were published before the last consumer died were already processed, existing messages will be dead-lettered before the queue expires, and new messages cannot come into the queue.


问:
PL/SQL: Run package after checking all rows in trigger
I have an inventory table with expected quantities and actually received quantities. Let's say inv.q_ex and inv.q_rd.

The INSERT to the table has a positive value in q_ex and a zero in q_rd because it hasn't arrived yet. I'd like to run a package when I detect that the q_rd value changes from 0 to something else, indicating it's been received and stored.

Making a trigger to detect after update and checking each row is easy, but I'm not sure how to ensure it only runs once.

The skeleton is:

```<code>CREATE OR REPLACE TRIGGER example
     AFTER UPDATE ON inv
          FOR EACH ROW
               BEGIN
                    IF :OLD.q_rd = 0 AND :NEW.q_rd > 0 THEN
                         pkg.proc();
                    END IF;
               END;
/
</code>```

The problem I see is I only want it to run one time. I just need to identify when it needs to be executed. Ideally, on the first row where my condition is met, I would exit the loop (seems like a waste to keep checking when I already know I need to execute) and call my procedure.

I couldn't find a way to "exit" the for each and treat it as a normal AFTER UPDATE, so then I tried using both BEFORE UPDATE and AFTER UPDATE. The BEFORE portion would check each row and update a boolean. The AFTER portion would wait for that to happen and if it was true, call the procedure.

```<code>CREATE OR REPLACE TRIGGER example
     BEFORE UPDATE ON inv
          FOR EACH ROW
               DECLARE
                    shouldExecute BOOLEAN;
               BEGIN
                    IF :OLD.q_rd = 0 AND :NEW.q_rd > 0 THEN
                         shouldExecute := TRUE;
                    END IF;
               END;
     AFTER UPDATE ON inv
          BEGIN
               IF shouldExecute THEN
                    pkg.proc();
               END IF;
          END;
/
</code>```

I suspect this wouldn't work anyway because, according to the syntax, it redeclares the boolean variable on each row. I thought that maybe I could make it "global" but regardless, turns out I can't add both BEFORE and AFTER to the same trigger for some reason (unless I didn't research enough), so I broke it out into two triggers. The problem now is I can't share that boolean between the two triggers. Can I share the value, or am I going about this all wrong?

答:
There's a lot of little questions here so I'll try to answer them all :)

Regarding "FOR EACH ROW", Oracle triggers support two different triggering methods, STATEMENT or ROW. If you include the "FOR EACH ROW" in the definition, you'll get a row trigger, which is fired once per row affected by the query, which is what you seem to want here. Statement level triggers get fired only once for each query. An advantage to using row triggers is that you can use the :OLD and :NEW metavariables which refer to the previous and current row values.

As you've discovered, you can't add BEFORE and AFTER to the same trigger - you'll need to break them out into two triggers.

Unfortunately there isn't a simple way of sharing the boolean variable between the two triggers. The easiest way is probably to create a package with a public variable, which you can set in the BEFORE trigger, and check in the AFTER trigger.

The package would look something like this:

```<code>CREATE OR REPLACE PACKAGE PCKG_DEMO
AS
  shouldExecute BOOLEAN;
END;
/
</code>```

Then your BEFORE UPDATE trigger:

```<code>CREATE OR REPLACE TRIGGER beforeexample
     BEFORE UPDATE ON inv
          FOR EACH ROW
               BEGIN
                    IF :OLD.q_rd = 0 AND :NEW.q_rd > 0 THEN
                         PCKG_DEMO.shouldExecute := TRUE;
                    END IF;
               END;
/
</code>```

And your AFTER UPDATE trigger:

```<code>CREATE OR REPLACE TRIGGER afterexample
     AFTER UPDATE ON inv
        FOR EACH ROW
          BEGIN
               IF PCKG_DEMO.shouldExecute THEN
                    pkg.proc();
               END IF;
          END;
/
</code>```

Those are a bit pseudocode-y - I don't have access to an Oracle database right now. You can read more about triggers here. Hope this helps!

Body:
I have an inventory table with expected quantities and actually received quantities. Let's say inv.q_ex and inv.q_rd.

The INSERT to the table has a positive value in q_ex and a zero in q_rd because it hasn't arrived yet. I'd like to run a package when I detect that the q_rd value changes from 0 to something else, indicating it's been received and stored.

Making a trigger to detect after update and checking each row is easy, but I'm not sure how to ensure it only runs once.

The skeleton is:

CREATE OR REPLACE TRIGGER example
     AFTER UPDATE ON inv
          FOR EACH ROW
               BEGIN
                    IF :OLD.q_rd = 0 AND :NEW.q_rd > 0 THEN
                         pkg.proc();
                    END IF;
               END;
/

The problem I see is I only want it to run one time. I just need to identify when it needs to be executed. Ideally, on the first row where my condition is met, I would exit the loop (seems like a waste to keep checking when I already know I need to execute) and call my procedure.

I couldn't find a way to "exit" the for each and treat it as a normal AFTER UPDATE, so then I tried using both BEFORE UPDATE and AFTER UPDATE. The BEFORE portion would check each row and update a boolean. The AFTER portion would wait for that to happen and if it was true, call the procedure.

CREATE OR REPLACE TRIGGER example
     BEFORE UPDATE ON inv
          FOR EACH ROW
               DECLARE
                    shouldExecute BOOLEAN;
               BEGIN
                    IF :OLD.q_rd = 0 AND :NEW.q_rd > 0 THEN
                         shouldExecute := TRUE;
                    END IF;
               END;
     AFTER UPDATE ON inv
          BEGIN
               IF shouldExecute THEN
                    pkg.proc();
               END IF;
          END;
/

I suspect this wouldn't work anyway because, according to the syntax, it redeclares the boolean variable on each row. I thought that maybe I could make it "global" but regardless, turns out I can't add both BEFORE and AFTER to the same trigger for some reason (unless I didn't research enough), so I broke it out into two triggers. The problem now is I can't share that boolean between the two triggers. Can I share the value, or am I going about this all wrong?

Body:
There's a lot of little questions here so I'll try to answer them all :)

Regarding "FOR EACH ROW", Oracle triggers support two different triggering methods, STATEMENT or ROW. If you include the "FOR EACH ROW" in the definition, you'll get a row trigger, which is fired once per row affected by the query, which is what you seem to want here. Statement level triggers get fired only once for each query. An advantage to using row triggers is that you can use the :OLD and :NEW metavariables which refer to the previous and current row values.

As you've discovered, you can't add BEFORE and AFTER to the same trigger - you'll need to break them out into two triggers.

Unfortunately there isn't a simple way of sharing the boolean variable between the two triggers. The easiest way is probably to create a package with a public variable, which you can set in the BEFORE trigger, and check in the AFTER trigger.

The package would look something like this:

CREATE OR REPLACE PACKAGE PCKG_DEMO
AS
  shouldExecute BOOLEAN;
END;
/

Then your BEFORE UPDATE trigger:

CREATE OR REPLACE TRIGGER beforeexample
     BEFORE UPDATE ON inv
          FOR EACH ROW
               BEGIN
                    IF :OLD.q_rd = 0 AND :NEW.q_rd > 0 THEN
                         PCKG_DEMO.shouldExecute := TRUE;
                    END IF;
               END;
/

And your AFTER UPDATE trigger:

CREATE OR REPLACE TRIGGER afterexample
     AFTER UPDATE ON inv
        FOR EACH ROW
          BEGIN
               IF PCKG_DEMO.shouldExecute THEN
                    pkg.proc();
               END IF;
          END;
/

Those are a bit pseudocode-y - I don't have access to an Oracle database right now. You can read more about triggers here. Hope this helps!


问:
Running CPython functions from C#
I'm working on a project where I need to be able to run a python function that depends on SciPy/NumPy.  Due to this being an add-on to a project already in progress, using IronPython would not be an option.

Additional info:

Python.NET seemed to be a good fit, but I was unable to get the return value from RunString() (it would only return NULL).

Passing arguments and catching the return value (a tuple) is necessary.

The function is in a statistical package that was created by a support group for the team, so modification of that would also not be possible.

I'm at quite a loss for what to do. Any hints in the right direction are appreciated. Thanks for any help you can give!

I understand that this may be quite vague, but I cannot give explicit details to the project. If any clarification is needed please let me know and I'll do my best!

答: The ironclad project was started to allow using CPython extensions from IronPython, especially SciPy/NumPy it seems. I don't know how usable it is (and how actively it is still being developed)</p>

Title: Running CPython functions from C#


问:
Operator precedence of +(concatenation) vs == in Javascript and Java
```<code>let valueOne = 3;
let valueTwo = "3";
if(valueOne==valueTwo)
    {console.log("same")}
else
    {console.log("different")}

    console.log("valueOne==valueTwo: " + valueOne==valueTwo);
</code>```

Why is the output:

```<code>same
false
</code>```

It doesn't even print the string  valueOne==valueTwo:.
However, when extra parentheses are added it's outputting the expected results.

```<code>console.log("valueOne==valueTwo: " + (valueOne==valueTwo));
</code>```

Output:

```<code>same
valueOne==valueTwo: true
</code>```

It appears that the == operator has lower precedence than concatenation in javascript,
http://www.scriptingmaster.com/javascript/operator-precedence.asp
which is different from Java:
https://introcs.cs.princeton.edu/java/11precedence/

Anyone know the design concern here?

Thanks!

答:
Its adding the string and number together and comparing it to the second variable. Using a string template fixes this.

let valueOne = 3;
let valueTwo = "3";
if(valueOne==valueTwo)
    {console.log("same")}
else
    {console.log("different")}

    console.log(`valueOne==valueTwo: ${valueOne == valueTwo}`); ```

Body:
let valueOne = 3;
let valueTwo = "3";
if(valueOne==valueTwo)
    {console.log("same")}
else
    {console.log("different")}

    console.log("valueOne==valueTwo: " + valueOne==valueTwo);

Why is the output:

same
false

It doesn't even print the string  valueOne==valueTwo:.
However, when extra parentheses are added it's outputting the expected results.

console.log("valueOne==valueTwo: " + (valueOne==valueTwo));

Output:

same
valueOne==valueTwo: true

It appears that the == operator has lower precedence than concatenation in javascript,
http://www.scriptingmaster.com/javascript/operator-precedence.asp
which is different from Java:
https://introcs.cs.princeton.edu/java/11precedence/

Anyone know the design concern here?

Thanks!


问:
Sales-Commission 8.10 Dietel

I can't figure out why I keep getting the "Index was outside the
  bounds of the array" error. I am trying to tally up the salaries to
  display.
  Is there are any someone who could explain to me how the error message works.

```<code>namespace sales_commission {
    class Program {
        static void Main (string[] args) {
            const int ARRAY_LENGTH = 8;

            int[] salaries = { 210, 400, 450, 950, 800, 330, 430, 233, 223, 590, 679, 1000 };

            var salary = new int[ARRAY_LENGTH];

            foreach(int number in salaries) {

                try {
                    if (number >= 200 && number <= 299) {
                        salary[0]++;
                    } else if (number >= 300 && number <= 399) {
                        salary[1]++;
                    } else if (number >= 400 && number <= 499) {
                        salary[2]++;
                    } else if (number >= 500 && number <= 599) {
                        salary[3]++;
                    } else if (number >= 600 && number <= 699) {
                        salary[4]++;
                    } else if (number >= 700 && number <= 799) {
                        salary[5]++;
                    } else if (number >= 800 && number <= 899) {
                        salary[6]++;
                    } else if (number >= 900 && number <= 999) {
                        salary[7]++;
                    } else if (number >= 1000) {
                        salary[8]++;
                    }
                } catch (IndexOutOfRangeException ex) {
                    Console.WriteLine (ex.Message);
                    Console.WriteLine ($"salaries[{number}] = {salary[number]}");
                }

            }

            for (var result = 0; result <= salary.Length; ++result) {
                Console.WriteLine ($"{result* 100 + 200} - {result * 100 + 200 + 99}  {salary[result],15}");
            }

        }
    }
}
</code>```

答:
You have 9 salary brackets.  200-299, 300-399, 400-499, 500-599, 600-699, 700-799, 800-899, 900-999 and >= 1000.  That means you need 9 storage spaces for the counts.  Array indexes start at 0, so your array length needs to be 9, this gives you [0 to 8] indexes.

```<code>const int ARRAY_LENGTH = 8;    // This needs to be 9.
</code>```

You get an array out of bounds because:

```<code>} else if (number >= 1000) {
    salary[8]++;              // Index 8 doesn't exist, only [0 to 7] for an ARRAY_LENGTH of 8.
</code>```

Your loop also accesses data outside of the array bounds.  This is because the condition of your loop runs until it reaches and includes the index of the length itself.  So if your array has 8 spaces [0 to 7], your loop runs from [0 to 8] and the moment it access index 8, you're out of bounds.  This can easily be fixed as below:-

```<code>for (var result = 0; result <= salary.Length; ++result) {  // Change this to result < salary.Length
    Console.WriteLine ($"{result* 100 + 200} - {result * 100 + 200 + 99 {salary[result],15}");
}
</code>```

Title: Sales-Commission 8.10 Dietel

Body:
I can't figure out why I keep getting the "Index was outside the
  bounds of the array" error. I am trying to tally up the salaries to
  display.
  Is there are any someone who could explain to me how the error message works.

namespace sales_commission {
    class Program {
        static void Main (string[] args) {
            const int ARRAY_LENGTH = 8;

            int[] salaries = { 210, 400, 450, 950, 800, 330, 430, 233, 223, 590, 679, 1000 };

            var salary = new int[ARRAY_LENGTH];

            foreach(int number in salaries) {

                try {
                    if (number >= 200 && number <= 299) {
                        salary[0]++;
                    } else if (number >= 300 && number <= 399) {
                        salary[1]++;
                    } else if (number >= 400 && number <= 499) {
                        salary[2]++;
                    } else if (number >= 500 && number <= 599) {
                        salary[3]++;
                    } else if (number >= 600 && number <= 699) {
                        salary[4]++;
                    } else if (number >= 700 && number <= 799) {
                        salary[5]++;
                    } else if (number >= 800 && number <= 899) {
                        salary[6]++;
                    } else if (number >= 900 && number <= 999) {
                        salary[7]++;
                    } else if (number >= 1000) {
                        salary[8]++;
                    }
                } catch (IndexOutOfRangeException ex) {
                    Console.WriteLine (ex.Message);
                    Console.WriteLine ($"salaries[{number}] = {salary[number]}");
                }

            }

            for (var result = 0; result <= salary.Length; ++result) {
                Console.WriteLine ($"{result* 100 + 200} - {result * 100 + 200 + 99}  {salary[result],15}");
            }

        }
    }
}

Body:
You have 9 salary brackets.  200-299, 300-399, 400-499, 500-599, 600-699, 700-799, 800-899, 900-999 and >= 1000.  That means you need 9 storage spaces for the counts.  Array indexes start at 0, so your array length needs to be 9, this gives you [0 to 8] indexes.

const int ARRAY_LENGTH = 8;    // This needs to be 9.

You get an array out of bounds because:

} else if (number >= 1000) {
    salary[8]++;              // Index 8 doesn't exist, only [0 to 7] for an ARRAY_LENGTH of 8.

Your loop also accesses data outside of the array bounds.  This is because the condition of your loop runs until it reaches and includes the index of the length itself.  So if your array has 8 spaces [0 to 7], your loop runs from [0 to 8] and the moment it access index 8, you're out of bounds.  This can easily be fixed as below:-

for (var result = 0; result <= salary.Length; ++result) {  // Change this to result < salary.Length
    Console.WriteLine ($"{result* 100 + 200} - {result * 100 + 200 + 99 {salary[result],15}");
}


问:
Counting continuous sequences of months
If I have a vector of year and month coded like this:

```<code>ym <- c(
  201401,
  201403:201412,
  201501:201502,
  201505:201510,
  201403
)
</code>```

And I'd like to end up with a vector that looks like this:

```<code> [1]  1  1  2  3  4  5  6  7  8  9 10  11  12  1  2  3  4  5  6  1
</code>```

That is, I want to count continuous sequences of month records. Can anyone recommend an approach? I've spinning my wheels with something like this:

```<code>ym_date <- as.Date(paste0(ym, 01), format = "%Y%m%d")

diff(ym_date)
</code>```

but haven't been able to get any farther because I'm not sure how to flag that start of a sequence when we are dealing with months. Any base R, tidyverse, data.frame centric or not solution would be welcomed.

答:
We can use

```<code>library(lubridate)
mth <- month(ym_date)
new <- mth + cumsum(c(0, (mth %/% 12)[-length(mth)])) * 12
ave(mth, cumsum(c(TRUE, diff(new) != 1)), FUN = seq_along)
#[1]  1  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  1
</code>```

It can be also written in a more compact way

```<code>ave(mth, cumsum(c(TRUE, diff(c(0, head(cumsum(mth == 12), -1)) * 12 + mth) != 1)), FUN = seq_along)
#[1]  1  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  1
</code>```

Title: Counting continuous sequences of months

Body:
If I have a vector of year and month coded like this:

ym <- c(
  201401,
  201403:201412,
  201501:201502,
  201505:201510,
  201403
)

And I'd like to end up with a vector that looks like this:

 [1]  1  1  2  3  4  5  6  7  8  9 10  11  12  1  2  3  4  5  6  1

That is, I want to count continuous sequences of month records. Can anyone recommend an approach? I've spinning my wheels with something like this:

ym_date <- as.Date(paste0(ym, 01), format = "%Y%m%d")

diff(ym_date)

but haven't been able to get any farther because I'm not sure how to flag that start of a sequence when we are dealing with months. Any base R, tidyverse, data.frame centric or not solution would be welcomed.

Body:
We can use

library(lubridate)
mth <- month(ym_date)
new <- mth + cumsum(c(0, (mth %/% 12)[-length(mth)])) * 12
ave(mth, cumsum(c(TRUE, diff(new) != 1)), FUN = seq_along)
#[1]  1  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  1

It can be also written in a more compact way

ave(mth, cumsum(c(TRUE, diff(c(0, head(cumsum(mth == 12), -1)) * 12 + mth) != 1)), FUN = seq_along)
#[1]  1  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6  1


问:
Remove axis labels from a plot in R after the plot has already been created
I am using the plot function of a particular package, namely the SPEI library. This function does not appear to accept any parameters to change the way the plot looks when it is generated.

I would like to know how to remove axis values, add new ones, and (ideally) rename the x-axis after the plot has already been created.

Please note that I have seen the other similar topics (e.g: Remove plot axis values) and they are not applicable to my situation. I know that when calling the base plot functions in R, you can set xaxt = "n", axes= FALSE, etc.

Here is a quick version of what I mean:

```<code>library(SPEI)
data(wichita)
x <- spei(wichita[,'PRCP'], 1)
plot.spei(x, main = "Here's a plot")
plot.spei(x, main = "Also a plot", xaxt = "n") #Note that xaxt does not affect output
</code>```

答:
That function uses base graphics and does not allow for any parameter to be passed through the function. There is no way to remove the x-axis labels without editing the function. Here's a way to make a copy and change just the one line that needs to be edited. (Note, since this method uses line numbers it's pretty fragile, this was tested with SPEI_1.7)

```<code>my_plot_spei <- plot.spei
my_plot_spei_body <- as.list(body(my_plot_spei))
my_plot_spei_body[[c(14,4,5)]] <- quote(plot(datt, type = "n", xlab = "", ylab = label, main = main[i], ...))
body(my_plot_spei) <- as.call(my_plot_spei_body)
</code>```

then this will work

```<code>x <- spei(wichita[,'PRCP'], 1)
my_plot_spei(x, main = "Here's a plot", xaxt="n")
</code>```

Body:
I am using the plot function of a particular package, namely the SPEI library. This function does not appear to accept any parameters to change the way the plot looks when it is generated.

I would like to know how to remove axis values, add new ones, and (ideally) rename the x-axis after the plot has already been created.

Please note that I have seen the other similar topics (e.g: Remove plot axis values) and they are not applicable to my situation. I know that when calling the base plot functions in R, you can set xaxt = "n", axes= FALSE, etc.

Here is a quick version of what I mean:

library(SPEI)
data(wichita)
x <- spei(wichita[,'PRCP'], 1)
plot.spei(x, main = "Here's a plot")
plot.spei(x, main = "Also a plot", xaxt = "n") #Note that xaxt does not affect output

Body:
That function uses base graphics and does not allow for any parameter to be passed through the function. There is no way to remove the x-axis labels without editing the function. Here's a way to make a copy and change just the one line that needs to be edited. (Note, since this method uses line numbers it's pretty fragile, this was tested with SPEI_1.7)

my_plot_spei <- plot.spei
my_plot_spei_body <- as.list(body(my_plot_spei))
my_plot_spei_body[[c(14,4,5)]] <- quote(plot(datt, type = "n", xlab = "", ylab = label, main = main[i], ...))
body(my_plot_spei) <- as.call(my_plot_spei_body)

then this will work

x <- spei(wichita[,'PRCP'], 1)
my_plot_spei(x, main = "Here's a plot", xaxt="n")


问:
Counting Amount of subsets from a set
Let set S = {a1, a2, a3, ..., a12}, where all 12 elements are distinct. We wish to form subsets, each of which contains one or more of the elements of set S (including the possibility of using all the elements of S). The only restriction is that the subscript of each element in a specific set must be an integer multiple of the smallest subscript in that set. For example, {a2, a4, a6} is an acceptable set, as is {a6}. How many such sets can be formed?

I was thinking of dividing the problem in cases, one for 3 elements, and then 4 and 5 and so on. This would take way too long so can I have help doing it a faster way?

答:
The constraint relates to the smallest subscript, so it makes more sense to branch on that, rather than branching on the size of the subset. You want to branch on something which simplifies the constraint, so instead of "each subscript is a multiple of the smallest subscript" you have e.g. "each subscript is a multiple of 3". Then within each branch it's much easier to count.

You only want to count non-empty subsets, so every subset has a smallest subscript:

If the subset contains a1, then each of the 11 remaining elements can be freely chosen as either present or not present. There are 211 such subsets.

If the smallest subscript is a2, then there are 5 possible other elements a4, a6, a8, a10, a12, each of which can be freely chosen as either present or not present. There are 25 such subsets.

If the smallest subscript is a3, then there are 3 possible other elements a6, a9, a12. There are 23 such subsets.

If the smallest subscript is a4, then there are 2 possible other elements a8, a12. There are 22 such subsets.

If the smallest subscript is a5 or a6, then there is one possible other element (a10 or a12 respectively). There are 2 subsets for a5 and 2 for a6.

Otherwise, the smallest subscript is a7, a8, a9, a10, a11, or a12, and the subset cannot contain any other elements due to the restriction. There is one subset in each case.

The total is therefore 211 + 25 + 23 + 22 + 2 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 2,102.

Generalising this argument, if there are n elements in the original set, then the total number of subsets satisfying this constraint is:

Title: Counting Amount of subsets from a set


问:
WPF custom TabItem disappears upon restyle?
I have a TabControl with a custom TabItem. The view xaml looks like this.

<UserControl x:Class="PeripheryModule.Views.MainTabView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:PeripheryModule.Controls"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TabControl>

            <TabItem Header="TabItem 4" />
            <local:CustomTabItem Header="Testing" />

        </TabControl>
    </Grid>
</UserControl>
```

<p>the CustomTabItem.xaml file looks like this</p>

<pre class="lang-xml prettyprint-override"><code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:PeripheryModule.Controls">

    <Style TargetType="{x:Type local:CustomTabItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomTabItem}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>
</code>```

and the CustomTabItem.xaml.cs file looks like this

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PeripheryModule.Controls
{
    public class CustomTabItem : TabItem
    {
        static CustomTabItem()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomTabItem), new FrameworkPropertyMetadata(typeof(CustomTabItem)));
        }
    }
}
</code>```

I get no errors thrown, all that happens is the tabItem simply doesn't show up. It will, however, show up if i comment out the DefaultStyleKeyProperty line in CustomTabItem.aspx.cs.

I've probably got this all set up wrong anyways. Ultimate goal is to have closeable tabs.

答:
Excerpt:

First, if you are not familiar with the concept of theme style vs explicit style I suggest you read this blog http://www.interact-sw.co.uk/iangblog/2007/02/14/wpfdefaulttemplate. All controls need a theme style (which is usually defined in files named Aero.NormalColor.xaml/Generic.xaml/etc under a folder named Themes) which defines their default look (Template)/properties and an optional explicit style (which is defined at the element/window/app level either with implicit key or explicit key).

DefaultStyleKeyProperty defines the key used to find the theme style of the control. If you comment out the line, you will end up with the default theme style of the base class. As a quick test, change the base class of custom control to Button. If you comment out the line, your custom control will get the theme style of Button and it will look like a button. If you dont comment out the line, your custom control will get the default style defined in generic.xaml.

From: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/9df46c62-3715-4e16-8ef6-538068c28eb6/

Edit:

Is there any reason why you don't want to define the header template and assign it?

ex. <TabItem Header="Testing" HeaderTemplate="{StaticResource customHeaderTemplate}" />

Body:
I have a TabControl with a custom TabItem. The view xaml looks like this.

<UserControl x:Class="PeripheryModule.Views.MainTabView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:PeripheryModule.Controls"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TabControl>

            <TabItem Header="TabItem 4" />
            <local:CustomTabItem Header="Testing" />

        </TabControl>
    </Grid>
</UserControl>

the CustomTabItem.xaml file looks like this

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:PeripheryModule.Controls">

</ResourceDictionary>

and the CustomTabItem.xaml.cs file looks like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PeripheryModule.Controls
{
    public class CustomTabItem : TabItem
    {
        static CustomTabItem()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomTabItem), new FrameworkPropertyMetadata(typeof(CustomTabItem)));
        }
    }
}

I get no errors thrown, all that happens is the tabItem simply doesn't show up. It will, however, show up if i comment out the DefaultStyleKeyProperty line in CustomTabItem.aspx.cs.

I've probably got this all set up wrong anyways. Ultimate goal is to have closeable tabs.


问:
How to get common rows/columns between multiple files in all possible combinations - python/pandas
enter image description hereI am beginner to programming, so forgive me if I'm not using right terms. I have data collected in multiple csv files. Now I want to collect data that contains common rows between two files (say File_1 and File_2). Likewise, I want data in all combinations (two files at a time)- File_1 & File_3, File_1 & File_N, File_2 & 3, File_2 & File_N and so on. I can use pd.merge if I want to do this between two files but to obtain data in different combinations I need a function. Can any help with a function in python/pandas to perform this task.

Example of what my data looks like:

[Here if I want to calculate common alphabets between multiple files, in all possible combinations][2]

Thank you so much in advance

答:
1- Create a list of file name pairs using itertools.  (Not the only way you can do this, but let's try to make it more pythonic)

Here is a quick link to an example:
Combination of values in pandas data frame

2- It is hard to conceive how you should ingest each file without knowing what kind of data you have.  But assuming that you have csv files, you can use pandas to read each file pair and join them on the field of your choice to each other and export the results.

I hope this gives you a rough idea how to do this.  I suggest posting some example data to
get more specific solutions.