问:
Is it normal to have regular model for GET and "flat" model for POST from Design REST point of view?
The questions about possibility to have different models for POST and GET methods in REST api have been asked several times but I would like to clarify one specific moment.
Suppose we are designing api about sport competition.

Models and corresponding resources:

```<code>1) Player
{  "id" : 2,
   "firstName" : "Nikolay",
   "lastName": "Grigoryan",
   .....
}
</code>```

/players/2

2) Tournament

```<code>{ "id" 1,
  "name": "Some tournament",
  "date" "01.02.2019",
  .......
}
</code>```

/tournaments/1

3) Participant

```<code>{
  "id": 2,
   "tournament": { "id" 1,
      "name": "Some tournament",
      "date" "01.02.2019",
      .......
    },
   "player": {  "id" : 2,
     "firstName" : "Nikolay",
     "lastName": "Grigoryan",
     .....
   }
}
</code>```

/tournament/1/participants/2

When I'm requesting the participants of the certain tournament it's convinient enough to have a separate field by name player containg full nested Player model whith all available fields. But when I'm creating a new participant the situation looks different for me. I would prefer to have just playerId to provide as POST body:

/tournament/1/participants

POST

```<code>{
  ....,
  playerId: 2,
  .....
}
</code>```

but not

```<code>{
  ....,
  "player": {
    "id": 2,
   ....
  }
}
</code>```

It seems no need to have nested model here but instead only playerId is enough and by this reason no need to have nested object only for holding id at all.

Is it ok to have such simplification of model for POST request or they should be of the same structure? Probably I miss something important by doing such conclusion. If so I would be grateful for explanation what exactly it is.

Thanks in advance.

答:
One approach to at least take inspiration of is to look at HAL.

If a tournament has players, and this is a many-to-many relation it might make sense for players to be associated to a tournament via a link.

To get a list of players, you would simply embed the player resources.

To identify players, you don't use their id, you use their url.

To associate players to a tournament, you could update the links.

As an aside I think that having models that are identical for both receiving (GET) and sending (POST) is a very nice property and makes things easier to understand, but it's also completely fine to abandon this rule where appropriate. I find that especially the situation where people often need a different approach is the case where multiple resources / models are associated with each other. There's not one elegant way to solve this, but using links instead of id's might give you some tools to solve this in a general manner that is applicable everywhere.

Body:
The questions about possibility to have different models for POST and GET methods in REST api have been asked several times but I would like to clarify one specific moment.
Suppose we are designing api about sport competition.

Models and corresponding resources:

1) Player
{  "id" : 2,
   "firstName" : "Nikolay",
   "lastName": "Grigoryan",
   .....
}

/players/2

2) Tournament

{ "id" 1,
  "name": "Some tournament",
  "date" "01.02.2019",
  .......
}

/tournaments/1

3) Participant

{
  "id": 2,
   "tournament": { "id" 1,
      "name": "Some tournament",
      "date" "01.02.2019",
      .......
    },
   "player": {  "id" : 2,
     "firstName" : "Nikolay",
     "lastName": "Grigoryan",
     .....
   }
}

/tournament/1/participants/2

When I'm requesting the participants of the certain tournament it's convinient enough to have a separate field by name player containg full nested Player model whith all available fields. But when I'm creating a new participant the situation looks different for me. I would prefer to have just playerId to provide as POST body:

/tournament/1/participants

POST

{
  ....,
  playerId: 2,
  .....
}

but not

{
  ....,
  "player": {
    "id": 2,
   ....
  }
}

It seems no need to have nested model here but instead only playerId is enough and by this reason no need to have nested object only for holding id at all.

Is it ok to have such simplification of model for POST request or they should be of the same structure? Probably I miss something important by doing such conclusion. If so I would be grateful for explanation what exactly it is.

Thanks in advance.


来源: stackexchange

问:
Output formatting using setw and setfill
I'm trying to get the following output using setw and setfill:

```<code>OPTIONS:
    <expression>
       The usual operators +, -, *, / and % (remainder)
       Expressions are fixed-point decimal numbers, and
       Parentheses () and corchetes {} may be used for grouping.
</code>```

I'm trying like this:

```<code>    cout << "OPTIONS:" << '\n';
    cout << "\t<expression>\n";
    cout << '\t' << setw(3) << setfill(' ') << "The usual operators +, -, *, / and % (remainder)\n";
    cout << '\t' << setw(3) << setfill(' ') << "Expressions are fixed-point decimal numbers, and\n";
    cout << '\t' << setw(3) << setfill(' ') << "Parentheses () and corchetes {} may be used for grouping.\n\n";
</code>```

答:
std::setw is a great tool for printing data with varying length in a table format. You specify the width of a column and spaces will get filled in automatically until the specified column width is reached. However, if you need a fixed number of spaces it's easier to hard code them: cout << "   ". If you need the same indentation many times you might want to define this as a constant

```<code>auto indent = string(3, ' ');
cout << indent << ...;
</code>```

This allows you to easily adjust the indentation later if needed.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get the following output using setw and setfill:

OPTIONS:
    <expression>
       The usual operators +, -, *, / and % (remainder)
       Expressions are fixed-point decimal numbers, and
       Parentheses () and corchetes {} may be used for grouping.

I'm trying like this:

    cout << "OPTIONS:" << '\n';
    cout << "\t<expression>\n";
    cout << '\t' << setw(3) << setfill(' ') << "The usual operators +, -, *, / and % (remainder)\n";
    cout << '\t' << setw(3) << setfill(' ') << "Expressions are fixed-point decimal numbers, and\n";
    cout << '\t' << setw(3) << setfill(' ') << "Parentheses () and corchetes {} may be used for grouping.\n\n";

Body:
std::setw is a great tool for printing data with varying length in a table format. You specify the width of a column and spaces will get filled in automatically until the specified column width is reached. However, if you need a fixed number of spaces it's easier to hard code them: cout << "   ". If you need the same indentation many times you might want to define this as a constant

auto indent = string(3, ' ');
cout << indent << ...;

This allows you to easily adjust the indentation later if needed.


问:
HTML Forwarding
So I've been playing around with some simple HTML forwarding with c++. Haven't accomplished much and I have some questions on the backbone.

First: Do I need to use any special libraries other than socket libraries to simply forward HTML data and connections?

Second: When a client connects to an HTML server, is the TCP connection kept open? Or is it closed once data is sent?

Third: When I forward data, from a client to the server, the packet includes the destination address. I should technically be able to read this address and connect to the server via port 80, keep it open, and send and receive on that newly opened port right? Is there anything I have to do? Any time constraints? If I directly forward every single packet directly between the client and server the website should show up correctly on the client, correct?

I would prefer to keep any external libs to a minimum. But if necessary I can expand the program to include any required libraries.

So far I've gotten data to and from both parties, however the website does not function.

[platform] :: windows.primary && posix_compliant.secondary

答:
First: No you do not need other special libraries but not using any that are available would to some extent be reinventing the wheel.

Second: No, HTTP is a connectionless protocol.

Third: An HTTP session begins with a request header, which in your case sounds like a POST. A POST may take more than one package, during which time the connection remains open. The server may well time you out.

You might look at libCURL even if you do not intend using it. (The source for that is in C, and is rather monolithic but it is commonly used).

ContentLicense: CC BY-SA 3.0

Title: HTML Forwarding


问:
How to convert a wav file into RGB image with melspectogram?
I am working on sound classification with wav files ranging from 1 second to 4 second.
i want to convert wav to 224x224x3 image that i can fee into Resnet for classification
The conversion should be using melspectogram
Thanks for help

答:
You can use librosa to produce mel spectrogram like this:

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

y, sr = librosa.load(librosa.util.example_audio_file()) # your file
S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128, fmax=8000)
librosa.display.specshow(librosa.power_to_db(S, ref=np.max), fmax=8000)
plt.savefig('mel.png')
</code>```

Mind though that these are false colours, RGB does not make sense here - nor any multi-channel. Use architecture that works with a single channel.

Body:
You can use librosa to produce mel spectrogram like this:

import librosa
import librosa.display
import numpy as np
import matplotlib.pyplot as plt

y, sr = librosa.load(librosa.util.example_audio_file()) # your file
S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128, fmax=8000)
librosa.display.specshow(librosa.power_to_db(S, ref=np.max), fmax=8000)
plt.savefig('mel.png')

Mind though that these are false colours, RGB does not make sense here - nor any multi-channel. Use architecture that works with a single channel.


问:
Using sed to split a file by a sequence. bash
I want to cut a 211,548,559 lines file into 10 smaller files. So, the first file, for example will have 1st to 21154856th line

I would like to write a for loop with a seq that allows me to automatize the process.

I tried to create a function first and then a loop with seq.

run_sed(){
    sed -n $1p Bar08_depth_chr1.txt > Bar8_d_c1_$1.txt
}
for pos in seq 1 10 211548559
do
    run_sed $pos
done
```

This script didn't work. I believe its because the $1 in sed -n 1$p But I don't know how to solve it

答:
For GNU split:

```<code>split -nl/10 --additional-suffix=.txt -d Bar08_depth_chr1.txt Bar8_d_c1_
</code>```

Which will create 10 files named Bar8_d_c1_00.txt through Bar8_d_c1_09.txt which will likely not need to be renamed.

For split under MacOS:

```<code>split -l $(( (211548559 - 9) / 10 )) Bar08_depth_chr1.txt Bar8_d_c1_
</code>```

Which will create 10 files named Bar8_d_c1_aa through Bar8_d_c1_aj which can be renamed to the name pattern you need.

The calculation shown causes the number of lines per file to be rounded up in order to avoid a very small 11th file.

Body:
I want to cut a 211,548,559 lines file into 10 smaller files. So, the first file, for example will have 1st to 21154856th line

I would like to write a for loop with a seq that allows me to automatize the process.

I tried to create a function first and then a loop with seq.

run_sed(){
    sed -n $1p Bar08_depth_chr1.txt > Bar8_d_c1_$1.txt
}
for pos in seq 1 10 211548559
do
    run_sed $pos
done

This script didn't work. I believe its because the $1 in sed -n 1$p But I don't know how to solve it

Body:
For GNU split:

split -nl/10 --additional-suffix=.txt -d Bar08_depth_chr1.txt Bar8_d_c1_

Which will create 10 files named Bar8_d_c1_00.txt through Bar8_d_c1_09.txt which will likely not need to be renamed.

For split under MacOS:

split -l $(( (211548559 - 9) / 10 )) Bar08_depth_chr1.txt Bar8_d_c1_

Which will create 10 files named Bar8_d_c1_aa through Bar8_d_c1_aj which can be renamed to the name pattern you need.

The calculation shown causes the number of lines per file to be rounded up in order to avoid a very small 11th file.


问:
How to calculate the length of JSON values in php?
I have a JSON as shown below in which I want to calculate through php how many values are present inside posts_id_en. At present, it is 7 as shown below:

```<code>{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}
</code>```

In php code on doing echo $data->{"posts_id_en"};, it displays the values as shown below:

```<code>149968, 149939, 149883, 149877, 149876, 149847, 154303
</code>```

Problem Statement:

I am wondering what php code I need to use so that we can calculate number of values entered inside posts_id_en. At this moment, it is entered 7 as shown above.

答:
```<code><?php

$json = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';
$decoded = json_decode($json, true);
$post_id = $decoded['posts_id_en'];

$resultList = [];
foreach($decoded as $key => $entry) {
    $everyNumberAsArray = explode(',', $entry);
    $count = count($everyNumberAsArray);
    $resultList[$key] = $count;
}

var_export($resultList);
</code>```

gives output:

```<code>array (
  'posts_id_en' => 7,
  'posts_id_fr' => 5,
  'episode_status' => 1,
)
</code>```

to get particular values you use them this way:

```<code>echo $resultList['posts_id_en'] . '<br>' . PHP_EOL;
</code>```

that gives you:

```<code>7
</code>```

Body:
I have a JSON as shown below in which I want to calculate through php how many values are present inside posts_id_en. At present, it is 7 as shown below:

{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}

In php code on doing echo $data->{"posts_id_en"};, it displays the values as shown below:

149968, 149939, 149883, 149877, 149876, 149847, 154303

Problem Statement:

I am wondering what php code I need to use so that we can calculate number of values entered inside posts_id_en. At this moment, it is entered 7 as shown above.

Body:
<?php

$json = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';
$decoded = json_decode($json, true);
$post_id = $decoded['posts_id_en'];

$resultList = [];
foreach($decoded as $key => $entry) {
    $everyNumberAsArray = explode(',', $entry);
    $count = count($everyNumberAsArray);
    $resultList[$key] = $count;
}

var_export($resultList);

gives output:

array (
  'posts_id_en' => 7,
  'posts_id_fr' => 5,
  'episode_status' => 1,
)

to get particular values you use them this way:

echo $resultList['posts_id_en'] . '<br>' . PHP_EOL;

that gives you:

7


问:
Error in system(command, intern = TRUE) : '“C:\Program' not found selectWeka function
I'm trying to run the code below from BioSeqClass package, however I get an error message:
Error in system(command, intern = TRUE) : '“C:\Program' not found

selectWeka(data, evaluator="CfsSubsetEval", search="BestFirst", n)

答:
This is a problem with how BioSeqClass is calling java: it is leaving the file names unprotected/unquoted, and R's system and system2 commands are horrible by not forcing quoting. (If you ever think of using these commands directly yourself, I strongly recommend something like processx.)

One should create an issue or bug-report, but I don't know how to do that with Bioconductor, and their mirror on github (https://github.com/Bioconductor-mirror) is defunct, so I'm at a loss there. Hopefully somebody with more info can weigh in on this.

Workarounds

It is not obvious if the problem is due to where weka.jar is located or perhaps one of the other arguments. You can find out where the problem is by debugging the selectWeka function and inspecting the value of command before the system call. Look for the Program Files component of a path.

If the problem is with weka.jar, then this suggests that you are installing packages somewhere under C:\Program Files\, which is in my experience bad practice on two counts:

For many problems I cannot recall (but this one re-ignites the discussion), I never install R in the default location under C:\Program Files\...; instead, I install it under a new directory, C:\R\R-3.5.3 (version-based) and go from there. You may not have control over this if on a university/company system.

Since this is not in a base-R package, this suggests that either you are not using a personal library location (collection of packages), or have placed your personal library for some reason under C:\Program Files. If the former, I strongly suggest you never install new packages inside the base-R installation directory, instead using your own. See ?.libPaths and many other tutorials/discussions on the topic online. Using packrat or checkpoint might also mitigate this problem.

If the problem is with trainFile (if I'm reading the source correctly), then your "permanent" fix is to change where Windows puts temporary files, as this trainFile is a temporary file created specifically for this function-run. If this is your problem, I'll leave it up to you to fix.

Regardless, you may not have time or need to make a more permanent solution, you just want to run this once or twice and then move on. For that fix:

Again, debug(selectWeka), and once command is defined (the next command to be executed is tmp <- system(command,intern = TRUE)), run this code to fix the value of command:

  if(search=="Ranker"){
      command = paste("java -cp ", shQuote(file.path(.path.package("BioSeqClass"), "scripts", "weka.jar")),
                      " weka.attributeSelection.", evaluator, " -i ", shQuote(trainFile),
                      " -s \"weka.attributeSelection.", search, " -N ", n, "\"", sep="" )
  }else{
      command = paste("java -cp ", shQuote(file.path(.path.package("BioSeqClass"), "scripts", "weka.jar")),
                      " weka.attributeSelection.", evaluator, " -i ", shQuote(trainFile),
                      " -s weka.attributeSelection.", search, sep="" )
  }
```

<p>(For the record, all I changed was adding <code>shQuote</code> twice to each <code>paste</code>.) Confirm that <code>command</code> now has quotes around things, something like</p>

<pre class="lang-r prettyprint-override"><code>Browse[2]> command
[1] "java -cp \"C:\\Program Files\\...\\weka.jar" weka.attributeSel... -i \"c:\\path\\to\\some\\tempfile\" ...
</code>```

Then you can continue-out of the debugger and let it run its course.

(I hope you don't have hundreds of calls to selectWeka.)

Caveat: I am not a use of BioSeqClass, so I'm saying all of this from speculation and inference. I might have mis-located the source of the error. And since I don't know what I'm doing with it, I have not tested the modified command assignment within selectWeka. I believe shQuote(...) is the right way to go, but you might need to use sQuote or dQuote instead, I'm not sure how your system is setup.

Body:
This is a problem with how BioSeqClass is calling java: it is leaving the file names unprotected/unquoted, and R's system and system2 commands are horrible by not forcing quoting. (If you ever think of using these commands directly yourself, I strongly recommend something like processx.)

One should create an issue or bug-report, but I don't know how to do that with Bioconductor, and their mirror on github (https://github.com/Bioconductor-mirror) is defunct, so I'm at a loss there. Hopefully somebody with more info can weigh in on this.

Workarounds

It is not obvious if the problem is due to where weka.jar is located or perhaps one of the other arguments. You can find out where the problem is by debugging the selectWeka function and inspecting the value of command before the system call. Look for the Program Files component of a path.

If the problem is with weka.jar, then this suggests that you are installing packages somewhere under C:\Program Files\, which is in my experience bad practice on two counts:

For many problems I cannot recall (but this one re-ignites the discussion), I never install R in the default location under C:\Program Files\...; instead, I install it under a new directory, C:\R\R-3.5.3 (version-based) and go from there. You may not have control over this if on a university/company system.

Since this is not in a base-R package, this suggests that either you are not using a personal library location (collection of packages), or have placed your personal library for some reason under C:\Program Files. If the former, I strongly suggest you never install new packages inside the base-R installation directory, instead using your own. See ?.libPaths and many other tutorials/discussions on the topic online. Using packrat or checkpoint might also mitigate this problem.

If the problem is with trainFile (if I'm reading the source correctly), then your "permanent" fix is to change where Windows puts temporary files, as this trainFile is a temporary file created specifically for this function-run. If this is your problem, I'll leave it up to you to fix.

Regardless, you may not have time or need to make a more permanent solution, you just want to run this once or twice and then move on. For that fix:

Again, debug(selectWeka), and once command is defined (the next command to be executed is tmp <- system(command,intern = TRUE)), run this code to fix the value of command:

  if(search=="Ranker"){
      command = paste("java -cp ", shQuote(file.path(.path.package("BioSeqClass"), "scripts", "weka.jar")),
                      " weka.attributeSelection.", evaluator, " -i ", shQuote(trainFile),
                      " -s \"weka.attributeSelection.", search, " -N ", n, "\"", sep="" )
  }else{
      command = paste("java -cp ", shQuote(file.path(.path.package("BioSeqClass"), "scripts", "weka.jar")),
                      " weka.attributeSelection.", evaluator, " -i ", shQuote(trainFile),
                      " -s weka.attributeSelection.", search, sep="" )
  }

(For the record, all I changed was adding shQuote twice to each paste.) Confirm that command now has quotes around things, something like

Browse[2]> command
[1] "java -cp \"C:\\Program Files\\...\\weka.jar" weka.attributeSel... -i \"c:\\path\\to\\some\\tempfile\" ...

Then you can continue-out of the debugger and let it run its course.

(I hope you don't have hundreds of calls to selectWeka.)

Caveat: I am not a use of BioSeqClass, so I'm saying all of this from speculation and inference. I might have mis-located the source of the error. And since I don't know what I'm doing with it, I have not tested the modified command assignment within selectWeka. I believe shQuote(...) is the right way to go, but you might need to use sQuote or dQuote instead, I'm not sure how your system is setup.


问:
Why does my input element drop a line when i use Float:left
I have used a CSS style sheet for W3 schools which defines columns of 25% and 75%.  I wanted to add two more column types of 10% and 65%

I copied the .col-25 class and renamed it .col-10 and adjusted the width to 10%

When I add this class to an input field the resulting form displays the input on the next line down and 100% wide

Can anyone explain what I have done wrong?

```<code>@charset "utf-8";
/* CSS Document */

input.invalid, textarea.invalid, select.invalid
{
    background-color: #ffdddd;
}

/* Style inputs, select elements and textareas */
input[type=text], select, textarea{
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  resize: vertical;
}

/* Style the label to display next to the inputs */
label {
  padding: 12px 12px 12px 0;
  display: inline-block;
  vertical-align: right;
}

/* Style the submit button */
input[type=submit] {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  float: right;
}

.my-button{
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  float: right;
}

/* Style the container */
.container {
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 20px;
}

/* Floating column for labels: 25% width */
.col-25 {
  float: left;
  width: 25%;
  margin-top: 6px;
  text-align: right;
}

/* Floating column for inputs: 75% width */
.col-75 {
  float: left;
  width: 75%;
  margin-top: 6px;
}

/* Floating column for inputs: 10% width added by Malcolm but will not     display correctly */
.col-10 {
  float: left;
  width: 10%;
  margin-top: 6px;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Responsive layout - when the screen is less than 600px wide, make the two columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
  .col-10, .col-25, .col-75, input[type=submit] {
    width: 100%;
    margin-top: 0;
  }
}
</code>```

```<code><body>
GOODS RECEIPT NOTE
<div class="container">
  <form name="f1" id = "f1" >
    <div class="row">
      <div class="col-25">
        <label for="haulier">Customer : </label>
      </div>
      <div class="col-75">
        <input type="text" id="customer" name="customer" placeholder="Customer name">
      </div>
    </div>

    <div class="row">
      <div class="col-25">
        <label for="haulier">Haulier : </label>
      </div>
      <div class="col-75">
        <input type="text" id="haulier" name="haulier" placeholder="Haulier name">
      </div>
    </div>

     <div class="row">
      <div class="col-25">
        <label for="vehicle_registration">Vehicle registration : </label>
      </div>
      <div class="col-75">
        <input type="text" id="vehicle_registration" name="vehicle_registration" placeholder="Vehicle registration">
      </div>
    </div>

     <div class="row">
      <div class="col-25">
        <label for="airwaybill">Airwaybill : </label>
      </div>
      <div class="col-10">
        <input type="text" id="Pfx" name="awb_pfx" placeholder="Pfx">
      </div>
      <div class="col-25">
        <input type="text" id="airwaybill" name="airwaybill" placeholder="Airwaybill number">
      </div>
    </div>

     <div class="row">
      <div class="col-25">
        <label for="shipper">Shipper : </label>
      </div>
      <div class="col-75">
        <input type="text" id="shipper" name="shipper" placeholder="Shipper name">
      </div>
    </div>

     <div class="row">
      <div class="col-25">
        <label for="consignee">Consignee : </label>
      </div>
      <div class="col-75">
        <input type="text" id="consignee" name="consignee" placeholder="Consignee name">
      </div>
    </div>

     <div class="row">
      <div class="col-25">
        <label for="destination">Destination : </label>
      </div>
      <div class="col-75">
        <input type="text" id="destination" name="destination" placeholder="Consignment destination">
      </div>
    </div>

      <div class="row">
      <div class="col-25">
        <label for="pieces">Pieces : </label>
      </div>
      <div class="col-75">
        <input type="text" id="pieces" name="pieces" placeholder="Number of pieces">
      </div>
    </div>

    <div class="row">
      <div class="col-25">
        <label for="documents">Documents : </label>
      </div>
      <div class="col-75">
        <select id="documents" name="documents">
          <option value="">Please select</option>
          <option value="yes">Yes</option>
          <option value="no">No</option>
        </select>
      </div>
    </div>

    <div class="row">
      <div class="col-25">
        <label for="subject">Comments : </label>
      </div>
      <div class="col-75">
        <textarea id="comments" name="comments" style="height:100px"></textarea>
      </div>
    </div>

    <div class="row">
      <div class="col-25">

      </div>
      <div class="col-75">
<input type="button" class="my-button" name="btn_grn" id="btn_grn" value="Create goods receipt note">
      </div>
    </div>
    </form>
</div>
<div id="errors"></div>

<div id="dialog-confirm" title="Print GRN & labels">

</div>

</body>
</code>```

答: Not sure I see the issue here.  I copied your code to this Codepen and it looks to be working as expected.  The only change I made was creating/adding a .col-65 class as you mentioned to the input next to the 10% width one, and everything is responsive and taking up one line.  Is that not the result you're looking for?

Body:
I have used a CSS style sheet for W3 schools which defines columns of 25% and 75%.  I wanted to add two more column types of 10% and 65%

I copied the .col-25 class and renamed it .col-10 and adjusted the width to 10%

When I add this class to an input field the resulting form displays the input on the next line down and 100% wide

Can anyone explain what I have done wrong?

@charset "utf-8";
/* CSS Document */

input.invalid, textarea.invalid, select.invalid
{
    background-color: #ffdddd;
}

/* Style inputs, select elements and textareas */
input[type=text], select, textarea{
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  resize: vertical;
}

/* Style the label to display next to the inputs */
label {
  padding: 12px 12px 12px 0;
  display: inline-block;
  vertical-align: right;
}

/* Style the submit button */
input[type=submit] {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  float: right;
}

.my-button{
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  float: right;
}

/* Style the container */
.container {
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 20px;
}

/* Floating column for labels: 25% width */
.col-25 {
  float: left;
  width: 25%;
  margin-top: 6px;
  text-align: right;
}

/* Floating column for inputs: 75% width */
.col-75 {
  float: left;
  width: 75%;
  margin-top: 6px;
}

/* Floating column for inputs: 10% width added by Malcolm but will not     display correctly */
.col-10 {
  float: left;
  width: 10%;
  margin-top: 6px;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Responsive layout - when the screen is less than 600px wide, make the two columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
  .col-10, .col-25, .col-75, input[type=submit] {
    width: 100%;
    margin-top: 0;
  }
}

GOODS RECEIPT NOTE

  <form name="f1" id = "f1" >

        Customer :

        <input type="text" id="customer" name="customer" placeholder="Customer name">

        Haulier :

        <input type="text" id="haulier" name="haulier" placeholder="Haulier name">

        Vehicle registration :

        <input type="text" id="vehicle_registration" name="vehicle_registration" placeholder="Vehicle registration">

        Airwaybill :

        <input type="text" id="Pfx" name="awb_pfx" placeholder="Pfx">

        <input type="text" id="airwaybill" name="airwaybill" placeholder="Airwaybill number">

        Shipper :

        <input type="text" id="shipper" name="shipper" placeholder="Shipper name">

        Consignee :

        <input type="text" id="consignee" name="consignee" placeholder="Consignee name">

        Destination :

        <input type="text" id="destination" name="destination" placeholder="Consignment destination">

        Pieces :

        <input type="text" id="pieces" name="pieces" placeholder="Number of pieces">

        Documents :

        <select id="documents" name="documents">
          <option value="">Please select</option>
          <option value="yes">Yes</option>
          <option value="no">No</option>
        </select>

        Comments :

        <textarea id="comments" name="comments" style="height:100px"></textarea>

<input type="button" class="my-button" name="btn_grn" id="btn_grn" value="Create goods receipt note">

    </form>


问:
Why is a parentheses not needed in removeItem? Why must li.onclick = removeItem be inside the newItem() function?

Why do I not need parentheses for removeItem?

Why must li.onclick = removeItem be inside the newItem() function?

What is the logical sequence when li.onclick event occurs? Is newItem() executed? If so how is it triggered?

I thought that only the enter key will trigger newItem() and since li.onclick = removeItem is inside newItem(), why does clicking trigger it?

Disclaimer: I found this code online but I don't understand these details, hope you guys can help out. Thanks!

html

<input id="input" placeholder="What needs to be done?">

```

<p>javascript</p>

```        function newItem() {
            var item = document.getElementById("input").value;
            var ul = document.getElementById("list");
            var li = document.createElement("li");
            if (document.getElementById("input").value != ""){
                li.appendChild(document.createTextNode(item));
                ul.appendChild(li);
                document.getElementById("input").value = "";
            }
            li.onclick = removeItem;
        }

        document.body.onkeyup = function(e) {
          if (e.keyCode == 13) {
            newItem();
          }
        }

        function removeItem(e) {
            e.target.parentElement.removeChild(e.target);
        }
```

答:
You don't need parentheses because you are storing a reference to the function. The function will be called later. See the following example:

function f1() {
    console.log("f1 called");
}

var function_storage = f1;

function_storage();```

li is declared local to newItem so it can only be used inside the function.

When the onclick event occurs, the removeItem function is called the same way as f1 in the example above.

Body:
Why do I not need parentheses for removeItem?

Why must li.onclick = removeItem be inside the newItem() function?

What is the logical sequence when li.onclick event occurs? Is newItem() executed? If so how is it triggered?

I thought that only the enter key will trigger newItem() and since li.onclick = removeItem is inside newItem(), why does clicking trigger it?

Disclaimer: I found this code online but I don't understand these details, hope you guys can help out. Thanks!

html

<input id="input" placeholder="What needs to be done?">

javascript

        function newItem() {
            var item = document.getElementById("input").value;
            var ul = document.getElementById("list");
            var li = document.createElement("li");
            if (document.getElementById("input").value != ""){
                li.appendChild(document.createTextNode(item));
                ul.appendChild(li);
                document.getElementById("input").value = "";
            }
            li.onclick = removeItem;
        }

        document.body.onkeyup = function(e) {
          if (e.keyCode == 13) {
            newItem();
          }
        }

        function removeItem(e) {
            e.target.parentElement.removeChild(e.target);
        }

Body:
You don't need parentheses because you are storing a reference to the function. The function will be called later. See the following example:

function f1() {
    console.log("f1 called");
}

var function_storage = f1;

function_storage();

li is declared local to newItem so it can only be used inside the function.

When the onclick event occurs, the removeItem function is called the same way as f1 in the example above.


问:
How to extend/reuse Python C Extensions/API implementation?
The problem is that now, I have to use the Posix C getline function to get the line from the file, only then convert it to a Python Unicode Object using PyUnicode_DecodeUTF8 and cache it using my caching policy algorithm. This process is losing 23% of performance compared to Python builtin for line in file C implementation.

If I remove the PyUnicode_DecodeUTF8 call from my code, then, my implementation using the Posix C getline becomes 5% faster than the Python builtin for line in file C implementation. So, if I can just make Python directly give me a Python Unicode String object, instead of having to call the Posix C getline function first (only then convert its result to a Python Unicode Object), my code performance would improve almost by 20% (from a maximum of 23%), i.e., it will not become 100% equivalent to for line in file performance because I am doing a little work by caching stuff, however this overhead is minimal.

For example, I would like to take the _textiowrapper_readline() function and use it in my code like this:

#include <Python.h>
#include <textio.c.h> // C Python file defininig:
                      // _textiowrapper_readline(),
                      // CHECK_ATTACHED(),
                      // PyUnicode_READY(), etc

typedef struct
{
    PyObject_HEAD
}
PyMymoduleExtendingPython;

static PyObject*
PyMymoduleExtendingPython_iternext(PyMymoduleExtendingPython* self, PyObject* args)
{
    PyObject *line;
    CHECK_ATTACHED(self);
    line = _textiowrapper_readline(self, -1); // <- function from `textio.c`

    if (line == NULL || PyUnicode_READY(line) == -1)
        return NULL;

    if (PyUnicode_GET_LENGTH(line) == 0) {
        /* Reached EOF or would have blocked */
        Py_DECREF(line);
        Py_CLEAR(self->snapshot);
        self->telling = self->seekable;
        return NULL;
    }
```

<pre class="lang-cpp prettyprint-override"><code>    return line;
}

// create my module
PyMODINIT_FUNC PyInit_mymodule_extending_python_api(void)
{
    PyObject* mymodule;
    PyMymoduleExtendingPython.tp_iternext =
           (iternextfunc) PyMymoduleExtendingPython_iternext;

    Py_INCREF( &PyMymoduleExtendingPython );
    PyModule_AddObject( mymodule, "FastFile", (PyObject*) &PyMymoduleExtendingPython );
    return mymodule;
}
</code>```

How could I include the textio implementation from C Python and reuse its code on my own Python C Extension/API?

As presented in my last question, How to improve Python C Extensions file line reading?, the Python builtin methods for reading lines are faster than writing my own with C or C++ standard methods to get lines from a file.

On this answer, it was suggested for me to reimplement the Python algorithm by reading chunks of 8KB and only then calling PyUnicode_DecodeUTF8 to decode them, instead of calling PyUnicode_DecodeUTF8 on every line I read.

However, instead of rewriting all C Python code already written/done/ready to read lines, I could just call its "getline" function _textiowrapper_readline() to directly get the line as a Python Unicode Object, then, cache it/use as I am already doing with the lines I get from Posix C getline function (and pass to PyUnicode_DecodeUTF8() decode them into Python Unicode Objects).

答:
I did not manage to directly import the C API (Extensions) functions, but I used Python to import the io module, which has a link/reference to the global builtin function open as io.open().

bool hasfinished;
const char* filepath;
long long int linecount;
std::deque<PyObject*> linecache;

PyObject* iomodule;
PyObject* openfile;
PyObject* fileiterator;

FastFile(const char* filepath) : hasfinished(false), filepath(filepath), linecount(0) {
    iomodule = PyImport_ImportModule( "io" );

    if( iomodule == NULL ) {
        std::cerr << "ERROR: FastFile failed to import the io module '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    PyObject* openfunction = PyObject_GetAttrString( iomodule, "open" );
```

<pre class="lang-cpp prettyprint-override"><code>    if( openfunction == NULL ) {
        std::cerr << "ERROR: FastFile failed get the io module open function '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    openfile = PyObject_CallFunction( openfunction, "s", filepath,
            "s", "r", "i", -1, "s", "UTF8", "s", "replace" );

    PyObject* iterfunction = PyObject_GetAttrString( openfile, "__iter__" );
    Py_DECREF( openfunction );

    if( iterfunction == NULL ) {
        std::cerr << "ERROR: FastFile failed get the io module iterator function '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    PyObject* openfileresult = PyObject_CallObject( iterfunction, NULL );
    Py_DECREF( iterfunction );
</code>```

    if( openfileresult == NULL ) {
        std::cerr << "ERROR: FastFile failed get the io module iterator object '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    fileiterator = PyObject_GetAttrString( openfile, "__next__" );
    Py_DECREF( openfileresult );

    if( fileiterator == NULL ) {
        std::cerr << "ERROR: FastFile failed get the io module iterator object '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
}

~FastFile() {
    this->close();
    Py_XDECREF( iomodule );
    Py_XDECREF( openfile );
    Py_XDECREF( fileiterator );

    for( PyObject* pyobject : linecache ) {
        Py_DECREF( pyobject );
    }
}

void close() {
    PyObject* closefunction = PyObject_GetAttrString( openfile, "close" );
```

<pre class="lang-cpp prettyprint-override"><code>    if( closefunction == NULL ) {
        std::cerr << "ERROR: FastFile failed get the close file function for '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    PyObject* closefileresult = PyObject_CallObject( closefunction, NULL );
    Py_DECREF( closefunction );

    if( closefileresult == NULL ) {
        std::cerr << "ERROR: FastFile failed close open file '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    Py_DECREF( closefileresult );
}

bool _getline() {
    // Fix StopIteration being raised multiple times because
    // _getlines is called multiple times
    if( hasfinished ) { return false; }
    PyObject* readline = PyObject_CallObject( fileiterator, NULL );

    if( readline != NULL ) {
        linecount += 1;
        linecache.push_back( readline );
        return true;
    }

    // PyErr_Print();
    PyErr_Clear();
    hasfinished = true;
    return false;
}
</code>```

When compiling this with Visual Studio Compiler, it has the following performance using this code:

print( 'fastfile_time %.2f%%, python_time %.2f%%' % (
        fastfile_time/python_time, python_time/fastfile_time ), flush=True )
```

```$ python3 fastfileperformance.py
Python   timedifference 0:00:00.985254
FastFile timedifference 0:00:01.084283
fastfile_time 1.10%, python_time 0.91% = 0.09%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.979861
FastFile timedifference 0:00:01.073879
fastfile_time 1.10%, python_time 0.91% = 0.09%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.990369
FastFile timedifference 0:00:01.086416
fastfile_time 1.10%, python_time 0.91% = 0.09%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.975223
FastFile timedifference 0:00:01.077857
fastfile_time 1.11%, python_time 0.90% = 0.10%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.988327
FastFile timedifference 0:00:01.085866
fastfile_time 1.10%, python_time 0.91% = 0.09%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.971848
FastFile timedifference 0:00:01.087894
fastfile_time 1.12%, python_time 0.89% = 0.11%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.968116
FastFile timedifference 0:00:01.079976
fastfile_time 1.12%, python_time 0.90% = 0.10%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.980856
FastFile timedifference 0:00:01.068325
fastfile_time 1.09%, python_time 0.92% = 0.08%
```

<p>But when compiling it with <code>g++</code>, it got this performance:</p>

```$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.703964
FastFile timedifference 0:00:00.813478
fastfile_time 1.16%, python_time 0.87% = 0.13%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.703432
FastFile timedifference 0:00:00.809531
fastfile_time 1.15%, python_time 0.87% = 0.13%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.705319
FastFile timedifference 0:00:00.814130
fastfile_time 1.15%, python_time 0.87% = 0.13%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.711852
FastFile timedifference 0:00:00.837132
fastfile_time 1.18%, python_time 0.85% = 0.15%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.695033
FastFile timedifference 0:00:00.800901
fastfile_time 1.15%, python_time 0.87% = 0.13%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.694661
FastFile timedifference 0:00:00.796754
fastfile_time 1.15%, python_time 0.87% = 0.13%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.699377
FastFile timedifference 0:00:00.816715
fastfile_time 1.17%, python_time 0.86% = 0.14%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.699229
FastFile timedifference 0:00:00.818774
fastfile_time 1.17%, python_time 0.85% = 0.15%
```

Body:
The problem is that now, I have to use the Posix C getline function to get the line from the file, only then convert it to a Python Unicode Object using PyUnicode_DecodeUTF8 and cache it using my caching policy algorithm. This process is losing 23% of performance compared to Python builtin for line in file C implementation.

If I remove the PyUnicode_DecodeUTF8 call from my code, then, my implementation using the Posix C getline becomes 5% faster than the Python builtin for line in file C implementation. So, if I can just make Python directly give me a Python Unicode String object, instead of having to call the Posix C getline function first (only then convert its result to a Python Unicode Object), my code performance would improve almost by 20% (from a maximum of 23%), i.e., it will not become 100% equivalent to for line in file performance because I am doing a little work by caching stuff, however this overhead is minimal.

For example, I would like to take the _textiowrapper_readline() function and use it in my code like this:

#include <Python.h>
#include <textio.c.h> // C Python file defininig:
                      // _textiowrapper_readline(),
                      // CHECK_ATTACHED(),
                      // PyUnicode_READY(), etc

typedef struct
{
    PyObject_HEAD
}
PyMymoduleExtendingPython;

static PyObject*
PyMymoduleExtendingPython_iternext(PyMymoduleExtendingPython* self, PyObject* args)
{
    PyObject *line;
    CHECK_ATTACHED(self);
    line = _textiowrapper_readline(self, -1); // <- function from `textio.c`

    if (line == NULL || PyUnicode_READY(line) == -1)
        return NULL;

    if (PyUnicode_GET_LENGTH(line) == 0) {
        /* Reached EOF or would have blocked */
        Py_DECREF(line);
        Py_CLEAR(self->snapshot);
        self->telling = self->seekable;
        return NULL;
    }

    return line;
}

// create my module
PyMODINIT_FUNC PyInit_mymodule_extending_python_api(void)
{
    PyObject* mymodule;
    PyMymoduleExtendingPython.tp_iternext =
           (iternextfunc) PyMymoduleExtendingPython_iternext;

    Py_INCREF( &PyMymoduleExtendingPython );
    PyModule_AddObject( mymodule, "FastFile", (PyObject*) &PyMymoduleExtendingPython );
    return mymodule;
}

How could I include the textio implementation from C Python and reuse its code on my own Python C Extension/API?

As presented in my last question, How to improve Python C Extensions file line reading?, the Python builtin methods for reading lines are faster than writing my own with C or C++ standard methods to get lines from a file.

On this answer, it was suggested for me to reimplement the Python algorithm by reading chunks of 8KB and only then calling PyUnicode_DecodeUTF8 to decode them, instead of calling PyUnicode_DecodeUTF8 on every line I read.

However, instead of rewriting all C Python code already written/done/ready to read lines, I could just call its "getline" function _textiowrapper_readline() to directly get the line as a Python Unicode Object, then, cache it/use as I am already doing with the lines I get from Posix C getline function (and pass to PyUnicode_DecodeUTF8() decode them into Python Unicode Objects).

Body:
I did not manage to directly import the C API (Extensions) functions, but I used Python to import the io module, which has a link/reference to the global builtin function open as io.open().

bool hasfinished;
const char* filepath;
long long int linecount;
std::deque<PyObject*> linecache;

PyObject* iomodule;
PyObject* openfile;
PyObject* fileiterator;

FastFile(const char* filepath) : hasfinished(false), filepath(filepath), linecount(0) {
    iomodule = PyImport_ImportModule( "io" );

    if( iomodule == NULL ) {
        std::cerr << "ERROR: FastFile failed to import the io module '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    PyObject* openfunction = PyObject_GetAttrString( iomodule, "open" );

    if( openfunction == NULL ) {
        std::cerr << "ERROR: FastFile failed get the io module open function '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    openfile = PyObject_CallFunction( openfunction, "s", filepath,
            "s", "r", "i", -1, "s", "UTF8", "s", "replace" );

    PyObject* iterfunction = PyObject_GetAttrString( openfile, "__iter__" );
    Py_DECREF( openfunction );

    if( iterfunction == NULL ) {
        std::cerr << "ERROR: FastFile failed get the io module iterator function '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    PyObject* openfileresult = PyObject_CallObject( iterfunction, NULL );
    Py_DECREF( iterfunction );

    if( openfileresult == NULL ) {
        std::cerr << "ERROR: FastFile failed get the io module iterator object '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    fileiterator = PyObject_GetAttrString( openfile, "__next__" );
    Py_DECREF( openfileresult );

    if( fileiterator == NULL ) {
        std::cerr << "ERROR: FastFile failed get the io module iterator object '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
}

~FastFile() {
    this->close();
    Py_XDECREF( iomodule );
    Py_XDECREF( openfile );
    Py_XDECREF( fileiterator );

    for( PyObject* pyobject : linecache ) {
        Py_DECREF( pyobject );
    }
}

void close() {
    PyObject* closefunction = PyObject_GetAttrString( openfile, "close" );

    if( closefunction == NULL ) {
        std::cerr << "ERROR: FastFile failed get the close file function for '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    PyObject* closefileresult = PyObject_CallObject( closefunction, NULL );
    Py_DECREF( closefunction );

    if( closefileresult == NULL ) {
        std::cerr << "ERROR: FastFile failed close open file '"
                << filepath << "')!" << std::endl;
        PyErr_Print();
        return;
    }
    Py_DECREF( closefileresult );
}

bool _getline() {
    // Fix StopIteration being raised multiple times because
    // _getlines is called multiple times
    if( hasfinished ) { return false; }
    PyObject* readline = PyObject_CallObject( fileiterator, NULL );

    if( readline != NULL ) {
        linecount += 1;
        linecache.push_back( readline );
        return true;
    }

    // PyErr_Print();
    PyErr_Clear();
    hasfinished = true;
    return false;
}

When compiling this with Visual Studio Compiler, it has the following performance using this code:

print( 'fastfile_time %.2f%%, python_time %.2f%%' % (
        fastfile_time/python_time, python_time/fastfile_time ), flush=True )

$ python3 fastfileperformance.py
Python   timedifference 0:00:00.985254
FastFile timedifference 0:00:01.084283
fastfile_time 1.10%, python_time 0.91% = 0.09%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.979861
FastFile timedifference 0:00:01.073879
fastfile_time 1.10%, python_time 0.91% = 0.09%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.990369
FastFile timedifference 0:00:01.086416
fastfile_time 1.10%, python_time 0.91% = 0.09%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.975223
FastFile timedifference 0:00:01.077857
fastfile_time 1.11%, python_time 0.90% = 0.10%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.988327
FastFile timedifference 0:00:01.085866
fastfile_time 1.10%, python_time 0.91% = 0.09%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.971848
FastFile timedifference 0:00:01.087894
fastfile_time 1.12%, python_time 0.89% = 0.11%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.968116
FastFile timedifference 0:00:01.079976
fastfile_time 1.12%, python_time 0.90% = 0.10%
$ python3 fastfileperformance.py
Python   timedifference 0:00:00.980856
FastFile timedifference 0:00:01.068325
fastfile_time 1.09%, python_time 0.92% = 0.08%

But when compiling it with g++, it got this performance:

$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.703964
FastFile timedifference 0:00:00.813478
fastfile_time 1.16%, python_time 0.87% = 0.13%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.703432
FastFile timedifference 0:00:00.809531
fastfile_time 1.15%, python_time 0.87% = 0.13%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.705319
FastFile timedifference 0:00:00.814130
fastfile_time 1.15%, python_time 0.87% = 0.13%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.711852
FastFile timedifference 0:00:00.837132
fastfile_time 1.18%, python_time 0.85% = 0.15%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.695033
FastFile timedifference 0:00:00.800901
fastfile_time 1.15%, python_time 0.87% = 0.13%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.694661
FastFile timedifference 0:00:00.796754
fastfile_time 1.15%, python_time 0.87% = 0.13%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.699377
FastFile timedifference 0:00:00.816715
fastfile_time 1.17%, python_time 0.86% = 0.14%
$ /bin/python3.6 fastfileperformance.py
Python   timedifference 0:00:00.699229
FastFile timedifference 0:00:00.818774
fastfile_time 1.17%, python_time 0.85% = 0.15%


问:
How to make random pick python differently?
I want to make a bot that sending 3 emoji but its different emoji , but when im running it , the bot took one emoji and sending a same 3 emoji, how do i make it take the different 3 emoji?

```<code>list  = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
text = random.choice(list)
</code>```

that the code

edit : can you tell me whats wrong in this one?

```<code>import discord
import requests
import random
import sys

token = sys.argv[1]
chan = sys.argv[2]
client = discord.Client()
list = requests.get('emoji.txt').text.split("\n")

@client.event
async def on_ready():
    txtchan = client.get_channel(int(chan))
    while not client.is_closed():
        message = ''
        for x in range(5):
            message += random.choice(list)
        await txtchan.send(message)
client.run(token, bot=False)
</code>```

答:
The correct code for this will be

```<code>text = random.sample(list, 3)
</code>```

This will randomly sample 3 emojis. Change the number to how many samples you want to draw.

Body:
I want to make a bot that sending 3 emoji but its different emoji , but when im running it , the bot took one emoji and sending a same 3 emoji, how do i make it take the different 3 emoji?

list  = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
text = random.choice(list)

that the code

edit : can you tell me whats wrong in this one?

import discord
import requests
import random
import sys

token = sys.argv[1]
chan = sys.argv[2]
client = discord.Client()
list = requests.get('emoji.txt').text.split("\n")

@client.event
async def on_ready():
    txtchan = client.get_channel(int(chan))
    while not client.is_closed():
        message = ''
        for x in range(5):
            message += random.choice(list)
        await txtchan.send(message)
client.run(token, bot=False)

Body:
The correct code for this will be

text = random.sample(list, 3)

This will randomly sample 3 emojis. Change the number to how many samples you want to draw.


问:
Swift string replace and get new range
Any better way to retrieve the Range after string replace?

Here is the current version:

```<code>let username = "apple"
msgString = "{{user}} has an apple"
guard let range = msgString.range(of: "{{user}}") else { return }
msgString.replaceSubrange(range, with username)
userRange = msgString.range(of: username)
</code>```

Does any better way to get the user name range

答:
Two functions:

replacingOccurrences... returns a new string and informs about the change ranges

replaceOccurrences... changes the value of the current variable and informs about the change ranges

The best place to implement those is in String extension:

```<code>extension String {

    func replacingOccurrences<T: StringProtocol>(of toReplace: T,
                                                 with newString: T,
                                                 options: String.CompareOptions = [],
                                                 range searchRange: Range<T.Index>? = nil,
                                                 completion: ((Range<T.Index>?, Range<T.Index>?) -> Void)) -> String {

        let oldRange = range(of: toReplace)

        let replacedString = replacingOccurrences(of: toReplace,
                                                  with: newString,
                                                  options: options,
                                                  range: searchRange)

        let newRange = replacedString.range(of: newString)

        completion(oldRange, newRange)

        return replacedString
    }

    mutating func replaceOccurrences<T: StringProtocol>(of toReplace: T,
                                                        with newString: T,
                                                        options: String.CompareOptions = [],
                                                        range searchRange: Range<T.Index>? = nil,
                                                        completion: ((Range<T.Index>?, Range<T.Index>?) -> Void)) {

        self = replacingOccurrences(of: toReplace,
                                    with: newString,
                                    options: options,
                                    range: searchRange,
                                    completion: completion)
    }
}
</code>```

Usage:

```<code>let username = "apple"
var msgString = "{{user}} has an apple"

msgString.replaceOccurrences(of: "{{user}}", with: username) { (oldRange, newRange) in
    print(oldRange)
    print(newRange)
}
</code>```

Title: Swift string replace and get new range

Body:
Any better way to retrieve the Range after string replace?

Here is the current version:

let username = "apple"
msgString = "{{user}} has an apple"
guard let range = msgString.range(of: "{{user}}") else { return }
msgString.replaceSubrange(range, with username)
userRange = msgString.range(of: username)

Does any better way to get the user name range

Body:
Two functions:

replacingOccurrences... returns a new string and informs about the change ranges

replaceOccurrences... changes the value of the current variable and informs about the change ranges

The best place to implement those is in String extension:

extension String {

    func replacingOccurrences<T: StringProtocol>(of toReplace: T,
                                                 with newString: T,
                                                 options: String.CompareOptions = [],
                                                 range searchRange: Range<T.Index>? = nil,
                                                 completion: ((Range<T.Index>?, Range<T.Index>?) -> Void)) -> String {

        let oldRange = range(of: toReplace)

        let replacedString = replacingOccurrences(of: toReplace,
                                                  with: newString,
                                                  options: options,
                                                  range: searchRange)

        let newRange = replacedString.range(of: newString)

        completion(oldRange, newRange)

        return replacedString
    }

    mutating func replaceOccurrences<T: StringProtocol>(of toReplace: T,
                                                        with newString: T,
                                                        options: String.CompareOptions = [],
                                                        range searchRange: Range<T.Index>? = nil,
                                                        completion: ((Range<T.Index>?, Range<T.Index>?) -> Void)) {

        self = replacingOccurrences(of: toReplace,
                                    with: newString,
                                    options: options,
                                    range: searchRange,
                                    completion: completion)
    }
}

Usage:

let username = "apple"
var msgString = "{{user}} has an apple"

msgString.replaceOccurrences(of: "{{user}}", with: username) { (oldRange, newRange) in
    print(oldRange)
    print(newRange)
}


问:
How to use async pipe with RxJS interval on dynamically created component?
I was wondering if it's somehow possible to use async pipe with RxJS interval() on dynamically created components like in this example . Because if I apply async pipe inside of it, then when the components will change the interval will be mostly ignored.

Let's say I want to get data every 15 minutes but the components change every 15 seconds.

The only way I found is to take data from one Observable and save it to another one but I don't think that this is the best practice. Is there some other way on how to achieve this or this practice is ok?

The Observable looks like this:

```<code>interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl')));
</code>```

Solution I found working:

```<code>interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl'))).subscribe((data) => {
  this.someUrlData = scheduled([data], asapScheduler);
});
</code>```

答: i think the answer you found is the best way to reach what you want to do. you can make a shared state with the time of interval and when you create the dynamic component you check the interval and based on it make the http call I think in all ways you will need an outer state that you can listen to because you will destroy the interval every time you create the component.</p>

Body:
I was wondering if it's somehow possible to use async pipe with RxJS interval() on dynamically created components like in this example . Because if I apply async pipe inside of it, then when the components will change the interval will be mostly ignored.

Let's say I want to get data every 15 minutes but the components change every 15 seconds.

The only way I found is to take data from one Observable and save it to another one but I don't think that this is the best practice. Is there some other way on how to achieve this or this practice is ok?

The Observable looks like this:

interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl')));

Solution I found working:

interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl'))).subscribe((data) => {
  this.someUrlData = scheduled([data], asapScheduler);
});


问:
Define front end controller for specific application in project
I created a front end controller within a project containing multiple (REST) applications. The issue is now that, the controller gets applied for all applications I try to access through the browser. I would like to ask whether the is a configuration or annotation to define for which application the controller should get applied.

This is the code of the controller:

```<code>@Controller
public class FrontendController {

    @RequestMapping(value = "/")
    public String index() {
        return "index";
    }
}
</code>```

In the same package the application which serves the front end sources is implemented:

```<code>@SpringBootApplication
public class WebServer {

    public static void main(String[] args) {
        // Tell server to look for web-server.properties or web-server.yml
        System.setProperty("spring.config.name", "web-server");

        SpringApplication.run(com.studienarbeit.chaoscenter.services.departments.DepartmentsServer.class, args);
    }

}
</code>```

The other applications are in different packages and yet they still serve the front end sources. There are no other controllers in the project and the other applications use Spring Data REST repositories.

Note: Each application runs on its own port.

Note 2: I tried the approach using a profile for the controller:

```<code>@Profile("web-server")
</code>```

Since I work with IntelliJ, I set the active profile to web-server and add the following flag in the VM Options for the specific application:

```<code>-Dspring.profiles.active=web-server
</code>```

Somehow still my other applications access the front end controller. Maybe I did miss something?

Note 3: The other application implementations look basically exactly like the WebServer application and they use Spring Data REST repositories which look like this:

```<code>public interface EmployeeRepository extends CrudRepository<Employee, Long> {

}
</code>```

答:
Use specific RequestMapping values for each of your controller classes like :

```<code>@Controller
@RequestMapping("/controller1")
public class FrontendController {

    @RequestMapping(value = "/")
    public String index() {
        return "index";
    }
}
</code>```

So you would consume this endpoint with the url http://localhost:8080/controller1

Also, if you're not going to use Mvc Views and this will be only a Rest Controller, use @RestController insted @Controller.

```<code>@RestController
@RequestMapping("/controller1")
public class FrontendController
</code>```

It's a combination of @Controller and @ResponseBody annotations. Detailed information could be found at here.

Body:
I created a front end controller within a project containing multiple (REST) applications. The issue is now that, the controller gets applied for all applications I try to access through the browser. I would like to ask whether the is a configuration or annotation to define for which application the controller should get applied.

This is the code of the controller:

@Controller
public class FrontendController {

    @RequestMapping(value = "/")
    public String index() {
        return "index";
    }
}

In the same package the application which serves the front end sources is implemented:

@SpringBootApplication
public class WebServer {

    public static void main(String[] args) {
        // Tell server to look for web-server.properties or web-server.yml
        System.setProperty("spring.config.name", "web-server");

        SpringApplication.run(com.studienarbeit.chaoscenter.services.departments.DepartmentsServer.class, args);
    }

}

The other applications are in different packages and yet they still serve the front end sources. There are no other controllers in the project and the other applications use Spring Data REST repositories.

Note: Each application runs on its own port.

Note 2: I tried the approach using a profile for the controller:

@Profile("web-server")

Since I work with IntelliJ, I set the active profile to web-server and add the following flag in the VM Options for the specific application:

-Dspring.profiles.active=web-server

Somehow still my other applications access the front end controller. Maybe I did miss something?

Note 3: The other application implementations look basically exactly like the WebServer application and they use Spring Data REST repositories which look like this:

public interface EmployeeRepository extends CrudRepository<Employee, Long> {

}

Body:
Use specific RequestMapping values for each of your controller classes like :

@Controller
@RequestMapping("/controller1")
public class FrontendController {

    @RequestMapping(value = "/")
    public String index() {
        return "index";
    }
}

So you would consume this endpoint with the url http://localhost:8080/controller1

Also, if you're not going to use Mvc Views and this will be only a Rest Controller, use @RestController insted @Controller.

@RestController
@RequestMapping("/controller1")
public class FrontendController

It's a combination of @Controller and @ResponseBody annotations. Detailed information could be found at here.


问:
Typescript - auto conversion from a Json string with a date string to an object with a Date property
When calling a REST service returning JSON, how can I format a date so that it is converted automatically into a typescript Date object?

The result of calling a REST call is this message:

{"id":3796,...,"startTempValue":"2019-05-26T19:39:01Z"}

I also tried this ISO format:

{"id":3796,...,"startTempValue": "2019-05-26T19:39:01.000Z"}

The model object is:

```<code>export class Settings {
    public id: number;
    public shortName;
    public description: string;
    public value: string;
    public possibleValues: string;
    public startTempValue: Date;
}
</code>```

The result of startTempValue is a string ... ?! I want the startTempValue to be a Date object.

Of course, I could convert the Date string to a Date object manually. So, doing something like the code below at reception of the REST service result. But there should be a better way. Another alternative would be to convert it at the server to an epoch (milliconds). That is possible, but still, this 'string' variant is more readable.

```<code>if ( this.settings[i].startTempValue !== undefined &&
     this.settings[i].startTempValue !== null) {
    this.settings[i].startTempValue = new Date(this.settings[i].startTempValue);
} else {
    this.settings[i].startTempValue = null;
}
</code>```

答:
JSON only deals with primitives like numbers, strings, arrays and objects.

There is no information within JSON that describes what its contents mean. So even if something looks like a date to you, it's still just a string.

So how could you convert it manually? Well, if you know in advanced what property names are always dates, you could loop through the result and convert these preemptively. Or you could loop through all the values and take anything that looks like a date and automatically convert.

A third option would be to have some kind of schema that marks certain things as dates and use that for your automatic conversion.

The point is that there is no built-in way to infer this, and it's kind of up to you do to something else with your data

Body:
When calling a REST service returning JSON, how can I format a date so that it is converted automatically into a typescript Date object?

The result of calling a REST call is this message:

{"id":3796,...,"startTempValue":"2019-05-26T19:39:01Z"}

I also tried this ISO format:

{"id":3796,...,"startTempValue": "2019-05-26T19:39:01.000Z"}

The model object is:

export class Settings {
    public id: number;
    public shortName;
    public description: string;
    public value: string;
    public possibleValues: string;
    public startTempValue: Date;
}

The result of startTempValue is a string ... ?! I want the startTempValue to be a Date object.

Of course, I could convert the Date string to a Date object manually. So, doing something like the code below at reception of the REST service result. But there should be a better way. Another alternative would be to convert it at the server to an epoch (milliconds). That is possible, but still, this 'string' variant is more readable.

if ( this.settings[i].startTempValue !== undefined &&
     this.settings[i].startTempValue !== null) {
    this.settings[i].startTempValue = new Date(this.settings[i].startTempValue);
} else {
    this.settings[i].startTempValue = null;
}


问:
SQL Join 2 tables with date difference
I have 2 tables, one of which is orders and the other one is receipts. The problem i am facing is that they dont have UID, the only thing they can be joined with is the date. Problem with that is, the date is the same, but the time difference between them is approx 30 seconds. My question is, is there any way i can join these 2 tables?

So, the 1st table is in the following format

```<code>|   date        | order | price |
|1/1/13 06:05:32|  tea  |   3   |
|1/2/13 07:04:24| coffee|   2   |
|4/3/13 13:31:23|  tea  |   3   |

</code>```

And the second table has this format

```<code>|   date        | order | quantity |
|1/1/13 06:05:42|  tea  |   3      |
|1/2/13 07:04:54| coffee|   2      |
|4/3/13 13:31:56|  tea  |   3      |

</code>```

My desired output is

```<code>|   date        | order | quantity |  price |
|1/1/13 06:05:42|  tea  |   3      |    3   |
|1/2/13 07:04:54| coffee|   2      |    2   |
|4/3/13 13:31:56|  tea  |   3      |    3   |

</code>```

Basically, my goal here is to combine these 2 tables so i can see the differences between them, but i dont have an idea how to join them without unique ID's, please help guys

答:
Here's one solution (tried on SQLite3 but it's similar for other DBMS if you replace with the corresponding date function):

```<code>create table orders([date],[order],price);
insert into orders values
('2013-01-01 06:05:32', 'tea',  3),
('2013-01-02 07:04:24','coffee',2),
('2013-04-03 13:31:23', 'tea',  3);

create table receipts([date],[order],quantity);
insert into receipts values
('2013-01-01 06:05:42', 'tea',  3),
('2013-01-02 07:04:54','coffee',2),
('2013-04-03 13:31:56', 'tea',  3);

-- My desired output is
--
-- |   date        | order | quantity |  price |
-- |1/1/13 06:05:42|  tea  |   3      |    3   |
-- |1/2/13 07:04:54| coffee|   2      |    2   |
-- |4/3/13 13:31:56|  tea  |   3      |    3   |

select r.[date],[order],quantity,price
  from orders o join receipts r using([order])
  where r.date > o.date
    and r.date < datetime(o.date,'+40 seconds')
</code>```

or even:

```<code>select r.[date],[order],quantity,price
  from orders o join receipts r using([order])
  where r.date between o.date and datetime(o.date,'+40 seconds')
</code>```

I used 40 seconds (you say approximately 30 seconds but your example output grabs the 33 second difference).  Adjust as needed.  I also assume (based on your example) that orders always come before receipts.

Title: SQL Join 2 tables with date difference

Body:
I have 2 tables, one of which is orders and the other one is receipts. The problem i am facing is that they dont have UID, the only thing they can be joined with is the date. Problem with that is, the date is the same, but the time difference between them is approx 30 seconds. My question is, is there any way i can join these 2 tables?

So, the 1st table is in the following format

|   date        | order | price |
|1/1/13 06:05:32|  tea  |   3   |
|1/2/13 07:04:24| coffee|   2   |
|4/3/13 13:31:23|  tea  |   3   |

And the second table has this format

|   date        | order | quantity |
|1/1/13 06:05:42|  tea  |   3      |
|1/2/13 07:04:54| coffee|   2      |
|4/3/13 13:31:56|  tea  |   3      |

My desired output is

|   date        | order | quantity |  price |
|1/1/13 06:05:42|  tea  |   3      |    3   |
|1/2/13 07:04:54| coffee|   2      |    2   |
|4/3/13 13:31:56|  tea  |   3      |    3   |

Basically, my goal here is to combine these 2 tables so i can see the differences between them, but i dont have an idea how to join them without unique ID's, please help guys

Body:
Here's one solution (tried on SQLite3 but it's similar for other DBMS if you replace with the corresponding date function):

create table orders([date],[order],price);
insert into orders values
('2013-01-01 06:05:32', 'tea',  3),
('2013-01-02 07:04:24','coffee',2),
('2013-04-03 13:31:23', 'tea',  3);

create table receipts([date],[order],quantity);
insert into receipts values
('2013-01-01 06:05:42', 'tea',  3),
('2013-01-02 07:04:54','coffee',2),
('2013-04-03 13:31:56', 'tea',  3);

-- My desired output is
--
-- |   date        | order | quantity |  price |
-- |1/1/13 06:05:42|  tea  |   3      |    3   |
-- |1/2/13 07:04:54| coffee|   2      |    2   |
-- |4/3/13 13:31:56|  tea  |   3      |    3   |

select r.[date],[order],quantity,price
  from orders o join receipts r using([order])
  where r.date > o.date
    and r.date < datetime(o.date,'+40 seconds')

or even:

select r.[date],[order],quantity,price
  from orders o join receipts r using([order])
  where r.date between o.date and datetime(o.date,'+40 seconds')

I used 40 seconds (you say approximately 30 seconds but your example output grabs the 33 second difference).  Adjust as needed.  I also assume (based on your example) that orders always come before receipts.


问:
How to pass parameter dynamically to JQuery click event from HTML elements?
First of all, I have to mention that I am a newbie in the JavaScript and JQuery world. I am not sure if I put down an appropriate title for my question but I'll try my best to explain my problem.

Scenario: I have a list of items whose names are being displayed. When one of the items is being clicked, a popup should show up and display the description of the item. The description is retrieved from the server via an AJAX call upon the click. The AJAX call requires the unique id of the item (in the database) to be provided. Here comes my problem which has two parts:

I don't know how and where to include the item id in the HTML. Note that the list only displays item name not id.

Assume 1) is resolved, how can I pass the id of the item that's being clicked to the AJAX call.

This is the HTML of the list of items. As you can see, it illustrates part 1) of my problem (ie. don't know how to include the ids in the HTML).

```<code><ul>
    <li class="item">Item1</li> <!-- this item has id=1 in the database -->
    <li class="item">Item2</li> <!-- this item has id=2 in the database -->
    <li class="item">Item3</li> <!-- this item has id=3 in the database -->
</ul>
</code>```

Below is the JQuery click event handler that sends the AJAX call (ie. getJSON) to the server. Note that the part 2) of the problem is illustrated by the line var item_id = ??. Note that popup is a self-defined javascript.

```<code>    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            $(".item").click(function() {
                var item_id = ??
                var data = {"item_id":item_id};
                $.getJSON("/item/json", data, function(data) {
                    var name = data[0]["fields"]["name"]
                    var description = data[0]["fields"]["description"]
                    popup.call(this, name, description);
                });
            });
        });
    </script>
</code>```

Additional Info: For the server side I use Django 1.3, and JQuery 1.5.2 for the client side.
I hope I have made my question clear and I appreciate any help from you experts. Thanks.

Here is an example that is similar to what I am looking for.

http://esdi.excelsystems.com/iseries400apps/exmain.pgm?wsname=DIALOG.pgm&wsnumb=214&wsprogtype=P

答:
http://www.w3schools.com/tags/tag_li.asp

The
 tag supports the following standard attributes:
id  Specifies a unique id for an element

In this case use:

```<code><ul>
    <li class="item" id="item_1">Item1</li> <!-- this item has id=1 in the database -->
    <li class="item" id="item_2">Item2</li> <!-- this item has id=2 in the database -->
    <li class="item" id="item_3">Item3</li> <!-- this item has id=3 in the database -->
</ul>
</code>```

And

```<code><script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        $(".item").click(function() {
            var item_id = $(this).attr('id').replace('item_','');
            var data = {"item_id":item_id};
            $.getJSON("/item/json", data, function(data) {
                var name = data[0]["fields"]["name"]
                var description = data[0]["fields"]["description"]
                popup.call(this, name, description);
            });
        });
    });
</script>
</code>```

Body:
First of all, I have to mention that I am a newbie in the JavaScript and JQuery world. I am not sure if I put down an appropriate title for my question but I'll try my best to explain my problem.

Scenario: I have a list of items whose names are being displayed. When one of the items is being clicked, a popup should show up and display the description of the item. The description is retrieved from the server via an AJAX call upon the click. The AJAX call requires the unique id of the item (in the database) to be provided. Here comes my problem which has two parts:

I don't know how and where to include the item id in the HTML. Note that the list only displays item name not id.

Assume 1) is resolved, how can I pass the id of the item that's being clicked to the AJAX call.

This is the HTML of the list of items. As you can see, it illustrates part 1) of my problem (ie. don't know how to include the ids in the HTML).

Item1

Item2

Item3

Below is the JQuery click event handler that sends the AJAX call (ie. getJSON) to the server. Note that the part 2) of the problem is illustrated by the line var item_id = ??. Note that popup is a self-defined javascript.

Additional Info: For the server side I use Django 1.3, and JQuery 1.5.2 for the client side.
I hope I have made my question clear and I appreciate any help from you experts. Thanks.

Here is an example that is similar to what I am looking for.

http://esdi.excelsystems.com/iseries400apps/exmain.pgm?wsname=DIALOG.pgm&wsnumb=214&wsprogtype=P

Body:
http://www.w3schools.com/tags/tag_li.asp

The < li > tag supports the following standard attributes:
id  Specifies a unique id for an element

In this case use:

<ul>
    <li class="item" id="item_1">Item1</li> <!-- this item has id=1 in the database -->
    <li class="item" id="item_2">Item2</li> <!-- this item has id=2 in the database -->
    <li class="item" id="item_3">Item3</li> <!-- this item has id=3 in the database -->
</ul>

And

<script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        $(".item").click(function() {
            var item_id = $(this).attr('id').replace('item_','');
            var data = {"item_id":item_id};
            $.getJSON("/item/json", data, function(data) {
                var name = data[0]["fields"]["name"]
                var description = data[0]["fields"]["description"]
                popup.call(this, name, description);
            });
        });
    });
</script>


答:
For example like that:

```<code>list  = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
text = set() #~ Set contains only unique elements
while len(text) < 3:
    text.add(random.choice(list))
</code>```

This should after while, always hold 3 elements, but it can take longer if pseudorandom will 'randomly' pick 999 times that same emoji, almost impossible, but there is a chance.

Another way, more constant in time is shuffle:

```<code>list  = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
random.shuffle(list)
text = list[:3]
</code>```

But that without makeing copy, always shuffle your first list variable.

Offtopic: list is key word in python interpreter, pls don't use variable named like function list() in your code. I think it provokes 'minus' votes on you.

@EDIT:
At first, change variable name list for array.
Then, it should work:

```<code>@client.event
async def on_ready():
    txtchan = client.get_channel(int(chan))
    while not client.is_closed():
        message = ''.join(random.sample(array, 3))
        await txtchan.send(message)
    client.run(token, bot=False)
</code>```

If it won't work, and some error occured, send it to us. Without that, most of people there, can't easy and fast test it and tell you what wasn't correct.

And i hope it isn't your all what code contains, becouse it isn't enough to correctly login bot into discord ;)

Title: How to make random pick python differently?

Body:
For example like that:

list  = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
text = set() #~ Set contains only unique elements
while len(text) < 3:
    text.add(random.choice(list))

This should after while, always hold 3 elements, but it can take longer if pseudorandom will 'randomly' pick 999 times that same emoji, almost impossible, but there is a chance.

Another way, more constant in time is shuffle:

list  = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
random.shuffle(list)
text = list[:3]

But that without makeing copy, always shuffle your first list variable.

Offtopic: list is key word in python interpreter, pls don't use variable named like function list() in your code. I think it provokes 'minus' votes on you.

@EDIT:
At first, change variable name list for array.
Then, it should work:

@client.event
async def on_ready():
    txtchan = client.get_channel(int(chan))
    while not client.is_closed():
        message = ''.join(random.sample(array, 3))
        await txtchan.send(message)
    client.run(token, bot=False)

If it won't work, and some error occured, send it to us. Without that, most of people there, can't easy and fast test it and tell you what wasn't correct.

And i hope it isn't your all what code contains, becouse it isn't enough to correctly login bot into discord ;)


问:
How to set the column order of DTO properties programatically
I am having simple DTO class. I would like to dynamically set the column order of this dto properties when the results are stored into excel.

```<code>Public class Student
{
   public int Id {get;set;}
   public string FirstName {get;set;}
   public string LastName {get;set;}
}
</code>```

I know there is a way using DataAnnotation Column Order Attribute on each property inside DTO. But is there a way to handle this using code to set the column order of DTO.

I am using simple web application and added System.ComponentModel.DataAnnotation Reference.

If there is a work around without using DataAnnotation to set the column order using code that will be great

答:
What about using a static array inside your class or in a different class which list all columns in the order you want, and while saving to excel you loop through this array first to get columns in the correct order.

Something like that:

```<code>public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public List<string> OrderedProperties => new List<string> { "LastName", "FirstName", "Id" };
}

public class DataAccess
{
    public void SaveStudentToExcel()
    {
        var student = new Student(); // instead of new this should be your object filled with real data.
        foreach (var propName in student.OrderedProperties)
        {
            var val = student.GetType().GetProperty(propName).GetValue(student, null);

            // new cell in excel => with val and propName then save
        }
    }
}
</code>```

Body:
I am having simple DTO class. I would like to dynamically set the column order of this dto properties when the results are stored into excel.

Public class Student
{
   public int Id {get;set;}
   public string FirstName {get;set;}
   public string LastName {get;set;}
}

I know there is a way using DataAnnotation Column Order Attribute on each property inside DTO. But is there a way to handle this using code to set the column order of DTO.

I am using simple web application and added System.ComponentModel.DataAnnotation Reference.

If there is a work around without using DataAnnotation to set the column order using code that will be great

Body:
What about using a static array inside your class or in a different class which list all columns in the order you want, and while saving to excel you loop through this array first to get columns in the correct order.

Something like that:

public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public List<string> OrderedProperties => new List<string> { "LastName", "FirstName", "Id" };
}

public class DataAccess
{
    public void SaveStudentToExcel()
    {
        var student = new Student(); // instead of new this should be your object filled with real data.
        foreach (var propName in student.OrderedProperties)
        {
            var val = student.GetType().GetProperty(propName).GetValue(student, null);

            // new cell in excel => with val and propName then save
        }
    }
}


问:
Pattern matching problem with Prolog
EDIT: See my answer below for why I am a fool. There is still a riddle in this that I would love to have answered though.

I've been stuck on this for far too long. I'm trying to print out a sudoku solution in a nice looking grid.

I think I'm running into problems because I don't understand some key part of how pattern matching works in Prolog.

Without further ado, my code:

```<code>prettier_print([]).
prettier_print([Puzzle]) :- prettier_print(0, [Puzzle]).

prettier_print(0, Puzzle) :-
    writeln('┌───────┬───────┬───────┐'),
    prettier_print(1, Puzzle).
prettier_print(4, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(5, Puzzle).
prettier_print(8, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(9, Puzzle).
prettier_print(12, []) :-
    writeln('└───────┴───────┴───────┘').

prettier_print(N, [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | Puzzle]) :-
    member(N, [1,2,3,5,6,7,9,10,11]),  % tried this when the line below did not work
    % N =\= 0, N =\= 4, N =\= 8, N =\= 13,

    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]),
    succ(N, N1),
    prettier_print(N1, Puzzle).
</code>```

Here is the call:

```<code>prettier_print(0, [1,2,3,4,5,6,7,8,9,
                   2,2,3,4,5,6,7,8,9,
                   3,2,3,4,5,6,7,8,9,
                   4,2,3,4,5,6,7,8,9,
                   5,2,3,4,5,6,7,8,9,
                   6,2,3,4,5,6,7,8,9,
                   7,2,3,4,5,6,7,8,9,
                   8,2,3,4,5,6,7,8,9,
                   9,2,3,4,5,6,7,8,9]).
</code>```

And here is the output:

```<code>┌───────┬───────┬───────┐
│ 1 2 3 │ 4 5 6 │ 7 8 9 │
│ 2 2 3 │ 4 5 6 │ 7 8 9 │
│ 3 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 4 2 3 │ 4 5 6 │ 7 8 9 │
│ 5 2 3 │ 4 5 6 │ 7 8 9 │
│ 6 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 7 2 3 │ 4 5 6 │ 7 8 9 │
│ 8 2 3 │ 4 5 6 │ 7 8 9 │
│ 9 2 3 │ 4 5 6 │ 7 8 9 │
└───────┴───────┴───────┘
true ;
false.
</code>```

The problem is it doesn't JUST return with true, I have to press ;, and then it returns false. This in turn means that my prettier_print/1 rule doesn't work properly.

I think I know enough to figure out that this means:

Prolog is backtracking and trying another interpretation of my rules (seeing if there is anything else it can unify with, if I'm understanding my terms correctly). This finds one other thing to unify with that, but that fails immediately. Is that right?

I want there to be only one possible interpretation. How can I fix my function to mean that?

Thank you for any help, this has me feeling like such a fool!

答:
For one way to see this, try SWI-Prolog's graphical tracer:

```<code>?- gtrace, your_goal.
</code>```

The tracer will show you where choicepoints are created, introducing non-determinism. On backtracking (for example, when you press SPACE or ";" on the toplevel), remaining alternative clauses will be considered.

Title: Pattern matching problem with Prolog

Body:
EDIT: See my answer below for why I am a fool. There is still a riddle in this that I would love to have answered though.

I've been stuck on this for far too long. I'm trying to print out a sudoku solution in a nice looking grid.

I think I'm running into problems because I don't understand some key part of how pattern matching works in Prolog.

Without further ado, my code:

prettier_print([]).
prettier_print([Puzzle]) :- prettier_print(0, [Puzzle]).

prettier_print(0, Puzzle) :-
    writeln('┌───────┬───────┬───────┐'),
    prettier_print(1, Puzzle).
prettier_print(4, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(5, Puzzle).
prettier_print(8, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(9, Puzzle).
prettier_print(12, []) :-
    writeln('└───────┴───────┴───────┘').

prettier_print(N, [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | Puzzle]) :-
    member(N, [1,2,3,5,6,7,9,10,11]),  % tried this when the line below did not work
    % N =\= 0, N =\= 4, N =\= 8, N =\= 13,

    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]),
    succ(N, N1),
    prettier_print(N1, Puzzle).

Here is the call:

prettier_print(0, [1,2,3,4,5,6,7,8,9,
                   2,2,3,4,5,6,7,8,9,
                   3,2,3,4,5,6,7,8,9,
                   4,2,3,4,5,6,7,8,9,
                   5,2,3,4,5,6,7,8,9,
                   6,2,3,4,5,6,7,8,9,
                   7,2,3,4,5,6,7,8,9,
                   8,2,3,4,5,6,7,8,9,
                   9,2,3,4,5,6,7,8,9]).

And here is the output:

┌───────┬───────┬───────┐
│ 1 2 3 │ 4 5 6 │ 7 8 9 │
│ 2 2 3 │ 4 5 6 │ 7 8 9 │
│ 3 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 4 2 3 │ 4 5 6 │ 7 8 9 │
│ 5 2 3 │ 4 5 6 │ 7 8 9 │
│ 6 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 7 2 3 │ 4 5 6 │ 7 8 9 │
│ 8 2 3 │ 4 5 6 │ 7 8 9 │
│ 9 2 3 │ 4 5 6 │ 7 8 9 │
└───────┴───────┴───────┘
true ;
false.

The problem is it doesn't JUST return with true, I have to press ;, and then it returns false. This in turn means that my prettier_print/1 rule doesn't work properly.

I think I know enough to figure out that this means:

Prolog is backtracking and trying another interpretation of my rules (seeing if there is anything else it can unify with, if I'm understanding my terms correctly). This finds one other thing to unify with that, but that fails immediately. Is that right?

I want there to be only one possible interpretation. How can I fix my function to mean that?

Thank you for any help, this has me feeling like such a fool!

Body:
For one way to see this, try SWI-Prolog's graphical tracer:

?- gtrace, your_goal.

The tracer will show you where choicepoints are created, introducing non-determinism. On backtracking (for example, when you press SPACE or ";" on the toplevel), remaining alternative clauses will be considered.