答:
Here is how I would do it. I tried adding as many comments as I could to explain why I did some things. There are some in the HTML, the CSS, and the JS code. Feel free to ask any question.

// When the DOM (HTML structure) is ready
document.addEventListener("DOMContentLoaded", function() {
  // First, we can create references to DOM elements on page start,
  // which we'll reuse instead of looking them up every time we perform a search.
  // As a convention, I like variables holding DOM elements to start with $,
  // so that I know what I'm dealing with in the blink of an eye
  var $input = document.getElementById("myInput"),
      $table = document.getElementById("myTable"),
      // Only select the
s inside the
 (double $ -> multiple elements)
      $$tr   = $table.querySelectorAll("tbody tr");

  // Add the normalized name as a property to each tr, so that you don't have
  // to compute that every time when performing a search
  for (var i = 0; i < $$tr.length; i++) {
    $$tr[i].normalizedValue = normalizeStr( $$tr[i].querySelector("td").innerText );
  }
  // When typing or pasting text, perform a search
  $input.addEventListener("input", performSearch);

  function performSearch() {
    var filter = normalizeStr(this.value);
    for (var i = 0; i < $$tr.length; i++) {
      var isMatch = $$tr[i].normalizedValue.includes(filter);
      // Toggle a 'visible' class
      $$tr[i].classList[isMatch ? "add" : "remove"]("visible");
    }
  }

  // Creating a reusable function will allow us to make
  // changes to it only in one place
  function normalizeStr(str) {
    return str.toUpperCase().trim();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* ... untouched CSS ... */ *{box-sizing:border-box}#myInput{background-image:url(/css/searchicon.png);background-position:10px 10px;background-repeat:no-repeat;width:100%;font-size:16px;padding:12px 20px 12px 40px;border:1px solid #ddd;margin-bottom:12px}#myTable{border-collapse:collapse;width:100%;border:1px solid #ddd;font-size:18px}#myTable td,#myTable th{text-align:left;padding:12px}#myTable tr{border-bottom:1px solid #ddd}

#myTable thead tr, /* notice the use of thead */
#myTable tr:hover {
  background-color: #f1f1f1;
}

#myTable tbody tr {
  display: none; /* Hide rows by default */
}

#myTable tbody tr.visible {
  display: table-row; /* Show them when they match */
}</code>```

My Customers

<input type="text" id="myInput" placeholder="Search for names" title="Type in a name" />

      Name
      Country

 Alfreds Futterkiste	 Germany

 Berglunds snabbkop	 Sweden

 Island Trading	 UK

 Koniglich Essen	 Germany

 Laughing Bacchus Winecellars	 Canada

 Magazzini Alimentari Riuniti	 Italy

 North/South	 UK

 Paris specialites	 France

```

Title: How to hide the all the content until the user searches for a specific item in this table?

Body:
Here is how I would do it. I tried adding as many comments as I could to explain why I did some things. There are some in the HTML, the CSS, and the JS code. Feel free to ask any question.

// When the DOM (HTML structure) is ready
document.addEventListener("DOMContentLoaded", function() {
  // First, we can create references to DOM elements on page start,
  // which we'll reuse instead of looking them up every time we perform a search.
  // As a convention, I like variables holding DOM elements to start with $,
  // so that I know what I'm dealing with in the blink of an eye
  var $input = document.getElementById("myInput"),
      $table = document.getElementById("myTable"),
      // Only select the <tr>s inside the <tbody> (double $ -> multiple elements)
      $$tr   = $table.querySelectorAll("tbody tr");

  // Add the normalized name as a property to each tr, so that you don't have
  // to compute that every time when performing a search
  for (var i = 0; i < $$tr.length; i++) {
    $$tr[i].normalizedValue = normalizeStr( $$tr[i].querySelector("td").innerText );
  }
  // When typing or pasting text, perform a search
  $input.addEventListener("input", performSearch);

  function performSearch() {
    var filter = normalizeStr(this.value);
    for (var i = 0; i < $$tr.length; i++) {
      var isMatch = $$tr[i].normalizedValue.includes(filter);
      // Toggle a 'visible' class
      $$tr[i].classList[isMatch ? "add" : "remove"]("visible");
    }
  }

  // Creating a reusable function will allow us to make
  // changes to it only in one place
  function normalizeStr(str) {
    return str.toUpperCase().trim();
  }
});

/* ... untouched CSS ... */ *{box-sizing:border-box}#myInput{background-image:url(/css/searchicon.png);background-position:10px 10px;background-repeat:no-repeat;width:100%;font-size:16px;padding:12px 20px 12px 40px;border:1px solid #ddd;margin-bottom:12px}#myTable{border-collapse:collapse;width:100%;border:1px solid #ddd;font-size:18px}#myTable td,#myTable th{text-align:left;padding:12px}#myTable tr{border-bottom:1px solid #ddd}

#myTable thead tr, /* notice the use of thead */
#myTable tr:hover {
  background-color: #f1f1f1;
}

#myTable tbody tr {
  display: none; /* Hide rows by default */
}

#myTable tbody tr.visible {
  display: table-row; /* Show them when they match */
}

<h2>My Customers</h2>

<!-- Try not using `on...=""` attributes. Separating HTML and JS is better practice -->
<input type="text" id="myInput" placeholder="Search for names" title="Type in a name" />

<table id="myTable">
  <!-- Use <thead> and <tbody> to separate data from headers -->
  <thead>
    <tr>
      <th style="width:60%;">Name</th>
      <th style="width:40%;">Country</th>
    </tr>
  </thead>
  <tbody>
    <tr> <td><a href="http://example.com/">Alfreds Futterkiste</a></td> <td>Germany</td> </tr>
    <tr> <td><a href="http://example.com/">Berglunds snabbkop</a></td> <td>Sweden</td> </tr>
    <tr> <td><a href="http://example.com/">Island Trading</a></td> <td>UK</td> </tr>
    <tr> <td><a href="http://example.com/">Koniglich Essen</a></td> <td>Germany</td> </tr>
    <tr> <td><a href="http://example.com/">Laughing Bacchus Winecellars</a></td> <td>Canada</td> </tr>
    <tr> <td><a href="http://example.com/">Magazzini Alimentari Riuniti</a></td> <td>Italy</td> </tr>
    <tr> <td><a href="http://example.com/">North/South</a></td> <td>UK</td> </tr>
    <tr> <td><a href="http://example.com/">Paris specialites</a></td> <td>France</td> </tr>
  </tbody>
</table>


来源: stackexchange

问:
Paramiko: calling "cd" command with exec_command does nothing
I have the following program using Paramiko:

```<code>#!/usr/bin/env python

import paramiko

hostname = '192.168.1.12'
port = 22
username = 'root'
password = 'whatl0ol'

if __name__ == "__main__":
    paramiko.util.log_to_file('paramiko.log')
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.connect(hostname, port, username, password)

while True:
      pick = raw_input("sshpy: ")
      stdin, stdout, stderr = ssh.exec_command(pick)
      print stdout.readlines()
</code>```

But when I connect and try to use cd, it doesn't work. How can I fix this?

答:
I needed to change directories and run an executable.  I have to do this all in one command.  The client unit was a windows 10 machine.
The cmd shell in windows is soo problematic!  Commands are different. ';' between commands doesn't work. You need to use '&'. cd d:/someDirectory doesn't work.  You need '/d'.  'pwd' doesn't work.   Also, echo%cd% to pwd doesn't work reliably.  'cd' with no parameters for pwd does work reliably.  I was hoping the not working list would save you time.  This is where it landed. </p>

```<code>cmd = 'cd /d D:\someDirectory & SomeExecutable.exe
      someParameter'
ssh_stdin, ssh_stdout, ssh_stderr =
ssh.exec_command(cmd_1_to_execute)
</code>```

<p>To check directory change use the following: </p>

```<code>cmd = 'cd /d D:\someDirectory & cd'
ssh_stdin, ssh_stdout, ssh_stderr =
ssh.exec_command(cmd_1_to_execute)

output = ssh_stdout.readline()
error = ssh_stderr.readline()
print("output: " + output)
print("error: " + error)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following program using Paramiko:

#!/usr/bin/env python

import paramiko

hostname = '192.168.1.12'
port = 22
username = 'root'
password = 'whatl0ol'

if __name__ == "__main__":
    paramiko.util.log_to_file('paramiko.log')
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.connect(hostname, port, username, password)

while True:
      pick = raw_input("sshpy: ")
      stdin, stdout, stderr = ssh.exec_command(pick)
      print stdout.readlines()

But when I connect and try to use cd, it doesn't work. How can I fix this?

Body:
I needed to change directories and run an executable.  I have to do this all in one command.  The client unit was a windows 10 machine.
The cmd shell in windows is soo problematic!  Commands are different. ';' between commands doesn't work. You need to use '&'. cd d:/someDirectory doesn't work.  You need '/d'.  'pwd' doesn't work.   Also, echo%cd% to pwd doesn't work reliably.  'cd' with no parameters for pwd does work reliably.  I was hoping the not working list would save you time.  This is where it landed.

cmd = 'cd /d D:\someDirectory & SomeExecutable.exe
      someParameter'
ssh_stdin, ssh_stdout, ssh_stderr =
ssh.exec_command(cmd_1_to_execute)

To check directory change use the following:

cmd = 'cd /d D:\someDirectory & cd'
ssh_stdin, ssh_stdout, ssh_stderr =
ssh.exec_command(cmd_1_to_execute)

output = ssh_stdout.readline()
error = ssh_stderr.readline()
print("output: " + output)
print("error: " + error)


问:
Dilemma about Spark partitions
I am working on a project where I have to read S3 files (each about 3MB zipped) using boto3. I have a small pyspark script that runs every hour to process the file and generate 2 types of output data which is written back to S3. The pyspark script uses 'xmltodict' python library to read some static data into a dictionary object needed for file processing. I have a small Amazon EMR cluster v5.28 running with 1 Master and 1 Core. This might be excessive but is not my main concern right now.

Questions:
1. How do I know 'IF' i should partition the data? I have read articles on how many partitions to create, etc but couldn't find anything on IF and WHEN. What is the criteria that drives partitioning - number of rows, columns, data type, actions taken in the script, etc in the source data file? I read the source file into an RDD and convert it to a DF and perform various operations by adding columns, grouping data, counting data, etc. How does spark handle partitioning behind the scenes?
2. Currently, I manually execute the pyspark script as follows:

```<code>spark-submit --master spark://x.x.x.x:7077 --deploy-mode client test.py
</code>```

on the master node as I have decided to stick with Standalone CM. The 'xmltodict' is installed on this node, but is not installed on the Core node. It doesn't seem like it needs to be installed or even python3 configured on Core node since I am not seeing any errors. Is that correct and can somebody shed some light on this confusion? I tried to install the python libraries via shell file as a bootstrap
when I created the cluster, but it failed and quite frankly after trying it a few times, I gave up.
3. Based on partitioning I think I am slightly confused on whether or not to use coalesce() or collect(). Again, the question is when to use and when not to?

Sorry too many questions. Now, that I have the pyspark script written, I am trying to work the efficiencies.
Thanks

答: Partitioning is the mechanism with which data is divided into optimum size chunks and based on that multiple tasks are run, each processing one piece of data. As you see this is the core of parallelism and without this there is no significant use of Spark (or any bigdata processing framework). Most of the file formats are splittable and some are splittable when compressed like Avro, parquet, orc etc. Some file formats are not splittable when compressed like - zip, gzip etc. Based on the size of the file being processed and their ability to be split, Spark automatically creates multiple partitions and processes data in parallel. In your case the data being zip, one file will be one partition and no more than 1 CPU can work on it at once. If this zip is small then its ok, but if it is big then its processing will be slow.

Title: Dilemma about Spark partitions

Body:
I am working on a project where I have to read S3 files (each about 3MB zipped) using boto3. I have a small pyspark script that runs every hour to process the file and generate 2 types of output data which is written back to S3. The pyspark script uses 'xmltodict' python library to read some static data into a dictionary object needed for file processing. I have a small Amazon EMR cluster v5.28 running with 1 Master and 1 Core. This might be excessive but is not my main concern right now.

Questions:
1. How do I know 'IF' i should partition the data? I have read articles on how many partitions to create, etc but couldn't find anything on IF and WHEN. What is the criteria that drives partitioning - number of rows, columns, data type, actions taken in the script, etc in the source data file? I read the source file into an RDD and convert it to a DF and perform various operations by adding columns, grouping data, counting data, etc. How does spark handle partitioning behind the scenes?
2. Currently, I manually execute the pyspark script as follows:

spark-submit --master spark://x.x.x.x:7077 --deploy-mode client test.py

on the master node as I have decided to stick with Standalone CM. The 'xmltodict' is installed on this node, but is not installed on the Core node. It doesn't seem like it needs to be installed or even python3 configured on Core node since I am not seeing any errors. Is that correct and can somebody shed some light on this confusion? I tried to install the python libraries via shell file as a bootstrap
when I created the cluster, but it failed and quite frankly after trying it a few times, I gave up.
3. Based on partitioning I think I am slightly confused on whether or not to use coalesce() or collect(). Again, the question is when to use and when not to?

Sorry too many questions. Now, that I have the pyspark script written, I am trying to work the efficiencies.
Thanks


问:
Too slow first run TorchScript model and its implementation in Flask
I'm trying to deploy torchscripted model in Python and Flask. As I realized (at least as mentioned here ) that scripted models need to be "warmed up" before using, so first run of such models takes much longer than subsequent ones. My question is: is there any way to load torchscripted models in Flask route and predict without loss of "worm-up" time? Can I store somewhere "warm-uped" model to avoid warming-up in every request?
I wrote simple code that reproduce the "warm-up" pass:

```<code>    import torchvision, torch, time
    model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
    model = torch.jit.script(model)
    model.eval()
    x = [torch.randn((3,224,224))]
    for i in range(3):
      start = time.time()
      model(x)
      print(‘Time elapsed: {}’.format(time.time()-start))
</code>```

Output:

```<code>Time elapsed: 38.29<br>
Time elapsed: 6.65<br>
Time elapsed: 6.65<br>
</code>```

And Flask code:

```<code>    import torch, torchvision, os, time
    from flask import  Flask
    app = Flask(__name__)
    @app.route('/')
    def test_scripted_model(path='/tmp/scripted_model.pth'):
        if os.path.exists(path):
            model = torch.jit.load(path, map_location='cpu')
        else:
            model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
            model = torch.jit.script(model)
            torch.jit.save(model, path)
        model.eval()
        x = [torch.randn((3, 224, 224))]
        out = ''
        for i in range(3):
            start = time.time()
            model(x)
            out += 'Run {} time: {};\t'.format(i+1, round((time.time() - start), 2))
        return out
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000, debug=False)
</code>```

Output:

```<code>Run 1 time: 46.01; Run 2 time: 8.76; Run 3 time: 8.55;
</code>```

OS: Ubuntu 18.04 & Windows10

Python version: 3.6.9
Flask: 1.1.1
Torch: 1.4.0
Torchvision: 0.5.0

Update:

Solved "warm-up" problem as:

```<code>with torch.jit.optimized_execution(False):
    model(x)
</code>```

Update2:
Solved Flask problem (as mentioned below) with creating global python model object before server starts and warming up it there. Then in each request the model is ready to use.

```<code>    model = torch.jit.load(path, map_location='cpu').eval()
    model(x)
    app = Flask(__name__)
</code>```

and then in @app.route:

```<code>@app.route('/')
def test_scripted_model():
    global model
    ...
    ...
</code>```

答:
Can I store somewhere "warm-uped" model to avoid warming-up in every request?

Yes, just instantiate your model outside of the test_scripted_model function and refer to it from within the function.

Body:
I'm trying to deploy torchscripted model in Python and Flask. As I realized (at least as mentioned here ) that scripted models need to be "warmed up" before using, so first run of such models takes much longer than subsequent ones. My question is: is there any way to load torchscripted models in Flask route and predict without loss of "worm-up" time? Can I store somewhere "warm-uped" model to avoid warming-up in every request?
I wrote simple code that reproduce the "warm-up" pass:

    import torchvision, torch, time
    model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
    model = torch.jit.script(model)
    model.eval()
    x = [torch.randn((3,224,224))]
    for i in range(3):
      start = time.time()
      model(x)
      print(‘Time elapsed: {}’.format(time.time()-start))

Output:

Time elapsed: 38.29

Time elapsed: 6.65

Time elapsed: 6.65

And Flask code:

    import torch, torchvision, os, time
    from flask import  Flask
    app = Flask(__name__)
    @app.route('/')
    def test_scripted_model(path='/tmp/scripted_model.pth'):
        if os.path.exists(path):
            model = torch.jit.load(path, map_location='cpu')
        else:
            model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
            model = torch.jit.script(model)
            torch.jit.save(model, path)
        model.eval()
        x = [torch.randn((3, 224, 224))]
        out = ''
        for i in range(3):
            start = time.time()
            model(x)
            out += 'Run {} time: {};\t'.format(i+1, round((time.time() - start), 2))
        return out
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000, debug=False)

Output:

Run 1 time: 46.01; Run 2 time: 8.76; Run 3 time: 8.55;

OS: Ubuntu 18.04 & Windows10

Python version: 3.6.9
Flask: 1.1.1
Torch: 1.4.0
Torchvision: 0.5.0

Update:

Solved "warm-up" problem as:

with torch.jit.optimized_execution(False):
    model(x)

Update2:
Solved Flask problem (as mentioned below) with creating global python model object before server starts and warming up it there. Then in each request the model is ready to use.

    model = torch.jit.load(path, map_location='cpu').eval()
    model(x)
    app = Flask(__name__)

and then in @app.route:

@app.route('/')
def test_scripted_model():
    global model
    ...
    ...


问:
No module named 'flask_cors' when using gunicorn
My application runs normally when running using python run.py but when running using gunicorn gunicorn run:app it gives 'flask_cors' module not found error.

I have created a basic application to make it easier to understand, I have debugged it a lot but didn't work, as it's running fine with python run.py so it should be running when using gunicorn, I think I do not actually understand how gunicorn is actually importing that it's leading to this error.

Working Directory

```<code>.
├── flaskblog
│   ├── __init__.py
│   └── routes.py
├── requirements.txt
└── run.py

1 directory, 4 files
</code>```

__init__.py file

```<code>from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, support_credentials=True)

from flaskblog import routes
</code>```

routes.py file

```<code>from flaskblog import app
from flask_cors import cross_origin

@app.route("/")
@cross_origin(supports_credentials=True)
def home():
    return "home"
</code>```

run.py file

```<code>from flaskblog import app

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
</code>```

requirements.txt

```<code>Flask
gunicorn
flask-cors
</code>```

edit:

I run the program again to get the error trace, and this time it worked?
It started at '127.0.0.1:8000' so I used gunicorn -b 0.0.0.0 run:app

How is it working now?

If you have a better title for the question then please edit it, as now my issue is it's strange behaviour.

答:
Deleted the pycache and created the environment again, this time it worked as it should be and hosted on heroku successfully.
Inside my procfile</p>

```<code>web: gunicorn gettingstarted.wsgi
web: gunicorn run:app
</code>```

Body:
My application runs normally when running using python run.py but when running using gunicorn gunicorn run:app it gives 'flask_cors' module not found error.

I have created a basic application to make it easier to understand, I have debugged it a lot but didn't work, as it's running fine with python run.py so it should be running when using gunicorn, I think I do not actually understand how gunicorn is actually importing that it's leading to this error.

Working Directory

.
├── flaskblog
│   ├── __init__.py
│   └── routes.py
├── requirements.txt
└── run.py

1 directory, 4 files

__init__.py file

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, support_credentials=True)

from flaskblog import routes

routes.py file

from flaskblog import app
from flask_cors import cross_origin

@app.route("/")
@cross_origin(supports_credentials=True)
def home():
    return "home"

run.py file

from flaskblog import app

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

requirements.txt

Flask
gunicorn
flask-cors

edit:

I run the program again to get the error trace, and this time it worked?
It started at '127.0.0.1:8000' so I used gunicorn -b 0.0.0.0 run:app

How is it working now?

If you have a better title for the question then please edit it, as now my issue is it's strange behaviour.

Body:
Deleted the pycache and created the environment again, this time it worked as it should be and hosted on heroku successfully.
Inside my procfile

web: gunicorn gettingstarted.wsgi
web: gunicorn run:app


问:
Loop through number array to construct object of index nodes
I have an array such as [2,5,3,1] each number represents an index number. How would I be able to construct an object path using these nodes? For example:

[2,5] would create:

```<code>myObject.conversations[i].conversations[i]
</code>```

[2,5,3,1] would create:

```<code>myObject.conversations[i].conversations[i].conversations[i].conversations[i]
</code>```

I can only use basic javascript. I tried a for loop to construct a string which I could just keep adding to but it didn’t work.

答:
```<code>  function minimizeElems(keyArray,object){
    var obj = object;
    for(keys of keyArray){
      obj = obj[keys];
    }
    return obj;
  }
</code>```

Hope this function helps.

Body:
I have an array such as [2,5,3,1] each number represents an index number. How would I be able to construct an object path using these nodes? For example:

[2,5] would create:

myObject.conversations[i].conversations[i]

[2,5,3,1] would create:

myObject.conversations[i].conversations[i].conversations[i].conversations[i]

I can only use basic javascript. I tried a for loop to construct a string which I could just keep adding to but it didn’t work.

Body:
  function minimizeElems(keyArray,object){
    var obj = object;
    for(keys of keyArray){
      obj = obj[keys];
    }
    return obj;
  }

Hope this function helps.


问:
Convert float to its binary representation (using MemoryStream?)
I'd like to convert a given float into its binary representation. I tried to write the float value into a MemoryStream, read this MemoryStream byte by byte and convert the bytes into their binary representation. But every attempt failed.

"Can't read closed stream" (but I only closed the writer)

For test purposes I simply wrote an integer (I think four bytes in size) and the length of the MemoryStream was 0, when I didn't flush the StreamWriter, and 1, when I did.

I'm sure there is a better way to convert floats to binary, but I also wanted to learn a little bit about the MemoryStream class.

答:
Dotnetfiddle

```<code>BitConverter.GetBytes(3.141f)
            .Reverse()
            .Select(x => Convert.ToString(x, 2))
            .Select(x => x.PadLeft(8, '0'))
            .Aggregate("0b", (a, b) => a + "_" + b);

// res = "0b_01000000_01001001_00000110_00100101"
</code>```

Couldn't resist to use a "small" LINQ Query.
Works with double too.

ContentLicense: CC BY-SA 3.0

Body:
Dotnetfiddle

BitConverter.GetBytes(3.141f)
            .Reverse()
            .Select(x => Convert.ToString(x, 2))
            .Select(x => x.PadLeft(8, '0'))
            .Aggregate("0b", (a, b) => a + "_" + b);

// res = "0b_01000000_01001001_00000110_00100101"

Couldn't resist to use a "small" LINQ Query.
Works with double too.


问:
Defining analogue (similar) colors
I want to do a program that take the color from a image, and than give me the analogue colors...,
but I don't know how I can use the color taken from the image because it doesn't give me the colors like the object...

I tried to make like this:

```<code>from PIL import Image

img = Image.open("C:/Marco/programas/orange2.jpg").convert("P")

colors = []

for cor_rgb in img.getpalette():
    if cor_rgb not in colors:
        colors.append(cor_rgb)
c = Image.Image.getdata(img)

print(c)
print (colors)
</code>```

Can anybody help me please?

答:
You can use specify an adaptive conversion when you use the Image.convert() method. The details aren't given but "adaptive" in this context usually means the set colors that best represents those in the image.

After doing the conversion, the value returned by Image.getpalette() is a list of RGB colors representing each of the colors the adaptive algorithm chose to put into the palette. From the looks of the results using my test image, it looks like the colors are in the table ordered by popularity (but I'm not sure and it's not documented).

Professional image editing programs like Adobe Photoshop®, have several options when converting to a paletted image, including "selective", "uniform", and "perceptual". I often use the latter because it takes into consideration the fact that the human eye can't detect differences between all color equally, it using some metric to measure "perceptual color difference".

```<code>from PIL import Image

image_filename = "oranges2.jpg"
img = Image.open(image_filename).convert("P", palette=Image.ADAPTIVE)
palette = img.getpalette()
colors = [palette[i:i+3]  # Split palette entries up into groups of 3.
            for i in range(0, len(palette), 3)]

print(len(colors))
for color in colors:
    print(color)
</code>```

Sample output:

256
[250, 212, 69]
[253, 194, 17]
[252, 185, 22]
[254, 185, 1]
[255, 177, 10]
[255, 177, 2]
[255, 177, 0]
[254, 177, 2]
[240, 177, 35]
[255, 167, 10]
[255, 168, 4]
[255, 167, 2]
...
[115, 15, 1]
[98, 19, 1]
[98, 11, 1]
[86, 16, 2]
[75, 15, 2]
[83, 7, 1]
[72, 7, 1]
[58, 12, 3]
[56, 6, 1]
[59, 3, 1]
[48, 3, 1]
[36, 8, 3]
[36, 2, 1]
[20, 6, 3]
[18, 2, 1]
```

Here's the image file I used for testing:

Title: Defining analogue (similar) colors

Body:
I want to do a program that take the color from a image, and than give me the analogue colors...,
but I don't know how I can use the color taken from the image because it doesn't give me the colors like the object...

I tried to make like this:

from PIL import Image

img = Image.open("C:/Marco/programas/orange2.jpg").convert("P")

colors = []

for cor_rgb in img.getpalette():
    if cor_rgb not in colors:
        colors.append(cor_rgb)
c = Image.Image.getdata(img)

print(c)
print (colors)

Can anybody help me please?

Body:
You can use specify an adaptive conversion when you use the Image.convert() method. The details aren't given but "adaptive" in this context usually means the set colors that best represents those in the image.

After doing the conversion, the value returned by Image.getpalette() is a list of RGB colors representing each of the colors the adaptive algorithm chose to put into the palette. From the looks of the results using my test image, it looks like the colors are in the table ordered by popularity (but I'm not sure and it's not documented).

Professional image editing programs like Adobe Photoshop®, have several options when converting to a paletted image, including "selective", "uniform", and "perceptual". I often use the latter because it takes into consideration the fact that the human eye can't detect differences between all color equally, it using some metric to measure "perceptual color difference".

from PIL import Image

image_filename = "oranges2.jpg"
img = Image.open(image_filename).convert("P", palette=Image.ADAPTIVE)
palette = img.getpalette()
colors = [palette[i:i+3]  # Split palette entries up into groups of 3.
            for i in range(0, len(palette), 3)]

print(len(colors))
for color in colors:
    print(color)

Sample output:

256
[250, 212, 69]
[253, 194, 17]
[252, 185, 22]
[254, 185, 1]
[255, 177, 10]
[255, 177, 2]
[255, 177, 0]
[254, 177, 2]
[240, 177, 35]
[255, 167, 10]
[255, 168, 4]
[255, 167, 2]
...
[115, 15, 1]
[98, 19, 1]
[98, 11, 1]
[86, 16, 2]
[75, 15, 2]
[83, 7, 1]
[72, 7, 1]
[58, 12, 3]
[56, 6, 1]
[59, 3, 1]
[48, 3, 1]
[36, 8, 3]
[36, 2, 1]
[20, 6, 3]
[18, 2, 1]

Here's the image file I used for testing:


答:
We do melt then join with str.split

```<code>s=df.melt(['City','State'])
s=s.join(s.variable.str.split(',',expand=True))
Out[120]:
       City State              variable   value                0     1
0        LA    CA  NumberofDrivers,2019   123.0  NumberofDrivers  2019
1  SanDiego    CA  NumberofDrivers,2019   456.0  NumberofDrivers  2019
2        LA    CA     NumberofCars,2019    10.0     NumberofCars  2019
3  SanDiego    CA     NumberofCars,2019  2345.0     NumberofCars  2019

# if you need change the name adding .rename(columns={}) at the end
</code>```

Title: Pandas - Pivot and Rearrange Table With Multiple Labels in Same Header

Body:
I have an xlsx file with tabs for multiple years of data. Each tab contains a table with many columns and the table is structured like this:

+-----------+-------+-------------------------+----------------------+
|   City    | State | Number of Drivers, 2019 | Number of Cars, 2019 |
+-----------+-------+-------------------------+----------------------+
| LA        | CA    |                     123 |                 10.0 |
| San Diego | CA    |                     456 |                 2345 |
+-----------+-------+-------------------------+----------------------+

I would like to rearrange the table to look like this, and do it for each tab in the xlsx:

+-----------+-------+------+-------------------+---------------+
|   City    | State | Year |   Measure Name    | Measure Value |
+-----------+-------+------+-------------------+---------------+
| LA        | CA    | 2019 | Number of Drivers |           123 |
| San Diego | CA    | 2019 | Number of Drivers |           456 |
| LA        | CA    | 2019 | Number of Cars    |            10 |
| San Diego | CA    | 2019 | Number of Cars    |          2345 |
+-----------+-------+------+-------------------+---------------+

There are a lot of moving pieces to this and has been a little tricky to get the final formatting correct.

Body:
We do melt then join with str.split

s=df.melt(['City','State'])
s=s.join(s.variable.str.split(',',expand=True))
Out[120]:
       City State              variable   value                0     1
0        LA    CA  NumberofDrivers,2019   123.0  NumberofDrivers  2019
1  SanDiego    CA  NumberofDrivers,2019   456.0  NumberofDrivers  2019
2        LA    CA     NumberofCars,2019    10.0     NumberofCars  2019
3  SanDiego    CA     NumberofCars,2019  2345.0     NumberofCars  2019

# if you need change the name adding .rename(columns={}) at the end


答:
This sounds like homework.

var source = [,,,[,,[,,,,[,,,'foo']]]];
console.log(source[3][2][4][3]);

console.log([3, 2, 4, 3].reduce((o, i) => o[i], source));```

Title: Loop through number array to construct object of index nodes


问:
Generating random points out of a triangle
I have the following code to generate random points on a given map. I want to avoid having points in the lake area (top right corner). I sort of divided the lake into a rectangle and a triangle. For the rectangle, I could figure out how to avoid having points in there. But, for the triangle (shown with the red line), I couldn't find a solution. Any suggestion? You can find the "Map.png" below the code.

```<code>import numpy as np
import matplotlib.pyplot as plt

def point_generator(number):
    xlist,ylist = [], []
    for i in range(number):
        x = np.random.uniform(BBox[0],BBox[1])
        y = np.random.uniform(BBox[2],BBox[3])
        while x>-87.8 and y>42.25:
            x = np.random.uniform(BBox[0],BBox[1])
            y = np.random.uniform(BBox[2],BBox[3])
        xlist.append(x); ylist.append(y)
    return(xlist,ylist)

BBox = ((-89.541239, -87.541239,
         40.773460, 42.498943))
im = plt.imread('Map.png')

fig, ax = plt.subplots(figsize = (15,15))
ax.set_xlim(BBox[0],BBox[1])
ax.set_ylim(BBox[2],BBox[3])

plt.plot([-87.8,-87.8],[42.25,42.498943],'-k')
plt.plot([-87.8,-87.541239],[42.25,42.25],'-k')
plt.plot([-87.8,-87.541239],[42.25,41.75],'-r')

xs,ys = point_generator(1500)
plt.plot(xs,ys, '.b')
ax.imshow(im, zorder=0, extent = BBox, aspect= 'equal',alpha=0.5)
</code>```

答:
I don't really know pandas, but maybe you could get the coordinates (x1, y1) of the start point you want the dots to be removed, and then the coordinates of the end point you want (x2, y2) and then create a rectangle with the rectangle you created, like (x1, y1)-(x2, y2) is one side times (x2, y2)-(x2, y1) is the other side you multiply with so you get a rectangle. Half that and you got the coast line showed in your image. The hypotenuse is the actual coastline

Rectangle: ((x2, y1) - (x1, y1)) * ((x2, y1) - (x2, y2)) = E(rect)

Triangle: E(rect) / 2 = E(triangle)

Coastline: ((x2, y1) - (x1, y1)) ** 2 + ((x2, y1) - (x2, y2)) ** 2 = Hypotenuse (Coastline)

Graphical representation:

So now you have the surface that you don't want points to appear inside, and the coordinates that make up that surface.

Body:
I have the following code to generate random points on a given map. I want to avoid having points in the lake area (top right corner). I sort of divided the lake into a rectangle and a triangle. For the rectangle, I could figure out how to avoid having points in there. But, for the triangle (shown with the red line), I couldn't find a solution. Any suggestion? You can find the "Map.png" below the code.

import numpy as np
import matplotlib.pyplot as plt

def point_generator(number):
    xlist,ylist = [], []
    for i in range(number):
        x = np.random.uniform(BBox[0],BBox[1])
        y = np.random.uniform(BBox[2],BBox[3])
        while x>-87.8 and y>42.25:
            x = np.random.uniform(BBox[0],BBox[1])
            y = np.random.uniform(BBox[2],BBox[3])
        xlist.append(x); ylist.append(y)
    return(xlist,ylist)

BBox = ((-89.541239, -87.541239,
         40.773460, 42.498943))
im = plt.imread('Map.png')

fig, ax = plt.subplots(figsize = (15,15))
ax.set_xlim(BBox[0],BBox[1])
ax.set_ylim(BBox[2],BBox[3])

plt.plot([-87.8,-87.8],[42.25,42.498943],'-k')
plt.plot([-87.8,-87.541239],[42.25,42.25],'-k')
plt.plot([-87.8,-87.541239],[42.25,41.75],'-r')

xs,ys = point_generator(1500)
plt.plot(xs,ys, '.b')
ax.imshow(im, zorder=0, extent = BBox, aspect= 'equal',alpha=0.5)


问:
How can I correctly flag the end of the first sequence of a group?
This is an example of the the type of dataframe that I'm using and the desired column output.

```<code>reprEx <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"))

Desireddf <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             desiredResult = c(0,0,1,1,0,0,1,0,0,1,1,1,1,1))
</code>```

I am trying to use dplyr to correctly flag whenever a stage changes within a grouped id. The approved and declined flags are easy because I only have to flag the first case of a declined or approved appearing with:

```<code>    reprExWrong <- reprEx %>% group_by(id,stage1) %>%
  mutate(desiredResult = ifelse(stage1 == last(stage1) & stage1 == "open",1,
                                ifelse(stage1 == first(stage1) & stage1 %in% c("approved","declined"),1,0)
                                )
  )
</code>```

The issue is with the open stage. I only want to apply a flag for when the first sequences of opens ends within a group of id's. With the code that I have now it is choosing the last open within the group, even if it wasn't part of the first sequence of opens. for example:

```<code>reprExWrong <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             notdesiredResult = c(0,0,0,1,0,1,1,0,0,1,1,1,1,1))
</code>```

In this case, within id1 I would need the flag to show up where the sequence reaches the last open before approved appears, and not in the open after approved appears. I only need the flag in the row of the last occurrence of open if that succession of opens is the first succession within the id. Sorry for any confusion, I would be happy to further elaborate. This is just to correctly identify stage transitions for recording purposes

答:
```<code>reprEx %>% group_by(id) %>% mutate(lastopen=cumsum(lead(stage1!="open"))==1)
</code>```

What this does is check for the first time stage1 is NOT "open" within an id group, and sets the line before that as TRUE. Result:

```<code># A tibble: 14 x 3
# Groups:   id [3]
      id stage1   lastopen
   <dbl> <fct>    <lgl>
 1     1 open     FALSE
 2     1 open     FALSE
 3     1 open     TRUE
 4     1 approved FALSE
 5     1 approved FALSE
 6     1 open     FALSE
 7     1 declined NA
 8     2 open     FALSE
 9     2 open     FALSE
10     2 open     TRUE
11     2 declined NA
12     3 open     TRUE
13     3 approved FALSE
14     3 declined NA
</code>```

If the NAs are a problem, you can also add:

```<code>%>% mutate(lastopen=ifelse(is.na(lastopen),FALSE,lastopen))

# A tibble: 14 x 3
# Groups:   id [3]
      id stage1   lastopen
   <dbl> <fct>    <lgl>
 1     1 open     FALSE
 2     1 open     FALSE
 3     1 open     TRUE
 4     1 approved FALSE
 5     1 approved FALSE
 6     1 open     FALSE
 7     1 declined FALSE
 8     2 open     FALSE
 9     2 open     FALSE
10     2 open     TRUE
11     2 declined FALSE
12     3 open     TRUE
13     3 approved FALSE
14     3 declined FALSE
</code>```

Body:
This is an example of the the type of dataframe that I'm using and the desired column output.

reprEx <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"))

Desireddf <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             desiredResult = c(0,0,1,1,0,0,1,0,0,1,1,1,1,1))

I am trying to use dplyr to correctly flag whenever a stage changes within a grouped id. The approved and declined flags are easy because I only have to flag the first case of a declined or approved appearing with:

    reprExWrong <- reprEx %>% group_by(id,stage1) %>%
  mutate(desiredResult = ifelse(stage1 == last(stage1) & stage1 == "open",1,
                                ifelse(stage1 == first(stage1) & stage1 %in% c("approved","declined"),1,0)
                                )
  )

The issue is with the open stage. I only want to apply a flag for when the first sequences of opens ends within a group of id's. With the code that I have now it is choosing the last open within the group, even if it wasn't part of the first sequence of opens. for example:

reprExWrong <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             notdesiredResult = c(0,0,0,1,0,1,1,0,0,1,1,1,1,1))

In this case, within id1 I would need the flag to show up where the sequence reaches the last open before approved appears, and not in the open after approved appears. I only need the flag in the row of the last occurrence of open if that succession of opens is the first succession within the id. Sorry for any confusion, I would be happy to further elaborate. This is just to correctly identify stage transitions for recording purposes

Body:
reprEx %>% group_by(id) %>% mutate(lastopen=cumsum(lead(stage1!="open"))==1)

What this does is check for the first time stage1 is NOT "open" within an id group, and sets the line before that as TRUE. Result:

# A tibble: 14 x 3
# Groups:   id [3]
      id stage1   lastopen
   <dbl> <fct>    <lgl>
 1     1 open     FALSE
 2     1 open     FALSE
 3     1 open     TRUE
 4     1 approved FALSE
 5     1 approved FALSE
 6     1 open     FALSE
 7     1 declined NA
 8     2 open     FALSE
 9     2 open     FALSE
10     2 open     TRUE
11     2 declined NA
12     3 open     TRUE
13     3 approved FALSE
14     3 declined NA

If the NAs are a problem, you can also add:

%>% mutate(lastopen=ifelse(is.na(lastopen),FALSE,lastopen))

# A tibble: 14 x 3
# Groups:   id [3]
      id stage1   lastopen
   <dbl> <fct>    <lgl>
 1     1 open     FALSE
 2     1 open     FALSE
 3     1 open     TRUE
 4     1 approved FALSE
 5     1 approved FALSE
 6     1 open     FALSE
 7     1 declined FALSE
 8     2 open     FALSE
 9     2 open     FALSE
10     2 open     TRUE
11     2 declined FALSE
12     3 open     TRUE
13     3 approved FALSE
14     3 declined FALSE


问:
Typescript Pick issues
My simplified code block is like the following

interface A {
    val: string;
    // Other optional parameters
}

function usingObject(obj: A) {
    return obj.val
}

function usingVal(val: Pick) {
    return usingObject({ val })
}
```

i am getting the following error

Type 'Pick' is not assignable to type 'string'.ts(2322)

I want a function which can accept object and other function which take each mandatory parameter as an argument

答:
The result type of Pick is essentially the same as interface A. In other words, Pick<...> constructs a new object type.

It appears that the following would work for you:

```<code>function usingVal(val: string) {
    return usingObject({ val })
}
</code>```

Title: Typescript Pick issues

Body:
My simplified code block is like the following

interface A {
    val: string;
    // Other optional parameters
}

function usingObject(obj: A) {
    return obj.val
}

function usingVal(val: Pick) {
    return usingObject({ val })
}

i am getting the following error

Type 'Pick' is not assignable to type 'string'.ts(2322)

I want a function which can accept object and other function which take each mandatory parameter as an argument

Body:
The result type of Pick<A, 'val'> is essentially the same as interface A. In other words, Pick<...> constructs a new object type.

It appears that the following would work for you:

function usingVal(val: string) {
    return usingObject({ val })
}


问:
Convert Excel workbook to a CSV in VBA
I am getting an error in my VBA script for converting an Excel Workbook to a CSV. The VBA script is ran through a Microsoft Word VBA script.

```<code>Private Sub CommandButton1_Click()

Dim objExcel As New Excel.Application
Dim wb_xl As Excel.Workbook
Dim wb As Excel.Worksheet

Set wb_xl = objExcel.Workbooks.Open("O:\documents\folder.xlsx")
wb_xl.SaveAs FileName:="O:\documents\folder.csv", FileFormat:=xlCSV
Set wb = objExcel.Workbooks.Open("O:\documents\folder.csv")
wb_xl.Close savechanges:=False

End Sub
</code>```

This seems straight-forward and the CSV is being produced, but I am receiving an error:

Run-time error '1004': Cannot access 'folder.csv'

The error is on Line 8 (wb_xl.SaveAs...).

答:
```<code>Dim objExcel As New Excel.Application
</code>```

If this isn't causing any problems now, it will be later. Split the declaration and the assignment, avoid auto-instantiated objects in general, but even more especially for objects that spawn an external process when created.

```<code>Dim objExcel As Excel.Application
Set objExcel = New Excel.Application
</code>```

...and don't forget to .Quit that instance when you're done:

```<code>'...
objExcel.Quit
</code>```

Now, error 1004.

```<code>wb_xl.SaveAs FileName:="O:\documents\folder.csv", FileFormat:=xlCSV
</code>```

This seems straight-forward and the CSV is being produced

The unqualified xlCSV constant is no biggie, but keep in mind that it's only valid because the Excel library is referenced; consider qualifying it:

```<code>wb_xl.SaveAs FileName:="O:\documents\folder.csv", FileFormat:=Excel.xlCSV
</code>```

If the CSV is being produced, then the SaveAs call worked, and the failing statement would be this one:

```<code>Set wb = objExcel.Workbooks.Open("O:\documents\folder.csv")
</code>```

You can't Open that file, it's already opened - that's why the statement is throwing error 1004: if you tried it in the Excel UI with a .xlsm file, you'd be getting a more detailed error message:

But the error message is different with a .csv file:

I got this error message by typing this in the immediate pane, with a new blank workbook opened:

```<code>ThisWorkbook.SaveAs "C:\Dev\test123.csv", xlCSV
Set b = Workbooks.Open("C:\Dev\VBA\test123.csv")
</code>```

I think that's exactly the error you're getting.

Remove wb, you don't need it (note: if the Open succeeded, the assignment would be throwing a type mismatch error, because you can't assign a Workbook object to a Worksheet reference; Dim wb As Excel.Worksheet looks wrong). Remove the Workbooks.Open operation too, the CSV is already opened.

In other words:

Private Sub CommandButton1_Click()

    Dim xlApp As Excel.Application
    Set xlApp = New Excel.Application

    Dim wb As Excel.Worksheet
    Set wb = xlApp.Workbooks.Open("O:\documents\folder.xlsx")

    wb.SaveAs FileName:="O:\documents\folder.csv", FileFormat:=Excel.xlCSV
    wb.Close savechanges:=False

    xlApp.Quit

End Sub
```

Title: Convert Excel workbook to a CSV in VBA

Body:
I am getting an error in my VBA script for converting an Excel Workbook to a CSV. The VBA script is ran through a Microsoft Word VBA script.

Private Sub CommandButton1_Click()

Dim objExcel As New Excel.Application
Dim wb_xl As Excel.Workbook
Dim wb As Excel.Worksheet

Set wb_xl = objExcel.Workbooks.Open("O:\documents\folder.xlsx")
wb_xl.SaveAs FileName:="O:\documents\folder.csv", FileFormat:=xlCSV
Set wb = objExcel.Workbooks.Open("O:\documents\folder.csv")
wb_xl.Close savechanges:=False

End Sub

This seems straight-forward and the CSV is being produced, but I am receiving an error:

Run-time error '1004': Cannot access 'folder.csv'

The error is on Line 8 (wb_xl.SaveAs...).

Body:
Dim objExcel As New Excel.Application

If this isn't causing any problems now, it will be later. Split the declaration and the assignment, avoid auto-instantiated objects in general, but even more especially for objects that spawn an external process when created.

Dim objExcel As Excel.Application
Set objExcel = New Excel.Application

...and don't forget to .Quit that instance when you're done:

'...
objExcel.Quit

Now, error 1004.

wb_xl.SaveAs FileName:="O:\documents\folder.csv", FileFormat:=xlCSV

This seems straight-forward and the CSV is being produced

The unqualified xlCSV constant is no biggie, but keep in mind that it's only valid because the Excel library is referenced; consider qualifying it:

wb_xl.SaveAs FileName:="O:\documents\folder.csv", FileFormat:=Excel.xlCSV

If the CSV is being produced, then the SaveAs call worked, and the failing statement would be this one:

Set wb = objExcel.Workbooks.Open("O:\documents\folder.csv")

You can't Open that file, it's already opened - that's why the statement is throwing error 1004: if you tried it in the Excel UI with a .xlsm file, you'd be getting a more detailed error message:

But the error message is different with a .csv file:

I got this error message by typing this in the immediate pane, with a new blank workbook opened:

ThisWorkbook.SaveAs "C:\Dev\test123.csv", xlCSV
Set b = Workbooks.Open("C:\Dev\VBA\test123.csv")

I think that's exactly the error you're getting.

Remove wb, you don't need it (note: if the Open succeeded, the assignment would be throwing a type mismatch error, because you can't assign a Workbook object to a Worksheet reference; Dim wb As Excel.Worksheet looks wrong). Remove the Workbooks.Open operation too, the CSV is already opened.

In other words:

Private Sub CommandButton1_Click()

    Dim xlApp As Excel.Application
    Set xlApp = New Excel.Application

    Dim wb As Excel.Worksheet
    Set wb = xlApp.Workbooks.Open("O:\documents\folder.xlsx")

    wb.SaveAs FileName:="O:\documents\folder.csv", FileFormat:=Excel.xlCSV
    wb.Close savechanges:=False

    xlApp.Quit

End Sub


问:
Windows 10 not allowing Python server.py to connect with client.py
I'm working a tutorial in Python 3.8 that involves sockets and networking. There is a server.py file and a client.py file. I took example code straight out of the Python doc for sockets to see if that would work, and it does not. The server starts and creates a socket and listens for the connection, but I get WinError 10061, the one where the target machine refuses the connection. My OS is Windows 10 and I'm using IDLE. I've looked at my Firewall and set a permission for pythonw.exe to be allowed through, but that has not helped. Anybody have any fixes for me to try? I can't really proceed until I can get the client and server connected.</p>

答:
I think I know what I’ve been doing wrong. I have been running both server and client files in the same console. I think I have to open two consoles and run one file in each so they can communicate.
(Doh!)
I’m at work so I can’t test it right now. Just in case anyone else has been befuddled by this .

Yes, I did not realize that each file had to run in its own instance of IDLE, but that makes perfect sense now. A socket won’t connect to itself!


问:
What happens with GETS command if input buffer overflow before any newline character?
Assume using the construct: while {[gets $id line]>0} {...}. Now what if the single line size is greater than input buffer size?

答:
Tcl will buffer the data when no newline is received as long as memory is available, and panic when there isn't. As this could be used for a DoS attack, TIP #287 introduced the chan pending command. This command can be used to take action when the buffered data exceeds a limit.

Note: chan pending can only help when used with non-blocking channels.


问:
react child state doesn't update with props from father (and deeper in the branch)
The problem is following:
I have components: Grandfather, father and child (literally :D).
Grandfather passes his state through props to father (and father sets his state with it).
Then father passes props to child and child also sets state with it.
When i display this.props everything is fine, but when i display
state then i see that nothing has changed in father and child.
I heard there is something like componentWillReceiveProps() but it is already deprecated.

Working example: https://codesandbox.io/s/doesitworkornot-rrcgt?fontsize=14&hidenavigation=1&theme=dark

And codes:

Grandfather.js

```<code>import React from "react";
import Father from "./Father";

class GrandFather extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clickedCounter: 1
    };
  }

  onClick = e => {
    this.setState(prevState => ({
      clickedCounter: prevState.clickedCounter + 1
    }));
  };

  render() {
    return (
      <div>
        <button onClick={this.onClick}>Press me</button> <br />
        Here is Grandfather -> state value={this.state.clickedCounter}
        <Father clickedCounter={this.state.clickedCounter} />
      </div>
    );
  }
}
export default GrandFather;

</code>```

Father.js

```<code>import React from "react";
import Child from "./Child";

class Father extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clickedCounter: this.props.clickedCounter
    };
  }
  render() {
    return (
      <div>
        Here is Father -> props value={this.props.clickedCounter} <br />
        Here is Father -> state value={this.state.clickedCounter}
        <Child clickedCounter={this.props.clickedCounter} />
      </div>
    );
  }
}
export default Father;

</code>```

Child.js

```<code>import React from "react";

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clickedCounter: this.props.clickedCounter
    };
  }
  render() {
    return (
      <div>
        Here is Child -> props value={this.props.clickedCounter} <br />
        Here is Child -> state value={this.state.clickedCounter}
      </div>
    );
  }
}

export default Child;

</code>```

I also heard there is something like cloning children... I'd like to avoid it if possible.

答:
When you initialise state from props, react will not refresh state but it do refresh props. You can use below code to make it work instead of componentWillReceiveProps.</p>

```<code>static getDerivedStateFromProps(nextProps) {
    return {
      clickedCounter: nextProps.clickedCounter,
    }
}
</code>```

Body:
The problem is following:
I have components: Grandfather, father and child (literally :D).
Grandfather passes his state through props to father (and father sets his state with it).
Then father passes props to child and child also sets state with it.
When i display this.props everything is fine, but when i display
state then i see that nothing has changed in father and child.
I heard there is something like componentWillReceiveProps() but it is already deprecated.

Working example: https://codesandbox.io/s/doesitworkornot-rrcgt?fontsize=14&hidenavigation=1&theme=dark

And codes:

Grandfather.js

import React from "react";
import Father from "./Father";

class GrandFather extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clickedCounter: 1
    };
  }

  onClick = e => {
    this.setState(prevState => ({
      clickedCounter: prevState.clickedCounter + 1
    }));
  };

  render() {
    return (

        <button onClick={this.onClick}>Press me</button>

        Here is Grandfather -> state value={this.state.clickedCounter}
        <Father clickedCounter={this.state.clickedCounter} />

    );
  }
}
export default GrandFather;

Father.js

import React from "react";
import Child from "./Child";

class Father extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clickedCounter: this.props.clickedCounter
    };
  }
  render() {
    return (

        Here is Father -> props value={this.props.clickedCounter}

        Here is Father -> state value={this.state.clickedCounter}
        <Child clickedCounter={this.props.clickedCounter} />

    );
  }
}
export default Father;

Child.js

import React from "react";

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clickedCounter: this.props.clickedCounter
    };
  }
  render() {
    return (

        Here is Child -> props value={this.props.clickedCounter}

        Here is Child -> state value={this.state.clickedCounter}

    );
  }
}

export default Child;

I also heard there is something like cloning children... I'd like to avoid it if possible.

Body:
When you initialise state from props, react will not refresh state but it do refresh props. You can use below code to make it work instead of componentWillReceiveProps.

static getDerivedStateFromProps(nextProps) {
    return {
      clickedCounter: nextProps.clickedCounter,
    }
}


问:
ISerialization Constructor not getting called
EDIT: The solution to my problem is to implement IXMLSerializer. Thanks everyone for the quick responses.

Hi everyone, I'm having this issue and I do not seem to a find a proper solution to it.

I have the following class

```<code>public class Child
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

        }
        [Serializable]
        public class Test: ISerializable
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

            private Child _child = new Child();

            public Child Child
            {
                get { return _child; }
                set { _child = value; }
            }

            public Test()
            {
            }
            protected Test(SerializationInfo info, StreamingContext context)
            {
                if (info.MemberCount > 1)
                    Child.Id = info.GetInt32("ChildId");
            }

            #region ISerializable Members

            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                info.AddValue("ChildId", Child.Id);
            }

            #endregion
        }
</code>```

If I send the following XML to be deserialzed

```<code><?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>
</code>```

using the following code to deserialize

```<code>serializer.Deserialize(new StringReader("<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>");
</code>```

I supposed that would call my Serialization constructor, but the thing is that is never getting called.

I am using the above posted XML instead of this one

```<code><?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><Child><Id>10</Id></Child></Test>
</code>```

Because I'm getting the xml posted from another application, so I need to manually created child objects and assigned its value manually from within the constructor.

I'll really appreciate all the help and guidance you can provide me.

答: What is the serializer variable you use? If it's an XmlSerializer, your serialization hooks won't be called because the XmlSerializer doesn't support them (see IXmlSerializable).

OwnerDisplayName: Paleta

ContentLicense: CC BY-SA 2.5

Body:
EDIT: The solution to my problem is to implement IXMLSerializer. Thanks everyone for the quick responses.

Hi everyone, I'm having this issue and I do not seem to a find a proper solution to it.

I have the following class

public class Child
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

        }
        [Serializable]
        public class Test: ISerializable
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

            private Child _child = new Child();

            public Child Child
            {
                get { return _child; }
                set { _child = value; }
            }

            public Test()
            {
            }
            protected Test(SerializationInfo info, StreamingContext context)
            {
                if (info.MemberCount > 1)
                    Child.Id = info.GetInt32("ChildId");
            }

            #region ISerializable Members

            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                info.AddValue("ChildId", Child.Id);
            }

            #endregion
        }

If I send the following XML to be deserialzed

<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>

using the following code to deserialize

serializer.Deserialize(new StringReader("<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>");

I supposed that would call my Serialization constructor, but the thing is that is never getting called.

I am using the above posted XML instead of this one

<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><Child><Id>10</Id></Child></Test>

Because I'm getting the xml posted from another application, so I need to manually created child objects and assigned its value manually from within the constructor.

I'll really appreciate all the help and guidance you can provide me.

LastEditorDisplayName: Paleta

OwnerDisplayName: Kent Boogaart


问:
What is the difference between ".class element" and "element.class"?
Is there a difference between .class element and element.class in a CSS selector?

I had always been shown element.class but just the other day came across a CSS file at work that had .class element and wanted to know if this was just a style choice (in which case I would make my changes match), or if there was a specific reason (in which case I would not necessarily want to make my changes match).

答:
element.class selects all <element />s with that class. .class element selects all <element />s that are descendants of elements that have that class.

For example, HTML:

```<code><div class='wrapper'>
  <div class='content'></div>
  <div></div>
  <div class='footer'></div>
</div>
</code>```

For example, CSS:

```<code>div.wrapper {
  background-color: white; /* the div with wrapper class will be white */
}

.wrapper div {
  background-color: red;   /* all 3 child divs of wrapper will be red */
}
</code>```

Body:
element.class selects all <element />s with that class. .class element selects all <element />s that are descendants of elements that have that class.

For example, HTML:

<div class='wrapper'>
  <div class='content'></div>
  <div></div>
  <div class='footer'></div>
</div>

For example, CSS:

div.wrapper {
  background-color: white; /* the div with wrapper class will be white */
}

.wrapper div {
  background-color: red;   /* all 3 child divs of wrapper will be red */
}


问:
Best way to edit Arrays in Vue. v-model issue
Im pretty new to Vue and have been trying edit an array of strings using the v-model property. I've created a small jsfiddle and am having issue editing the array. An error pops up saying I should be using an object when using v-model but when I hit the delete button it seems so know its been edited. also adding a new input field will reset the previous ones.

what is the best way to about this editing an array and keeping it in the same format

答:
i forked your jsfiddle, where basically i changed the binding of the input element to modify it value when the input event is emitted:

```<code><input id="field-option-0" class="input-large form-control" type="text" @input="inputHandler(index, $event)" :value="option">
</code>```

now you are passing to it handler function the current index of your list and the native $event to set it over your list.

```<code>inputHandler(index, e) {
  this.field_data.value_options[index] = e.target.value
}
</code>```

Body:
i forked your jsfiddle, where basically i changed the binding of the input element to modify it value when the input event is emitted:

<input id="field-option-0" class="input-large form-control" type="text" @input="inputHandler(index, $event)" :value="option">

now you are passing to it handler function the current index of your list and the native $event to set it over your list.

inputHandler(index, e) {
  this.field_data.value_options[index] = e.target.value
}


问:
Make Pipenv create the virtualenv in the same folder
I want Pipenv to make virtual environment in the same folder with my project (Django).

I searched and found the PIPENV_VENV_IN_PROJECT option but I don't know where and how to use this.

答:
This maybe helps someone else. I found another easy way to solve this!

Just make an empty folder inside your project and name it .venv and pipenv will use this folder.


问:
Trying to stop a single thread out of multiple running at the same time in java
So im trying to stop a single thread when I have multiple threads running, here is the code im using to initialise the threads. Basically I have multiple textFields in javafx, and when a button is clicked on the screen, it fills the textFields, one by one, with an incrementing timer. Now I also have a button for each of the textfields to clear it, but the problem is when I clear it, because the thread is still running, the timer vanishes for a second and comes back because of the line 'orderTimes.get(boxNo).setText(minute + second);' in the code.

Now what I've tried is creating a list of threads and I've tried implementing it below but it doesn't work, this is so I can call each individual thread if its button to clear has been clicked.

Does anyone know how I can close/stop only one single thread out of multiple that are running? If more info is needed just let me know, thanks.

```<code>public static void createIncrementingTimer(int boxNo, List<TextField> orderTimes) {
minutesList.set(boxNo, 0);
secondsList.set(boxNo, 0);
state = true;
new Thread(threadList.get(boxNo))  {
  int currentMinutes = 0;
  int currentSeconds = 0;
  public void run() {
    for (;;) {
      if (state = true) {
        try {
          sleep(1000);
          if (secondsList.get(boxNo) > 59) {
            secondsList.set(boxNo, 0);
            currentSeconds = 0;
            minutesList.set(boxNo, currentMinutes + 1);
            currentMinutes++;
          }
          if (secondsList.get(boxNo) < 10) {
            second = ":0" + Integer.toString(secondsList.get(boxNo));
          } else {
            second = ":" + Integer.toString(secondsList.get(boxNo));
          }
          secondsList.set(boxNo, currentSeconds + 1);
          currentSeconds++;
          if (minutesList.get(boxNo) < 10) {
            minute = "0" + Integer.toString(minutesList.get(boxNo));
          } else {
            minute = Integer.toString(minutesList.get(boxNo));
          }
          orderTimes.get(boxNo).setText(minute + second);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
};
threadList.get(boxNo).start();
}
</code>```

The code I'm using to clear the textfields is below, with orderTimes being the list of textFields that I'm trying to clear.

```<code>public static void eraseBox(int clickedButtonNumber, List<TextArea> orderContentsList, List<TextField> tableNumbers, List<TextField> orderNumbers, List<TextField> orderTimes) {
orderContentsList.get(clickedButtonNumber).setText(null);
  tableNumbers.get(clickedButtonNumber).clear();
  orderNumbers.get(clickedButtonNumber).clear();
  orderTimes.get(clickedButtonNumber).clear();
}
</code>```

答:
The if(state=true) should rather be if(state==true) or just if(state), but in fact the for(;;) could do the entire thing as while(state), simply shutting down the thread when you set state=false.

Then, fully stopping the thread could happen as state=false;threadList.get(boxNo).join();, and you can clear the field only after that (since the thread will set it to something in the last step too).

With a simpler approach you could throw away the state, and revert to for(;;), with the twist of having the try-catch() around the loop, outside. This way you can use threadList.get(boxNo).interrupt();threadList.get(boxNo);.join(); to stop the thread, and on top of that it will be immediate, as the sleep() ends immediately when the thread is interrupted.

Body:
So im trying to stop a single thread when I have multiple threads running, here is the code im using to initialise the threads. Basically I have multiple textFields in javafx, and when a button is clicked on the screen, it fills the textFields, one by one, with an incrementing timer. Now I also have a button for each of the textfields to clear it, but the problem is when I clear it, because the thread is still running, the timer vanishes for a second and comes back because of the line 'orderTimes.get(boxNo).setText(minute + second);' in the code.

Now what I've tried is creating a list of threads and I've tried implementing it below but it doesn't work, this is so I can call each individual thread if its button to clear has been clicked.

Does anyone know how I can close/stop only one single thread out of multiple that are running? If more info is needed just let me know, thanks.

public static void createIncrementingTimer(int boxNo, List<TextField> orderTimes) {
minutesList.set(boxNo, 0);
secondsList.set(boxNo, 0);
state = true;
new Thread(threadList.get(boxNo))  {
  int currentMinutes = 0;
  int currentSeconds = 0;
  public void run() {
    for (;;) {
      if (state = true) {
        try {
          sleep(1000);
          if (secondsList.get(boxNo) > 59) {
            secondsList.set(boxNo, 0);
            currentSeconds = 0;
            minutesList.set(boxNo, currentMinutes + 1);
            currentMinutes++;
          }
          if (secondsList.get(boxNo) < 10) {
            second = ":0" + Integer.toString(secondsList.get(boxNo));
          } else {
            second = ":" + Integer.toString(secondsList.get(boxNo));
          }
          secondsList.set(boxNo, currentSeconds + 1);
          currentSeconds++;
          if (minutesList.get(boxNo) < 10) {
            minute = "0" + Integer.toString(minutesList.get(boxNo));
          } else {
            minute = Integer.toString(minutesList.get(boxNo));
          }
          orderTimes.get(boxNo).setText(minute + second);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
};
threadList.get(boxNo).start();
}

The code I'm using to clear the textfields is below, with orderTimes being the list of textFields that I'm trying to clear.

public static void eraseBox(int clickedButtonNumber, List<TextArea> orderContentsList, List<TextField> tableNumbers, List<TextField> orderNumbers, List<TextField> orderTimes) {
orderContentsList.get(clickedButtonNumber).setText(null);
  tableNumbers.get(clickedButtonNumber).clear();
  orderNumbers.get(clickedButtonNumber).clear();
  orderTimes.get(clickedButtonNumber).clear();
}


问:
How to remove AST nodes with pycparser?
Let's start by considering this snippet:

```<code>import sys

from pycparser import c_parser, c_ast, c_generator

text = r"""
void main() {
    foo(1,3);

    foo1(4);

    x = 1;

     foo2(4,

        10,

        3);
    foo3(
        "xxx"

    );
}
"""

class FuncCallVisitor(c_ast.NodeVisitor):

    def visit_FuncCall(self, node):
        print('%s called at %s' % (node.name.name, node.name.coord))

        if node.args:
            self.visit(node.args)

class RemoveFuncCalls(c_generator.CGenerator):

    def visit_FuncCall(self, n):
        # fref = self._parenthesize_unless_simple(n.name)
        # return fref + '(' + self.visit(n.args) + ')'
        return ""

if __name__ == '__main__':
    parser = c_parser.CParser()
    ast = parser.parse(text)
    v = FuncCallVisitor()
    v.visit(ast)
    print('-' * 80)

    ast.show(showcoord=True)
    generator = RemoveFuncCalls()

    print('-' * 80)
    print(generator.visit(ast))
</code>```

The output of the above will be:

```<code>void main()
{
  ;
  ;
  x = 1;
  ;
  ;
}
</code>```

But I'd like it to become this instead:

```<code>void main()
{
  x = 1;
}
</code>```

So my question is, what's the canonical/idiomatic way to delete nodes/subtrees from the AST with pycparser?

答:
It looks like c_generator.CGenerator calls _generate_stmt method for scope-like structures which appends ';\n' (with indentation) to result of visit for statement even if it is an empty string.

To remove function calls we can overload it like

class RemoveFuncCalls(c_generator.CGenerator):
    def _generate_stmt(self, n, add_indent=False):
        if isinstance(n, c_ast.FuncCall):
            return ''
        else:
            return super()._generate_stmt(n, add_indent)
```

<p>with that</p>

<pre class="lang-py prettyprint-override"><code>void main()
{
  x = 1;
}
</code>```

which looks like what you want.

Let's consider a case

if (bar(42, "something"))
    return;
```

<p>if we need it to become</p>

<pre class="lang-c prettyprint-override"><code>if ()
    return;
</code>```

then we need to add

    def visit_FuncCall(self, n):
        return ''
```

<p>like in OP, because <code>_generate_stmt</code> isn't called by <code>RemoveFuncCalls.visit_If</code> method for <code>cond</code> field serialization.</p>

<h1>Going further</h1>

<p>I don't know what "canonical/idiomatic way to delete nodes/subtrees from the AST with pycparser", but I do know one for <code>ast</code> module from stdlib -- <code>ast.NodeTransformer</code> class (which is absent in <code>pycparser</code> for some reason).</p>

<p>It will allow us to avoid messing with how AST is serialized to <code>str</code> by overriding private'ish methods and modify AST itself</p>

<pre class="lang-py prettyprint-override"><code>from pycparser import c_ast

class NodeTransformer(c_ast.NodeVisitor):
    def generic_visit(self, node):
        for field, old_value in iter_fields(node):
            if isinstance(old_value, list):
                new_values = []
                for value in old_value:
                    if isinstance(value, c_ast.Node):
                        value = self.visit(value)
                        if value is None:
                            continue
                        elif not isinstance(value, c_ast.Node):
                            new_values.extend(value)
                            continue
                    new_values.append(value)
                old_value[:] = new_values
            elif isinstance(old_value, c_ast.Node):
                new_node = self.visit(old_value)
                setattr(node, field, new_node)
        return node

def iter_fields(node):
    # this doesn't look pretty because `pycparser` decided to have structure
    # for AST node classes different from stdlib ones
    index = 0
    children = node.children()
    while index < len(children):
        name, child = children[index]
        try:
            bracket_index = name.index('[')
        except ValueError:
            yield name, child
            index += 1
        else:
            name = name[:bracket_index]
            child = getattr(node, name)
            index += len(child)
            yield name, child
</code>```

and for our case it can be simply subclassed

class FuncCallsRemover(NodeTransformer):
    def visit_FuncCall(self, node):
        return None
```

<p>and used like</p>

<pre class="lang-py prettyprint-override"><code>...
ast = parser.parse(text)
v = FuncCallsRemover()
ast = v.visit(ast)  # note that `NodeTransformer` returns modified AST instead of `None`
</code>```

after that we can use unmodified c_generator.CGenerator instance and get the same result.

Title: How to remove AST nodes with pycparser?

Body:
Let's start by considering this snippet:

import sys

from pycparser import c_parser, c_ast, c_generator

text = r"""
void main() {
    foo(1,3);

    foo1(4);

    x = 1;

     foo2(4,

        10,

        3);
    foo3(
        "xxx"

    );
}
"""

class FuncCallVisitor(c_ast.NodeVisitor):

    def visit_FuncCall(self, node):
        print('%s called at %s' % (node.name.name, node.name.coord))

        if node.args:
            self.visit(node.args)

class RemoveFuncCalls(c_generator.CGenerator):

    def visit_FuncCall(self, n):
        # fref = self._parenthesize_unless_simple(n.name)
        # return fref + '(' + self.visit(n.args) + ')'
        return ""

if __name__ == '__main__':
    parser = c_parser.CParser()
    ast = parser.parse(text)
    v = FuncCallVisitor()
    v.visit(ast)
    print('-' * 80)

    ast.show(showcoord=True)
    generator = RemoveFuncCalls()

    print('-' * 80)
    print(generator.visit(ast))

The output of the above will be:

void main()
{
  ;
  ;
  x = 1;
  ;
  ;
}

But I'd like it to become this instead:

void main()
{
  x = 1;
}

So my question is, what's the canonical/idiomatic way to delete nodes/subtrees from the AST with pycparser?

Body:
It looks like c_generator.CGenerator calls _generate_stmt method for scope-like structures which appends ';\n' (with indentation) to result of visit for statement even if it is an empty string.

To remove function calls we can overload it like

class RemoveFuncCalls(c_generator.CGenerator):
    def _generate_stmt(self, n, add_indent=False):
        if isinstance(n, c_ast.FuncCall):
            return ''
        else:
            return super()._generate_stmt(n, add_indent)

with that

void main()
{
  x = 1;
}

which looks like what you want.

Let's consider a case

if (bar(42, "something"))
    return;

if we need it to become

if ()
    return;

then we need to add

    def visit_FuncCall(self, n):
        return ''

like in OP, because _generate_stmt isn't called by RemoveFuncCalls.visit_If method for cond field serialization.

Going further

I don't know what "canonical/idiomatic way to delete nodes/subtrees from the AST with pycparser", but I do know one for ast module from stdlib -- ast.NodeTransformer class (which is absent in pycparser for some reason).

It will allow us to avoid messing with how AST is serialized to str by overriding private'ish methods and modify AST itself

from pycparser import c_ast

class NodeTransformer(c_ast.NodeVisitor):
    def generic_visit(self, node):
        for field, old_value in iter_fields(node):
            if isinstance(old_value, list):
                new_values = []
                for value in old_value:
                    if isinstance(value, c_ast.Node):
                        value = self.visit(value)
                        if value is None:
                            continue
                        elif not isinstance(value, c_ast.Node):
                            new_values.extend(value)
                            continue
                    new_values.append(value)
                old_value[:] = new_values
            elif isinstance(old_value, c_ast.Node):
                new_node = self.visit(old_value)
                setattr(node, field, new_node)
        return node

def iter_fields(node):
    # this doesn't look pretty because `pycparser` decided to have structure
    # for AST node classes different from stdlib ones
    index = 0
    children = node.children()
    while index < len(children):
        name, child = children[index]
        try:
            bracket_index = name.index('[')
        except ValueError:
            yield name, child
            index += 1
        else:
            name = name[:bracket_index]
            child = getattr(node, name)
            index += len(child)
            yield name, child

and for our case it can be simply subclassed

class FuncCallsRemover(NodeTransformer):
    def visit_FuncCall(self, node):
        return None

and used like

...
ast = parser.parse(text)
v = FuncCallsRemover()
ast = v.visit(ast)  # note that `NodeTransformer` returns modified AST instead of `None`

after that we can use unmodified c_generator.CGenerator instance and get the same result.


问:
How to write to a file name defined at runtime?
I want to write to a gs file but I don’t know the file name at compile time. Its name is based on behavior that is defined at runtime. How can I proceed?</p>

答:
I know this is a bit of an old question but I struggled with the examples in the documentation.

Here is a simple example of how to split files based on dict items.

```<code>pipeline_options = PipelineOptions()
pipeline_options.view_as(SetupOptions).save_main_session = False

def file_names(*args):
    file_name = fileio.destination_prefix_naming()(*args)
    destination, *_ = file_name.split("----")
    return f"{destination}.json"

class JsonSink(fileio.TextSink):
    def write(self, element):
        record = json.loads(element)
        record.pop("id")
        self._fh.write(json.dumps(record).encode("utf8"))
        self._fh.write("\n".encode("utf8"))

def destination(element):
    return json.loads(element)["id"]

with beam.Pipeline(options=pipeline_options) as p:

    data = [
        {"id": 0, "message": "whhhhhhyyyyyyy"},
        {"id": 1, "message": "world"},
        {"id": 1, "message": "hi there!"},
        {"id": 1, "message": "what's up!!!?!?!!?"},
    ]

    (
        p
        | "CreateEmails" >> beam.Create(data)
        | "JSONify" >> beam.Map(json.dumps)
        | "Write Files"
        >> fileio.WriteToFiles(
            path="path/",
            destination=destination,
            sink=lambda dest: JsonSink(),
            file_naming=file_names,
        )
    )
</code>```

Body:
I know this is a bit of an old question but I struggled with the examples in the documentation.

Here is a simple example of how to split files based on dict items.

pipeline_options = PipelineOptions()
pipeline_options.view_as(SetupOptions).save_main_session = False

def file_names(*args):
    file_name = fileio.destination_prefix_naming()(*args)
    destination, *_ = file_name.split("----")
    return f"{destination}.json"

class JsonSink(fileio.TextSink):
    def write(self, element):
        record = json.loads(element)
        record.pop("id")
        self._fh.write(json.dumps(record).encode("utf8"))
        self._fh.write("\n".encode("utf8"))

def destination(element):
    return json.loads(element)["id"]

with beam.Pipeline(options=pipeline_options) as p:

    data = [
        {"id": 0, "message": "whhhhhhyyyyyyy"},
        {"id": 1, "message": "world"},
        {"id": 1, "message": "hi there!"},
        {"id": 1, "message": "what's up!!!?!?!!?"},
    ]

    (
        p
        | "CreateEmails" >> beam.Create(data)
        | "JSONify" >> beam.Map(json.dumps)
        | "Write Files"
        >> fileio.WriteToFiles(
            path="path/",
            destination=destination,
            sink=lambda dest: JsonSink(),
            file_naming=file_names,
        )
    )


问:
When do I use if/endif versus If{}?
Well the question is self explanatory.

In PHP when do I use the if/endif notation instead of the standard if(something){} notation?

Example:

```<code><?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>
</code>```

Versus:

```<code><?php if($a == 5){ ?>
A is equal to 5
<?php } ?>
</code>```

答:
Short answer:

Always use if($something) { } and pretty much never use if/endif. It's standard since PHP 4.0.0 and while the old syntax is not going away this is the one everybody expects.

If you are really looking for a case where you can use if/endif then it's when using php as a template language.

Some people like something like this:

```<code><?php if ($foo): ?>
Hi There
<?php else: ?>
cya!
<?php endif; ?>
</code>```

better than

```<code><?php if ($foo) { ?>
Hi There
<?php } else { ?>
cya!
<?php } ?>
</code>```

and imho it is because every line "speaks" and that can be helpful when there is a lot of html inbetween the php tags.

Title: When do I use if/endif versus If{}?

Body:
Well the question is self explanatory.

In PHP when do I use the if/endif notation instead of the standard if(something){} notation?

Example:

<?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>

Versus:

<?php if($a == 5){ ?>
A is equal to 5
<?php } ?>

Body:
Short answer:

Always use if($something) { } and pretty much never use if/endif. It's standard since PHP 4.0.0 and while the old syntax is not going away this is the one everybody expects.

If you are really looking for a case where you can use if/endif then it's when using php as a template language.

Some people like something like this:

<?php if ($foo): ?>
Hi There
<?php else: ?>
cya!
<?php endif; ?>

better than

<?php if ($foo) { ?>
Hi There
<?php } else { ?>
cya!
<?php } ?>

and imho it is because every line "speaks" and that can be helpful when there is a lot of html inbetween the php tags.


问:
Selecting from 2 tables at one time in node js
I want to select all the patrols and select all the users from the database. But I got an error and I'm not sure why is it even an error.

The code that I wrote

```<code>connection.query("SELECT * FROM patrols; SELECT * FROM user", function (err, result, field){
    if (err){
         return console.log('error: ' + err.message);
    }

    res.render('patrol_schedule', {result: result, name: name});
});
</code>```

The error message

```<code> ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM user' at line 1
</code>```

答:
You can't do two queries in one call to connection.query(). Do the second query in the callback function of the first.

```<code>connection.query("SELECT * FROM patrols", function(err, patrol_result) {
  if (err) {
    return console.log('error: ' + err.message);
  }
  connection.query("SELECT * FROM user", function(err, user_result) {
    if (err) {
      return console.log('error: ' + err.message);
    }
    res.render('patrol_schedule', {
      patrol: patrol_result,
      user: user_result
    });
  });
});
</code>```

Body:
I want to select all the patrols and select all the users from the database. But I got an error and I'm not sure why is it even an error.

The code that I wrote

connection.query("SELECT * FROM patrols; SELECT * FROM user", function (err, result, field){
    if (err){
         return console.log('error: ' + err.message);
    }

    res.render('patrol_schedule', {result: result, name: name});
});

The error message

 ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM user' at line 1

Body:
You can't do two queries in one call to connection.query(). Do the second query in the callback function of the first.

connection.query("SELECT * FROM patrols", function(err, patrol_result) {
  if (err) {
    return console.log('error: ' + err.message);
  }
  connection.query("SELECT * FROM user", function(err, user_result) {
    if (err) {
      return console.log('error: ' + err.message);
    }
    res.render('patrol_schedule', {
      patrol: patrol_result,
      user: user_result
    });
  });
});


答:
Probably we should know more about your usingObject implementation, but the following worked for me:

```<code>function usingVal(val: Pick<A, 'val'>) {
  return usingObject(val)
}
</code>```

Title: Typescript Pick issues

Body:
My simplified code block is like the following

interface A {
    val: string;
    // Other optional parameters
}

function usingObject(obj: A) {
    return obj.val
}

function usingVal(val: Pick) {
    return usingObject({ val })
}

i am getting the following error

Type 'Pick' is not assignable to type 'string'.ts(2322)

I want a function which can accept object and other function which take each mandatory parameter as an argument

Body:
Probably we should know more about your usingObject implementation, but the following worked for me:

function usingVal(val: Pick<A, 'val'>) {
  return usingObject(val)
}


问:
Angular 8: Nested Reactive Form in sub-component not working
I'm using Angular 8 Nested Reactive Form in a child component, but it does not work. I have searched the official Angular documentation, but I can not find any example on this.

My solution is available at stackblitz.com. I'm unable to show companyName for each company and address details for each address. Any ideas?

According to Kara Ericksons talk about “Angular Forms” at the Angular Connect 2017 it should be straight forward...

Her video Nested Forms in Angular between 35:31-36:51

In parent.component.html

```<code><form [formGroup]="form">

    <div *ngFor="let address of addresses">
        <app-child [address]="address"></app-child>
    </div>

    <button type="submit">Save</button>

</form>
</code>```

In parent.component.ts

```<code>export class ParentComponent implements OnInit {

  form = new FormGroup({});

  addresses : Address[] = [
    new Address("Street 1", "City 1"),
    new Address("Street 2", "City 2"),
    new Address("Street 3", "City 3"),
  ]

  constructor() { }

  ngOnInit() {
  }
}

</code>```

In child.component.html

```<code><div formGroupName="address">

     <input formControlName="street">
     <input formControlName="city">

</div>

</code>```

In child.component.ts

```<code>@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.less']
})
export class ChildComponent implements OnInit {

  @Input() address: Address;
  form: FormGroup;

  constructor(parent: FormGroupDirective) {
    this.form = parent.form;
  }

  ngOnInit() {
    this.form.addControl('address', new FormGroup({
      street: new FormControl()
      city: new FormControl()

    }));
  }
}

</code>```

答:
Try passing your formGroup as input instead of using the constructor into the child component.

```<code>@Input() formGroup: FormGroup;
</code>```

instead of

```<code>constructor(parent: FormGroupDirective) {
  this.form = parent.form;
}
</code>```

Edited 02/15/2020

I changed some code and solved your issue. The solution is available here: https://stackblitz.com/edit/angular-vyaj57-kgkdih

Body:
I'm using Angular 8 Nested Reactive Form in a child component, but it does not work. I have searched the official Angular documentation, but I can not find any example on this.

My solution is available at stackblitz.com. I'm unable to show companyName for each company and address details for each address. Any ideas?

According to Kara Ericksons talk about “Angular Forms” at the Angular Connect 2017 it should be straight forward...

Her video Nested Forms in Angular between 35:31-36:51

In parent.component.html

<form [formGroup]="form">

        <app-child [address]="address"></app-child>

    <button type="submit">Save</button>

</form>

In parent.component.ts

export class ParentComponent implements OnInit {

  form = new FormGroup({});

  addresses : Address[] = [
    new Address("Street 1", "City 1"),
    new Address("Street 2", "City 2"),
    new Address("Street 3", "City 3"),
  ]

  constructor() { }

  ngOnInit() {
  }
}

In child.component.html

     <input formControlName="street">
     <input formControlName="city">

In child.component.ts

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.less']
})
export class ChildComponent implements OnInit {

  @Input() address: Address;
  form: FormGroup;

  constructor(parent: FormGroupDirective) {
    this.form = parent.form;
  }

  ngOnInit() {
    this.form.addControl('address', new FormGroup({
      street: new FormControl()
      city: new FormControl()

    }));
  }
}

Body:
Try passing your formGroup as input instead of using the constructor into the child component.

@Input() formGroup: FormGroup;

instead of

constructor(parent: FormGroupDirective) {
  this.form = parent.form;
}

Edited 02/15/2020

I changed some code and solved your issue. The solution is available here: https://stackblitz.com/edit/angular-vyaj57-kgkdih


问:
How to create a loop 1M with random numbers >100000
My teacher asked me to create a loop that will be executed 1M times.
I tried for(long i=0;i<1000000;i++), but the program is crashing. The maximum number that the program accepts is 10.000.

Any ideas? Is this possible?

Also he asked me to create a random number >100.000. I am using rand();. Should I use a different method?

this is the code:

```<code>start_time = clock();
for(long i=0;i<1000000;i++){
   num1 = rand();
   num2=rand();
   gcd1(num1,num2);
}

end_time = clock();

elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

printf( "time is %.3f seconds\n", elapsed_time );
system("pause");
</code>```

This the gcd:

```<code>int gcd1(int x, int y){
    int z;
    if (x<y)
        z=x+1;
    else if (y<x)
        z=y+1;
    do{
        z=z-1;
    }
    while((x%z!=0) or (y%z!=0));
        return z;
    }
}
</code>```

答:
Try one of the following:

Step through the code in the debugger to find which line is crashing.

Comment out lines in the loop (and after it) until it runs. Then uncomment things one by one to track down the culprit.

One suspcious thing I see off the bat: What type is elapsed_time declared as? You are doing what looks like integer (or quadword integer?) math on it, and then you tell printf to print it as a float. printf doesn't do intelligent type conversions for you or anything. If you feed it a variable of the wrong type, you are liable to get garbage, or a crash.

Body:
My teacher asked me to create a loop that will be executed 1M times.
I tried for(long i=0;i<1000000;i++), but the program is crashing. The maximum number that the program accepts is 10.000.

Any ideas? Is this possible?

Also he asked me to create a random number >100.000. I am using rand();. Should I use a different method?

this is the code:

start_time = clock();
for(long i=0;i<1000000;i++){
   num1 = rand();
   num2=rand();
   gcd1(num1,num2);
}

end_time = clock();

elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

printf( "time is %.3f seconds\n", elapsed_time );
system("pause");

This the gcd:

int gcd1(int x, int y){
    int z;
    if (x<y)
        z=x+1;
    else if (y<x)
        z=y+1;
    do{
        z=z-1;
    }
    while((x%z!=0) or (y%z!=0));
        return z;
    }
}