问:
Node: TypeError: Cannot read property 'replace' of undefined
Last Node project. When I try to access the server from the browser, it crashes and I get: "cannot read property 'replace' of undefined at ReadFileContext.callback". The server runs from the 'index.js' file fine, up until I try to access it from the browser. Not sure what it means. Hopefully, I am getting this error because I simply misspelled something.

const fs = require('fs');
const http = require('http');
const url = require('url');

const json = fs.readFileSync( `${__dirname}/data/data.json`, 'utf-8' );

// parses through the JSON file, returns a JS object, stores the object
const laptopData = JSON.parse(json);

const server = http.createServer( function(request, response) {

 // (1) we parse (read line-by-line) through the URL OBJECT, inside the object is the REQUEST OBJECT, inside that object is the value of the URL we typed into the BROWSER, we use 'true' so it returns an object,we only want the value of the URLs pathname property, lastly we store that value into a container: pathName
 const pathName = url.parse(request.url, true).pathname;

 // (2) we parse through the url object to get the value of the 'query' property
 const id = url.parse(request.url, true).query.id;

 // if the value of pathName is '/products'
 if (pathName === '/products' || pathName == '/') {

  // (1) our response will be a header
  response.writeHead(200, { 'Content-type': 'text/html' });

  // (2) this is the response
  response.end('This is the PRODUCTS page.'); //'This is the PRODUCTS page.'

 // if the value of pathName is '/laptop'
 } else if (pathName === '/laptop' && id < laptopData.length) {

  // (1) our response will be a header
  // the first value is the HTTP STATUS CODE that is displayed
  response.writeHead(200, { 'Content-type': 'text/html' });

  // stores the HTML into the 'data' para
  fs.readFile(`${__dirname}/templates/template-laptop.html`, 'utf-8', function (error, data) {

   // used to clean up the code
   const laptop = laptopData[id];

   // replaces all of the placeholders
   let output = data.replace(/{%PRODUCTNAME%}/g, laptop.productName);

   output = output.replace(/{%IMAGE%}/g, laptop.image);
   output = output.replace(/{%PRICE%}/g, laptop.price);
   output = output.replace(/{%SCREEN%}/g, laptop.screen);
   output = output.replace(/{%CPU%}/g, laptop.cpu);
   output = output.replace(/{%STORAGE%}/g, laptop.storage);
   output = output.replace(/{%RAM%}/g, laptop.ram);
   output = output.replace(/{%DESCRIPTION%}/g, laptop.description);

   response.end(output);

  });

 // if the value of pathName is neither '/products' nor '/laptop' nor empty
 } else {

  // (1) our response will be a header
  response.writeHead(400, { 'Content-type': 'text/html' });

  // (2) this is the response
  response.end('URL was not ground on the server!');

 };

});

server.listen(1337, '127.0.0.1', function() {
 console.log('Server is working.');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://fonts.googleapis.com/css?family=Bungee+Inline|Nunito+Sans" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <title>Apple Macbook Pro 2018 /// The Laptop Store!</title>

    <style>
        *,
        *::before,
        *::after {
            margin: 0;
            padding: 0;
            box-sizing: inherit;
        }

        html {
            font-size: 62.5%;
            box-sizing: border-box;
        }

        body {
            padding: 6rem 4rem 10rem;
            line-height: 1.7;
            font-family: "Nunito Sans", sans-serif;
            color: #555;
            min-height: 100vh;
            background: linear-gradient(to bottom right, #67b26f, #4ca2cd);
        }

        h1 {
            font-family: "Bungee Inline", sans-serif;
            font-weight: 400;
            font-size: 6rem;
            color: white;
            transform: skewY(-5deg);
            margin-bottom: 6rem;
            text-align: center;
            position: relative;
            word-spacing: 3px;
        }

        h1::before {
            content: '';
            display: block;
            height: 65%;
            width: 58%;
            position: absolute;
            top: 105%;
            left: 50%;
            background: linear-gradient(to bottom, #67b26f, #4ca2cd);
            opacity: .8;
            z-index: -1;
            transform: skewY(370deg) translate(-50%, -50%);
        }

        .container {
            width: 110rem;
            margin: 0 auto;
        }

        .laptop {
            width: 70rem;
            margin: 0 auto;
            background: white;
            box-shadow: 0 3rem 6rem 1rem rgba(0, 0, 0, 0.25);
            position: relative;
        }

        .laptop__hero {
            position: relative;
        }

        .laptop__hero::before {
            content: '';
            display: block;
            height: 100%;
            width: 100%;
            position: absolute;
            top: 0;
            left: 0;
            background-image: linear-gradient(to right bottom, #67b26f, #4ca2cd);
            opacity: .4;
        }

        .laptop__img {
            width: 100%;
            display: block;
        }

        .laptop__price {
            position: absolute;
            top: -3rem;
            right: -3rem;
            z-index: 100;
            background: linear-gradient(to right bottom, #67b26f, #4ca2cd);
            height: 14rem;
            width: 14rem;
            border: 6px solid white;
            border-radius: 50%;
            transform: rotate(15deg);
            box-shadow: 0 2rem 4rem rgba(0, 0, 0, 0.4);
            color: white;
            font-size: 3rem;
            font-family: "Bungee Inline", sans-serif;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .laptop__back:link,
        .laptop__back:visited {
            position: absolute;
            top: 2rem;
            left: 2rem;
            font-size: 1.5rem;
            color: white;
            font-weight: 700;
            text-transform: uppercase;
            text-decoration: none;
            z-index: 1;
            border: 2px solid white;
            border-radius: 100rem;
            padding: 0 2rem;
            transition: all .3s;
            display: flex;
            align-items: center;
        }

        .laptop__back:hover,
        .laptop__back:active {
            background-color: white;
            color: #555;
        }

        .laptop__name {
            background: linear-gradient(to right, #67b26f, #4ca2cd);
            padding: 1.75rem 1rem;
            font-family: "Bungee Inline", sans-serif;
            font-weight: 400;
            font-size: 3.25rem;
            color: white;
            text-align: center;
            word-spacing: 2px;
        }

        .laptop__details {
            background-color: #eee;
            padding: 4rem 6rem;
            font-size: 1.5rem;
            display: grid;
            grid-template-columns: 1fr 1fr;
            grid-gap: 1.75rem;
        }

        .laptop__description {
            padding: 5rem 6rem;
            font-size: 1.6rem;
            line-height: 1.8;
        }

        .laptop__link:link,
        .laptop__link:visited {
            display: block;
            background-color: #5aaa9d;
            color: white;
            font-size: 1.6rem;
            font-weight: 700;
            text-transform: uppercase;
            text-decoration: none;
            padding: 1.5rem;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all .3s;
        }

        .laptop__link:hover,
        .laptop__link:active {
            background-color: #67b26f;
        }

        .laptop__source {
            padding: 0 6rem 3rem;
            color: #999;
            font-size: 1.2rem;
        }

        .laptop__source a:link,
        .laptop__source a:visited {
            color: #999;
        }

        .laptop__source a:hover,
        .laptop__source a:active {
            color: #555;
        }

        .emoji-left {
            font-size: 2rem;
            margin-right: 1rem;
        }

        .emoji-right {
            font-size: 2rem;
            margin-left: 1rem;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>The Laptop Store!</h1>
        <figure class="laptop">
            <p class="laptop__price">${%PRICE%}</p>
            <span class="emoji-left"></span>Back
            <div class="laptop__hero">
                <img src="${%IMAGE%}" alt="${%PRODUCTNAME%}" class="laptop__img">
            </div>
            <h2 class="laptop__name">${%PRODUCTNAME%}</h2>
            <div class="laptop__details">
                <p><span class="emoji-left"></span> ${%SCREEN%}</p>
                <p><span class="emoji-left"></span> ${%CPU%}</p>
                <p><span class="emoji-left"></span> ${%STORAGE%}</p>
                <p><span class="emoji-left"></span> ${%RAM%}</p>
            </div>
            <p class="laptop__description">${%DESCRIPTION%}</p>
            <p class="laptop__source">Source: https://www.techradar.com/news/mobile-computing/laptops/best-laptops-1304361</p>
            ${%PRICE%} <span class="emoji-right"> </span>
        </figure>
    </div>
</body>

</html></code>```

答:
data is not a string (as indicated by the error message).

This means, most likely, there was an error. You are not looking at the error parameter error. You should check that to be sure you are getting a valid result before processing data.

Outputting the error will also give you information about how it is breaking.

Body:
Last Node project. When I try to access the server from the browser, it crashes and I get: "cannot read property 'replace' of undefined at ReadFileContext.callback". The server runs from the 'index.js' file fine, up until I try to access it from the browser. Not sure what it means. Hopefully, I am getting this error because I simply misspelled something.

const fs = require('fs');
const http = require('http');
const url = require('url');

const json = fs.readFileSync( `${__dirname}/data/data.json`, 'utf-8' );

// parses through the JSON file, returns a JS object, stores the object
const laptopData = JSON.parse(json);

const server = http.createServer( function(request, response) {

 // (1) we parse (read line-by-line) through the URL OBJECT, inside the object is the REQUEST OBJECT, inside that object is the value of the URL we typed into the BROWSER, we use 'true' so it returns an object,we only want the value of the URLs pathname property, lastly we store that value into a container: pathName
 const pathName = url.parse(request.url, true).pathname;

 // (2) we parse through the url object to get the value of the 'query' property
 const id = url.parse(request.url, true).query.id;

 // if the value of pathName is '/products'
 if (pathName === '/products' || pathName == '/') {

  // (1) our response will be a header
  response.writeHead(200, { 'Content-type': 'text/html' });

  // (2) this is the response
  response.end('This is the PRODUCTS page.'); //'This is the PRODUCTS page.'

 // if the value of pathName is '/laptop'
 } else if (pathName === '/laptop' && id < laptopData.length) {

  // (1) our response will be a header
  // the first value is the HTTP STATUS CODE that is displayed
  response.writeHead(200, { 'Content-type': 'text/html' });

  // stores the HTML into the 'data' para
  fs.readFile(`${__dirname}/templates/template-laptop.html`, 'utf-8', function (error, data) {

   // used to clean up the code
   const laptop = laptopData[id];

   // replaces all of the placeholders
   let output = data.replace(/{%PRODUCTNAME%}/g, laptop.productName);

   output = output.replace(/{%IMAGE%}/g, laptop.image);
   output = output.replace(/{%PRICE%}/g, laptop.price);
   output = output.replace(/{%SCREEN%}/g, laptop.screen);
   output = output.replace(/{%CPU%}/g, laptop.cpu);
   output = output.replace(/{%STORAGE%}/g, laptop.storage);
   output = output.replace(/{%RAM%}/g, laptop.ram);
   output = output.replace(/{%DESCRIPTION%}/g, laptop.description);

   response.end(output);

  });

 // if the value of pathName is neither '/products' nor '/laptop' nor empty
 } else {

  // (1) our response will be a header
  response.writeHead(400, { 'Content-type': 'text/html' });

  // (2) this is the response
  response.end('URL was not ground on the server!');

 };

});

server.listen(1337, '127.0.0.1', function() {
 console.log('Server is working.');
});

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://fonts.googleapis.com/css?family=Bungee+Inline|Nunito+Sans" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <title>Apple Macbook Pro 2018 /// The Laptop Store!</title>

The Laptop Store!

${%PRICE%}

            Back

${%PRODUCTNAME%}

 ${%SCREEN%}

 ${%CPU%}

 ${%STORAGE%}

 ${%RAM%}

${%DESCRIPTION%}

Source: https://www.techradar.com/news/mobile-computing/laptops/best-laptops-1304361

            ${%PRICE%}


来源: stackexchange

问:
How to prevent program from deleting last index in method
I have created a method that will take the first two values of the previous array and add them together and repeating this until it has created a new array of the added values. However, what I want to add a rule where if the last number of the previous array is odd I don't want that number to be added. I was able to somewhat do this but unfortunately at the cost of deleting the 2nd to last value of the index. Example my array of {1, 4, 6, 8, 3, 4, 6, 7, 10, 1} is printing [5,14,7,13,1] while I got the last number I still want that 10 to exist but I am stumped on how to get the code to work while not erasing the 10.</p>

```<code>import java.util.*;
import java.io.*;
public class reduceNumbers{
     public static int[] reduce(int[] numArray){
         int[] returnedArray = new int[(numArray.length) / 2];
         if(returnedArray[returnedArray.length - 1] % 2 == 1){
         for(int i = 0; i < returnedArray.length; i++) {

         returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
    }

}
else{
  for(int i = 0; i < returnedArray.length - 1; i++) {

    returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
}

returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1];

}

return returnedArray;
}

public static void main(String[] args){

int[] firstArray = {1, 4, 6, 8, 3, 4, 6, 7, 10, 1};

   int[] firstArrayA,

   firstArrayA= reduce(firstArray);

       System.out.println(Arrays.toString(firstArrayA) );

   }
}
</code>```

答:
To address the reason why your last element is a 1 the snippet of code:

```<code>returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1];
</code>```

should be instead:

```<code>returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1] + numArray[numArray.length - 2];
</code>```

in your else statement!

overall your code should look like this:

```<code>import java.io.*;

public class StackOverflow {
    public static int[] reduce(int[] numArray) {
        int[] returnedArray = new int[(numArray.length) / 2];
        if (returnedArray[returnedArray.length - 1] % 2 == 1) {
            for (int i = 0; i < returnedArray.length; i++) {

                returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
            }

        } else {
            for (int i = 0; i < returnedArray.length - 1; i++) {

                returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
            }

            returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1] + numArray[numArray.length - 2];

        }

        return returnedArray;
    }

    public static void main(String[] args) {

        int[] firstArray = { 1, 4, 6, 8, 3, 4, 6, 7, 10,1 };

        int[] firstArrayA;

        firstArrayA = reduce(firstArray);

        System.out.println(Arrays.toString(firstArrayA));

    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created a method that will take the first two values of the previous array and add them together and repeating this until it has created a new array of the added values. However, what I want to add a rule where if the last number of the previous array is odd I don't want that number to be added. I was able to somewhat do this but unfortunately at the cost of deleting the 2nd to last value of the index. Example my array of {1, 4, 6, 8, 3, 4, 6, 7, 10, 1} is printing [5,14,7,13,1] while I got the last number I still want that 10 to exist but I am stumped on how to get the code to work while not erasing the 10.

import java.util.*;
import java.io.*;
public class reduceNumbers{
     public static int[] reduce(int[] numArray){
         int[] returnedArray = new int[(numArray.length) / 2];
         if(returnedArray[returnedArray.length - 1] % 2 == 1){
         for(int i = 0; i < returnedArray.length; i++) {

         returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
    }

}
else{
  for(int i = 0; i < returnedArray.length - 1; i++) {

    returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
}

returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1];

}

return returnedArray;
}

public static void main(String[] args){

int[] firstArray = {1, 4, 6, 8, 3, 4, 6, 7, 10, 1};

   int[] firstArrayA,

   firstArrayA= reduce(firstArray);

       System.out.println(Arrays.toString(firstArrayA) );

   }
}

Body:
To address the reason why your last element is a 1 the snippet of code:

returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1];

should be instead:

returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1] + numArray[numArray.length - 2];

in your else statement!

overall your code should look like this:

import java.io.*;

public class StackOverflow {
    public static int[] reduce(int[] numArray) {
        int[] returnedArray = new int[(numArray.length) / 2];
        if (returnedArray[returnedArray.length - 1] % 2 == 1) {
            for (int i = 0; i < returnedArray.length; i++) {

                returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
            }

        } else {
            for (int i = 0; i < returnedArray.length - 1; i++) {

                returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
            }

            returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1] + numArray[numArray.length - 2];

        }

        return returnedArray;
    }

    public static void main(String[] args) {

        int[] firstArray = { 1, 4, 6, 8, 3, 4, 6, 7, 10,1 };

        int[] firstArrayA;

        firstArrayA = reduce(firstArray);

        System.out.println(Arrays.toString(firstArrayA));

    }
}


问:
Setting an array variable that is passed by reference
I have an array object variable as [ref] $InsertColHeadName = @() in a function and then call another function with param ([ref] $InsertColHeadName).  In the called function I then tried refering to my parameter set in param ([ref] $InsertColHeadName) += expression. The expression returns a string. I placed a breakpoint in the line and tried forcing a string with single quotes eg.: ([ref] $InsertColHeadName) += 'xyz';.

I tried googling around but can't seem to find a suitable solution.

I am getting the following error:

```Method invocation failed because [System.Management.Automation.PSReference`1
[[System.Management.Automation.PSReference`1
[[System.Management.Automation.PSReference`1
[[System.Object[], mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089]], System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Management.Automation,
Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]] does not
contain a method named 'op_Addition'.
At line:1 char:1
+ ([ref] $InsertColHeadName) += 'DepartmentNo';
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound```

答: Had this same issue.  Just have to make sure you do not cast the object to [ref] multiple times.  It's like casting [ref][ref][ref]$YourObject.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have an array object variable as [ref] $InsertColHeadName = @() in a function and then call another function with param ([ref] $InsertColHeadName).  In the called function I then tried refering to my parameter set in param ([ref] $InsertColHeadName) += expression. The expression returns a string. I placed a breakpoint in the line and tried forcing a string with single quotes eg.: ([ref] $InsertColHeadName) += 'xyz';.

I tried googling around but can't seem to find a suitable solution.

I am getting the following error:

Method invocation failed because [System.Management.Automation.PSReference`1
[[System.Management.Automation.PSReference`1
[[System.Management.Automation.PSReference`1
[[System.Object[], mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089]], System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Management.Automation,
Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]] does not
contain a method named 'op_Addition'.
At line:1 char:1
+ ([ref] $InsertColHeadName) += 'DepartmentNo';
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound


问:
Get maximum and minimum value using group by channel id
I want to get maximum and minimum value using group by channel id and also want to get maximum video id and minimum video id</p>

```<code> {

  "query": {
    "term": {
      "channel_id.keyword": {
        "value": "UCQOd1f6pYldvhgvdQ_ktpGA"
      }
    }
  },
  "aggs": {
    "views_max": {
      "max": {
        "field": "views",
        "missing": 0
      },
      "_source":["video_id","views"]
    },
     "views_min": {
      "min": {
        "field": "views",
        "missing": 0
      },
       "_source":["video_id","views"]
    }
  }
}
</code>```

答:
```<code>{
  "aggs": {
    "2": {
      "terms": {
        "field": "channel_id.keyword",
        "order": {
          "1": "desc"
        },
        "size": 10
      },
      "aggs": {
        "1": {
          "max": {
            "field": "video_id"
          }
        },
        "3": {
          "min": {
            "field": "video_id"
          }
        }
      }
    }
  },
  "size": 0,
  "_source": {
    "excludes": []
  },
  "query": {
    "bool": {
      "must": [],
      "filter": [
        {
          "bool": {
            "should": [
              {
                "match": {
                  "channel_id.keyword": "UCQOd1f6pYldvhgvdQ_ktpGA"
                }
              }
            ],
            "minimum_should_match": 1
          }
        }
      ]
    }
  }
}
</code>```

The above query will give the maximum and minimum of video_id for a particular channel_id.

```<code>{
  "aggs": {
    "2": {
      "terms": {
        "field": "channel_id.keyword",
        "order": {
          "1": "desc"
        },
        "size": 10
      },
      "aggs": {
        "1": {
          "max": {
            "field": "video_id"
          }
        },
        "3": {
          "min": {
            "field": "video_id"
          }
        }
      }
    }
  },
  "size": 0,
  "_source": {
    "excludes": []
  }
}
</code>```

With the above query, you will be able to fetch for all the distinct channel_id its respective maximum and minimum video_id

Body:
I want to get maximum and minimum value using group by channel id and also want to get maximum video id and minimum video id

 {

  "query": {
    "term": {
      "channel_id.keyword": {
        "value": "UCQOd1f6pYldvhgvdQ_ktpGA"
      }
    }
  },
  "aggs": {
    "views_max": {
      "max": {
        "field": "views",
        "missing": 0
      },
      "_source":["video_id","views"]
    },
     "views_min": {
      "min": {
        "field": "views",
        "missing": 0
      },
       "_source":["video_id","views"]
    }
  }
}

Body:
{
  "aggs": {
    "2": {
      "terms": {
        "field": "channel_id.keyword",
        "order": {
          "1": "desc"
        },
        "size": 10
      },
      "aggs": {
        "1": {
          "max": {
            "field": "video_id"
          }
        },
        "3": {
          "min": {
            "field": "video_id"
          }
        }
      }
    }
  },
  "size": 0,
  "_source": {
    "excludes": []
  },
  "query": {
    "bool": {
      "must": [],
      "filter": [
        {
          "bool": {
            "should": [
              {
                "match": {
                  "channel_id.keyword": "UCQOd1f6pYldvhgvdQ_ktpGA"
                }
              }
            ],
            "minimum_should_match": 1
          }
        }
      ]
    }
  }
}

The above query will give the maximum and minimum of video_id for a particular channel_id.

{
  "aggs": {
    "2": {
      "terms": {
        "field": "channel_id.keyword",
        "order": {
          "1": "desc"
        },
        "size": 10
      },
      "aggs": {
        "1": {
          "max": {
            "field": "video_id"
          }
        },
        "3": {
          "min": {
            "field": "video_id"
          }
        }
      }
    }
  },
  "size": 0,
  "_source": {
    "excludes": []
  }
}

With the above query, you will be able to fetch for all the distinct channel_id its respective maximum and minimum video_id


Title: 1d array from columns of an ndarray

Body:
This is the array I have at hand:

[array([[[ 4, 9,  1, -3],
         [-2, 0, 8, 6],
         [ 1, 3, 7,  9 ],
         [ 2,  5, 0, -7],
         [-1, -6, -5, -8]]]),
 array([[[ 0,  2, -1, 6 ],
         [9,  8,  0,  3],
         [ -1, 2, 5, -4],
         [0,  5, 9, 6],
         [ 6, 2,  9, 4]]]),
 array([[[ 1,  2,  0, 9],
         [3,  4, 8, -1],
         [5,  6,  9,  0],
         [ 7, 8, -3, -],
         [9, 0,  8, -2]]])]

But the goal is obtain arrays A from first columns of nested arrays, B from second columns of nested arrays, Cfrom third columns of nested array etc.

Such that:

A = array([4, -2, 1, 2, -1, 0, 9, -1 ,0, 6, 1, 3, 5, 7, 9])
B = array([9, 0, 3, 5, -6, 2, 8, 2, 5, 2, 2,, 4, 6, 8, 0])

How should I do this?

Body:
You can do this with a single hstack() and use squeeze() to remove the extra dimension. With that you can use regular numpy indexing to pull out columns (or anything else you want):

import numpy as np

l = [np.array([[[ 4, 9,  1, -3],
         [-2, 0, 8, 6],
         [ 1, 3, 7,  9 ],
         [ 2,  5, 0, -7],
         [-1, -6, -5, -8]]]),
     np.array([[[ 0,  2, -1, 6 ],
         [9,  8,  0,  3],
         [ -1, 2, 5, -4],
         [0,  5, 9, 6],
         [ 6, 2,  9, 4]]]),
     np.array([[[ 1,  2,  0, 9],
         [3,  4, 8, -1],
         [5,  6,  9,  0],
         [ 7, 8, -3, -1],
         [9, 0,  8, -2]]])]

arr = np.hstack(l).squeeze()

A = arr[:,0]
print(A)
# [ 4 -2  1  2 -1  0  9 -1  0  6  1  3  5  7  9]

B = arr[:,1]
print(B)
#[ 9  0  3  5 -6  2  8  2  5  2  2  4  6  8  0]
# etc...


问:
Pressing enter clicks button again
I have this button that I click to print a document. but the issues is it stays in focus I think and if I press enter key by mistake it prints it again {basically the button is getting pressed again on enter key. I am already using e.preventDefault() so I don't know why it is doing it. Is it possible to remopve this behaviour?

Basically I only want handleOrderPrint() to run on click and not when Enter key is pressed.

```<code><Button onClick={e => handleOrderPrint(e)} type="primary">Print</Button>}
</code>```

```<code> const handleOrderPrint = (e: any) => {
    e.preventDefault();
    ipcRenderer.send('generatePickingDocs', order);
    setPrinted(true);
  };
</code>```

Edit---------------->
Already tried this:

```<code>const btnEl = React.useRef(null);
  const handleOrderPrint = (e: any) => {
    e.preventDefault();
    if (e.keyCode !== 13) {
      console.log("Keycode", e.keyCode);
      ipcRenderer.send('generatePickingDocs', order);
      setPrinted(true);
    }
  };
</code>```

```<code><Button ref={btnEl} onClick={e => handleOrderPrint(e)} type="primary">Print</Button>
</code>```

答:
I believe you can use printed as button disable trigger

```<code> const [printed, setPrinted] = React.useState(false);
 const handleOrderPrint = (e: any) => {
        e.preventDefault();
        ipcRenderer.send('generatePickingDocs', order);
        setPrinted(true);
      };
 return (
 <Button disabled={printed} onClick={e => handleOrderPrint(e)} type="primary">Print</Button>)
</code>```

Edited

How about using ref

```<code> const [printed, setPrinted] = React.useState(false);
 const btnEl = React.useRef(null);
 const handleOrderPrint = (e: any) => {
        e.preventDefault();
        btnEl.blur();
        ipcRenderer.send('generatePickingDocs', order);
        setPrinted(true);
      };
 return (
 <Button ref={btnEl} onClick={e => handleOrderPrint(e)} type="primary">Print</Button>)
</code>```

Title: Pressing enter clicks button again

Body:
I have this button that I click to print a document. but the issues is it stays in focus I think and if I press enter key by mistake it prints it again {basically the button is getting pressed again on enter key. I am already using e.preventDefault() so I don't know why it is doing it. Is it possible to remopve this behaviour?

Basically I only want handleOrderPrint() to run on click and not when Enter key is pressed.

<Button onClick={e => handleOrderPrint(e)} type="primary">Print</Button>}

 const handleOrderPrint = (e: any) => {
    e.preventDefault();
    ipcRenderer.send('generatePickingDocs', order);
    setPrinted(true);
  };

Edit---------------->
Already tried this:

const btnEl = React.useRef(null);
  const handleOrderPrint = (e: any) => {
    e.preventDefault();
    if (e.keyCode !== 13) {
      console.log("Keycode", e.keyCode);
      ipcRenderer.send('generatePickingDocs', order);
      setPrinted(true);
    }
  };

<Button ref={btnEl} onClick={e => handleOrderPrint(e)} type="primary">Print</Button>

Body:
I believe you can use printed as button disable trigger

 const [printed, setPrinted] = React.useState(false);
 const handleOrderPrint = (e: any) => {
        e.preventDefault();
        ipcRenderer.send('generatePickingDocs', order);
        setPrinted(true);
      };
 return (
 <Button disabled={printed} onClick={e => handleOrderPrint(e)} type="primary">Print</Button>)

Edited

How about using ref

 const [printed, setPrinted] = React.useState(false);
 const btnEl = React.useRef(null);
 const handleOrderPrint = (e: any) => {
        e.preventDefault();
        btnEl.blur();
        ipcRenderer.send('generatePickingDocs', order);
        setPrinted(true);
      };
 return (
 <Button ref={btnEl} onClick={e => handleOrderPrint(e)} type="primary">Print</Button>)


问:
Returned is not empty but says length is 0
I'm returning data from firebase by using snapshots and pushing it to my own array. When i console.log it, it does have the elements in them, but console.log the length says 0.</p>

```<code>getConnections( user ) {
    const connections = [];
    const connectionsRef = this.db.database.ref( this.dbPath + user.id + '/connections/');
    connectionsRef.on('value', snapshot => {
            snapshot.forEach( childSS => {
                connections.push( childSS.child('personID').val() );
            });
    });
    return connections;
}

const connectionsOfUser = await this.chatService.getConnections( user );
            console.log(connectionsOfUser); // Gives result
            console.log(connectionsOfUser.length); // Shows 0
</code>```

答:
By the time your return connections runs, the connections.push(...) calls haven't run yet. So you always return an empty array. The console.log(connectionsOfUser) may seem to work, because Chrome dev tools updates the array when it is populated. If you want to see that what the value is at the moment, you can log it with console.log(JSON.stringify(connectionsOfUser)), which will show the empty array.

Your await doesn't work here because:

your getConnections is not marked as async

you're not returning a promise of a later array, but an empty array now.

A simple fix is to just use promises:

```<code>getConnections( user ) {
    const connectionsRef = this.db.database.ref( this.dbPath + user.id + '/connections/');
    return connectionsRef.once('value', snapshot => {
        const connections = [];
        snapshot.forEach( childSS => {
            connections.push( childSS.child('personID').val() );
        });
        return connections;
    });
}

this.chatService.getConnections( user ).then((connections) => {
    console.log(connectionsOfUser); // Gives result
    console.log(connectionsOfUser.length); // Shows 0
})
</code>```

So here:

We use once instead of on, since on() may fire multiple times, and we can only return a result once.

We return the connections from inside the callback, and then bubble them up with another return in the top-level of the function.

We then use then() in the calling code to get the connections.

You can probably now mark getConnections as async and then call it with await like you were trying:

```<code>const connectionsOfUser = await this.chatService.getConnections( user );
console.log(connectionsOfUser.length);
</code>```

Body:
I'm returning data from firebase by using snapshots and pushing it to my own array. When i console.log it, it does have the elements in them, but console.log the length says 0.

getConnections( user ) {
    const connections = [];
    const connectionsRef = this.db.database.ref( this.dbPath + user.id + '/connections/');
    connectionsRef.on('value', snapshot => {
            snapshot.forEach( childSS => {
                connections.push( childSS.child('personID').val() );
            });
    });
    return connections;
}

const connectionsOfUser = await this.chatService.getConnections( user );
            console.log(connectionsOfUser); // Gives result
            console.log(connectionsOfUser.length); // Shows 0

Body:
By the time your return connections runs, the connections.push(...) calls haven't run yet. So you always return an empty array. The console.log(connectionsOfUser) may seem to work, because Chrome dev tools updates the array when it is populated. If you want to see that what the value is at the moment, you can log it with console.log(JSON.stringify(connectionsOfUser)), which will show the empty array.

Your await doesn't work here because:

your getConnections is not marked as async

you're not returning a promise of a later array, but an empty array now.

A simple fix is to just use promises:

getConnections( user ) {
    const connectionsRef = this.db.database.ref( this.dbPath + user.id + '/connections/');
    return connectionsRef.once('value', snapshot => {
        const connections = [];
        snapshot.forEach( childSS => {
            connections.push( childSS.child('personID').val() );
        });
        return connections;
    });
}

this.chatService.getConnections( user ).then((connections) => {
    console.log(connectionsOfUser); // Gives result
    console.log(connectionsOfUser.length); // Shows 0
})

So here:

We use once instead of on, since on() may fire multiple times, and we can only return a result once.

We return the connections from inside the callback, and then bubble them up with another return in the top-level of the function.

We then use then() in the calling code to get the connections.

You can probably now mark getConnections as async and then call it with await like you were trying:

const connectionsOfUser = await this.chatService.getConnections( user );
console.log(connectionsOfUser.length);


问:
How to avoid parallel class hierarchy in python
I've been running into a weird little smell in my python code lately and I think it has something to do with parallel inheritance. Here is a small example I concocted:

```<code>class DogHabits:
    def __init__(self):
        self.habits = ['lick butt']

class GermanShepherdHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['herd sheep'])

class LabradorHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['hunt', 'pee on owner'])

class Dog:
    def __init__(self):
        self.type = 'generic_dog'
        self.my_habits = DogHabits()

    def do_stuff(self):
        for habit in self.my_habits.habits:
            print(habit)

class GermanShepherd(Dog):
    def __init__(self):
        self.type = 'german shepherd'
        self.my_habits = GermanShepherdHabits()

class Labrador(Dog):
    def __init__(self):
        self.type = 'labrador'
        self.my_habits = LabradorHabits()

if __name__ == "__main__":
    german_shepherd = GermanShepherd()
    print('\n{}'.format(german_shepherd.type))
    german_shepherd.do_stuff()

    labrador = Labrador()
    print('\n{}'.format(labrador.type))
    labrador.do_stuff()
</code>```

I have a generic dog class from which concrete dog implementations inherit. Every dog class (including the generic/abstract one) has a set of habits, itself represented by another class hierarchy for the habits.

I am annoyed by the fact that I have to have both hierarchies exactly the same at all times. Furthermore the inheritance between the DogHabits is useful within the habits hierarchy, but it is not useful within the dogs hierarchy, as I need to instantiate a separate habits object for each class in the dog hierarchy.

What is the antidote to this? I may want to add many implementations of the dog class, and updating the corresponding habits hierarchy sounds tedious and smells bad...

答:
IF habits need to a class attribute, rather than instance attributes, this may actually be a good use for metaclasses.

Habits need not be a simple list, it could be something else, as long as there is the notion of addition to previous and return new.  (__add__ or __radd__ on a Habits class would do the trick I think)

```<code>class DogType(type):

    def __init__(cls, name, bases, attrs):
        """ this is called at the Dog-class creation time.  """

        if not bases:
            return

        #pick the habits of direct ancestor and extend it with
        #this class then assign to cls.
        if "habits" in attrs:
            base_habits = getattr(bases[0], "habits", [])
            cls.habits = base_habits + cls.habits

class Dog(metaclass=DogType):
    habits = ["licks butt"]

    def __repr__(self):
        return f"My name is {self.name}.  I am a {self.__class__.__name__} %s and I like to {self.habits}"

    def __init__(self, name):
        """ dog instance can have all sorts of instance variables"""
        self.name = name

class Sheperd(Dog):
    habits = ["herds sheep"]

class GermanSheperd(Sheperd):
    habits = ["bites people"]

class Poodle(Dog):
    habits = ["barks stupidly"]

class StBernard(Dog):
    pass

for ix, cls in enumerate([GermanSheperd, Poodle, StBernard]):
    name = f"dog{ix}"
    dog = cls(name)
    print(dog)
</code>```

output:

```<code>My name is dog0.  I am a GermanSheperd %s and I like to ['licks butt', 'herds sheep', 'bites people']
My name is dog1.  I am a Poodle %s and I like to ['licks butt', 'barks stupidly']
My name is dog2.  I am a StBernard %s and I like to ['licks butt']
</code>```

Body:
I've been running into a weird little smell in my python code lately and I think it has something to do with parallel inheritance. Here is a small example I concocted:

class DogHabits:
    def __init__(self):
        self.habits = ['lick butt']

class GermanShepherdHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['herd sheep'])

class LabradorHabits(DogHabits):
    def __init__(self):
        super().__init__()
        self.habits.extend(['hunt', 'pee on owner'])

class Dog:
    def __init__(self):
        self.type = 'generic_dog'
        self.my_habits = DogHabits()

    def do_stuff(self):
        for habit in self.my_habits.habits:
            print(habit)

class GermanShepherd(Dog):
    def __init__(self):
        self.type = 'german shepherd'
        self.my_habits = GermanShepherdHabits()

class Labrador(Dog):
    def __init__(self):
        self.type = 'labrador'
        self.my_habits = LabradorHabits()

if __name__ == "__main__":
    german_shepherd = GermanShepherd()
    print('\n{}'.format(german_shepherd.type))
    german_shepherd.do_stuff()

    labrador = Labrador()
    print('\n{}'.format(labrador.type))
    labrador.do_stuff()

I have a generic dog class from which concrete dog implementations inherit. Every dog class (including the generic/abstract one) has a set of habits, itself represented by another class hierarchy for the habits.

I am annoyed by the fact that I have to have both hierarchies exactly the same at all times. Furthermore the inheritance between the DogHabits is useful within the habits hierarchy, but it is not useful within the dogs hierarchy, as I need to instantiate a separate habits object for each class in the dog hierarchy.

What is the antidote to this? I may want to add many implementations of the dog class, and updating the corresponding habits hierarchy sounds tedious and smells bad...

Body:
IF habits need to a class attribute, rather than instance attributes, this may actually be a good use for metaclasses.

Habits need not be a simple list, it could be something else, as long as there is the notion of addition to previous and return new.  (__add__ or __radd__ on a Habits class would do the trick I think)

class DogType(type):

    def __init__(cls, name, bases, attrs):
        """ this is called at the Dog-class creation time.  """

        if not bases:
            return

        #pick the habits of direct ancestor and extend it with
        #this class then assign to cls.
        if "habits" in attrs:
            base_habits = getattr(bases[0], "habits", [])
            cls.habits = base_habits + cls.habits

class Dog(metaclass=DogType):
    habits = ["licks butt"]

    def __repr__(self):
        return f"My name is {self.name}.  I am a {self.__class__.__name__} %s and I like to {self.habits}"

    def __init__(self, name):
        """ dog instance can have all sorts of instance variables"""
        self.name = name

class Sheperd(Dog):
    habits = ["herds sheep"]

class GermanSheperd(Sheperd):
    habits = ["bites people"]

class Poodle(Dog):
    habits = ["barks stupidly"]

class StBernard(Dog):
    pass

for ix, cls in enumerate([GermanSheperd, Poodle, StBernard]):
    name = f"dog{ix}"
    dog = cls(name)
    print(dog)

output:

My name is dog0.  I am a GermanSheperd %s and I like to ['licks butt', 'herds sheep', 'bites people']
My name is dog1.  I am a Poodle %s and I like to ['licks butt', 'barks stupidly']
My name is dog2.  I am a StBernard %s and I like to ['licks butt']


问:
how to find/replace in a json file using jtc?
I have the file below. Using jtc how to I replace all occurrences of "value": 1234.56 with "value": {"$numberDecimal":"1234.56"}; that is, wrap the numbers. This is for mongoimport, I want to require values to be imported as decimals not floats.

Or maybe there's a better solution using jq?

An example file:

```<code>{
  "data": {
    "slice": [
      {
        "source": {
          "id": "foo"
        },
        "value": 1.0
      },
      {
        "source": {
          "id": "bar"
        },
        "value": 2.0
      }
    ]
  }
}
</code>```

答:
If I understand the question correctly, then with the latest jtc build you can do it like this:

```<code>bash $ <file.json jtc -w'[value]:<>N:' -u'{"$numberDecimal":"{}"};' -tc
{
   "data": {
      "slice": [
         {
            "source": { "id": "foo" },
            "value": { "$numberDecimal": "1.0" }
         },
         {
            "source": { "id": "bar" },
            "value": { "$numberDecimal": "2.0" }
         }
      ]
   }
}
bash $
</code>```

and if you like to do an in-place file modifications then use -f:

```<code>bash $ jtc -w'[value]:<>N:' -u'{"$numberDecimal":"{}"};' -f file.json
</code>```

Body:
I have the file below. Using jtc how to I replace all occurrences of "value": 1234.56 with "value": {"$numberDecimal":"1234.56"}; that is, wrap the numbers. This is for mongoimport, I want to require values to be imported as decimals not floats.

Or maybe there's a better solution using jq?

An example file:

{
  "data": {
    "slice": [
      {
        "source": {
          "id": "foo"
        },
        "value": 1.0
      },
      {
        "source": {
          "id": "bar"
        },
        "value": 2.0
      }
    ]
  }
}

Body:
If I understand the question correctly, then with the latest jtc build you can do it like this:

bash $ <file.json jtc -w'[value]:<>N:' -u'{"$numberDecimal":"{}"};' -tc
{
   "data": {
      "slice": [
         {
            "source": { "id": "foo" },
            "value": { "$numberDecimal": "1.0" }
         },
         {
            "source": { "id": "bar" },
            "value": { "$numberDecimal": "2.0" }
         }
      ]
   }
}
bash $

and if you like to do an in-place file modifications then use -f:

bash $ jtc -w'[value]:<>N:' -u'{"$numberDecimal":"{}"};' -f file.json


问:
CSS selector when no sibling of certain type is present
Consider these scenarios:

Scenario 1:

```<code><div>
  <Button class="button"/>
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div>
</code>```

Scenario 2:

```<code><div>
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div>
</code>```

I want to write a css selector for div3 only when its <button>sibling is not present i.e. for Scenario 2.

Is that possible?

答:
if you want to use class selector in particular you can do:

div .div3 {
  background: red;
}
div .button ~ .div3 {
  background: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>with Button
<div>
  <button class="button"></button>
  <div class="div1" >div1</div>
  <div class="div2"> div2</div>
  <div class="div3" >div3</div>
</div>
    <br><br>
without Button
<div>
  <div class="div1" >div1</div>
  <div class="div2"> div2</div>
  <div class="div3" >div3</div>
</div></code>```

Body:
Consider these scenarios:

Scenario 1:

  <Button class="button"/>

Scenario 2:

I want to write a css selector for div3 only when its <button>sibling is not present i.e. for Scenario 2.

Is that possible?

Body:
if you want to use class selector in particular you can do:

div .div3 {
  background: red;
}
div .button ~ .div3 {
  background: none;
}

with Button
<div>
  <button class="button"></button>
  <div class="div1" >div1</div>
  <div class="div2"> div2</div>
  <div class="div3" >div3</div>
</div>
    <br><br>
without Button
<div>
  <div class="div1" >div1</div>
  <div class="div2"> div2</div>
  <div class="div3" >div3</div>
</div>


问:
Execute @Handler method in multi-thread
Need to execute @Handler(import org.apache.camel.Handler) method in multi-threading environment. below is my current code and camelroute.xml file. Any Idea or suggestion would be appreciable.

```<code>@Component("messagehandler")
public class HandleMessages {
    @Handler
    public void handle(String body, Exchange exchange) throws Exception {
      // do some business operation
    }
    }
</code>```

```<code><?xml version="1.0" encoding="UTF-8"?>

<routes xmlns="http://camel.apache.org/schema/spring"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <route id="IncomingRoute">
         <from uri="someSourceURL" />
        <to uri="bean:messagehandler" />
        <log message="Message Body - ${body}" />
    </route>

</routes>
</code>```

答:
In general terms, thread safety is all about execution – that's all. A given method / routine / piece of code is thread-safe if it guarantees the manipulation of shared data (data structures, etc.) safely in a way that multiple threads don't corrupt that data.

So it really depends on how you structure the execution of a given workflow; and that's the same for any other piece of code you can think of.

Since you are using Apache Camel, take a look at their threading model. If I remember correctly, you would have to define your routes / workflows in such a way they run concurrently by using parallelProcessing (CC EIP), a custom thread pool, or using staged event-driven architecture (SEDA); at that point you would need to take care about what you do in the handlers (or any other "processor(s)" that handle shared data), otherwise you should be OK.

Another thing you need to think about is how Camel uses its routing engine to route messages synchronously or asynchronously; be aware that synchronicity and MEP affects the threading model.

Title: Execute @Handler method in multi-thread

Body:
Need to execute @Handler(import org.apache.camel.Handler) method in multi-threading environment. below is my current code and camelroute.xml file. Any Idea or suggestion would be appreciable.

@Component("messagehandler")
public class HandleMessages {
    @Handler
    public void handle(String body, Exchange exchange) throws Exception {
      // do some business operation
    }
    }

<?xml version="1.0" encoding="UTF-8"?>

<routes xmlns="http://camel.apache.org/schema/spring"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <route id="IncomingRoute">
         <from uri="someSourceURL" />
        <to uri="bean:messagehandler" />
        <log message="Message Body - ${body}" />
    </route>

</routes>


问:
Score number of factors in common with R
I'm dealing with a tricky problem. Suppose I have the following data:

```<code>df <- data.frame(matrix(ncol = 0, nrow = 7))
df$x <- factor(c("blue","blue","red","red","green","green","black"))
df$y <- factor(c("A","B","A","C","B","C","A"))
df$z <- c(1998, 1998, 1998, 1998, 1999, 2000, 2001)
</code>```

We can see that A and B have blue in common, but not red or black. A and C have red in common, but not blue, green, or black. And so on.

I want to generate a matrix that scores the proportion of colors that letters i,j have in common out of the union of all colors they occupy (but not colors unoccupied by either letter). In other words, the diagonals would be the number of colors letter i occupies total, and the off-diagonals would be the share of colors letter i jointly occupies with letter j for all i,j.

I can do it for each pair A,B individually with something like this:

```<code>df.A <- df[df$x %in% unique(df$x[df$y=="A"]),] # number of rows occupied by A

df.B <- df[df$x %in% unique(df$x[df$y=="B"]),] # number of rows occupied by B

length(df.A$y[df.A$y=="B"]) # number of A's rows occupied by B

length(df.A$y[df.A$y=="B"]) / (length(df.A$y[df.A$y=="A"])) # proportion of times B agrees with A; i.e. (B|A) / A
</code>```

In this example, we find that A occupies three colors total, and B two total. Of these, A and B only have one in common. Out of everything A occupies (n=3, NOT the entire set of n=6), B only overlaps on one, for a proportion of 0.333.

In my actual data have thousands of rows and hundreds of factor levels, so it's impossible to do all the permutations by hand. But I can't figure out how to write a function that does it, even after much searching. I figure there must be a straightforward solution that I'm overlooking. Please help!

UPDATE: Thanks to @Ian Campbell and @thelatemail, the solution is simply:

```<code>t(table(df[,1:2])) %*% table(df[,1:2])
</code>```

or crossprod(table(df$x, df$y))

To answer the rest of my own question, I can obtain the proportions I want simply by taking:

```<code>x <- t(table(df[,1:2])) %*% table(df[,1:2])

x / diag(x)
</code>```

答:
I love it when I can use linear algebra for something.

```<code>t(table(df[,1:2])) %*% table(df[,1:2])
   y
y   A B C
  A 3 1 1
  B 1 2 1
  C 1 1 2
</code>```

Edit: As noted by @thelatemail, there is a built in (potentially faster) function as well:

```<code>crossprod(table(df$x, df$y))

    A B C
  A 3 1 1
  B 1 2 1
  C 1 1 2
</code>```

Body:
I'm dealing with a tricky problem. Suppose I have the following data:

df <- data.frame(matrix(ncol = 0, nrow = 7))
df$x <- factor(c("blue","blue","red","red","green","green","black"))
df$y <- factor(c("A","B","A","C","B","C","A"))
df$z <- c(1998, 1998, 1998, 1998, 1999, 2000, 2001)

We can see that A and B have blue in common, but not red or black. A and C have red in common, but not blue, green, or black. And so on.

I want to generate a matrix that scores the proportion of colors that letters i,j have in common out of the union of all colors they occupy (but not colors unoccupied by either letter). In other words, the diagonals would be the number of colors letter i occupies total, and the off-diagonals would be the share of colors letter i jointly occupies with letter j for all i,j.

I can do it for each pair A,B individually with something like this:

df.A <- df[df$x %in% unique(df$x[df$y=="A"]),] # number of rows occupied by A

df.B <- df[df$x %in% unique(df$x[df$y=="B"]),] # number of rows occupied by B

length(df.A$y[df.A$y=="B"]) # number of A's rows occupied by B

length(df.A$y[df.A$y=="B"]) / (length(df.A$y[df.A$y=="A"])) # proportion of times B agrees with A; i.e. (B|A) / A

In this example, we find that A occupies three colors total, and B two total. Of these, A and B only have one in common. Out of everything A occupies (n=3, NOT the entire set of n=6), B only overlaps on one, for a proportion of 0.333.

In my actual data have thousands of rows and hundreds of factor levels, so it's impossible to do all the permutations by hand. But I can't figure out how to write a function that does it, even after much searching. I figure there must be a straightforward solution that I'm overlooking. Please help!

UPDATE: Thanks to @Ian Campbell and @thelatemail, the solution is simply:

t(table(df[,1:2])) %*% table(df[,1:2])

or crossprod(table(df$x, df$y))

To answer the rest of my own question, I can obtain the proportions I want simply by taking:

x <- t(table(df[,1:2])) %*% table(df[,1:2])

x / diag(x)

Body:
I love it when I can use linear algebra for something.

t(table(df[,1:2])) %*% table(df[,1:2])
   y
y   A B C
  A 3 1 1
  B 1 2 1
  C 1 1 2

Edit: As noted by @thelatemail, there is a built in (potentially faster) function as well:

crossprod(table(df$x, df$y))

    A B C
  A 3 1 1
  B 1 2 1
  C 1 1 2


问:
pageload() not being called after postback
My div "attachements" is not refreshing after a post back and pageLoad() is not being called

```<code>    <div id ="attachments">
<asp:UpdatePanel ID="updtPnlAttachements" runat ="server"  >

    <ContentTemplate>
         <asp:GridView ID="gvAttachments" runat="server"  ClientIDMode = "Static"   Width ="100%">
           <Columns>

           </Columns>
           <EmptyDataTemplate>
           <div> Sorry Empty</div>
           </EmptyDataTemplate>
         </asp:GridView>

     </ContentTemplate>

</asp:UpdatePanel>
</code>```

After making this button call

```<code> public void ReportLinkButton_Click(object sender, EventArgs e)
{

  LinkButton Lbtn = (LinkButton)sender;
  string assessmentString = Lbtn.CommandArgument;
  Guid assessmentID = new Guid(assessmentString);

  DR_Data db = new DR_Data();
  var reports = db.GetAttachmentsByAssessmentID(assessmentID).ToList();

  gvAttachments.DataSource = reports;
  gvAttachments.DataBind();

  if (reports.Count() > 0)
  {
      gvAttachments.HeaderRow.TableSection = TableRowSection.TableHeader;
      gvAttachments.FooterRow.TableSection = TableRowSection.TableFooter;
  }

}
</code>```

My script looks like this

```<code>       function pageLoad() {var totalRows = $("#<%=gvAttachments.ClientID %> tr").length;

    if (totalRows > 0) {

        $("#dialog:ui-dialog").dialog("destroy");

        $("#attachments").dialog({
            hide: "fold",
            show: "blind",
            height: 500,
            width: 800,
            modal: true
        });
    }

    $('#gvNcReports').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers"
    });
}`
</code>```

any suggestions. Thanks

*UPDATE**

I had multiple update panels, once I removed them it worked.

答:
II ended up adding this to Page_Load and it works

```<code> string script = @"<script>
                   function pageLoad() {
                    $('#gvNcReports').dataTable({
                      "bJQueryUI": true,
                      "bPaginate": false
                            });
                   $("#dialog:ui-dialog").dialog("destroy");
                   $("#updtPnlAttachements").dialog({
                    hide: "fold",
                    show: "blind",
                    height: 500,
                    width: 800,
                    modal: true
                   });
                }
                });</script>";

 Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"hover",script);
</code>```

However I still have to add $(document).ready and the same script in the header to make sure everything works when it initially renders, is this bad practice?

Body:
My div "attachements" is not refreshing after a post back and pageLoad() is not being called

<asp:UpdatePanel ID="updtPnlAttachements" runat ="server"  >

    <ContentTemplate>
         <asp:GridView ID="gvAttachments" runat="server"  ClientIDMode = "Static"   Width ="100%">
           <Columns>

           </Columns>
           <EmptyDataTemplate>

 Sorry Empty

           </EmptyDataTemplate>
         </asp:GridView>

     </ContentTemplate>

</asp:UpdatePanel>

After making this button call

 public void ReportLinkButton_Click(object sender, EventArgs e)
{

  LinkButton Lbtn = (LinkButton)sender;
  string assessmentString = Lbtn.CommandArgument;
  Guid assessmentID = new Guid(assessmentString);

  DR_Data db = new DR_Data();
  var reports = db.GetAttachmentsByAssessmentID(assessmentID).ToList();

  gvAttachments.DataSource = reports;
  gvAttachments.DataBind();

  if (reports.Count() > 0)
  {
      gvAttachments.HeaderRow.TableSection = TableRowSection.TableHeader;
      gvAttachments.FooterRow.TableSection = TableRowSection.TableFooter;
  }

}

My script looks like this

       function pageLoad() {var totalRows = $("#<%=gvAttachments.ClientID %> tr").length;

    if (totalRows > 0) {

        $("#dialog:ui-dialog").dialog("destroy");

        $("#attachments").dialog({
            hide: "fold",
            show: "blind",
            height: 500,
            width: 800,
            modal: true
        });
    }

    $('#gvNcReports').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers"
    });
}`

any suggestions. Thanks

*UPDATE**

I had multiple update panels, once I removed them it worked.

Body:
II ended up adding this to Page_Load and it works

 string script = @"<script>
                   function pageLoad() {
                    $('#gvNcReports').dataTable({
                      "bJQueryUI": true,
                      "bPaginate": false
                            });
                   $("#dialog:ui-dialog").dialog("destroy");
                   $("#updtPnlAttachements").dialog({
                    hide: "fold",
                    show: "blind",
                    height: 500,
                    width: 800,
                    modal: true
                   });
                }
                });</script>";

 Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"hover",script);

However I still have to add $(document).ready and the same script in the header to make sure everything works when it initially renders, is this bad practice?


答:
Update the code to include both scenarios.

div > *:first-child:not(Button) ~ div.div3 {
  background: skyblue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <Button class="button"> Show Button </Button>
  <div class="div1"> Show Button div1 </div>
  <div class="div2"> Show Button div2 </div>
  <div class="div3"> Show Button div3 </div>
</div>

<div>
  <div class="div1"> div1 </div>
  <div class="div2"> div2 </div>
  <div class="div3"> div3 </div>
</div></code>```

Title: CSS selector when no sibling of certain type is present

Body:
Update the code to include both scenarios.

div > *:first-child:not(Button) ~ div.div3 {
  background: skyblue;
}

<div>
  <Button class="button"> Show Button </Button>
  <div class="div1"> Show Button div1 </div>
  <div class="div2"> Show Button div2 </div>
  <div class="div3"> Show Button div3 </div>
</div>

<div>
  <div class="div1"> div1 </div>
  <div class="div2"> div2 </div>
  <div class="div3"> div3 </div>
</div>


问:
How to connect to 3rd party snowflake database using django?
How to create an engine to connect the snowflake db? On Configuring the

settings.py

, it errors out with below message.

Try using 'django.db.backends.XXX', where XXX is one of:
      'mysql', 'oracle', 'postgresql', 'sqlite3'

答:
Django officially supports these databases:

PostgreSQL

MariaDB

MySQL

Oracle

SQLite

And also these 3rd party databases:

CockroachDB

Firebird

IBM DB2

Microsoft SQL Server

ODBC

Since snowflakedb isn't in either of the two and you want to create an engine, I suggest creating your own custom database engine using pyodbc.
django custom database engine documentation


答:
You can use :not()

div:not(button) > div{
  background-color:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div> has-button
  <Button class="button"/>
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div>

<div> no-button
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div></code>```

Body:
You can use :not()

div:not(button) > div{
  background-color:red;
}

<div> has-button
  <Button class="button"/>
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div>

<div> no-button
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div>


问:
Risks involved with publicly accessible AWS RDS databases
I've come across multiple guidelines stating that AWS RDS instances should not be configured to be publicly accessible, because it is a major security risk. Example:RDS Publicly Accessible - RDS best practice

If the RDS instance is configured with a sufficiently strong and unique password which is practically impossible to brute-force, is it still a security risk? Wouldn't a strong and unique password make the instance reasonably safe, even if it is publicly accessible?

答:
It is a significant risk due to other aspect involved

Normally, how many time you change the DB password? I suspect not a lot

How easy it is to change the DB password? Shall it impact the running applications?

Do you properly restrict access to DB to a handful IPs ( which would limit the access surface to around the same level as a private subnet do ) - or you will just let any IP access? If that's the case, once the password is leaked, you have no protection

Do you / your customer value the data? Most of the time, databases are highly valued property which need adequate protection


答:
I think rather than attempting to store the book codes as a string, a better way to model the table would be to break the book_code string into individual rows.

This would help in searching the data and future extensibility of the data model.

Title: Unable to store complete json field in mysql table field

Body:
I am getting a large json data in a api response. I am trying to store this json response in local mysql table. But unable to store complete json response. Please find the below json info.

Sample API json response :

{
    "responseCode": 200,
    "date": "2020-06-03",
    "message": "Success",
    "couponDetails": {
        "total": 14949,
        "codes": "35033769,35441136,35803675,34407176,34717909,34950692,35059148,35452352,35688911,35904465,35904658,35904753,35904824,35904942,35905306,35905318,35905434,35905673,35906615,35907029,35907154,35907222,35907345,35907592,35907683,35907951,35908161,35908194,35908206,34664348,34664436,34665057,34665072,34665768,34665950,34666051,34666110,34666879,34667228,34668101,34670133,34670162,34670259,34670661,34670687,34670994,34671179,34671296,34672207,34672276,34672631,34672747,34673619,34673709,34675355,34676588,34677690,34678019,34679260,34679468,34680550,34680694,34680838,34683321,34684752,34684796,34685198,34685826,34686220,34686276,34351922,34352193,34352369,34352553,34353629,34353971,34355064,34355541,34355625,34356802,34357668,34357869,34357922,34360451,34360500,34360764,34361049,34361174,34361315,34362337,34362412,34363370,34364187,34365025,34365188,34365415,34365904,34366777,34366877,34367361,34368025,34368078,35542974,35543013,35543084,35268238,35268397,35268774,35269689,35269933,35270038,35250597,35063719,35064231,35064237,35270577,35270705,35270969,35064514,35064963,35065129,35251645,35251660,35251798,35253022,35253300,35272389,35272446,35272519,35272640,35272641,35273596,35273716,35423127,35423184,35423372,35424244,35425607,35485524,35486647,35486711,35486970,35487111,35470199,35470485,35488099,35488145,35488270,35490204,35534378,35535484,35535520,35535559,35535601,35535818,21979363,21508096,26237385,24734847,22263784,26889428,29292212,20415646,21836743,20300178,21831783,21198543,23739734,29773862,20715551,25488915,28894112,26536357,26695866,27133857,29133336,28763373,21850298,21990790,27757421,2421785723"
    }
}

In my local DB table I am able to insert the below information only, which is not complete :

{
    "responseCode": 200,
    "date": "2020-06-03",
    "message": "Success",
    "couponDetails": {
        "total": 14949,
        "codes": "35033769,35441136,35803675,34407176,34717909,34950692,35059148,35452352,35688911,35904465,35904658,35904753,35904824,35904942,35905306,

Mysql Table Structure :

CREATE TABLE `bookdata_codeinfo_history` (
  `generated_date` date DEFAULT NULL,
  `book_code` longtext,
  `service` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I want to store json in 'book_code' field but only few information is storing. I am using mysql-5.7.13 version.
Please tell me how to resolve this issue


问:
How to update MirrorMaker 2 topics whitelist?
I run MirrorMaker2 with the high-level driver, as documented here, with ./bin/connect-mirror-maker.sh mm2.properties running in 3 pods in a k8s deployment.

The mm2.properties file looks like this:

```<code>clusters = source, dest

source.bootstrap.servers = ***:9092
dest.bootstrap.servers =  ***:9092

source->dest.enabled = true
dest->source.enabled = false

source->dest.topics = event\.PROD\.some_id.*

replication.factor=3

checkpoints.topic.replication.factor=3
heartbeats.topic.replication.factor=3
offset-syncs.topic.replication.factor=3

offset.storage.replication.factor=3
status.storage.replication.factor=3
config.storage.replication.factor=3

sync.topic.acls.enabled = false
</code>```

This works fine, with all topics matching the event\.PROD\.some_id.* regex being replicated.
Now, when I need to add other topic the whitelisting, I expected to be able to simply scale everything down, update the regex, and scale everything up again.

When I update the whitelist regex to source->dest.topics = event\.PROD\.(some_id|another_id).* , the topics matching "another_id" are created in the dest cluster, but no data is replicated, and mirrormaker seems to be lost commiting offsets:

```<code>[2020-05-28 20:33:19,496] INFO WorkerSourceTask{id=MirrorHeartbeatConnector-0} Committing offsets (org.apache.kafka.connect.runtime.WorkerSourceTask:424)
[2020-05-28 20:33:19,496] INFO WorkerSourceTask{id=MirrorHeartbeatConnector-0} flushing 0 outstanding messages for offset commit (org.apache.kafka.connect.runtime.WorkerSourceTask:441)
[2020-05-28 20:33:19,499] INFO WorkerSourceTask{id=MirrorHeartbeatConnector-0} Finished commitOffsets successfully in 3 ms (org.apache.kafka.connect.runtime.WorkerSourceTask:523)
</code>```

Is this a limitation of the high level driver, or am I doing something wrong? From my understanding, being able to dynamically add topics to the whitelist was one of the motivations for MM2.

答:
I am playing with mmv2 as well. Can you try setting these configurations? I had to enable the sync.topic.configs.enabled parameter so my mmv2 would detect the new topics and their data.

refresh.topics.enabled = true
sync.topic.configs.enabled = true
refresh.topics.interval.seconds = 10
```

Pd.- I am adding my reply as an answer because I wanted to paste come configs.

Body:
I run MirrorMaker2 with the high-level driver, as documented here, with ./bin/connect-mirror-maker.sh mm2.properties running in 3 pods in a k8s deployment.

The mm2.properties file looks like this:

clusters = source, dest

source.bootstrap.servers = ***:9092
dest.bootstrap.servers =  ***:9092

source->dest.enabled = true
dest->source.enabled = false

source->dest.topics = event\.PROD\.some_id.*

replication.factor=3

checkpoints.topic.replication.factor=3
heartbeats.topic.replication.factor=3
offset-syncs.topic.replication.factor=3

offset.storage.replication.factor=3
status.storage.replication.factor=3
config.storage.replication.factor=3

sync.topic.acls.enabled = false

This works fine, with all topics matching the event\.PROD\.some_id.* regex being replicated.
Now, when I need to add other topic the whitelisting, I expected to be able to simply scale everything down, update the regex, and scale everything up again.

When I update the whitelist regex to source->dest.topics = event\.PROD\.(some_id|another_id).* , the topics matching "another_id" are created in the dest cluster, but no data is replicated, and mirrormaker seems to be lost commiting offsets:

[2020-05-28 20:33:19,496] INFO WorkerSourceTask{id=MirrorHeartbeatConnector-0} Committing offsets (org.apache.kafka.connect.runtime.WorkerSourceTask:424)
[2020-05-28 20:33:19,496] INFO WorkerSourceTask{id=MirrorHeartbeatConnector-0} flushing 0 outstanding messages for offset commit (org.apache.kafka.connect.runtime.WorkerSourceTask:441)
[2020-05-28 20:33:19,499] INFO WorkerSourceTask{id=MirrorHeartbeatConnector-0} Finished commitOffsets successfully in 3 ms (org.apache.kafka.connect.runtime.WorkerSourceTask:523)

Is this a limitation of the high level driver, or am I doing something wrong? From my understanding, being able to dynamically add topics to the whitelist was one of the motivations for MM2.

Body:
I am playing with mmv2 as well. Can you try setting these configurations? I had to enable the sync.topic.configs.enabled parameter so my mmv2 would detect the new topics and their data.

refresh.topics.enabled = true
sync.topic.configs.enabled = true
refresh.topics.interval.seconds = 10

Pd.- I am adding my reply as an answer because I wanted to paste come configs.


问:
how to sleep in one function without sleeping the whole program
So I am trying to make a game, in this game I call upon a function that I want to slowly execute, but when I use "time.sleep(x)" it pauses everything in the file instead of just pausing the process of the function. I am trying to add a jump feature to a 2-d game, so if there is a better way to do it then I would be grateful for any advice but this is just the first idea that game to me.

```<code>for n in range(15):
    Dino.rect.bottom -= 5
    update_screen(Dino, screen, cactus)
    time.sleep(0.01)
time.sleep(0.25)
inair = False
for n in range(15):
    Dino.rect.bottom += 5
    update_screen(Dino, screen, cactus)
    time.sleep(0.01)
</code>```

so I have it so that when I jump, it gives me a slow jump instead of just teleporting but like I said, it pauses everything while jumping.

答:
This is not a good approach to timing.  As you say, this sleeps the entire program.  Multi-threading is a bit complex for simply moving a sprite.

A simple way to solve this problem is to use the PyGame function time.get_ticks() which returns an ever-increasing time in milliseconds.

Using this time-stamp, record the previous-time of an operation, but then do not update again until enough time has elapsed.

For example:

```<code>DINO_UPDATE_DELAY = 100   # milliseconds

next_dino_update = 0     # time next move due

[...]

# Move dino, if necessary
time_now = pygame.time.get_ticks()
if ( time_now > next_dino_update ):
    Dino.rect.bottom += 5
    next_dino_update = time_now + DINO_UPDATE_DELAY   # in the future

# Paint the dino, wherever it is
update_screen(Dino, screen, cactus)
</code>```

It's also possible to request a timer to send the event-loop a message in the future.

```<code>MOVE_DINO_EVENT = pygame.USEREVENT + 1

[...]

pygame.time.set_timer( MOVE_DINO_EVENT, DINO_UPDATE_DELAY )
</code>```

EDIT:  More in-depth explanation.

So basically you're implementing an animation, like an anime/cartoon.  The thing on the display moves at some speed.  In the above code, you seem to be moving a "dino" in the direction of y + 5 every 0.01 seconds (10 milliseconds).

Right now, you paint the dino, then sleep(), then move & paint again.  When it hits the apogee of the jump, you wait 250 milliseconds, then repeat the previous phase for the down-jump.

So the problem with using sleep() is that it holds up the whole program (including the event loop, which can cause bad stuff to happen).

So instead of sleeping for some time period, the above example simply looks at the PyGame clock to determine if that same time-period has past.  This allows the program to know if the animation needs to be updated.

The whole idea is to keep looking at the clock, using the time as the arbiter of what/where to draw next, rather than multiple calls to sleep().

Body:
So I am trying to make a game, in this game I call upon a function that I want to slowly execute, but when I use "time.sleep(x)" it pauses everything in the file instead of just pausing the process of the function. I am trying to add a jump feature to a 2-d game, so if there is a better way to do it then I would be grateful for any advice but this is just the first idea that game to me.

for n in range(15):
    Dino.rect.bottom -= 5
    update_screen(Dino, screen, cactus)
    time.sleep(0.01)
time.sleep(0.25)
inair = False
for n in range(15):
    Dino.rect.bottom += 5
    update_screen(Dino, screen, cactus)
    time.sleep(0.01)

so I have it so that when I jump, it gives me a slow jump instead of just teleporting but like I said, it pauses everything while jumping.

Body:
This is not a good approach to timing.  As you say, this sleeps the entire program.  Multi-threading is a bit complex for simply moving a sprite.

A simple way to solve this problem is to use the PyGame function time.get_ticks() which returns an ever-increasing time in milliseconds.

Using this time-stamp, record the previous-time of an operation, but then do not update again until enough time has elapsed.

For example:

DINO_UPDATE_DELAY = 100   # milliseconds

next_dino_update = 0     # time next move due

[...]

# Move dino, if necessary
time_now = pygame.time.get_ticks()
if ( time_now > next_dino_update ):
    Dino.rect.bottom += 5
    next_dino_update = time_now + DINO_UPDATE_DELAY   # in the future

# Paint the dino, wherever it is
update_screen(Dino, screen, cactus)

It's also possible to request a timer to send the event-loop a message in the future.

MOVE_DINO_EVENT = pygame.USEREVENT + 1

[...]

pygame.time.set_timer( MOVE_DINO_EVENT, DINO_UPDATE_DELAY )

EDIT:  More in-depth explanation.

So basically you're implementing an animation, like an anime/cartoon.  The thing on the display moves at some speed.  In the above code, you seem to be moving a "dino" in the direction of y + 5 every 0.01 seconds (10 milliseconds).

Right now, you paint the dino, then sleep(), then move & paint again.  When it hits the apogee of the jump, you wait 250 milliseconds, then repeat the previous phase for the down-jump.

So the problem with using sleep() is that it holds up the whole program (including the event loop, which can cause bad stuff to happen).

So instead of sleeping for some time period, the above example simply looks at the PyGame clock to determine if that same time-period has past.  This allows the program to know if the animation needs to be updated.

The whole idea is to keep looking at the clock, using the time as the arbiter of what/where to draw next, rather than multiple calls to sleep().


问:
angular (version 8) pass async @input value to fetch another call
I have a parent component that has a button when the user clicks it will make a request and passed the data into a child component (a ngx-bootstrap modal). The child component will use the async data to make another request to render its UI.

My parent component is like this:

```<code><Parent>
<child-modal [subSectionInfo]="subSectionInfo"></child-modal>
</Parent>
</code>```

the subSectionInfo is async data retrieved from an ajax in Parent component.

My child component will make call like this:

```<code>  ngOnInit() {
   const id = this.subSectionInfo.id;
   this._fetchData(id)
  }

   private _fetchData(id: number) {
     this.service
     .getData(id).pipe(
     .subscribe((data: any) => {
      this.list = data;
   });
  }
</code>```

However, this always gives me undefined which causes the child component ajax call failed. Is any way to solve this issue? Thank you so much in advance!

答:
Currently, your code does not wait on the first request to complete. While the request for subSectionInfo is being made in the parent component, it's value is undefined since the value hasn't returned from the server yet. This is why the child component get's undefined. There are 2 ways to approach this.

In your parent component, you can wait until the data is loaded and then pass in subSectionInfo to your child component.

In your child component, you can make use of the ngOnChanges life-cycle hook. This is where your child component implements OnChanges. You can read more about it here.

```<code> ngOnChanges(changes: SimpleChanges) {
   if (changes['subSectionInfo'].currentValue !== undefined) {
      const id = this.subSectionInfo.id;
      this._fetchData(id)
   }

 }

  private _fetchData(id: number) {
    this.service
      .getData(id).pipe(
      .subscribe((data: any) => {
        this.list = data;
    });
  }
</code>```

Hope this helps

Body:
I have a parent component that has a button when the user clicks it will make a request and passed the data into a child component (a ngx-bootstrap modal). The child component will use the async data to make another request to render its UI.

My parent component is like this:

<Parent>
<child-modal [subSectionInfo]="subSectionInfo"></child-modal>
</Parent>

the subSectionInfo is async data retrieved from an ajax in Parent component.

My child component will make call like this:

  ngOnInit() {
   const id = this.subSectionInfo.id;
   this._fetchData(id)
  }

   private _fetchData(id: number) {
     this.service
     .getData(id).pipe(
     .subscribe((data: any) => {
      this.list = data;
   });
  }

However, this always gives me undefined which causes the child component ajax call failed. Is any way to solve this issue? Thank you so much in advance!

Body:
Currently, your code does not wait on the first request to complete. While the request for subSectionInfo is being made in the parent component, it's value is undefined since the value hasn't returned from the server yet. This is why the child component get's undefined. There are 2 ways to approach this.

In your parent component, you can wait until the data is loaded and then pass in subSectionInfo to your child component.

In your child component, you can make use of the ngOnChanges life-cycle hook. This is where your child component implements OnChanges. You can read more about it here.

 ngOnChanges(changes: SimpleChanges) {
   if (changes['subSectionInfo'].currentValue !== undefined) {
      const id = this.subSectionInfo.id;
      this._fetchData(id)
   }

 }

  private _fetchData(id: number) {
    this.service
      .getData(id).pipe(
      .subscribe((data: any) => {
        this.list = data;
    });
  }

Hope this helps


答:
Add the onKeyPress handler and check if Enter key is pressed.
Use Event.preventDefault().

const { useRef, useEffect } = React;

const App = (props) => {
  const ref = useRef();

  // set focus to button for testing
  useEffect(() => ref.current.focus(), []);

  const print = msg => console.log(msg);

  const handleClick = e => print('Printing...');

  const handleKeyPress = e => {
    if (e.key === 'Enter') {
      e.preventDefault();
      return;
    }
  }

  return (

      <button
        ref={ref}
        onKeyPress={handleKeyPress}
        onClick={handleClick}
      >
        Print
      </button>

  );
};

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div></code>```

Title: Pressing enter clicks button again

Body:
I have this button that I click to print a document. but the issues is it stays in focus I think and if I press enter key by mistake it prints it again {basically the button is getting pressed again on enter key. I am already using e.preventDefault() so I don't know why it is doing it. Is it possible to remopve this behaviour?

Basically I only want handleOrderPrint() to run on click and not when Enter key is pressed.

<Button onClick={e => handleOrderPrint(e)} type="primary">Print</Button>}

 const handleOrderPrint = (e: any) => {
    e.preventDefault();
    ipcRenderer.send('generatePickingDocs', order);
    setPrinted(true);
  };

Edit---------------->
Already tried this:

const btnEl = React.useRef(null);
  const handleOrderPrint = (e: any) => {
    e.preventDefault();
    if (e.keyCode !== 13) {
      console.log("Keycode", e.keyCode);
      ipcRenderer.send('generatePickingDocs', order);
      setPrinted(true);
    }
  };

<Button ref={btnEl} onClick={e => handleOrderPrint(e)} type="primary">Print</Button>

Body:
Add the onKeyPress handler and check if Enter key is pressed.
Use Event.preventDefault().

const { useRef, useEffect } = React;

const App = (props) => {
  const ref = useRef();

  // set focus to button for testing
  useEffect(() => ref.current.focus(), []);

  const print = msg => console.log(msg);

  const handleClick = e => print('Printing...');

  const handleKeyPress = e => {
    if (e.key === 'Enter') {
      e.preventDefault();
      return;
    }
  }

  return (
    <div>
      <button
        ref={ref}
        onKeyPress={handleKeyPress}
        onClick={handleClick}
      >
        Print
      </button>
    </div>
  );
};

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>


问:
Embed logo into email
I'm wondering how can I embed a logo into email. The logo is saved on Google Drive. Also, I know the reference inlineimage and blob need to be used but I don't know how.

I tried this code, but no success

var Img = DriveApp.getFileById(1pRBZ....cKMFll1OouC..er2V97e8...).getBlob();

The line below retreive the message template. So, I want to include the image into the message as a signature.

var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();

```<code>function EnvoiIDCourriel() {

  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Liste").activate();
  var SS = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var LR = SS.getLastRow()

  var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
  //Permet d'utiliser le corps du courriel qui se trouve dans l'onglet Template

  //Logger.log(NomCandidat);

  //Cette ligne permet de passer à travers de toutes les lignes inscrites
  var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
  values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
    if (check === true) {
       var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
       var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
  }
});

}
</code>```

答:
To send an image from your Google Drive in an email:

1. Make the image file as sharing to "Anyone with the link"

2. Copy the image ID from the shared link

3. In your application which is sending the email retrieve this image as a blob

```<code>var imageBlob = DriveApp
                  .getFileById(imageID)
                  .getBlob()
                  .setName("Logo");
</code>```

To include the image in your email, you need to compose your email using html tags.
Declare a variable to hold the html script.

```<code>var html = ""
</code>```

The above variable will be used to hold the contents of your entire email, using html tags to preserve formatting.

If html tags are not included, the email may not be displayed correctly across devices. There may be mislaignment of paragraphs, tables, images may not be displayed, etc.

```<code>html = '<body>' +
html = html + '<p style="color:grey; font-family: Palatino, Times, serif; font-size: 16px;font-style: italic;">';
html = html + CorpsMessage + '</p>';
html = html + '<div align=' + imageAlignment +'><img src="cid:image" width=' + imageWidth + '%height='+ imageHeight + '% align=' + imageAlignment +'></div><br><br></body>';
</code>```

You then send your email using GmailApp.sendEmail or MailApp.sendEmail:

```<code>try{
  MailApp.sendEmail(emailAddress, subject, '',{
  cc: emailCc,
  bcc: emailBcc,
  htmlBody: html,
  inlineImages:{image: imageBlob}});
  sheet.getRange("G28").setFontColor("#228B22");
  sheet.getRange("G28").setValue("Latest update: Mail sent @" + new Date());
    }catch(e){
      sheet.getRange("G28").setFontColor("#FF0000")
      sheet.getRange("G28").setValue("Alert! Error: " + "  " + new Date() + "  " + e.message)
  }
</code>```

Always enclose sendEmail method in a try/catch block, if for any reason there is an error even in 1 message, all messages following the error message will not be sent. This is irrespective of the email being in simple text format or in html format.

Enclosing a try/catch block prevents sending only erroneous messages. Correct messages only will be sent.

Title: Embed logo into email

Body:
I'm wondering how can I embed a logo into email. The logo is saved on Google Drive. Also, I know the reference inlineimage and blob need to be used but I don't know how.

I tried this code, but no success

var Img = DriveApp.getFileById(1pRBZ....cKMFll1OouC..er2V97e8...).getBlob();

The line below retreive the message template. So, I want to include the image into the message as a signature.

var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();

function EnvoiIDCourriel() {

  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Liste").activate();
  var SS = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var LR = SS.getLastRow()

  var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
  //Permet d'utiliser le corps du courriel qui se trouve dans l'onglet Template

  //Logger.log(NomCandidat);

  //Cette ligne permet de passer à travers de toutes les lignes inscrites
  var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
  values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
    if (check === true) {
       var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
       var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
  }
});

}

Body:
To send an image from your Google Drive in an email:

1. Make the image file as sharing to "Anyone with the link"

2. Copy the image ID from the shared link

3. In your application which is sending the email retrieve this image as a blob

var imageBlob = DriveApp
                  .getFileById(imageID)
                  .getBlob()
                  .setName("Logo");

To include the image in your email, you need to compose your email using html tags.
Declare a variable to hold the html script.

var html = ""

The above variable will be used to hold the contents of your entire email, using html tags to preserve formatting.

If html tags are not included, the email may not be displayed correctly across devices. There may be mislaignment of paragraphs, tables, images may not be displayed, etc.

html = '<body>' +
html = html + '<p style="color:grey; font-family: Palatino, Times, serif; font-size: 16px;font-style: italic;">';
html = html + CorpsMessage + '</p>';
html = html + '<div align=' + imageAlignment +'><img src="cid:image" width=' + imageWidth + '%height='+ imageHeight + '% align=' + imageAlignment +'></div><br><br></body>';

You then send your email using GmailApp.sendEmail or MailApp.sendEmail:

try{
  MailApp.sendEmail(emailAddress, subject, '',{
  cc: emailCc,
  bcc: emailBcc,
  htmlBody: html,
  inlineImages:{image: imageBlob}});
  sheet.getRange("G28").setFontColor("#228B22");
  sheet.getRange("G28").setValue("Latest update: Mail sent @" + new Date());
    }catch(e){
      sheet.getRange("G28").setFontColor("#FF0000")
      sheet.getRange("G28").setValue("Alert! Error: " + "  " + new Date() + "  " + e.message)
  }

Always enclose sendEmail method in a try/catch block, if for any reason there is an error even in 1 message, all messages following the error message will not be sent. This is irrespective of the email being in simple text format or in html format.

Enclosing a try/catch block prevents sending only erroneous messages. Correct messages only will be sent.


问:
Default value on insert PHP and SQL
I want to make that when someone inserts a post into my database that if they don't supply their name it defaults to anonymous. How would I do this?
My code here

$query =  "INSERT INTO cinemaPost (name, text, likes, reply_to) VALUES (?, ?, 0, NULL)";

$stmt = $conn->prepare($query);
$stmt->bindValue(1, $post_data['name']);
$stmt->bindValue(2, $post_data['post']);

$stmt->execute();
```

<p>I have tried doing a default in the create tables for the db but when the user triggers the insert it overides it as a blank field.</p>

<pre class="lang-sql prettyprint-override"><code>CREATE TABLE CinemaPost(
  id INT AUTO_INCREMENT NOT NULL,
  name varchar(255) NOT NULL DEFAULT 'anonymous',
  text varchar(100) NOT NULL,
  post_date timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
  likes INT NOT NULL,
  reply_to INT,
  Primary KEY (id)
);
</code>```

答:
The default value will only be used if you don't actually insert to the column i.e. you would need to remove name from the INSERT column list. For example:

```<code>if (empty($post_data['name'])) {
    $query =  "INSERT INTO cinemaPost (text, likes, reply_to) VALUES (?, 0, NULL)";
    $stmt = $conn->prepare($query);
    $stmt->bindValue(1, $post_data['post']);
}
else {
    $query =  "INSERT INTO cinemaPost (name, text, likes, reply_to) VALUES (?, ?, 0, NULL)";
    $stmt = $conn->prepare($query);
    $stmt->bindValue(1, $post_data['name']);
    $stmt->bindValue(2, $post_data['post']);
}
</code>```

It's probably simplest just to check the input value and replace it with "anonymous" if it's empty instead:

```<code>$stmt->bindValue(1, empty($post_data['name']) ? 'anonymous' : $post_data['name']);
</code>```

Title: Default value on insert PHP and SQL

Body:
I want to make that when someone inserts a post into my database that if they don't supply their name it defaults to anonymous. How would I do this?
My code here

$query =  "INSERT INTO cinemaPost (name, text, likes, reply_to) VALUES (?, ?, 0, NULL)";

$stmt = $conn->prepare($query);
$stmt->bindValue(1, $post_data['name']);
$stmt->bindValue(2, $post_data['post']);

$stmt->execute();

I have tried doing a default in the create tables for the db but when the user triggers the insert it overides it as a blank field.

CREATE TABLE CinemaPost(
  id INT AUTO_INCREMENT NOT NULL,
  name varchar(255) NOT NULL DEFAULT 'anonymous',
  text varchar(100) NOT NULL,
  post_date timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
  likes INT NOT NULL,
  reply_to INT,
  Primary KEY (id)
);

Body:
The default value will only be used if you don't actually insert to the column i.e. you would need to remove name from the INSERT column list. For example:

if (empty($post_data['name'])) {
    $query =  "INSERT INTO cinemaPost (text, likes, reply_to) VALUES (?, 0, NULL)";
    $stmt = $conn->prepare($query);
    $stmt->bindValue(1, $post_data['post']);
}
else {
    $query =  "INSERT INTO cinemaPost (name, text, likes, reply_to) VALUES (?, ?, 0, NULL)";
    $stmt = $conn->prepare($query);
    $stmt->bindValue(1, $post_data['name']);
    $stmt->bindValue(2, $post_data['post']);
}

It's probably simplest just to check the input value and replace it with "anonymous" if it's empty instead:

$stmt->bindValue(1, empty($post_data['name']) ? 'anonymous' : $post_data['name']);


问:
Check if User input correct ipv4 format
My first time here, i have a question please:

i want to check if user type on input an ipv4 if it's not ipv4 user should receive error 3 times and then exit. My example code below:

```<code>    # Hosts and Commands
    for attempt in range(3):
        host = input("Enter IPs separated by SPACE: ")
        cmd = input("Enter Command(s) seperated by ',' : ")
        if(len(host) != 0) and (len(cmd) != 0):
            break
        print("Fields Cannot be Blank, try again...")
    else:
        Screen().input("Sorry...Execution Terminated, Press [ENTER] to Exit")
        return
</code>```

答: Thank you inspectorG4dget! It worked fine if i add only one IP in the array, if i type more than 1 separated by space to be captured later in an array it doesn't work. The idea is to receive as many ip as user desire to consult but the user cannot type non valid ipv4.</p>

Title: Check if User input correct ipv4 format

Body:
My first time here, i have a question please:

i want to check if user type on input an ipv4 if it's not ipv4 user should receive error 3 times and then exit. My example code below:

    # Hosts and Commands
    for attempt in range(3):
        host = input("Enter IPs separated by SPACE: ")
        cmd = input("Enter Command(s) seperated by ',' : ")
        if(len(host) != 0) and (len(cmd) != 0):
            break
        print("Fields Cannot be Blank, try again...")
    else:
        Screen().input("Sorry...Execution Terminated, Press [ENTER] to Exit")
        return