问:
Amazon transcribe "Operation not found: StartTranscriptionJob"

Windows 7 Pro

PHP 7.0.2

AWS transcribe API 2017-10-26

Hi,
I'm trying to use Amazon Web Services to transcribe recordings from an IVR (Please leave your name after the tone. etc) using PHP. I can upload the recordings to my AWS bucket (so something is right) but when I try to start the transcription job I get the following error:
"Operation not found: StartTranscriptionJob"

I can get transcription to work using the AWS CLI so my system seems to be set up OK. There is not a lot online about this issue, I've done all the usual Googling and the info isn't very helpful - such as:

https://docs.aws.amazon.com/transcribe/latest/dg/API_StartTranscriptionJob.html
https://docs.aws.amazon.com/sdk-for-go/api/service/transcribeservice/#TranscribeService.StartTranscriptionJob

Here's my code, the StartTranscriptionJob is at the end:

```<code><?php
require 'aws\aws-autoloader.php';
chdir('asr');
$logFile = 'asr.log';
$log = "\n\n".date("d/m/Y H:i:s");

###################
# get the recording
###################

$service   = htmlspecialchars($_GET["service"]);
$recording = htmlspecialchars($_GET["recording"]);

$ftp_server = "ftp.****";
$ftp_username = "****";
$ftp_userpass = "****";
$ftp_conn = ftp_connect($ftp_server,7721) or die("Could not connect to $ftp_server");
ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
ftp_chdir($ftp_conn,'Recordings');
ftp_pasv($ftp_conn, true);
ftp_chdir($ftp_conn,$service);
ftp_get ($ftp_conn , $recording , $recording, FTP_BINARY);
ftp_close($ftp_conn);

######################
# Upload to AWS bucket
######################

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$credentials = new Aws\Credentials\Credentials('****', '****');
$bucket = 'asr-bucket-test';
$keyname = $recording;

$s3 = new S3Client([
   'profile' => 'default',
   'version' => 'latest',
   'region'  => 'us-west-2',
   'credentials' => $credentials
]);

try {
   // Upload data.
   $result = $s3->putObject([
       'Bucket' => $bucket,
       'Key'    => $keyname,
       'SourceFile'  => '\xampp\htdocs\****.co.uk\asr\\'.$recording,
       'ACL'    => 'public-read'
   ]);

   // Print the URL to the object.
   $log.= "\n".$result['ObjectURL'] . PHP_EOL;
} catch (S3Exception $e) {
   $log.= "\n".$e->getMessage() . PHP_EOL;
}

############
# Transcribe
############

try {
  $result = $s3->StartTranscriptionJob([
  'LanguageCode' => 'en-US', // REQUIRED
  'Media' => [
    'MediaFileUri' => 'https://s3-us-west-2.amazonaws.com/asr-bucket-test/'.$recording,
  ],
  'MediaFormat' => 'wav', // REQUIRED
  'OutputBucketName' => $bucket,
  'Settings' => [
  #  'ChannelIdentification' => true || false,
    'MaxSpeakerLabels' => 5,
  #  'ShowSpeakerLabels' => true || false,
  #  'VocabularyName' => $recording
  ],
  'TranscriptionJobName' => 'test_job', // REQUIRED
  ]);
  $log.="\n".$result;
} catch (Exception $e) {
  $log.="\nError: Cannot start transcripion job " . $e->getMessage();
}

file_put_contents($logFile, $log,FILE_APPEND);
exit();

?>
</code>```

答:
You have to create a new TranscribeServiceClient and then connect through that. Here's a snippet from my working code:</p>

```<code>    $transcribe = new Aws\TranscribeService\TranscribeServiceClient([
        'region'  => $region,
        'version' => 'latest',
        'credentials' => [
            'key'    => $accessKey,
            'secret' => $secretKey,
        ],
    ]);

    //print_r($transcribe);

    $result = $transcribe->startTranscriptionJob([
        'LanguageCode' => $languageCode, // REQUIRED
        'Media' => [ // REQUIRED
            'MediaFileUri' => $mediaURI,
        ],
        'MediaFormat' => $fileExt, // REQUIRED
        'OutputBucketName' => $bucketName,
        'Settings' => [
            'ChannelIdentification' => false,
            'MaxSpeakerLabels' => 5,
            'ShowSpeakerLabels' => true,
            'VocabularyName' => '',
        ],
        'TranscriptionJobName' => $fileName . "-" . date('Ymd-his') // REQUIRED
    ]);
</code>```

Body:
Windows 7 Pro

PHP 7.0.2

AWS transcribe API 2017-10-26

Hi,
I'm trying to use Amazon Web Services to transcribe recordings from an IVR (Please leave your name after the tone. etc) using PHP. I can upload the recordings to my AWS bucket (so something is right) but when I try to start the transcription job I get the following error:
"Operation not found: StartTranscriptionJob"

I can get transcription to work using the AWS CLI so my system seems to be set up OK. There is not a lot online about this issue, I've done all the usual Googling and the info isn't very helpful - such as:

https://docs.aws.amazon.com/transcribe/latest/dg/API_StartTranscriptionJob.html
https://docs.aws.amazon.com/sdk-for-go/api/service/transcribeservice/#TranscribeService.StartTranscriptionJob

Here's my code, the StartTranscriptionJob is at the end:

<?php
require 'aws\aws-autoloader.php';
chdir('asr');
$logFile = 'asr.log';
$log = "\n\n".date("d/m/Y H:i:s");

###################
# get the recording
###################

$service   = htmlspecialchars($_GET["service"]);
$recording = htmlspecialchars($_GET["recording"]);

$ftp_server = "ftp.****";
$ftp_username = "****";
$ftp_userpass = "****";
$ftp_conn = ftp_connect($ftp_server,7721) or die("Could not connect to $ftp_server");
ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
ftp_chdir($ftp_conn,'Recordings');
ftp_pasv($ftp_conn, true);
ftp_chdir($ftp_conn,$service);
ftp_get ($ftp_conn , $recording , $recording, FTP_BINARY);
ftp_close($ftp_conn);

######################
# Upload to AWS bucket
######################

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$credentials = new Aws\Credentials\Credentials('****', '****');
$bucket = 'asr-bucket-test';
$keyname = $recording;

$s3 = new S3Client([
   'profile' => 'default',
   'version' => 'latest',
   'region'  => 'us-west-2',
   'credentials' => $credentials
]);

try {
   // Upload data.
   $result = $s3->putObject([
       'Bucket' => $bucket,
       'Key'    => $keyname,
       'SourceFile'  => '\xampp\htdocs\****.co.uk\asr\\'.$recording,
       'ACL'    => 'public-read'
   ]);

   // Print the URL to the object.
   $log.= "\n".$result['ObjectURL'] . PHP_EOL;
} catch (S3Exception $e) {
   $log.= "\n".$e->getMessage() . PHP_EOL;
}

############
# Transcribe
############

try {
  $result = $s3->StartTranscriptionJob([
  'LanguageCode' => 'en-US', // REQUIRED
  'Media' => [
    'MediaFileUri' => 'https://s3-us-west-2.amazonaws.com/asr-bucket-test/'.$recording,
  ],
  'MediaFormat' => 'wav', // REQUIRED
  'OutputBucketName' => $bucket,
  'Settings' => [
  #  'ChannelIdentification' => true || false,
    'MaxSpeakerLabels' => 5,
  #  'ShowSpeakerLabels' => true || false,
  #  'VocabularyName' => $recording
  ],
  'TranscriptionJobName' => 'test_job', // REQUIRED
  ]);
  $log.="\n".$result;
} catch (Exception $e) {
  $log.="\nError: Cannot start transcripion job " . $e->getMessage();
}

file_put_contents($logFile, $log,FILE_APPEND);
exit();

?>

Body:
You have to create a new TranscribeServiceClient and then connect through that. Here's a snippet from my working code:

    $transcribe = new Aws\TranscribeService\TranscribeServiceClient([
        'region'  => $region,
        'version' => 'latest',
        'credentials' => [
            'key'    => $accessKey,
            'secret' => $secretKey,
        ],
    ]);

    //print_r($transcribe);

    $result = $transcribe->startTranscriptionJob([
        'LanguageCode' => $languageCode, // REQUIRED
        'Media' => [ // REQUIRED
            'MediaFileUri' => $mediaURI,
        ],
        'MediaFormat' => $fileExt, // REQUIRED
        'OutputBucketName' => $bucketName,
        'Settings' => [
            'ChannelIdentification' => false,
            'MaxSpeakerLabels' => 5,
            'ShowSpeakerLabels' => true,
            'VocabularyName' => '',
        ],
        'TranscriptionJobName' => $fileName . "-" . date('Ymd-his') // REQUIRED
    ]);


来源: stackexchange

问:
How to add margins between columns in Bootsrap4?
I try to arrange 3 sections columns equally by assigning either col-lg-4 or col-lg-3 for each of them with Bootsstrap 4.

With col-lg-4 or any responsive combination that takes total of 12 columns, I get no margin between the columns.

With col-lg-3 the margins become too wide.

The same problem arises with both "container" and "container-fluid" class.

I tried also to adjust the margins manually, replacing mx-auto with Bootstrap4 margin set at m-3, but it does not solve the problem because in that case all the columns move to the left, leaving empty space on the right side of the screen.

The problem arises the moment I try to put margins. Otherwise, if there are no margins I can set col-lg-4 without a problem. I will get for instance 3 nice columns. But once I put margins, it becomes wrong. I followed the recommendation on https://getbootstrap.com/docs/4.0/utilities/spacing/ but still it does not help.

* {
  box-sizing: border-box;
}

body {
    font-size: 16px;
    color: black;
    background-color: #eeeeee;
    font-family: 'Oxygen', sans-serif;
  }

 .navbar {
    background-color: rgb(178, 238, 13);
    border-radius: 0;
    border: 0;
    margin: 0;
    padding: 0;
  }

  #collapsibleNavbar {
    background-color: rgb(229, 243, 192);
    text-align: center;
  }

  .navbar-nav li a {
    color: black;
    border-style: solid;
    border-width: 1px;
  }

  .navbar-brand {
      color: black;
      padding: 15px;
  }

  h5{
    margin-bottom: 15px;
    padding-top: 7px;
  }

  h2{
    font-size: 175%;
    margin-bottom: 30px;
    margin-top: 20px;
  }

  .paraf{
    background-color: #e6ee9c;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Module 3</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="styles.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>

<header>
    <nav class="navbar navbar-expand-md navbar-light">
            Food, LLC

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
                    <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="collapsibleNavbar">
                    <ul class="d-lg-none d-md-none navbar-nav">
                      <li class="nav-item">
                        Chicken
                      </li>
                      <li class="nav-item">
                        Beef
                      </li>
                      <li class="nav-item">
                        Sushi
                      </li>
                    </ul>
                  </div>
    </nav>

</header>
<h2 class="text-center"> Our Menu </h2>

<div class="container">
<div class="row">

<div class="col-lg-4 col-md-6 col-sm-12 col-12 paraf mx-auto">
<h5 class="text-center" id="chicken">Chicken</h5>
<p>Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros. <br> (End of Chicken section) Back to Top</p></div>

<div class="col-lg-4 col-md-6 col-sm-12 col-12 paraf mx-auto">
<h5 class="text-center" id="beef">Beef</h5>
<p>Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.<br>(End of Beef section) Back to Top</p></div>

<div class="col-lg-4 col-md-12 col-sm-12 col-12 paraf mx-auto">
<h5 class="text-center" id="sushi">Sushi</h5>
<p>Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.<br>(End of Sushi section) Back to Top</p></div>
</div>
</div>

</body>
</html></code>```

Can you suggest how to fix this and get margins between the columns.

答:
```<code><div class="col-lg-4">
<div class="col-lg-12">
 your content 1
</div>
</div>

<div class="col-lg-4">
<div class="col-lg-12">
your content 2
</div>
</div>

<div class="col-lg-4">
<div class="col-lg-12">
your content 3
</div>
</div>
</code>```

so just add col-lg-12 in col-lg-4

ContentLicense: CC BY-SA 4.0

Body:
I try to arrange 3 sections columns equally by assigning either col-lg-4 or col-lg-3 for each of them with Bootsstrap 4.

With col-lg-4 or any responsive combination that takes total of 12 columns, I get no margin between the columns.

With col-lg-3 the margins become too wide.

The same problem arises with both "container" and "container-fluid" class.

I tried also to adjust the margins manually, replacing mx-auto with Bootstrap4 margin set at m-3, but it does not solve the problem because in that case all the columns move to the left, leaving empty space on the right side of the screen.

The problem arises the moment I try to put margins. Otherwise, if there are no margins I can set col-lg-4 without a problem. I will get for instance 3 nice columns. But once I put margins, it becomes wrong. I followed the recommendation on https://getbootstrap.com/docs/4.0/utilities/spacing/ but still it does not help.

* {
  box-sizing: border-box;
}

body {
    font-size: 16px;
    color: black;
    background-color: #eeeeee;
    font-family: 'Oxygen', sans-serif;
  }

 .navbar {
    background-color: rgb(178, 238, 13);
    border-radius: 0;
    border: 0;
    margin: 0;
    padding: 0;
  }

  #collapsibleNavbar {
    background-color: rgb(229, 243, 192);
    text-align: center;
  }

  .navbar-nav li a {
    color: black;
    border-style: solid;
    border-width: 1px;
  }

  .navbar-brand {
      color: black;
      padding: 15px;
  }

  h5{
    margin-bottom: 15px;
    padding-top: 7px;
  }

  h2{
    font-size: 175%;
    margin-bottom: 30px;
    margin-top: 20px;
  }

  .paraf{
    background-color: #e6ee9c;
  }

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Module 3</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="styles.css">

            Food, LLC

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">

            </button>

                        Chicken

                        Beef

                        Sushi

 Our Menu

Chicken

Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
 (End of Chicken section) Back to Top

Beef

Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
(End of Beef section) Back to Top

Sushi

Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
(End of Sushi section) Back to Top

Can you suggest how to fix this and get margins between the columns.

Body:
<div class="col-lg-4">
<div class="col-lg-12">
 your content 1
</div>
</div>

<div class="col-lg-4">
<div class="col-lg-12">
your content 2
</div>
</div>

<div class="col-lg-4">
<div class="col-lg-12">
your content 3
</div>
</div>

so just add col-lg-12 in col-lg-4


问:
Delphi-7 WSDL Importer Error "The following types, referred to in the WSDL document are not being represented..."
Importing NetSuite WSDL into Delphi-7 results in errors:

  // The following types, referred to in the WSDL document are not being represented

  // in this file. They are either aliases[@] of other types represented or were referred

  // to but never[!] declared in the document. The types from the latter category

  // typically map to predefined/known XML or Borland types; however, they could also

  // indicate incorrechtt WSDL documents that failed to declare or import a schema type.

  // ************************************************************************

  // !:login           - "urn:messages_2009_2.platform.webservices.netsuite.com"

  // !:loginResponse   - "urn:messages_2009_2.platform.webservices.netsuite.com"

  // !:applicationInfo - "urn:messages_2009_2.platform.webservices.netsuite.com"

WSDL is at: https://webservices.netsuite.com/wsdl/v2009_1_0/netsuite.wsdl
or it can be downloaded along with all XSDs from: https://system.netsuite.com/download/WSDL_v2009_1_0.zip

I saw this thread http://forums.embarcadero.com/thread.jspa?messageID=157927 but I did not find any issue with NetSuite Certificate.

Any help to solve this would be appreciated!

答:
I helped harry by generating the Delphi units with the Delphi 2010 WSDL importer. They don't compile in Delphi 7.

This was his reaction:

I could not use that file with Delphi
  7 because Delphi 7 does not support
  {$SCOPEDENUMS ON}

Scoped Enums are a nice feature, but difficult to back-port to Delphi 7.

ContentLicense: CC BY-SA 3.0


问:
How to pass a variable from one component to another that is at the same level?
How to pass a variable from one component to another that is at the same level? I have the user variable in the Auth component service

```<code>@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private user: string = null;

  getUser() {
    return this.user;
  }

  setUser(username) {
    sessionStorage.setItem('username', username);
    this.user = sessionStorage.getItem('username');
    console.log('VAMOS!!!', this.user);
  }
}
</code>```

in the first component I inject it and if I get the value of the user variable then when the user authenticates I redirect it with this.router.navigate (['/ meet']) that is, I visualize the next component.

In this next component called list-user in which I get null in getUser ().

```<code>async ngOnInit() {
  console.log('HOY', this.authService.getUser());
}
</code>```

答:
We can use service store the data globally so that we can access the data in any component.

If you provide the service in module level(same singleton instance
will share for all component).

If you provide  the service in component level(new instance will

create for component).

So based on your use case do not inject the service in the component level.

```<code>@Component({
  selector: 'a-comp',
  template: `<div></div>`
})
export class AComponent implements OnInit {
  constructor( private authService: AuthService ) {}
  ngOnInit() {
    console.log('HOY', this.authService.getUser());
  }
}

@Component({
  selector: 'b-comp',
  template: `<div></div>`
})
export class BComponent implements OnInit {
  constructor( private authService: AuthService ) {}
  ngOnInit() {
    console.log('HOY', this.authService.getUser());
  }
}

</code>```

Body:
How to pass a variable from one component to another that is at the same level? I have the user variable in the Auth component service

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private user: string = null;

  getUser() {
    return this.user;
  }

  setUser(username) {
    sessionStorage.setItem('username', username);
    this.user = sessionStorage.getItem('username');
    console.log('VAMOS!!!', this.user);
  }
}

in the first component I inject it and if I get the value of the user variable then when the user authenticates I redirect it with this.router.navigate (['/ meet']) that is, I visualize the next component.

In this next component called list-user in which I get null in getUser ().

async ngOnInit() {
  console.log('HOY', this.authService.getUser());
}

Body:
We can use service store the data globally so that we can access the data in any component.

If you provide the service in module level(same singleton instance
will share for all component).

If you provide  the service in component level(new instance will

create for component).

So based on your use case do not inject the service in the component level.

@Component({
  selector: 'a-comp',
  template: `<div></div>`
})
export class AComponent implements OnInit {
  constructor( private authService: AuthService ) {}
  ngOnInit() {
    console.log('HOY', this.authService.getUser());
  }
}

@Component({
  selector: 'b-comp',
  template: `<div></div>`
})
export class BComponent implements OnInit {
  constructor( private authService: AuthService ) {}
  ngOnInit() {
    console.log('HOY', this.authService.getUser());
  }
}


问:
How to convert a column in a csv file using Nifi?
I Have a raw csv file as below

```<code>   SVEIS , SVESID,SVETIME
   Quneter,53553,01122003010005
   renchure,37151,12092008011005
</code>```

now I need to change the data  from day month year to year day month as below

```<code>   SVEIS , SVESID,SVETIME
  Quneter,53553,2003-01-12 01:00:05
  renchure,37151,2008-12-09 01:10:05
</code>```

I need to change this using NIFI

I have used replace text processor but I am getting error like unable to process 10 of 10 records in nifi

答:
We can start from a simple expression using quantifiers and capturing groups:

```<code>(.+,)([0-9]{2})([0-9]{2})([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})
</code>```

and replace it with:

```<code>$1$4-$3-$2 $5:$6:$7
</code>```

where $1-$7 are our groups with new desired format.

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

Demo

const regex = /(.+,)([0-9]{2})([0-9]{2})([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})/gm;
const str = `Quneter,53553,01122003010005
renchure,37151,12092008011005`;
const subst = `$1$4-$3-$2 $5:$6:$7`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);```

Body:
I Have a raw csv file as below

   SVEIS , SVESID,SVETIME
   Quneter,53553,01122003010005
   renchure,37151,12092008011005

now I need to change the data  from day month year to year day month as below

   SVEIS , SVESID,SVETIME
  Quneter,53553,2003-01-12 01:00:05
  renchure,37151,2008-12-09 01:10:05

I need to change this using NIFI

I have used replace text processor but I am getting error like unable to process 10 of 10 records in nifi

Body:
We can start from a simple expression using quantifiers and capturing groups:

(.+,)([0-9]{2})([0-9]{2})([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})

and replace it with:

$1$4-$3-$2 $5:$6:$7

where $1-$7 are our groups with new desired format.

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

Demo

const regex = /(.+,)([0-9]{2})([0-9]{2})([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})/gm;
const str = `Quneter,53553,01122003010005
renchure,37151,12092008011005`;
const subst = `$1$4-$3-$2 $5:$6:$7`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);


问:
How do I make an alphabetized list of all distinct words in a file with the number of times each word was used?
I am writing a program using Microsoft Visual C++. In the program I must read in a text file and print out an alphabetized list of all distinct words in that file with the number of times each word was used.

I have looked up different ways to alphabetize a string but they do not work with the way I have my string initialized.

```<code>// What is inside my text file
Any experienced programmer engaged in writing programs for use by others knows
that, once his program is working correctly, good output is a must. Few people
really care how much time and trouble a programmer has spent in designing and
debugging a program. Most people see only the results. Often, by the time a
programmer has finished tackling a difficult problem, any output may look
great. The programmer knows what it means and how to interpret it. However,
the same cannot be said for others, or even for the programmer himself six
months hence.
</code>```

```<code>string lines;
getline(input, lines);      // Stores what is in file into the string
</code>```

I expect an alphabetized list of words with the number of times each word was used. So far, I do not know how to begin this process.

答: Id probably start by inserting all of those words into an array of strings, then start with the first index of the array and compare that with all of the other indexes if you find matches, add 1 to a counter and after you went through the array you could display the word you were searching for and how many matches there were and then go onto the next element and compare that with all of the other elements in the array and display etc. Or maybe if you wanna make a parallel array of integers that holds the number of matches you could do all the comparisons at one time and the displays at one time. </p>

Body:
I am writing a program using Microsoft Visual C++. In the program I must read in a text file and print out an alphabetized list of all distinct words in that file with the number of times each word was used.

I have looked up different ways to alphabetize a string but they do not work with the way I have my string initialized.

// What is inside my text file
Any experienced programmer engaged in writing programs for use by others knows
that, once his program is working correctly, good output is a must. Few people
really care how much time and trouble a programmer has spent in designing and
debugging a program. Most people see only the results. Often, by the time a
programmer has finished tackling a difficult problem, any output may look
great. The programmer knows what it means and how to interpret it. However,
the same cannot be said for others, or even for the programmer himself six
months hence.

string lines;
getline(input, lines);      // Stores what is in file into the string

I expect an alphabetized list of words with the number of times each word was used. So far, I do not know how to begin this process.


问:
React native text word break strategy of strings with dash

Setup

```<code>react: 16.6.0-alpha.8af6728
react-native: 0.57.4
</code>```

Problem

Word breaking in Text component does not handle strings with dashes the way app design wants it. I want to word wrap the whole word taking into account dashes. This whole string-with-dashes should be considered a word when word wrapping. But flexbox does not.

Code

```<code><TouchableOpacity style={{ width: 250, backgroundColor: 'skyblue' }}>
    <Text style={styles.welcome}>This is a sample of text-with-dash incorrectly word breaking</Text>
</TouchableOpacity>
</code>```

Restult looks like this:

But I want it to end up like this (text-with-dash on a seperate line):

The issue is I get the strings from an online CMS and want a flexbox styling solution to this problem. There might be situation where a string-with-dash could end up in a single line so in those instances I don't want a word wrap of cause.

答:
You can now use the textbreakstrategy as props of Text.

By default, the text break strategy is 'highQuality' which breaks the words and appends the '-' for those words.

Use 'simple' in the textbreakstrategy to avoid the '-' when breaking words.

For example:

```<code><Text textBreakStrategy={'simple'}>
This is a sample of text-with-dash incorrectly word breaking
</Text>
</code>```

Additional Reference:
https://developer.android.com/reference/android/text/Layout.html#BREAK_STRATEGY_SIMPLE

Body:
Setup

react: 16.6.0-alpha.8af6728
react-native: 0.57.4

Problem

Word breaking in Text component does not handle strings with dashes the way app design wants it. I want to word wrap the whole word taking into account dashes. This whole string-with-dashes should be considered a word when word wrapping. But flexbox does not.

Code

<TouchableOpacity style={{ width: 250, backgroundColor: 'skyblue' }}>
    <Text style={styles.welcome}>This is a sample of text-with-dash incorrectly word breaking</Text>
</TouchableOpacity>

Restult looks like this:

But I want it to end up like this (text-with-dash on a seperate line):

The issue is I get the strings from an online CMS and want a flexbox styling solution to this problem. There might be situation where a string-with-dash could end up in a single line so in those instances I don't want a word wrap of cause.

Body:
You can now use the textbreakstrategy as props of Text.

By default, the text break strategy is 'highQuality' which breaks the words and appends the '-' for those words.

Use 'simple' in the textbreakstrategy to avoid the '-' when breaking words.

For example:

<Text textBreakStrategy={'simple'}>
This is a sample of text-with-dash incorrectly word breaking
</Text>

Additional Reference:
https://developer.android.com/reference/android/text/Layout.html#BREAK_STRATEGY_SIMPLE


问:
Why is my jQuery is not append in select option?
I try to append data in select option
but it's not showing/append in it

The AJAX works perfectly, but the append is fail

```<code><select class="form-control show-tick" style="font-size: 14px;" id="office_code" name="office_code" data-live-search="true">
  <option value="choose" disabled selected>-- Choose Office --</option>
</select>
<select class="form-control show-tick" style="font-size: 14px;" id="kode_kantor" name="office_code" data-live-search="true">
  <option value="choose" disabled selected>-- choose office --</option>
</select>
</code>```

This is the AJAX code

```<code><script type="text/javascript">
  $.ajax({
    'url': 'http://x.x.x.x/test/API/getOfficeBySearch',
    'method': 'POST',
    'data': {
      'request': JSON.stringify({
        "username": "test",
        "password": "test",
        "searchparam": "type",
        "searchvalue": "office"
      })
    },
    'success': function(result) {
      result = JSON.parse(result)
      result.data.forEach(function(value, index) {
      var element =`<optionvalue="${value.officeid}">${value.name}</option>`
        $('#office_code').append(element)
      })

    }
  })
</script>
</code>```

答: There's a missing space, replace <optionvalue with <option value.

Body:
I try to append data in select option
but it's not showing/append in it

The AJAX works perfectly, but the append is fail

<select class="form-control show-tick" style="font-size: 14px;" id="office_code" name="office_code" data-live-search="true">
  <option value="choose" disabled selected>-- Choose Office --</option>
</select>
<select class="form-control show-tick" style="font-size: 14px;" id="kode_kantor" name="office_code" data-live-search="true">
  <option value="choose" disabled selected>-- choose office --</option>
</select>

This is the AJAX code


问:
How to deep link my android app to paytm and freecharge app?
I am creating an android application for browsing plans and tariff of mobile recharges. What I want is that when the user selects a plan from my app, then on clicking either of the one option ie paytm or freecharge:

The mobile recharge screen of the respective app gets open.

User's phone number and amount of recharge gets prefilled.

As far as I know this is possible either through Intends or Deeplinking. But the problem is that:

If I use intends and open paytm/freecharge using their package names it will open the home screen of those apps. Now how to open the
  recharge mobile screen and prefill the numbers and recharge amount??

If I follow the deeplink approach, for either of the apps what url to call and what parameters to pass?? I got a deeplink url of paytm in
  their api docs but that too opens only the home screen.

Once this is done, user can proceed to recharge via both these apps. I have seen this feature in a similar app ireff and thats excatly what I want to implement.

Above are the screen on which I want to reach and fill in the phone number and amount which user has filled on my app. Please let me know how to do this I couldn't find anything useful about this on the internet. Thanks.

答:
I have done for paytm in kotlin</p>

```<code>fun paytm(amount:String,contact_number:String){
val intent = Intent()
val bundle = Bundle()
bundle.putString(PaytmConstants.TRANSACTION_AMOUNT, amount)
bundle.putString(
PaytmConstants.PAYEE_MOBILE_NUMBER,
contact_number
)
bundle.putBoolean(PaytmConstants.IS_MOBILE_NUMBER_EDITABLE, false)
bundle.putBoolean(PaytmConstants.IS_AMOUNT_EDITABLE, false)
intent.component = ComponentName("net.one97.paytm", "net.one97.paytm.AJRJarvisSplash")
intent.putExtra(PaytmConstants.PAYMENT_MODE, 1)
intent.putExtra(PaytmConstants.MERCHANT_DATA, bundle)
startActivityForResult(intent, 103)
}
</code>```

Body:
I have done for paytm in kotlin

fun paytm(amount:String,contact_number:String){
val intent = Intent()
val bundle = Bundle()
bundle.putString(PaytmConstants.TRANSACTION_AMOUNT, amount)
bundle.putString(
PaytmConstants.PAYEE_MOBILE_NUMBER,
contact_number
)
bundle.putBoolean(PaytmConstants.IS_MOBILE_NUMBER_EDITABLE, false)
bundle.putBoolean(PaytmConstants.IS_AMOUNT_EDITABLE, false)
intent.component = ComponentName("net.one97.paytm", "net.one97.paytm.AJRJarvisSplash")
intent.putExtra(PaytmConstants.PAYMENT_MODE, 1)
intent.putExtra(PaytmConstants.MERCHANT_DATA, bundle)
startActivityForResult(intent, 103)
}


问:
How do I write a csv file in R, where my input is written to the file as row?
This is a very simple issue and I'm surprised that there are no examples online.

I have a vector:

```<code>vector <- c(1,1,1,1,1)
</code>```

I would like to write this as a csv as a simple row:

```<code>write.csv(vector, file ="myfile.csv", row.names=FALSE)
</code>```

When I open up the file I've just written, the csv is written as a column of values.
It's as if R decided to put in newlines after each number 1.

Forgive me for being ignorant, but I always assumed that the point of having comma-separated-values was to express a sequence from left to right, of values, separated by commas.  Sort of like I just did; in a sense mimicking the syntax of written word.  Why does R cling so desperately to the column format when a csv so clearly should be a row?

All linguistic philosophy aside, I have tried to use the transpose function.  I've dug through the documentation.  Please help!  Thanks.

答:
fwrite from data.table package is also another option: </p>

```<code>library(data.table)

vector <- c(1,1,1,1,1)
fwrite(data.frame(t(vector)),file="myfile.csv",sep=",",row.names = FALSE)
</code>```

Body:
This is a very simple issue and I'm surprised that there are no examples online.

I have a vector:

vector <- c(1,1,1,1,1)

I would like to write this as a csv as a simple row:

write.csv(vector, file ="myfile.csv", row.names=FALSE)

When I open up the file I've just written, the csv is written as a column of values.
It's as if R decided to put in newlines after each number 1.

Forgive me for being ignorant, but I always assumed that the point of having comma-separated-values was to express a sequence from left to right, of values, separated by commas.  Sort of like I just did; in a sense mimicking the syntax of written word.  Why does R cling so desperately to the column format when a csv so clearly should be a row?

All linguistic philosophy aside, I have tried to use the transpose function.  I've dug through the documentation.  Please help!  Thanks.

Body:
fwrite from data.table package is also another option:

library(data.table)

vector <- c(1,1,1,1,1)
fwrite(data.frame(t(vector)),file="myfile.csv",sep=",",row.names = FALSE)


问:
Nodejs - How do HTTP responses always hit the right device?
Нello to all! A while ago I asked this question. After helpful responses I learned that the web, by design, makes it impossible to directly differentiate devices connected to the same router.

So for example, the code below can never be 100% functional...

```<code>require('http').createServer((req, res) => {

    let uniqueDeviceId = getUniqueDeviceId(req);

}).listen(80, '<my public ip>', 511);
</code>```

... because there's no way to implement getUniqueDeviceId in a guaranteed way. It can't just return req.connection.remoteAddress, as multiple devices could have the same address.

Given this, my question is: How does res.end(...) always respond to the correct device??

E.g. consider this simple server:

```<code>require('http').createServer((req, res) => {

    res.end(req.url);

}).listen(80, '{{my public ip}}', 511);
</code>```

Take two different devices, connected to the same IP address. Each device uses its own url:

Device 1 uses http://{{my public ip}}/device1

Device 2 uses http://{{my public ip}}/device2

Now both these devices bombard their url with thousands of requests per second.

In response, Device 1 will always get /device1, and Device 2 will always get /device2, even with this configuration that should lead to race conditions!

Even though I can't determine a device's unique id directly, res.end will always correspond to the appropriate req - it will never blunder and send a response to some different req, even if that different req was received at almost exactly the same time, from the same IP address. To me this is proof that at some level, lower than Nodejs, unique device IDs can be determined.

If this is correct, at what level of HTTP architecture do we get the guarantee that a response will always go back to its initial requester? And how is this implemented?

答:
MAC addresses do "uniquely" identify devices. But even tho:

First off: http is on top of tcp/ip.
IP is a Standart of defining locations of devices in a Network. Devices get an IP from their router, and the device can send to a router to their own IP. (192.168.2.1:80(Router) -> 192.168.2.100:80(PC))

The router then sends stuff to the WWW, via your ISP.

Your public IP -Request> ISP -Request> TargetIP -Answer> ISP -Answer> You

(This all happens while the IP and Ports of the Package are kept in the Package which is wrapped inside other Packets. Also there are much more hops than these most of the time.)

Then there are ports: If you use an Port it will be locally blocked by the device. If there would not be Ports, TCP/IP would have those race conditions you mentioned as they would block each other.

The thing is this: You are not using different Ports or IP's. So whatever you are doing is just having one Server who handles both incoming Requests otherwise the second Server who tries to block the Port will not be able to as it's not TCP/IP conform.
You will not be able to have IP1:80/device1 and IP1:80/device2 running with 2 different Applications trying to block the Port 80.

So you are kind of right(that there would be discrepancies) but also very mislead by the thought of 2 Server being able to run of Port 80.

They way to handle the case you are talking about is the following:

Either

Use Apache/Nginx/Nodejs and make a main Application(Router) to redirect Querys to the Server via Reverse Proxy and other kinds of *questing methods.

Use different Ports

And for clarification: HTTP is the following:

Pathing ( /this/is/a/path )

Headers ( these you don't really see, but they contain cache hints, data types, and file handling on how files should be treated and as what and security )

What Servers do with HTTP is using the data that they get from the HTTP format. (which is simply just a specific layout of data in TCP)
And use that to determine where to path/route the outcome.

Socket Handling as shaochuancs mentioned is Part of TCP and UDP, two low level Protocols.
There are about 7 Layers in Networking. So this is only part of the whole story. If you are interested in learning more search for Network Layers specifically on Google. It's a good keyword to get more info about this Stuff.

Body:
Нello to all! A while ago I asked this question. After helpful responses I learned that the web, by design, makes it impossible to directly differentiate devices connected to the same router.

So for example, the code below can never be 100% functional...

require('http').createServer((req, res) => {

    let uniqueDeviceId = getUniqueDeviceId(req);

}).listen(80, '<my public ip>', 511);

... because there's no way to implement getUniqueDeviceId in a guaranteed way. It can't just return req.connection.remoteAddress, as multiple devices could have the same address.

Given this, my question is: How does res.end(...) always respond to the correct device??

E.g. consider this simple server:

require('http').createServer((req, res) => {

    res.end(req.url);

}).listen(80, '{{my public ip}}', 511);

Take two different devices, connected to the same IP address. Each device uses its own url:

Device 1 uses http://{{my public ip}}/device1

Device 2 uses http://{{my public ip}}/device2

Now both these devices bombard their url with thousands of requests per second.

In response, Device 1 will always get /device1, and Device 2 will always get /device2, even with this configuration that should lead to race conditions!

Even though I can't determine a device's unique id directly, res.end will always correspond to the appropriate req - it will never blunder and send a response to some different req, even if that different req was received at almost exactly the same time, from the same IP address. To me this is proof that at some level, lower than Nodejs, unique device IDs can be determined.

If this is correct, at what level of HTTP architecture do we get the guarantee that a response will always go back to its initial requester? And how is this implemented?


问:
Display arraylist object using javabeans
I'm making a webscraping application so I'm not using any database just javabeans to store the data and xhtml pages to display it, now I have an arraylist objects in which every object there's data I need to display in xhtml page, but I don't know how to.
I know it is posible with jsp using jstl but some days ago I heard that almost nobody uses jsp these days,... So I don't wan't to use it for this project.

javabeans

```<code>@ManagedBean(name = "login")
@SessionScoped
public class Login implements Serializable{
    private boolean isLoged=false;
    PortalUDB portaludb;
    Estudiante estudiante; // This is the object tha has the array list
</code>```

Class that contains the two arraylist of objects

```<code>public final class Estudiante{
    private Document document;
    private int uv_carrera;
    private int uv_actuales;
    private final Connection.Response loginForm;
    public List<MateriaPensum> materia_pensum = new ArrayList<>();
    public List<MateriaExpediente> materia_expediente = new ArrayList<>();
</code>```

I've already achieved it using ui:repeat

```<code><ui:repeat var="materia" value="#{login.estudiante.materia_expediente}"> <h1>#{materia.asignatura}</h1> </ui:repeat>
</code>```

Just I don't know why I can use every variable in the class MateriaExpediente when they are private.

```<code>public class MateriaExpediente extends MateriaPensum{
    int anio;
    String ciclo;
    String asignatura;
    String matricula;
    float nota;
    String resultado;
</code>```

Maybe because I use getter and setter methods?

答:
If you're using Spring MVC or Spring Boot then you can use Thymeleaf. I am guessing you are passing the Estudiante bean to the request scope as estudiante attribute. So, in order to loop over the materia_pensum list in your html:

```<code><p th:each="materiaPensum : ${estudiante}" th:text="${materiaPensum.name}"><p/>
</code>```

Body:
I'm making a webscraping application so I'm not using any database just javabeans to store the data and xhtml pages to display it, now I have an arraylist objects in which every object there's data I need to display in xhtml page, but I don't know how to.
I know it is posible with jsp using jstl but some days ago I heard that almost nobody uses jsp these days,... So I don't wan't to use it for this project.

javabeans

@ManagedBean(name = "login")
@SessionScoped
public class Login implements Serializable{
    private boolean isLoged=false;
    PortalUDB portaludb;
    Estudiante estudiante; // This is the object tha has the array list

Class that contains the two arraylist of objects

public final class Estudiante{
    private Document document;
    private int uv_carrera;
    private int uv_actuales;
    private final Connection.Response loginForm;
    public List<MateriaPensum> materia_pensum = new ArrayList<>();
    public List<MateriaExpediente> materia_expediente = new ArrayList<>();

I've already achieved it using ui:repeat

<ui:repeat var="materia" value="#{login.estudiante.materia_expediente}">
#{materia.asignatura}
 </ui:repeat>

Just I don't know why I can use every variable in the class MateriaExpediente when they are private.

public class MateriaExpediente extends MateriaPensum{
    int anio;
    String ciclo;
    String asignatura;
    String matricula;
    float nota;
    String resultado;

Maybe because I use getter and setter methods?

Body:
If you're using Spring MVC or Spring Boot then you can use Thymeleaf. I am guessing you are passing the Estudiante bean to the request scope as estudiante attribute. So, in order to loop over the materia_pensum list in your html:

<p th:each="materiaPensum : ${estudiante}" th:text="${materiaPensum.name}"><p/>


问:
I want to Modifying bar-position in matplotlib bar-plot
I find an answer below
Modifying bar-width and bar-position in matplotlib bar-plot (looping over containers)
but I really do not know what "sizes" mean when I run the code, python told me, "sizes" is unknown, the code is below, anyone can help me?</p>

```<code> for container in axes.containers:
        for i, child in enumerate(container.get_children()):
            child.set_x(df.index[i] - sizes[i]/2)
            plt.setp(child, width=sizes[i])
</code>```

答:
In the code you refer to, sizes is a list or array of widths that the person wants their bars to be.

When you are using the code you should define such a list or array, based on the bar widths you want.

Hope this helps.

Body:
I find an answer below
Modifying bar-width and bar-position in matplotlib bar-plot (looping over containers)
but I really do not know what "sizes" mean when I run the code, python told me, "sizes" is unknown, the code is below, anyone can help me?

 for container in axes.containers:
        for i, child in enumerate(container.get_children()):
            child.set_x(df.index[i] - sizes[i]/2)
            plt.setp(child, width=sizes[i])


问:
React Hooks - Should I use 'useState' for state that is unchanging?
When I initially learned React Component's I was always told to put everything in this.state. Whether it be some pieces of data that update frequently or some that never update at all.

However, with the implementation of React hooks, I'm not sure how frequently I should use useState even when the state will not update.

Let me give you an example of some of my form logic:

```<code>const FormAuth = props => {
    //Frequently updates
    const [validInput, setValidInput] = useState({
        isCompletedForm: Boolean,
        firstName: Boolean,
        lastName: Boolean,
        email: Boolean,
        password: Boolean,
        confirmPassword: Boolean
    });

    // Never updates
    const [formSchema, setFormSchema] = useState({
        firstName: Joi.string().required(),
        lastName: Joi.string().required(),
        email: Joi.string().required().email().regex(emailRegex),
        password: Joi.string().required().regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$^+=!*()@%&?.]).{8,30}$/),
        confirmPassword: Joi.string().required()
    })

    // Never updates
    const [inputRef, setInputRef] = useState({
        firstNameRef: React.createRef(),
        lastNameRef: React.createRef(),
        emailRef: React.createRef(),
        passwordRef: React.createRef(),
        confirmPasswordRef: React.createRef()
    });

    // render some JSX
}
</code>```

Here I have 3 states. The first state are Booleans that say if the inputs look good. The second state is a formSchema which will never be updated. Lastly, the third state is the Refs for each of the inputs which will also never be updated.

My question is: Would is make more sense to only have one state for validInputs since it updates frequently, and then for formSchema and inputRef create a const object with vanilla javascript? Or should everything go into state like before?

It seems to me that it would make more sense to only use useState if that state is going to update, but I'm trying to see what is the proper convention for hooks moving forward.

答:
You should only need to utilize state if:

it controls some sort of element (like an input, select,
textarea and so on).

it's controlling some sort of data that needs to be manipulated (like a todo list that needs to have some items that are created, read, updated and deleted  -- holds true for isomorphic apps as well, where some data needs to be manipulated on the front-end before being sent to a back-end for storage).

it's used for some sort of conditional rendering, where the DOM needs to be re-rendered with UI changes (like an isLoading boolean that shows a Spinner when true, but then displays some sort of layout when false).

There's no reason to clutter your state if it (whatever data type it is): Needs to be reusable across multiple components, is static, and doesn't update the DOM in any way (like a ref, or a field-level validation function or some sort static list of items).

In simple terms, doesn't matter if it's a class component or a functional component with a hook, you'll only need to use state if it requires dynamically manipulating/controlling something within the DOM.

Here's a simple example of a form with some validation:

Body:
When I initially learned React Component's I was always told to put everything in this.state. Whether it be some pieces of data that update frequently or some that never update at all.

However, with the implementation of React hooks, I'm not sure how frequently I should use useState even when the state will not update.

Let me give you an example of some of my form logic:

const FormAuth = props => {
    //Frequently updates
    const [validInput, setValidInput] = useState({
        isCompletedForm: Boolean,
        firstName: Boolean,
        lastName: Boolean,
        email: Boolean,
        password: Boolean,
        confirmPassword: Boolean
    });

    // Never updates
    const [formSchema, setFormSchema] = useState({
        firstName: Joi.string().required(),
        lastName: Joi.string().required(),
        email: Joi.string().required().email().regex(emailRegex),
        password: Joi.string().required().regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$^+=!*()@%&?.]).{8,30}$/),
        confirmPassword: Joi.string().required()
    })

    // Never updates
    const [inputRef, setInputRef] = useState({
        firstNameRef: React.createRef(),
        lastNameRef: React.createRef(),
        emailRef: React.createRef(),
        passwordRef: React.createRef(),
        confirmPasswordRef: React.createRef()
    });

    // render some JSX
}

Here I have 3 states. The first state are Booleans that say if the inputs look good. The second state is a formSchema which will never be updated. Lastly, the third state is the Refs for each of the inputs which will also never be updated.

My question is: Would is make more sense to only have one state for validInputs since it updates frequently, and then for formSchema and inputRef create a const object with vanilla javascript? Or should everything go into state like before?

It seems to me that it would make more sense to only use useState if that state is going to update, but I'm trying to see what is the proper convention for hooks moving forward.


问:
Choose knots in Python regression splines
I'm trying to make a model for a very simple data set using spline regression but so far I couldn't find any Python implementation that lets me choose knots position. The picture below shows where I want to put my knot, I want my function to consist only of 2 linear regressions and nothing more.

So far I've tried pyearth and scipy splines but I couldn't find in any of them parameter responsible for setting knots position and even when I tweak other parameters I can't get result that would satisfy me.

答: patsy.dmatrix and scipy.interpolate.splrep both have knot selection features </p>


问:
What is the quickest way from a concept to a site?
I've got a bunch of website ideas and I was wondering what is the quickest way to get from a pretty thorough concept definition (idea mind-maps, use-cases, architecture diagrams ) to a working website. The only point is to get to something that's functional, not worrying about performance. The idea is to get something out to showcase a functional site, and after worry about fine-tuning or re-writing parts if necessary.

I am familiar with quite a few web frameworks from open-source and proprietary world, but I could not find so far a swiss-army-knife of web development environments that can get you fast from a concept to a working site.  I was kinda wondering if there is such a thing, free or non-free

Looking forward to your suggestions...

UPDATE: The question might get a bit too metaphoric for the kind readers of this site, but I'm at a moment where I feel that implementation details are killing my creativity ... maybe you'll laugh or you'll feel offended, I'm just wondering if anyone can give me a useful hint..

答:
From the perspective of an asp.net developer, and not wanting to incite a holy war, web forms designer in visual studio, not really free.

Use an ORM like SubSonic (or similar) to generate a DAL, you can then use the forms designer to drag and drop your way to a functioning proof of concept pretty quickly, utilising a toolkit which will cover 80% of the tasks that you are likely to encounter.

The resultant markup will probably be very ugly and the site may be a little less performant that what you would want for production, but pplz will be able to click stuff and watch dem blinkenlights.

If the idea floats, you can then tweak and maybe reuse your DAL, and maybe port the site to MVC or something else that makes leaner markup.

Over time, you end up collecting a fair amount of commonly used things, and your prototypes aren't quite so ugly under the hood, so they take less time to turn in to production pieces.

So, that's one perspective, but if you have never used .net, the initial learning curve might make this not so quick.

OwnerDisplayName: Cip

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: seanb


问:
Import CSV to SQLite
I'm trying to import a csv file to an SQLite table.

Example csv:

```<code>1,2
5,6
2,7
</code>```

Example command:

```<code>sqlite> create table foo(a, b);
sqlite> .separator ,
sqlite> .import test.csv foo
Error: test.csv line 1: expected 2 columns of data but found 4
</code>```

I'm not even sure why it would find four columns with six pieces of data and two columns.

答:
How to import csv file to sqlite3

Create database

```<code>sqlite3 NYC.db
</code>```

Set the mode & tablename

```<code>.mode csv tripdata
</code>```

Import the csv file data to sqlite3

```<code>.import yellow_tripdata_2017-01.csv tripdata
</code>```

Find tables

```<code>.tables
</code>```

Find your table schema

```<code>.schema tripdata
</code>```

Find table data

```<code>select * from tripdata limit 10;
</code>```

Count the number of rows in the table

```<code>select count (*) from tripdata;
</code>```

Title: Import CSV to SQLite

Body:
I'm trying to import a csv file to an SQLite table.

Example csv:

1,2
5,6
2,7

Example command:

sqlite> create table foo(a, b);
sqlite> .separator ,
sqlite> .import test.csv foo
Error: test.csv line 1: expected 2 columns of data but found 4

I'm not even sure why it would find four columns with six pieces of data and two columns.

Body:
How to import csv file to sqlite3

Create database

sqlite3 NYC.db

Set the mode & tablename

.mode csv tripdata

Import the csv file data to sqlite3

.import yellow_tripdata_2017-01.csv tripdata

Find tables

.tables

Find your table schema

.schema tripdata

Find table data

select * from tripdata limit 10;

Count the number of rows in the table

select count (*) from tripdata;


问:
How to combine two postgres columns to single value (json object)
I'm trying to write a query on my food.list table:

```<code>categories    | items
----------------------------
dairy         | ["milk", "cheese"]
fruit         | ["apples", "pears", "grapes"]
vegetables    | ["carrots"]
</code>```

and return a selected_foods column with a single row. I want the row's value to be an object with a list of categories (keys) with an array of items (values).

```<code>selected_foods
------------------------------------
{
  dairy: ["milk", "cheese"],
  fruit: ["apples", "pears", "grapes"],
  vegetables: ["carrots"]
}
</code>```

So far, I've tried:

```<code>SELECT json_agg(json_build_object(categories, items::json))::json
AS selected_foods
FROM food.list
</code>```

But this returns an array of objects, i.e.:

```<code>selected_foods
------------------------------------
[
  { dairy: ["milk", "cheese"] },
  { fruit: ["apples", "pears", "grapes"] },
  { vegetables: ["carrots"] }
]
</code>```

I think I'm applying the json_build_object function too early...or maybe I need to unwrap them again after?

Any help would be awesome, thanks :)

答:
Use json_object_agg

```<code>SELECT json_object_agg( categories, items::json)  as selected_foods
     from list
</code>```

DEMO

Body:
I'm trying to write a query on my food.list table:

categories    | items
----------------------------
dairy         | ["milk", "cheese"]
fruit         | ["apples", "pears", "grapes"]
vegetables    | ["carrots"]

and return a selected_foods column with a single row. I want the row's value to be an object with a list of categories (keys) with an array of items (values).

selected_foods
------------------------------------
{
  dairy: ["milk", "cheese"],
  fruit: ["apples", "pears", "grapes"],
  vegetables: ["carrots"]
}

So far, I've tried:

SELECT json_agg(json_build_object(categories, items::json))::json
AS selected_foods
FROM food.list

But this returns an array of objects, i.e.:

selected_foods
------------------------------------
[
  { dairy: ["milk", "cheese"] },
  { fruit: ["apples", "pears", "grapes"] },
  { vegetables: ["carrots"] }
]

I think I'm applying the json_build_object function too early...or maybe I need to unwrap them again after?

Any help would be awesome, thanks :)

Body:
Use json_object_agg

SELECT json_object_agg( categories, items::json)  as selected_foods
     from list

DEMO


问:
The value is truncated in JSON object when the '-' is contained in the string value
I want to get the value from database using a SQL query (by sampleId which contains '-' sign), however, the query string is truncated.

Here is some of my script where the sampleId is fetched from the last API call:

```<code>   * json result = response[0].result
    * print result
    * def personId = result[0].personid
    * def sampleId = result[0].sampleid
</code>```

Given path 'srehr/SendSample'

```<code>    * def config = read('classpath:utils/yntestDBConfig.json')
    * def DbUtils = Java.type('utils.DBUtils')
    * def db = new DbUtils(config)

    * def foo = {getBatchIDSQL: '#("select operatetime from sr_sendreceive_sample where sampleid = " + sampleId)'}
    * print foo.getBatchIDSQL
</code>```

Here is the specified log in the report:

09:00:06.130 [print] select operatetime from sr_sendreceive_sample where sampleid = 1cfacfa4-eb06-4413-b060-9507bdebd1eb

mainFlow.feature:72 - javascript evaluation failed: db.readValue(foo.getBatchIDSQL), StatementCallback; bad SQL grammar [select operatetime from sr_sendreceive_sample where sampleid = 1cfacfa4-eb06-4413-b060-9507bdebd1eb]; nested exception is java.sql.SQLSyntaxErrorException: Unknown column '1cfacfa4' in 'where clause'

My question: from the log, you see that unknown column '1cfacfa4' is not expected, it should be '1cfacfa4-eb06-4413-b060-9507bdebd1eb'

答:
Try having the strings in SQL within quotes:</p>

```<code>* def sql = "select operatetime from sr_sendreceive_sample where sampleid = '" + sampleId + "'"
</code>```

Body:
I want to get the value from database using a SQL query (by sampleId which contains '-' sign), however, the query string is truncated.

Here is some of my script where the sampleId is fetched from the last API call:

   * json result = response[0].result
    * print result
    * def personId = result[0].personid
    * def sampleId = result[0].sampleid

Given path 'srehr/SendSample'

    * def config = read('classpath:utils/yntestDBConfig.json')
    * def DbUtils = Java.type('utils.DBUtils')
    * def db = new DbUtils(config)

    * def foo = {getBatchIDSQL: '#("select operatetime from sr_sendreceive_sample where sampleid = " + sampleId)'}
    * print foo.getBatchIDSQL

Here is the specified log in the report:

09:00:06.130 [print] select operatetime from sr_sendreceive_sample where sampleid = 1cfacfa4-eb06-4413-b060-9507bdebd1eb

mainFlow.feature:72 - javascript evaluation failed: db.readValue(foo.getBatchIDSQL), StatementCallback; bad SQL grammar [select operatetime from sr_sendreceive_sample where sampleid = 1cfacfa4-eb06-4413-b060-9507bdebd1eb]; nested exception is java.sql.SQLSyntaxErrorException: Unknown column '1cfacfa4' in 'where clause'

My question: from the log, you see that unknown column '1cfacfa4' is not expected, it should be '1cfacfa4-eb06-4413-b060-9507bdebd1eb'

Body:
Try having the strings in SQL within quotes:

* def sql = "select operatetime from sr_sendreceive_sample where sampleid = '" + sampleId + "'"


问:
Sublime Text 3 JavaScript Autocomplete
I use SublimeText3 and I get the function of autocomplete only for HTML and CSS but not for JavaScript. Why is this? And how can I get JavaScript autocomplete?</p>

答: there is Javascript Autocompletion, but it seem not up to date with document. https://packagecontrol.io/packages/JavaScript%20Completions</p>

Title: Sublime Text 3 JavaScript Autocomplete


问:
How do I turn off echo in a terminal?
I'm writing a Bourne shell script and have a password input like this:

```<code>echo -n 'Password: '
read password
</code>```

Obviously, I don't want the password being echoed to the terminal, so I want to turn off echo for the duration of the read. I know there's way to do this with stty, but I'll ask the question for the benefit of the community whilst I go read the manpage. ;)

答:
```<code>stty_orig=`stty -g`
stty -echo
echo 'hidden section'
stty $stty_orig
</code>```

Title: How do I turn off echo in a terminal?

Body:
I'm writing a Bourne shell script and have a password input like this:

echo -n 'Password: '
read password

Obviously, I don't want the password being echoed to the terminal, so I want to turn off echo for the duration of the read. I know there's way to do this with stty, but I'll ask the question for the benefit of the community whilst I go read the manpage. ;)


问:
Working with Dates rowwise: Get rows of Dates ("POSIXct") from a dataframe without loosing class
I have a dataframe called df where all columns are of class "POSIXct". Like that:

```<code>df
                   X1                  X2
1 2000-01-01 00:00:00 2000-01-01 00:00:03
2 2000-01-01 00:00:01 2000-01-01 00:00:04
3 2000-01-01 00:00:02 2000-01-01 00:00:05
</code>```

I want to have all values as one "POSIXct" vector by extracting the values rowwise. So this is my expected output:

```<code>vec <- magicfunction(df)
vec
2000-01-01 00:00:00 2000-01-01 00:00:03 2000-01-01 00:00:01 2000-01-01 00:00:04 2000-01-01 00:00:02 2000-01-01 00:00:05
</code>```

Unfortunately, do.call("c", df) works columnwise. There is a question about how to unlist rowwise where it is recommended to use t() but using the t() function converts the dataframe to a matrix which also does not work with Dates. Further, apply(df, 1, function(x) ...) processes dataframes rowwise, but apply() also changes dates. On the other hand, lapply() works with Dates but it works columnwise.

This is the data I used in the example:

```<code>library(lubridate)
k <- 2
vec <- seq(ymd_hms("2000-01-01 00:00:00"),
           ymd_hms("2000-01-01 00:00:5"),
           by = 1)

df <- as.data.frame(split(vec, f = as.factor(rep(1:k, each = length(vec)/k))))
</code>```

答:
As I mentioned in my comment, you can use the answer in the duplicate repeatedly on each line:

```<code>df1 <- split(df,1:nrow(df))
do.call("c",lapply(df1,function(x) do.call("c",x)))
</code>```

Note that neither the duplicate nor my comment suggests do.call("c",df) on the entire data frame, so it is not surprising that that does not work.

Body:
I have a dataframe called df where all columns are of class "POSIXct". Like that:

df
                   X1                  X2
1 2000-01-01 00:00:00 2000-01-01 00:00:03
2 2000-01-01 00:00:01 2000-01-01 00:00:04
3 2000-01-01 00:00:02 2000-01-01 00:00:05

I want to have all values as one "POSIXct" vector by extracting the values rowwise. So this is my expected output:

vec <- magicfunction(df)
vec
2000-01-01 00:00:00 2000-01-01 00:00:03 2000-01-01 00:00:01 2000-01-01 00:00:04 2000-01-01 00:00:02 2000-01-01 00:00:05

Unfortunately, do.call("c", df) works columnwise. There is a question about how to unlist rowwise where it is recommended to use t() but using the t() function converts the dataframe to a matrix which also does not work with Dates. Further, apply(df, 1, function(x) ...) processes dataframes rowwise, but apply() also changes dates. On the other hand, lapply() works with Dates but it works columnwise.

This is the data I used in the example:

library(lubridate)
k <- 2
vec <- seq(ymd_hms("2000-01-01 00:00:00"),
           ymd_hms("2000-01-01 00:00:5"),
           by = 1)

df <- as.data.frame(split(vec, f = as.factor(rep(1:k, each = length(vec)/k))))

Body:
As I mentioned in my comment, you can use the answer in the duplicate repeatedly on each line:

df1 <- split(df,1:nrow(df))
do.call("c",lapply(df1,function(x) do.call("c",x)))

Note that neither the duplicate nor my comment suggests do.call("c",df) on the entire data frame, so it is not surprising that that does not work.


问:
iText certificate verification
I'm following the iText certificate verification example (it's the 3rd example found here: https://itextpdf.com/en/resources/examples/itext-7/digital-signatures-chapter-5).

I don't quite get the following piece of code (I'm using iTextsharp with C#, but code for java is similar):

```<code>PdfPKCS7 pkcs7 = base.VerifySignature(fields, name);
X509Certificate[] certs = pkcs7.SignCertificateChain;
DateTime cal = pkcs7.SignDate;
Object[] errors = CertificateVerification.VerifyCertificates(certs, certificates, null, cal);
</code>```

certificates is the list used to verify certs (certificates are trusted certificates). In the example, it's created from the next files:

```<code>public const String ADOBE = "../../../../resources/adobeRootCA.cer";
public const String CACERT = "../../../../resources/CACertSigningAuthority.crt";
public const String BRUNO = "../../../../resources/bruno.crt";
</code>```

I'm not sure where should I get those files from when trying to implement this myself.

I'm thinking of verifying the signatures certificates against trusted certificates in Windows store, but since I don't get why the example uses those files, I'm not sure if verifying against Windows store would be ok.

答:
As confirmed in a comment, you most of all want to know which certificates to use as trusted certificates.

This depends on your very use case.

For example:

If you want to validate like Adobe Reader, you'll have to trust all the certificates on the Adobe Approved Trust List and the European Union Trust Lists plus (depending on your configuration) certificates from the OS trust store.

If you want to validate personal signatures in India, you most likely will want to trust Aadhaar CA certificates.

In a company internal application you may want to trust the root certificates of that company's PKI.

In example code of one's signature API one may want to trust a self-signed certificate one generated for using in these examples for signing (like bruno.crt above in example code for the iText signing API).

Etc etc etc

Title: iText certificate verification

Body:
I'm following the iText certificate verification example (it's the 3rd example found here: https://itextpdf.com/en/resources/examples/itext-7/digital-signatures-chapter-5).

I don't quite get the following piece of code (I'm using iTextsharp with C#, but code for java is similar):

PdfPKCS7 pkcs7 = base.VerifySignature(fields, name);
X509Certificate[] certs = pkcs7.SignCertificateChain;
DateTime cal = pkcs7.SignDate;
Object[] errors = CertificateVerification.VerifyCertificates(certs, certificates, null, cal);

certificates is the list used to verify certs (certificates are trusted certificates). In the example, it's created from the next files:

public const String ADOBE = "../../../../resources/adobeRootCA.cer";
public const String CACERT = "../../../../resources/CACertSigningAuthority.crt";
public const String BRUNO = "../../../../resources/bruno.crt";

I'm not sure where should I get those files from when trying to implement this myself.

I'm thinking of verifying the signatures certificates against trusted certificates in Windows store, but since I don't get why the example uses those files, I'm not sure if verifying against Windows store would be ok.


问:
use auto increment id with jenssegers mongodb laravel
I need auto generate id sequence.

I am using jenssegers.

I have a UseAutoIncrementID trait from here.

And using it as:

```<code>use App\Traits\UseAutoIncrementID;
....
....
$data['_id'] = $this->getID('request_feeds'); // request_feeds is collection name.
</code>```

I get this error:

```<code>(1/1) FatalThrowableError
Call to undefined method Illuminate\Database\MySqlConnection::getCollection()
</code>```

How can I get auto generated id sequence with jenssegers?

答:
In your model, add these methods :

```<code>    public function nextid()
    {
        // ref is the counter - change it to whatever you want to increment
        $this->ref = self::getID();
    }

    public static function bootUseAutoIncrementID()
    {
        static::creating(function ($model) {
            $model->sequencial_id = self::getID($model->getTable());
        });
    }
    public function getCasts()
    {
        return $this->casts;
    }

    private static function getID()
    {
        $seq = DB::connection('mongodb')->getCollection('counters')->findOneAndUpdate(
            ['ref' => 'ref'],
            ['$inc' => ['seq' => 1]],
            ['new' => true, 'upsert' => true, 'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER]
        );
        return $seq->seq;
    }

</code>```

In your controller, create a new collection and use nextid() method - Example :

```<code>$car = new Car();
$car->nextid(); // auto-increment
$car->name = "Ferrari",
$car->save();
</code>```

Body:
I need auto generate id sequence.

I am using jenssegers.

I have a UseAutoIncrementID trait from here.

And using it as:

use App\Traits\UseAutoIncrementID;
....
....
$data['_id'] = $this->getID('request_feeds'); // request_feeds is collection name.

I get this error:

(1/1) FatalThrowableError
Call to undefined method Illuminate\Database\MySqlConnection::getCollection()

How can I get auto generated id sequence with jenssegers?

Body:
In your model, add these methods :

    public function nextid()
    {
        // ref is the counter - change it to whatever you want to increment
        $this->ref = self::getID();
    }

    public static function bootUseAutoIncrementID()
    {
        static::creating(function ($model) {
            $model->sequencial_id = self::getID($model->getTable());
        });
    }
    public function getCasts()
    {
        return $this->casts;
    }

    private static function getID()
    {
        $seq = DB::connection('mongodb')->getCollection('counters')->findOneAndUpdate(
            ['ref' => 'ref'],
            ['$inc' => ['seq' => 1]],
            ['new' => true, 'upsert' => true, 'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER]
        );
        return $seq->seq;
    }

In your controller, create a new collection and use nextid() method - Example :

$car = new Car();
$car->nextid(); // auto-increment
$car->name = "Ferrari",
$car->save();


问:
How to delete foreign key as well as primary key
I want to use SQL and PHP to delete a specific row, events, and the foreign key eventlocation along with it. I tried to use an inner join function, but this gave me an error. Any ideas?</p>

```<code>DELETE FROM Events, EventLocation JOIN ON EventLocation.EventLocationID = Events.EventLocationID WHERE EventID = '".$_POST["id"]."' AND EventLocationID = '".$_POST["id"]."'
</code>```

答:
use inner join

```<code>DELETE Events, EventLocation FROM Events INNER JOIN EventLocation WHERE Events.EventID=EventLocation.EventID
</code>```

Body:
I want to use SQL and PHP to delete a specific row, events, and the foreign key eventlocation along with it. I tried to use an inner join function, but this gave me an error. Any ideas?

DELETE FROM Events, EventLocation JOIN ON EventLocation.EventLocationID = Events.EventLocationID WHERE EventID = '".$_POST["id"]."' AND EventLocationID = '".$_POST["id"]."'

Body:
use inner join

DELETE Events, EventLocation FROM Events INNER JOIN EventLocation WHERE Events.EventID=EventLocation.EventID


问:
Blocking locks created due to inactive session in last 2 months
How to find the details of blocking locks due to inactive session for last 2 months ? Please help with a PL -sql code</p>

答:
You might be able to find historical blocking information in the Active Workload Repository (AWR).  This query might be helpful:

```<code>--Blocked sessions for the past two months.
select *
from dba_hist_active_sess_history
where blocking_session is not null
    and sample_time > sysdate - interval '2' month
order by sample_time desc;
</code>```

However, AWR is only available in Enterprise Edition, when licensed.  And by default it is only configured to supply information for 8 days.

You can investigate and increase the AWR retention period with the below code.  But keep in mind that storing extra data will use additional space in the SYSAUX tablespace:

```<code>--Find how long AWR retains this information.
select dbid, retention from dba_hist_wr_control;

--If necessary, change the retention period to 62 days (62*24*60).
begin
    dbms_workload_repository.modify_snapshot_settings(retention => 89280);
end;
/
</code>```

Also, this information will only help with troubleshooting some types of locks.  AWR uses sampling, and will only catch things that are waiting on a lock for (on average) more than 10 seconds.  Some locks, like space locks, may fail immediately if the parameter RESUMABLE_TIMEOUT is disabled.

Also, the view DBA_HIST_ACTIVE_SESS_HISTORY does not tell you if the blocking session was active or not.  But this view may be a good starting point for an investigation.

Body:
You might be able to find historical blocking information in the Active Workload Repository (AWR).  This query might be helpful:

--Blocked sessions for the past two months.
select *
from dba_hist_active_sess_history
where blocking_session is not null
    and sample_time > sysdate - interval '2' month
order by sample_time desc;

However, AWR is only available in Enterprise Edition, when licensed.  And by default it is only configured to supply information for 8 days.

You can investigate and increase the AWR retention period with the below code.  But keep in mind that storing extra data will use additional space in the SYSAUX tablespace:

--Find how long AWR retains this information.
select dbid, retention from dba_hist_wr_control;

--If necessary, change the retention period to 62 days (62*24*60).
begin
    dbms_workload_repository.modify_snapshot_settings(retention => 89280);
end;
/

Also, this information will only help with troubleshooting some types of locks.  AWR uses sampling, and will only catch things that are waiting on a lock for (on average) more than 10 seconds.  Some locks, like space locks, may fail immediately if the parameter RESUMABLE_TIMEOUT is disabled.

Also, the view DBA_HIST_ACTIVE_SESS_HISTORY does not tell you if the blocking session was active or not.  But this view may be a good starting point for an investigation.


问:
Refused to display '' in a frame because it set 'X-Frame-Options' to 'sameorigin' with Looker
I'm trying to display a iFrame with Looker SSO, I used looker_sso_tool to generate the Embed URL, and it shows the dashboard I want, however when I try to use the url with a localhost application it shows the error:

Refused to display 'https://xerpabr.looker.com/login' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

I also notice the requested URL from this tool has a Location Response of:

https://xerpabr.looker.com/embed/dashboards/2

While in localhost it is:

https://xerpabr.looker.com/login

I'm using the node_example of sso embed, just changing the return to display the iFrame, like so:

```<code>res.end("<iframe height=400 width=600 src=" + url + "> </iframe> ");
</code>```

How can I solve that?

答:
Could you try generating a URL from the tester tool (with preview turned off) and serving that exact URL from localhost? I suspect the problem may be with something in your script, even though you said you didn't change much.

That error is often a bit of a red herring that means your URL isn't authenticating properly— Looker sets x-frame-option headers on the login page that prevent it from being embedded, so if the generated URL doesn't work to log you in and instead redirects to /login, the error can appear. If you take a generated URL from your script and pass it through the Admin > Embed url verification tool, do you get any hints?

You could also try asking over on discourse.looker.com where there's a wealth of Looker experts!

Body:
I'm trying to display a iFrame with Looker SSO, I used looker_sso_tool to generate the Embed URL, and it shows the dashboard I want, however when I try to use the url with a localhost application it shows the error:

Refused to display 'https://xerpabr.looker.com/login' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

I also notice the requested URL from this tool has a Location Response of:

https://xerpabr.looker.com/embed/dashboards/2

While in localhost it is:

https://xerpabr.looker.com/login

I'm using the node_example of sso embed, just changing the return to display the iFrame, like so:

res.end("  ");

How can I solve that?


问:
How to fix http error 400 with microsoft ASP.NET MVC create command
I'm setting up a first C# ASP.NET MVC application using Microsofts tutorial. https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-2.2&tabs=visual-studio

In the process of this tutorial, it asks to check if the create movies works, but when I attempt to use it, I get an HTTP error 400 - bad request. I believe the data I am entering is accurate, but I can't seem to get anything but a bad request, does anyone know how to fix this.

Model class:

```<code>using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int Id { get; set; }
        public string Title { get; set; }

        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }

        [Column(TypeName = "decimal(18, 2)")]
        public decimal Price { get; set; }
    }
}
</code>```

Razor view:

```<code>@model MvcMovie.Models.Movie

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Movie</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ReleaseDate" class="control-label"></label>
                <input asp-for="ReleaseDate" class="form-control" />
                <span asp-validation-for="ReleaseDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Genre" class="control-label"></label>
                <input asp-for="Genre" class="form-control" />
                <span asp-validation-for="Genre" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
</code>```

Controller action method:

```<code>    public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] Movie movie)
    {
        if (ModelState.IsValid)
        {
            _context.Add(movie);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(movie);
    }
</code>```

The expected output is to add to the database, but but the actual output is bad request.

答:
Do you have httpPost over method of controller and why you not use model?</p>

```<code>[HttpPost]
public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] ....
</code>```

Body:
I'm setting up a first C# ASP.NET MVC application using Microsofts tutorial. https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-2.2&tabs=visual-studio

In the process of this tutorial, it asks to check if the create movies works, but when I attempt to use it, I get an HTTP error 400 - bad request. I believe the data I am entering is accurate, but I can't seem to get anything but a bad request, does anyone know how to fix this.

Model class:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int Id { get; set; }
        public string Title { get; set; }

        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }

        [Column(TypeName = "decimal(18, 2)")]
        public decimal Price { get; set; }
    }
}

Razor view:

@model MvcMovie.Models.Movie

@{
    ViewData["Title"] = "Create";
}

Create

Movie

        <form asp-action="Create">

                <input asp-for="Title" class="form-control" />

                <input asp-for="ReleaseDate" class="form-control" />

                <input asp-for="Genre" class="form-control" />

                <input asp-for="Price" class="form-control" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

    Back to List

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Controller action method:

    public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] Movie movie)
    {
        if (ModelState.IsValid)
        {
            _context.Add(movie);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(movie);
    }

The expected output is to add to the database, but but the actual output is bad request.

Body:
Do you have httpPost over method of controller and why you not use model?

[HttpPost]
public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] ....


问:
Turn Off Visual Studio/VB.Net Lines around each method
In Visual Studio when working in VB.Net, it automatically creates lines/regions around methods etc.

How can this be turned off somewhere in the options?

答:
Using Visual Studio 2017 and above

For C# and Basic

Open  Tools > Options or press Alt + T + O

At the top of the list search for "Show procedure line separators"

select Advanced

In  group  box  Outlining

Uncheck "Show procedure line separators"

OwnerDisplayName: Jon