问:
Typescript type transform
While working my way through typescript types, I have a question about transformations. I have the following type:

export type DataChampLogLevel = 'debug' | 'verbose' | 'info' | 'warning' | 'error'
```
<p>No it is the case that some loggers only accept <code>debug</code> while others expect <code>verbose</code></p>
<p>I have a logging facade which expects <code>DataChampLoglevel</code></p>
<pre class="lang-js prettyprint-override"><code>export interface DataChampLogger {

  setLogLevel(level: DataChampLogLevel): void

}

//implementation

  setLogLevel(level: DataChampLogLevel): void {
    SomeLogger.setLogLevel(level) // compiler type error debug is not allowed in type OtherLogLevel..
  }
</code>```

internally I need to convert the value from e.g. debug to verbose while it is rather simple to write a convert function I was wondering if the same was possible with typesxript types e.g. String Templates or the like. I was playing around a bit but was not able to come up with the proper solution.
This is just my own curiosity to improve my skills ;)

Regards
Mathias

答:
I was wondering if the same was possible with typesxript types

No. What you're describing is a runtime value conversion. TypeScript types don't exist at runtime (other than a small caveat around enums). So there's no TypeScript type solution to this. You'll need a runtime solution to modify a runtime value.

There may or may not be a type aspect to this as well, since SomeLogger.setLogLevel seems to accept a different type from DataChampLogLevel, so you'll need a way to tell TypeScript that the (updated) value is allowed for SomeLogger.setLogLevel. But it can't help with the runtime side of it.

For instance, let's say that SomeLogger.setLogLevel accepts a SomeLoggerLogLevel which is:

```<code>type SomeLoggerLogLevel = 'verbose' | 'info' | 'warning' | 'error';
</code>```

In that case, there's no need to do anything explicit with the type, since TypeScript's flow analysis can see you handling it inline if you do something like:

```<code>setLogLevel(level: DataChampLogLevel): void {
    if (level === "debug") {
        level = "verbose";
    }
    SomeLogger.setLogLevel(level);
}
</code>```

But if you do it another way (like a lookup table), you may need to reassure TypeScript that your runtime conversion is correct. For instance, TypeScript won't be happy with this:

```<code>const logLevelMap: Partial<Record<DataChampLogLevel, SomeLoggerLogLevel>> = {
    debug: "verbose",
};

const obj: DataChampLogger = {
    setLogLevel(level: DataChampLogLevel): void {
        level = logLevelMap[level] ?? level;
        SomeLogger.setLogLevel(level); // Argument of type 'DataChampLogLevel' is not assignable to parameter of type 'SomeLoggerLogLevel'.
    }
};
</code>```

but if you add a type assertion function, it's happy:

```<code>const logLevelMap: Partial<Record<DataChampLogLevel, SomeLoggerLogLevel>> = {
    debug: "verbose",
};

function assertsIsValidSomeLoggerLogLevel(level: DataChampLogLevel): asserts level is SomeLoggerLogLevel {
    if (level in logLevelMap) {
        throw new Error(`Invalid SomeLoggerLogLevel "${level}"`);
    }
}

const obj: DataChampLogger = {
    setLogLevel(level: DataChampLogLevel): void {
        level = logLevelMap[level] ?? level;
        assertsIsValidSomeLoggerLogLevel(level);
        SomeLogger.setLogLevel(level);
    }
};
</code>```

Title: Typescript type transform

Body:
While working my way through typescript types, I have a question about transformations. I have the following type:

export type DataChampLogLevel = 'debug' | 'verbose' | 'info' | 'warning' | 'error'

No it is the case that some loggers only accept debug while others expect verbose

I have a logging facade which expects DataChampLoglevel

export interface DataChampLogger {

  setLogLevel(level: DataChampLogLevel): void

}

//implementation

  setLogLevel(level: DataChampLogLevel): void {
    SomeLogger.setLogLevel(level) // compiler type error debug is not allowed in type OtherLogLevel..
  }

internally I need to convert the value from e.g. debug to verbose while it is rather simple to write a convert function I was wondering if the same was possible with typesxript types e.g. String Templates or the like. I was playing around a bit but was not able to come up with the proper solution.
This is just my own curiosity to improve my skills ;)

Regards
Mathias

Body:
I was wondering if the same was possible with typesxript types

No. What you're describing is a runtime value conversion. TypeScript types don't exist at runtime (other than a small caveat around enums). So there's no TypeScript type solution to this. You'll need a runtime solution to modify a runtime value.

There may or may not be a type aspect to this as well, since SomeLogger.setLogLevel seems to accept a different type from DataChampLogLevel, so you'll need a way to tell TypeScript that the (updated) value is allowed for SomeLogger.setLogLevel. But it can't help with the runtime side of it.

For instance, let's say that SomeLogger.setLogLevel accepts a SomeLoggerLogLevel which is:

type SomeLoggerLogLevel = 'verbose' | 'info' | 'warning' | 'error';

In that case, there's no need to do anything explicit with the type, since TypeScript's flow analysis can see you handling it inline if you do something like:

setLogLevel(level: DataChampLogLevel): void {
    if (level === "debug") {
        level = "verbose";
    }
    SomeLogger.setLogLevel(level);
}

But if you do it another way (like a lookup table), you may need to reassure TypeScript that your runtime conversion is correct. For instance, TypeScript won't be happy with this:

const logLevelMap: Partial<Record<DataChampLogLevel, SomeLoggerLogLevel>> = {
    debug: "verbose",
};

const obj: DataChampLogger = {
    setLogLevel(level: DataChampLogLevel): void {
        level = logLevelMap[level] ?? level;
        SomeLogger.setLogLevel(level); // Argument of type 'DataChampLogLevel' is not assignable to parameter of type 'SomeLoggerLogLevel'.
    }
};

but if you add a type assertion function, it's happy:

const logLevelMap: Partial<Record<DataChampLogLevel, SomeLoggerLogLevel>> = {
    debug: "verbose",
};

function assertsIsValidSomeLoggerLogLevel(level: DataChampLogLevel): asserts level is SomeLoggerLogLevel {
    if (level in logLevelMap) {
        throw new Error(`Invalid SomeLoggerLogLevel "${level}"`);
    }
}

const obj: DataChampLogger = {
    setLogLevel(level: DataChampLogLevel): void {
        level = logLevelMap[level] ?? level;
        assertsIsValidSomeLoggerLogLevel(level);
        SomeLogger.setLogLevel(level);
    }
};


来源: stackexchange

问:
How to clear setInterval ID in Angular?
I am building a basic timer in Angular. For this I have two button, one of them starts the timer and the other stops it. I am implementing setInterval with 1000ms delay. But when I press the stop button, the timer stops but the timeoutId is not cleared. I want to prevent the user not to start another timer when the first one doesnt finish. I use - if (this.timeoutId) return; - But I am not able to start it again as I stop it.
The question is how I can prevent the user to start new timer when the timer started. And how can I start it again when I stop it.

//game-control-component.ts

```<code>import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-game-control',
  templateUrl: './game-control.component.html',
  styleUrls: ['./game-control.component.css'],
})
export class GameControlComponent implements OnInit {

@Output() onIncrement: EventEmitter<number> = new EventEmitter();
timer: number = 0;
timeoutId!: ReturnType<typeof setTimeout>;

constructor() {
  console.log(this.timeoutId);
}

increment() {
  this.timer++;
}

startTimer() {
  if (this.timeoutId) return;
  this.timeoutId = setInterval(() => {
    this.increment();
    this.onIncrement.emit(this.timer);
  }, 1000);
}

stopTimer() {
  clearInterval(this.timeoutId);
  console.log(this.timeoutId);
}

ngOnInit(): void {
  console.log(this.timeoutId);
 }

}
</code>```

//game-control-component-html

```<code><div class="row mt-5">
  <div class="col-12">
    <div class="button-group d-flex justify-content-evenly">
      <button (click)="startTimer()" class="btn btn-primary">Start</button>
      <button (click)="stopTimer()" class="btn btn-danger">Stop</button>
    </div>
  <h1 class="mt-5" style="text-align: center">{{ timer }}</h1>
  </div>
</code>```

答:
There is no inbuilt way for achieving this.

The only possible solution is to clear the interval variable once you clear the interval object.

```<code>stopTimer() {
  clearInterval(this.timeoutId);
  this.timeoutId = null; // Clear the timeoutId
}
</code>```

And now the start timer works as expexted. You are checking whether the timeoutId exist inside the start timer function

```<code>startTimer() {
  if (this.timeoutId) return; // Function will exist from here if timeoutId exist
  this.timeoutId = setInterval(() => {
    this.increment();
    this.onIncrement.emit(this.timer);
  }, 1000);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to clear setInterval ID in Angular?

Body:
I am building a basic timer in Angular. For this I have two button, one of them starts the timer and the other stops it. I am implementing setInterval with 1000ms delay. But when I press the stop button, the timer stops but the timeoutId is not cleared. I want to prevent the user not to start another timer when the first one doesnt finish. I use - if (this.timeoutId) return; - But I am not able to start it again as I stop it.
The question is how I can prevent the user to start new timer when the timer started. And how can I start it again when I stop it.

//game-control-component.ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-game-control',
  templateUrl: './game-control.component.html',
  styleUrls: ['./game-control.component.css'],
})
export class GameControlComponent implements OnInit {

@Output() onIncrement: EventEmitter<number> = new EventEmitter();
timer: number = 0;
timeoutId!: ReturnType<typeof setTimeout>;

constructor() {
  console.log(this.timeoutId);
}

increment() {
  this.timer++;
}

startTimer() {
  if (this.timeoutId) return;
  this.timeoutId = setInterval(() => {
    this.increment();
    this.onIncrement.emit(this.timer);
  }, 1000);
}

stopTimer() {
  clearInterval(this.timeoutId);
  console.log(this.timeoutId);
}

ngOnInit(): void {
  console.log(this.timeoutId);
 }

}

//game-control-component-html

      <button (click)="startTimer()" class="btn btn-primary">Start</button>
      <button (click)="stopTimer()" class="btn btn-danger">Stop</button>

{{ timer }}

Body:
There is no inbuilt way for achieving this.

The only possible solution is to clear the interval variable once you clear the interval object.

stopTimer() {
  clearInterval(this.timeoutId);
  this.timeoutId = null; // Clear the timeoutId
}

And now the start timer works as expexted. You are checking whether the timeoutId exist inside the start timer function

startTimer() {
  if (this.timeoutId) return; // Function will exist from here if timeoutId exist
  this.timeoutId = setInterval(() => {
    this.increment();
    this.onIncrement.emit(this.timer);
  }, 1000);
}


问:
How to view/save AVFrame have format AV_PIX_FMT_YUVJ420P to file
I have a AVFrame and I want to save it to file. If I only store frame->data[0] to file, the image will be Grey image, how to view full color? I use C language.

Do you have any suggestions on what I should read to understand and do these things by myself?

答:
A relatively simple way to save and view the image is writing Y, U and V (planar) data to binary file, and using FFmpeg CLI to convert the binary file to RGB.

Some background:

yuvj420p in FFmpeg (libav) terminology applies YUV420 "full range" format.

I suppose the j in yuvj comes from JPEG - JPEG images uses "full range" YUV420 format.

Most of the video files use "limited range" (or TV range) YUV format.

In "limited range", Y range is [16, 235], U range is [16, 240] and V range is [0, 240].

In "full range", Y range is [0, 255], U range is [0, 255] and V range is [0, 255].

yuvj420p is deprecated, and supposed to be marked using yuv420p combined with dst_range 1 (or src_range 1) in FFmpeg CLI. I never looked for a way to define "full range" in C.

yuvj420p in FFmpeg (libav) applies "planar" format.

Separate planes for Y channel, for U channel and for V channel.

Y plane is given in full resolution, and U, V are down-scaled by a factor of x2 in each axis.

Illustration:

Y - data[0]:  YYYYYYYYYYYY
              YYYYYYYYYYYY
              YYYYYYYYYYYY
              YYYYYYYYYYYY

U - data[1]:  UUUUUU
              UUUUUU
              UUUUUU

V - data[2]:  VVVVVV
              VVVVVV
              VVVVVV
```
<p>In C, each "plane" is stored in a separate buffer in memory.<br />
When writing the data to a binary file, we may simply write the buffers to the file one after the other.</p>
<hr />
<p>For demonstration, I am reusing my following answer.</p>
<p>I copied and paste the complete answer, and replaced YUV420 with YUVJ420.</p>
<p>In the example, the input format is NV12 (and I kept it).
The input format is irrelevant (you may ignore it) - only the output format is relevant for your question.</p>
<hr />
<p>I have created a "self contained" code sample that demonstrates the conversion from NV12 to YUV420 (<code>yuvj420p</code>) using <code>sws_scale</code>.</p>
<ul>
<li>Start by building synthetic input frame using FFmpeg (command line tool).<br />
The command creates 320x240 video frame in raw NV12 format:</li>
</ul>
<pre class="lang-none prettyprint-override"><code>    ffmpeg -y -f lavfi -i testsrc=size=320x240:rate=1 -vcodec rawvideo -pix_fmt nv12 -frames 1 -f rawvideo nv12_image.bin
</code>```

The next code sample applies the following stages:

Allocate memory for the source frame (in NV12 format).

Read NV12 data from binary file (for testing).

Allocate memory for the destination frame (in YUV420 / yuvj420 format).

Apply color space conversion (using sws_scale).

Write the converted YUV420 (yuvj420) data to binary file (for testing).

Here is the complete code:

```<code>//Use extern "C", because the code is built as C++ (cpp file) and not C.
extern "C"
{
#include <libswscale/swscale.h>
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>
#include <libavutil/pixdesc.h>
#include <libavutil/imgutils.h>
}

int main()
{
    int width = 320;
    int height = 240;   //The code sample assumes height is even.
    int align = 0;
    AVPixelFormat srcPxlFormat = AV_PIX_FMT_NV12;
    AVPixelFormat dstPxlFormat = AV_PIX_FMT_YUVJ420P;
    int sts;

    //Source frame allocation
    ////////////////////////////////////////////////////////////////////////////
    AVFrame* pNV12Frame = av_frame_alloc();

    pNV12Frame->format = srcPxlFormat;
    pNV12Frame->width = width;
    pNV12Frame->height = height;

    sts = av_frame_get_buffer(pNV12Frame, align);

    if (sts < 0)
    {
        return -1;  //Error!
    }
    ////////////////////////////////////////////////////////////////////////////

    //Read NV12 data from binary file (for testing)
    ////////////////////////////////////////////////////////////////////////////
    //Use FFmpeg for building raw NV12 image (used as input).
    //ffmpeg -y -f lavfi -i testsrc=size=320x240:rate=1 -vcodec rawvideo -pix_fmt nv12 -frames 1 -f rawvideo nv12_image.bin

    FILE* f = fopen("nv12_image.bin", "rb");

    if (f == NULL)
    {
        return -1;  //Error!
    }

    //Read Y channel from nv12_image.bin (Y channel size is width x height).
    //Reading row by row is required in rare cases when pNV12Frame->linesize[0] != width
    uint8_t* Y = pNV12Frame->data[0];   //Pointer to Y color channel of the NV12 frame.
    for (int row = 0; row < height; row++)
    {
        fread(Y + (uintptr_t)row * pNV12Frame->linesize[0], 1, width, f); //Read row (width pixels) to Y0.
    }

    //Read UV channel from nv12_image.bin (UV channel size is width x height/2).
    uint8_t* UV = pNV12Frame->data[1];   //Pointer to UV color channels of the NV12 frame (ordered as UVUVUVUV...).
    for (int row = 0; row < height / 2; row++)
    {
        fread(UV + (uintptr_t)row * pNV12Frame->linesize[1], 1, width, f); //Read row (width pixels) to UV0.
    }

    fclose(f);
    ////////////////////////////////////////////////////////////////////////////

    //Destination frame allocation
    ////////////////////////////////////////////////////////////////////////////
    AVFrame* pYUV420Frame = av_frame_alloc();

    pYUV420Frame->format = dstPxlFormat;
    pYUV420Frame->width = width;
    pYUV420Frame->height = height;

    sts = av_frame_get_buffer(pYUV420Frame, align);

    if (sts < 0)
    {
        return -1;  //Error!
    }
    ////////////////////////////////////////////////////////////////////////////

    //Color space conversion
    ////////////////////////////////////////////////////////////////////////////
    SwsContext* sws_context = sws_getContext(width,
        height,
        srcPxlFormat,
        width,
        height,
        dstPxlFormat,
        SWS_FAST_BILINEAR,
        NULL,
        NULL,
        NULL);

    if (sws_context == NULL)
    {
        return -1;  //Error!
    }

    sts = sws_scale(sws_context, //struct SwsContext* c,
        pNV12Frame->data,        //const uint8_t* const srcSlice[],
        pNV12Frame->linesize,    //const int srcStride[],
        0,                       //int srcSliceY,
        pNV12Frame->height,      //int srcSliceH,
        pYUV420Frame->data,      //uint8_t* const dst[],
        pYUV420Frame->linesize); //const int dstStride[]);

    if (sts != pYUV420Frame->height)
    {
        return -1;  //Error!
    }
    ////////////////////////////////////////////////////////////////////////////

    //Write YUV420 (yuvj420p) data to binary file (for testing)
    ////////////////////////////////////////////////////////////////////////////
    //Use FFmpeg for converting the binary image to PNG after saving the data.
    //ffmpeg -y -f rawvideo -video_size 320x240 -pixel_format yuvj420p -i yuvj420_image.bin -pix_fmt rgb24 rgb_image.png

    f = fopen("yuvj420_image.bin", "wb");

    if (f == NULL)
    {
        return -1;  //Error!
    }

    //Write Y channel to yuvj420_image.bin (Y channel size is width x height).
    //Writing row by row is required in rare cases when pYUV420Frame->linesize[0] != width
    Y = pYUV420Frame->data[0];   //Pointer to Y color channel of the YUV420 frame.
    for (int row = 0; row < height; row++)
    {
        fwrite(Y + (uintptr_t)row * pYUV420Frame->linesize[0], 1, width, f); //Write row (width pixels) to file.
    }

    //Write U channel to yuvj420_image.bin (U channel size is width/2 x height/2).
    uint8_t* U = pYUV420Frame->data[1];   //Pointer to U color channels of the YUV420 frame.
    for (int row = 0; row < height / 2; row++)
    {
        fwrite(U + (uintptr_t)row * pYUV420Frame->linesize[1], 1, width / 2, f); //Write row (width/2 pixels) to file.
    }

    //Write V channel to yuv420_image.bin (V channel size is width/2 x height/2).
    uint8_t* V = pYUV420Frame->data[2];   //Pointer to V color channels of the YUV420 frame.
    for (int row = 0; row < height / 2; row++)
    {
        fwrite(V + (uintptr_t)row * pYUV420Frame->linesize[2], 1, width / 2, f); //Write row (width/2 pixels) to file.
    }

    fclose(f);
    ////////////////////////////////////////////////////////////////////////////

    //Cleanup
    ////////////////////////////////////////////////////////////////////////////
    sws_freeContext(sws_context);
    av_frame_free(&pYUV420Frame);
    av_frame_free(&pNV12Frame);
    ////////////////////////////////////////////////////////////////////////////

    return 0;
}
</code>```

The execution shows a warning message (that we may ignore):

[swscaler @ 000002a19227e640] deprecated pixel format used, make sure you did set range correctly

For viewing the output as colored image:

After executing the code, execute FFmpeg (command line tool).

The following command converts the raw binary frame (in YUV420 / yuvj420p format) to PNG (in RGB format).

    ffmpeg -y -f rawvideo -video_size 320x240 -pixel_format yuvj420p -i yuvj420_image.bin -pix_fmt rgb24 rgb_image.png
```

Sample output (after converting from yuvj420p to PNG image file format):

Body:
A relatively simple way to save and view the image is writing Y, U and V (planar) data to binary file, and using FFmpeg CLI to convert the binary file to RGB.

Some background:

yuvj420p in FFmpeg (libav) terminology applies YUV420 "full range" format.

I suppose the j in yuvj comes from JPEG - JPEG images uses "full range" YUV420 format.

Most of the video files use "limited range" (or TV range) YUV format.

In "limited range", Y range is [16, 235], U range is [16, 240] and V range is [0, 240].

In "full range", Y range is [0, 255], U range is [0, 255] and V range is [0, 255].

yuvj420p is deprecated, and supposed to be marked using yuv420p combined with dst_range 1 (or src_range 1) in FFmpeg CLI. I never looked for a way to define "full range" in C.

yuvj420p in FFmpeg (libav) applies "planar" format.

Separate planes for Y channel, for U channel and for V channel.

Y plane is given in full resolution, and U, V are down-scaled by a factor of x2 in each axis.

Illustration:

Y - data[0]:  YYYYYYYYYYYY
              YYYYYYYYYYYY
              YYYYYYYYYYYY
              YYYYYYYYYYYY

U - data[1]:  UUUUUU
              UUUUUU
              UUUUUU

V - data[2]:  VVVVVV
              VVVVVV
              VVVVVV

In C, each "plane" is stored in a separate buffer in memory.

When writing the data to a binary file, we may simply write the buffers to the file one after the other.

For demonstration, I am reusing my following answer.

I copied and paste the complete answer, and replaced YUV420 with YUVJ420.

In the example, the input format is NV12 (and I kept it).
The input format is irrelevant (you may ignore it) - only the output format is relevant for your question.

I have created a "self contained" code sample that demonstrates the conversion from NV12 to YUV420 (yuvj420p) using sws_scale.

Start by building synthetic input frame using FFmpeg (command line tool).

The command creates 320x240 video frame in raw NV12 format:

    ffmpeg -y -f lavfi -i testsrc=size=320x240:rate=1 -vcodec rawvideo -pix_fmt nv12 -frames 1 -f rawvideo nv12_image.bin

The next code sample applies the following stages:

Allocate memory for the source frame (in NV12 format).

Read NV12 data from binary file (for testing).

Allocate memory for the destination frame (in YUV420 / yuvj420 format).

Apply color space conversion (using sws_scale).

Write the converted YUV420 (yuvj420) data to binary file (for testing).

Here is the complete code:

//Use extern "C", because the code is built as C++ (cpp file) and not C.
extern "C"
{
#include <libswscale/swscale.h>
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>
#include <libavutil/pixdesc.h>
#include <libavutil/imgutils.h>
}

int main()
{
    int width = 320;
    int height = 240;   //The code sample assumes height is even.
    int align = 0;
    AVPixelFormat srcPxlFormat = AV_PIX_FMT_NV12;
    AVPixelFormat dstPxlFormat = AV_PIX_FMT_YUVJ420P;
    int sts;

    //Source frame allocation
    ////////////////////////////////////////////////////////////////////////////
    AVFrame* pNV12Frame = av_frame_alloc();

    pNV12Frame->format = srcPxlFormat;
    pNV12Frame->width = width;
    pNV12Frame->height = height;

    sts = av_frame_get_buffer(pNV12Frame, align);

    if (sts < 0)
    {
        return -1;  //Error!
    }
    ////////////////////////////////////////////////////////////////////////////

    //Read NV12 data from binary file (for testing)
    ////////////////////////////////////////////////////////////////////////////
    //Use FFmpeg for building raw NV12 image (used as input).
    //ffmpeg -y -f lavfi -i testsrc=size=320x240:rate=1 -vcodec rawvideo -pix_fmt nv12 -frames 1 -f rawvideo nv12_image.bin

    FILE* f = fopen("nv12_image.bin", "rb");

    if (f == NULL)
    {
        return -1;  //Error!
    }

    //Read Y channel from nv12_image.bin (Y channel size is width x height).
    //Reading row by row is required in rare cases when pNV12Frame->linesize[0] != width
    uint8_t* Y = pNV12Frame->data[0];   //Pointer to Y color channel of the NV12 frame.
    for (int row = 0; row < height; row++)
    {
        fread(Y + (uintptr_t)row * pNV12Frame->linesize[0], 1, width, f); //Read row (width pixels) to Y0.
    }

    //Read UV channel from nv12_image.bin (UV channel size is width x height/2).
    uint8_t* UV = pNV12Frame->data[1];   //Pointer to UV color channels of the NV12 frame (ordered as UVUVUVUV...).
    for (int row = 0; row < height / 2; row++)
    {
        fread(UV + (uintptr_t)row * pNV12Frame->linesize[1], 1, width, f); //Read row (width pixels) to UV0.
    }

    fclose(f);
    ////////////////////////////////////////////////////////////////////////////

    //Destination frame allocation
    ////////////////////////////////////////////////////////////////////////////
    AVFrame* pYUV420Frame = av_frame_alloc();

    pYUV420Frame->format = dstPxlFormat;
    pYUV420Frame->width = width;
    pYUV420Frame->height = height;

    sts = av_frame_get_buffer(pYUV420Frame, align);

    if (sts < 0)
    {
        return -1;  //Error!
    }
    ////////////////////////////////////////////////////////////////////////////

    //Color space conversion
    ////////////////////////////////////////////////////////////////////////////
    SwsContext* sws_context = sws_getContext(width,
        height,
        srcPxlFormat,
        width,
        height,
        dstPxlFormat,
        SWS_FAST_BILINEAR,
        NULL,
        NULL,
        NULL);

    if (sws_context == NULL)
    {
        return -1;  //Error!
    }

    sts = sws_scale(sws_context, //struct SwsContext* c,
        pNV12Frame->data,        //const uint8_t* const srcSlice[],
        pNV12Frame->linesize,    //const int srcStride[],
        0,                       //int srcSliceY,
        pNV12Frame->height,      //int srcSliceH,
        pYUV420Frame->data,      //uint8_t* const dst[],
        pYUV420Frame->linesize); //const int dstStride[]);

    if (sts != pYUV420Frame->height)
    {
        return -1;  //Error!
    }
    ////////////////////////////////////////////////////////////////////////////

    //Write YUV420 (yuvj420p) data to binary file (for testing)
    ////////////////////////////////////////////////////////////////////////////
    //Use FFmpeg for converting the binary image to PNG after saving the data.
    //ffmpeg -y -f rawvideo -video_size 320x240 -pixel_format yuvj420p -i yuvj420_image.bin -pix_fmt rgb24 rgb_image.png

    f = fopen("yuvj420_image.bin", "wb");

    if (f == NULL)
    {
        return -1;  //Error!
    }

    //Write Y channel to yuvj420_image.bin (Y channel size is width x height).
    //Writing row by row is required in rare cases when pYUV420Frame->linesize[0] != width
    Y = pYUV420Frame->data[0];   //Pointer to Y color channel of the YUV420 frame.
    for (int row = 0; row < height; row++)
    {
        fwrite(Y + (uintptr_t)row * pYUV420Frame->linesize[0], 1, width, f); //Write row (width pixels) to file.
    }

    //Write U channel to yuvj420_image.bin (U channel size is width/2 x height/2).
    uint8_t* U = pYUV420Frame->data[1];   //Pointer to U color channels of the YUV420 frame.
    for (int row = 0; row < height / 2; row++)
    {
        fwrite(U + (uintptr_t)row * pYUV420Frame->linesize[1], 1, width / 2, f); //Write row (width/2 pixels) to file.
    }

    //Write V channel to yuv420_image.bin (V channel size is width/2 x height/2).
    uint8_t* V = pYUV420Frame->data[2];   //Pointer to V color channels of the YUV420 frame.
    for (int row = 0; row < height / 2; row++)
    {
        fwrite(V + (uintptr_t)row * pYUV420Frame->linesize[2], 1, width / 2, f); //Write row (width/2 pixels) to file.
    }

    fclose(f);
    ////////////////////////////////////////////////////////////////////////////

    //Cleanup
    ////////////////////////////////////////////////////////////////////////////
    sws_freeContext(sws_context);
    av_frame_free(&pYUV420Frame);
    av_frame_free(&pNV12Frame);
    ////////////////////////////////////////////////////////////////////////////

    return 0;
}

The execution shows a warning message (that we may ignore):

[swscaler @ 000002a19227e640] deprecated pixel format used, make sure you did set range correctly

For viewing the output as colored image:

After executing the code, execute FFmpeg (command line tool).

The following command converts the raw binary frame (in YUV420 / yuvj420p format) to PNG (in RGB format).

    ffmpeg -y -f rawvideo -video_size 320x240 -pixel_format yuvj420p -i yuvj420_image.bin -pix_fmt rgb24 rgb_image.png

Sample output (after converting from yuvj420p to PNG image file format):


问:
Why im getting this error Warning: Operand of null-aware operation '??' has type 'String' which excludes null. Dart Language
so i was learning about SWITCH and CASE Statements in dart language, in the course he explains the code but he don't get an error while i get one.

the error i get
: Warning: Operand of null-aware operation '??' has type 'String' which excludes null.
String ``userName = name ?? "Guest User";

My Code is

```<code>void learnCondExpr() {
 String name = 'Yamix';

 String userName = name ?? "Guest User";
 print(userName);
}
</code>```

can i get some help please :)

答:
Dart, by default, will assume any variable you've declared can never be null. You won't be able to assign null to a variable, and at runtime it will throw an error. It will also complain if you try to treat a non-nullable variable like it could be null, which is what you're doing with '??'.

You can use the ? after a variable's type to tell Dart that your variable will accept null values. ?? allows us to handle null values without writing extra lines of code

In short, x = y ?? z can be described as

If the left operand (y) is null, then assign the right operand (z) ie.

```<code>void example(String? myString) {
  String? y = myString;
  String z = 'spam';

  var x = y ?? z;
  print(x);
}

void main() {
  example('hello!');
  example(null);
}

// Output:
// hello!
// spam

</code>```

Notice that I've added '?' after 'String' on the 2nd line, letting Dart know that 'y' could be null. This prevents me getting an error later in the code where I try to use a null-aware operator (??) to assign it to 'x'.

I hope this helped give you some background beyond just resolving your issue! :)

Short medium article on Null-aware operators in Dart

Body:
so i was learning about SWITCH and CASE Statements in dart language, in the course he explains the code but he don't get an error while i get one.

the error i get
: Warning: Operand of null-aware operation '??' has type 'String' which excludes null.
String ``userName = name ?? "Guest User";

My Code is

void learnCondExpr() {
 String name = 'Yamix';

 String userName = name ?? "Guest User";
 print(userName);
}

can i get some help please :)

Body:
Dart, by default, will assume any variable you've declared can never be null. You won't be able to assign null to a variable, and at runtime it will throw an error. It will also complain if you try to treat a non-nullable variable like it could be null, which is what you're doing with '??'.

You can use the ? after a variable's type to tell Dart that your variable will accept null values. ?? allows us to handle null values without writing extra lines of code

In short, x = y ?? z can be described as

If the left operand (y) is null, then assign the right operand (z) ie.

void example(String? myString) {
  String? y = myString;
  String z = 'spam';

  var x = y ?? z;
  print(x);
}

void main() {
  example('hello!');
  example(null);
}

// Output:
// hello!
// spam

Notice that I've added '?' after 'String' on the 2nd line, letting Dart know that 'y' could be null. This prevents me getting an error later in the code where I try to use a null-aware operator (??) to assign it to 'x'.

I hope this helped give you some background beyond just resolving your issue! :)

Short medium article on Null-aware operators in Dart


问:
Tycho integration test are not run (but Unit tests are..)
I have a multi module project with a plugin and fragment to test this plugin.
The build is done through maven/tycho. Maven v.3.8.4 and Tycho v2.6.0.

In the fragment I have 3 Unit and 1 Integration test, in the test folder:

```<code>test
   ├── CoreTestConstants.java
   ├── CoreUtils2Test.java
   ├── CoreUtils3Test.java
   ├── CoreUtilsIT.java
   └── CoreUtilsTest.java
</code>```

This is the pom of the fragment plugin:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>com.tycho.rcp.core.test</artifactId>
     <version>0.2.4-SNAPSHOT</version>
     <packaging>eclipse-test-plugin</packaging>

     <parent>
          <groupId>com.tycho</groupId>
          <artifactId>com.tycho.mps</artifactId>
          <version>0.3.4-SNAPSHOT</version>
          <relativePath>..</relativePath>
     </parent>

     <build>
          <sourceDirectory>src</sourceDirectory>
          <plugins>
               <plugin>
                    <groupId>org.eclipse.tycho</groupId>
                    <artifactId>tycho-surefire-plugin</artifactId>
                    <executions>
                         <execution>
                              <id>it-test</id>
                              <phase>integration-test</phase>
                              <goals>
                                   <goal>integration-test</goal>
                              </goals>
                         </execution>
                    </executions>

                    <configuration>
                         <testSourceDirectory>src</testSourceDirectory>
                         <testClassesDirectory>target/classes</testClassesDirectory>

                         <!-- workspace directory -->
                         <osgiDataDirectory>${mas.test.workspace}</osgiDataDirectory>

                         <!-- system properties -->
                         <systemProperties>
                              <mas.test.archive_location>${mas.test.archive_location}</mas.test.archive_location>
                         </systemProperties>

                         <!-- add slf4j implementation dependency from Orbit -->
                         <dependencies>
                              <dependency>
                                   <groupId>org.eclipse.orbit.bundles</groupId>
                                   <artifactId>ch.qos.logback.slf4j</artifactId>
                                   <version>1.1.2</version>
                                   <type>eclipse-plugin</type>
                              </dependency>
                         </dependencies>
                    </configuration>
               </plugin>
          </plugins>
     </build>
</project>
</code>```

The tycho-surefire-plugin is enabled in pluginManagement of the parent project:

```<code><plugin>
   <groupId>org.eclipse.tycho</groupId>
   <artifactId>tycho-surefire-plugin</artifactId>
   <version>${tycho.version}</version>
</plugin>
</code>```

The 3 Unit test are executed correctly, but the IT test is never run!
This is the relevant part of the output, when I run mvn clean verify inside the fragment project:

```<code>[INFO] --- tycho-surefire-plugin:2.6.0:test (default-test) @ com.marchesini.mas.rcp.core.test ---
[INFO] Executing Test Runtime with timeout 0, logs (if any) will be placed at: /home/gionata/runtime-EclipseApplication/.metadata/.log
[INFO] Command line:
    [/usr/lib/jvm/java-11-openjdk-11.0.9.11-0.fc31.x86_64/bin/java, -Dosgi.noShutdown=false, -Dosgi.os=linux, -Dosgi.ws=gtk, -Dosgi.arch=x86_64, -Dosgi.clean=true, -Dmas.test.archive_location=/home/gionata/ARCHIVIO.BLK, -jar, /home/gionata/.m2/repository/p2/osgi/bundle/org.eclipse.equinox.launcher/1.5.100.v20180827-1352/org.eclipse.equinox.launcher-1.5.100.v20180827-1352.jar, -data, /home/gionata/runtime-EclipseApplication, -install, /home/gionata/Workspace_Eclipse_Maven/MAS/MPS/com.marchesini.mas.rcp.core.test/target/work, -configuration, /home/gionata/Workspace_Eclipse_Maven/MAS/MPS/com.marchesini.mas.rcp.core.test/target/work/configuration, -application, org.eclipse.tycho.surefire.osgibooter.headlesstest, -testproperties, /home/gionata/Workspace_Eclipse_Maven/MAS/MPS/com.marchesini.mas.rcp.core.test/target/surefire.properties]
Running com.marchesini.mas.rcp.core.test.CoreUtils2Test
Logger launcher start...4
2022-02-05 18:36:11,221 DEBUG [main]: CHECKSUM 2 = 340351cde832c00505c88f3fe1a962d4
2022-02-05 18:36:11,442 DEBUG [main]: Workspace = /home/gionata/runtime-EclipseApplication
2022-02-05 18:36:11,442 DEBUG [main]: Archive location = /home/gionata/ARCHIVIO.BLK
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.569 s - in com.marchesini.mas.rcp.core.test.CoreUtils2Test
testCoreUtils2(com.marchesini.mas.rcp.core.test.CoreUtils2Test)  Time elapsed: 0.226 s
Running com.marchesini.mas.rcp.core.test.CoreUtilsTest

#################################################################################
REPORT
CHECKSUM = 340351cde832c00505c88f3fe1a962d4

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 s - in com.marchesini.mas.rcp.core.test.CoreUtilsTest
testCoreUtils(com.marchesini.mas.rcp.core.test.CoreUtilsTest)  Time elapsed: 0.002 s
Running com.marchesini.mas.rcp.core.test.CoreUtils3Test
Logger launcher start...4
2022-02-05 18:36:11,537 DEBUG [main]: CHECKSUM 3 = 340351cde832c00505c88f3fe1a962d4
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.024 s - in com.marchesini.mas.rcp.core.test.CoreUtils3Test
testCoreUtils3(com.marchesini.mas.rcp.core.test.CoreUtils3Test)  Time elapsed: 0.001 s

Results:

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

[INFO] All tests passed!
[INFO]
[INFO] --- tycho-surefire-plugin:2.6.0:integration-test (it-test) @ com.marchesini.mas.rcp.core.test ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
</code>```

The execution it-test simply doesn't run anything! I have been wasting hours on this....

Thankyou for any help.

答:
First of all, you shouldn't add any specific configuration if you follow the default conventions. Moreover, parameters like <testSourceDirectory>src</testSourceDirectory> are not read by the tycho surefire plugin. Moreover, there's no need to create products or features for what you need. The reason why it's not working it's because of a bug:
https://github.com/eclipse/tycho/issues/643

On a side note, I've updated the RELEASE notes
https://github.com/eclipse/tycho/pull/641
trying to document better the rationale behind the new goal (but, again, it does not work due to a bug)

Body:
I have a multi module project with a plugin and fragment to test this plugin.
The build is done through maven/tycho. Maven v.3.8.4 and Tycho v2.6.0.

In the fragment I have 3 Unit and 1 Integration test, in the test folder:

test
   ├── CoreTestConstants.java
   ├── CoreUtils2Test.java
   ├── CoreUtils3Test.java
   ├── CoreUtilsIT.java
   └── CoreUtilsTest.java

This is the pom of the fragment plugin:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>com.tycho.rcp.core.test</artifactId>
     <version>0.2.4-SNAPSHOT</version>
     <packaging>eclipse-test-plugin</packaging>

     <parent>
          <groupId>com.tycho</groupId>
          <artifactId>com.tycho.mps</artifactId>
          <version>0.3.4-SNAPSHOT</version>
          <relativePath>..</relativePath>
     </parent>

     <build>
          <sourceDirectory>src</sourceDirectory>
          <plugins>
               <plugin>
                    <groupId>org.eclipse.tycho</groupId>
                    <artifactId>tycho-surefire-plugin</artifactId>
                    <executions>
                         <execution>
                              <id>it-test</id>
                              <phase>integration-test</phase>
                              <goals>
                                   <goal>integration-test</goal>
                              </goals>
                         </execution>
                    </executions>

                    <configuration>
                         <testSourceDirectory>src</testSourceDirectory>
                         <testClassesDirectory>target/classes</testClassesDirectory>

                         <osgiDataDirectory>${mas.test.workspace}</osgiDataDirectory>

                         <systemProperties>
                              <mas.test.archive_location>${mas.test.archive_location}</mas.test.archive_location>
                         </systemProperties>

                         <dependencies>
                              <dependency>
                                   <groupId>org.eclipse.orbit.bundles</groupId>
                                   <artifactId>ch.qos.logback.slf4j</artifactId>
                                   <version>1.1.2</version>
                                   <type>eclipse-plugin</type>
                              </dependency>
                         </dependencies>
                    </configuration>
               </plugin>
          </plugins>
     </build>
</project>

The tycho-surefire-plugin is enabled in pluginManagement of the parent project:

<plugin>
   <groupId>org.eclipse.tycho</groupId>
   <artifactId>tycho-surefire-plugin</artifactId>
   <version>${tycho.version}</version>
</plugin>

The 3 Unit test are executed correctly, but the IT test is never run!
This is the relevant part of the output, when I run mvn clean verify inside the fragment project:

[INFO] --- tycho-surefire-plugin:2.6.0:test (default-test) @ com.marchesini.mas.rcp.core.test ---
[INFO] Executing Test Runtime with timeout 0, logs (if any) will be placed at: /home/gionata/runtime-EclipseApplication/.metadata/.log
[INFO] Command line:
    [/usr/lib/jvm/java-11-openjdk-11.0.9.11-0.fc31.x86_64/bin/java, -Dosgi.noShutdown=false, -Dosgi.os=linux, -Dosgi.ws=gtk, -Dosgi.arch=x86_64, -Dosgi.clean=true, -Dmas.test.archive_location=/home/gionata/ARCHIVIO.BLK, -jar, /home/gionata/.m2/repository/p2/osgi/bundle/org.eclipse.equinox.launcher/1.5.100.v20180827-1352/org.eclipse.equinox.launcher-1.5.100.v20180827-1352.jar, -data, /home/gionata/runtime-EclipseApplication, -install, /home/gionata/Workspace_Eclipse_Maven/MAS/MPS/com.marchesini.mas.rcp.core.test/target/work, -configuration, /home/gionata/Workspace_Eclipse_Maven/MAS/MPS/com.marchesini.mas.rcp.core.test/target/work/configuration, -application, org.eclipse.tycho.surefire.osgibooter.headlesstest, -testproperties, /home/gionata/Workspace_Eclipse_Maven/MAS/MPS/com.marchesini.mas.rcp.core.test/target/surefire.properties]
Running com.marchesini.mas.rcp.core.test.CoreUtils2Test
Logger launcher start...4
2022-02-05 18:36:11,221 DEBUG [main]: CHECKSUM 2 = 340351cde832c00505c88f3fe1a962d4
2022-02-05 18:36:11,442 DEBUG [main]: Workspace = /home/gionata/runtime-EclipseApplication
2022-02-05 18:36:11,442 DEBUG [main]: Archive location = /home/gionata/ARCHIVIO.BLK
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.569 s - in com.marchesini.mas.rcp.core.test.CoreUtils2Test
testCoreUtils2(com.marchesini.mas.rcp.core.test.CoreUtils2Test)  Time elapsed: 0.226 s
Running com.marchesini.mas.rcp.core.test.CoreUtilsTest

#################################################################################
REPORT
CHECKSUM = 340351cde832c00505c88f3fe1a962d4

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 s - in com.marchesini.mas.rcp.core.test.CoreUtilsTest
testCoreUtils(com.marchesini.mas.rcp.core.test.CoreUtilsTest)  Time elapsed: 0.002 s
Running com.marchesini.mas.rcp.core.test.CoreUtils3Test
Logger launcher start...4
2022-02-05 18:36:11,537 DEBUG [main]: CHECKSUM 3 = 340351cde832c00505c88f3fe1a962d4
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.024 s - in com.marchesini.mas.rcp.core.test.CoreUtils3Test
testCoreUtils3(com.marchesini.mas.rcp.core.test.CoreUtils3Test)  Time elapsed: 0.001 s

Results:

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

[INFO] All tests passed!
[INFO]
[INFO] --- tycho-surefire-plugin:2.6.0:integration-test (it-test) @ com.marchesini.mas.rcp.core.test ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

The execution it-test simply doesn't run anything! I have been wasting hours on this....

Thankyou for any help.


问:
How do I create accumulated bandwidth usages in RRDtool (ie. GB's per month down)?
The following data comes from a mobile phone provider, it's a list of kb's downloaded at a certain time, usually on a per minute basis.

It's not the average, not the max, but the total of that time interval, which allows to track the data consumption precisely. These graphs were made with PIL, and instead of showing spikes to indicate a large data consumption, large steps can be seen, which is much more revealing, because it doesn't just tell "much happened here", but "exactly this much happened here". For example second graph Sat 10 at night 100mb. A rate-change graph wouldn't be as informative.

I'm also trying to find a way to do this with rrd.

I was mislead when using the COUNTER to track my networks data usage into thinking that I would be able to precisely compute the monthly/weekly accumulated data usage, but now it turned out to be a wrong assumption.

How I store my data in rrd in order to be able to easily generate graphs like below? Would that be by using ABSOLUTE and before updating it I would subtract the previous insertion value? Would that be precise down to the byte when checking the monthly usage?

答:
This is a common question which very few answers online but I first encountered a method to do this with RRD in 2009.

The DS type to use is a GAUGE and in your update script manually handle resetting the GAUGE to 0 at the start of the month for monthly usage graphs.

Then came along RRDTool's ' mrtg-traffic-sum ' package.
More recently I've had to monitor both traffic bandwidth and traffic volume so I created a standard RRD for that first and confirmed that was working.

So with the bandwidth being sampled (captured to the RRD), then use the mrtg-traffic-sum tool to generate the stat's needed as in the example below then pump them into another RRD created with just the GAUGE DS type and just LAST (no need for MIN/AVG/MAX).

This allows using RRDs to collect both traffic bandwidth as well as monthly traffic volumes / traffic quota limits.

```<code>root@server:~# /usr/bin/mrtg-traffic-sum --range=current --units=MB /etc/mrtg/R4.cfg
Subject: Traffic total for '/etc/mrtg/R4.cfg' (1.9) 2022/02

Start: Tue Feb  1 01:00:00 2022
End:   Tue Mar  1 00:59:59 2022
Interface                                    In+Out in MB
------------------------------------------------------------------------------
eth0                                                    0
eth1                                                14026
eth2                                                 5441
eth3                                                    0
eth4                                                15374
switch0.5                                           12024
switch0.19                                            151
switch0.49                                              1
switch0.51                                              0
switch0.92                                           2116
root@server:~#
</code>```

From mrtg-traffic-sum just write up a script that will populate your 2nd rrd with these values & presto you have a traffic volume / quota graph also.

ContentLicense: CC BY-SA 3.0

Body:
This is a common question which very few answers online but I first encountered a method to do this with RRD in 2009.

The DS type to use is a GAUGE and in your update script manually handle resetting the GAUGE to 0 at the start of the month for monthly usage graphs.

Then came along RRDTool's ' mrtg-traffic-sum ' package.
More recently I've had to monitor both traffic bandwidth and traffic volume so I created a standard RRD for that first and confirmed that was working.

So with the bandwidth being sampled (captured to the RRD), then use the mrtg-traffic-sum tool to generate the stat's needed as in the example below then pump them into another RRD created with just the GAUGE DS type and just LAST (no need for MIN/AVG/MAX).

This allows using RRDs to collect both traffic bandwidth as well as monthly traffic volumes / traffic quota limits.

root@server:~# /usr/bin/mrtg-traffic-sum --range=current --units=MB /etc/mrtg/R4.cfg
Subject: Traffic total for '/etc/mrtg/R4.cfg' (1.9) 2022/02

Start: Tue Feb  1 01:00:00 2022
End:   Tue Mar  1 00:59:59 2022
Interface                                    In+Out in MB
------------------------------------------------------------------------------
eth0                                                    0
eth1                                                14026
eth2                                                 5441
eth3                                                    0
eth4                                                15374
switch0.5                                           12024
switch0.19                                            151
switch0.49                                              1
switch0.51                                              0
switch0.92                                           2116
root@server:~#

From mrtg-traffic-sum just write up a script that will populate your 2nd rrd with these values & presto you have a traffic volume / quota graph also.


问:
Is there any way we can import one specific lerna package from another repo
Newbie question - Not sure whether I am doing anything wrong. Is there a way to import a specific package from a lerna repository?

design system repo

```<code>// ./lerna.js
{
  "packages": [
    "packages/Button",
    "..."
  ],
}

// ./packages/Button/package.json
{
  name: "@namespace/button"
}
</code>```

application repo

```<code>// ./package.json
{
  "dependencies": {
    "@namespace/button": "git+ssh://git@github.com/design-system-private/repo.git",
  }
}

</code>```

It seems to download the root design system repo but not the button.

答:
You need to version the internal package that you want to use.</p>
```<code>    // ./package.json
    {
      "dependencies": {
        "@namespace/button": "1.0.0",
      }
    }

    // ./lerna.js
    {
      "packages": [
        "packages/Button",
        "..."
      ],
    }

    // ./packages/Button/package.json
    {
      name: "@namespace/button",
      "version": "1.0.0",
    }
</code>```

Body:
Newbie question - Not sure whether I am doing anything wrong. Is there a way to import a specific package from a lerna repository?

design system repo

// ./lerna.js
{
  "packages": [
    "packages/Button",
    "..."
  ],
}

// ./packages/Button/package.json
{
  name: "@namespace/button"
}

application repo

// ./package.json
{
  "dependencies": {
    "@namespace/button": "git+ssh://git@github.com/design-system-private/repo.git",
  }
}

It seems to download the root design system repo but not the button.

Body:
You need to version the internal package that you want to use.

    // ./package.json
    {
      "dependencies": {
        "@namespace/button": "1.0.0",
      }
    }

    // ./lerna.js
    {
      "packages": [
        "packages/Button",
        "..."
      ],
    }

    // ./packages/Button/package.json
    {
      name: "@namespace/button",
      "version": "1.0.0",
    }


问:
ORA-00906: missing left parenthesis
```<code>create table widep(
 cac NUMBER,
 ddate DATE,
 dtime TIMESTAMP,
 type VARCHAR2,
 amount NUMBER(10,2),
 constraint qwe foreign key(cac) references cust(cac)
)
</code>```

答:
It is mandatory to give a size to VARCHAR2. VARCHAR2 generally takes 4000 bytes(standard) or can take up to 32767 bytes if it is extended.

We have 2 options Byte or Char.

BYTE indicates that the column will have byte length semantics.
CHAR indicates that the column will have character semantics.
*Source: https://docs.oracle.com/database/121/SQLRF/sql_elements001.htm#SQLRF30020

Title: ORA-00906: missing left parenthesis


问:
Typescript Generics and not assignable error
I seem to have a understanding problem of how typescript types works. I have the following situation. I have a class which provides a function which can be overriden:

    /**
     * The current log method. Can be overridden to redirect output.
     */
    log: (...args: any[]) => void;
```
<p>I have the following type</p>
<pre class="lang-js prettyprint-override"><code>type AzureTransport = {
  (...args: any[]): void
}
</code>```

No I have a kind of facade which looks like:

export interface DataChampLogger {
  info(...args: any[]): void
  error(...args: any[]): void
  warn(...args: any[]): void
  verbose(...args: any[]): void
  setLogLevel(level: DataChampLogLevel): void
  setTransport<T>(transport: T): void

// implementation
class .... {
 setTransport<AzureTransport>(transport: AzureTransport): void {
    AzureLogger.log = transport
  }
}
}
```
<p>this does not work, I get the following error <code>Type 'AzureTransport' is not assignable to type '(...args: any[]) => void'.ts(2322)</code></p>
<p>when I refactor the code to:</p>
<pre class="lang-js prettyprint-override"><code>export interface DataChampLogger {
  info(...args: any[]): void
  error(...args: any[]): void
  warn(...args: any[]): void
  verbose(...args: any[]): void
  setLogLevel(level: DataChampLogLevel): void
  setTransport(transport: unknown): void

// implementation
class .... {
 setTransport(transport: AzureTransport): void {
    AzureLogger.log = transport
  }
}
}
</code>```

everything works fine, but it is not really clear to why I get an error in the first version of the implementation.

[edit] Playground Link

Thanks for your time and help

Regards
Mathias

答:
It's because Typescript cannot know that the AzureTransport type that you use in the class will be assignable to T, since T could be something else.

You can add a generic constraint like that:

```<code>export interface DataChampLogger {
  setTransport<T extends AzureTransport>(transport: T): void; // "T extends AzureTransport" is the constraint
}

class MyClass implements DataChampLogger {
  setTransport(transport: AzureTransport): void {
  }
}
</code>```

Alternatively, you can move the generic to the interface itself, like that:

```<code>export interface DataChampLogger<T> // generic is here  {
  setTransport(transport: T): void;
}

class MyClass implements DataChampLogger<AzureTransport> {
  setTransport(transport: AzureTransport): void { // no complaints since T is AzureTransport
  }
}

</code>```

On a side note, this

```<code>type AzureTransport = {
  (...args: any[]): void
}
</code>```

is the same as

```<code>type AzureTransport = (...args: any[]) => void;
</code>```

You don't need the curly brackets.

Body:
I seem to have a understanding problem of how typescript types works. I have the following situation. I have a class which provides a function which can be overriden:

    /**
     * The current log method. Can be overridden to redirect output.
     */
    log: (...args: any[]) => void;

I have the following type

type AzureTransport = {
  (...args: any[]): void
}

No I have a kind of facade which looks like:

export interface DataChampLogger {
  info(...args: any[]): void
  error(...args: any[]): void
  warn(...args: any[]): void
  verbose(...args: any[]): void
  setLogLevel(level: DataChampLogLevel): void
  setTransport<T>(transport: T): void

// implementation
class .... {
 setTransport<AzureTransport>(transport: AzureTransport): void {
    AzureLogger.log = transport
  }
}
}

this does not work, I get the following error Type 'AzureTransport' is not assignable to type '(...args: any[]) => void'.ts(2322)

when I refactor the code to:

export interface DataChampLogger {
  info(...args: any[]): void
  error(...args: any[]): void
  warn(...args: any[]): void
  verbose(...args: any[]): void
  setLogLevel(level: DataChampLogLevel): void
  setTransport(transport: unknown): void

// implementation
class .... {
 setTransport(transport: AzureTransport): void {
    AzureLogger.log = transport
  }
}
}

everything works fine, but it is not really clear to why I get an error in the first version of the implementation.

[edit] <a href="https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAbzgQQF4FcoFMAyEDm+WUANHAMbYCGMWAwgDbBYB2MehxZAzluwTiwA3LAzJpMuAcNFwAvnABmUCCDgByAAJUM2APQMCRKOoCwAKCwAPSLDgwAnmCxwAIjSp0AFlXAdBIgxwALwaACZYAEbo+OpwAD4aIlCRELxxierALIoQGRoA7lRQLNmxCRrEKiYWFnoAVHAc+GVKVORUEXD1ehbWtvDZtFCK7S7uMJ4+fkbEiLXmcHC8MAAqUFQs3AMAPKsAfAAUMBtbAwBccKsAlJdCEMBhFkt6est865vb0DDHp9+wS7oFgAaxYEAKLFucHujzgr3sXmA3DgYQgWBRBWgIIscgWDXqz0aAEl4GAoEMUTAvC5ivh0CBWDAqRBES5yBAthAGFgyByWCJSptyC5GdSIGElNA4IYOkEIoEIGBGWwiXBNGBir5EJsHABtAC6CjpKIAtHBdYaib1LDYfhROdx4BJsHRHdysJ8zvbQocAHQBk2XS0G6GwyXBfbzRYOrk8v2GfD+wNQfDca64hb9e2OZwoXSe-4DELRpbJv1Bi0sfWhu4PJ7mPHmPp2uzkBhUbgoiZTXxgF1SThQOCgMA8lXMtwebx95pzBDPOAAYkTxkuA7nUEXBMX3V3PUX-KdUHQ5Bg0EOLF8GM1Isux7K11LS0RyL9K9mw9ClCwNHoTCZTdL2vbYxgzGMmxeepCRjbo4DoTY4EiFx0F4SVzzgCBkgpLpqRcCJRnQBh4BOL5iwKJFyC8EcUQAAydCIoCgWi4FQrBFCIoJcmHWUqHlGRDGVJl93Vaw+x5OARNo6SACsqCETtKGAMAYBEo94FXOZQhYLACinSYZ3ADdP0OdQwgZEAHHAl9Gk0qA-RWL0AV+ctKxDMN6xCKMF1gl8liPD0EwIVzU3TXcljkJ9XgwxN7FZAKeSk6SRI1LU1FI707Dw+wixzVlj1-NRE24FLeBcBBNCYUF80kN040LMifkgpYD2bGNHNy2AdgHJyBiODLnPXAtep+Dy4R8vzjKHIL8BLAaBkXJsFlxIA" rel="nofollow noreferrer">Playground Link

Thanks for your time and help

Regards
Mathias

Body:
It's because Typescript cannot know that the AzureTransport type that you use in the class will be assignable to T, since T could be something else.

You can add a generic constraint like that:

export interface DataChampLogger {
  setTransport<T extends AzureTransport>(transport: T): void; // "T extends AzureTransport" is the constraint
}

class MyClass implements DataChampLogger {
  setTransport(transport: AzureTransport): void {
  }
}

Alternatively, you can move the generic to the interface itself, like that:

export interface DataChampLogger<T> // generic is here  {
  setTransport(transport: T): void;
}

class MyClass implements DataChampLogger<AzureTransport> {
  setTransport(transport: AzureTransport): void { // no complaints since T is AzureTransport
  }
}

On a side note, this

type AzureTransport = {
  (...args: any[]): void
}

is the same as

type AzureTransport = (...args: any[]) => void;

You don't need the curly brackets.


问:
How to split words into different columns in dataframe?
I am new to coding , recently started learning to code. Currently I am stuck in the process to split a column. Please help me

I have this dataframe

```<code>data = ['TOOK22JAN1515100HG','BOOK22FEB1643200GH','TOOK22MAR1742200HG']
df= pd.DataFrame(data)
</code>```

and I want to split it into

```<code>0   TOOK22JAN1515100HG       TOOK    22-01-15   15100  HG
1   BOOK22FEB1643200GH       BOOK    22-02-16   43200  GH
2   TOOK22MAR1742200HG       TOOK    22-03-17   42200  HG
</code>```

Really appreciate for taking your time and answering to my problem.

PS: this is just an example of option symbol which is combination of Index + date + strike + type (stock market)

答:
Use str.extract to explode your string:

```<code>pattern = r'(?P<id>[A-Z]{4})(?P<date>\w{7})(?P<val>\d+)(?P<misc>[A-Z]{2})'

df = df.join(df[0].str.extract(pattern))

df['date'] = pd.to_datetime(df['date'])
df['val'] = df['val'].astype(int)
print(df)

# Output
                    0    id       date    val misc
0  TOOK22JAN1515100HG  TOOK 2015-01-22  15100   HG
1  BOOK22FEB1643200GH  BOOK 2016-02-22  43200   GH
2  TOOK22MAR1742200HG  TOOK 2017-03-22  42200   HG
</code>```

Body:
I am new to coding , recently started learning to code. Currently I am stuck in the process to split a column. Please help me

I have this dataframe

data = ['TOOK22JAN1515100HG','BOOK22FEB1643200GH','TOOK22MAR1742200HG']
df= pd.DataFrame(data)

and I want to split it into

0   TOOK22JAN1515100HG       TOOK    22-01-15   15100  HG
1   BOOK22FEB1643200GH       BOOK    22-02-16   43200  GH
2   TOOK22MAR1742200HG       TOOK    22-03-17   42200  HG

Really appreciate for taking your time and answering to my problem.

PS: this is just an example of option symbol which is combination of Index + date + strike + type (stock market)

Body:
Use str.extract to explode your string:

pattern = r'(?P<id>[A-Z]{4})(?P<date>\w{7})(?P<val>\d+)(?P<misc>[A-Z]{2})'

df = df.join(df[0].str.extract(pattern))

df['date'] = pd.to_datetime(df['date'])
df['val'] = df['val'].astype(int)
print(df)

# Output
                    0    id       date    val misc
0  TOOK22JAN1515100HG  TOOK 2015-01-22  15100   HG
1  BOOK22FEB1643200GH  BOOK 2016-02-22  43200   GH
2  TOOK22MAR1742200HG  TOOK 2017-03-22  42200   HG


问:
terraform the db instance and ec2 security group are in different vpcs
i am trying to create a vpc with public and private subnet along with Aurora mysql cluster and instance in same vpc with custom security group for RDS.

i've created vpc (public/private subnet, custom security group) in a module. also aurora-mysql in different module.

My vpc configuration in a module file

```<code>resource "aws_vpc" "main" {
    cidr_block       = "${var.vpc_cidr}"
    instance_tenancy = "${var.tenancy}"
    enable_dns_support = "true"
    enable_dns_hostnames = "true"
   tags {
      Name = "${var.tag_name}"
   }
}

resource "aws_subnet" "main-public-1" {
   vpc_id     = "${var.vpc_id}"
   cidr_block = "${var.subnet_cidr_1}"
   availability_zone = "${var.region}a"
   map_public_ip_on_launch = true
   tags {
       Name = "${var.tag_name}-subnet1"
    }
}

resource "aws_subnet" "main-private-1" {
    count      = "${var.create_private_subnet}"
    vpc_id     = "${var.vpc_id}"
    cidr_block = "${var.private_subnet_cidr_1}"
    map_public_ip_on_launch = false
    availability_zone = "${var.region}a"

   tags {
        Name = "${var.tag_name}-private-subnet1"
    }
}
resource "aws_subnet" "main-private-2" {
    count      = "${var.create_private_subnet}"
    vpc_id     = "${var.vpc_id}"
    cidr_block = "${var.private_subnet_cidr_2}"
    map_public_ip_on_launch = false
    availability_zone = "${var.region}b"

    tags {
        Name = "${var.tag_name}-private-subnet2"
    }
}

resource "aws_security_group" "aurora-sg" {
  name   = "aurora-security-group"
  vpc_id = "${var.vpc_id}"
  ingress {
    protocol    = "tcp"
    from_port   = 0
    to_port     = 65535
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    protocol    = -1
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }
}
</code>```

My RDS configuration in a module file

```<code>resource "aws_rds_cluster" "cluster" {
  cluster_identifier     = "${var.cluster_name}"
  engine                 = "aurora-mysql"
  database_name          = "sample_rds"
  master_username        = "${var.username}"
  master_password        = "${var.password}"
  vpc_security_group_ids = ["${aws_security_group.aurora-sg.id}"]
  skip_final_snapshot    = true
}

resource "aws_rds_cluster_instance" "cluster_instances" {
  identifier         = "${var.cluster_name}-instance"
  cluster_identifier = "${aws_rds_cluster.cluster.id}"
  instance_class     = "${var.instance_class}"
  publicly_accessible = "${var.publicly_accessible}"
  db_subnet_group_name    =
        "${aws_db_subnet_group.aurora_subnet_group.id}"
}

resource "aws_db_subnet_group" "aurora_subnet_group" {
  name       = "tf-rds-${var.cluster_name}"
  subnet_ids = ["${var.subnets}"]

  tags {
    Name = "tf-rds-${var.cluster_name}"
  }
}
</code>```

My main terraform script. i have passed variables to RDS module like vpc_id, db username and password,private subnet ids and security group id

```<code>module "aurora_mysql" {
  source      = "../modules/rds-aurora"

  vpc_id              = "${module.my_vpc.vpc_id}"
  publicly_accessible = true
  instance_class      = "db.t2.medium"
  username            = "${var.db_username}"
  password            = "${var.db_password}"
  subnets             =
 ["${module.my_vpc.subnet_id_1[1]}","${module.my_vpc.subnet_id_1[2]}"]
  security_group_ids = "${module.my_vpc.vpc_rds_sg_id}"
}
</code>```

When i try to apply the configuration vpc created successfully with subnet and security group but get the error
Error creating DB Instance: InvalidParameterCombination: DB instance and EC2 security group are in different VPC

My RDS instance gets created in the default VPC even though i am passing new vpc private subnet ids and custom security group id.

答:
You need to specify the same aws_db_subnet_group_name for both aws_rds_cluster and aws_rds_cluster_instance.
Your configuration is missing the db_subnet_group_name specification for aws_rds_cluster.</p>

Body:
i am trying to create a vpc with public and private subnet along with Aurora mysql cluster and instance in same vpc with custom security group for RDS.

i've created vpc (public/private subnet, custom security group) in a module. also aurora-mysql in different module.

My vpc configuration in a module file

resource "aws_vpc" "main" {
    cidr_block       = "${var.vpc_cidr}"
    instance_tenancy = "${var.tenancy}"
    enable_dns_support = "true"
    enable_dns_hostnames = "true"
   tags {
      Name = "${var.tag_name}"
   }
}

resource "aws_subnet" "main-public-1" {
   vpc_id     = "${var.vpc_id}"
   cidr_block = "${var.subnet_cidr_1}"
   availability_zone = "${var.region}a"
   map_public_ip_on_launch = true
   tags {
       Name = "${var.tag_name}-subnet1"
    }
}

resource "aws_subnet" "main-private-1" {
    count      = "${var.create_private_subnet}"
    vpc_id     = "${var.vpc_id}"
    cidr_block = "${var.private_subnet_cidr_1}"
    map_public_ip_on_launch = false
    availability_zone = "${var.region}a"

   tags {
        Name = "${var.tag_name}-private-subnet1"
    }
}
resource "aws_subnet" "main-private-2" {
    count      = "${var.create_private_subnet}"
    vpc_id     = "${var.vpc_id}"
    cidr_block = "${var.private_subnet_cidr_2}"
    map_public_ip_on_launch = false
    availability_zone = "${var.region}b"

    tags {
        Name = "${var.tag_name}-private-subnet2"
    }
}

resource "aws_security_group" "aurora-sg" {
  name   = "aurora-security-group"
  vpc_id = "${var.vpc_id}"
  ingress {
    protocol    = "tcp"
    from_port   = 0
    to_port     = 65535
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    protocol    = -1
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }
}

My RDS configuration in a module file

resource "aws_rds_cluster" "cluster" {
  cluster_identifier     = "${var.cluster_name}"
  engine                 = "aurora-mysql"
  database_name          = "sample_rds"
  master_username        = "${var.username}"
  master_password        = "${var.password}"
  vpc_security_group_ids = ["${aws_security_group.aurora-sg.id}"]
  skip_final_snapshot    = true
}

resource "aws_rds_cluster_instance" "cluster_instances" {
  identifier         = "${var.cluster_name}-instance"
  cluster_identifier = "${aws_rds_cluster.cluster.id}"
  instance_class     = "${var.instance_class}"
  publicly_accessible = "${var.publicly_accessible}"
  db_subnet_group_name    =
        "${aws_db_subnet_group.aurora_subnet_group.id}"
}

resource "aws_db_subnet_group" "aurora_subnet_group" {
  name       = "tf-rds-${var.cluster_name}"
  subnet_ids = ["${var.subnets}"]

  tags {
    Name = "tf-rds-${var.cluster_name}"
  }
}

My main terraform script. i have passed variables to RDS module like vpc_id, db username and password,private subnet ids and security group id

module "aurora_mysql" {
  source      = "../modules/rds-aurora"

  vpc_id              = "${module.my_vpc.vpc_id}"
  publicly_accessible = true
  instance_class      = "db.t2.medium"
  username            = "${var.db_username}"
  password            = "${var.db_password}"
  subnets             =
 ["${module.my_vpc.subnet_id_1[1]}","${module.my_vpc.subnet_id_1[2]}"]
  security_group_ids = "${module.my_vpc.vpc_rds_sg_id}"
}

When i try to apply the configuration vpc created successfully with subnet and security group but get the error
Error creating DB Instance: InvalidParameterCombination: DB instance and EC2 security group are in different VPC

My RDS instance gets created in the default VPC even though i am passing new vpc private subnet ids and custom security group id.


问:
How avoid __res_querydomain - sendmail compilation problem
During sendmail compilation on Debian (raspberry) I've encountered problem with __res_querydomain  undefinded funtion.
How avoid it?</p>

答:
My mistake

there should be pointed directory of libresolv.

In my case it is the same as glib.


问:
The same class name in two different css files conflict in ReactJS
I have a component folder and two different components in it, every component has its own css file with the link in its jsx file.
:

when I use a the same class name in them it affects the other component too! While the other component has its own css file and link.
Why is that?

For example:
In both components I have a class named: "PlayerPhoto"
when I change its height and width, the photo in other components (with separate css file but the same class name) would change too!

答:
Your app.js file may has the property for the className="PlayerPhoto", make sure that your app.css has not the same className if there were, then it overwrite your component base css.
You can also use inline css, to overcome this type of issues.</p>


问:
how can i update a specific object property within an array in firebase
im having trouble updating the quantity property in my angular-firebase project

```<code>chosenMeal(meal,price,quantity){
  for (let i = 0; i < this.order.length; i++) {
        const element = this.order[i];
        if(element.meal != meal){
          this.db.collection('tables').doc(this.table.propertyId).update({order:({meal,price,quantity})})
        }else{
        // my question
  }
}
</code>```

so the logic is like this if the chosen meal isn't in the order array then add it to the order array in firebase, else if the meal exists on the order array just increment the quantity, i don't know how to update just the quantity in the order object in firebase, or i don't know how to access only the one property in a firebase object

答:
Update the array locally and after that update it in your database.

chosenMeal(meal,price,quantity){
  for (let i = 0; i < this.order.length; i++) {
        const element = this.order[i];
        if(element.meal != meal){
          this.db.collection('tables').doc(this.table.propertyId).update({order:({meal,price,quantity})})
        } else {
           this.order[i].quantity += 1;
           this.db.collection('tables').doc(this.table.propertyId).update({order: this.order})
        }
}

```

If you want to add/remove elements from the array you can use arrayUnion() or arrayRemove()
https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

Body:
im having trouble updating the quantity property in my angular-firebase project

chosenMeal(meal,price,quantity){
  for (let i = 0; i < this.order.length; i++) {
        const element = this.order[i];
        if(element.meal != meal){
          this.db.collection('tables').doc(this.table.propertyId).update({order:({meal,price,quantity})})
        }else{
        // my question
  }
}

so the logic is like this if the chosen meal isn't in the order array then add it to the order array in firebase, else if the meal exists on the order array just increment the quantity, i don't know how to update just the quantity in the order object in firebase, or i don't know how to access only the one property in a firebase object

Body:
Update the array locally and after that update it in your database.

chosenMeal(meal,price,quantity){
  for (let i = 0; i < this.order.length; i++) {
        const element = this.order[i];
        if(element.meal != meal){
          this.db.collection('tables').doc(this.table.propertyId).update({order:({meal,price,quantity})})
        } else {
           this.order[i].quantity += 1;
           this.db.collection('tables').doc(this.table.propertyId).update({order: this.order})
        }
}

If you want to add/remove elements from the array you can use arrayUnion() or arrayRemove()
https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array


问:
how to get MouseMove and MouseClick in bash?
I'm wondering how to get the MouseClick and MouseMove events in bash scripting for my own simple OS events.

Please tell me how to get that events.

答:
you can use xdotool for mousemove and mouseclick events.
xdotool is a tool which fakes keyboard and mouse.
install it by typing,
sudo apt-get install xdotool.
By using xdotool you can automate almost everything you do using keyboard and mouse.</p>


问:
How to make some CSS Grid elements stick to the viewport?
I'm try to have 100vh viewport with multiple responsive overlay on top of that
Here is the code, I can make header element get fixed on the viewport with position sticky but for the rest that doesn't work

Also, I'm trying to use CSS Grid for this
Here is the code

body {
  display: grid;
  grid-template-columns: 1fr minmax(20em, 30vw);
  grid-template-rows: clamp(3em, 10vh, 5em) 1fr clamp(7em, 20vh, 9em);
}

header {
  background-color: #eee;
  grid-column: 1 / end;
  grid-row: 1 / 2;
}

main {
  height: 100vh;
  grid-column: 1 / end;
  grid-row: 1 / end;
}

aside {
  background-color: #ccc;
  grid-column: 2 / end;
  grid-row: 2 / end;
}

footer {
  background-color: #444;
  grid-row: 3 / end;
  grid-column: 1 / end;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <header></header>
  <main>
    <section class="questions" id="objectives">
      <h2>Objectives</h2>
      <div class="question">
        <h3>1. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
        <button>Yes</button><button>No</button>
      </div>
      <div class="question">
        <h3>2. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
        <button>Yes</button><button>No</button>
      </div>
      <div class="question">
        <h3>3. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
        <button>Yes</button><button>No</button>
      </div>
      <div class="question">
        <h3>4. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
        <button>Yes</button><button>No</button>
      </div>
      <div class="question">
        <h3>5. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
        <button>Yes</button><button>No</button>
      </div>
      <div class="question">
        <h3>6. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
        <button>Yes</button><button>No</button>
      </div>
      <div class="question">
        <h3>7. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
        <button>Yes</button><button>No</button>
      </div>
      <div class="question">
        <h3>8. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
        <button>Yes</button><button>No</button>
      </div>
      <div class="question">
        <h3>9. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
        <button>Yes</button><button>No</button>
      </div>
    </section>
  </main>
  <aside></aside>
  <footer></footer>
</body></code>```

Codepen https://codepen.io/ikamy/pen/rNYwOwM

Please vertically minimize and then scroll
I'm trying to fix footer and aside without using position fixed or absolute

While the body is display Grid I'm trying to use with: 100vh on the body and make the other Grid elements sticks , and I only scroll on the main element

答:
You need to use min-height:100vh instead of height:100vh

And then use position:sticky on element you want to be sticky with top or bottom.

body {
        display: grid;
        grid-template-columns: 1fr minmax(20em, 30vw);
        grid-template-rows: clamp(3em, 10vh, 5em) 1fr clamp(7em, 20vh, 9em);
    }

    header {
        background-color: #eee;
        grid-column: 1 / end;
        grid-row: 1 / 2;
    }

    main {
      min-height:100vh;
        grid-column: 1 / end;
        grid-row: 1 / end;
    }

    aside {
        background-color: #ccc;
        grid-column: 2 / end;
        grid-row: 2 / end;
        position: sticky;
        top: 0;
        z-index:99999;
    }

    footer {
        background-color: #444;
        grid-row: 3 / end;
        grid-column: 1 / end;
       position: sticky;
        bottom: 0
          ;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <header></header>
    <main>
        <section class="questions" id="objectives">
            <h2>Objectives</h2>
            <div class="question">
                <h3>1. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>2. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>3. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>4. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>5. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>6. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>7. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>8. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>9. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
        </section>
    </main>
    <aside></aside>
    <footer></footer>
</body></code>```

For reference you may look at this question: 'position: sticky' not working when 'height' is defined

Body:
I'm try to have 100vh viewport with multiple responsive overlay on top of that
Here is the code, I can make header element get fixed on the viewport with position sticky but for the rest that doesn't work

Also, I'm trying to use CSS Grid for this
Here is the code

body {
  display: grid;
  grid-template-columns: 1fr minmax(20em, 30vw);
  grid-template-rows: clamp(3em, 10vh, 5em) 1fr clamp(7em, 20vh, 9em);
}

header {
  background-color: #eee;
  grid-column: 1 / end;
  grid-row: 1 / 2;
}

main {
  height: 100vh;
  grid-column: 1 / end;
  grid-row: 1 / end;
}

aside {
  background-color: #ccc;
  grid-column: 2 / end;
  grid-row: 2 / end;
}

footer {
  background-color: #444;
  grid-row: 3 / end;
  grid-column: 1 / end;
}

Objectives

1. Lorem ipsum dolor sit amet, consectetur adipisicing.

        <button>Yes</button><button>No</button>

2. Lorem ipsum dolor sit amet, consectetur adipisicing.

        <button>Yes</button><button>No</button>

3. Lorem ipsum dolor sit amet, consectetur adipisicing.

        <button>Yes</button><button>No</button>

4. Lorem ipsum dolor sit amet, consectetur adipisicing.

        <button>Yes</button><button>No</button>

5. Lorem ipsum dolor sit amet, consectetur adipisicing.

        <button>Yes</button><button>No</button>

6. Lorem ipsum dolor sit amet, consectetur adipisicing.

        <button>Yes</button><button>No</button>

7. Lorem ipsum dolor sit amet, consectetur adipisicing.

        <button>Yes</button><button>No</button>

8. Lorem ipsum dolor sit amet, consectetur adipisicing.

        <button>Yes</button><button>No</button>

9. Lorem ipsum dolor sit amet, consectetur adipisicing.

        <button>Yes</button><button>No</button>

Codepen https://codepen.io/ikamy/pen/rNYwOwM

Please vertically minimize and then scroll
I'm trying to fix footer and aside without using position fixed or absolute

While the body is display Grid I'm trying to use with: 100vh on the body and make the other Grid elements sticks , and I only scroll on the main element

Body:
You need to use min-height:100vh instead of height:100vh

And then use position:sticky on element you want to be sticky with top or bottom.

body {
        display: grid;
        grid-template-columns: 1fr minmax(20em, 30vw);
        grid-template-rows: clamp(3em, 10vh, 5em) 1fr clamp(7em, 20vh, 9em);
    }

    header {
        background-color: #eee;
        grid-column: 1 / end;
        grid-row: 1 / 2;
    }

    main {
      min-height:100vh;
        grid-column: 1 / end;
        grid-row: 1 / end;
    }

    aside {
        background-color: #ccc;
        grid-column: 2 / end;
        grid-row: 2 / end;
        position: sticky;
        top: 0;
        z-index:99999;
    }

    footer {
        background-color: #444;
        grid-row: 3 / end;
        grid-column: 1 / end;
       position: sticky;
        bottom: 0
          ;
    }

<body>
    <header></header>
    <main>
        <section class="questions" id="objectives">
            <h2>Objectives</h2>
            <div class="question">
                <h3>1. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>2. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>3. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>4. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>5. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>6. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>7. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>8. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
            <div class="question">
                <h3>9. Lorem ipsum dolor sit amet, consectetur adipisicing.</h3>
                <button>Yes</button><button>No</button>
            </div>
        </section>
    </main>
    <aside></aside>
    <footer></footer>
</body>

For reference you may look at this question: 'position: sticky' not working when 'height' is defined


问:
Column number - copying and pasting from file to another file
I have a little problem with my code. I want to copy my data from one file to my main file. When I check the code I meet with one problem. The code works fine until copied. In this line

Set cell1 = wsDest.Cells(1, Range("B1").End(xlToRight).Column + 1)

the cell is selected from the file from I am taking the data and not the folder I am pasting into.

I want my data to paste from these other files into the main file. I want to add them as columns, not rows.

```<code>
Sub MoveCopyRowsColumns()

Dim mainWb As Workbook
Dim newWb As Workbook
Dim mainWs As Worksheet
Dim newWs As Worksheet
Dim strFolder As String

Set mainWb = Workbooks("Main_file.xlsm")
Set mainWs = mainWb.Worksheets("Worksheet1")

mainWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
mainWs.Columns(ActiveCell.Column).EntireColumn.Delete

    strFolder = "C:\Users\User1\Desktop\Folder_with_files\"
    strFile = Dir(strFolder & "*.xls*")
    Do While strFile <> ""
        Set newWb = Workbooks.Open(strFolder & strFile)
        Set newWs = newWb.Sheets(1)

        strFile = Dir

        newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
        newWs.Columns(ActiveCell.Column).EntireColumn.Delete

        newWs.Range("B1", Range("B1").End(xlDown).End(xlToRight)).Copy _
        mainWs.Range("P1")

    Loop

End Sub

</code>```

答:
You have to declare which file/sheet is which. Each line should refer to the right worksheet. All lines starting with cell or range should have worksheet first like: "mainWs.Cell".
In the new file you have not declared any worksheet, only workbook (wb).
I haven't tryed the code below, but I hope it unlocks your problem thinking.
Good luck!</p>
```<code>Sub MoveCopyRowsColumns()
Dim mainWb As Workbook
Dim newWb As Workbook
Dim mainWs As Worksheet
Dim newWs As Worksheet
Dim strFolder As String
Dim strFile As String
Dim cell1 As Range

Set mainWb = Workbooks("Main_file.xlsm")
Set mainWs = mainWb.Worksheets("Worksheet1")

mainWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
mainWs.Columns(ActiveCell.Column).EntireColumn.Delete
'in my main file I delete the last column  only one

    strFolder = "C:\Users\User1\Desktop\Folder_with_files\"
    strFile = Dir(strFolder & "*.xls*")
    Do While strFile <> ""
        Set newWb = Workbooks.Open(strFolder & strFile)
        'Set the sheet you want to use, using "first sheet" or sheet by name
        'Set newWs = newWb.Sheets(1)
        'Set newWs = newWb.Worksheets("Worksheet1")
        strFile = Dir

        newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
        newWs.Columns(ActiveCell.Column).EntireColumn.Delete

        'Set cell1 = newWs.Cells(1, Range("B1").End(xlToRight).Column + 1)
        newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Copy
        'the adress is taking from file when I take the data, not the main file which should take.

        mainWs.Range(cell1).PasteSpecial Paste:=xlPasteValues
    Loop

End Sub
</code>```

Body:
I have a little problem with my code. I want to copy my data from one file to my main file. When I check the code I meet with one problem. The code works fine until copied. In this line

Set cell1 = wsDest.Cells(1, Range("B1").End(xlToRight).Column + 1)

the cell is selected from the file from I am taking the data and not the folder I am pasting into.

I want my data to paste from these other files into the main file. I want to add them as columns, not rows.

Sub MoveCopyRowsColumns()

Dim mainWb As Workbook
Dim newWb As Workbook
Dim mainWs As Worksheet
Dim newWs As Worksheet
Dim strFolder As String

Set mainWb = Workbooks("Main_file.xlsm")
Set mainWs = mainWb.Worksheets("Worksheet1")

mainWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
mainWs.Columns(ActiveCell.Column).EntireColumn.Delete

    strFolder = "C:\Users\User1\Desktop\Folder_with_files\"
    strFile = Dir(strFolder & "*.xls*")
    Do While strFile <> ""
        Set newWb = Workbooks.Open(strFolder & strFile)
        Set newWs = newWb.Sheets(1)

        strFile = Dir

        newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
        newWs.Columns(ActiveCell.Column).EntireColumn.Delete

        newWs.Range("B1", Range("B1").End(xlDown).End(xlToRight)).Copy _
        mainWs.Range("P1")

    Loop

End Sub

Body:
You have to declare which file/sheet is which. Each line should refer to the right worksheet. All lines starting with cell or range should have worksheet first like: "mainWs.Cell".
In the new file you have not declared any worksheet, only workbook (wb).
I haven't tryed the code below, but I hope it unlocks your problem thinking.
Good luck!

Sub MoveCopyRowsColumns()
Dim mainWb As Workbook
Dim newWb As Workbook
Dim mainWs As Worksheet
Dim newWs As Worksheet
Dim strFolder As String
Dim strFile As String
Dim cell1 As Range

Set mainWb = Workbooks("Main_file.xlsm")
Set mainWs = mainWb.Worksheets("Worksheet1")

mainWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
mainWs.Columns(ActiveCell.Column).EntireColumn.Delete
'in my main file I delete the last column  only one

    strFolder = "C:\Users\User1\Desktop\Folder_with_files\"
    strFile = Dir(strFolder & "*.xls*")
    Do While strFile <> ""
        Set newWb = Workbooks.Open(strFolder & strFile)
        'Set the sheet you want to use, using "first sheet" or sheet by name
        'Set newWs = newWb.Sheets(1)
        'Set newWs = newWb.Worksheets("Worksheet1")
        strFile = Dir

        newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
        newWs.Columns(ActiveCell.Column).EntireColumn.Delete

        'Set cell1 = newWs.Cells(1, Range("B1").End(xlToRight).Column + 1)
        newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Copy
        'the adress is taking from file when I take the data, not the main file which should take.

        mainWs.Range(cell1).PasteSpecial Paste:=xlPasteValues
    Loop

End Sub


问:
how do fetch the year wise data alone from timestamp with time zone DEFAULT CURRENT_TIMESTAMP?
I am trying to fetch the records based on year alone from table whose created_at column value is like Eg:'2020-03-10 16:47:32.226592'. I need to fetch the year-wise data from a table.

SQL column structure:

created_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP;

Tried Query

SELECT * FROM
 order by created_time ASC;

答:
for 2022

```<code>SELECT YEAR(current_timestamp);
</code>```

prints 2022.

In where

```<code>WHERE created_time >= YEAR(current_timestamp)
</code>```

Body:
for 2022

SELECT YEAR(current_timestamp);

prints 2022.

In where

WHERE created_time >= YEAR(current_timestamp)


问:
How to underline two div's consecutively?
I've got 2
s that each gather their text from some JS that I've written.
But I want the end-result to look like in the following image. And I can't figure out how to do that.

I can consolidate them into a single  but then I have the issue of needing to apply two different weights to a single
, which also wracks my brain.

So basically I want text with 2 different font-weights to be underlined with no interruption.

I've tried the following, and a lot of googling:

```<code>div.parentDiv {
    text-decoration-line : underline;
}
</code>```

答:
To style the two parts individually you need to have at least one of them in its own element.

This snippet wraps the parts in spans and puts the underline under the whole containing element.

Note that to get a continuous underline like in the image given in the question you need to set underline position as well, otherwise, in some browsers,  there will be a break in the line when it comes across a descender (in this case the brackets).

If you need the line to cut across the descenders in all browsers you will need to abandon underline and paint in the line using linear-gradient background on the containing div.

div {
  text-decoration: underline;
  text-underline-position: under;
}

span:nth-child(1) {
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div><span>Good Reviews</span><span>(30)</span></div></code>```

Body:
I've got 2
s that each gather their text from some JS that I've written.
But I want the end-result to look like in the following image. And I can't figure out how to do that.

I can consolidate them into a single  but then I have the issue of needing to apply two different weights to a single
, which also wracks my brain.

So basically I want text with 2 different font-weights to be underlined with no interruption.

I've tried the following, and a lot of googling:

div.parentDiv {
    text-decoration-line : underline;
}

Body:
To style the two parts individually you need to have at least one of them in its own element.

This snippet wraps the parts in spans and puts the underline under the whole containing element.

Note that to get a continuous underline like in the image given in the question you need to set underline position as well, otherwise, in some browsers,  there will be a break in the line when it comes across a descender (in this case the brackets).

If you need the line to cut across the descenders in all browsers you will need to abandon underline and paint in the line using linear-gradient background on the containing div.

div {
  text-decoration: underline;
  text-underline-position: under;
}

span:nth-child(1) {
  font-weight: bold;
}

<div><span>Good Reviews</span><span>(30)</span></div>


问:
How many processors should be used with multiprocessing.Pool?
I am trying to use multiprocessing.Pool to run my code in parallel. To instantiate Pool, you have to set the number of processes. I am trying to figure out how many I should set for this. I understand this number shouldn't be more than the number of cores you have but I've seen different ways to determine what your system has available.

2 Methods:

multiprocessing.cpu_count()

len(os.sched_getaffinity(0))

I'm a little confused; what is the difference between the two and which should be implemented with Pool? I am working on a remote cluster, with the first, it outputs that there are 128 cpu, but the second gives 10.

答:
The difference between the two is clearly stated in the doc:

multiprocessing.cpu_count()
Return the number of CPUs in the system.

This number is not equivalent to the number of CPUs the current process can use. The number of usable CPUs can be obtained with len(os.sched_getaffinity(0)).

So even if you are on a 128-core system, your program could have been somehow limited to only run on a specific set of 10 out of the 128 available CPUs. Since affinity also applies to child threads and processes, it doesn't make much sense to spawn more than 10. You could however try to increase the number of available CPUs through os.sched_setaffinity() before starting your pool.

import os
import multiprocessing as mp

cpu_count = mp.cpu_count()

if len(os.sched_getaffinity(0)) < cpu_count:
    try:
        os.sched_setaffinity(0, range(cpu_count))
    except OSError:
        print('Could not set affinity')

n = max(len(os.sched_getaffinity(0)), 96)
print('Using', n, 'processes for the pool')

pool = mp.Pool(n)
# ...
```

See also man 2 sched_setaffinity.

Body:
The difference between the two is clearly stated in the doc:

multiprocessing.cpu_count()
Return the number of CPUs in the system.

This number is not equivalent to the number of CPUs the current process can use. The number of usable CPUs can be obtained with len(os.sched_getaffinity(0)).

So even if you are on a 128-core system, your program could have been somehow limited to only run on a specific set of 10 out of the 128 available CPUs. Since affinity also applies to child threads and processes, it doesn't make much sense to spawn more than 10. You could however try to increase the number of available CPUs through os.sched_setaffinity() before starting your pool.

import os
import multiprocessing as mp

cpu_count = mp.cpu_count()

if len(os.sched_getaffinity(0)) < cpu_count:
    try:
        os.sched_setaffinity(0, range(cpu_count))
    except OSError:
        print('Could not set affinity')

n = max(len(os.sched_getaffinity(0)), 96)
print('Using', n, 'processes for the pool')

pool = mp.Pool(n)
# ...

See also man 2 sched_setaffinity.


问:
jquery picture selector
Does anyone have an example of a jquery based photo selector?  This is something you see in small photo albums.

I have the following code:

```<code><div><img class="bigpicture" src="1.jpg"></img></div>
<div>
    <img class="smallpicture" src="1.jpg"></img>
    <img class="smallpicture" src="2.jpg"></img>
    <img class="smallpicture" src="3.jpg"></img>
    <img class="smallpicture" src="4.jpg"></img>
    <img class="smallpicture" src="5.jpg"></img>
    <img class="smallpicture" src="6.jpg"></img>
</div>
</code>```

The behavior I'm looking for is when the users hovers over any of the smaller pictures, it updates the bigger picture with the one that was just hovered.

Any thoughts?

Thanks

答:
Using jQuery:</p>

```<code>$('.smallpicture').hover(function() {
    $('.bigpicture').attr('src', $(this).attr('src'));
});
</code>```

Title: jquery picture selector

Body:
Does anyone have an example of a jquery based photo selector?  This is something you see in small photo albums.

I have the following code:

The behavior I'm looking for is when the users hovers over any of the smaller pictures, it updates the bigger picture with the one that was just hovered.

Any thoughts?

Thanks

Body:
Using jQuery:

$('.smallpicture').hover(function() {
    $('.bigpicture').attr('src', $(this).attr('src'));
});