问:
Upload to Skip Web Server
I'm trying to upload a JSON file to the SKIP (getskip.com) web server and I am getting socket error 10054. They are not very good at giving samples of how, since they think everyone is using cUrl, but we are still using Delphi XE6 with Indy.

Here is what they provided.

For Java using OK HTTP:

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
RequestBody body = RequestBody.create(mediaType, "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"path\"; filename=\"<<file_name>>\"\r\nContent-Type: application/vnd.novadigm.ext\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"data\"\r\n\r\n[{\"file_key\": \"path\", \"store_id\"::<<store_id>>}]\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");
Request request = new Request.Builder()
  .url("https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json")
  .post(body)
  .addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
  .addHeader("Authorization", "Bearer <<api_user_token>>")
  .addHeader("Content-Type", "application/x-www-form-urlencoded")
  .addHeader("User-Agent", "PostmanRuntime/7.13.0")
  .addHeader("Accept", "*/*")
  .addHeader("Cache-Control", "no-cache")
  .addHeader("Postman-Token", "de9932d2-bda0-4df6-8a9a-e2d4f74c2048,d59a9861-1a65-471a-8ada-6e025e985dca")
  .addHeader("Host", "upload.goskip.com:8080")
  .addHeader("accept-encoding", "gzip, deflate")
  .addHeader("content-length", "407")
  .addHeader("Connection", "keep-alive")
  .addHeader("cache-control", "no-cache")
  .build();

Response response = client.newCall(request).execute();
```

<p>Java using Unirest:</p>

<pre class="lang-java prettyprint-override"><code>HttpResponse<String> response = Unirest.post("https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json")
  .header("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
  .header("Authorization", "Bearer <<api_user_token>>")
  .header("Content-Type", "application/x-www-form-urlencoded")
  .header("User-Agent", "PostmanRuntime/7.13.0")
  .header("Accept", "*/*")
  .header("Cache-Control", "no-cache")
  .header("Postman-Token", "de9932d2-bda0-4df6-8a9a-e2d4f74c2048,d1ea454e-594c-4746-9de7-e813377ff095")
  .header("Host", "upload.goskip.com:8080")
  .header("accept-encoding", "gzip, deflate")
  .header("content-length", "407")
  .header("Connection", "keep-alive")
  .header("cache-control", "no-cache")
  .body("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"path\"; filename=\"<<file_name>>\"\r\nContent-Type: application/vnd.novadigm.ext\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"data\"\r\n\r\n[{\"file_key\": \"path\", \"store_id\":<<store_id>>}]\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--")
  .asString();
</code>```

PHP using HttpRequest:

<?php

$request = new HttpRequest();
$request->setUrl('https://upload.goskip.com:8080/v2/backoffice/files/pricebook');
$request->setMethod(HTTP_METH_POST);

$request->setQueryData(array(
  'type' => 'json'
));

$request->setHeaders(array(
  'cache-control' => 'no-cache',
  'Connection' => 'keep-alive',
  'content-length' => '407',
  'accept-encoding' => 'gzip, deflate',
  'Host' => 'upload.goskip.com:8080',
  'Postman-Token' => 'de9932d2-bda0-4df6-8a9a-e2d4f74c2048,c7acbc0a-6450-43d1-b4ca-bc2a56cebc4e',
  'Cache-Control' => 'no-cache',
  'Accept' => '*/*',
  'User-Agent' => 'PostmanRuntime/7.13.0',
  'Content-Type' => 'application/x-www-form-urlencoded',
  'Authorization' => 'Bearer <<api_user_token>>',
  'content-type' => 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
));

$request->setBody('------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="path"; filename="<<file_name>>"
Content-Type: application/vnd.novadigm.ext

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="data"

[{"file_key": "path", "store_id"::<<store_id>>}]
------WebKitFormBoundary7MA4YWxkTrZu0gW--');

try {
  $response = $request->send();

  echo $response->getBody();
} catch (HttpException $ex) {
  echo $ex;
}
```

<p>Here is what I tried in Indy. I pasted the JSON file in to a Memo on the Form:</p>

<pre class="lang-pascal prettyprint-override"><code>function TFormJsonWrite.HTTPPost: String;
var
  JsonToSend : TStringStream;
  Response: String;
  IdHTTP1: TIdHTTP;
  IdSSLIOHandlerSocketOpenSSL2: TIdSSLIOHandlerSocketOpenSSL;
begin
  IdSSLIOHandlerSocketOpenSSL2 := TIdSSLIOHandlerSocketOpenSSL.Create;
  IdHTTP1 := TIdHTTP.Create;
  IdHTTP1.Request.CharSet := 'utf-8';

  JsonToSend := TStringStream.Create(memolog.text, TEncoding.UTF8);
  IdHTTP1.Request.ContentDisposition := 'form-data; name=[{"file_key":''' + memolog.text + ''', "store_id"::001}]------WebKitFormBoundary7MA4YWxkTrZu0gW--';
  IdHTTP1.Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
  IdHTTP1.Request.ContentType := 'multipart/form-data';
  IdHTTP1.Request.Accept := '*/*';
  IdHTTP1.Request.AcceptEncoding := 'gzip,deflate';
  IdHTTP1.Request.ContentLength := -1;
  IdHTTP1.Request.CacheControl := 'no-cache';
  IdHTTP1.Request.Connection := 'keep-alive';
  IdHTTP1.Request.BasicAuthentication := false;
  IdHTTP1.Request.Host := 'upload.goskip.com:8080';
  IdHTTP1.Request.CustomHeaders.Clear;
  IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer eyJhbGc.......................';
  IdHTTP1.Request.CustomHeaders.Values['Postman-Token'] := 'de9932d2-bda0-4df6-8a9a-e2d4f74c2048,d59a9861-1a65-471a-8ada-6e025e985dca';
  IdHTTP1.ReadTimeout := 50000;
  IdSSLIOHandlerSocketOpenSSL2.SSLOptions.Method := sslvTLSv1_2;
  IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL2;
  Response := IdHTTP1.Post('https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json', JsonToSend);
  HTTPPost := Response;
  JsonToSend.Free;
  IdHTTP1.Free;
end;
</code>```

curl

```<code>Kim@KIMNEW MINGW64 ~
$ curl -F "file=@"C:/mydata/Items-114946.json -H "authorization:Bearer eyJ........................." https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json&store_id=001
[1] 13296
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
Kim@KIMNEW MINGW64 ~
100  951k  100    53  100  951k     53   968k  0:00:01 --:--:--  0:00:01  967k{"message":"#/data: null value where array expected"}
</code>```

They updating all their endpoints this is the latest I got.

```<code>curl -X POST   'https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json'   -H 'Authorization: Bearer <api_user_token>' -F path=@<path_to_first_file>   -F path1=@<path_to_second_file>   -F 'data=[{"file_key":"path","store_id":<store_id_for_first_file>},{"file_key":"path1","store_id":<store_id_for_second_file>}]'
</code>```

答:
Your Delphi code is all wrong.

You are setting the wrong Content-Disposition header to the wrong value.

You are posting the JSON data as-is without wrapping it inside of MIME at all.

DO NOT set the TIdHTTP.Request.AcceptEncoding property manually.  You are not  setting up the TIdHTTP to enable compression support, but you are giving the server permission to send compressed responses, which TIdHTTP will not be able to decompress for you.

The correct way to send a multipart/form-data request using TIdHTTP is to use the overloaded Post() method that takes a TIdMultipartFormDataStream as input, like this:

function TFormJsonWrite.HTTPPost: String;
var
  JsonToSend : String;
  IdHTTP1: TIdHTTP;
  IdSSLIOHandlerSocketOpenSSL2: TIdSSLIOHandlerSocketOpenSSL;
  PostData: TIdMultipartFormDataStream;
begin
  JsonToSend := '[{"file_key": "path", "store_id": <<store_id>>}]';

  IdHTTP1 := TIdHTTP.Create;
  try
    IdHTTP1.ReadTimeout := 50000;

    IdHTTP1.Request.BasicAuthentication := false;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer ...';
    IdHTTP1.Request.CustomHeaders.Values['Postman-Token'] := '...';

    IdSSLIOHandlerSocketOpenSSL2 := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
    IdSSLIOHandlerSocketOpenSSL2.SSLOptions.Method := sslvTLSv1_2;
    IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL2;

    PostData := TIdMultipartFormDataStream.Create;
    try
      PostData.AddFormField('path', '', '', 'application/vnd.novadigm.ext').FileName := '<<file_name>>';
      PostData.AddFormField('data', JsonToSend, 'utf-8', 'application/json').ContentTransfer := '8bit';

      Result := IdHTTP1.Post('https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json', PostData);
    finally
      PostData.Free;
    end;
  finally
    IdHTTP1.Free;
  end;
end;
```
<p>If, by chance, the server has issues with how <code>TIdMultipartFormDataStream</code> formats the MIME data (ie, if the server rejects the MIME <code>Content-Type</code> and/or <code>Content-Transfer-Encoding</code> headers that are generated by <code>TIdMultipartFormDataStream</code> for each MIME field, as it does not yet conform to RFC 7578, which is used by HTML5), you can format the MIME data manually to match SKIP's examples exactly, like this:</p>
<pre class="lang-pascal prettyprint-override"><code>function TFormJsonWrite.HTTPPost: String;
var
  JsonToSend : String;
  IdHTTP1: TIdHTTP;
  IdSSLIOHandlerSocketOpenSSL2: TIdSSLIOHandlerSocketOpenSSL;
  PostData: TStringStream;
begin
  JsonToSend := '[{"file_key": "path", "store_id": <<store_id>>}]';

  IdHTTP1 := TIdHTTP.Create;
  try
    IdHTTP1.ReadTimeout := 50000;

    IdHTTP1.Request.ContentType := 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW';
    IdHTTP1.Request.BasicAuthentication := false;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer ...';
    IdHTTP1.Request.CustomHeaders.Values['Postman-Token'] := '...';

    IdSSLIOHandlerSocketOpenSSL2 := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
    IdSSLIOHandlerSocketOpenSSL2.SSLOptions.Method := sslvTLSv1_2;
    IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL2;

    PostData := TStringStream.Create(
      '------WebKitFormBoundary7MA4YWxkTrZu0gW' + EOL +
      'Content-Disposition: form-data; name="path"; filename="<<file_name>>"' + EOL +
      'Content-Type: application/vnd.novadigm.ext' + EOL +
      EOL +
      EOL +
      '------WebKitFormBoundary7MA4YWxkTrZu0gW' + EOL +
      'Content-Disposition: form-data; name="data"' + EOL +
      EOL +
      JsonToSend + EOL +
      '------WebKitFormBoundary7MA4YWxkTrZu0gW--',
      TEncoding.UTF8
    );
    try
      Result := IdHTTP1.Post('https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json', PostData);
    finally
      PostData.Free;
    end;
  finally
    IdHTTP1.Free;
  end;
end;
</code>```

UPDATE: based on the new curl commands you have provided, the original examples you showed do not match the commands.  Try something more like this instead:

function TFormJsonWrite.HTTPPost: String;
var
  JsonToSend : String;
  IdHTTP1: TIdHTTP;
  IdSSLIOHandlerSocketOpenSSL2: TIdSSLIOHandlerSocketOpenSSL;
  PostData: TIdMultipartFormDataStream;
begin
  JsonToSend := '[{"file_key": "path", "store_id": <<store_id>>}]';

  IdHTTP1 := TIdHTTP.Create;
  try
    IdHTTP1.ReadTimeout := 50000;

    IdHTTP1.Request.BasicAuthentication := false;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer ...';
    IdHTTP1.Request.CustomHeaders.Values['Postman-Token'] := '...';

    IdSSLIOHandlerSocketOpenSSL2 := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
    IdSSLIOHandlerSocketOpenSSL2.SSLOptions.Method := sslvTLSv1_2;
    IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL2;

    PostData := TIdMultipartFormDataStream.Create;
    try
      PostData.AddFile('path', '<<path_to_file>>').ContentTransfer := 'binary';
      PostData.AddFormField('data', JsonToSend, 'utf-8', 'application/json').ContentTransfer := '8bit';

      Result := IdHTTP1.Post('https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json', PostData);
    finally
      PostData.Free;
    end;
  finally
    IdHTTP1.Free;
  end;
end;
```
<p>Or:</p>
<pre class="lang-pascal prettyprint-override"><code>function TFormJsonWrite.HTTPPost: String;
var
  JsonToSend : String;
  IdHTTP1: TIdHTTP;
  IdSSLIOHandlerSocketOpenSSL2: TIdSSLIOHandlerSocketOpenSSL;
  PostData: TMemoryStream;
  FS: TIdReadFileExclusiveStream;
begin
  JsonToSend := '[{"file_key": "path", "store_id": <<store_id>>}]';

  IdHTTP1 := TIdHTTP.Create;
  try
    IdHTTP1.ReadTimeout := 50000;

    IdHTTP1.Request.ContentType := 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW';
    IdHTTP1.Request.BasicAuthentication := false;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer ...';
    IdHTTP1.Request.CustomHeaders.Values['Postman-Token'] := '...';

    IdSSLIOHandlerSocketOpenSSL2 := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
    IdSSLIOHandlerSocketOpenSSL2.SSLOptions.Method := sslvTLSv1_2;
    IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL2;

    PostData := TMemoryStream.Create;
    try
      WriteStringToStream(PostData, '------WebKitFormBoundary7MA4YWxkTrZu0gW' + EOL);
      WriteStringToStream(PostData, 'Content-Disposition: form-data; name="path"; filename="<<file_name>>"' + EOL);
      WriteStringToStream(PostData, 'Content-Type: ' + GetMIMETypeFromFile('<<file_name>>') + EOL);
      WriteStringToStream(PostData, 'Content-Transfer-Encoding: binary' + EOL);
      WriteStringToStream(PostData, EOL);

      FS := TIdReadFileExclusiveStream.Create('<<path_to_file>>', fmOpenRead or fmShareDenyWrite);
      try
        PostData.CopyFrom(FS, 0);
      finally
        FS.Free;
      end;

      WriteStringToStream(PostData, EOL);
      WriteStringToStream(PostData, '------WebKitFormBoundary7MA4YWxkTrZu0gW' + EOL);
      WriteStringToStream(PostData, 'Content-Disposition: form-data; name="data"' + EOL);
      WriteStringToStream(PostData, EOL);
      WriteStringToStream(PostData, JsonToSend + EOL, IndyTextEncoding_UTF8);
      WriteStringToStream(PostData, '------WebKitFormBoundary7MA4YWxkTrZu0gW--');

      PostData.Position := 0;

      Result := IdHTTP1.Post('https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json', PostData);
    finally
      PostData.Free;
    end;
  finally
    IdHTTP1.Free;
  end;
end;
</code>```

Title: Upload to Skip Web Server

Body:
I'm trying to upload a JSON file to the SKIP (getskip.com) web server and I am getting socket error 10054. They are not very good at giving samples of how, since they think everyone is using cUrl, but we are still using Delphi XE6 with Indy.

Here is what they provided.

For Java using OK HTTP:

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
RequestBody body = RequestBody.create(mediaType, "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"path\"; filename=\"<<file_name>>\"\r\nContent-Type: application/vnd.novadigm.ext\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"data\"\r\n\r\n[{\"file_key\": \"path\", \"store_id\"::<<store_id>>}]\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");
Request request = new Request.Builder()
  .url("https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json")
  .post(body)
  .addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
  .addHeader("Authorization", "Bearer <<api_user_token>>")
  .addHeader("Content-Type", "application/x-www-form-urlencoded")
  .addHeader("User-Agent", "PostmanRuntime/7.13.0")
  .addHeader("Accept", "*/*")
  .addHeader("Cache-Control", "no-cache")
  .addHeader("Postman-Token", "de9932d2-bda0-4df6-8a9a-e2d4f74c2048,d59a9861-1a65-471a-8ada-6e025e985dca")
  .addHeader("Host", "upload.goskip.com:8080")
  .addHeader("accept-encoding", "gzip, deflate")
  .addHeader("content-length", "407")
  .addHeader("Connection", "keep-alive")
  .addHeader("cache-control", "no-cache")
  .build();

Response response = client.newCall(request).execute();

Java using Unirest:

HttpResponse<String> response = Unirest.post("https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json")
  .header("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
  .header("Authorization", "Bearer <<api_user_token>>")
  .header("Content-Type", "application/x-www-form-urlencoded")
  .header("User-Agent", "PostmanRuntime/7.13.0")
  .header("Accept", "*/*")
  .header("Cache-Control", "no-cache")
  .header("Postman-Token", "de9932d2-bda0-4df6-8a9a-e2d4f74c2048,d1ea454e-594c-4746-9de7-e813377ff095")
  .header("Host", "upload.goskip.com:8080")
  .header("accept-encoding", "gzip, deflate")
  .header("content-length", "407")
  .header("Connection", "keep-alive")
  .header("cache-control", "no-cache")
  .body("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"path\"; filename=\"<<file_name>>\"\r\nContent-Type: application/vnd.novadigm.ext\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"data\"\r\n\r\n[{\"file_key\": \"path\", \"store_id\":<<store_id>>}]\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--")
  .asString();

PHP using HttpRequest:

<?php

$request = new HttpRequest();
$request->setUrl('https://upload.goskip.com:8080/v2/backoffice/files/pricebook');
$request->setMethod(HTTP_METH_POST);

$request->setQueryData(array(
  'type' => 'json'
));

$request->setHeaders(array(
  'cache-control' => 'no-cache',
  'Connection' => 'keep-alive',
  'content-length' => '407',
  'accept-encoding' => 'gzip, deflate',
  'Host' => 'upload.goskip.com:8080',
  'Postman-Token' => 'de9932d2-bda0-4df6-8a9a-e2d4f74c2048,c7acbc0a-6450-43d1-b4ca-bc2a56cebc4e',
  'Cache-Control' => 'no-cache',
  'Accept' => '*/*',
  'User-Agent' => 'PostmanRuntime/7.13.0',
  'Content-Type' => 'application/x-www-form-urlencoded',
  'Authorization' => 'Bearer <<api_user_token>>',
  'content-type' => 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
));

$request->setBody('------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="path"; filename="<<file_name>>"
Content-Type: application/vnd.novadigm.ext

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="data"

[{"file_key": "path", "store_id"::<<store_id>>}]
------WebKitFormBoundary7MA4YWxkTrZu0gW--');

try {
  $response = $request->send();

  echo $response->getBody();
} catch (HttpException $ex) {
  echo $ex;
}

Here is what I tried in Indy. I pasted the JSON file in to a Memo on the Form:

function TFormJsonWrite.HTTPPost: String;
var
  JsonToSend : TStringStream;
  Response: String;
  IdHTTP1: TIdHTTP;
  IdSSLIOHandlerSocketOpenSSL2: TIdSSLIOHandlerSocketOpenSSL;
begin
  IdSSLIOHandlerSocketOpenSSL2 := TIdSSLIOHandlerSocketOpenSSL.Create;
  IdHTTP1 := TIdHTTP.Create;
  IdHTTP1.Request.CharSet := 'utf-8';

  JsonToSend := TStringStream.Create(memolog.text, TEncoding.UTF8);
  IdHTTP1.Request.ContentDisposition := 'form-data; name=[{"file_key":''' + memolog.text + ''', "store_id"::001}]------WebKitFormBoundary7MA4YWxkTrZu0gW--';
  IdHTTP1.Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
  IdHTTP1.Request.ContentType := 'multipart/form-data';
  IdHTTP1.Request.Accept := '*/*';
  IdHTTP1.Request.AcceptEncoding := 'gzip,deflate';
  IdHTTP1.Request.ContentLength := -1;
  IdHTTP1.Request.CacheControl := 'no-cache';
  IdHTTP1.Request.Connection := 'keep-alive';
  IdHTTP1.Request.BasicAuthentication := false;
  IdHTTP1.Request.Host := 'upload.goskip.com:8080';
  IdHTTP1.Request.CustomHeaders.Clear;
  IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer eyJhbGc.......................';
  IdHTTP1.Request.CustomHeaders.Values['Postman-Token'] := 'de9932d2-bda0-4df6-8a9a-e2d4f74c2048,d59a9861-1a65-471a-8ada-6e025e985dca';
  IdHTTP1.ReadTimeout := 50000;
  IdSSLIOHandlerSocketOpenSSL2.SSLOptions.Method := sslvTLSv1_2;
  IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL2;
  Response := IdHTTP1.Post('https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json', JsonToSend);
  HTTPPost := Response;
  JsonToSend.Free;
  IdHTTP1.Free;
end;

curl

Kim@KIMNEW MINGW64 ~
$ curl -F "file=@"C:/mydata/Items-114946.json -H "authorization:Bearer eyJ........................." https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json&store_id=001
[1] 13296
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
Kim@KIMNEW MINGW64 ~
100  951k  100    53  100  951k     53   968k  0:00:01 --:--:--  0:00:01  967k{"message":"#/data: null value where array expected"}

They updating all their endpoints this is the latest I got.

curl -X POST   'https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json'   -H 'Authorization: Bearer <api_user_token>' -F path=@<path_to_first_file>   -F path1=@<path_to_second_file>   -F 'data=[{"file_key":"path","store_id":<store_id_for_first_file>},{"file_key":"path1","store_id":<store_id_for_second_file>}]'

Body:
Your Delphi code is all wrong.

You are setting the wrong Content-Disposition header to the wrong value.

You are posting the JSON data as-is without wrapping it inside of MIME at all.

DO NOT set the TIdHTTP.Request.AcceptEncoding property manually.  You are not  setting up the TIdHTTP to enable compression support, but you are giving the server permission to send compressed responses, which TIdHTTP will not be able to decompress for you.

The correct way to send a multipart/form-data request using TIdHTTP is to use the overloaded Post() method that takes a TIdMultipartFormDataStream as input, like this:

function TFormJsonWrite.HTTPPost: String;
var
  JsonToSend : String;
  IdHTTP1: TIdHTTP;
  IdSSLIOHandlerSocketOpenSSL2: TIdSSLIOHandlerSocketOpenSSL;
  PostData: TIdMultipartFormDataStream;
begin
  JsonToSend := '[{"file_key": "path", "store_id": <<store_id>>}]';

  IdHTTP1 := TIdHTTP.Create;
  try
    IdHTTP1.ReadTimeout := 50000;

    IdHTTP1.Request.BasicAuthentication := false;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer ...';
    IdHTTP1.Request.CustomHeaders.Values['Postman-Token'] := '...';

    IdSSLIOHandlerSocketOpenSSL2 := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
    IdSSLIOHandlerSocketOpenSSL2.SSLOptions.Method := sslvTLSv1_2;
    IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL2;

    PostData := TIdMultipartFormDataStream.Create;
    try
      PostData.AddFormField('path', '', '', 'application/vnd.novadigm.ext').FileName := '<<file_name>>';
      PostData.AddFormField('data', JsonToSend, 'utf-8', 'application/json').ContentTransfer := '8bit';

      Result := IdHTTP1.Post('https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json', PostData);
    finally
      PostData.Free;
    end;
  finally
    IdHTTP1.Free;
  end;
end;

If, by chance, the server has issues with how TIdMultipartFormDataStream formats the MIME data (ie, if the server rejects the MIME Content-Type and/or Content-Transfer-Encoding headers that are generated by TIdMultipartFormDataStream for each MIME field, as it does not yet conform to RFC 7578, which is used by HTML5), you can format the MIME data manually to match SKIP's examples exactly, like this:

function TFormJsonWrite.HTTPPost: String;
var
  JsonToSend : String;
  IdHTTP1: TIdHTTP;
  IdSSLIOHandlerSocketOpenSSL2: TIdSSLIOHandlerSocketOpenSSL;
  PostData: TStringStream;
begin
  JsonToSend := '[{"file_key": "path", "store_id": <<store_id>>}]';

  IdHTTP1 := TIdHTTP.Create;
  try
    IdHTTP1.ReadTimeout := 50000;

    IdHTTP1.Request.ContentType := 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW';
    IdHTTP1.Request.BasicAuthentication := false;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer ...';
    IdHTTP1.Request.CustomHeaders.Values['Postman-Token'] := '...';

    IdSSLIOHandlerSocketOpenSSL2 := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
    IdSSLIOHandlerSocketOpenSSL2.SSLOptions.Method := sslvTLSv1_2;
    IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL2;

    PostData := TStringStream.Create(
      '------WebKitFormBoundary7MA4YWxkTrZu0gW' + EOL +
      'Content-Disposition: form-data; name="path"; filename="<<file_name>>"' + EOL +
      'Content-Type: application/vnd.novadigm.ext' + EOL +
      EOL +
      EOL +
      '------WebKitFormBoundary7MA4YWxkTrZu0gW' + EOL +
      'Content-Disposition: form-data; name="data"' + EOL +
      EOL +
      JsonToSend + EOL +
      '------WebKitFormBoundary7MA4YWxkTrZu0gW--',
      TEncoding.UTF8
    );
    try
      Result := IdHTTP1.Post('https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json', PostData);
    finally
      PostData.Free;
    end;
  finally
    IdHTTP1.Free;
  end;
end;

UPDATE: based on the new curl commands you have provided, the original examples you showed do not match the commands.  Try something more like this instead:

function TFormJsonWrite.HTTPPost: String;
var
  JsonToSend : String;
  IdHTTP1: TIdHTTP;
  IdSSLIOHandlerSocketOpenSSL2: TIdSSLIOHandlerSocketOpenSSL;
  PostData: TIdMultipartFormDataStream;
begin
  JsonToSend := '[{"file_key": "path", "store_id": <<store_id>>}]';

  IdHTTP1 := TIdHTTP.Create;
  try
    IdHTTP1.ReadTimeout := 50000;

    IdHTTP1.Request.BasicAuthentication := false;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer ...';
    IdHTTP1.Request.CustomHeaders.Values['Postman-Token'] := '...';

    IdSSLIOHandlerSocketOpenSSL2 := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
    IdSSLIOHandlerSocketOpenSSL2.SSLOptions.Method := sslvTLSv1_2;
    IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL2;

    PostData := TIdMultipartFormDataStream.Create;
    try
      PostData.AddFile('path', '<<path_to_file>>').ContentTransfer := 'binary';
      PostData.AddFormField('data', JsonToSend, 'utf-8', 'application/json').ContentTransfer := '8bit';

      Result := IdHTTP1.Post('https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json', PostData);
    finally
      PostData.Free;
    end;
  finally
    IdHTTP1.Free;
  end;
end;

Or:

function TFormJsonWrite.HTTPPost: String;
var
  JsonToSend : String;
  IdHTTP1: TIdHTTP;
  IdSSLIOHandlerSocketOpenSSL2: TIdSSLIOHandlerSocketOpenSSL;
  PostData: TMemoryStream;
  FS: TIdReadFileExclusiveStream;
begin
  JsonToSend := '[{"file_key": "path", "store_id": <<store_id>>}]';

  IdHTTP1 := TIdHTTP.Create;
  try
    IdHTTP1.ReadTimeout := 50000;

    IdHTTP1.Request.ContentType := 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW';
    IdHTTP1.Request.BasicAuthentication := false;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer ...';
    IdHTTP1.Request.CustomHeaders.Values['Postman-Token'] := '...';

    IdSSLIOHandlerSocketOpenSSL2 := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
    IdSSLIOHandlerSocketOpenSSL2.SSLOptions.Method := sslvTLSv1_2;
    IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL2;

    PostData := TMemoryStream.Create;
    try
      WriteStringToStream(PostData, '------WebKitFormBoundary7MA4YWxkTrZu0gW' + EOL);
      WriteStringToStream(PostData, 'Content-Disposition: form-data; name="path"; filename="<<file_name>>"' + EOL);
      WriteStringToStream(PostData, 'Content-Type: ' + GetMIMETypeFromFile('<<file_name>>') + EOL);
      WriteStringToStream(PostData, 'Content-Transfer-Encoding: binary' + EOL);
      WriteStringToStream(PostData, EOL);

      FS := TIdReadFileExclusiveStream.Create('<<path_to_file>>', fmOpenRead or fmShareDenyWrite);
      try
        PostData.CopyFrom(FS, 0);
      finally
        FS.Free;
      end;

      WriteStringToStream(PostData, EOL);
      WriteStringToStream(PostData, '------WebKitFormBoundary7MA4YWxkTrZu0gW' + EOL);
      WriteStringToStream(PostData, 'Content-Disposition: form-data; name="data"' + EOL);
      WriteStringToStream(PostData, EOL);
      WriteStringToStream(PostData, JsonToSend + EOL, IndyTextEncoding_UTF8);
      WriteStringToStream(PostData, '------WebKitFormBoundary7MA4YWxkTrZu0gW--');

      PostData.Position := 0;

      Result := IdHTTP1.Post('https://upload.goskip.com:8080/v2/backoffice/files/pricebook?type=json', PostData);
    finally
      PostData.Free;
    end;
  finally
    IdHTTP1.Free;
  end;
end;


来源: stackexchange

问:
Writing a jquery plugin in coffeescript - how to get "(function($)" and "(jQuery)"?
I am writing a jquery plugin in coffeescript but am not sure how to get the function wrapper part right.

My coffeescript starts with this:

```<code>$.fn.extend({
    myplugin: ->
        @each ->
</code>```

Which creates the javascript with a function wrapper:

```<code>(function() {
  $.fn.extend({
      myplugin: function() {
          return this.each(function() {
</code>```

but I want a '$' passed in like this:

```<code>(function($) {
  $.fn.extend({
</code>```

Similar for the ending I have... nothing in particular in coffeescript.

I get this in javascript:

```<code>})();
</code>```

But would like this:

```<code>})(jQuery);
</code>```

Does anyone know how to achieve this with the coffeescript compiler?
Or what is the best way to get this done within coffeescript?

答:
The easiest way is to extend $.fn object

Simple jQuery plugin can be written in CoffeeScript as follows:

```<code>$.extend $.fn,

  disable: ->
    @each ->
      e = $(this)
      e.attr("disabled", "disabled") if e.is("button") or e.is("input")
</code>```

it will compile to

```<code>(function() {
  $.extend($.fn, {
    disable: function() {
      return this.each(function() {
        var e;
        e = $(this);
        if (e.is("button") || e.is("input")) {
          return e.attr("disabled", "disabled");
        }
      });
    }
  });
}).call(this);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am writing a jquery plugin in coffeescript but am not sure how to get the function wrapper part right.

My coffeescript starts with this:

$.fn.extend({
    myplugin: ->
        @each ->

Which creates the javascript with a function wrapper:

(function() {
  $.fn.extend({
      myplugin: function() {
          return this.each(function() {

but I want a '$' passed in like this:

(function($) {
  $.fn.extend({

Similar for the ending I have... nothing in particular in coffeescript.

I get this in javascript:

})();

But would like this:

})(jQuery);

Does anyone know how to achieve this with the coffeescript compiler?
Or what is the best way to get this done within coffeescript?

Body:
The easiest way is to extend $.fn object

Simple jQuery plugin can be written in CoffeeScript as follows:

$.extend $.fn,

  disable: ->
    @each ->
      e = $(this)
      e.attr("disabled", "disabled") if e.is("button") or e.is("input")

it will compile to

(function() {
  $.extend($.fn, {
    disable: function() {
      return this.each(function() {
        var e;
        e = $(this);
        if (e.is("button") || e.is("input")) {
          return e.attr("disabled", "disabled");
        }
      });
    }
  });
}).call(this);

ContentLicense: CC BY-SA 3.0


问:
Relate elements in table form from Json file with jq
I'm new to jq and I have the following code to obtain tabulated the values for each element called Abc:

```<code>["Abc"], ( .. | objects | select(has("Abc")) | [.["Abc"]] ) | @tsv
</code>```

This is the current output I get:

```<code>"Abc"
"4"
"2"
"1"
"9"
"3"
"2"
"4"
"9"
</code>```

I would like to add 4 columns to the left to show for each Abc value the corresponding page, row and column. Additionally if possible as first column add a counter from 1 to number of "Abc" elements.

Below I show the current output, compared with the desired output and the structure of the Json file in order to clarify:

The input Json file is below:

```<code>{
  "document": {
    "page": [
      {
        "@index": "0",
        "image": {
          "Abc": "4"
        }
      },
      {
        "@index": "1",
        "row": [
          {
            "column": [
              {
                "text": {
                  "Abc": "2"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "1"
                }
              },
              {
                "text": {
                  "Abc": "9"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "3"
                }
              }
            ]
          }
        ]
      },
      {
        "@index": "2",
        "row": [
          {
            "column": [
              {
                "text": {
                  "Abc": "2"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "4"
                }
              },
              {
                "text": {
                  "Abc": "9"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}
</code>```

I hope someone could help me. Thanks in advance.

答:
The irregularity of the input data makes the requirements a little opaque, but the following produces the desired output.

```<code>["counter", "page", "row", "column", "Abc"],
(foreach (.document.page[] | objects) as $page ({page: -1, counter: 0};
  .page += 1
  | if ($page | (has("image") and (.image|has("Abc"))))
    then
      .counter +=1
      | .out = [.counter, .page, null, null, ($page|.image.Abc)]
    else foreach ($page | .row[]?) as $row (.row=-1;
      .row += 1
      | foreach ($row | .column[]) as $column (.column=-1;
          .column +=1
          | foreach ($column | .text | objects) as $x (.;
              .counter += 1
              | .out = [.counter, .page, .row, .column, $x["Abc"]]
              ; . )
           ; . )
      ; . )
    end
    ; .out )
)
| @tsv
</code>```

Output

Specifically, with the -r command-line option, the output produced from the given input is as follows (tabs included):

```<code>counter page    row column  Abc
1   0           4
2   1   0   0   2
3   1   1   0   1
4   1   1   1   9
5   1   2   0   3
6   2   0   0   2
7   2   1   0   4
8   2   1   1   9
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to jq and I have the following code to obtain tabulated the values for each element called Abc:

["Abc"], ( .. | objects | select(has("Abc")) | [.["Abc"]] ) | @tsv

This is the current output I get:

"Abc"
"4"
"2"
"1"
"9"
"3"
"2"
"4"
"9"

I would like to add 4 columns to the left to show for each Abc value the corresponding page, row and column. Additionally if possible as first column add a counter from 1 to number of "Abc" elements.

Below I show the current output, compared with the desired output and the structure of the Json file in order to clarify:

The input Json file is below:

{
  "document": {
    "page": [
      {
        "@index": "0",
        "image": {
          "Abc": "4"
        }
      },
      {
        "@index": "1",
        "row": [
          {
            "column": [
              {
                "text": {
                  "Abc": "2"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "1"
                }
              },
              {
                "text": {
                  "Abc": "9"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "3"
                }
              }
            ]
          }
        ]
      },
      {
        "@index": "2",
        "row": [
          {
            "column": [
              {
                "text": {
                  "Abc": "2"
                }
              }
            ]
          },
          {
            "column": [
              {
                "text": {
                  "Abc": "4"
                }
              },
              {
                "text": {
                  "Abc": "9"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

I hope someone could help me. Thanks in advance.

Body:
The irregularity of the input data makes the requirements a little opaque, but the following produces the desired output.

["counter", "page", "row", "column", "Abc"],
(foreach (.document.page[] | objects) as $page ({page: -1, counter: 0};
  .page += 1
  | if ($page | (has("image") and (.image|has("Abc"))))
    then
      .counter +=1
      | .out = [.counter, .page, null, null, ($page|.image.Abc)]
    else foreach ($page | .row[]?) as $row (.row=-1;
      .row += 1
      | foreach ($row | .column[]) as $column (.column=-1;
          .column +=1
          | foreach ($column | .text | objects) as $x (.;
              .counter += 1
              | .out = [.counter, .page, .row, .column, $x["Abc"]]
              ; . )
           ; . )
      ; . )
    end
    ; .out )
)
| @tsv

Output

Specifically, with the -r command-line option, the output produced from the given input is as follows (tabs included):

counter page    row column  Abc
1   0           4
2   1   0   0   2
3   1   1   0   1
4   1   1   1   9
5   1   2   0   3
6   2   0   0   2
7   2   1   0   4
8   2   1   1   9


问:
Initializing bloc in provider constructor vs initializing inline declaration of the bloc instance variable
After creating a Bloc Provider class that extends an InheritedWidget, what is the difference between initializing the bloc instance variable inside the Provider constructor and initializing it while declaring the variable?</p>

```<code>class CommentsProvider extends InheritedWidget {

  final CommentsBloc bloc;

  CommentsProvider({Key key, Widget child})
    : bloc = CommentsBloc(),
      super(key: key, child: child);
}

class CommentsProvider extends InheritedWidget {

  final CommentsBloc bloc = CommentsBloc();

  CommentsProvider({Key key, Widget child})
    : super(key: key, child: child);
}
</code>```

答:
These two are strictly equivalent, but both options are bad.

You should not create mutate data inside an Inheritedwidget.You could easily loose your state and it is considered bad practice.

Instead consider wrapping your Inheritedwidge  into a StatefulWidget, or use a package such as provider.

Using provider, you don't need to make such class anymore. Instead you can directly do:

```<code>Provider(
  builder: (_) => CommentsBloc(),
  dispose: (_, bloc) => bloc.dispose(),
  child: Whatever(),
)
</code>```

Body:
After creating a Bloc Provider class that extends an InheritedWidget, what is the difference between initializing the bloc instance variable inside the Provider constructor and initializing it while declaring the variable?

class CommentsProvider extends InheritedWidget {

  final CommentsBloc bloc;

  CommentsProvider({Key key, Widget child})
    : bloc = CommentsBloc(),
      super(key: key, child: child);
}

class CommentsProvider extends InheritedWidget {

  final CommentsBloc bloc = CommentsBloc();

  CommentsProvider({Key key, Widget child})
    : super(key: key, child: child);
}

Body:
These two are strictly equivalent, but both options are bad.

You should not create mutate data inside an Inheritedwidget.You could easily loose your state and it is considered bad practice.

Instead consider wrapping your Inheritedwidge  into a StatefulWidget, or use a package such as provider.

Using provider, you don't need to make such class anymore. Instead you can directly do:

Provider(
  builder: (_) => CommentsBloc(),
  dispose: (_, bloc) => bloc.dispose(),
  child: Whatever(),
)


问:
ModuleNotFoundError error with PyCharm project folder recs
I am working on a project in PyCharm.  The project has the following structure:

```<code>/projectRoot/
   folder1/
       somecode.py
   utils/
       __init__.py
       myutils1.py
</code>```

I'd want to know how I can do an import such that the import works when running the code in the pyCharm console in an interactive manner, as well as when running the code using the

```<code>python somecode.py
</code>```

command in the terminal.

Currently I do:

from utils.myutils1.py import myClass

But command line I get the error:

File "somecode.py", line 10, in
      from utils.myutils1 import myClass ModuleNotFoundError: No module named 'utils'

and on PyCharm:

Traceback (most recent call last):   File
  "/home/ubuntu/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py",
  line 2881, in run_code
      exec(code_obj, self.user_global_ns, self.user_ns)   File "", line 1, in
      from utils.myutils1 import myClass ModuleNotFoundError: No module named 'utils'

Any recommendations on the proper folder structure for modules within a project, and how to import them properly?

Thanks!

答:
Similar error here and this appears to be working for me:

Make sure Project Interpreter is set to, for example: C:\Python36\python.exe (in my case) and not a copy somewhere or another.

'File > Settings > Project ____ > Project Interpreter'

Or, long story short, if that route isn't cooperating, can also try finding workspace.xml and manually change SDK_HOME before starting PyCharm:

```<code><option name="SDK_HOME" value="C:\Python36\python.exe" />
</code>```

Body:
I am working on a project in PyCharm.  The project has the following structure:

/projectRoot/
   folder1/
       somecode.py
   utils/
       __init__.py
       myutils1.py

I'd want to know how I can do an import such that the import works when running the code in the pyCharm console in an interactive manner, as well as when running the code using the

python somecode.py

command in the terminal.

Currently I do:

from utils.myutils1.py import myClass

But command line I get the error:

File "somecode.py", line 10, in
      from utils.myutils1 import myClass ModuleNotFoundError: No module named 'utils'

and on PyCharm:

Traceback (most recent call last):   File
  "/home/ubuntu/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py",
  line 2881, in run_code
      exec(code_obj, self.user_global_ns, self.user_ns)   File "", line 1, in
      from utils.myutils1 import myClass ModuleNotFoundError: No module named 'utils'

Any recommendations on the proper folder structure for modules within a project, and how to import them properly?

Thanks!

Body:
Similar error here and this appears to be working for me:

Make sure Project Interpreter is set to, for example: C:\Python36\python.exe (in my case) and not a copy somewhere or another.

'File > Settings > Project ____ > Project Interpreter'

Or, long story short, if that route isn't cooperating, can also try finding workspace.xml and manually change SDK_HOME before starting PyCharm:

<option name="SDK_HOME" value="C:\Python36\python.exe" />


问:
Accessing "file" structure from user space
In reference to linux kernel, I would like to access the "file" structure information like current file offset in a user space C program. How do I do it?

Thanks in advance

答: Is "in reference to linux kernel" relevant, or misleading information? That is, are you asking about the kernel-level open file description and its status, or the C library-level FILE * used in stdio? Either way, you cannot poke at the internals yourself. There are accessor functions you can use: ftello(f) for stdio, or lseek(fd, 0, SEEK_CUR) for file descriptors.


问:
Use of Ngfor in label mat-ltab
I am facing a problem when using *ngFor in a mat-tab (included from angular material). I have a button that when clicked duplicates the code with *ngFor. My textArea inside this code has an id = serReal{{j}} where j is the index of the *ngFor. My reference is not working though. When I tried to get the element in my typescript code, it gets only the first one (serReal0). For the others I receive null.

My Html code:

```<code>    <!-- here I call it to duplicate -->
    <button mat-icon-button (click)="addData()" type="button" id="add_icon"></button>

    <!-- here it is my ngfor code which will duplicate -->
    <mat-tab-group>
          <mat-tab *ngFor="let itemServ of itemsServ; let j = index;" [label] = label[j]>
                <div class="areaTexto">
                      <div class="mdc-text-field text-field mdc-text-field--fullwidth mdc-text-field--textarea">
                            <textarea class="campoTextoServReal"
id ="servReal{{j}}"></textarea>
                      </div>
                </div>
          </mat-tab>
    </mat-tab-group>

    <!-- here I call it to read the text areas by the id -->
    <div class="divEncerraRel" id = apply>
          <button mat-raised-button (click) = 'setRelatorio()'>Encerrar Relatório</button>
    </div>
</code>```

My TS code:

```<code>    itemsServ: number[] = [1];

addData() {
  this.itemsServ.push(this.itemsServ.length + 1);
  this.label.push('Titulo');
}

setRelatorio() {
  for (let i = 0; i < this.itemsServ.length; i++) {
     console.log((<HTMLInputElement>document.getElementById("servReal" + i)));
  }
}
</code>```

答:
By Binding the HtmlElements to back-end code you have access to them.
For this purpose angular prepared "ViewChild Property decorator".

In your HTML I added :

```<code>    <textarea #cmp class="campoTextoServReal"
                       [id]="'servReal'+j"></textarea>
</code>```

And in BackEnd component class define a variable:

```<code>  @ViewChildren('cmp') components:QueryList<HTMLInputElement>;
</code>```

And for Logging

```<code> for (let i = 0; i < this.itemsServ.length; i++) {
    console.log(this.components._results[i].nativeElement.id);
     //console.log((<HTMLInputElement>document.getElementById("servReal" + i)));
  }
</code>```

link to stackbliz : https://stackblitz.com/edit/angular-material-example-lkbkm8?file=app/app.component.ts

Title: Use of Ngfor in label mat-ltab

Body:
I am facing a problem when using *ngFor in a mat-tab (included from angular material). I have a button that when clicked duplicates the code with *ngFor. My textArea inside this code has an id = serReal{{j}} where j is the index of the *ngFor. My reference is not working though. When I tried to get the element in my typescript code, it gets only the first one (serReal0). For the others I receive null.

My Html code:

    <button mat-icon-button (click)="addData()" type="button" id="add_icon"></button>

    <mat-tab-group>
          <mat-tab *ngFor="let itemServ of itemsServ; let j = index;" [label] = label[j]>

                            <textarea class="campoTextoServReal"
id ="servReal{{j}}"></textarea>

          </mat-tab>
    </mat-tab-group>

          <button mat-raised-button (click) = 'setRelatorio()'>Encerrar Relatório</button>

My TS code:

    itemsServ: number[] = [1];

addData() {
  this.itemsServ.push(this.itemsServ.length + 1);
  this.label.push('Titulo');
}

setRelatorio() {
  for (let i = 0; i < this.itemsServ.length; i++) {
     console.log((<HTMLInputElement>document.getElementById("servReal" + i)));
  }
}

Body:
By Binding the HtmlElements to back-end code you have access to them.
For this purpose angular prepared "ViewChild Property decorator".

In your HTML I added :

    <textarea #cmp class="campoTextoServReal"
                       [id]="'servReal'+j"></textarea>

And in BackEnd component class define a variable:

  @ViewChildren('cmp') components:QueryList<HTMLInputElement>;

And for Logging

 for (let i = 0; i < this.itemsServ.length; i++) {
    console.log(this.components._results[i].nativeElement.id);
     //console.log((<HTMLInputElement>document.getElementById("servReal" + i)));
  }

link to stackbliz : https://stackblitz.com/edit/angular-material-example-lkbkm8?file=app/app.component.ts


问:
How to convert date as string to date type
I have a variable '2019-05-30 21:01:09' that needs to be converted into 2019-05-30 21:01:09. What is the best way to go about this.

答:
```<code>from datetime import datetime

strToDate = datetime.strptime('2019-05-30 21:01:09','%Y-%m-%d %H:%M:%S')
</code>```

strptime() allows for the conversion of string to date time object provided that you give the format the function should expect as the second argument

Body:
from datetime import datetime

strToDate = datetime.strptime('2019-05-30 21:01:09','%Y-%m-%d %H:%M:%S')

strptime() allows for the conversion of string to date time object provided that you give the format the function should expect as the second argument


问:
Java -> Context, Expression expected?
I'm trying to learn and make an Android app via Java and Android Studio. My extent of Java is a few hours of youtube studying and a basic college course two years ago. I do know how to code however. I'm proficient with Python.

I wish to use this bluetooth library (https://github.com/akexorcist/Android-BluetoothSPPLibrary) so that I can communicate simply between a phone and a bluetooth enabled ESP32 microcontroller.

In my project I created a button which I'll use for testing this library.

```<code>*snip*
        //my button
        Button btn = findViewById(R.id.myBtn); //use R.id for the button id
        btn.setOnClickListener(new View.OnClickListener() { //button listener
            @Override
            public void onClick(View v) {
                //add whatever code here
                Log.e("my app", "log msg test"); //outputs to logcat window
                BluetoothSPP bt = new BluetoothSPP(Context);

                if(!bt.isBluetoothAvailable()) {
                    Log.e("my app", "bluetooth is not available");
                } else {
                    Log.e("my app", "bluetooth is available");
                }

            }
*snip*
</code>```

I'm stuck on:

```<code>BluetoothSPP bt = new BluetoothSPP(Context);
</code>```

Context gives me an error saying expression expected. I looked up what Context is in Java and understand why that would be a thing. However, I have no idea how to implement it, let alone, the proper context here.

答:
if your code is in a class that is inherited from Activity class

i.e. class MainActivity extends Activity

you can try passing like this:

```<code>BluetoothSPP bt = new BluetoothSPP(MainActivity.this);
</code>```

(because Activity is implementing context)

if it is inside something like a View class or a fragment you should try something like this:

```<code>BluetoothSPP bt = new BluetoothSPP(getContext());
</code>```

Title: Java -> Context, Expression expected?

Body:
I'm trying to learn and make an Android app via Java and Android Studio. My extent of Java is a few hours of youtube studying and a basic college course two years ago. I do know how to code however. I'm proficient with Python.

I wish to use this bluetooth library (https://github.com/akexorcist/Android-BluetoothSPPLibrary) so that I can communicate simply between a phone and a bluetooth enabled ESP32 microcontroller.

In my project I created a button which I'll use for testing this library.

*snip*
        //my button
        Button btn = findViewById(R.id.myBtn); //use R.id for the button id
        btn.setOnClickListener(new View.OnClickListener() { //button listener
            @Override
            public void onClick(View v) {
                //add whatever code here
                Log.e("my app", "log msg test"); //outputs to logcat window
                BluetoothSPP bt = new BluetoothSPP(Context);

                if(!bt.isBluetoothAvailable()) {
                    Log.e("my app", "bluetooth is not available");
                } else {
                    Log.e("my app", "bluetooth is available");
                }

            }
*snip*

I'm stuck on:

BluetoothSPP bt = new BluetoothSPP(Context);

Context gives me an error saying expression expected. I looked up what Context is in Java and understand why that would be a thing. However, I have no idea how to implement it, let alone, the proper context here.

Body:
if your code is in a class that is inherited from Activity class

i.e. class MainActivity extends Activity

you can try passing like this:

BluetoothSPP bt = new BluetoothSPP(MainActivity.this);

(because Activity is implementing context)

if it is inside something like a View class or a fragment you should try something like this:

BluetoothSPP bt = new BluetoothSPP(getContext());


问:
Unique identifier for Racket objects?
Is there a way to get a unique identifier for an object in Racket? For instance, when we use Racket's eq? operator to check whether two variables refer to the same object, what identifier is it using to achieve this comparison?

I'm looking for something like python's id function or Ruby's object_id method, in other words, some function id such that (= (id obj) (id obj2)) means that (eq? obj obj2) is true.

Some relevant docs:

Object Identity and Comparisons

Variables and Locations

答:
There's a way to get a C pointer of an object via ffi/unsafe, with the obvious caveat that it's UNSAFE.

```<code>;; from https://rosettacode.org/wiki/Address_of_a_variable#Racket

(require ffi/unsafe)

(define (madness v) ; i'm so sorry
   (cast v _racket _gcpointer))
</code>```

To use it:

```<code>(define a (list 1 2))
(define b (list 1 2))

(printf "a and b have different address: ~a ~a\n"
        (equal? (madness a) (madness b))
        (eq? a b))

(printf "a and a have the same address: ~a ~a\n"
        (equal? (madness a) (madness a))
        (eq? a a))

(printf "1 and 1 have the same address: ~a ~a\n"
        (equal? (madness 1) (madness 1))
        (eq? 1 1))
</code>```

Though the pointer is not a number or an identifier. It's an opaque object... So in a sense, this is kinda useless. You could have used the real objects with eq? instead.

I also don't know any guarantee of this method. In particular, I don't know if the pointer will be updated to its latest value when the copy GC copies objects.

Title: Unique identifier for Racket objects?

Body:
There's a way to get a C pointer of an object via ffi/unsafe, with the obvious caveat that it's UNSAFE.

;; from https://rosettacode.org/wiki/Address_of_a_variable#Racket

(require ffi/unsafe)

(define (madness v) ; i'm so sorry
   (cast v _racket _gcpointer))

To use it:

(define a (list 1 2))
(define b (list 1 2))

(printf "a and b have different address: ~a ~a\n"
        (equal? (madness a) (madness b))
        (eq? a b))

(printf "a and a have the same address: ~a ~a\n"
        (equal? (madness a) (madness a))
        (eq? a a))

(printf "1 and 1 have the same address: ~a ~a\n"
        (equal? (madness 1) (madness 1))
        (eq? 1 1))

Though the pointer is not a number or an identifier. It's an opaque object... So in a sense, this is kinda useless. You could have used the real objects with eq? instead.

I also don't know any guarantee of this method. In particular, I don't know if the pointer will be updated to its latest value when the copy GC copies objects.


问:
How to perform approximate (fuzzy) name matching in R
I have a large data set, dedicated to biological journals, which was being composed for a long time by different people. So, the data are not in a single format. For example, in the column "AUTHOR" I can find John Smith, Smith John, Smith J and so on while it is the same person. I can not perform even the simplest actions. For example, I can't figure out what authors wrote the most articles.

Is there any way in R to determine if the majority of symbols in the different names is the same, take them as the same elements?

答:
This extends @joshua-daly 's excellent response in order to accomplish two useful goals.

(1) Finding permutations of names with n>2 words (eg. Robert Allen Zimmerman aka Bob Dylan)

(2) Performing searches defined over fewer than all names on record (eg. Bob Dylan).

```<code>library(gtools)
x <- c("Yoda","speaks","thus")
permutations(n=3, r=3, v=x, repeats.allowed = FALSE) # n=num.elems r=num.times v=x

# generate some random names
names <- c(
  "John Smith",
  "Robert Allen Zimmerman (Bob Dylan)",
  "Everette Camille Arron",
  "Valentina Riquelme Molina",
  "Smith J",
  "Smith John",
  "John S",
  "John Sally"
);

# drop parentheses, if any
names <- gsub("[(|)]", "", names)

# split those names and get all ways to write that name into a list of same length
split_names <- lapply(
  X = gsub("[(|)]", "", names),
  FUN = function(x){
    print(x);
    # split by a space
    c_split = unlist(x = strsplit(x = x, split = " "));
    # get all permutations of c_split to compensate for order
    n <- r <- length(c_split)
    c_splits <- list(permutations(n=n, r=r, v=c_split, repeats.allowed = FALSE))
    # return c_splits
    c_splits;
  }
)

split_names

# suppose we're looking for this name
search_for <- "Bob Dylan";

# split it by " " and then find all ways to write that name
search_for_split <- unlist(x = strsplit(x = search_for, split = " "));
# permutations over search_for_split seem redundant

# initialize a vector containing if search_for was matched in names
match_statuses <- c();

# for each name that's been split
for(i in 1:length(names)){

    # the match status for the current name
    match_status <- FALSE;

    # the current split name
    c_split_name <- as.data.frame(split_names[[i]]);

    # for each element in c_split_name
    for(j in 1:nrow(c_split_name)){

        # the current permutation of current split name
        c_c_split_name <- as.matrix(c_split_name[j,]);

        # will receive hits in name's words, one by one, in sequence
        hits <- rep(0, 20) # length 20 should always be above max number of words in names

        # for each element in search_for_split
        for(k in 1:length(search_for_split)){

            # the current permutation of name
            c_search_for_split <- search_for_split[[k]];

            # L first hits will receive hit counts
            L <- min(ncol(c_c_split_name), length(search_for_split));

            # will match as many words as the shortest current pair of names
            for(l in 1:L){

                # if there's a match, the length of grep is greater than zero
                if(
                    # is c_search_for_split in c_c_split_name's lth element
                    length(
                        grep(
                            pattern = c_search_for_split,
                            x = as.character(c_c_split_name[l])
                        )
                    ) > 0 ||
                    # or, is c_c_split_name's lth element in c_search_for_split
                    length(
                        grep(
                            pattern = c_c_split_name[l],
                            x = c_search_for_split
                        )
                    ) > 0

                # if this is the case, record a hit
                ){
                    hits[l] <- 1;
                } else {
                # otherwise, don't update hit
                }
            }
        }

        # take L first elements
        hits <- hits[1:L]

       # if hits vector has all ones for this permutation, update match status to TRUE
       if(
           sum(hits)/length(hits)==1 # <- can/should be made more flexible (agrep, or sum/length<1)
       ){
           match_status <- TRUE;
       } else {
       # otherwise, don't update match status
       }
    }

    # append match_status to the match_statuses list
    match_statuses <- c(match_statuses, match_status);
}

search_for;

cbind(names, match_statuses);
</code>```

Body:
This extends @joshua-daly 's excellent response in order to accomplish two useful goals.

(1) Finding permutations of names with n>2 words (eg. Robert Allen Zimmerman aka Bob Dylan)

(2) Performing searches defined over fewer than all names on record (eg. Bob Dylan).

library(gtools)
x <- c("Yoda","speaks","thus")
permutations(n=3, r=3, v=x, repeats.allowed = FALSE) # n=num.elems r=num.times v=x

# generate some random names
names <- c(
  "John Smith",
  "Robert Allen Zimmerman (Bob Dylan)",
  "Everette Camille Arron",
  "Valentina Riquelme Molina",
  "Smith J",
  "Smith John",
  "John S",
  "John Sally"
);

# drop parentheses, if any
names <- gsub("[(|)]", "", names)

# split those names and get all ways to write that name into a list of same length
split_names <- lapply(
  X = gsub("[(|)]", "", names),
  FUN = function(x){
    print(x);
    # split by a space
    c_split = unlist(x = strsplit(x = x, split = " "));
    # get all permutations of c_split to compensate for order
    n <- r <- length(c_split)
    c_splits <- list(permutations(n=n, r=r, v=c_split, repeats.allowed = FALSE))
    # return c_splits
    c_splits;
  }
)

split_names

# suppose we're looking for this name
search_for <- "Bob Dylan";

# split it by " " and then find all ways to write that name
search_for_split <- unlist(x = strsplit(x = search_for, split = " "));
# permutations over search_for_split seem redundant

# initialize a vector containing if search_for was matched in names
match_statuses <- c();

# for each name that's been split
for(i in 1:length(names)){

    # the match status for the current name
    match_status <- FALSE;

    # the current split name
    c_split_name <- as.data.frame(split_names[[i]]);

    # for each element in c_split_name
    for(j in 1:nrow(c_split_name)){

        # the current permutation of current split name
        c_c_split_name <- as.matrix(c_split_name[j,]);

        # will receive hits in name's words, one by one, in sequence
        hits <- rep(0, 20) # length 20 should always be above max number of words in names

        # for each element in search_for_split
        for(k in 1:length(search_for_split)){

            # the current permutation of name
            c_search_for_split <- search_for_split[[k]];

            # L first hits will receive hit counts
            L <- min(ncol(c_c_split_name), length(search_for_split));

            # will match as many words as the shortest current pair of names
            for(l in 1:L){

                # if there's a match, the length of grep is greater than zero
                if(
                    # is c_search_for_split in c_c_split_name's lth element
                    length(
                        grep(
                            pattern = c_search_for_split,
                            x = as.character(c_c_split_name[l])
                        )
                    ) > 0 ||
                    # or, is c_c_split_name's lth element in c_search_for_split
                    length(
                        grep(
                            pattern = c_c_split_name[l],
                            x = c_search_for_split
                        )
                    ) > 0

                # if this is the case, record a hit
                ){
                    hits[l] <- 1;
                } else {
                # otherwise, don't update hit
                }
            }
        }

        # take L first elements
        hits <- hits[1:L]

       # if hits vector has all ones for this permutation, update match status to TRUE
       if(
           sum(hits)/length(hits)==1 # <- can/should be made more flexible (agrep, or sum/length<1)
       ){
           match_status <- TRUE;
       } else {
       # otherwise, don't update match status
       }
    }

    # append match_status to the match_statuses list
    match_statuses <- c(match_statuses, match_status);
}

search_for;

cbind(names, match_statuses);


问:
Java: How to create new child class instance from abstract parent class?
Here is the gist of what I am trying to do:

```<code>abstract class Animal {
    abstract static Animal fromInput(String input); // <- error

    static List<Animal> makeFive() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(Animal.fromInput("Input 1"));
        animals.add(Animal.fromInput("Input 2"));
        animals.add(Animal.fromInput("Input 3"));
        animals.add(Animal.fromInput("Input 4"));
        animals.add(Animal.fromInput("Input 5"));
        return animals;
    }
    // ^^^ how to this rewrite this so Dog.makeFive() ^^^ //
    // ^^^ makes Dogs and Cat.makeFive() makes Cats?  ^^^ //
}

class Dog extends Animal {
    @Override static Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal {
    @Override static Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}
</code>```

How to write this correctly?

I want to be able to call Dog.makeFive() to give me a List<Dog> or Cat.makeFive() to give me a List<Cat> without having to re-define makeFive() in Dog, Cat, and every other animal class.

EDIT: I know the use of static within an abstract class is wrong. My question is how to work around that so one is able to call Dog.makeFive() or Cat.makeFive() while only defining makeFive() once.

答:
A super class may not invoke instances of their sub classes unless they are explicitly declared in the super class. Otherwise the super classes don't even know about them.  So for every instance of Dog or Cat that you want in the list, you need to add them from your sub class.

In your original design, you called makeFive once which contained a single instance of Dog or Cat.  How would you expect the parent class of Animal to be able to instantiate different ones with different state?

Even if you had an interface to support this, each subclass would have to implement that interface to support its type.

But you already implement fromInput in each subclass so why not ignore that method and just implement (or override) makeFive()?  It seems like you're implementing one method to keep from having to implement another.

Finally, there is one subtle problem with this.  Unless you want List<Animal> to contain the same Dog or Cat object, you also need to copy the newly created List<Animal> to each Dog or Cat instance.  Otherwise, they will be accessing an empty (and probably null) list.

Body:
Here is the gist of what I am trying to do:

abstract class Animal {
    abstract static Animal fromInput(String input); // <- error

    static List<Animal> makeFive() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(Animal.fromInput("Input 1"));
        animals.add(Animal.fromInput("Input 2"));
        animals.add(Animal.fromInput("Input 3"));
        animals.add(Animal.fromInput("Input 4"));
        animals.add(Animal.fromInput("Input 5"));
        return animals;
    }
    // ^^^ how to this rewrite this so Dog.makeFive() ^^^ //
    // ^^^ makes Dogs and Cat.makeFive() makes Cats?  ^^^ //
}

class Dog extends Animal {
    @Override static Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal {
    @Override static Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}

How to write this correctly?

I want to be able to call Dog.makeFive() to give me a List<Dog> or Cat.makeFive() to give me a List<Cat> without having to re-define makeFive() in Dog, Cat, and every other animal class.

EDIT: I know the use of static within an abstract class is wrong. My question is how to work around that so one is able to call Dog.makeFive() or Cat.makeFive() while only defining makeFive() once.


问:
Uncaught exception java.lang.stackoverflowerror
I am getting the error "Uncaught Exception java.lang.stack overflow error null in Jmeter while performing only one thread.  Initially, all requests passed, when I try to click on 11th request to see the HTML response type it starts throwing errors.  Since that page contains more  images with search functionality</p>

答:
You can run the Java VM with a larger stack size by applying a flag like -Xss1024k. From what I found, the default is 1024k (1 MB).

For example:

```<code>$ java -Xss2048k -jar myfile.jar
</code>```

or

```<code>$ java -Xss256m -jar myfile.jar
</code>```

The alternative is to optimize your code. However,

Premature optimization is the root of all evil.

- Donald Knuth

Body:
You can run the Java VM with a larger stack size by applying a flag like -Xss1024k. From what I found, the default is 1024k (1 MB).

For example:

$ java -Xss2048k -jar myfile.jar

or

$ java -Xss256m -jar myfile.jar

The alternative is to optimize your code. However,

Premature optimization is the root of all evil.

- Donald Knuth


问:
__subclassess__() function does not exist
I want to get a list of classes in my class. According to this answer How to find all the subclasses of a class given its name? I should be able to use cls.__subclasses__, but this function does not exist.

I tried the answer to question How to find all the subclasses of a class given its name?

class X:
  class my_subclass:
    pass

x=X()
x.__subclassess__()

# This reports AttributeError 'X' has no attribute '__subclasses__'
```

I would expect to get a dictionary object or the like. But I just get an error message AttributeError 'X' has no attribute '__subclasses__'.

答:
You're doing 3 things wrong.

1) That's not how you make a subclass.

A subclass is not a class inside a class, rather it's a separate class that you define that inherits from a parent/base class. See Python: How do I make a subclass from a superclass?

class Cake():
    pass

# a subclass of Cake
class Crepe(Cake):
    pass

# a subclass of Cake
class Pound(Cake):
    pass
```

<p><strong>2)</strong> You have to call <code>__subclasses__</code> on the parent class name, not on the instance.</p>

<pre class="lang-py prettyprint-override"><code>an_instance_of_crepe=Crepe()

an_instance_of_crepe.__subclasses__()
# This will result in "AttributeError: 'Crepe' object has no attribute '__subclasses__'"
# This is what you are getting

Cake.__subclasses__()
# This will work, and printing out the result will give
# [<class '__main__.Crepe'>, <class '__main__.Pound'>]
</code>```

3) It's __subclasses__ (1 's' at the end)

Body:
I want to get a list of classes in my class. According to this answer How to find all the subclasses of a class given its name? I should be able to use cls.__subclasses__, but this function does not exist.

I tried the answer to question How to find all the subclasses of a class given its name?

class X:
  class my_subclass:
    pass

x=X()
x.__subclassess__()

# This reports AttributeError 'X' has no attribute '__subclasses__'

I would expect to get a dictionary object or the like. But I just get an error message AttributeError 'X' has no attribute '__subclasses__'.

Body:
You're doing 3 things wrong.

1) That's not how you make a subclass.

A subclass is not a class inside a class, rather it's a separate class that you define that inherits from a parent/base class. See Python: How do I make a subclass from a superclass?

class Cake():
    pass

# a subclass of Cake
class Crepe(Cake):
    pass

# a subclass of Cake
class Pound(Cake):
    pass

2) You have to call __subclasses__ on the parent class name, not on the instance.

an_instance_of_crepe=Crepe()

an_instance_of_crepe.__subclasses__()
# This will result in "AttributeError: 'Crepe' object has no attribute '__subclasses__'"
# This is what you are getting

Cake.__subclasses__()
# This will work, and printing out the result will give
# [<class '__main__.Crepe'>, <class '__main__.Pound'>]

3) It's __subclasses__ (1 's' at the end)


问:
Why does a cartesian product yield "TypeError: iteration over a 0-d array"?
I am trying to make a cartesian product from a list of arrays but it keeps giving me a TypeError: iteration over a 0-d array

I have a list which looks like:

print(a)
>>>[array([1., 2.]), array([3., 4.]), array(1400.)]
```

<p>Now, when I try to do:</p>

<pre class="lang-py prettyprint-override"><code>b=list(itertools.product(*a))
>>>TypeError: iteration over a 0-d array
</code>```

What am I missing?

答:
As explained by @user2357112 in the comments, you currently have the last element as a 0 dimensional array. If you check the length of it, you will get TypeError: len() of unsized object. To get your solution working, you need to enclose the element in the last array using  [] to be able to use the product

```<code>import itertools

a = [np.array([1., 2.]), np.array([3., 4.]), np.array([1400.])]

b = list(itertools.product(*a))

#[(1.0, 3.0, 1400.0),
# (1.0, 4.0, 1400.0),
# (2.0, 3.0, 1400.0),
# (2.0, 4.0, 1400.0)]
</code>```

Edit answering second question on request:

```<code>import itertools

dict1 = {'wdth_i': ['1', '2'], 'wdth_p': ['3', '4'], 'mu': '1400'}

a = []
for i in dict1.values():
    if isinstance(i, list):
        a.append(i)
    else:
        a.append([i])

f = list(itertools.product(*a))
# [('1', '3', '1400'),
#  ('1', '4', '1400'),
#  ('2', '3', '1400'),
#  ('2', '4', '1400')]
</code>```

Body:
I am trying to make a cartesian product from a list of arrays but it keeps giving me a TypeError: iteration over a 0-d array

I have a list which looks like:

print(a)
>>>[array([1., 2.]), array([3., 4.]), array(1400.)]

Now, when I try to do:

b=list(itertools.product(*a))
>>>TypeError: iteration over a 0-d array

What am I missing?

Body:
As explained by @user2357112 in the comments, you currently have the last element as a 0 dimensional array. If you check the length of it, you will get TypeError: len() of unsized object. To get your solution working, you need to enclose the element in the last array using  [] to be able to use the product

import itertools

a = [np.array([1., 2.]), np.array([3., 4.]), np.array([1400.])]

b = list(itertools.product(*a))

#[(1.0, 3.0, 1400.0),
# (1.0, 4.0, 1400.0),
# (2.0, 3.0, 1400.0),
# (2.0, 4.0, 1400.0)]

Edit answering second question on request:

import itertools

dict1 = {'wdth_i': ['1', '2'], 'wdth_p': ['3', '4'], 'mu': '1400'}

a = []
for i in dict1.values():
    if isinstance(i, list):
        a.append(i)
    else:
        a.append([i])

f = list(itertools.product(*a))
# [('1', '3', '1400'),
#  ('1', '4', '1400'),
#  ('2', '3', '1400'),
#  ('2', '4', '1400')]


问:
ORM vs Handcoded Data Access Layer
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

```
 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)
```

Hand Coded Advantages

```
 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only
```

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

答:
I have used Castle Project's Active Record implementation with NHibernate for a personal project. The project was never deployed, partly because of my inability to work with the ORM choice that I made.

The reason that I decided to use ORM was because I wanted the ability to switch from SQL Server to MYSQL without changing my code. In real projects the decision to use SQL server is already made for me, and it is easier to just write datalayers in the traditional 3-tier way when you know that the database won't change.
But for personal projects I use shared hosting, and MySQL is a cheaper solution.

The reason I went with Castle was because it was very easy to use. With the activewriter plugin for visual studio, I was able to generate my classes and database using a designer (kind of like the linq to SQL designer), and it seemed to fit well with my mental model of how the ORM should dictate your application architecture.

The problem that I had with that ORM was that I wasn't able to find information on how to  properly optimize it. It was making extremely large calls to the database. (The SQL query generated to get a user was 1mb of text when I logged it.)

So, I using the ORM, I saved myself a lot of work upfront, but I ran into a wall when I tried to fix the problem with the framework generating too much SQL. (On which I am still slowly working).

Even though I didn't find the solution perfect, I would still try ORM for other personal projects, because it's just me, and I want to spend my project time on fun code, not datalayers.

At work, however, I would probably not be too quick to suggest that we use an ORM, before I was an expert (Maybe after I get several working personal projects under my belt).

OwnerDisplayName: Frustrating Developments

Title: ORM vs Handcoded Data Access Layer

Body:
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)

Hand Coded Advantages

 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

LastEditorDisplayName: Frustrating Developments

OwnerDisplayName: NetHawk


问:
Limiting a doctrine query with a fetch-joined collection?
I have a doctrine query that returns blog posts and their comments:

```<code>SELECT b, c FROM BlogPost b LEFT JOIN b.comments c
</code>```

I would like to limit the results to 10 blog posts. According to the DQL documentation, setMaxResults() doesn't work correctly on queries that fetch-join a collection (comments in this case):

If your query contains a fetch-joined
  collection specifying the result limit
  methods are not working as you would
  expect. Set Max Results restricts the
  number of database result rows,
  however in the case of fetch-joined
  collections one root entity might
  appear in many rows, effectively
  hydrating less than the specified
  number of results.

How would I properly limit a doctrine query that contains a fetch-joined collection (in this case, limit the results to 10 blog posts)?

答: This repository http://github.com/beberlei/DoctrineExtensions has a paginator extension that works with fetch joins. You have to essentially make 3 SELECT statements, all of which this extension does for you.</p>

Body:
I have a doctrine query that returns blog posts and their comments:

SELECT b, c FROM BlogPost b LEFT JOIN b.comments c

I would like to limit the results to 10 blog posts. According to the DQL documentation, setMaxResults() doesn't work correctly on queries that fetch-join a collection (comments in this case):

If your query contains a fetch-joined
  collection specifying the result limit
  methods are not working as you would
  expect. Set Max Results restricts the
  number of database result rows,
  however in the case of fetch-joined
  collections one root entity might
  appear in many rows, effectively
  hydrating less than the specified
  number of results.

How would I properly limit a doctrine query that contains a fetch-joined collection (in this case, limit the results to 10 blog posts)?


问:
Firebase dynamic link not opening the app iOS
I have developed & installed an iOS app locally on my device.

And have set custom scheme in the info.plist as mydlink

Set associated domains as weel: applinks:<myapp>.app.goo.gl

Created dynamic link on firebase as:

```<code>https://<myapp>.app.goo.gl/?link=http://<mysite.com>/&ibi=<app bundle id>&ius=mydlink&ifl=https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id%3D<app store id>%26mt%3D8&pt=<app store id>
</code>```

When I open or click on dynamic link, it opens app page in the "App Store" app and not opening app itself though its installed.

What am I missing here?

答:
I have great news.

I always hear that it's IMPOSSIBLE to test a dynamic link on simulator.

But now WE CAN test firebase dynamic link on simulator

https://stackoverflow.com/a/56385506/6273003

Body:
I have developed & installed an iOS app locally on my device.

And have set custom scheme in the info.plist as mydlink

Set associated domains as weel: applinks:<myapp>.app.goo.gl

Created dynamic link on firebase as:

https://<myapp>.app.goo.gl/?link=http://<mysite.com>/&ibi=<app bundle id>&ius=mydlink&ifl=https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id%3D<app store id>%26mt%3D8&pt=<app store id>

When I open or click on dynamic link, it opens app page in the "App Store" app and not opening app itself though its installed.

What am I missing here?


问:
Image not showing through css
I'm trying to set up a cover photo for my website. I am using "background-image" through CSS to link the image.

None of my other photos through css image links are showing up either.

I am positive that the local path is correct. (photo is located in "website name"[where index.html is located]/resources/photos/cover.jpg)

What's weird is that the image shows up correctly when linking through HTML using the same path.

CSS:

```<code>.cover{
    background-image: url(../resources/photos/cover.jpg);
    height: 34.3rem;
    min-height: 100%;
}
</code>```

HTML:

```<code><div class="cover">
    <div class="summary">
        <span style="width: 80%;">Delightful Days Daycare
            <p>Where everyday is delightful!</p>
        </span>
    </div>
</div>
</code>```

答: You should find the image in the inspector and right click open in new tab and check whether the image loads or not. You can also view the full URL path and better debug if the URL is correct or not. If it loads it's a problem with the code, if not check the URL and match it with your folder structure.

Title: Image not showing through css

Body:
I'm trying to set up a cover photo for my website. I am using "background-image" through CSS to link the image.

None of my other photos through css image links are showing up either.

I am positive that the local path is correct. (photo is located in "website name"[where index.html is located]/resources/photos/cover.jpg)

What's weird is that the image shows up correctly when linking through HTML using the same path.

CSS:

.cover{
    background-image: url(../resources/photos/cover.jpg);
    height: 34.3rem;
    min-height: 100%;
}

HTML:

        Delightful Days Daycare

Where everyday is delightful!


问:
maven-install-plugin: Can i define a custom packaging type but get the artifact installed as jar in the repo?
I am trying to come out with a plugin to detect and process Java EE application clients.

I created a new packaging type called 'car' through META-INF/plexus/components.xml (http://maven-car-plugin.googlecode.com/svn/trunk/maven-car-plugin/src/main/resources/META-INF/plexus/components.xml) and a corresponding mojo for Java EE app clients. I have pretty much followed the same steps as the maven-ejb-plugin.

The behaviour i want is the same as the maven-ejb-plugin: Defines an ejb packaging type but the artifact gets installed in the repo as a .jar and gets bundled in the ear as .jar too.

I believe must be configurable some how because ejb packaging type gets installed as .jar but war packaging type produces a .war.

The problem in my case is that a .car file gets installed in the repo and a .car file gets bundled in the ear.

Does anyone know how to make sure it gets installed in the repo as a .jar file?

答:
I ran into the same issue you have, except, I'm building a .war file and wanted a .jar file installed into my local repo. What I did was use the maven-jar-plugin to create a jar file in addition to a war file, it's generated in my /target directory. I also used the maven-install-plugin to install the outputted jar to my local repo.</p>

```<code>    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <executions>
            <execution>
                <id>make-jar</id>
                <phase>compile</phase>
                <goals>
                        <goal>jar</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-install-plugin</artifactId>
        <executions>
            <execution>
                <id>install-jar</id>
                <phase>install</phase>
                <goals>
                    <goal>install-file</goal>
                </goals>
                <configuration>
                    <packaging>jar</packaging>
                    <artifactId>${project.artifactId}</artifactId>
                    <groupId>${project.groupId}</groupId>
                    <version>${project.version}</version>
                    <file>${project.build.directory}/${project.artifactId}.jar</file>
                </configuration>
            </execution>
        </executions>
    </plugin>
</code>```

Body:
I ran into the same issue you have, except, I'm building a .war file and wanted a .jar file installed into my local repo. What I did was use the maven-jar-plugin to create a jar file in addition to a war file, it's generated in my /target directory. I also used the maven-install-plugin to install the outputted jar to my local repo.

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <executions>
            <execution>
                <id>make-jar</id>
                <phase>compile</phase>
                <goals>
                        <goal>jar</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-install-plugin</artifactId>
        <executions>
            <execution>
                <id>install-jar</id>
                <phase>install</phase>
                <goals>
                    <goal>install-file</goal>
                </goals>
                <configuration>
                    <packaging>jar</packaging>
                    <artifactId>${project.artifactId}</artifactId>
                    <groupId>${project.groupId}</groupId>
                    <version>${project.version}</version>
                    <file>${project.build.directory}/${project.artifactId}.jar</file>
                </configuration>
            </execution>
        </executions>
    </plugin>


问:
Pandas identify # of items which generate 80 of sales
I have a dataframe with for each country, list of product and the relevant sales
I need to identify for each country how many are # of top sales items of which cumulative sales represent 80% of the total sales for all the items in each country.

E.g.

```<code>Cnt Product, units
Italy apple 500
Italy beer 1500
Italy bread 2000
Italy orange 3000
Italy butter 3000
</code>```

Expected results

```<code>Italy 3
</code>```

(Total units are 10.000 and the sales of the top 3 product - Butter, Orange, Bread, is 8.000 which is the 80% of total)

答:
Try define a function and apply on groupby:

```<code>def get_sale(x, pct=0.8):

    thresh = 0.8 * x.sum()

    # sort values descendingly for top salse
    x=x.sort_values(ascending=False).reset_index(drop=True)

    # store indices of those with cumsum pass threshold
    sale_pass_thresh = x.index[x.cumsum().ge(thresh)]

    return sale_pass_thresh[0] + 1

df.groupby('Cnt').units.apply(get_sale)
</code>```

Output:

```<code>Cnt
Italy    3
Name: units, dtype: int64
</code>```

Body:
I have a dataframe with for each country, list of product and the relevant sales
I need to identify for each country how many are # of top sales items of which cumulative sales represent 80% of the total sales for all the items in each country.

E.g.

Cnt Product, units
Italy apple 500
Italy beer 1500
Italy bread 2000
Italy orange 3000
Italy butter 3000

Expected results

Italy 3

(Total units are 10.000 and the sales of the top 3 product - Butter, Orange, Bread, is 8.000 which is the 80% of total)

Body:
Try define a function and apply on groupby:

def get_sale(x, pct=0.8):

    thresh = 0.8 * x.sum()

    # sort values descendingly for top salse
    x=x.sort_values(ascending=False).reset_index(drop=True)

    # store indices of those with cumsum pass threshold
    sale_pass_thresh = x.index[x.cumsum().ge(thresh)]

    return sale_pass_thresh[0] + 1

df.groupby('Cnt').units.apply(get_sale)

Output:

Cnt
Italy    3
Name: units, dtype: int64


问:
cannot await method group func delegate
I have a func delegate that is defined as follows,

```<code>   public enum RunEndStatus
    {
        Success
    }
    public class classA
    {
        Func<object, RunEndStatus> ProcessCalibrationRun { get; set; }
    }
</code>```

Now in an other class lets say classB I am doing something like this,

```<code>public class ClassB
{
    public void DoSomething()
    {
        ClassA a = new ClassA();
        a.ProcessCalibrationRun = ProcessCalibrationRun;//This is just fine. It won't complain here.
    }
    public RunEndStatus ProcessCalibrationRun(object obj)
    {
        //Here I have some piece of code takes so much time. To replicate it,
        Thread.Sleep(10000);
    }
}
</code>```

When the DoSomething method is called from somewhere, the application blocks for 10 minutes.So I am trying to fix my problem as follows,

```<code> public async Task<RunEndStatus> ProcessCalibrationRun(object obj)
    {
        await Task.Run(() => { Thread.Sleep(10000)});
        return RunEndStatus.Success;
    }
</code>```

I am modifying the call as follows. But it says cannot await method group. Please help how can I await on that method.

```<code> public async void DoSomething()
    {
        ClassA a = new ClassA();
        a.ProcessCalibrationRun = await ProcessCalibrationRun; //Here it complains saying cannot await method group.
    }
</code>```

答:
An async signature returns a Task, so your Func will need to as well

```<code>public Func<object, Task<RunEndStatus>> ProcessCalibrationRun { get; set; }
</code>```

Meaning you will not need the async signature  in your DoSomething, which should not be async void anyway

```<code>public void DoSomething()
{
   vara = new ClassA();
   a.ProcessCalibrationRun = ProcessCalibrationRun;
}
</code>```

Then somewhere else (perhaps in ClassA) you can invoke it

```<code>public async Task DoSomethingElse()
{
   await ProcessCalibrationRun(somethignObject);
}
</code>```

Title: cannot await method group func delegate

Body:
I have a func delegate that is defined as follows,

   public enum RunEndStatus
    {
        Success
    }
    public class classA
    {
        Func<object, RunEndStatus> ProcessCalibrationRun { get; set; }
    }

Now in an other class lets say classB I am doing something like this,

public class ClassB
{
    public void DoSomething()
    {
        ClassA a = new ClassA();
        a.ProcessCalibrationRun = ProcessCalibrationRun;//This is just fine. It won't complain here.
    }
    public RunEndStatus ProcessCalibrationRun(object obj)
    {
        //Here I have some piece of code takes so much time. To replicate it,
        Thread.Sleep(10000);
    }
}

When the DoSomething method is called from somewhere, the application blocks for 10 minutes.So I am trying to fix my problem as follows,

 public async Task<RunEndStatus> ProcessCalibrationRun(object obj)
    {
        await Task.Run(() => { Thread.Sleep(10000)});
        return RunEndStatus.Success;
    }

I am modifying the call as follows. But it says cannot await method group. Please help how can I await on that method.

 public async void DoSomething()
    {
        ClassA a = new ClassA();
        a.ProcessCalibrationRun = await ProcessCalibrationRun; //Here it complains saying cannot await method group.
    }

Body:
An async signature returns a Task, so your Func will need to as well

public Func<object, Task<RunEndStatus>> ProcessCalibrationRun { get; set; }

Meaning you will not need the async signature  in your DoSomething, which should not be async void anyway

public void DoSomething()
{
   vara = new ClassA();
   a.ProcessCalibrationRun = ProcessCalibrationRun;
}

Then somewhere else (perhaps in ClassA) you can invoke it

public async Task DoSomethingElse()
{
   await ProcessCalibrationRun(somethignObject);
}


答:
You can using datetime library

from datetime import datetime
datetime.strptime('2019-05-30 21:01:09', '%Y-%m-%d %H:%M:%S')
```

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

Title: How to convert date as string to date type

Body: I have a variable '2019-05-30 21:01:09' that needs to be converted into 2019-05-30 21:01:09. What is the best way to go about this.

Body:
You can using datetime library

from datetime import datetime
datetime.strptime('2019-05-30 21:01:09', '%Y-%m-%d %H:%M:%S')

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior


问:
What is the difference between Pytesseract and Tesserocr?
I'm using Python 3.6 in Windows 10 and have Pytesseract already installed but I found in a code Tesserocr which by the way I can't install. What is the difference?</p>

答:
From my experience Tesserocr is much faster than Pytesseract.

Tesserocr is a python wrapper around the Tesseract C++ API. Whereas pytesseract is a wrapper around the tesseract-ocr CLI.

With Tesserocr you can pre-load the model at the beginning or your program (which is called memoization), and run the model separately (for example in loops to process videos).

With pytesseract, each time you call image_to_string function, it loads the model and process the image, which makes it slower for repeated calls.

To install tesserocr I just typed in the terminal pip install tesserocr.

To use tesserocr

```<code>import tesserocr
from PIL import Image
api = tesserocr.PyTessBaseAPI()
pil_image = Image.open('sample.jpg')
api.SetImage(pil_image)
text = api.GetUTF8Text()
</code>```

To install pytesseract : pip install pytesseract.

To run it :

```<code>import pytesseract
import cv2
image = cv2.imread('sample.jpg')
text = pytesseract.image_to_string(image)
</code>```

Body:
From my experience Tesserocr is much faster than Pytesseract.

Tesserocr is a python wrapper around the Tesseract C++ API. Whereas pytesseract is a wrapper around the tesseract-ocr CLI.

With Tesserocr you can pre-load the model at the beginning or your program (which is called memoization), and run the model separately (for example in loops to process videos).

With pytesseract, each time you call image_to_string function, it loads the model and process the image, which makes it slower for repeated calls.

To install tesserocr I just typed in the terminal pip install tesserocr.

To use tesserocr

import tesserocr
from PIL import Image
api = tesserocr.PyTessBaseAPI()
pil_image = Image.open('sample.jpg')
api.SetImage(pil_image)
text = api.GetUTF8Text()

To install pytesseract : pip install pytesseract.

To run it :

import pytesseract
import cv2
image = cv2.imread('sample.jpg')
text = pytesseract.image_to_string(image)