问:
react_dom_development is undefined in Deno React project
I wanted to try out Deno, so I decided to make a simple single-page React app.
But, when I try to pull in ReactDOM from the CDN, I get a console error: react_dom_development_js_2 is undefined.

I think what's going on is it can't resolve the ReactDOM CDN, but I can reach it from my browser? I also tried replacing it with what the browser resolves it to (https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js), but I still end up with the same error. Maybe I'm using the deno bundle wrong?

index.jsx

```<code>import { React } from "https://unpkg.com/react@16/umd/react.development.js";
import { ReactDOM } from "https://unpkg.com/react-dom@16/umd/react-dom.development.js";

ReactDOM.render(<p>Hello</p>, document.findElementById("app"));
</code>```

index.html

```<code><html>
  <head>
    <title>Test with Deno</title>
  </head>
  <body>

    <div id="app"></div>
    <script src="index.bundle.js"></script>
  </body>
</html>
</code>```

I run deno bundle index.jsx index.bundle.js to create my bundle,

index.bundle.js

```<code>// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

// This is a specialised implementation of a System module loader.

// @ts-nocheck
/* eslint-disable */
let System, __instantiateAsync, __instantiate;

(() => {
  const r = new Map();

  System = {
    register(id, d, f) {
      r.set(id, { d, f, exp: {} });
    },
  };

  async function dI(mid, src) {
    let id = mid.replace(/\.\w+$/i, "");
    if (id.includes("./")) {
      const [o, ...ia] = id.split("/").reverse(),
        [, ...sa] = src.split("/").reverse(),
        oa = [o];
      let s = 0,
        i;
      while ((i = ia.shift())) {
        if (i === "..") s++;
        else if (i === ".") break;
        else oa.push(i);
      }
      if (s < sa.length) oa.push(...sa.slice(s));
      id = oa.reverse().join("/");
    }
    return r.has(id) ? gExpA(id) : import(mid);
  }

  function gC(id, main) {
    return {
      id,
      import: (m) => dI(m, id),
      meta: { url: id, main },
    };
  }

  function gE(exp) {
    return (id, v) => {
      v = typeof id === "string" ? { [id]: v } : id;
      for (const [id, value] of Object.entries(v)) {
        Object.defineProperty(exp, id, {
          value,
          writable: true,
          enumerable: true,
        });
      }
    };
  }

  function rF(main) {
    for (const [id, m] of r.entries()) {
      const { f, exp } = m;
      const { execute: e, setters: s } = f(gE(exp), gC(id, id === main));
      delete m.f;
      m.e = e;
      m.s = s;
    }
  }

  async function gExpA(id) {
    if (!r.has(id)) return;
    const m = r.get(id);
    if (m.s) {
      const { d, e, s } = m;
      delete m.s;
      delete m.e;
      for (let i = 0; i < s.length; i++) s[i](await gExpA(d[i]));
      const r = e();
      if (r) await r;
    }
    return m.exp;
  }

  function gExp(id) {
    if (!r.has(id)) return;
    const m = r.get(id);
    if (m.s) {
      const { d, e, s } = m;
      delete m.s;
      delete m.e;
      for (let i = 0; i < s.length; i++) s[i](gExp(d[i]));
      e();
    }
    return m.exp;
  }

  __instantiateAsync = async (m) => {
    System = __instantiateAsync = __instantiate = undefined;
    rF(m);
    return gExpA(m);
  };

  __instantiate = (m) => {
    System = __instantiateAsync = __instantiate = undefined;
    rF(m);
    return gExp(m);
  };
})();

System.register(
  "index",
  [
    "https://unpkg.com/react@16/umd/react.development.js",
    "https://unpkg.com/react-dom@16/umd/react-dom.development.js",
  ],
  function (exports_1, context_1) {
    "use strict";
    var react_development_js_1, react_dom_development_js_1;
    var __moduleName = context_1 && context_1.id;
    return {
      setters: [
        function (react_development_js_1_1) {
          react_development_js_1 = react_development_js_1_1;
        },
        function (react_dom_development_js_1_1) {
          react_dom_development_js_1 = react_dom_development_js_1_1;
        },
      ],
      execute: function () {
        react_dom_development_js_1.ReactDOM.render(
          react_development_js_1.React.createElement("p", null, "Hello"),
          document.findElementById("app"),
        );
      },
    };
  },
);

__instantiate("index");
</code>```

答:
The issue here is due to the typical React and ReactDOM packages being written as commonJS packages.

Deno by default requires all modules to be written using ES Modules (ESM). https://github.com/pikapkg/react is a build of React and ReactDOM that use ESM, so they should be importable in Deno. link with CDN

There is a standard library module in deno that lets you use commonJS modules, though you'll need to be careful with them especially if they require node specific functionality: https://deno.land/std/node#commonjs-module-loading

Body:
I wanted to try out Deno, so I decided to make a simple single-page React app.
But, when I try to pull in ReactDOM from the CDN, I get a console error: react_dom_development_js_2 is undefined.

I think what's going on is it can't resolve the ReactDOM CDN, but I can reach it from my browser? I also tried replacing it with what the browser resolves it to (https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js), but I still end up with the same error. Maybe I'm using the deno bundle wrong?

index.jsx

import { React } from "https://unpkg.com/react@16/umd/react.development.js";
import { ReactDOM } from "https://unpkg.com/react-dom@16/umd/react-dom.development.js";

ReactDOM.render(
Hello
, document.findElementById("app"));

index.html

    <title>Test with Deno</title>

I run deno bundle index.jsx index.bundle.js to create my bundle,

index.bundle.js

// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

// This is a specialised implementation of a System module loader.

// @ts-nocheck
/* eslint-disable */
let System, __instantiateAsync, __instantiate;

(() => {
  const r = new Map();

  System = {
    register(id, d, f) {
      r.set(id, { d, f, exp: {} });
    },
  };

  async function dI(mid, src) {
    let id = mid.replace(/\.\w+$/i, "");
    if (id.includes("./")) {
      const [o, ...ia] = id.split("/").reverse(),
        [, ...sa] = src.split("/").reverse(),
        oa = [o];
      let s = 0,
        i;
      while ((i = ia.shift())) {
        if (i === "..") s++;
        else if (i === ".") break;
        else oa.push(i);
      }
      if (s < sa.length) oa.push(...sa.slice(s));
      id = oa.reverse().join("/");
    }
    return r.has(id) ? gExpA(id) : import(mid);
  }

  function gC(id, main) {
    return {
      id,
      import: (m) => dI(m, id),
      meta: { url: id, main },
    };
  }

  function gE(exp) {
    return (id, v) => {
      v = typeof id === "string" ? { [id]: v } : id;
      for (const [id, value] of Object.entries(v)) {
        Object.defineProperty(exp, id, {
          value,
          writable: true,
          enumerable: true,
        });
      }
    };
  }

  function rF(main) {
    for (const [id, m] of r.entries()) {
      const { f, exp } = m;
      const { execute: e, setters: s } = f(gE(exp), gC(id, id === main));
      delete m.f;
      m.e = e;
      m.s = s;
    }
  }

  async function gExpA(id) {
    if (!r.has(id)) return;
    const m = r.get(id);
    if (m.s) {
      const { d, e, s } = m;
      delete m.s;
      delete m.e;
      for (let i = 0; i < s.length; i++) s[i](await gExpA(d[i]));
      const r = e();
      if (r) await r;
    }
    return m.exp;
  }

  function gExp(id) {
    if (!r.has(id)) return;
    const m = r.get(id);
    if (m.s) {
      const { d, e, s } = m;
      delete m.s;
      delete m.e;
      for (let i = 0; i < s.length; i++) s[i](gExp(d[i]));
      e();
    }
    return m.exp;
  }

  __instantiateAsync = async (m) => {
    System = __instantiateAsync = __instantiate = undefined;
    rF(m);
    return gExpA(m);
  };

  __instantiate = (m) => {
    System = __instantiateAsync = __instantiate = undefined;
    rF(m);
    return gExp(m);
  };
})();

System.register(
  "index",
  [
    "https://unpkg.com/react@16/umd/react.development.js",
    "https://unpkg.com/react-dom@16/umd/react-dom.development.js",
  ],
  function (exports_1, context_1) {
    "use strict";
    var react_development_js_1, react_dom_development_js_1;
    var __moduleName = context_1 && context_1.id;
    return {
      setters: [
        function (react_development_js_1_1) {
          react_development_js_1 = react_development_js_1_1;
        },
        function (react_dom_development_js_1_1) {
          react_dom_development_js_1 = react_dom_development_js_1_1;
        },
      ],
      execute: function () {
        react_dom_development_js_1.ReactDOM.render(
          react_development_js_1.React.createElement("p", null, "Hello"),
          document.findElementById("app"),
        );
      },
    };
  },
);

__instantiate("index");


来源: stackexchange

问:
Average by row and column
I have a large matrix, for each cell I want to calculate the average of the numbers falling in the column and row of that specific cell.

As the matrix contains NA values and I'm not interested in those I skip them

How could I speed-up this and do it better?

Thanks

```<code>mtx <- matrix(seq(1:25), ncol = 5)
mtx[2,3] <- NA

mean.pos <- mtx
for(i in 1:dim(mtx)[1]){

  for(j in 1:dim(mtx)[2]){

    if(is.na(mtx[i,j])){

    } else {
      row.values <- mtx[i, !is.na(mtx[i,])]

      # -- Remove mtx[i,j] value itself to not count it twice
      row.values <- row.values[-which(row.values == mtx[i,j])[1]]

      col.values <- mtx[!is.na(mtx[,j]),j]
      mean.pos[i,j] <- mean(c(row.values, col.values), na.rm = T)
    }
  }
}
</code>```

答:
This does it without explicitly looping through the elements.

```<code>num <- outer(rowSums(mtx, na.rm = TRUE), colSums(mtx, na.rm = TRUE), "+") - mtx
not_na <- !is.na(mtx)
den <- outer(rowSums(not_na), colSums(not_na), "+") - 1
result <- num/den

# check
identical(result, mean.pos)
## [1] TRUE
</code>```

If there were no NAs then it could be simplified to:

```<code>(outer(rowSums(mtx), colSums(mtx), "+") - mtx) / (sum(dim(mtx)) - 1)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Average by row and column

Body:
I have a large matrix, for each cell I want to calculate the average of the numbers falling in the column and row of that specific cell.

As the matrix contains NA values and I'm not interested in those I skip them

How could I speed-up this and do it better?

Thanks

mtx <- matrix(seq(1:25), ncol = 5)
mtx[2,3] <- NA

mean.pos <- mtx
for(i in 1:dim(mtx)[1]){

  for(j in 1:dim(mtx)[2]){

    if(is.na(mtx[i,j])){

    } else {
      row.values <- mtx[i, !is.na(mtx[i,])]

      # -- Remove mtx[i,j] value itself to not count it twice
      row.values <- row.values[-which(row.values == mtx[i,j])[1]]

      col.values <- mtx[!is.na(mtx[,j]),j]
      mean.pos[i,j] <- mean(c(row.values, col.values), na.rm = T)
    }
  }
}

Body:
This does it without explicitly looping through the elements.

num <- outer(rowSums(mtx, na.rm = TRUE), colSums(mtx, na.rm = TRUE), "+") - mtx
not_na <- !is.na(mtx)
den <- outer(rowSums(not_na), colSums(not_na), "+") - 1
result <- num/den

# check
identical(result, mean.pos)
## [1] TRUE

If there were no NAs then it could be simplified to:

(outer(rowSums(mtx), colSums(mtx), "+") - mtx) / (sum(dim(mtx)) - 1)


问:
List of increasing lists
Given integers n >= m, I want to build the list of all increasing lists of length m with elements the set {1,...,n}.

For instance, if n= 4 and m=2, I want
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]].

Is there a nice way to do that with very few lines of Python code?

I would like to build an efficient function

```<code>def listOfLists(n, m):
    ????
    return ? # the list of all increasing lists of m elements in {1, 2, ..., n}
</code>```

Thanks!

Remark: I have basically done this, but my code is ridiculously long https://sagecell.sagemath.org/?z=eJxVkcFuwyAQRO98xR5Bdqo66ikq-YJIvfRm5eDIuF2ZbBB21H5-FpYWh4PFmHmzHjy6Ccj9rp_34J2eWyBzUMArvQQLc384Zx1YeEd6NlkiywA76LL6-Ubv2ItnsJbPGiA-C5Ik9p0t3hScjI19ghHeJbBC4mw6Dq1UgST0PyO69R4pu5QauZPHZf2YTvxcNLUQSiuceMgRqA4pZC8tZx7Vv8p-ukUegQRxoC-nu5qSnS9DCI5GjXIhl2HBJdEVjk_wBel2xcHL56Qim7RM_yWmOzd1UGm_-UPbyplUKkSkVW9bv7WwN-YBIpR8dQ==&lang=python&interacts=eJyLjgUAARUAuQ==

答:
I think this might work :

n=4
m=2
result=[]
for i in range(1,n):
    for j in range(i+1,n+1):
        result.append([i,j])
```

Title: List of increasing lists

Body:
Given integers n >= m, I want to build the list of all increasing lists of length m with elements the set {1,...,n}.

For instance, if n= 4 and m=2, I want
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]].

Is there a nice way to do that with very few lines of Python code?

I would like to build an efficient function

def listOfLists(n, m):
    ????
    return ? # the list of all increasing lists of m elements in {1, 2, ..., n}

Thanks!

Remark: I have basically done this, but my code is ridiculously long https://sagecell.sagemath.org/?z=eJxVkcFuwyAQRO98xR5Bdqo66ikq-YJIvfRm5eDIuF2ZbBB21H5-FpYWh4PFmHmzHjy6Ccj9rp_34J2eWyBzUMArvQQLc384Zx1YeEd6NlkiywA76LL6-Ubv2ItnsJbPGiA-C5Ik9p0t3hScjI19ghHeJbBC4mw6Dq1UgST0PyO69R4pu5QauZPHZf2YTvxcNLUQSiuceMgRqA4pZC8tZx7Vv8p-ukUegQRxoC-nu5qSnS9DCI5GjXIhl2HBJdEVjk_wBel2xcHL56Qim7RM_yWmOzd1UGm_-UPbyplUKkSkVW9bv7WwN-YBIpR8dQ==&lang=python&interacts=eJyLjgUAARUAuQ==


问:
IOError: [Errno 2] No such file or directory - file from the same directory
For some reason when I do the following:

```<code>filename = 'time_series_covid_confirmed_US.csv'
with open (os.path.join("mnt/c", "Users/ibhat/repo/nasa-hackathon-2020/covid-parsing", filename)) as csv_file:
</code>```

I get "No such file or directory" when trying to access a csv file. Any ideas?

答:
You need to add a forward slash before mnt:

```<code>filename = 'time_series_covid_confirmed_US.csv'
with open (os.path.join("/mnt/c", "Users/ibhat/repo/nasa-hackathon-2020/covid-parsing", filename)) as csv_file:
</code>```

Body:
For some reason when I do the following:

filename = 'time_series_covid_confirmed_US.csv'
with open (os.path.join("mnt/c", "Users/ibhat/repo/nasa-hackathon-2020/covid-parsing", filename)) as csv_file:

I get "No such file or directory" when trying to access a csv file. Any ideas?

Body:
You need to add a forward slash before mnt:

filename = 'time_series_covid_confirmed_US.csv'
with open (os.path.join("/mnt/c", "Users/ibhat/repo/nasa-hackathon-2020/covid-parsing", filename)) as csv_file:


问:
Quicksort doesn't work with sorted array
I am doing a project to compare Bubblesort and Quicksort algorithms. Everything works fine until I want to sort data which has been already sorted with Quicksort method. It crashes on large arrays (50k, 100k).

In my case firstly I sort data in descending order and then I try sorting in ascending order and then it crashes.

```<code>        read();  // just creates an array with random integers
        quickSortDSC(0, length - 1); //Here is the problem! (works if commented)
        t1 = clock();
        quickSortASC(0, length - 1);
        t2 = clock();
        cout << "Quick Sort\t: " << (t2 - t1)/CLK_TCK << " sec\n";
</code>```

Full code:

```<code>    #include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>

using namespace std;

long length = 1000;
const long max_length = 100000;

int list[max_length];

void read()
{
    ifstream fin("random.dat", ios::binary);
    for (long i = 0; i < length; i++)
    {
        fin.read((char*)&list[i], sizeof(int));
    }
    fin.close();
}

void bubbleSort()
{
    int temp;
    for(long i = 0; i < length; i++)
    {
        for(long j = 0; j < length-i-1; j++)
        {
            if (list[j] > list[j+1])
            {
                temp        = list[j];
                list[j]     = list[j+1];
                list[j+1]   = temp;
            }
        }
    }
}

long partitionASC(long left, long right)
{
    int pivot_element = list[left];
    int lb = left, ub = right;
    int temp;

    while (left < right)
    {
        while(list[left] <= pivot_element)
            left++;
        while(list[right] > pivot_element)
            right--;
        if (left < right)
        {
            temp        = list[left];
            list[left]  = list[right];
            list[right] = temp;
        }
    }
    list[lb] = list[right];
    list[right] = pivot_element;
    return right;
}

long partitionDSC(long left, long right)
{
    int pivot_element = list[left];
    int lb = left, ub = right;
    int temp;

    while (left < right)
    {
        while(list[left] >= pivot_element)
            left++;
        while(list[right] < pivot_element)
            right--;
        if (left < right)
        {
            temp        = list[left];
            list[left]  = list[right];
            list[right] = temp;
        }
    }
    list[lb] = list[right];
    list[right] = pivot_element;
    return right;
}
//ascending order
void quickSortASC(long left, long right)
{
    long pivot;
    if (left < right)
    {
        pivot = partitionASC(left, right);
        quickSortASC(left, pivot-1);
        quickSortASC(pivot+1, right);
    }
}

//descending order
void quickSortDSC(long left, long right)
{
    long pivot;
    if (left < right)
    {
        pivot = partitionDSC(left, right);
        quickSortDSC(left, pivot-1);
        quickSortDSC(pivot+1, right);
    }
}

int main()
{
    double t1, t2;

    for (length = 1000; length <= max_length; )
    {
        cout << "\nLength\t: " << length << '\n';

        read();
        t1 = clock();
        bubbleSort();
        t2 = clock();
        cout << "Bubble Sort\t: " << (t2 - t1)/CLK_TCK << " sec\n";

        read();
        quickSortDSC(0, length - 1); //Here is the problem!
        t1 = clock();
        quickSortASC(0, length - 1);
        t2 = clock();
        cout << "Quick Sort\t: " << (t2 - t1)/CLK_TCK << " sec\n";

        if(length == max_length)
            break;

        switch (length)
        {
        case 1000 :
            length = 10000;
            break;
        case 10000 :
            length = 50000;
            break;
        case 50000 :
            length = 100000;
            break;
        }
    }

    return 0;
}
</code>```

答:
For example.. Suppose {3, 6, 4, 7} is the case.
Whether you choose Single pivot or Double pivot QuickSort, if you always make first element as pivot then for a sorted array there are fair chances that you may face stack-overflow or O(n2).

So, randomising the pivot/s in each recursion cycle is the prevention from entering into O(n2) or endless loop in worst case.

Below example will explain well the worst case..

package algo.sorting.rev;

import java.util.Arrays;

public class DualPivotQuickSort {

```<code>public static void main(String[] args) {
    int[] input = new int[] { 8, 6, 2, 4, 17,    3, 10, 19, 21, 13,   9, 19, 14, 13, 7,   17 };
    quicksort(input, 0, input.length - 1);
    System.out.println(Arrays.toString(input));
}

/**
 * 3 segments are as below.
 *
 * | item < pivotL | pivotL <= item <= pivotR | item > pivotR |
 *
 * |pivotLPos . . . j-1|j . . . k|k+1 . . . pivotRPos|
 *
 *
 * @param a
 * @param pivotLPos
 * @param pivotRPos
 */
private static void quicksort(int [] a, int pivotLPos, int pivotRPos){
    int size  = pivotRPos - pivotLPos + 1;

    if(size < 3)
        return;

    int pivotL = a[pivotLPos];
    int pivotR = a[pivotRPos];

    if(pivotL > pivotR)
        swapContent(a, pivotLPos, pivotRPos);

    int i = pivotLPos + 1;
    int j = pivotRPos - 1;
    int k = pivotRPos;

    while(i <= j){

        while(i < pivotRPos && a[i] < pivotL)
            i++;

        while(j >= pivotLPos && a[j] >= pivotL){
            if(a[j] <= pivotR)
                j--;
            else{
                // adding to segment3
                swapContent(a, j, k);
                j--;
                k--;
            }
        }

        if(i < j){
            swapContent(a, i, j);
            i++;

            if(a[j] > pivotR){
                // adding to segment3
                swapContent(a, j, k);
                k--;
            }
            j--;
        }
    }

    swapContent(a, j, pivotLPos);

    if(size > 3){
        if(j - pivotLPos >= 3)
            quicksort(a, pivotLPos, j-1);  // recursion on seg1
        if(k - j >= 3)
            quicksort(a, j, k);  // recursion on seg2
        if(j - pivotRPos >= 3)
            quicksort(a, k+1, pivotRPos);  // recursion on seg3
    }
}

private static void swapContent(int [] a, int pos1, int pos2){
    int b = a[pos1];
    int c = a[pos2];

    b ^= c;
    c ^= b;
    b ^= c;

    a[pos1] = b;
    a[pos2] = c;
}
</code>```

}

ContentLicense: CC BY-SA 3.0

Body:
I am doing a project to compare Bubblesort and Quicksort algorithms. Everything works fine until I want to sort data which has been already sorted with Quicksort method. It crashes on large arrays (50k, 100k).

In my case firstly I sort data in descending order and then I try sorting in ascending order and then it crashes.

        read();  // just creates an array with random integers
        quickSortDSC(0, length - 1); //Here is the problem! (works if commented)
        t1 = clock();
        quickSortASC(0, length - 1);
        t2 = clock();
        cout << "Quick Sort\t: " << (t2 - t1)/CLK_TCK << " sec\n";

Full code:

    #include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>

using namespace std;

long length = 1000;
const long max_length = 100000;

int list[max_length];

void read()
{
    ifstream fin("random.dat", ios::binary);
    for (long i = 0; i < length; i++)
    {
        fin.read((char*)&list[i], sizeof(int));
    }
    fin.close();
}

void bubbleSort()
{
    int temp;
    for(long i = 0; i < length; i++)
    {
        for(long j = 0; j < length-i-1; j++)
        {
            if (list[j] > list[j+1])
            {
                temp        = list[j];
                list[j]     = list[j+1];
                list[j+1]   = temp;
            }
        }
    }
}

long partitionASC(long left, long right)
{
    int pivot_element = list[left];
    int lb = left, ub = right;
    int temp;

    while (left < right)
    {
        while(list[left] <= pivot_element)
            left++;
        while(list[right] > pivot_element)
            right--;
        if (left < right)
        {
            temp        = list[left];
            list[left]  = list[right];
            list[right] = temp;
        }
    }
    list[lb] = list[right];
    list[right] = pivot_element;
    return right;
}

long partitionDSC(long left, long right)
{
    int pivot_element = list[left];
    int lb = left, ub = right;
    int temp;

    while (left < right)
    {
        while(list[left] >= pivot_element)
            left++;
        while(list[right] < pivot_element)
            right--;
        if (left < right)
        {
            temp        = list[left];
            list[left]  = list[right];
            list[right] = temp;
        }
    }
    list[lb] = list[right];
    list[right] = pivot_element;
    return right;
}
//ascending order
void quickSortASC(long left, long right)
{
    long pivot;
    if (left < right)
    {
        pivot = partitionASC(left, right);
        quickSortASC(left, pivot-1);
        quickSortASC(pivot+1, right);
    }
}

//descending order
void quickSortDSC(long left, long right)
{
    long pivot;
    if (left < right)
    {
        pivot = partitionDSC(left, right);
        quickSortDSC(left, pivot-1);
        quickSortDSC(pivot+1, right);
    }
}

int main()
{
    double t1, t2;

    for (length = 1000; length <= max_length; )
    {
        cout << "\nLength\t: " << length << '\n';

        read();
        t1 = clock();
        bubbleSort();
        t2 = clock();
        cout << "Bubble Sort\t: " << (t2 - t1)/CLK_TCK << " sec\n";

        read();
        quickSortDSC(0, length - 1); //Here is the problem!
        t1 = clock();
        quickSortASC(0, length - 1);
        t2 = clock();
        cout << "Quick Sort\t: " << (t2 - t1)/CLK_TCK << " sec\n";

        if(length == max_length)
            break;

        switch (length)
        {
        case 1000 :
            length = 10000;
            break;
        case 10000 :
            length = 50000;
            break;
        case 50000 :
            length = 100000;
            break;
        }
    }

    return 0;
}

Body:
For example.. Suppose {3, 6, 4, 7} is the case.
Whether you choose Single pivot or Double pivot QuickSort, if you always make first element as pivot then for a sorted array there are fair chances that you may face stack-overflow or O(n2).

So, randomising the pivot/s in each recursion cycle is the prevention from entering into O(n2) or endless loop in worst case.

Below example will explain well the worst case..

package algo.sorting.rev;

import java.util.Arrays;

public class DualPivotQuickSort {

public static void main(String[] args) {
    int[] input = new int[] { 8, 6, 2, 4, 17,    3, 10, 19, 21, 13,   9, 19, 14, 13, 7,   17 };
    quicksort(input, 0, input.length - 1);
    System.out.println(Arrays.toString(input));
}

/**
 * 3 segments are as below.
 *
 * | item < pivotL | pivotL <= item <= pivotR | item > pivotR |
 *
 * |pivotLPos . . . j-1|j . . . k|k+1 . . . pivotRPos|
 *
 *
 * @param a
 * @param pivotLPos
 * @param pivotRPos
 */
private static void quicksort(int [] a, int pivotLPos, int pivotRPos){
    int size  = pivotRPos - pivotLPos + 1;

    if(size < 3)
        return;

    int pivotL = a[pivotLPos];
    int pivotR = a[pivotRPos];

    if(pivotL > pivotR)
        swapContent(a, pivotLPos, pivotRPos);

    int i = pivotLPos + 1;
    int j = pivotRPos - 1;
    int k = pivotRPos;

    while(i <= j){

        while(i < pivotRPos && a[i] < pivotL)
            i++;

        while(j >= pivotLPos && a[j] >= pivotL){
            if(a[j] <= pivotR)
                j--;
            else{
                // adding to segment3
                swapContent(a, j, k);
                j--;
                k--;
            }
        }

        if(i < j){
            swapContent(a, i, j);
            i++;

            if(a[j] > pivotR){
                // adding to segment3
                swapContent(a, j, k);
                k--;
            }
            j--;
        }
    }

    swapContent(a, j, pivotLPos);

    if(size > 3){
        if(j - pivotLPos >= 3)
            quicksort(a, pivotLPos, j-1);  // recursion on seg1
        if(k - j >= 3)
            quicksort(a, j, k);  // recursion on seg2
        if(j - pivotRPos >= 3)
            quicksort(a, k+1, pivotRPos);  // recursion on seg3
    }
}

private static void swapContent(int [] a, int pos1, int pos2){
    int b = a[pos1];
    int c = a[pos2];

    b ^= c;
    c ^= b;
    b ^= c;

    a[pos1] = b;
    a[pos2] = c;
}

}


问:
Ruby on Rails finding last saved record
In a scenario I am finding the last saved record using the code

```<code>last = Category.find(:last)
</code>```

This is to assign the id of category as the parent id to the sub-categories.

And so, I am assigning the it in this manner.

```<code>@subcategory.parent_id = last.id
</code>```

This works fine, but when multiple users are trying to create Categories, then there is a wrong assignment of parent_id to the subcategory. (Sometimes it takes the id of a different category if that was created last.)

Is there any other way to find the last record?

答:
Try this example...it might help you:</p>

```<code><% Specimen.find(:all, :order => 'distribution_sheet_id DESC', :limit => 10).each do |df| %>
  <%= df.id %>
<% end %>
</code>```

Title: Ruby on Rails finding last saved record

Body:
In a scenario I am finding the last saved record using the code

last = Category.find(:last)

This is to assign the id of category as the parent id to the sub-categories.

And so, I am assigning the it in this manner.

@subcategory.parent_id = last.id

This works fine, but when multiple users are trying to create Categories, then there is a wrong assignment of parent_id to the subcategory. (Sometimes it takes the id of a different category if that was created last.)

Is there any other way to find the last record?

Body:
Try this example...it might help you:

<% Specimen.find(:all, :order => 'distribution_sheet_id DESC', :limit => 10).each do |df| %>
  <%= df.id %>
<% end %>


问:
React Native: How to pass props from a Button?
Any idea how I can pass props from a button to a Component accessed via reference?

The component: <RBSheet ref={refRBSheet} >  </RBSheet>

The caller Button: <Button title="open" onPress={() => refRBSheet.current.open()} />

答:
You have to use React.forward ref for passing ref prop to other components.

For more information read this.

https://reactjs.org/docs/forwarding-refs.html


问:
How to display summary statistics by group in ggplot2
I have a data fram with 3 variables: manu, brand and vol.

Here is my plot. How can I display the total vol and % vol by manufacturer somewhere in the plot?

So, for manu A, we'll se 65 and 38% For manu B, we'll see 60 and 35%
Finally, for manu C, we'll see 45 and 26%

My data:

```<code>manu <- c('A', 'A', 'A', 'B',"B", "C","C")
brand <- c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2")
vol <- c(10,    25, 30, 45, 15, 25, 20)
</code>```

My code:

```<code>ggplot2::ggplot(environment=environment()) + ggplot2::geom_bar(ggplot2::aes(y = vol, x = manu, fill = brand), stat = "identity", position = ggplot2::position_stack(reverse = TRUE), data = df)
</code>```

FINAL ANSWER FOR COMPLETION SAKE:

```<code>library("magrittr")
library("dplyr")
library(ggplot2)

manu  <- c('A', 'A', 'A', 'B',"B", "C","C")
brand <- c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2")
vol   <- c(10, 25, 30, 45, 15, 25, 20)

df <- data.frame(manu = c('A', 'A', 'A', 'B',"B", "C","C"),
                 brand = c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2"),
                 vol = c(10, 25, 30, 45, 15, 25, 20))

df$grand_total_vol = sum(df$vol)

df2 <- df %>% group_by(manu) %>% mutate(total_vol = sum(vol)) %>% mutate(percent_vol = 100*total_vol/grand_total_vol)  %>% ungroup()

ggplot(data=df2) +
  geom_bar(aes(x=manu, y=vol, fill=brand),stat = "identity",position = position_stack(reverse = TRUE)) +
  geom_text(aes(x=manu, y=vol, label= paste0("Percent Vol: ", round(percent_vol*100,1),"%")),
            position = position_stack(vjust = .5)) +
  geom_text(aes(x = manu,y = 70, label = paste0(df2$total_vol, "; ", round(df2$percent_vol, 1), "%")))
</code>```

答:
Something like this should work. You will have to round/ play with the position of the percentages as you see fit.

```<code>install.packages("dplyr")
install.packages("magrittr")
library("magrittr")
library("dplyr")
library(ggplot2)

manu <- c('A', 'A', 'A', 'B',"B", "C","C")
brand <- c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2")
vol <- c(10,    25, 30, 45, 15, 25, 20)

df <- data.frame(manu = c('A', 'A', 'A', 'B',"B", "C","C"),
                 brand = c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2"),
                 vol = c(10, 25, 30, 45, 15, 25, 20))

df2 <- df %>% group_by(manu) %>% mutate(total_vol = sum(vol),
                                        percent_vol = vol/total_vol) %>%
          ungroup()

ggplot(data=df2) +
     geom_bar(aes(x=manu, y=vol, fill=brand),stat = "identity",position = position_stack(reverse = TRUE)) +
     geom_text(aes(x=manu, y=vol, label= paste0("Percent Vol: ", round(percent_vol*100,1),"%")),
              position = position_stack(vjust = .5)) +
     geom_text(aes(x = manu,y = 70, label = paste0("Total Vol: ",df2$total_vol)))
</code>```

EDITED

Body:
I have a data fram with 3 variables: manu, brand and vol.

Here is my plot. How can I display the total vol and % vol by manufacturer somewhere in the plot?

So, for manu A, we'll se 65 and 38% For manu B, we'll see 60 and 35%
Finally, for manu C, we'll see 45 and 26%

My data:

manu <- c('A', 'A', 'A', 'B',"B", "C","C")
brand <- c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2")
vol <- c(10,    25, 30, 45, 15, 25, 20)

My code:

ggplot2::ggplot(environment=environment()) + ggplot2::geom_bar(ggplot2::aes(y = vol, x = manu, fill = brand), stat = "identity", position = ggplot2::position_stack(reverse = TRUE), data = df)

FINAL ANSWER FOR COMPLETION SAKE:

library("magrittr")
library("dplyr")
library(ggplot2)

manu  <- c('A', 'A', 'A', 'B',"B", "C","C")
brand <- c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2")
vol   <- c(10, 25, 30, 45, 15, 25, 20)

df <- data.frame(manu = c('A', 'A', 'A', 'B',"B", "C","C"),
                 brand = c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2"),
                 vol = c(10, 25, 30, 45, 15, 25, 20))

df$grand_total_vol = sum(df$vol)

df2 <- df %>% group_by(manu) %>% mutate(total_vol = sum(vol)) %>% mutate(percent_vol = 100*total_vol/grand_total_vol)  %>% ungroup()

ggplot(data=df2) +
  geom_bar(aes(x=manu, y=vol, fill=brand),stat = "identity",position = position_stack(reverse = TRUE)) +
  geom_text(aes(x=manu, y=vol, label= paste0("Percent Vol: ", round(percent_vol*100,1),"%")),
            position = position_stack(vjust = .5)) +
  geom_text(aes(x = manu,y = 70, label = paste0(df2$total_vol, "; ", round(df2$percent_vol, 1), "%")))

Body:
Something like this should work. You will have to round/ play with the position of the percentages as you see fit.

install.packages("dplyr")
install.packages("magrittr")
library("magrittr")
library("dplyr")
library(ggplot2)

manu <- c('A', 'A', 'A', 'B',"B", "C","C")
brand <- c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2")
vol <- c(10,    25, 30, 45, 15, 25, 20)

df <- data.frame(manu = c('A', 'A', 'A', 'B',"B", "C","C"),
                 brand = c('A1', 'A2', 'A3', 'B1',"B2", "C1","C2"),
                 vol = c(10, 25, 30, 45, 15, 25, 20))

df2 <- df %>% group_by(manu) %>% mutate(total_vol = sum(vol),
                                        percent_vol = vol/total_vol) %>%
          ungroup()

ggplot(data=df2) +
     geom_bar(aes(x=manu, y=vol, fill=brand),stat = "identity",position = position_stack(reverse = TRUE)) +
     geom_text(aes(x=manu, y=vol, label= paste0("Percent Vol: ", round(percent_vol*100,1),"%")),
              position = position_stack(vjust = .5)) +
     geom_text(aes(x = manu,y = 70, label = paste0("Total Vol: ",df2$total_vol)))

EDITED


问:
Visual Studio Code - coding beginner
everyone. I am a graphic designer, and thought I would start to learn coding to write scripts for Adobe Illustrator in ExtendScript/JavaScript. I started some beginner tutorials and have been making progress. A response to a question I had posted on a JavaScript forum suggested I use Visual Studio Code as a writing environment, so I downloaded it. It seems to be very advanced, and I can't figure out how to use it. I watched some of the introductory videos and they seem to start with an assumption of some experience.

My question is does anyone know of any resources for someone just starting out with Visual Studio Code? I did some searching and couldn't find anything suitable.

Thanks for your time.
Joe

答:
Thanks to the popularity of VSCode, there are tons of YouTube videos on setup.  You did not mention whether your platform is MacOs or Windows, but there are plenty for both.

One suggestion:

If you're getting started with Illustrator scripts for the first time, it can be helpful to check out AI's preset scripts, already loaded on your machine when you install the program.  Play with them, break them, fix, and see how they work.

You can copy the script, save under a new name in the same directory you found them, and they'll be available in your AI scripts menu. In other words, you can use VSCode to edit, and execute that code within illustrator.

On a Windows machine, you might find them here:

C:\Program Files\Adobe\Adobe Illustrator 2020\Presets\en_US\Scripts

I hope this helps you get started.

Title: Visual Studio Code - coding beginner


问:
DART : Why dart apps are so big in size? (console app)
i made a console app  with dart that calculates 2 numbers and prints them
the size came about 5 MB !!

Download link (Windows only) https://drive.google.com/open?id=1sxlvlSZUdxewzFNiAv_bXwaUui2gs2yA

Here is the code

import 'dart:io';

int inputf1;
int inputf2;
int inputf3;

void main() {
  stdout.writeln('Type The First Number');
  var input1 = stdin.readLineSync();
  stdout.writeln('You typed: $input1 as the first number');
  sleep( Duration(seconds: 1));
  stdout.writeln('\nType The Second Number');
  var input2 = stdin.readLineSync();
  stdout.writeln('You typed: $input2 as the second number');
  sleep( Duration(seconds: 1));
  inputf1 = int.parse(input1);
  inputf2 = int.parse(input2);

  inputf3 = inputf1 + inputf2;
  print('\nfinal answer is : $inputf3');
  sleep( Duration(seconds: 10));
}
```

答:
The reason for the big executable is because the dart2native compiler is not really made to make a executable you can directly run on your machine from scratch. Instead, it package the dartaotruntime executable together with your AOT compiled Dart program.

The dartaotruntime contains all the Dart runtime libraries and dart2native does not remove anything from the dartaotruntime (also difficult since it is a binary) so you will get the whole runtime even if you only adds two numbers.

But it is not that bad since it is an one-cost penalty for every program. So if you make a very big program, the dartaotruntime are still only include once.

However, if you are deploying many small programs in a single package I will recommend you add the -k aot parameter to dart2native so it instead of an executable will generate an .aot file which you then can run with dartaotruntime <program.aot>.

This will make your deployment a bit more complicated but you will just need to provide the dartaotruntime binary together with you multiple .aot files.

I have compiled your program to both .exe and .aot on Dart for Windows 64 bit. version 2.8.2 so you can see the size difference:

Again, -k aot will not save you any disk space if you are only going to deploy a single executable. But it can save a lot if your project contains many programs.

It should also be noted that the .aot file is platform dependent like the .exe file would be. And you should use the same version of dartaotruntime which has been used to compile the file.


问:
Nodejs express promise.all().then() is not synchronous
I'm building a little app using Nodejs express where I update/delete some data. After it did the update/delete, I want to return the data from the database again. I'm using promise.all() because I want to either have everything succeed or fail together.

My problem is that it's not being run synchronously. Every now and then my code returns the data before the update/delete has happend.

Here is an example:

const save = async (houseId, personIds, pets, petsToDelete) => {
    let dbActions = []

    personIds.forEach((personId) => {
        pets.forEach((pet) => {
            pet.ownerId = personId
        })
        dbActions.push(
            PetRepository.deletePets(personId, petsToDelete),
            PetRepository.updatePets(personId, pets),
        )
    })

    await Promise.all(dbActions)
    let promiseResult = await Promise.all([
           PetRepository.findByHouse({ houseId: houseId })
    ])

    return promiseResult
}

```

<p>The issue is that PetRepository.findByHouse is sometimes returning data before all dbActions in the loop were executed/completed.</p>

<p>I thought adding them to an array and using that array in a Promise.all outside the loop would fix the issue, but it didn't. Any ideas?</p>

<p>How save() is called: </p>

<pre class="lang-js prettyprint-override"><code>    const promiseResponseHandler = (req, res, promise) => {
        promise.then(successResponse(req, res)).catch(...errorhandling...)
    }

    App.put('save/:houseId', (req, res) => {
        promiseResponseHandler(req, res, PetService.save(req.params.houseId, req.body[0], req.body[1], req.body[2]))
    })
</code>```

Update: repository functions

const Mongoose = require('mongoose')
Mongoose.Promise = global.Promise

Mongoose.connection.on('open', () => Logger.info('Db connection established'))
let connectionString

connectionString = `mongodb+srv://${Config.MONGO_HOST}?retryWrites=true`

connection = Mongoose.connect(
    connectionString,
    {
        user: Config.MONGO_USER,
        pass: Config.MONGO_PW,
        dbName: Config.MONGO_DB,
        reconnectTries: 3,
        useNewUrlParser: true
    }
).catch((err) => {
    Logger.error(err)
})

const deletePets = async (personId, petsToDelete) => {
    if (petsToDelete.length > 0) {
        await Pet.bulkWrite(
            petsToDelete.map((petId) => {
                deleteMany: {
                    filter: { personId: personId, petId: petId}
                }
            })
        )
    }
}

const updatePets = async (personId, pets) => {
    if (pets.length > 0) {
        await Pet.bulkWrite(
            pets.map((pet) => ({
                updateOne: {
                    filter: { personId: pet.personId, petId: petId },
                    update: {
                        $set: { name: pet.name },
                        $setOnInsert: {
                            petId: pet.petId,
                            personId: personId,
                            houseId: pet.houseId
                        }
                    }
                }
            }))
        )
    }
}

module.exports = { deletePets, updatePets }
```

答:
You are using thenables (callbacks) to approach this problem. It would be easier to use async/await. In order to be able to await the Promise.all, you would need to define save as an asynchronous function, like so:

const save = async (houseId, personIds, pets, petsToDelete) => {
    let dbActions = []

    personIds.forEach((personId) => {
        pets.forEach((pet) => {
            pet.ownerId = personId
        })
        dbActions.push(
            PetRepository.deletePets(personId, petsToDelete),
            PetRepository.updatePets(personId, pets),
        )
    })

    await Promise.all(dbActions)
    let promiseResult = await PetRepository.findByHouse({ houseId: houseId })
    return promiseResult
}
```

<p>You would then proceed to await the save in order to make sure it concludes before you continue.
Of course, you could do this with callbacks too, passing it to the save method, and calling it with your final response, like so:</p>

<pre class="lang-js prettyprint-override"><code>const save = (houseId, personIds, pets, petsToDelete, callback) => {
    let dbActions = []

    personIds.forEach((personId) => {
        pets.forEach((pet) => {
            pet.ownerId = personId
        })
        dbActions.push(
            PetRepository.deletePets(personId, petsToDelete),
            PetRepository.updatePets(personId, pets),
        )
    })

    Promise.all(dbActions).then(()=>
        // callback gets called with the response of the promise
        PetRepository.findByHouse({ houseId: houseId }).then(callback)
    )
}
</code>```

You do have to keep in mind that you can't just assign a promise to a variable and expect it to be the result. If you do:

let result = Promise.all([promise1, promise2])
```

result will contain a promise, so in order to get the value you'll either have to await it (inline) or then it (callback)

Body:
I'm building a little app using Nodejs express where I update/delete some data. After it did the update/delete, I want to return the data from the database again. I'm using promise.all() because I want to either have everything succeed or fail together.

My problem is that it's not being run synchronously. Every now and then my code returns the data before the update/delete has happend.

Here is an example:

const save = async (houseId, personIds, pets, petsToDelete) => {
    let dbActions = []

    personIds.forEach((personId) => {
        pets.forEach((pet) => {
            pet.ownerId = personId
        })
        dbActions.push(
            PetRepository.deletePets(personId, petsToDelete),
            PetRepository.updatePets(personId, pets),
        )
    })

    await Promise.all(dbActions)
    let promiseResult = await Promise.all([
           PetRepository.findByHouse({ houseId: houseId })
    ])

    return promiseResult
}

The issue is that PetRepository.findByHouse is sometimes returning data before all dbActions in the loop were executed/completed.

I thought adding them to an array and using that array in a Promise.all outside the loop would fix the issue, but it didn't. Any ideas?

How save() is called:

    const promiseResponseHandler = (req, res, promise) => {
        promise.then(successResponse(req, res)).catch(...errorhandling...)
    }

    App.put('save/:houseId', (req, res) => {
        promiseResponseHandler(req, res, PetService.save(req.params.houseId, req.body[0], req.body[1], req.body[2]))
    })

Update: repository functions

const Mongoose = require('mongoose')
Mongoose.Promise = global.Promise

Mongoose.connection.on('open', () => Logger.info('Db connection established'))
let connectionString

connectionString = `mongodb+srv://${Config.MONGO_HOST}?retryWrites=true`

connection = Mongoose.connect(
    connectionString,
    {
        user: Config.MONGO_USER,
        pass: Config.MONGO_PW,
        dbName: Config.MONGO_DB,
        reconnectTries: 3,
        useNewUrlParser: true
    }
).catch((err) => {
    Logger.error(err)
})

const deletePets = async (personId, petsToDelete) => {
    if (petsToDelete.length > 0) {
        await Pet.bulkWrite(
            petsToDelete.map((petId) => {
                deleteMany: {
                    filter: { personId: personId, petId: petId}
                }
            })
        )
    }
}

const updatePets = async (personId, pets) => {
    if (pets.length > 0) {
        await Pet.bulkWrite(
            pets.map((pet) => ({
                updateOne: {
                    filter: { personId: pet.personId, petId: petId },
                    update: {
                        $set: { name: pet.name },
                        $setOnInsert: {
                            petId: pet.petId,
                            personId: personId,
                            houseId: pet.houseId
                        }
                    }
                }
            }))
        )
    }
}

module.exports = { deletePets, updatePets }

Body:
You are using thenables (callbacks) to approach this problem. It would be easier to use async/await. In order to be able to await the Promise.all, you would need to define save as an asynchronous function, like so:

const save = async (houseId, personIds, pets, petsToDelete) => {
    let dbActions = []

    personIds.forEach((personId) => {
        pets.forEach((pet) => {
            pet.ownerId = personId
        })
        dbActions.push(
            PetRepository.deletePets(personId, petsToDelete),
            PetRepository.updatePets(personId, pets),
        )
    })

    await Promise.all(dbActions)
    let promiseResult = await PetRepository.findByHouse({ houseId: houseId })
    return promiseResult
}

You would then proceed to await the save in order to make sure it concludes before you continue.
Of course, you could do this with callbacks too, passing it to the save method, and calling it with your final response, like so:

const save = (houseId, personIds, pets, petsToDelete, callback) => {
    let dbActions = []

    personIds.forEach((personId) => {
        pets.forEach((pet) => {
            pet.ownerId = personId
        })
        dbActions.push(
            PetRepository.deletePets(personId, petsToDelete),
            PetRepository.updatePets(personId, pets),
        )
    })

    Promise.all(dbActions).then(()=>
        // callback gets called with the response of the promise
        PetRepository.findByHouse({ houseId: houseId }).then(callback)
    )
}

You do have to keep in mind that you can't just assign a promise to a variable and expect it to be the result. If you do:

let result = Promise.all([promise1, promise2])

result will contain a promise, so in order to get the value you'll either have to await it (inline) or then it (callback)


问:
Get the Username in a Gmail Contextual Gadget
I am writing a Gmail Contextual Gadget, and in order to authenticate the user correctly on the server, i need to know their full email address (john@googleapps.com).

I can retrieve the domain (googleapps.com) but not the username.

Using the content extractors I can get the 'To' field on the email, the only problem is if there are two users on the same domain emailed (ie john@googleapps.com and james@googleapps.com).

Any thoughts?

答:
You need to implement SSO (single sign-on) within the contextual gadget. When the contextual gadget loads it passes the opensocialid of the user. You have to maintain a correlation between the user emailid and user opensocialid in your local database and do the identification by opensocialid lookup.

Read here for more details: http://code.google.com/googleapps/marketplace/best_practices.html#gadget_sso


问:
Javascript modified array before group by
i am trying to modified array before groupBy

i have this array

```<code>[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]
</code>```

i am trying to modified as per count value has in object value count 3 + 2 = 5 object should in array

witch function i use ? for output array like this

```<code>[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]
</code>```

答:
```<code>let newArr = yourArr.reduce((arr, item) => {
  for (let i = 0; i < item.count; i++) {
      arr.push(item);
  }
  return arr;
}, []);

console.log(newArr);
</code>```

you can use reduce array's function. And make iterating by count inside it

or if you need create new objects try spread syntax

```<code>let newArr = yourArr.reduce((arr, item) => {
  for (let i = 0; i < item.count; i++) {
      arr.push({...item});
  }
  return arr;
}, []);

console.log(newArr);
</code>```

Body:
i am trying to modified array before groupBy

i have this array

[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]

i am trying to modified as per count value has in object value count 3 + 2 = 5 object should in array

witch function i use ? for output array like this

[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]

Body:
let newArr = yourArr.reduce((arr, item) => {
  for (let i = 0; i < item.count; i++) {
      arr.push(item);
  }
  return arr;
}, []);

console.log(newArr);

you can use reduce array's function. And make iterating by count inside it

or if you need create new objects try spread syntax

let newArr = yourArr.reduce((arr, item) => {
  for (let i = 0; i < item.count; i++) {
      arr.push({...item});
  }
  return arr;
}, []);

console.log(newArr);


问:
Product boxes with the same width and height, despite the size of the images
I was trying to create cards for different products, and the idea is that they should be all the same size in all directions, independent from the original size of the images, but now all the images are exceeding the limits that I thought I had placed.

Also, I started studying HTML and CSS about two weeks ago, so, sorry if it's just a simple thing.

image of my problem

#products-btn{
 outline: none;
 border-radius: 18px;
 background: transparent;
 border:2px solid black;
 font-size: 20px;
 width: 60%;
 height: 45px;
 cursor: pointer;
 margin: 10px;
}

#products-btn:hover{
 background-color:black;
 color: white;
}

#products-btn:active{
 opacity: 0.7;
}

#products{
 width: 100%;
 max-width: 1280px;
 text-align: center;

}

#cards{
 display: inline-block;
 border:1px solid black;
 max-width: 250px;
 text-align: center;
 font-family: arial;
 box-shadow: 2px 0 3px 4px #ccc;
}

#cards:not(:last-child){
 margin-right: 20px;
}

/*#cards img{
 border:1px solid black;
}
*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="products">

     <div id="cards" class="Product1">
      <img src="images/products/img1.jpg">
      <h1>Travel 1</h1>
      <p class="price">$240.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product one -->

     <div id="cards" class="Product2">
      <img src="images/products/img2.jpg">
      <h1>Travel 2</h1>
      <p class="price">$300.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product two -->

     <div id="cards" class="Product3">
      <img src="images/products/img3.jpg">
      <h1>Travel 3</h1>
      <p class="price">$280.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product three -->

    </div><!-- products container --></code>```

答:
You can make some changes to fit your images to the size you want. Like seen below.

Please also not, don't use #cards as id -- IDs must be globally unique so it doesn't make sense to be an ID. The same applies for your other ID values (e.g. buttons, and similar).

#products-btn{
 outline: none;
 border-radius: 18px;
 background: transparent;
 border:2px solid black;
 font-size: 20px;
 width: 60%;
 height: 45px;
 cursor: pointer;
 margin: 10px;
}

#products-btn:hover{
 background-color:black;
 color: white;
}

#products-btn:active{
 opacity: 0.7;
}

#products{
 width: 100%;
 max-width: 1280px;
 text-align: center;

}

.cards{
 display: inline-block;
 border:1px solid black;
 max-width: 250px;
 text-align: center;
 font-family: arial;
 box-shadow: 2px 0 3px 4px #ccc;
}

.cards:not(:last-child){
 margin-right: 20px;
}

.product-img {
  width: 100%;
  height: 200px;
  background-color: black;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

/*#cards img{
 border:1px solid black;
}
*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="products">

     <div class="cards Product1">
            <div class="product-img" style="background-image: url('https://placekitten.com/200/300');"></div>
      <h1>Travel 1</h1>
      <p class="price">$240.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product one -->

     <div class="cards Product2">
            <div class="product-img" style="background-image: url('https://placekitten.com/800/300');"></div>
      <h1>Travel 2</h1>
      <p class="price">$300.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product two -->

     <div class="cards Product3">
            <div class="product-img" style="background-image: url('https://placekitten.com/200/800');"></div>
      <h1>Travel 3</h1>
      <p class="price">$280.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product three -->

    </div><!-- products container --></code>```

Body:
I was trying to create cards for different products, and the idea is that they should be all the same size in all directions, independent from the original size of the images, but now all the images are exceeding the limits that I thought I had placed.

Also, I started studying HTML and CSS about two weeks ago, so, sorry if it's just a simple thing.

image of my problem

#products-btn{
 outline: none;
 border-radius: 18px;
 background: transparent;
 border:2px solid black;
 font-size: 20px;
 width: 60%;
 height: 45px;
 cursor: pointer;
 margin: 10px;
}

#products-btn:hover{
 background-color:black;
 color: white;
}

#products-btn:active{
 opacity: 0.7;
}

#products{
 width: 100%;
 max-width: 1280px;
 text-align: center;

}

#cards{
 display: inline-block;
 border:1px solid black;
 max-width: 250px;
 text-align: center;
 font-family: arial;
 box-shadow: 2px 0 3px 4px #ccc;
}

#cards:not(:last-child){
 margin-right: 20px;
}

/*#cards img{
 border:1px solid black;
}
*/

Travel 1

$240.00

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.

<button id="products-btn">Travel now!</button>

Travel 2

$300.00

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.

<button id="products-btn">Travel now!</button>

Travel 3

$280.00

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.

<button id="products-btn">Travel now!</button>

Body:
You can make some changes to fit your images to the size you want. Like seen below.

Please also not, don't use #cards as id -- IDs must be globally unique so it doesn't make sense to be an ID. The same applies for your other ID values (e.g. buttons, and similar).

#products-btn{
 outline: none;
 border-radius: 18px;
 background: transparent;
 border:2px solid black;
 font-size: 20px;
 width: 60%;
 height: 45px;
 cursor: pointer;
 margin: 10px;
}

#products-btn:hover{
 background-color:black;
 color: white;
}

#products-btn:active{
 opacity: 0.7;
}

#products{
 width: 100%;
 max-width: 1280px;
 text-align: center;

}

.cards{
 display: inline-block;
 border:1px solid black;
 max-width: 250px;
 text-align: center;
 font-family: arial;
 box-shadow: 2px 0 3px 4px #ccc;
}

.cards:not(:last-child){
 margin-right: 20px;
}

.product-img {
  width: 100%;
  height: 200px;
  background-color: black;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

/*#cards img{
 border:1px solid black;
}
*/

<div id="products">

     <div class="cards Product1">
            <div class="product-img" style="background-image: url('https://placekitten.com/200/300');"></div>
      <h1>Travel 1</h1>
      <p class="price">$240.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product one -->

     <div class="cards Product2">
            <div class="product-img" style="background-image: url('https://placekitten.com/800/300');"></div>
      <h1>Travel 2</h1>
      <p class="price">$300.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product two -->

     <div class="cards Product3">
            <div class="product-img" style="background-image: url('https://placekitten.com/200/800');"></div>
      <h1>Travel 3</h1>
      <p class="price">$280.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product three -->

    </div><!-- products container -->


答:
function then expects function to be provided but you provide just assignment and this assignment executes in a same time. So instead of

```<code>Promise.all(dbActions).then(
        (promiseResult = Promise.all([
            PetRepository.findByHouse({ houseId: houseId })
        ]))
    )
</code>```

write at least

```<code>Promise.all(dbActions).then( () =>
        (promiseResult = Promise.all([
            PetRepository.findByHouse({ houseId: houseId })
        ]))
    )
</code>```

but even this code looks strange. Why you put one promise inside Promise.all, and what do you expect to get in promiseResult - promise or result?

May be you meant

```<code>Promise.all(dbActions).then( () =>
  PetRepository.findByHouse({ houseId: houseId })
).then(res => { promiseResult = res })
</code>```

then in promiseResult you will get Pet instance itself

Title: Nodejs express promise.all().then() is not synchronous

Body:
function then expects function to be provided but you provide just assignment and this assignment executes in a same time. So instead of

Promise.all(dbActions).then(
        (promiseResult = Promise.all([
            PetRepository.findByHouse({ houseId: houseId })
        ]))
    )

write at least

Promise.all(dbActions).then( () =>
        (promiseResult = Promise.all([
            PetRepository.findByHouse({ houseId: houseId })
        ]))
    )

but even this code looks strange. Why you put one promise inside Promise.all, and what do you expect to get in promiseResult - promise or result?

May be you meant

Promise.all(dbActions).then( () =>
  PetRepository.findByHouse({ houseId: houseId })
).then(res => { promiseResult = res })

then in promiseResult you will get Pet instance itself


问:
.NET Entity Framework and stored procedures
I'm new to EF and I got a bit of a philosophical question: all the books, videos, online courses etc - go on and on about working directly with table databases - i.e. with classes that correspond directly to them. How the class I create will abstract away the tables and all that. and then the entire books or courses show all the things I can do to a class that will in turn happen at the database table - the CRUD operations and such.

And I'm thinking - we never work directly with tables, and there are reasons for it. Its such a bad idea - be for us to do it manually or for a framework to handle it for us. We always work with stored procedures, which is the way it should be done (they return SELECTs which JOINs from a bunch of tables typically, and this way we exploit the relational model and encapsulate it. we give permissions to execute stored procedures, not directly, full access to tables, etc etc...)

But all the EF material is 99% on OR mapping which is code-to-physical table, and then a quick mention that its possible to do it with stored procedures.

So... is that the thinking behind the EF philosophy? did I get it right and... what were MS people thinking??

Thank you

答:
I think this question is really ORM vs non-ORM. You mention stored procedures being the "correct" way to do it and I think most people ten years ago would've agreed with you. However, ORM's, like you said, are merely a more expressive, human-readable abstraction on top of SQL (or any query language).

There's something to be said about over-permissioning and ORM's definitely do require more permissions on a database than just execute on stored procedures. The trade-off in security (if it truly can't be controlled at another level) is developer speed, testability, and maintainability. That's not to say that query languages aren't able to be any of those things but that's a main goal of abstractions.

I've worked at shops that have been on both sides of the coin. In my experience, the shops who use ORM's also seem to have higher velocity. Whether directly correlated, I cannot say.


问:
Japanese Kanji handwriting input
I'd just like to ask if there are plans to provide a built-in handwriting IME for Japanese Kanji.  And perhaps for Traditional and Simplified Chinese as well.

The reason I ask is because is the only thing thing that I seem to miss from the iPhone.  It's really convenient to be able to naturally input the said characters on the phone and I've still yet to find a good enough input method.

Thanks in advance.

答: The add-on IME MultiLing Keyboard provides a Chinese/Japanese handwriting input plugin.</p>

Title: Japanese Kanji handwriting input


答:
You can use itertools:

```<code>from itertools import combinations

m = 2
n = 4

list(combinations(list(range(1, n+1)), m))
</code>```

EDITED: If you want a function, just return it:

```<code>from itertools import combinations

m = 2
n = 4

def listOfLists(n, m):
    return list(combinations(list(range(1, n+1)), m))

listOfLists(n, m)
</code>```

Title: List of increasing lists

Body:
You can use itertools:

from itertools import combinations

m = 2
n = 4

list(combinations(list(range(1, n+1)), m))

EDITED: If you want a function, just return it:

from itertools import combinations

m = 2
n = 4

def listOfLists(n, m):
    return list(combinations(list(range(1, n+1)), m))

listOfLists(n, m)


问:
Does every function get its own stack in c?
I recently learned about stacks, so I was experimenting to see what the stack size is and what happens when it overflows. I found out that on Unix the default stack size is 8 MiB, and that supports my findings since I cannot declare a string having size greater than or equal to 8 MiB in my main function. However, when I declare a variable in main() it affects other functions. For example:

```<code>#include <stdio.h>

void foo(void)
{
    long int size = 1024*1024*2;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
}

int main(int argc, char** argv)
{
    long int size = 1024*1024*6;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
    foo();
    return 0;
}
</code>```

This code results in segmentation fault but if I make the string size 5 MiB in main() then there is no segmentation fault. Does that mean my C program cannot allocate more than 8 MiB of RAM for local variables (of all functions)? If so, what IS the point of stacks?

答:
Does that mean my c program cannot allocate more than 8MB of ram for local variables (of all functions) ?

Yes and no. Yes, your program can't use more space for local variables than the available stack space, whatever that is. But no, you're not limited to 8MB for all functions, you're only limited to that much total stack space for functions that are currently executing. A program might contain thousands of functions, but only a relative handful of those will be invoked at any given moment.

When your program calls a function, space is reserved on the stack for the function's return value and it's local variables. If that function calls another function, space will then be reserved for that next function's return value and local variables. When each function returns, the return value is read and the local variables and return value are popped off the stack. So functions only use stack space while they're executing.

If so, what's the point of stacks ?

The point is to provide the space needed for local variables, to facilitate returning a value to the caller, and to make allocating that space fast and efficient. Functions don't typically need huge amounts of storage for local variables, so 8MB is typically more than enough.

If you find that you need to allocate a large amount of memory, there are memory allocation functions that make that easy. Let's say you need to create a multi-megabyte string as in your example. You'd typically use a function like malloc() or calloc() to create that object on the heap instead of on the stack, and the only local variable you'd need is a pointer to the allocated memory.

Body:
I recently learned about stacks, so I was experimenting to see what the stack size is and what happens when it overflows. I found out that on Unix the default stack size is 8 MiB, and that supports my findings since I cannot declare a string having size greater than or equal to 8 MiB in my main function. However, when I declare a variable in main() it affects other functions. For example:

#include <stdio.h>

void foo(void)
{
    long int size = 1024*1024*2;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
}

int main(int argc, char** argv)
{
    long int size = 1024*1024*6;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
    foo();
    return 0;
}

This code results in segmentation fault but if I make the string size 5 MiB in main() then there is no segmentation fault. Does that mean my C program cannot allocate more than 8 MiB of RAM for local variables (of all functions)? If so, what IS the point of stacks?


答:
You should give the image a maximum width of 100%. Then it can not exceed the maximum size of his parent div.

#cards img{
    max-width: 100%;
}
```

By the way, you should also focus on the usage of classes and ids. A class can be used on multiple elements on a page. But an id should only be used on one element.

Title: Product boxes with the same width and height, despite the size of the images

Body:
You should give the image a maximum width of 100%. Then it can not exceed the maximum size of his parent div.

#cards img{
    max-width: 100%;
}

By the way, you should also focus on the usage of classes and ids. A class can be used on multiple elements on a page. But an id should only be used on one element.


问:
fable::ARIMA produces only NULL model

Issue

I am trying to produce forecasts using regression models with ARIMA errors, but they always fail to produce anything other than a NULL model; in contrast, TSLM models work just fine on the same data.

Looking for an answer, I found this question on applying models to multiple time-series and tried to reproduce Rob Hyndman's example (copy-paste the code in rstudio cloud).

It didn't work (details below).

What's wrong?

Code

```<code>library(tidyverse)
library(tsibble)
library(fable)
library(lubridate)
set.seed(1)
ar1  <-  arima.sim(model=list(ar=.6), n=30)
ma1 <- arima.sim(model=list(ma=0.4), n=30)
Date  <- ymd(paste0("2019-01-",1:30))
tb <- bind_cols(Date=Date, ar1=ar1, ma1=ma1) %>%
        gather("Series", "value", -Date) %>%
        as_tsibble(index=Date, key=Series)
tb
tb_all <- tb %>% model(arima = ARIMA(value))
tb_all
</code>```

Output

```<code># A mable: 2 x 2
# Key:     Series [2]
  Series arima
  <chr>  <model>
1 ar1    <NULL model>
2 ma1    <NULL model>
</code>```

Session Info (on rstudio cloud)

```<code>R version 4.0.0 (2020-04-24)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.6 LTS

Matrix products: default
BLAS:   /usr/lib/atlas-base/atlas/libblas.so.3.0
LAPACK: /usr/lib/atlas-base/atlas/liblapack.so.3.0

locale:
 [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8
 [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8
 [7] LC_PAPER=C.UTF-8       LC_NAME=C              LC_ADDRESS=C
[10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] lubridate_1.7.8  gridtext_0.1.1   ggtext_0.1.0     forcats_0.5.0    stringr_1.4.0
 [6] dplyr_0.8.5      purrr_0.3.4      tidyr_1.1.0      tibble_3.0.1     ggplot2_3.3.0
[11] tidyverse_1.3.0  patchwork_1.0.0  zoo_1.8-8        tsibble_0.8.6    feasts_0.1.3
[16] fable_0.2.0      fabletools_0.1.3 janitor_2.0.1    eurostat_3.6.1   scales_1.1.1
[21] readr_1.3.1      here_0.1         devtools_2.3.0   usethis_1.6.1    pacman_0.5.1

loaded via a namespace (and not attached):
 [1] nlme_3.1-147       fs_1.4.1           sf_0.9-3           RColorBrewer_1.1-2
 [5] httr_1.4.1         rprojroot_1.3-2    tools_4.0.0        backports_1.1.7
 [9] utf8_1.1.4         R6_2.4.1           KernSmooth_2.23-16 DBI_1.1.0
[13] colorspace_1.4-1   withr_2.2.0        sp_1.4-2           tidyselect_1.1.0
[17] prettyunits_1.1.1  processx_3.4.2     curl_4.3           compiler_4.0.0
[21] rvest_0.3.5        cli_2.0.2          xml2_1.3.2         desc_1.2.0
[25] classInt_0.4-3     callr_3.4.3        digest_0.6.25      pkgconfig_2.0.3
[29] bibtex_0.4.2.2     sessioninfo_1.1.1  dbplyr_1.4.4       rlang_0.4.6
[33] readxl_1.3.1       rstudioapi_0.11    generics_0.0.2     jsonlite_1.6.1
[37] magrittr_1.5       Rcpp_1.0.4.6       munsell_0.5.0      fansi_0.4.1
[41] RefManageR_1.2.12  lifecycle_0.2.0    stringi_1.4.6      snakecase_0.11.0
[45] pkgbuild_1.0.8     plyr_1.8.6         grid_4.0.0         blob_1.2.1
[49] slider_0.1.3       crayon_1.3.4       lattice_0.20-41    haven_2.3.0
[53] hms_0.5.3          knitr_1.28         anytime_0.3.7      ps_1.3.3
[57] pillar_1.4.4       pkgload_1.0.2      reprex_0.3.0       glue_1.4.1
[61] remotes_2.1.1      modelr_0.1.8       vctrs_0.3.0        cellranger_1.1.0
[65] testthat_2.3.2     gtable_0.3.0       assertthat_0.2.1   xfun_0.14
[69] broom_0.5.6        countrycode_1.2.0  e1071_1.7-3        class_7.3-16
[73] warp_0.1.0         memoise_1.1.0      units_0.6-6        ellipsis_0.3.1
</code>```

答: manually installed package urca

Title: fable::ARIMA produces only NULL model

Body:
Issue

I am trying to produce forecasts using regression models with ARIMA errors, but they always fail to produce anything other than a NULL model; in contrast, TSLM models work just fine on the same data.

Looking for an answer, I found this question on applying models to multiple time-series and tried to reproduce Rob Hyndman's example (copy-paste the code in rstudio cloud).

It didn't work (details below).

What's wrong?

Code

library(tidyverse)
library(tsibble)
library(fable)
library(lubridate)
set.seed(1)
ar1  <-  arima.sim(model=list(ar=.6), n=30)
ma1 <- arima.sim(model=list(ma=0.4), n=30)
Date  <- ymd(paste0("2019-01-",1:30))
tb <- bind_cols(Date=Date, ar1=ar1, ma1=ma1) %>%
        gather("Series", "value", -Date) %>%
        as_tsibble(index=Date, key=Series)
tb
tb_all <- tb %>% model(arima = ARIMA(value))
tb_all

Output

# A mable: 2 x 2
# Key:     Series [2]
  Series arima
  <chr>  <model>
1 ar1    <NULL model>
2 ma1    <NULL model>

Session Info (on rstudio cloud)

R version 4.0.0 (2020-04-24)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.6 LTS

Matrix products: default
BLAS:   /usr/lib/atlas-base/atlas/libblas.so.3.0
LAPACK: /usr/lib/atlas-base/atlas/liblapack.so.3.0

locale:
 [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8
 [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8
 [7] LC_PAPER=C.UTF-8       LC_NAME=C              LC_ADDRESS=C
[10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] lubridate_1.7.8  gridtext_0.1.1   ggtext_0.1.0     forcats_0.5.0    stringr_1.4.0
 [6] dplyr_0.8.5      purrr_0.3.4      tidyr_1.1.0      tibble_3.0.1     ggplot2_3.3.0
[11] tidyverse_1.3.0  patchwork_1.0.0  zoo_1.8-8        tsibble_0.8.6    feasts_0.1.3
[16] fable_0.2.0      fabletools_0.1.3 janitor_2.0.1    eurostat_3.6.1   scales_1.1.1
[21] readr_1.3.1      here_0.1         devtools_2.3.0   usethis_1.6.1    pacman_0.5.1

loaded via a namespace (and not attached):
 [1] nlme_3.1-147       fs_1.4.1           sf_0.9-3           RColorBrewer_1.1-2
 [5] httr_1.4.1         rprojroot_1.3-2    tools_4.0.0        backports_1.1.7
 [9] utf8_1.1.4         R6_2.4.1           KernSmooth_2.23-16 DBI_1.1.0
[13] colorspace_1.4-1   withr_2.2.0        sp_1.4-2           tidyselect_1.1.0
[17] prettyunits_1.1.1  processx_3.4.2     curl_4.3           compiler_4.0.0
[21] rvest_0.3.5        cli_2.0.2          xml2_1.3.2         desc_1.2.0
[25] classInt_0.4-3     callr_3.4.3        digest_0.6.25      pkgconfig_2.0.3
[29] bibtex_0.4.2.2     sessioninfo_1.1.1  dbplyr_1.4.4       rlang_0.4.6
[33] readxl_1.3.1       rstudioapi_0.11    generics_0.0.2     jsonlite_1.6.1
[37] magrittr_1.5       Rcpp_1.0.4.6       munsell_0.5.0      fansi_0.4.1
[41] RefManageR_1.2.12  lifecycle_0.2.0    stringi_1.4.6      snakecase_0.11.0
[45] pkgbuild_1.0.8     plyr_1.8.6         grid_4.0.0         blob_1.2.1
[49] slider_0.1.3       crayon_1.3.4       lattice_0.20-41    haven_2.3.0
[53] hms_0.5.3          knitr_1.28         anytime_0.3.7      ps_1.3.3
[57] pillar_1.4.4       pkgload_1.0.2      reprex_0.3.0       glue_1.4.1
[61] remotes_2.1.1      modelr_0.1.8       vctrs_0.3.0        cellranger_1.1.0
[65] testthat_2.3.2     gtable_0.3.0       assertthat_0.2.1   xfun_0.14
[69] broom_0.5.6        countrycode_1.2.0  e1071_1.7-3        class_7.3-16
[73] warp_0.1.0         memoise_1.1.0      units_0.6-6        ellipsis_0.3.1

Body: manually installed package urca


问:
Implementation of TogetherJS is not working
I am trying to make a simple shareable text editor with Mozilla's TogetherJS, but it does not seem to work. Based on their instructions, I added the library/script in the head and calling the JS from the button.

https://togetherjs.com/

In the Head tag:

```<code><script src="https://togetherjs.com/togetherjs-min.js"></script>
</code>```

In the body:

```<code><button onclick="TogetherJS(this); return false;">Start TogetherJS</button>
</code>```

Full code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Test JS</title>
</head>
<body>
  <button onclick="TogetherJS(this); return false;">Start TogetherJS</button>

  <div>
    <textarea style="border:1px solid red; height:300px; width: 500px; font-size: 16px;">
   </textarea>
</div>

  <script src="https://togetherjs.com/togetherjs-min.js"></script>
  </body>
</html>
</code>```

It seems to super-simple, yet for some reason, it does not seem to work!

答:
Could you please check now wrap your script in the body i.e. </p>

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Test JS</title>
</head>
<body>
  <button onclick="TogetherJS(this); return false;">Start TogetherJS</button>

  <script src="https://togetherjs.com/togetherjs-min.js"></script>
</body>
</html>
</code>```

Body:
I am trying to make a simple shareable text editor with Mozilla's TogetherJS, but it does not seem to work. Based on their instructions, I added the library/script in the head and calling the JS from the button.

https://togetherjs.com/

In the Head tag:

In the body:

<button onclick="TogetherJS(this); return false;">Start TogetherJS</button>

Full code:

<!DOCTYPE html>

  <title>Test JS</title>

  <button onclick="TogetherJS(this); return false;">Start TogetherJS</button>

    <textarea style="border:1px solid red; height:300px; width: 500px; font-size: 16px;">
   </textarea>

It seems to super-simple, yet for some reason, it does not seem to work!

Body:
Could you please check now wrap your script in the body i.e.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Test JS</title>
</head>
<body>
  <button onclick="TogetherJS(this); return false;">Start TogetherJS</button>

  <script src="https://togetherjs.com/togetherjs-min.js"></script>
</body>
</html>


问:
Optimize row access and transformation in pyspark
I have a large dataset(5GB) in the form of jason in S3 bucket.
I need to transform the schema of the data, and write back the transformed data to S3 using an ETL script.

So I use a crawler to detect the schema and load the data in pyspark dataframe, and change the schema. Now I iterate over every row in the dataframe and convert it to dictionary. Remove null columns, and then convert the dictionary to string and write back to S3. Following is the code:

```<code>#df is the pyspark dataframe
columns = df.columns
print(columns)
s3 = boto3.resource('s3')
cnt = 1

for row in df.rdd.toLocalIterator():
    data = row.asDict(True)

    for col_name in columns:
        if data[col_name] is None:
            del data[col_name]

    content = json.dumps(data)
    object = s3.Object('write-test-transaction-transformed', str(cnt)).put(Body=content)
    cnt = cnt+1
print(cnt)
</code>```

I have used toLocalIterator.
Is the execution of above code performes serially? if yes then how to optimize it? Is there any better approach for execution of above logic?

答:
I solved the above problem.
We can simply query the dataframe for null values.
df = df.filter(df.column.isNotNull()) thereby removing all rows where null is present.
So if there are n columns, We need 2^n queries to filter out all possible combinations. In my case there were 10 columns so total of 1024 queries, which is acceptable as sql queries are parrallelized. </p>

Body:
I have a large dataset(5GB) in the form of jason in S3 bucket.
I need to transform the schema of the data, and write back the transformed data to S3 using an ETL script.

So I use a crawler to detect the schema and load the data in pyspark dataframe, and change the schema. Now I iterate over every row in the dataframe and convert it to dictionary. Remove null columns, and then convert the dictionary to string and write back to S3. Following is the code:

#df is the pyspark dataframe
columns = df.columns
print(columns)
s3 = boto3.resource('s3')
cnt = 1

for row in df.rdd.toLocalIterator():
    data = row.asDict(True)

    for col_name in columns:
        if data[col_name] is None:
            del data[col_name]

    content = json.dumps(data)
    object = s3.Object('write-test-transaction-transformed', str(cnt)).put(Body=content)
    cnt = cnt+1
print(cnt)

I have used toLocalIterator.
Is the execution of above code performes serially? if yes then how to optimize it? Is there any better approach for execution of above logic?


问:
Cannot npm install due to node-gyp: binding.gyp not found
I have been working on this all day and have tried lots of different things:

Uninstalling node and installing latest version

Using the --msvs_version= flag set to 2010, 2011, 2012, 2013, 2015

Deleting the .node-gyp folder

Adding python path to .npmrc like so: python=C:\Python27\python.exe

npm -g install npm@next

Running node-gyp rebuild and node-gyp configure

Following Robert Kehoe's guide

Rough times.

The package is an Electron/React app and I am running Windows 10. Console output for npm install is

```<code>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\x64\Microsoft.Cpp.x64.Targets(514,5): error MSB8008: Specif
ied platform toolset (v120) is not installed or invalid. Please make sure that a supported PlatformToolset value is sel
ected. [C:\Users\scheinerbock\Desktop\mpstudio\node_modules\mplib\build\addon.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `msbuild` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Users\scheinerbock\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\build.js:276:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:191:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Windows_NT 10.0.14393
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\scheinerbock\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\scheinerbock\Desktop\mpstudio\node_modules\mplib
gyp ERR! node -v v6.10.0
gyp ERR! node-gyp -v v3.5.0
gyp ERR! not ok
</code>```

And for node-gyp rebuild:

gyp: binding.gyp not found (cwd: C:\Users\scheinerbock\Desktop\mpstudio) while trying to load binding.gyp

I am well out of my wheelhouse here and would appreciate any suggestions or information in addition to solutions.

答:
I am using macos catalina 10.15.5 and i faced the same issues and all the above solutions didn't worked for me. I was able to resolve this by running

```<code>npm i -g node-gyp@latest && npm config set node_gyp "/usr/local/lib/node_modules/node-gyp/bin/node-gyp.js"
</code>```

Hope this helps people.

Body:
I have been working on this all day and have tried lots of different things:

Uninstalling node and installing latest version

Using the --msvs_version= flag set to 2010, 2011, 2012, 2013, 2015

Deleting the .node-gyp folder

Adding python path to .npmrc like so: python=C:\Python27\python.exe

npm -g install npm@next

Running node-gyp rebuild and node-gyp configure

Following Robert Kehoe's guide

Rough times.

The package is an Electron/React app and I am running Windows 10. Console output for npm install is

C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\x64\Microsoft.Cpp.x64.Targets(514,5): error MSB8008: Specif
ied platform toolset (v120) is not installed or invalid. Please make sure that a supported PlatformToolset value is sel
ected. [C:\Users\scheinerbock\Desktop\mpstudio\node_modules\mplib\build\addon.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `msbuild` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Users\scheinerbock\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\build.js:276:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:191:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Windows_NT 10.0.14393
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\scheinerbock\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\scheinerbock\Desktop\mpstudio\node_modules\mplib
gyp ERR! node -v v6.10.0
gyp ERR! node-gyp -v v3.5.0
gyp ERR! not ok

And for node-gyp rebuild:

gyp: binding.gyp not found (cwd: C:\Users\scheinerbock\Desktop\mpstudio) while trying to load binding.gyp

I am well out of my wheelhouse here and would appreciate any suggestions or information in addition to solutions.

Body:
I am using macos catalina 10.15.5 and i faced the same issues and all the above solutions didn't worked for me. I was able to resolve this by running

npm i -g node-gyp@latest && npm config set node_gyp "/usr/local/lib/node_modules/node-gyp/bin/node-gyp.js"

Hope this helps people.


问:
Linkedlist keep track of min in constant time?

EDIT:

This isn't as trivial as
  you think. Consider the fact that each
  addition of a new number pushes out an
  old number from the linkedlist.

The solution doesn't seem to be as
  simple as keeping track of a min
  number with a variable. What if the
  minimum gets pushed out of the
  linkedlist? Then what? How do you know
  what the new min is?

I heard this interview question:

You have a fixed length linked list.

At time t=0, the linkedlist is filled
with random numbers.

At each increment in time, one new
number is fed into the head of the
linkedlist, and one number is pushed
out from the tail.

You are allowed only ONE traversal before the first time interval.

This means one traversal ever. Not once at every time t.

.

O(1) storage.

Your task is to be able to return the min of the linkedlist at every time interation.

What is an algorithm that would be able to do this?

Interesting note:

Since there's no information regarding time complexity, you are allowed to use sort operations. The only problem then is: sorting takes more than one iteration.

答:
If node can be defined as follows, then solution is simple:</p>

```<code>class Node {
    int data;
    Node next;
    Node prevMin;
}
</code>```

Body:
If node can be defined as follows, then solution is simple:

class Node {
    int data;
    Node next;
    Node prevMin;
}


问:
The command returned a non-zero code: 2 docker
The following is the Dockerfile,

```<code>FROM alpine:3.10

# Add the testing repo in case it's needed for additional dependencies
# For example, gdal can be installed by using gdal@community
RUN echo "@community http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories

# Install system dependencies
RUN apk add --no-cache --update \
  bash \
  gcc \
  build-base \
  musl-dev \
  postgresql-dev \
  'python3~=3.7.5' \
  'python3-dev~=3.7.5' \
  curl \
# zlib, zlib-dev, and libjpeg-turbo are required by pillow
  zlib \
  zlib-dev \
  libjpeg-turbo \
  libjpeg-turbo-dev \
  libffi-dev
RUN pip3 install --no-cache-dir -q pipenv

# Add our code
ADD ./ /opt/webapp/
WORKDIR /opt/webapp

# Install dependencies
RUN pipenv install --deploy --system

# Allow SECRET_KEY to be passed via arg so collectstatic can run during build time
ARG SECRET_KEY
RUN python3 manage.py collectstatic --no-input

# Run the image as a non-root user
RUN adduser -D myuser
USER myuser

# Run the web server on port $PORT
CMD waitress-serve --port=$PORT performit_15391.wsgi:application
</code>```

The following is the LOG from the server that is recorded, I don't know why the build is failing, can anybody guide please?

```<code>=== Fetching app code.

=== Building release (./backend/Dockerfile)
Sending build context to Docker daemon    895kB

Step 1/12 : FROM alpine:3.10
3.10: Pulling from library/alpine
21c83c524219: Pulling fs layer
21c83c524219: Verifying Checksum
21c83c524219: Download complete
21c83c524219: Pull complete
Digest: sha256:f0e9534a598e501320957059cb2a23774b4d4072e37c7b2cf7e95b241f019e35
Status: Downloaded newer image for alpine:3.10
 ---> be4e4bea2c2e
Step 2/12 : RUN echo "@community http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories
 ---> Running in 42057b30f8bf
Removing intermediate container 42057b30f8bf
 ---> 015ada914599
Step 3/12 : RUN apk add --no-cache --update   bash   gcc   build-base   musl-dev   postgresql-dev   'python3~=3.7.5'   'python3-dev~=3.7.5'   curl   zlib   zlib-dev   libjpeg-turbo   libjpeg-turbo-dev   libffi-dev
 ---> Running in acf5e541c616
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
[91mERROR: unsatisfiable constraints:
[0m  python3-3.7.7-r0:
    breaks: world[python3~3.7.5]
    satisfies: python3-dev-3.7.7-r0[python3=3.7.7-r0]
  python3-dev-3.7.7-r0:
    breaks: world[python3-dev~3.7.5]
The command '/bin/sh -c apk add --no-cache --update   bash   gcc   build-base   musl-dev   postgresql-dev   'python3~=3.7.5'   'python3-dev~=3.7.5'   curl   zlib   zlib-dev   libjpeg-turbo   libjpeg-turbo-dev   libffi-dev' returned a non-zero code: 2
</code>```

This above is the log, the apk command is failing. Is there any dependency issue? for me the log message isn't very much useful. Thanks in advance.

答: There is a version conflict while installing Python. APK package manager supports python-3.7.7-r0 for alpine:3.10. But you have explicitly mentioned version 3.7.5 which is not available. Here either you can go with python 3.7.7 or use a base image which has python 3.7.5 to build your app.

Body:
The following is the Dockerfile,

FROM alpine:3.10

# Add the testing repo in case it's needed for additional dependencies
# For example, gdal can be installed by using gdal@community
RUN echo "@community http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories

# Install system dependencies
RUN apk add --no-cache --update \
  bash \
  gcc \
  build-base \
  musl-dev \
  postgresql-dev \
  'python3~=3.7.5' \
  'python3-dev~=3.7.5' \
  curl \
# zlib, zlib-dev, and libjpeg-turbo are required by pillow
  zlib \
  zlib-dev \
  libjpeg-turbo \
  libjpeg-turbo-dev \
  libffi-dev
RUN pip3 install --no-cache-dir -q pipenv

# Add our code
ADD ./ /opt/webapp/
WORKDIR /opt/webapp

# Install dependencies
RUN pipenv install --deploy --system

# Allow SECRET_KEY to be passed via arg so collectstatic can run during build time
ARG SECRET_KEY
RUN python3 manage.py collectstatic --no-input

# Run the image as a non-root user
RUN adduser -D myuser
USER myuser

# Run the web server on port $PORT
CMD waitress-serve --port=$PORT performit_15391.wsgi:application

The following is the LOG from the server that is recorded, I don't know why the build is failing, can anybody guide please?

=== Fetching app code.

=== Building release (./backend/Dockerfile)
Sending build context to Docker daemon    895kB

Step 1/12 : FROM alpine:3.10
3.10: Pulling from library/alpine
21c83c524219: Pulling fs layer
21c83c524219: Verifying Checksum
21c83c524219: Download complete
21c83c524219: Pull complete
Digest: sha256:f0e9534a598e501320957059cb2a23774b4d4072e37c7b2cf7e95b241f019e35
Status: Downloaded newer image for alpine:3.10
 ---> be4e4bea2c2e
Step 2/12 : RUN echo "@community http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories
 ---> Running in 42057b30f8bf
Removing intermediate container 42057b30f8bf
 ---> 015ada914599
Step 3/12 : RUN apk add --no-cache --update   bash   gcc   build-base   musl-dev   postgresql-dev   'python3~=3.7.5'   'python3-dev~=3.7.5'   curl   zlib   zlib-dev   libjpeg-turbo   libjpeg-turbo-dev   libffi-dev
 ---> Running in acf5e541c616
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
[91mERROR: unsatisfiable constraints:
[0m  python3-3.7.7-r0:
    breaks: world[python3~3.7.5]
    satisfies: python3-dev-3.7.7-r0[python3=3.7.7-r0]
  python3-dev-3.7.7-r0:
    breaks: world[python3-dev~3.7.5]
The command '/bin/sh -c apk add --no-cache --update   bash   gcc   build-base   musl-dev   postgresql-dev   'python3~=3.7.5'   'python3-dev~=3.7.5'   curl   zlib   zlib-dev   libjpeg-turbo   libjpeg-turbo-dev   libffi-dev' returned a non-zero code: 2

This above is the log, the apk command is failing. Is there any dependency issue? for me the log message isn't very much useful. Thanks in advance.


问:
merge 2 txt file in linux
file1

```<code>1
2
3
4
</code>```

file2

```<code>5
6
7
8
</code>```

result I want

```<code>1
5
2
6
3
7
4
8
</code>```

which file1 alternative with file2

not like

```<code>1
2
3
4
5
6
7
8
</code>```

can I merge file like this?

答:
Have you tried the below in the linux command line?

```<code>cat file2.txt >> file1.txt
</code>```

This will append the text in file1 to file 2.

Edit: Having seen your query is referring to intertwining the files, I think this article will help you using the 'sed' command: https://unix.stackexchange.com/questions/288521/with-the-linux-cat-command-how-do-i-show-only-certain-lines-by-number

Title: merge 2 txt file in linux

Body:
file1

1
2
3
4

file2

5
6
7
8

result I want

1
5
2
6
3
7
4
8

which file1 alternative with file2

not like

1
2
3
4
5
6
7
8

can I merge file like this?

Body:
Have you tried the below in the linux command line?

cat file2.txt >> file1.txt

This will append the text in file1 to file 2.

Edit: Having seen your query is referring to intertwining the files, I think this article will help you using the 'sed' command: https://unix.stackexchange.com/questions/288521/with-the-linux-cat-command-how-do-i-show-only-certain-lines-by-number


答:
hi can you try by applying css to image as i shown below this works correct

```<code>img{
max-width: 250px;
max-height: 300px;
}
</code>```

here is the image

Body:
hi can you try by applying css to image as i shown below this works correct

img{
max-width: 250px;
max-height: 300px;
}

here is the image