问:
Stream ffmpeg transcoding result to S3
I want to transcode a large file using FFMPEG and store the result directly on AWS S3. This will be done inside of an AWS Lambda that has limited tmp space so I can't store the transcoding result locally and then upload it to S3 in a second step. I won't have enough tmp space. I therefore want to store the FFMPEG output directly on S3.

I therefore created a S3 pre-signed url that allows 'PUT':

var outputPath = s3Client.GetPreSignedURL(new Amazon.S3.Model.GetPreSignedUrlRequest
{
    BucketName = "my-bucket",
    Expires = DateTime.UtcNow.AddMinutes(5),
    Key = "output.mp3",
    Verb = HttpVerb.PUT,
});
```

<p>I then called ffmpeg with the resulting pre-signed url:</p>

```ffmpeg -i C:\input.wav -y -vn -ar 44100 -ac 2 -ab 192k -f mp3 https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550427237&Signature=%2BE8Wc%2F%2FQYrvGxzc%2FgXnsvauKnac%3D
```

<p>FFMPEG returns an exit code of 1 with the following output:</p>

```ffmpeg version N-93120-ga84af760b8 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 8.2.1 (GCC) 20190212
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt
  libavutil      56. 26.100 / 56. 26.100
  libavcodec     58. 47.100 / 58. 47.100
  libavformat    58. 26.101 / 58. 26.101
  libavdevice    58.  6.101 / 58.  6.101
  libavfilter     7. 48.100 /  7. 48.100
  libswscale      5.  4.100 /  5.  4.100
  libswresample   3.  4.100 /  3.  4.100
  libpostproc    55.  4.100 / 55.  4.100
Guessed Channel Layout for Input Stream #0.0 : stereo
Input #0, wav, from 'C:\input.wav':
  Duration: 00:04:16.72, bitrate: 3072 kb/s
    Stream #0:0: Audio: pcm_s32le ([1][0][0][0] / 0x0001), 48000 Hz, stereo, s32, 3072 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (pcm_s32le (native) -> mp3 (libmp3lame))
Press [q] to stop, [?] for help
Output #0, mp3, to 'https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550427237&Signature=%2BE8Wc%2F%2FQYrvGxzc%2FgXnsvauKnac%3D':
  Metadata:
    TSSE            : Lavf58.26.101
    Stream #0:0: Audio: mp3 (libmp3lame), 44100 Hz, stereo, s32p, 192 kb/s
    Metadata:
      encoder         : Lavc58.47.100 libmp3lame
size=     577kB time=00:00:24.58 bitrate= 192.2kbits/s speed=49.1x
size=    1109kB time=00:00:47.28 bitrate= 192.1kbits/s speed=47.2x
[tls @ 000001d73d786b00] Error in the push function.
av_interleaved_write_frame(): I/O error
Error writing trailer of https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550427237&Signature=%2BE8Wc%2F%2FQYrvGxzc%2FgXnsvauKnac%3D: I/O error
size=    1143kB time=00:00:48.77 bitrate= 192.0kbits/s speed=  47x
video:0kB audio:1144kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
[tls @ 000001d73d786b00] The specified session has been invalidated for some reason.
[tls @ 000001d73d786b00] Error in the pull function.
[https @ 000001d73d784fc0] URL read error:  -5
Conversion failed!
```

<p>As you can see, I have a <code>URL read error</code>. This is a little surprising to me since I want to output to this url and not read it. </p>

<p>Anybody know how I can store directly my FFMPEG output directly to S3 without having to store it locally first?</p>

<p><strong>Edit 1</strong>
I then tried to use the <code>-method PUT</code> parameter and use http instead of https to remove TLS from the equation. Here's the output that I got when running ffmpeg with the <code>-v trace</code> option.</p>

```ffmpeg version N-93120-ga84af760b8 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 8.2.1 (GCC) 20190212
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt
  libavutil      56. 26.100 / 56. 26.100
  libavcodec     58. 47.100 / 58. 47.100
  libavformat    58. 26.101 / 58. 26.101
  libavdevice    58.  6.101 / 58.  6.101
  libavfilter     7. 48.100 /  7. 48.100
  libswscale      5.  4.100 /  5.  4.100
  libswresample   3.  4.100 /  3.  4.100
  libpostproc    55.  4.100 / 55.  4.100
Splitting the commandline.
Reading option '-i' ... matched as input url with argument 'C:\input.wav'.
Reading option '-y' ... matched as option 'y' (overwrite output files) with argument '1'.
Reading option '-vn' ... matched as option 'vn' (disable video) with argument '1'.
Reading option '-ar' ... matched as option 'ar' (set audio sampling rate (in Hz)) with argument '44100'.
Reading option '-ac' ... matched as option 'ac' (set number of audio channels) with argument '2'.
Reading option '-ab' ... matched as option 'ab' (audio bitrate (please use -b:a)) with argument '192k'.
Reading option '-f' ... matched as option 'f' (force format) with argument 'mp3'.
Reading option '-method' ... matched as AVOption 'method' with argument 'PUT'.
Reading option '-v' ... matched as option 'v' (set logging level) with argument 'trace'.
Reading option 'https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D' ... matched as output url.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option y (overwrite output files) with argument 1.
Applying option v (set logging level) with argument trace.
Successfully parsed a group of options.
Parsing a group of options: input url C:\input.wav.
Successfully parsed a group of options.
Opening an input file: C:\input.wav.
[NULL @ 000001fb37abb180] Opening 'C:\input.wav' for reading
[file @ 000001fb37abc180] Setting default whitelist 'file,crypto'
Probing wav score:99 size:2048
[wav @ 000001fb37abb180] Format wav probed with size=2048 and score=99
[wav @ 000001fb37abb180] Before avformat_find_stream_info() pos: 54 bytes read:65590 seeks:1 nb_streams:1
[wav @ 000001fb37abb180] parser not found for codec pcm_s32le, packets or times may be invalid.
    Last message repeated 1 times
[wav @ 000001fb37abb180] All info found
[wav @ 000001fb37abb180] stream 0: start_time: -192153584101141.156 duration: 256.716
[wav @ 000001fb37abb180] format: start_time: -9223372036854.775 duration: 256.716 bitrate=3072 kb/s
[wav @ 000001fb37abb180] After avformat_find_stream_info() pos: 204854 bytes read:294966 seeks:1 frames:50
Guessed Channel Layout for Input Stream #0.0 : stereo
Input #0, wav, from 'C:\input.wav':
  Duration: 00:04:16.72, bitrate: 3072 kb/s
    Stream #0:0, 50, 1/48000: Audio: pcm_s32le ([1][0][0][0] / 0x0001), 48000 Hz, stereo, s32, 3072 kb/s
Successfully opened the file.
Parsing a group of options: output url https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D.
Applying option vn (disable video) with argument 1.
Applying option ar (set audio sampling rate (in Hz)) with argument 44100.
Applying option ac (set number of audio channels) with argument 2.
Applying option ab (audio bitrate (please use -b:a)) with argument 192k.
Applying option f (force format) with argument mp3.
Successfully parsed a group of options.
Opening an output file: https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D.
[http @ 000001fb37b15140] Setting default whitelist 'http,https,tls,rtp,tcp,udp,crypto,httpproxy'
[tcp @ 000001fb37b16c80] Original list of addresses:
[tcp @ 000001fb37b16c80] Address 52.216.8.203 port 80
[tcp @ 000001fb37b16c80] Interleaved list of addresses:
[tcp @ 000001fb37b16c80] Address 52.216.8.203 port 80
[tcp @ 000001fb37b16c80] Starting connection attempt to 52.216.8.203 port 80
[tcp @ 000001fb37b16c80] Successfully connected to 52.216.8.203 port 80
[http @ 000001fb37b15140] request: PUT /output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D HTTP/1.1
Transfer-Encoding: chunked
User-Agent: Lavf/58.26.101
Accept: */*
Connection: close
Host: landr-distribution-reportsdev-mb.s3.amazonaws.com
Icy-MetaData: 1
Successfully opened the file.
Stream mapping:
  Stream #0:0 -> #0:0 (pcm_s32le (native) -> mp3 (libmp3lame))
Press [q] to stop, [?] for help
cur_dts is invalid (this is harmless if it occurs once at the start per stream)
detected 8 logical cores
[graph_0_in_0_0 @ 000001fb37b21080] Setting 'time_base' to value '1/48000'
[graph_0_in_0_0 @ 000001fb37b21080] Setting 'sample_rate' to value '48000'
[graph_0_in_0_0 @ 000001fb37b21080] Setting 'sample_fmt' to value 's32'
[graph_0_in_0_0 @ 000001fb37b21080] Setting 'channel_layout' to value '0x3'
[graph_0_in_0_0 @ 000001fb37b21080] tb:1/48000 samplefmt:s32 samplerate:48000 chlayout:0x3
[format_out_0_0 @ 000001fb37b22cc0] Setting 'sample_fmts' to value 's32p|fltp|s16p'
[format_out_0_0 @ 000001fb37b22cc0] Setting 'sample_rates' to value '44100'
[format_out_0_0 @ 000001fb37b22cc0] Setting 'channel_layouts' to value '0x3'
[format_out_0_0 @ 000001fb37b22cc0] auto-inserting filter 'auto_resampler_0' between the filter 'Parsed_anull_0' and the filter 'format_out_0_0'
[AVFilterGraph @ 000001fb37b0d940] query_formats: 4 queried, 6 merged, 3 already done, 0 delayed
[auto_resampler_0 @ 000001fb37b251c0] picking s32p out of 3 ref:s32
[auto_resampler_0 @ 000001fb37b251c0] [SWR @ 000001fb37b252c0] Using fltp internally between filters
[auto_resampler_0 @ 000001fb37b251c0] ch:2 chl:stereo fmt:s32 r:48000Hz -> ch:2 chl:stereo fmt:s32p r:44100Hz
Output #0, mp3, to 'https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D':
  Metadata:
    TSSE            : Lavf58.26.101
    Stream #0:0, 0, 1/44100: Audio: mp3 (libmp3lame), 44100 Hz, stereo, s32p, delay 1105, 192 kb/s
    Metadata:
      encoder         : Lavc58.47.100 libmp3lame
cur_dts is invalid (this is harmless if it occurs once at the start per stream)
    Last message repeated 6 times
size=     649kB time=00:00:27.66 bitrate= 192.2kbits/s speed=55.3x
size=    1207kB time=00:00:51.48 bitrate= 192.1kbits/s speed=51.5x
av_interleaved_write_frame(): Unknown error
No more output streams to write to, finishing.
[libmp3lame @ 000001fb37b147c0] Trying to remove 47 more samples than there are in the queue
Error writing trailer of https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D: Error number -10054 occurred
size=    1251kB time=00:00:53.39 bitrate= 192.0kbits/s speed=51.5x
video:0kB audio:1252kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
Input file #0 (C:\input.wav):
  Input stream #0:0 (audio): 5014 packets read (20537344 bytes); 5014 frames decoded (2567168 samples);
  Total: 5014 packets (20537344 bytes) demuxed
Output file #0 (https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D):
  Output stream #0:0 (audio): 2047 frames encoded (2358144 samples); 2045 packets muxed (1282089 bytes);
  Total: 2045 packets (1282089 bytes) muxed
5014 frames successfully decoded, 0 decoding errors
[AVIOContext @ 000001fb37b1f440] Statistics: 0 seeks, 2046 writeouts
[http @ 000001fb37b15140] URL read error:  -10054
[AVIOContext @ 000001fb37ac4400] Statistics: 20611126 bytes read, 1 seeks
Conversion failed!
```

So it looks like it is able to connect to my S3 pre-signed url but I still have the Error writing trailer error coupled with a URL read error.

答:
The AWS CLI actually has a feature for doing exactly what @mabead described above.  Since the CLI is not installed in lambda by default, you will need to include it, probably as a layer, but if you have ffmpeg installed already, you obviously know how to do this.

Basically, it looks like this (without ffmpeg options):

```<code>aws s3 cp s3://source-bucket/source.mp4 - | ffmpeg -i - -f matroska - | aws s3 cp - s3://dest-bucket/output.mkv
</code>```

You can include a dash ('-') as either the source or filename in both the CLI and ffmpeg commands.  So this this case, we're saying read from S3 into STDOUT, pipe that to ffmpeg STDIN, write ffmpeg output to STDOUT, pipe that to S3 destination.

I generally only work with Video files, so I don't have a lot of experience with straight audio so you'll have to give it a shot.  One thing I have noticed is that certain container formats don't work for the output side of this.  For example, if I try to write to an mp4 file in S3 I see the following error:

```<code>muxer does not support non seekable output Could not write header for
output file #0 (incorrect codec parameters ?): Invalid argument Error
initializing output stream 0:0 --
</code>```

I think this is probably the same issue as the comment about not being able to update the header with results of the final encode.  You'll have to see what happens with mp3.

Title: Stream ffmpeg transcoding result to S3

Body:
I want to transcode a large file using FFMPEG and store the result directly on AWS S3. This will be done inside of an AWS Lambda that has limited tmp space so I can't store the transcoding result locally and then upload it to S3 in a second step. I won't have enough tmp space. I therefore want to store the FFMPEG output directly on S3.

I therefore created a S3 pre-signed url that allows 'PUT':

var outputPath = s3Client.GetPreSignedURL(new Amazon.S3.Model.GetPreSignedUrlRequest
{
    BucketName = "my-bucket",
    Expires = DateTime.UtcNow.AddMinutes(5),
    Key = "output.mp3",
    Verb = HttpVerb.PUT,
});

I then called ffmpeg with the resulting pre-signed url:

ffmpeg -i C:\input.wav -y -vn -ar 44100 -ac 2 -ab 192k -f mp3 https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550427237&Signature=%2BE8Wc%2F%2FQYrvGxzc%2FgXnsvauKnac%3D

FFMPEG returns an exit code of 1 with the following output:

ffmpeg version N-93120-ga84af760b8 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 8.2.1 (GCC) 20190212
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt
  libavutil      56. 26.100 / 56. 26.100
  libavcodec     58. 47.100 / 58. 47.100
  libavformat    58. 26.101 / 58. 26.101
  libavdevice    58.  6.101 / 58.  6.101
  libavfilter     7. 48.100 /  7. 48.100
  libswscale      5.  4.100 /  5.  4.100
  libswresample   3.  4.100 /  3.  4.100
  libpostproc    55.  4.100 / 55.  4.100
Guessed Channel Layout for Input Stream #0.0 : stereo
Input #0, wav, from 'C:\input.wav':
  Duration: 00:04:16.72, bitrate: 3072 kb/s
    Stream #0:0: Audio: pcm_s32le ([1][0][0][0] / 0x0001), 48000 Hz, stereo, s32, 3072 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (pcm_s32le (native) -> mp3 (libmp3lame))
Press [q] to stop, [?] for help
Output #0, mp3, to 'https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550427237&Signature=%2BE8Wc%2F%2FQYrvGxzc%2FgXnsvauKnac%3D':
  Metadata:
    TSSE            : Lavf58.26.101
    Stream #0:0: Audio: mp3 (libmp3lame), 44100 Hz, stereo, s32p, 192 kb/s
    Metadata:
      encoder         : Lavc58.47.100 libmp3lame
size=     577kB time=00:00:24.58 bitrate= 192.2kbits/s speed=49.1x
size=    1109kB time=00:00:47.28 bitrate= 192.1kbits/s speed=47.2x
[tls @ 000001d73d786b00] Error in the push function.
av_interleaved_write_frame(): I/O error
Error writing trailer of https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550427237&Signature=%2BE8Wc%2F%2FQYrvGxzc%2FgXnsvauKnac%3D: I/O error
size=    1143kB time=00:00:48.77 bitrate= 192.0kbits/s speed=  47x
video:0kB audio:1144kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
[tls @ 000001d73d786b00] The specified session has been invalidated for some reason.
[tls @ 000001d73d786b00] Error in the pull function.
[https @ 000001d73d784fc0] URL read error:  -5
Conversion failed!

As you can see, I have a URL read error. This is a little surprising to me since I want to output to this url and not read it.

Anybody know how I can store directly my FFMPEG output directly to S3 without having to store it locally first?

Edit 1
I then tried to use the -method PUT parameter and use http instead of https to remove TLS from the equation. Here's the output that I got when running ffmpeg with the -v trace option.

ffmpeg version N-93120-ga84af760b8 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 8.2.1 (GCC) 20190212
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt
  libavutil      56. 26.100 / 56. 26.100
  libavcodec     58. 47.100 / 58. 47.100
  libavformat    58. 26.101 / 58. 26.101
  libavdevice    58.  6.101 / 58.  6.101
  libavfilter     7. 48.100 /  7. 48.100
  libswscale      5.  4.100 /  5.  4.100
  libswresample   3.  4.100 /  3.  4.100
  libpostproc    55.  4.100 / 55.  4.100
Splitting the commandline.
Reading option '-i' ... matched as input url with argument 'C:\input.wav'.
Reading option '-y' ... matched as option 'y' (overwrite output files) with argument '1'.
Reading option '-vn' ... matched as option 'vn' (disable video) with argument '1'.
Reading option '-ar' ... matched as option 'ar' (set audio sampling rate (in Hz)) with argument '44100'.
Reading option '-ac' ... matched as option 'ac' (set number of audio channels) with argument '2'.
Reading option '-ab' ... matched as option 'ab' (audio bitrate (please use -b:a)) with argument '192k'.
Reading option '-f' ... matched as option 'f' (force format) with argument 'mp3'.
Reading option '-method' ... matched as AVOption 'method' with argument 'PUT'.
Reading option '-v' ... matched as option 'v' (set logging level) with argument 'trace'.
Reading option 'https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D' ... matched as output url.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option y (overwrite output files) with argument 1.
Applying option v (set logging level) with argument trace.
Successfully parsed a group of options.
Parsing a group of options: input url C:\input.wav.
Successfully parsed a group of options.
Opening an input file: C:\input.wav.
[NULL @ 000001fb37abb180] Opening 'C:\input.wav' for reading
[file @ 000001fb37abc180] Setting default whitelist 'file,crypto'
Probing wav score:99 size:2048
[wav @ 000001fb37abb180] Format wav probed with size=2048 and score=99
[wav @ 000001fb37abb180] Before avformat_find_stream_info() pos: 54 bytes read:65590 seeks:1 nb_streams:1
[wav @ 000001fb37abb180] parser not found for codec pcm_s32le, packets or times may be invalid.
    Last message repeated 1 times
[wav @ 000001fb37abb180] All info found
[wav @ 000001fb37abb180] stream 0: start_time: -192153584101141.156 duration: 256.716
[wav @ 000001fb37abb180] format: start_time: -9223372036854.775 duration: 256.716 bitrate=3072 kb/s
[wav @ 000001fb37abb180] After avformat_find_stream_info() pos: 204854 bytes read:294966 seeks:1 frames:50
Guessed Channel Layout for Input Stream #0.0 : stereo
Input #0, wav, from 'C:\input.wav':
  Duration: 00:04:16.72, bitrate: 3072 kb/s
    Stream #0:0, 50, 1/48000: Audio: pcm_s32le ([1][0][0][0] / 0x0001), 48000 Hz, stereo, s32, 3072 kb/s
Successfully opened the file.
Parsing a group of options: output url https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D.
Applying option vn (disable video) with argument 1.
Applying option ar (set audio sampling rate (in Hz)) with argument 44100.
Applying option ac (set number of audio channels) with argument 2.
Applying option ab (audio bitrate (please use -b:a)) with argument 192k.
Applying option f (force format) with argument mp3.
Successfully parsed a group of options.
Opening an output file: https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D.
[http @ 000001fb37b15140] Setting default whitelist 'http,https,tls,rtp,tcp,udp,crypto,httpproxy'
[tcp @ 000001fb37b16c80] Original list of addresses:
[tcp @ 000001fb37b16c80] Address 52.216.8.203 port 80
[tcp @ 000001fb37b16c80] Interleaved list of addresses:
[tcp @ 000001fb37b16c80] Address 52.216.8.203 port 80
[tcp @ 000001fb37b16c80] Starting connection attempt to 52.216.8.203 port 80
[tcp @ 000001fb37b16c80] Successfully connected to 52.216.8.203 port 80
[http @ 000001fb37b15140] request: PUT /output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D HTTP/1.1
Transfer-Encoding: chunked
User-Agent: Lavf/58.26.101
Accept: */*
Connection: close
Host: landr-distribution-reportsdev-mb.s3.amazonaws.com
Icy-MetaData: 1
Successfully opened the file.
Stream mapping:
  Stream #0:0 -> #0:0 (pcm_s32le (native) -> mp3 (libmp3lame))
Press [q] to stop, [?] for help
cur_dts is invalid (this is harmless if it occurs once at the start per stream)
detected 8 logical cores
[graph_0_in_0_0 @ 000001fb37b21080] Setting 'time_base' to value '1/48000'
[graph_0_in_0_0 @ 000001fb37b21080] Setting 'sample_rate' to value '48000'
[graph_0_in_0_0 @ 000001fb37b21080] Setting 'sample_fmt' to value 's32'
[graph_0_in_0_0 @ 000001fb37b21080] Setting 'channel_layout' to value '0x3'
[graph_0_in_0_0 @ 000001fb37b21080] tb:1/48000 samplefmt:s32 samplerate:48000 chlayout:0x3
[format_out_0_0 @ 000001fb37b22cc0] Setting 'sample_fmts' to value 's32p|fltp|s16p'
[format_out_0_0 @ 000001fb37b22cc0] Setting 'sample_rates' to value '44100'
[format_out_0_0 @ 000001fb37b22cc0] Setting 'channel_layouts' to value '0x3'
[format_out_0_0 @ 000001fb37b22cc0] auto-inserting filter 'auto_resampler_0' between the filter 'Parsed_anull_0' and the filter 'format_out_0_0'
[AVFilterGraph @ 000001fb37b0d940] query_formats: 4 queried, 6 merged, 3 already done, 0 delayed
[auto_resampler_0 @ 000001fb37b251c0] picking s32p out of 3 ref:s32
[auto_resampler_0 @ 000001fb37b251c0] [SWR @ 000001fb37b252c0] Using fltp internally between filters
[auto_resampler_0 @ 000001fb37b251c0] ch:2 chl:stereo fmt:s32 r:48000Hz -> ch:2 chl:stereo fmt:s32p r:44100Hz
Output #0, mp3, to 'https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D':
  Metadata:
    TSSE            : Lavf58.26.101
    Stream #0:0, 0, 1/44100: Audio: mp3 (libmp3lame), 44100 Hz, stereo, s32p, delay 1105, 192 kb/s
    Metadata:
      encoder         : Lavc58.47.100 libmp3lame
cur_dts is invalid (this is harmless if it occurs once at the start per stream)
    Last message repeated 6 times
size=     649kB time=00:00:27.66 bitrate= 192.2kbits/s speed=55.3x
size=    1207kB time=00:00:51.48 bitrate= 192.1kbits/s speed=51.5x
av_interleaved_write_frame(): Unknown error
No more output streams to write to, finishing.
[libmp3lame @ 000001fb37b147c0] Trying to remove 47 more samples than there are in the queue
Error writing trailer of https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D: Error number -10054 occurred
size=    1251kB time=00:00:53.39 bitrate= 192.0kbits/s speed=51.5x
video:0kB audio:1252kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
Input file #0 (C:\input.wav):
  Input stream #0:0 (audio): 5014 packets read (20537344 bytes); 5014 frames decoded (2567168 samples);
  Total: 5014 packets (20537344 bytes) demuxed
Output file #0 (https://my-bucket.s3.amazonaws.com/output.mp3?AWSAccessKeyId=AKIAJDSGJWM63VQEXHIQ&Expires=1550695990&Signature=dy3RVqDlX%2BlJ0INlDkl0Lm1Rqb4%3D):
  Output stream #0:0 (audio): 2047 frames encoded (2358144 samples); 2045 packets muxed (1282089 bytes);
  Total: 2045 packets (1282089 bytes) muxed
5014 frames successfully decoded, 0 decoding errors
[AVIOContext @ 000001fb37b1f440] Statistics: 0 seeks, 2046 writeouts
[http @ 000001fb37b15140] URL read error:  -10054
[AVIOContext @ 000001fb37ac4400] Statistics: 20611126 bytes read, 1 seeks
Conversion failed!

So it looks like it is able to connect to my S3 pre-signed url but I still have the Error writing trailer error coupled with a URL read error.

Body:
The AWS CLI actually has a feature for doing exactly what @mabead described above.  Since the CLI is not installed in lambda by default, you will need to include it, probably as a layer, but if you have ffmpeg installed already, you obviously know how to do this.

Basically, it looks like this (without ffmpeg options):

aws s3 cp s3://source-bucket/source.mp4 - | ffmpeg -i - -f matroska - | aws s3 cp - s3://dest-bucket/output.mkv

You can include a dash ('-') as either the source or filename in both the CLI and ffmpeg commands.  So this this case, we're saying read from S3 into STDOUT, pipe that to ffmpeg STDIN, write ffmpeg output to STDOUT, pipe that to S3 destination.

I generally only work with Video files, so I don't have a lot of experience with straight audio so you'll have to give it a shot.  One thing I have noticed is that certain container formats don't work for the output side of this.  For example, if I try to write to an mp4 file in S3 I see the following error:

muxer does not support non seekable output Could not write header for
output file #0 (incorrect codec parameters ?): Invalid argument Error
initializing output stream 0:0 --

I think this is probably the same issue as the comment about not being able to update the header with results of the final encode.  You'll have to see what happens with mp3.


来源: stackexchange

问:
Split text input to few cells using CSS
I need to split input to few cells. I want to draw few blocks and in each user press, one of the blocks will fill. Something like this:

What is the right way to do it?

This is the code of the form:

```<code>  <div class="wrap-log-in-form" *ngIf="step == 'pass'">

  <input type="text" class="spliting-input"  maxlength="6">

  <div class="buttens-log-in">
      <input type="button" value="אמת">
      <input type="button" value="קבל הודעה בטלפון">
  </div>
</div>
</code>```

答:
You can use a CSS background image on the input and try to use letter-spacing to get the text to fall in the correct areas, BUT this is really hard and not a great solution.

The issue is each device and browser displays characters slightly differently so the spacing is always off just a bit. This is pretty hacky but works if you only have access to the CSS.

A better solution

Use Javascript to parse the input and split each character into its own element with unique placement and background styling.

ContentLicense: CC BY-SA 4.0

Title: Split text input to few cells using CSS

Body:
I need to split input to few cells. I want to draw few blocks and in each user press, one of the blocks will fill. Something like this:

What is the right way to do it?

This is the code of the form:

  <input type="text" class="spliting-input"  maxlength="6">

      <input type="button" value="אמת">
      <input type="button" value="קבל הודעה בטלפון">


问:
Is there any way to create a video stream from image buffers(without saving to disk)using ffmpeg?
Can you "stream" images to ffmpeg to construct a video, instead of saving them to disk?
I want something similar but in node js</p>

答: The equivalent for nodejs would be child_process https://nodejs.org/api/child_process.html . The spawn call returns an object that has a stdin property (e.g. process.stdin), essentially the same as the answer you linked. </p>


问:
I have this error: Ambiguous use of 'locationManager'
I'm trying to make a Geofence in Swift 4, but I have a problem, I have an error when calling locationManager, I do not understand why I get this error

this is the error:

Ambiguous use of locationManager

I tried to correct it by placing self.locationManager.startUpdatingLocation () and other different methods but none worked

Here I declare my variable locationManager:

```<code>var locationManager = CLLocationManager()

    if let appDelegate = UIApplication.shared.delegate as? AppDelegate{
      locationManager = appDelegate.locationManager
      locationManager.delegate = self
    }
</code>```

This is the code block where I get an error:

```<code>if let locationManager = self.locationManager{
        let region = self.regionToMonitor()
        if(locationManager.monitoredRegions.count > 0){
            self.geofencesLabel.text = "Geofences OFF"
            locationManager.stopMonitoring(for: region)
            mapView.removeOverlays(mapView.overlays)
        }else{
            self.geofencesLabel.text = "Geofences ON"
            locationManager.startMonitoring(for: region)
            mapView.add(MKCircle(center: region.center, radius: region.radius))

            nombreU.isHidden = true
            empresaU.isHidden = true
            correoElectronicoU.isHidden = true
            telefonoU.isHidden = true

            //Generamos el registro en la base de datos local en el servidor
            let nombreEvento = self.nombreE
            let nombreOficial = self.nombreO
            let fechaEvento = self.fechaE
            let fechaFormato = self.fechaF
            let lugarEvento = self.lugarE
            let descripcionEvento = self.descripcionE
            let imagenEvento = self.imagenE
            let latitudEvento = self.latitudE
            let longitudEvento = self.longitudE
            let empresaEvento = self.empresaE
            let rolEvento = self.rolE

            //Recuperamos el contenido de las cajas de texto para validarlo
            let nombreC = self.nombreU.text!
            let empresaC = self.empresaU.text!
            let correoC = self.correoElectronicoU.text!
            let telefonoC = self.telefonoU.text!

            //Validamos que no este vacio ninguna de los datos recibidos del servidor y ninguna de las cajas de texto

            if(nombreC.isEmpty || empresaC.isEmpty || correoC.isEmpty || telefonoC.isEmpty){
                displayMyAlertMessage(userMessage: "Todos los campos deben ser llenados")
                return
            }

            if(nombreEvento.isEmpty || nombreOficial.isEmpty || fechaEvento.isEmpty || fechaFormato.isEmpty || lugarEvento.isEmpty || descripcionEvento.isEmpty){
                displayMyAlertMessage(userMessage: "Ocurrio un error al cargar los eventos")
                dismiss(animated: true, completion: nil)
                return
            }

            //Ingresamos los valores a la base de datos local
            let newEvento = NSEntityDescription.insertNewObject(forEntityName: "Eventos", into: context)
            newEvento.setValue(nombreEvento, forKey: "nombreE")
            newEvento.setValue(nombreOficial, forKey: "nombreO")
            newEvento.setValue(fechaEvento, forKey: "fechaE")
            newEvento.setValue(fechaFormato, forKey: "fechaF")
            newEvento.setValue(lugarEvento, forKey: "lugarE")
            newEvento.setValue(descripcionEvento, forKey: "descripcionE")
            newEvento.setValue(imagenEvento, forKey: "imagenE")
            newEvento.setValue(latitudEvento, forKey: "latitudE")
            newEvento.setValue(longitudEvento, forKey: "longitudE")
            newEvento.setValue(empresaEvento, forKey: "empresaE")
            newEvento.setValue(rolEvento, forKey: "rolE")

            nombreU.isHidden = true
            empresaU.isHidden = true
            correoElectronicoU.isHidden = true
            telefonoU.isHidden = true

            //Mostramos mensaje de que ya estas registrado
            mensajeRegistro.text = "Gracias por registrarte a nuestro evento"
            mensajeRegistro.isHidden = false

            do{
                try context.save()
                print("El registro al evento se realizo de forma correcta")
            }catch{
                print(error)
            }

            //Ejecutamos el codigo del WebService
            guard let url = URL(string: "http://www.sitioweb.mx/webservice/registro.php?nombre=\(nom)&empresa=\(empresaC)&correo=\(corC)&telefono=\(telC)") else { return }

            let session = URLSession.shared
            session.dataTask(with: url) { (data, response, error) in
                if let response = response {
                    print(response)
                }else{
                    print(error!)
                }
            }
        }

    }else{
        notify(msg: "El geofence no esta disponible")
    }
</code>```

My class has this extension:

```<code>// MARK: - Location Manager Delegate
extension RegistroViewController: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        mapView.showsUserLocation = status == .authorizedAlways
    }

    func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
        print("Monitoring failed for region with identifier: \(region!.identifier)")
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Location Manager failed with the following error: \(error)")
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("Location update")
    }

}
</code>```

I do not understand what is wrong or what method I should refer to when calling self.locationManager

This is my Appdelegate:

```<code>import UIKit
import CoreData
import CoreLocation
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    static var menu_bool = true
    static var menu_boolS = true

    let locationManager = CLLocationManager()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        locationManager.delegate = self as? CLLocationManagerDelegate
        locationManager.requestAlwaysAuthorization()
        let options: UNAuthorizationOptions = [.badge, .sound, .alert]
        UNUserNotificationCenter.current().requestAuthorization(options: options){ success, error in
            if let error = error{
                print("Error: \(error)")
            }
        }
        return true
    }
</code>```

答:
If locationManager is an instance property use it directly

```<code>let locationManager = CLLocationManager()
</code>```

```<code>    let region = self.regionToMonitor()
    if(locationManager.monitoredRegions.count > 0){
        self.geofencesLabel.text = "Geofences OFF"
        locationManager.stopMonitoring(for: region)
        mapView.removeOverlays(mapView.overlays)
    }else{
        self.geofencesLabel.text = "Geofences ON"
        locationManager.startMonitoring(for: region)
        mapView.add(MKCircle(center: region.center, radius: region.radius))
</code>```

Without

```<code>if let locationManager = self.locationManager{
</code>```

Body:
I'm trying to make a Geofence in Swift 4, but I have a problem, I have an error when calling locationManager, I do not understand why I get this error

this is the error:

Ambiguous use of locationManager

I tried to correct it by placing self.locationManager.startUpdatingLocation () and other different methods but none worked

Here I declare my variable locationManager:

var locationManager = CLLocationManager()

    if let appDelegate = UIApplication.shared.delegate as? AppDelegate{
      locationManager = appDelegate.locationManager
      locationManager.delegate = self
    }

This is the code block where I get an error:

if let locationManager = self.locationManager{
        let region = self.regionToMonitor()
        if(locationManager.monitoredRegions.count > 0){
            self.geofencesLabel.text = "Geofences OFF"
            locationManager.stopMonitoring(for: region)
            mapView.removeOverlays(mapView.overlays)
        }else{
            self.geofencesLabel.text = "Geofences ON"
            locationManager.startMonitoring(for: region)
            mapView.add(MKCircle(center: region.center, radius: region.radius))

            nombreU.isHidden = true
            empresaU.isHidden = true
            correoElectronicoU.isHidden = true
            telefonoU.isHidden = true

            //Generamos el registro en la base de datos local en el servidor
            let nombreEvento = self.nombreE
            let nombreOficial = self.nombreO
            let fechaEvento = self.fechaE
            let fechaFormato = self.fechaF
            let lugarEvento = self.lugarE
            let descripcionEvento = self.descripcionE
            let imagenEvento = self.imagenE
            let latitudEvento = self.latitudE
            let longitudEvento = self.longitudE
            let empresaEvento = self.empresaE
            let rolEvento = self.rolE

            //Recuperamos el contenido de las cajas de texto para validarlo
            let nombreC = self.nombreU.text!
            let empresaC = self.empresaU.text!
            let correoC = self.correoElectronicoU.text!
            let telefonoC = self.telefonoU.text!

            //Validamos que no este vacio ninguna de los datos recibidos del servidor y ninguna de las cajas de texto

            if(nombreC.isEmpty || empresaC.isEmpty || correoC.isEmpty || telefonoC.isEmpty){
                displayMyAlertMessage(userMessage: "Todos los campos deben ser llenados")
                return
            }

            if(nombreEvento.isEmpty || nombreOficial.isEmpty || fechaEvento.isEmpty || fechaFormato.isEmpty || lugarEvento.isEmpty || descripcionEvento.isEmpty){
                displayMyAlertMessage(userMessage: "Ocurrio un error al cargar los eventos")
                dismiss(animated: true, completion: nil)
                return
            }

            //Ingresamos los valores a la base de datos local
            let newEvento = NSEntityDescription.insertNewObject(forEntityName: "Eventos", into: context)
            newEvento.setValue(nombreEvento, forKey: "nombreE")
            newEvento.setValue(nombreOficial, forKey: "nombreO")
            newEvento.setValue(fechaEvento, forKey: "fechaE")
            newEvento.setValue(fechaFormato, forKey: "fechaF")
            newEvento.setValue(lugarEvento, forKey: "lugarE")
            newEvento.setValue(descripcionEvento, forKey: "descripcionE")
            newEvento.setValue(imagenEvento, forKey: "imagenE")
            newEvento.setValue(latitudEvento, forKey: "latitudE")
            newEvento.setValue(longitudEvento, forKey: "longitudE")
            newEvento.setValue(empresaEvento, forKey: "empresaE")
            newEvento.setValue(rolEvento, forKey: "rolE")

            nombreU.isHidden = true
            empresaU.isHidden = true
            correoElectronicoU.isHidden = true
            telefonoU.isHidden = true

            //Mostramos mensaje de que ya estas registrado
            mensajeRegistro.text = "Gracias por registrarte a nuestro evento"
            mensajeRegistro.isHidden = false

            do{
                try context.save()
                print("El registro al evento se realizo de forma correcta")
            }catch{
                print(error)
            }

            //Ejecutamos el codigo del WebService
            guard let url = URL(string: "http://www.sitioweb.mx/webservice/registro.php?nombre=\(nom)&empresa=\(empresaC)&correo=\(corC)&telefono=\(telC)") else { return }

            let session = URLSession.shared
            session.dataTask(with: url) { (data, response, error) in
                if let response = response {
                    print(response)
                }else{
                    print(error!)
                }
            }
        }

    }else{
        notify(msg: "El geofence no esta disponible")
    }

My class has this extension:

// MARK: - Location Manager Delegate
extension RegistroViewController: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        mapView.showsUserLocation = status == .authorizedAlways
    }

    func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
        print("Monitoring failed for region with identifier: \(region!.identifier)")
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Location Manager failed with the following error: \(error)")
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("Location update")
    }

}

I do not understand what is wrong or what method I should refer to when calling self.locationManager

This is my Appdelegate:

import UIKit
import CoreData
import CoreLocation
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    static var menu_bool = true
    static var menu_boolS = true

    let locationManager = CLLocationManager()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        locationManager.delegate = self as? CLLocationManagerDelegate
        locationManager.requestAlwaysAuthorization()
        let options: UNAuthorizationOptions = [.badge, .sound, .alert]
        UNUserNotificationCenter.current().requestAuthorization(options: options){ success, error in
            if let error = error{
                print("Error: \(error)")
            }
        }
        return true
    }

Body:
If locationManager is an instance property use it directly

let locationManager = CLLocationManager()

    let region = self.regionToMonitor()
    if(locationManager.monitoredRegions.count > 0){
        self.geofencesLabel.text = "Geofences OFF"
        locationManager.stopMonitoring(for: region)
        mapView.removeOverlays(mapView.overlays)
    }else{
        self.geofencesLabel.text = "Geofences ON"
        locationManager.startMonitoring(for: region)
        mapView.add(MKCircle(center: region.center, radius: region.radius))

Without

if let locationManager = self.locationManager{


问:
AWS Lambda get data from external public API (basic)
I am trying to write a simple AWS Lambda function to retrieve data from an external public API. I have copied and pasted code from all over the internet without any luck.

I have stripped down the code to be a simple as possible to keep it simple. The public API is : https://swapi.co/api/people/1/

How can I get the data back from the public API?

```<code>const https = require('https');

exports.handler = async (event) => {

    var options = {
      method: 'GET',
      host: 'https://swapi.co/api/people/1/',

    };

     console.log('options', options);

     const req = https.request(options, (res) => {
         console.log('statusCode: ${res.statusCode}')
         console.log(JSON.stringify(res))
     });

    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};
</code>```

The log file within the AWS editor shows:

```<code>START RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728 Version: $LATEST
2019-05-27T16:17:44.839Z    3ba3f23a-11c2-40af-b9e7-0258a6531728    INFO    options { method: 'GET', host: 'https://swapi.co/api/people/1/' }
END RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728
REPORT RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728  Duration: 305.90 ms Billed Duration: 400 ms     Memory Size: 128 MB Max Memory Used: 26 MB
</code>```

答:
There were a few issues with your code:

The callback function passed into the handler triggers the end of the execution, or is called for you when your code exits if you don't call it yourself. I'm not entirely sure how this interacts with asynchronous javascript code, but it might have been causing your code to exit early that you didn't call it anywhere.

You're using an async method, which is good practice, but your rest call isn't using it, but a callback approach. This can be converted into an async call, as I show below, which makes the code a bit easier to understand.

I think the biggest problem, though, is that your options are wrong. You don't need https at the start of the host (because it already knows the scheme) and the path can't be in the host. I didn't spot this initially.

This is working for me, although you can't call JSON.stringify on the entire response, because it's a complex object, not just a model.

```<code>const https = require('https');

exports.handler = async (event, context, callback) => {
    var options = {
        method: 'GET',
        host: 'swapi.co',
        path: '/api/people/1/',
    };
    await new Promise((resolve, reject) => {
        let request = https.request(options, response => {
            try {
                // do whatever
            } finally {
                resolve();
            }
        });
        request.on('error', (e) => reject(e));
        request.end();
    });
    callback();
};
</code>```

Body:
I am trying to write a simple AWS Lambda function to retrieve data from an external public API. I have copied and pasted code from all over the internet without any luck.

I have stripped down the code to be a simple as possible to keep it simple. The public API is : https://swapi.co/api/people/1/

How can I get the data back from the public API?

const https = require('https');

exports.handler = async (event) => {

    var options = {
      method: 'GET',
      host: 'https://swapi.co/api/people/1/',

    };

     console.log('options', options);

     const req = https.request(options, (res) => {
         console.log('statusCode: ${res.statusCode}')
         console.log(JSON.stringify(res))
     });

    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

The log file within the AWS editor shows:

START RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728 Version: $LATEST
2019-05-27T16:17:44.839Z    3ba3f23a-11c2-40af-b9e7-0258a6531728    INFO    options { method: 'GET', host: 'https://swapi.co/api/people/1/' }
END RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728
REPORT RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728  Duration: 305.90 ms Billed Duration: 400 ms     Memory Size: 128 MB Max Memory Used: 26 MB

Body:
There were a few issues with your code:

The callback function passed into the handler triggers the end of the execution, or is called for you when your code exits if you don't call it yourself. I'm not entirely sure how this interacts with asynchronous javascript code, but it might have been causing your code to exit early that you didn't call it anywhere.

You're using an async method, which is good practice, but your rest call isn't using it, but a callback approach. This can be converted into an async call, as I show below, which makes the code a bit easier to understand.

I think the biggest problem, though, is that your options are wrong. You don't need https at the start of the host (because it already knows the scheme) and the path can't be in the host. I didn't spot this initially.

This is working for me, although you can't call JSON.stringify on the entire response, because it's a complex object, not just a model.

const https = require('https');

exports.handler = async (event, context, callback) => {
    var options = {
        method: 'GET',
        host: 'swapi.co',
        path: '/api/people/1/',
    };
    await new Promise((resolve, reject) => {
        let request = https.request(options, response => {
            try {
                // do whatever
            } finally {
                resolve();
            }
        });
        request.on('error', (e) => reject(e));
        request.end();
    });
    callback();
};


问:
Future-proofing Mobile Applications
We're working on the next version of a tracking system. The previous incarnation used an LCD with a simple custom UI however as we've had usability problems and we've found development time-consuming, and as our display is going out of production, we're considering using a regular cellphone or PDA as the interface instead.

Our main worry is whether we can keep such a product on the market for five to ten years without having to continually keep porting and adapting the application to new devices. To make things somewhat easier we intend to bundle the phones with the system, though in an ideal world our (largely non-technical) users would be able to use their own.

So, what's our best bet? Are there a good platform-independent libraries we can count on being supported for a while? Or are we better of betting on a single platform at a time? Perhaps backward-compatibility is more likely to be maintained on a PDA? Truth be told I'm not even sure what language to bet on for the generic parts of the code.

I'm also a little anxious about the link to our hardware. Bluetooth SPP is attractive since it's particularly easy to use and there are plenty of ready-made modules available, but support on the phone side is far from universal.

Any pragmatic advice would be most welcome as I must admit to having no experience with mobile application development.

答: Cross platform sounds like HTML 5, CSS and Javascript, along with some javascript frameworks for mobile development like the ones listed here</p>

ContentLicense: CC BY-SA 3.0

Title: Future-proofing Mobile Applications


问:
How to extract string from a long string
I'm struggling to extract strings from a long string which is a row of a csv file with python or R. The long string is  </p>

```<code>"Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"
</code>```

<p>And the results should be  </p>

```<code>"Zhao, Sihai" "Cai, T. Tony" "Li, Hongzhe"
</code>```

答:
In R you can do</p>

```<code>a <- "Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"

sub('(^.+)@.*$', '\\1', unlist(strsplit(a, '::')))
#[1] "Zhao, Sihai"  "Cai, T. Tony" "Li, Hongzhe"
</code>```

Body:
I'm struggling to extract strings from a long string which is a row of a csv file with python or R. The long string is

"Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"

And the results should be

"Zhao, Sihai" "Cai, T. Tony" "Li, Hongzhe"

Body:
In R you can do

a <- "Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"

sub('(^.+)@.*$', '\\1', unlist(strsplit(a, '::')))
#[1] "Zhao, Sihai"  "Cai, T. Tony" "Li, Hongzhe"


问:
Index not getting created using stored procedure - Oracle
I have this stored procedure to create index on table:

```<code>CREATE OR REPLACE PROCEDURE create_index (
    in_tb        VARCHAR2,
    in_index     VARCHAR2,
    in_columns   VARCHAR2,
    lc_status    OUT          NUMBER
) AS
    lc_affected   NUMBER;
    lc_stmt       VARCHAR2(1500);
BEGIN
    lc_stmt := 'BEGIN EXECUTE IMMEDIATE ''CREATE INDEX '
               || in_index
               || ' ON '
               || in_tb
               || ' ('
               || in_columns
               || ')''; END;';

    dbms_output.put_line(lc_stmt);
    dbms_utility.exec_ddl_statement(lc_stmt);
    lc_affected := SQL%rowcount;
    dbms_output.put_line('AFFECTED -->' || lc_affected);
    IF ( lc_affected > 0 ) THEN
        lc_status := 1;
    ELSE
        lc_status := 1;
    END IF;

END create_index;
/
</code>```

I execute the stored procedure using:

```<code>SET SERVEROUTPUT ON;
DECLARE
    lc_status   NUMBER;
BEGIN
    create_index('TABLE_1_LOAD', 'ON_RUN_INDEX', 'MY_ID', lc_status);
END;
</code>```

However, the index is not getting created in table TABLE_1_LOAD.

The output is:

```<code>BEGIN EXECUTE IMMEDIATE 'CREATE INDEX ON_RUN_INDEX ON TABLE_1_LOAD (MY_ID)'; END;
AFFECTED -->

PL/SQL procedure successfully completed.
</code>```

I am not able to understand why the stored procedure is not creating indexes. Can you please help?

答:
The dynamic statement you are trying to run via exec_ddl_statement is not DDL. It contains DDL, but embedded in an anonymous PL/SQL block, which is not the same thing. It looks like the dbms_utility procedure is just silently ignoring it for that reason.

If you simplify your statement to remove the unnecessary block then it will work:

```<code>...
BEGIN
    lc_stmt := 'CREATE INDEX '
               || in_index
               || ' ON '
               || in_tb
               || ' ('
               || in_columns
               || ')';

...
</code>```

Demo:

```<code>create table table_1_load (my_id number);

Table TABLE_1_LOAD created.
</code>```

```<code>CREATE OR REPLACE PROCEDURE create_index (
    in_tb        VARCHAR2,
    in_index     VARCHAR2,
    in_columns   VARCHAR2,
    lc_status    OUT          NUMBER
) AS
    lc_affected   NUMBER;
    lc_stmt       VARCHAR2(1500);
BEGIN
    lc_stmt := 'CREATE INDEX '
               || in_index
               || ' ON '
               || in_tb
               || ' ('
               || in_columns
               || ')';

    dbms_output.put_line(lc_stmt);
    dbms_utility.exec_ddl_statement(lc_stmt);
    lc_affected := SQL%rowcount;
    dbms_output.put_line('AFFECTED -->' || lc_affected);
    IF ( lc_affected > 0 ) THEN
        lc_status := 1;
    ELSE
        lc_status := 1;
    END IF;

END create_index;
/

Procedure CREATE_INDEX compiled
</code>```

```<code>SET SERVEROUTPUT ON;
DECLARE
    lc_status   NUMBER;
BEGIN
    create_index('TABLE_1_LOAD', 'ON_RUN_INDEX', 'MY_ID', lc_status);
END;
/

CREATE INDEX ON_RUN_INDEX ON TABLE_1_LOAD (MY_ID)
AFFECTED -->

PL/SQL procedure successfully completed.
</code>```

The 'affected' number is still null, because execute_ddl_statement doesn't cause SQL%rowcount to be set, so you can't rely on that to tell you anything. But the index has been created:

```<code>select object_type, object_name from user_objects where created > trunc(sysdate);

OBJECT_TYPE         OBJECT_NAME
------------------- ------------------------------
TABLE               TABLE_1_LOAD
PROCEDURE           CREATE_INDEX
INDEX               ON_RUN_INDEX
</code>```

You could run your original statement with execute immediate, and that would actually set SQL%rowcount, but as you still haven't run any DML it's meaningless really. To show that, with the (still unnecessary) anonymous block you get 1; without the block, using the same simplified statement as above, you get 0.

Body:
I have this stored procedure to create index on table:

CREATE OR REPLACE PROCEDURE create_index (
    in_tb        VARCHAR2,
    in_index     VARCHAR2,
    in_columns   VARCHAR2,
    lc_status    OUT          NUMBER
) AS
    lc_affected   NUMBER;
    lc_stmt       VARCHAR2(1500);
BEGIN
    lc_stmt := 'BEGIN EXECUTE IMMEDIATE ''CREATE INDEX '
               || in_index
               || ' ON '
               || in_tb
               || ' ('
               || in_columns
               || ')''; END;';

    dbms_output.put_line(lc_stmt);
    dbms_utility.exec_ddl_statement(lc_stmt);
    lc_affected := SQL%rowcount;
    dbms_output.put_line('AFFECTED -->' || lc_affected);
    IF ( lc_affected > 0 ) THEN
        lc_status := 1;
    ELSE
        lc_status := 1;
    END IF;

END create_index;
/

I execute the stored procedure using:

SET SERVEROUTPUT ON;
DECLARE
    lc_status   NUMBER;
BEGIN
    create_index('TABLE_1_LOAD', 'ON_RUN_INDEX', 'MY_ID', lc_status);
END;

However, the index is not getting created in table TABLE_1_LOAD.

The output is:

BEGIN EXECUTE IMMEDIATE 'CREATE INDEX ON_RUN_INDEX ON TABLE_1_LOAD (MY_ID)'; END;
AFFECTED -->

PL/SQL procedure successfully completed.

I am not able to understand why the stored procedure is not creating indexes. Can you please help?

Body:
The dynamic statement you are trying to run via exec_ddl_statement is not DDL. It contains DDL, but embedded in an anonymous PL/SQL block, which is not the same thing. It looks like the dbms_utility procedure is just silently ignoring it for that reason.

If you simplify your statement to remove the unnecessary block then it will work:

...
BEGIN
    lc_stmt := 'CREATE INDEX '
               || in_index
               || ' ON '
               || in_tb
               || ' ('
               || in_columns
               || ')';

...

Demo:

create table table_1_load (my_id number);

Table TABLE_1_LOAD created.

CREATE OR REPLACE PROCEDURE create_index (
    in_tb        VARCHAR2,
    in_index     VARCHAR2,
    in_columns   VARCHAR2,
    lc_status    OUT          NUMBER
) AS
    lc_affected   NUMBER;
    lc_stmt       VARCHAR2(1500);
BEGIN
    lc_stmt := 'CREATE INDEX '
               || in_index
               || ' ON '
               || in_tb
               || ' ('
               || in_columns
               || ')';

    dbms_output.put_line(lc_stmt);
    dbms_utility.exec_ddl_statement(lc_stmt);
    lc_affected := SQL%rowcount;
    dbms_output.put_line('AFFECTED -->' || lc_affected);
    IF ( lc_affected > 0 ) THEN
        lc_status := 1;
    ELSE
        lc_status := 1;
    END IF;

END create_index;
/

Procedure CREATE_INDEX compiled

SET SERVEROUTPUT ON;
DECLARE
    lc_status   NUMBER;
BEGIN
    create_index('TABLE_1_LOAD', 'ON_RUN_INDEX', 'MY_ID', lc_status);
END;
/

CREATE INDEX ON_RUN_INDEX ON TABLE_1_LOAD (MY_ID)
AFFECTED -->

PL/SQL procedure successfully completed.

The 'affected' number is still null, because execute_ddl_statement doesn't cause SQL%rowcount to be set, so you can't rely on that to tell you anything. But the index has been created:

select object_type, object_name from user_objects where created > trunc(sysdate);

OBJECT_TYPE         OBJECT_NAME
------------------- ------------------------------
TABLE               TABLE_1_LOAD
PROCEDURE           CREATE_INDEX
INDEX               ON_RUN_INDEX

You could run your original statement with execute immediate, and that would actually set SQL%rowcount, but as you still haven't run any DML it's meaningless really. To show that, with the (still unnecessary) anonymous block you get 1; without the block, using the same simplified statement as above, you get 0.


问:
Can't assign value with ternary operator
I need to assign a value to a var depending on the value obtained from another var, but it gives me undefined.

I need to give discount depending on the days in advance that you made a reservation
e.g.

```<code><input type="date" id="arriveDate">
<input type="submit" value="submit">
</code>```

The case is that i need to calculate the days between today and arriveDate. There's no problem with that (but any comment will be welcomed)

in js i do it this way

```<code>var today = Date.now();
var arriveDateInserted = new Date(document.getElementById("arriveDate").value);

var diffDays = Math.round(((arriveDateInserted - today)/86400000)+1);
</code>```

Now, i need to give some discount depending on how many days in advance is the reservation made.
I tried with ternary operator, like this.

```<code>var discount = diffDays < 61 ? 0:
    diffDays > 60 && diffDays < 91 ? 0.10:
    diffDays > 90 && diffDays < 121 ? 0.15;
</code>```

But i don't even have an alert(discount)

Any help will be VERY appreciated :)

答:
Check your console, you're probably getting a syntax error like:

Uncaught SyntaxError: Unexpected token ;

You're missing the else in the later condition:

```<code>diffDays > 90 && diffDays < 121 ? 0.15 /* Here should be a : and an else condition
</code>```

Example:

```<code>var discount = diffDays < 61 ? 0 :
    diffDays > 60 && diffDays < 91 ? 0.10 :
    diffDays > 90 && diffDays < 121 ? 0.15 : 0.20;
</code>```

I would advise to avoid using nested ternary conditions for better reading:

```<code>let discount = 0;
if (diffDays > 60 && diffDays < 91) {
    discount = 0.10;
} else if (diffDays > 90) {
    discount = 0.15;
}
</code>```

Body:
I need to assign a value to a var depending on the value obtained from another var, but it gives me undefined.

I need to give discount depending on the days in advance that you made a reservation
e.g.

<input type="date" id="arriveDate">
<input type="submit" value="submit">

The case is that i need to calculate the days between today and arriveDate. There's no problem with that (but any comment will be welcomed)

in js i do it this way

var today = Date.now();
var arriveDateInserted = new Date(document.getElementById("arriveDate").value);

var diffDays = Math.round(((arriveDateInserted - today)/86400000)+1);

Now, i need to give some discount depending on how many days in advance is the reservation made.
I tried with ternary operator, like this.

var discount = diffDays < 61 ? 0:
    diffDays > 60 && diffDays < 91 ? 0.10:
    diffDays > 90 && diffDays < 121 ? 0.15;

But i don't even have an alert(discount)

Any help will be VERY appreciated :)

Body:
Check your console, you're probably getting a syntax error like:

Uncaught SyntaxError: Unexpected token ;

You're missing the else in the later condition:

diffDays > 90 && diffDays < 121 ? 0.15 /* Here should be a : and an else condition

Example:

var discount = diffDays < 61 ? 0 :
    diffDays > 60 && diffDays < 91 ? 0.10 :
    diffDays > 90 && diffDays < 121 ? 0.15 : 0.20;

I would advise to avoid using nested ternary conditions for better reading:

let discount = 0;
if (diffDays > 60 && diffDays < 91) {
    discount = 0.10;
} else if (diffDays > 90) {
    discount = 0.15;
}


问:
Using dataframe values to query SQL database and appending back into dataframe
I have a dataframe that I can draw values from to write a query for a sql database and want to append the queried information on that dataframe. The original dataframe would be something like:

df =

```<code>ID YEAR CODE
43 2013 051
97 2015 087
...
</code>```

and my current code being:

```<code>import pypyodbc as podbc

db = podbc.connect('Driver={SQL Server};Server=server;Database=database')

for row in df:
    cursor = db.cursor()
    query = '''
    SELECT ID, Tool, Date, Version
    FROM table
    WHERE ID = '{id}'
    AND Year(Date) = '{year}'
    AND Code = '{code}'
    '''.format(id = df.ID, year = df.YEAR, code = df.CODE)

    cursor.execute(query)
    rows = cursor.fetchall()
    pd.DataFrame(rows, columns=[x[0] for x in cursor.description)

</code>```

The returned value from a single query is like:

```<code>    ID   Tool   Date         Version
0   43   C15    22-05-2013   1.0
</code>```

So my issues right now are

```<code>1. I don't know how to create an iterable query (for row in df)
2. I don't know how to relate the new dataframe that the query creates to the original df
</code>```

Hopefully the result would be something like:

```<code>ID YEAR CODE Tool Date        Version
43 2013 051  C15  22-05-2013  1.0
97 2015 087  C67  31-01-2015  2.0
</code>```

答:
As you already using pandas,

Try this,

```<code>conn = podbc.connect('Driver={SQL Server};Server=server;Database=database')

query = ''' SELECT ID, Tool, Date, Version
            FROM table
            WHERE ID = '{id}' AND
            Year(Date) = '{year}' AND
            Code = '{code}' '''.replace("\n","").format(id = df.ID, year = df.YEAR, code = df.CODE)

df = pd.read_sql(query,conn)
    # For large datasets use chunks=chunk_size, low_memory=False
</code>```

Note: Don't forget to add space at the end of every line of query.

Body:
I have a dataframe that I can draw values from to write a query for a sql database and want to append the queried information on that dataframe. The original dataframe would be something like:

df =

ID YEAR CODE
43 2013 051
97 2015 087
...

and my current code being:

import pypyodbc as podbc

db = podbc.connect('Driver={SQL Server};Server=server;Database=database')

for row in df:
    cursor = db.cursor()
    query = '''
    SELECT ID, Tool, Date, Version
    FROM table
    WHERE ID = '{id}'
    AND Year(Date) = '{year}'
    AND Code = '{code}'
    '''.format(id = df.ID, year = df.YEAR, code = df.CODE)

    cursor.execute(query)
    rows = cursor.fetchall()
    pd.DataFrame(rows, columns=[x[0] for x in cursor.description)

The returned value from a single query is like:

    ID   Tool   Date         Version
0   43   C15    22-05-2013   1.0

So my issues right now are

1. I don't know how to create an iterable query (for row in df)
2. I don't know how to relate the new dataframe that the query creates to the original df

Hopefully the result would be something like:

ID YEAR CODE Tool Date        Version
43 2013 051  C15  22-05-2013  1.0
97 2015 087  C67  31-01-2015  2.0

Body:
As you already using pandas,

Try this,

conn = podbc.connect('Driver={SQL Server};Server=server;Database=database')

query = ''' SELECT ID, Tool, Date, Version
            FROM table
            WHERE ID = '{id}' AND
            Year(Date) = '{year}' AND
            Code = '{code}' '''.replace("\n","").format(id = df.ID, year = df.YEAR, code = df.CODE)

df = pd.read_sql(query,conn)
    # For large datasets use chunks=chunk_size, low_memory=False

Note: Don't forget to add space at the end of every line of query.


问:
Autosize css dropdown to fit it's largest element
I would like to make a dropdown for choosing from a list of items that always have a width of it's widest element. The selected item is the item that's always shown and other options are shown on hover.

It's a simple CSS dropdown, and ideally, I would like to see pure CSS solution. Since I'm using React and this dropdown is a component, a js solution would be acceptable (without using jQuery or other libraries if possible).

const Dropdown = (props) => (

{props.active}

      {props.items
        .filter(x => x !== props.active)
        .map(x =>
{x}
)}

)

var items = [
 "abc", "abcdcdssd", "a"
]

ReactDOM.render(

Hello <Dropdown items={items} active={"abc"} /> world.
,
  document.querySelector("#app")
)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown {
  display: inline-block;
  background-color: blue;
  text-align: center;
}

.dropdown .dropdown-item {
  background-color: red;
  width: auto;
  padding: 0 6px;
}

.dropdown .dropdown-body {
  display: none;
  position: absolute;
  z-index: 1000;
}

.dropdown:hover .dropdown-body {
  display: block;
}</code>```

```

In the example above, I would like for the "abc" element to have a width of the largest element "abcdcdssd".

答:
Pure CSS Solution

A pure css solution would be to give your container a width: auto and use the visibility style instead of display on your items to hide them:

const Dropdown = (props) => (

{props.active}

      {props.items
        .filter(x => x !== props.active)
        .map(x =>
{x}
)}

)

var items = [
 "abc", "abcdcdssd", "a"
]

ReactDOM.render(

Hello <Dropdown items={items} active={"abc"} /> world.
,
  document.querySelector("#app")
)

var items = [
 "abc", "abcdcdssd", "a"
]

ReactDOM.render(

Hello <Dropdown items={items} active={"abc"} /> world.
,
  document.querySelector("#app")
)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown {
  display: inline-block;
  text-align: center;
  vertical-align: top;
  width: auto;
}

.dropdown .dropdown-item {
  background-color: red;
  padding: 0 6px;
}

.dropdown .dropdown-body {
  visibility: hidden;
  z-index: 1000;
}

.dropdown:hover .dropdown-body {
  visibility: visible;
}</code>```

```
</div>
</div>
</p>

<p>The caveat is that because the items are only hidden if you select the text your hidden items will be selected too.</p>

<h2>JS Solution</h2>

<p>You can measure the width of the dropdown body after the initial render and apply it to the active dropdown item. To make this work you initially need to use <code>visibility: hidden</code> instead of <code>display: none</code> because only the width of hidden elements can be measured. You could hide them as soon as they have been measured initially.</p>

<p>The example below uses react hooks which requires a version <code>>16.8</code> but it can also be achieved with a class based component using <code>componentDidMount</code>.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const {useRef, useState, useLayoutEffect} = React;

const Dropdown = props => {
    const bodyRef = useRef();
    const [bodyWidth, setWidth] = useState(null);
    const [itemsHidden, setItemsHidden] = useState(false);
    useLayoutEffect(() => {
        setWidth(bodyRef.current.clientWidth);
        setItemsHidden(true);
    }, []);

    return (
        <div style={{width: bodyWidth || 'auto'}} className="dropdown">
            <div className="dropdown-item">{props.active}</div>
            <div ref={bodyRef} className={`dropdown-body${itemsHidden ? ' hidden' : ''}`}>
                {props.items
                    .filter(x => x !== props.active)
                    .map((x, idx) => (
                        <div key={idx} className="dropdown-item">{x}</div>
                    ))}
            </div>
        </div>
    );
};

var items = [
 "abc", "abcdcdssd", "a"
]

ReactDOM.render(
 <div>Hello <Dropdown items={items} active={"abc"} /> world.</div>,
  document.querySelector("#app")
)</code>```

.dropdown {
    display: inline-block;
    background-color: blue;
    text-align: center;
}

.dropdown .dropdown-item {
    background-color: red;
    width: auto;
    padding: 0 6px;
}

.dropdown .dropdown-body {
    position: absolute;
    z-index: 1000;
}

.dropdown .dropdown-body.hidden {
  display: none;
  position: absolute;
  z-index: 1000;
}

.dropdown:hover .dropdown-body {
    display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="app"></div></code>```

Body:
I would like to make a dropdown for choosing from a list of items that always have a width of it's widest element. The selected item is the item that's always shown and other options are shown on hover.

It's a simple CSS dropdown, and ideally, I would like to see pure CSS solution. Since I'm using React and this dropdown is a component, a js solution would be acceptable (without using jQuery or other libraries if possible).

const Dropdown = (props) => (

{props.active}

      {props.items
        .filter(x => x !== props.active)
        .map(x =>
{x}
)}

)

var items = [
 "abc", "abcdcdssd", "a"
]

ReactDOM.render(

Hello <Dropdown items={items} active={"abc"} /> world.
,
  document.querySelector("#app")
)

.dropdown {
  display: inline-block;
  background-color: blue;
  text-align: center;
}

.dropdown .dropdown-item {
  background-color: red;
  width: auto;
  padding: 0 6px;
}

.dropdown .dropdown-body {
  display: none;
  position: absolute;
  z-index: 1000;
}

.dropdown:hover .dropdown-body {
  display: block;
}

In the example above, I would like for the "abc" element to have a width of the largest element "abcdcdssd".

Body:
Pure CSS Solution

A pure css solution would be to give your container a width: auto and use the visibility style instead of display on your items to hide them:

const Dropdown = (props) => (
 <div className="dropdown">
   <div className="dropdown-item">{props.active}</div>
    <div className="dropdown-body">
      {props.items
        .filter(x => x !== props.active)
        .map(x => <div className="dropdown-item">{x}</div>)}
    </div>
 </div>
)

var items = [
 "abc", "abcdcdssd", "a"
]

ReactDOM.render(
 <div>Hello <Dropdown items={items} active={"abc"} /> world.</div>,
  document.querySelector("#app")
)

var items = [
 "abc", "abcdcdssd", "a"
]

ReactDOM.render(
 <div>Hello <Dropdown items={items} active={"abc"} /> world.</div>,
  document.querySelector("#app")
)

.dropdown {
  display: inline-block;
  text-align: center;
  vertical-align: top;
  width: auto;
}

.dropdown .dropdown-item {
  background-color: red;
  padding: 0 6px;
}

.dropdown .dropdown-body {
  visibility: hidden;
  z-index: 1000;
}

.dropdown:hover .dropdown-body {
  visibility: visible;
}

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="app"></div>

The caveat is that because the items are only hidden if you select the text your hidden items will be selected too.

JS Solution

You can measure the width of the dropdown body after the initial render and apply it to the active dropdown item. To make this work you initially need to use visibility: hidden instead of display: none because only the width of hidden elements can be measured. You could hide them as soon as they have been measured initially.

The example below uses react hooks which requires a version >16.8 but it can also be achieved with a class based component using componentDidMount.

const {useRef, useState, useLayoutEffect} = React;

const Dropdown = props => {
    const bodyRef = useRef();
    const [bodyWidth, setWidth] = useState(null);
    const [itemsHidden, setItemsHidden] = useState(false);
    useLayoutEffect(() => {
        setWidth(bodyRef.current.clientWidth);
        setItemsHidden(true);
    }, []);

    return (
        <div style={{width: bodyWidth || 'auto'}} className="dropdown">
            <div className="dropdown-item">{props.active}</div>
            <div ref={bodyRef} className={`dropdown-body${itemsHidden ? ' hidden' : ''}`}>
                {props.items
                    .filter(x => x !== props.active)
                    .map((x, idx) => (
                        <div key={idx} className="dropdown-item">{x}</div>
                    ))}
            </div>
        </div>
    );
};

var items = [
 "abc", "abcdcdssd", "a"
]

ReactDOM.render(
 <div>Hello <Dropdown items={items} active={"abc"} /> world.</div>,
  document.querySelector("#app")
)

.dropdown {
    display: inline-block;
    background-color: blue;
    text-align: center;
}

.dropdown .dropdown-item {
    background-color: red;
    width: auto;
    padding: 0 6px;
}

.dropdown .dropdown-body {
    position: absolute;
    z-index: 1000;
}

.dropdown .dropdown-body.hidden {
  display: none;
  position: absolute;
  z-index: 1000;
}

.dropdown:hover .dropdown-body {
    display: block;
}

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="app"></div>


问:
SMOTE is not available in WEKA
8.0 version but I was unable to find the SMOTE package is available there. Can someone let me know what I'm missing here, and why I can't see it</p>

答:
I'm seeing the version number of the SMOTE package for Weka as 1.0.3, not 8.

Use the Package Manager to add this into Weka.

It will show up in the Preprocess tab, as a supervised instance filter.

Title: SMOTE is not available in WEKA


问:
findViewById returrns null from searchView
I'm trying to remove the unnderline from the searchView but the findViewById method returns null all the time</p>

```<code>@Override
protected void onResume() {
    super.onResume();
    View view = mSearchView.findViewById(android.support.v7.appcompat.R.id.search_plate);
    view.setBackgroundColor(Color.TRANSPARENT);
}
</code>```

答:
Init your SearchView in your onCreate

```<code>    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    searchView = findViewById(R.id.search);
    View v = searchView.findViewById(android.support.v7.appcompat.R.id.search_plate);
    v.setBackgroundColor(Color.TRANSPARENT);

}
</code>```

The layout  R.layout.activity_main

```<code>   <android.support.v7.widget.SearchView
    android:id="@+id/search"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</code>```

Body:
I'm trying to remove the unnderline from the searchView but the findViewById method returns null all the time

@Override
protected void onResume() {
    super.onResume();
    View view = mSearchView.findViewById(android.support.v7.appcompat.R.id.search_plate);
    view.setBackgroundColor(Color.TRANSPARENT);
}

Body:
Init your SearchView in your onCreate

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    searchView = findViewById(R.id.search);
    View v = searchView.findViewById(android.support.v7.appcompat.R.id.search_plate);
    v.setBackgroundColor(Color.TRANSPARENT);

}

The layout  R.layout.activity_main

   <android.support.v7.widget.SearchView
    android:id="@+id/search"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


问:
java maven make jar : Could not find or load main class
I have a problem with making executable jar from my project.
I've made a test project with the name

test_project

there is 1 package

testpack

and a public class with my main()

testclass

```<code>     package testpack;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

 public class testclass{

    public static void main(String[] args) throws IOException {...}
</code>```

I have tried to plugins maven-jar-plugin and maven-assembly-plugin just to see what the difference; in both cases i have the same problem with

```<code>   <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
            <archive>
                <manifest>
                    <mainClass>testpack.testclass</mainClass>
                </manifest>
            </archive>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.1.2</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>testpack.testclass</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
</code>```

Error: Could not find or load main class testpack.testclass

yes I have read this similar question and it didn't help me

I've checked my env variables and all the step 1 points; I think i just don't understand how to point on my main() in maven setup

I don't understand were can I find this information about my project

```<code><archive>
    <manifest>
      <mainClass>com.domain.project.MainClass</mainClass>
    </manifest>
  </archive>
</code>```

what's the right way to point on the main class?

答:
Please check below the maven jar plugin usage. I have written a simple Hello World Program just to demonstrate.

```<code><build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>
                                com.ddlab.rnd.App
                            </mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

If you want to check the complete small source code, check this github link.
https://github.com/debjava/runnableJar

I did not add any classpath dependencies, if you want, you can add other libraries like this.

```<code><addClasspath>true</addClasspath>
<classpathPrefix>you lib dir containing all jar file/</classpathPrefix>
</code>```

Body:
I have a problem with making executable jar from my project.
I've made a test project with the name

test_project

there is 1 package

testpack

and a public class with my main()

testclass

     package testpack;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

 public class testclass{

    public static void main(String[] args) throws IOException {...}

I have tried to plugins maven-jar-plugin and maven-assembly-plugin just to see what the difference; in both cases i have the same problem with

   <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
            <archive>
                <manifest>
                    <mainClass>testpack.testclass</mainClass>
                </manifest>
            </archive>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.1.2</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>testpack.testclass</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

Error: Could not find or load main class testpack.testclass

yes I have read this similar question and it didn't help me

I've checked my env variables and all the step 1 points; I think i just don't understand how to point on my main() in maven setup

I don't understand were can I find this information about my project

<archive>
    <manifest>
      <mainClass>com.domain.project.MainClass</mainClass>
    </manifest>
  </archive>

what's the right way to point on the main class?

Body:
Please check below the maven jar plugin usage. I have written a simple Hello World Program just to demonstrate.

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>
                                com.ddlab.rnd.App
                            </mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

If you want to check the complete small source code, check this github link.
https://github.com/debjava/runnableJar

I did not add any classpath dependencies, if you want, you can add other libraries like this.

<addClasspath>true</addClasspath>
<classpathPrefix>you lib dir containing all jar file/</classpathPrefix>


问:
RegEx for capturing a word in between = and ;
I want to select word2 from the following :

```<code>word2;word3
</code>```

word2 that is between ; and start of the line unless there is a = in between. In that case, I want start from the = instead of the start of the line
like word2 from

```<code>word1=word2;word3
</code>```

I have tried using this regex

```<code>(?<=\=|^).*?(?=;)
</code>```

which select the word2 from

```<code>word2;word3
</code>```

but also the whole word1=word2 from

```<code>word1=word2;word3
</code>```

答:
You can use an optional group to check for a word followed by an equals sign and capture the value in the first capturing group:

```<code>^(?:\w+=)?(\w+);
</code>```

Explanation

^ Start of string

(?:\w+=)? Optional non capturing group matching 1+ word chars followed by =

(\w+) Capture in the first capturing group 1+ word chars

; Match ;

See a regex demo

In .NET you might also use:

```<code>(?<=^(?:\w+=)?)\w+(?=;)
</code>```

Regex demo | C# demo

Body:
I want to select word2 from the following :

word2;word3

word2 that is between ; and start of the line unless there is a = in between. In that case, I want start from the = instead of the start of the line
like word2 from

word1=word2;word3

I have tried using this regex

(?<=\=|^).*?(?=;)

which select the word2 from

word2;word3

but also the whole word1=word2 from

word1=word2;word3

Body:
You can use an optional group to check for a word followed by an equals sign and capture the value in the first capturing group:

^(?:\w+=)?(\w+);

Explanation

^ Start of string

(?:\w+=)? Optional non capturing group matching 1+ word chars followed by =

(\w+) Capture in the first capturing group 1+ word chars

; Match ;

See a regex demo

In .NET you might also use:

(?<=^(?:\w+=)?)\w+(?=;)

Regex demo | C# demo


问:
How to do a HTTP HEAD request from the windows command line?
What's the best way (or tool) on the Windows (Vista) command line to get size and modification time for a file on a remote webserver, without downloading it?</p>

答:
If you cannot install aditional applications, then you can telnet (you will need to install this feature for your windows 7 by following this) the remote server:

```<code>TELNET server_name 80
</code>```

followed by:

```<code>HEAD /virtual/directory/file.ext
</code>```

or

```<code>GET /virtual/directory/file.ext
</code>```

depending on if you want just the header (HEAD) or the full contents (GET)

OwnerDisplayName: Henning

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: dbr

Body:
If you cannot install aditional applications, then you can telnet (you will need to install this feature for your windows 7 by following this) the remote server:

TELNET server_name 80

followed by:

HEAD /virtual/directory/file.ext

or

GET /virtual/directory/file.ext

depending on if you want just the header (HEAD) or the full contents (GET)


问:
Converting from alpha to numeric with decimals fails
I have to convert a alphanumeric value  to a numeric value with decimal places:

Input: '6000'

Output. 60.00

So I tried the %dec() BIF which takes the input as alpha, the precision and the decimal places. But when trying this:

```<code>dcl-s alphanumeric char(13);
dcl-s numeric packed(13:2);

alphanumeric = '6000';
numeric = %dec(alphanumeric:13:2);

*inlr = *on;
</code>```

the conversion produces NUMERIC = 00000006000.00 and not NUMERIC = 000000060.00. So what am I doing wrong?

Even when using zoned(13:2) instead of packed(13:2) the value doesn't have decimal places other than '00'

答:
Another way to do get 60.00 is to multiply the result by .01.

```<code>numeric = %dec(alphanumeric:13:0) * .01;
</code>```

The length and decimal places for %DEC aren't used to specify how to interpret the character value, they are just used to set the size of the result. If the character value is '6000', the result of %DEC is always 6000, but depending on the length and decimals of %DEC, it might be 006000.000, or 6000.00, etc.

Body:
I have to convert a alphanumeric value  to a numeric value with decimal places:

Input: '6000'

Output. 60.00

So I tried the %dec() BIF which takes the input as alpha, the precision and the decimal places. But when trying this:

dcl-s alphanumeric char(13);
dcl-s numeric packed(13:2);

alphanumeric = '6000';
numeric = %dec(alphanumeric:13:2);

*inlr = *on;

the conversion produces NUMERIC = 00000006000.00 and not NUMERIC = 000000060.00. So what am I doing wrong?

Even when using zoned(13:2) instead of packed(13:2) the value doesn't have decimal places other than '00'

Body:
Another way to do get 60.00 is to multiply the result by .01.

numeric = %dec(alphanumeric:13:0) * .01;

The length and decimal places for %DEC aren't used to specify how to interpret the character value, they are just used to set the size of the result. If the character value is '6000', the result of %DEC is always 6000, but depending on the length and decimals of %DEC, it might be 006000.000, or 6000.00, etc.


问:
mobx computed / reactive context with event handlers?
With MobX, @computed properties are only cached when accessed from an observer or reactive context.  So for example:

```<code>class Foo {
    @computed
    get somethingExpensive() { return someReallyExpensiveOperation() }
}

const f = new Foo();
setInterval(() => console.log(f.somethingExpensive), 1);
</code>```

Will always call someReallyExpensiveOperation() because the computed is being called outside of a reactive context.

Is there a way to "enter" a reactive context to gain the benefits of @computed for setTimeout callbacks, EventEmitter event handlers etc?

EDIT: Another way to put this.. if I change the decorator to

```<code>class Foo {
    @computed({ requiresReaction: true })
    get somethingExpensive() { return someReallyExpensiveOperation() }
}
</code>```

..it will throw when accessed from the setInterval example.

答:
I use an instantly disposed autorun:

```<code>autorun((reaction) => {
    console.log(f.somethingExpensive)
    reaction.dispose()
})
</code>```

Also made a npm module:

```<code>import runInReactiveContext from 'mobx-run-in-reactive-context'

// ...

runInReactiveContext(() => {
    console.log(f.somethingExpensive)
})
</code>```

Body:
With MobX, @computed properties are only cached when accessed from an observer or reactive context.  So for example:

class Foo {
    @computed
    get somethingExpensive() { return someReallyExpensiveOperation() }
}

const f = new Foo();
setInterval(() => console.log(f.somethingExpensive), 1);

Will always call someReallyExpensiveOperation() because the computed is being called outside of a reactive context.

Is there a way to "enter" a reactive context to gain the benefits of @computed for setTimeout callbacks, EventEmitter event handlers etc?

EDIT: Another way to put this.. if I change the decorator to

class Foo {
    @computed({ requiresReaction: true })
    get somethingExpensive() { return someReallyExpensiveOperation() }
}

..it will throw when accessed from the setInterval example.

Body:
I use an instantly disposed autorun:

autorun((reaction) => {
    console.log(f.somethingExpensive)
    reaction.dispose()
})

Also made a npm module:

import runInReactiveContext from 'mobx-run-in-reactive-context'

// ...

runInReactiveContext(() => {
    console.log(f.somethingExpensive)
})