问:
How to move issue to project column based on issue comment using github actions?
I want to create a Github workflow that adds newly created issues to a Project (Classic)'s "Todo" column automatically. If any issue comment is created with "[Forward]" keyword, the issue should be moved to "In Progress" column of the same project.

Is there any way to do so using Github actions?

Thanks in advance.

I combined following two solutions and came up with a hybrid one.

Assign new issues to a project – https://github.com/marketplace/actions/assign-to-one-project

Trigger workflow based on specific keyword in the comment – https://github.com/orgs/community/discussions/25389

Based on above to solutions, here's my workflow –

```<code>
name: Auto Assign to Project(s)

on:
  issues:
    types: [opened]
  issue_comment:
    types: [created]
env:
  GITHUB_TOKEN: ${{ secrets.MY_GITHUB_TOKEN }}

jobs:
  assign_one_project:
    runs-on: ubuntu-latest
    name: Assign to One Project
    steps:
    - name: JOB 1
      uses: srggrs/assign-one-project-github-action@1.2.1
      if: github.event.action == 'opened'
      with:
        project: 'https://github.com/<project uri>'
        column_name: 'Todo'

    - name: JOB 2
      uses: srggrs/assign-one-project-github-action@1.2.1
      if: contains(github.event.comment.body, '[Forward]')
      with:
        project: 'https://github.com/<project uri>'
        column_name: 'In Progress'

</code>```

Body:
I want to create a Github workflow that adds newly created issues to a Project (Classic)'s "Todo" column automatically. If any issue comment is created with "[Forward]" keyword, the issue should be moved to "In Progress" column of the same project.

Is there any way to do so using Github actions?

Thanks in advance.

I combined following two solutions and came up with a hybrid one.

Assign new issues to a project – https://github.com/marketplace/actions/assign-to-one-project

Trigger workflow based on specific keyword in the comment – https://github.com/orgs/community/discussions/25389

Based on above to solutions, here's my workflow –

name: Auto Assign to Project(s)

on:
  issues:
    types: [opened]
  issue_comment:
    types: [created]
env:
  GITHUB_TOKEN: ${{ secrets.MY_GITHUB_TOKEN }}

jobs:
  assign_one_project:
    runs-on: ubuntu-latest
    name: Assign to One Project
    steps:
    - name: JOB 1
      uses: srggrs/assign-one-project-github-action@1.2.1
      if: github.event.action == 'opened'
      with:
        project: 'https://github.com/<project uri>'
        column_name: 'Todo'

    - name: JOB 2
      uses: srggrs/assign-one-project-github-action@1.2.1
      if: contains(github.event.comment.body, '[Forward]')
      with:
        project: 'https://github.com/<project uri>'
        column_name: 'In Progress'


来源: stackexchange

问:
How to fix getaddrinfo ENOTFOUND error thrown by axios post()?
There are many articles and questions I found to resolve this issue but nothing works, How to fix this error thrown by axios post request?

I have tried to remove http:// from url, flushed dns, this url works in other environments but not in development environment.

```<code>Error: getaddrinfo ENOTFOUND "billingxyz.....cluster.local/msp/v2/events" at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:67:26) {
errno: -3008,
code: 'ENOTFOUND',
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There are many articles and questions I found to resolve this issue but nothing works, How to fix this error thrown by axios post request?

I have tried to remove http:// from url, flushed dns, this url works in other environments but not in development environment.

Error: getaddrinfo ENOTFOUND "billingxyz.....cluster.local/msp/v2/events" at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:67:26) {
errno: -3008,
code: 'ENOTFOUND',


问:
Is it possible to use dynamic types base on URLSearchParams value in typescript
is it possible change my type dynamically based on a function call, like the URLSearchParams has?

here's what i am triyng to:

interface X<T> {
  get: (Uparams?: URLSearchParams) => Promise<
    Uparams.has('page') extends true ? T[] : PaginatedReturn<T>
  >;
}
```


问:
How to use node-libcurl with NETRC option
I need to make an HTTP GET using curl with netrc file with auth credentials. But I think that I'm doing something brong because I get an HTTP 200 RESPONSE but in the body there is the HTML for the authentication page of the site.

This is the code that I made:

```<code>const { Curl } = require('node-libcurl');

async function start() {
    const curl = new Curl();

    curl.setOpt('URL', 'https://cddis.nasa.gov/archive/gps/data/highrate/2022/331/22d/00/ABMF00GLP_S_20223310000_15M_01S_MO.crx.gz');
    curl.setOpt('FOLLOWLOCATION', true);
    curl.setOpt('NETRC', true);
    curl.setOpt('NETRC_FILE', '.netrc');
    curl.setOpt('MAXREDIRS', 5);
    curl.setOpt('SSL_VERIFYPEER', false);
    curl.setOpt('SSL_VERIFYHOST', false);

    curl.on('end', function (statusCode, data, headers) {
      console.info(statusCode);
      console.info('---');
      console.info(data.length);
      console.info('---');
      console.info(data);
      console.info('---');
      console.info(this.getInfo( 'TOTAL_TIME'));

      this.close();
    });

    curl.on('error', curl.close.bind(curl));
    curl.perform();
}

start();
</code>```

And the .netrc file is in the same directory that the code. This content is:

machine urs.earthdata.nasa.gov login <username> password <password>

Thanks so much!

Body:
I need to make an HTTP GET using curl with netrc file with auth credentials. But I think that I'm doing something brong because I get an HTTP 200 RESPONSE but in the body there is the HTML for the authentication page of the site.

This is the code that I made:

const { Curl } = require('node-libcurl');

async function start() {
    const curl = new Curl();

    curl.setOpt('URL', 'https://cddis.nasa.gov/archive/gps/data/highrate/2022/331/22d/00/ABMF00GLP_S_20223310000_15M_01S_MO.crx.gz');
    curl.setOpt('FOLLOWLOCATION', true);
    curl.setOpt('NETRC', true);
    curl.setOpt('NETRC_FILE', '.netrc');
    curl.setOpt('MAXREDIRS', 5);
    curl.setOpt('SSL_VERIFYPEER', false);
    curl.setOpt('SSL_VERIFYHOST', false);

    curl.on('end', function (statusCode, data, headers) {
      console.info(statusCode);
      console.info('---');
      console.info(data.length);
      console.info('---');
      console.info(data);
      console.info('---');
      console.info(this.getInfo( 'TOTAL_TIME'));

      this.close();
    });

    curl.on('error', curl.close.bind(curl));
    curl.perform();
}

start();

And the .netrc file is in the same directory that the code. This content is:

machine urs.earthdata.nasa.gov login <username> password <password>

Thanks so much!


问:
Backpack Crud Filter by relation
I have these 2 models: Purchase and (has many) Payments

in Purchase Model I have this relation and getter field

```<code>protected $appends = ['paymentstatus'];

public function payments()
{
    return $this->hasMany(Payment::class, 'purchase_id');
}

public function getPaymentstatusAttribute($value)
{
    return $this->payments->count() > 0 ? '1' : '0';
}
</code>```

In Purchase List Controller, I tried to add filter whether Payments exist or not but not working....

```<code>$this->crud->addFilter([
        'name'  => 'paymentstatus',
        'type'  => 'dropdown',
        'label' => 'Payment Status'
    ], [
        '0' => 'Unpaid',
        '1' => 'Paid'
    ], function($value) { // if the filter is active
        $this->crud->addClause('where', 'paymentstatus', $value);
    });
</code>```

I keep getting Search Error when selecting the filter.. What is the problem? Should't paymentstatus treated like a normal column for Purchase model?

Title: Backpack Crud Filter by relation

Body:
I have these 2 models: Purchase and (has many) Payments

in Purchase Model I have this relation and getter field

protected $appends = ['paymentstatus'];

public function payments()
{
    return $this->hasMany(Payment::class, 'purchase_id');
}

public function getPaymentstatusAttribute($value)
{
    return $this->payments->count() > 0 ? '1' : '0';
}

In Purchase List Controller, I tried to add filter whether Payments exist or not but not working....

$this->crud->addFilter([
        'name'  => 'paymentstatus',
        'type'  => 'dropdown',
        'label' => 'Payment Status'
    ], [
        '0' => 'Unpaid',
        '1' => 'Paid'
    ], function($value) { // if the filter is active
        $this->crud->addClause('where', 'paymentstatus', $value);
    });

I keep getting Search Error when selecting the filter.. What is the problem? Should't paymentstatus treated like a normal column for Purchase model?


问:
Refine pnp js Search function
I'm trying to get search results from the site where query string matches "Description" which is a custom column in one of the multiple document libraries in the site. Is there a way to achieve this?

I have used Select Properties but that doesn't seem to be working

Title: Refine pnp js Search function


问:
How to share common code between libraries in nx monorepo
There are 2 libraries a (with angular) and b (with react), and a util library c which is used in both a and b. What I am expecting is when a or b is built, the code of c should be present in both the builds.

The react library(b) which uses @nxext/vite:package as executor works fine by keeping the build of c inside react build with relative paths to c, but I am facing issue with angular library(a) build which is using @nrwl/angular:package as executor. Here when I build angular library, the build still has the absolute path reference to c, and the build of c will be not present inside angular build.

If we publish this util(c) library, then I agree the issue will be solved, but my requirement is not to publish it, but I need the build/code of utils to be present inside angular's build just like reacts build

Example folder structure:

- libs

 - angular

 - react

 - utils


问:
how to add alert on changing color of Average_Line in mt5
How to add alert on changing color of Average_Line in metatrader5 (mt5)
I tried a lot but cant do it. I am able to add alert depends on arrows. But didn't know depend on color change. Can anybody add alerts Native alert (popup),Sound alert, Push notifications (mobile)</p>


问:
Docker not found, even though it is installed
I tried setting up a Docker environment for my developing ventures:

I installed docker using the docs "Install docker engine" from their website and receive the following output:

sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin
Paketlisten werden gelesen… Fertig
Abhängigkeitsbaum wird aufgebaut… Fertig
Statusinformationen werden eingelesen… Fertig
containerd.io ist schon die neueste Version (1.6.13-1).
docker-ce-cli ist schon die neueste Version (5:20.10.22~3-0~ubuntu-jammy).
docker-ce ist schon die neueste Version (5:20.10.22~3-0~ubuntu-jammy).
docker-compose-plugin ist schon die neueste Version (2.14.1~ubuntu-jammy).
Die folgenden Pakete wurden automatisch installiert und werden nicht mehr benötigt:
  cpu-checker ibverbs-providers ipxe-qemu ipxe-qemu-256k-compat-efi-roms libaio1
  libbrlapi0.8 libcacard0 libfdt1 libgfapi0 libgfrpc0 libgfxdr0 libglusterfs0
  libibverbs1 libiscsi7 libpmemobj1 librados2 librbd1 librdmacm1 libspice-server1
  libusbredirparser1 libvirglrenderer1 msr-tools ovmf pass qemu-block-extra
  qemu-system-common qemu-system-data qemu-system-gui qemu-system-x86 qemu-utils
  qrencode seabios tree uidmap xclip
Verwenden Sie »sudo apt autoremove«, um sie zu entfernen.
0 aktualisiert, 0 neu installiert, 0 zu entfernen und 9 nicht aktualisiert.
2 nicht vollständig installiert oder entfernt.
Nach dieser Operation werden 0 B Plattenplatz zusätzlich benutzt.
Möchten Sie fortfahren? [J/n] j
```
<p>then nothing more.
(well, my nvidia drivers are running bonkers at the moment.)</p>
<pre class="lang-bash prettyprint-override"><code>sudo docker run hello-world sudo: docker: Befehl nicht gefunden
</code>```

I reinstalled maybe ten times now and have not a single clue how to pursue this further.

We run a dev-environment in docker that emulates a rather complex working environment, where servers push things to other servers etc. so I am depending on docker a lot and cannot work at the moment.

By now I am so confused, that I think starting from the beginning works best, thus I tried uninstalling following this one: https://askubuntu.com/questions/935569/how-to-completely-uninstall-docker

Now nothing works, not even installing ...

any hint is highly appreciated

Body:
I tried setting up a Docker environment for my developing ventures:

I installed docker using the docs "Install docker engine" from their website and receive the following output:

sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin
Paketlisten werden gelesen… Fertig
Abhängigkeitsbaum wird aufgebaut… Fertig
Statusinformationen werden eingelesen… Fertig
containerd.io ist schon die neueste Version (1.6.13-1).
docker-ce-cli ist schon die neueste Version (5:20.10.22~3-0~ubuntu-jammy).
docker-ce ist schon die neueste Version (5:20.10.22~3-0~ubuntu-jammy).
docker-compose-plugin ist schon die neueste Version (2.14.1~ubuntu-jammy).
Die folgenden Pakete wurden automatisch installiert und werden nicht mehr benötigt:
  cpu-checker ibverbs-providers ipxe-qemu ipxe-qemu-256k-compat-efi-roms libaio1
  libbrlapi0.8 libcacard0 libfdt1 libgfapi0 libgfrpc0 libgfxdr0 libglusterfs0
  libibverbs1 libiscsi7 libpmemobj1 librados2 librbd1 librdmacm1 libspice-server1
  libusbredirparser1 libvirglrenderer1 msr-tools ovmf pass qemu-block-extra
  qemu-system-common qemu-system-data qemu-system-gui qemu-system-x86 qemu-utils
  qrencode seabios tree uidmap xclip
Verwenden Sie »sudo apt autoremove«, um sie zu entfernen.
0 aktualisiert, 0 neu installiert, 0 zu entfernen und 9 nicht aktualisiert.
2 nicht vollständig installiert oder entfernt.
Nach dieser Operation werden 0 B Plattenplatz zusätzlich benutzt.
Möchten Sie fortfahren? [J/n] j

then nothing more.
(well, my nvidia drivers are running bonkers at the moment.)

sudo docker run hello-world sudo: docker: Befehl nicht gefunden

I reinstalled maybe ten times now and have not a single clue how to pursue this further.

We run a dev-environment in docker that emulates a rather complex working environment, where servers push things to other servers etc. so I am depending on docker a lot and cannot work at the moment.

By now I am so confused, that I think starting from the beginning works best, thus I tried uninstalling following this one: https://askubuntu.com/questions/935569/how-to-completely-uninstall-docker

Now nothing works, not even installing ...

any hint is highly appreciated


问:
Transition_reveal() ending on the wrong frame for an animated line chart
I want to create an animated line chart that stops after one loop. But when I use the following code the line chart ends on one lower x value for the second line.

Simulating the issue with a dummy dataset.

```<code>library(ggplot2)
library(gifski)
library(gganimate)
library(transformr)

cat<-c("A","B","A","B","A","B")
val<-c(0.1,0.2,1,2,0.3,3)
year<-c("2000","2000","2001","2001","2002","2002")

df<-data.frame(cat,val,year)
df$year<-as.Date(df$year,"%Y")

anim<-ggplot(df, aes(year, val,colour=cat,group=cat)) + geom_line(aes(group=cat))+transition_reveal(year)
animate(anim,renderer = gifski_renderer(loop = FALSE))
</code>```

Body:
I want to create an animated line chart that stops after one loop. But when I use the following code the line chart ends on one lower x value for the second line.

Simulating the issue with a dummy dataset.

library(ggplot2)
library(gifski)
library(gganimate)
library(transformr)

cat<-c("A","B","A","B","A","B")
val<-c(0.1,0.2,1,2,0.3,3)
year<-c("2000","2000","2001","2001","2002","2002")

df<-data.frame(cat,val,year)
df$year<-as.Date(df$year,"%Y")

anim<-ggplot(df, aes(year, val,colour=cat,group=cat)) + geom_line(aes(group=cat))+transition_reveal(year)
animate(anim,renderer = gifski_renderer(loop = FALSE))


问:
How to pass an audio recording through an FIR window in **Python**
I need to read an audio recording of myself, Fourier transform it and then calculate the average frequency.
After that i need to create an FIR window with boundaries of f_min = 82 Hz, f_max = 1047 Hz.
I need to pass my audio recording through that window and then recalculate the average frequency.
I am not sure when should I use the Fourier and inverse Fourier transforms, and I am only starting to use python.

```<code>import numpy as np
from scipy.signal import convolve
from scipy.io import wavfile as wav
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
from scipy import signal

# Load the audio sound as a NumPy array
fs, file = wav.read('Recording.wav')
fft_out = fft(file)

# Define the FIR window as a NumPy array
nyq = fs / 2
filter_order = 1
low, high = 82 / nyq, 1047 / nyq
fir_window = signal.firwin(filter_order, [low, high], pass_zero=False)

# Convolve the audio sound with the FIR window
filtered_audio = convolve(fft_out, fir_window, mode='same')
final_audio = ifft(filtered_audio)

final_audio *= 32767
final_audio = np.int16(final_audio)
wav.write('filtered_Recording.wav', fs, final_audio)

plt.plot(filtered_audio)
plt.show()

</code>```

I'm pretty sure i got a lot of things wrong, hope someone can help me!

Body:
I need to read an audio recording of myself, Fourier transform it and then calculate the average frequency.
After that i need to create an FIR window with boundaries of f_min = 82 Hz, f_max = 1047 Hz.
I need to pass my audio recording through that window and then recalculate the average frequency.
I am not sure when should I use the Fourier and inverse Fourier transforms, and I am only starting to use python.

import numpy as np
from scipy.signal import convolve
from scipy.io import wavfile as wav
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
from scipy import signal

# Load the audio sound as a NumPy array
fs, file = wav.read('Recording.wav')
fft_out = fft(file)

# Define the FIR window as a NumPy array
nyq = fs / 2
filter_order = 1
low, high = 82 / nyq, 1047 / nyq
fir_window = signal.firwin(filter_order, [low, high], pass_zero=False)

# Convolve the audio sound with the FIR window
filtered_audio = convolve(fft_out, fir_window, mode='same')
final_audio = ifft(filtered_audio)

final_audio *= 32767
final_audio = np.int16(final_audio)
wav.write('filtered_Recording.wav', fs, final_audio)

plt.plot(filtered_audio)
plt.show()

I'm pretty sure i got a lot of things wrong, hope someone can help me!


问:
The size of the tensor (49) must match the existing size (64) at non-singleton dimension 1. Target sizes: [-1, 49, 49]. Tensor sizes: [64, 1]
Help me, please. I just try to use AdaptiveAvgPool2d but now I have mistake and I don't understand how to fix it. Someone knows?

```<code>
class AntispoofModel(nn.Module):
    def __init__(self, device="cpu", **kwargs):
        super().__init__()
        resnet = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=True)
        self.resnet = nn.Sequential(*[i for i in list(resnet.children())[:-1]]).to(device)
        for ch in self.resnet.children():
            for param in ch.parameters():
                param.requires_grad = False
        self.gat = GAT(**kwargs).to(device)
        self.device = device
        self.adj = torch.tensor(grid_to_graph(7, 7, return_as=np.ndarray)).to(device)
        self.avgpool = nn.AdaptiveAvgool2d(1)
        self.fc1 = nn.Linear(512, 1)

    def forward(self, x):
        x = self.resnet(x.to(self.device))
        x = self.avgpool(x).view(x.size(0), -1)
        x = self.gat(x, self.adj)
        x = self.fc1(x)
        return x

torch.manual_seed(42)
kwargs = {"nfeat":512, "nhid":64, "nclass":1, "nheads":64, "dropout":0.6, "alpha":0.01}
model = AntispoofModel(**kwargs, device="cpu")

train_dataloader = DataLoader(train_dataset, batch_size=64, shuffle=True)
</code>```

Mistake screen 1
Mistake screen 2

```<code>RuntimeError: The expanded size of the tensor (49) must match the existing size (64) at non-singleton dimension 1.  Target sizes: [-1, 49, 49].  Tensor sizes: [64, 1]
</code>```

Body:
Help me, please. I just try to use AdaptiveAvgPool2d but now I have mistake and I don't understand how to fix it. Someone knows?

class AntispoofModel(nn.Module):
    def __init__(self, device="cpu", **kwargs):
        super().__init__()
        resnet = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=True)
        self.resnet = nn.Sequential(*[i for i in list(resnet.children())[:-1]]).to(device)
        for ch in self.resnet.children():
            for param in ch.parameters():
                param.requires_grad = False
        self.gat = GAT(**kwargs).to(device)
        self.device = device
        self.adj = torch.tensor(grid_to_graph(7, 7, return_as=np.ndarray)).to(device)
        self.avgpool = nn.AdaptiveAvgool2d(1)
        self.fc1 = nn.Linear(512, 1)

    def forward(self, x):
        x = self.resnet(x.to(self.device))
        x = self.avgpool(x).view(x.size(0), -1)
        x = self.gat(x, self.adj)
        x = self.fc1(x)
        return x

torch.manual_seed(42)
kwargs = {"nfeat":512, "nhid":64, "nclass":1, "nheads":64, "dropout":0.6, "alpha":0.01}
model = AntispoofModel(**kwargs, device="cpu")

train_dataloader = DataLoader(train_dataset, batch_size=64, shuffle=True)

Mistake screen 1
Mistake screen 2

RuntimeError: The expanded size of the tensor (49) must match the existing size (64) at non-singleton dimension 1.  Target sizes: [-1, 49, 49].  Tensor sizes: [64, 1]


问:
Why $localize `:@@ID:` does not working with standard angular unit test configuration
$localize ':@@ID:' is returning empty string always in a unit test’s.

The usage:

• In some component code I am using $localize':@@Some:' and everything works well when serving the app or building it for prod.
• I use the standard angular unit test setup/configuration

The problem:

When trying to test that the exact text is returned I get an empty string, and I want to avoid mocking the $localize to keep the test code simple.

Unit test code sample:

```<code>// in the unit test the $localize`:@@Some:` is returning always ‘’
const testResult = service.getInfo(param); // in the method we return $localize`:@@Some:`;
expect(testResult).toBe($localize`:@@Some:`);
</code>```

Body:
$localize ':@@ID:' is returning empty string always in a unit test’s.

The usage:

• In some component code I am using $localize':@@Some:' and everything works well when serving the app or building it for prod.
• I use the standard angular unit test setup/configuration

The problem:

When trying to test that the exact text is returned I get an empty string, and I want to avoid mocking the $localize to keep the test code simple.

Unit test code sample:

// in the unit test the $localize`:@@Some:` is returning always ‘’
const testResult = service.getInfo(param); // in the method we return $localize`:@@Some:`;
expect(testResult).toBe($localize`:@@Some:`);


问:
Null check operator used on a null value Error Flutter Dart
I want to make a to do list application. I use Flutter & Dart. I tried to add condition where i got datas but it did not work. I do not know what i need to do. I got this error many places.
SnackBars do not works, i do not know why. This app have task books and tasks. When i want to see tasks of task book, it does not give me this error but when i want to search a task, it gives this error.

Error

```<code>The following _CastError was thrown building FutureBuilder<List<taskBooksDataModel>>(state: _FutureBuilderState<List<taskBooksDataModel>>#56975):
Null check operator used on a null value

The relevant error-causing widget was:
  FutureBuilder<List<taskBooksDataModel>> FutureBuilder:file:///C:/Users/Administrator/Desktop/todolist/lib/screens/generalListerWidgets/taskBookWidget.dart:22:12
When the exception was thrown, this was the stack:
#0      _SnackBarState.initState (package:flutter/src/material/snack_bar.dart:391:21)
#1      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:5015:57)
#2      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5)
...     Normal element mounting (50 frames)
#52     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3863:16)
#53     MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6435:36)
#54     MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6447:32)
...     Normal element mounting (387 frames)
</code>```

Data Model

```<code>class taskBooksDataModel {
  late int taskBookId;
  late String taskBookName;

  taskBooksDataModel() {}

  taskBooksDataModel.withOutId(this.taskBookName);
  taskBooksDataModel.withInfo(this.taskBookId, this.taskBookName);
  taskBooksDataModel.justWithId(this.taskBookId);

  static List<taskBooksDataModel> convertToTaskBookDataModel(List<Map<String, Object?>> value) {
    List<taskBooksDataModel> newList = [];
    for(int i = 0; i < value.length; i++) {
      newList.add(new taskBooksDataModel.withInfo(int.parse(value[i]["c_id"].toString()), value[i]["c_name"].toString()));
    }
    return newList;
  }
}
</code>```

Widget

```<code>import 'package:flutter/material.dart';
import "package:flutter/cupertino.dart";
import 'package:todolist/dataModels/taskBookDataModel.dart';
import 'package:todolist/database/database.dart';
import 'package:todolist/screens/tasksScreen/tasksScreen.dart';

class taskBooksWidget extends StatefulWidget {
  late String searchingValue;
  Function callback;

  taskBooksWidget(this.callback, {this.searchingValue = ""});

  @override
  State<taskBooksWidget> createState() => _taskBooksWidgetState();
}

class _taskBooksWidgetState extends State<taskBooksWidget> {
  @override
  Widget build(BuildContext context) {
    databaseHelper databaseTrans = new databaseHelper();

    return FutureBuilder(
      future: databaseTrans.getTables(whereValue: widget.searchingValue),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return taskBookErrorWidget(context);
        } else if (snapshot.data == null) {
          return taskBookErrorWidget(context);
        } else {
          return GridView.count(
            crossAxisCount: 3,
            children: List.generate(snapshot.data!.length, (i) {
              return Dismissible(
                  key: Key(snapshot.data![i].taskBookId.toString()),
                  direction: DismissDirection.horizontal,
                  child: Container(
                    margin: EdgeInsets.all(10),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Colors.white10,
                      borderRadius: BorderRadius.circular(30),
                    ),
                    child: InkWell(
                      onTap: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => tasksScreen(
                                    snapshot.data![i].taskBookId,
                                    snapshot.data![i].taskBookName)));
                      },
                      child: Text(snapshot.data![i].taskBookName.toString(),
                          style: TextStyle(color: Colors.white)),
                    ),
                  ),
                  onDismissed: (DismissDirection direction) {
                    databaseTrans.deleteTaskBook(
                        new taskBooksDataModel.justWithId(
                            snapshot.data![i].taskBookId));
                    widget.callback();
                  });
            }),
          );
        }
      },
    );
  }

  SnackBar taskBookErrorWidget(BuildContext context) {
    return SnackBar(
      content: Text(
        "There is no task book",
        style: TextStyle(fontSize: 20, color: Colors.white),
      ),
      behavior: SnackBarBehavior.floating,
      backgroundColor: Colors.pinkAccent,
      dismissDirection: DismissDirection.startToEnd,
    );
  }
}
</code>```

Database Function

```<code>import 'dart:async';
import "package:sqflite/sqflite.dart";
import "package:path/path.dart";
import 'package:todolist/dataModels/taskBookDataModel.dart';
import 'package:todolist/dataModels/tasksDataModel.dart';

class databaseHelper {
  Database? _databaseConn;

  final _chartTable = "charts_table";
  final _taskTable = "tasks_table";
  final _state_table = "state_table";

  Future get database async {
    if (_databaseConn == null) {
      _databaseConn = await databaseConnect();
    } else {
      return _databaseConn;
    }
    return _databaseConn;
  }

  Future<Database> databaseConnect() async {
    String path = join(getDatabasesPath().toString(), "8hhgjgggegerege.db");
    var connection = await openDatabase(path, version: 1, onCreate: createDefaultDatabase);
    return connection;
  }

  FutureOr<void> createDefaultDatabase(Database db, int version) async {
    db.execute("CREATE TABLE IF NOT EXISTS ${_chartTable} (c_id INTEGER NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT, c_name TEXT NOT NULL)");
    db.execute("CREATE TABLE IF NOT EXISTS ${_state_table} (s_id INTEGER NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT, s_name TEXT NOT NULL)");
    db.execute("CREATE TABLE IF NOT EXISTS ${_taskTable} (t_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, t_name TEXT NOT NULL, t_content TEXT NOT NULL, t_date TEXT NOT NULL, c_id INTEGER NOT NULL, s_id INT NOT NULL DEFAULT '2')");

    db.execute("INSERT INTO ${_state_table} (s_name) VALUES ('done')");
    db.execute("INSERT INTO ${_state_table} (s_name) VALUES ('undone')");
  }

  Future<List<taskBooksDataModel>> getTables({String whereValue = ""}) async {
    Database db = await database;

    if (whereValue == "") {
      var result = await db.rawQuery("SELECT * FROM ${_chartTable}");

      return taskBooksDataModel.convertToTaskBookDataModel(result);
    } else {
      var result = await db.rawQuery("SELECT * FROM ${_chartTable} WHERE c_name LIKE '${whereValue}%'");

      return taskBooksDataModel.convertToTaskBookDataModel(result);
    }
  }

  Future<int> createTaskBook(taskBooksDataModel table) async {
    Database db = await database;
    return await db.rawInsert("INSERT INTO ${_chartTable} (c_name) VALUES ('${table.taskBookName}')");
  }

  Future<int> deleteTaskBook(taskBooksDataModel table) async {
    Database db = await database;
    return await db.rawDelete("DELETE FROM ${_chartTable} WHERE c_id = '${table.taskBookId}'");
  }

  Future<List<taskDataModel>> getTasks(taskBooksDataModel table, {String whereValue = ""}) async {
    Database db = await database;

    if (whereValue == "") {
      var result = await db.rawQuery("SELECT * FROM ${_taskTable} WHERE c_id = '${table.taskBookId}'");
      return taskDataModel.convertToTasksDataModel(result);
    } else {
      var result = await db.rawQuery("SELECT * FROM ${_taskTable} WHERE c_id = '${table.taskBookId}' AND t_name LIKE '${whereValue}%'");
      return taskDataModel.convertToTasksDataModel(result);
    }
  }

  Future<int> createTask(taskDataModel value) async {
    Database db = await database;
    return await db.rawInsert("INSERT INTO ${_taskTable} (t_name, t_content, t_date, c_id) VALUES ('${value.taskName}', '${value.taskContent}', '${value.taskDate}', '${value.tableId}')");
  }

  Future<int> deleteTask(taskDataModel value) async {
    Database db = await database;
    return await db.rawDelete("DELETE FROM ${_taskTable} WHERE t_id = '${value.taskId}'");
  }

  Future<int> changeTaskState(taskDataModel value) async {
    Database db = await database;
    return await db.rawUpdate("UPDATE ${_taskTable} SET s_id = '1' WHERE t_id = '${value.taskId}'");
  }
}
</code>```

Body:
I want to make a to do list application. I use Flutter & Dart. I tried to add condition where i got datas but it did not work. I do not know what i need to do. I got this error many places.
SnackBars do not works, i do not know why. This app have task books and tasks. When i want to see tasks of task book, it does not give me this error but when i want to search a task, it gives this error.

Error

The following _CastError was thrown building FutureBuilder<List<taskBooksDataModel>>(state: _FutureBuilderState<List<taskBooksDataModel>>#56975):
Null check operator used on a null value

The relevant error-causing widget was:
  FutureBuilder<List<taskBooksDataModel>> FutureBuilder:file:///C:/Users/Administrator/Desktop/todolist/lib/screens/generalListerWidgets/taskBookWidget.dart:22:12
When the exception was thrown, this was the stack:
#0      _SnackBarState.initState (package:flutter/src/material/snack_bar.dart:391:21)
#1      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:5015:57)
#2      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5)
...     Normal element mounting (50 frames)
#52     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3863:16)
#53     MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6435:36)
#54     MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6447:32)
...     Normal element mounting (387 frames)

Data Model

class taskBooksDataModel {
  late int taskBookId;
  late String taskBookName;

  taskBooksDataModel() {}

  taskBooksDataModel.withOutId(this.taskBookName);
  taskBooksDataModel.withInfo(this.taskBookId, this.taskBookName);
  taskBooksDataModel.justWithId(this.taskBookId);

  static List<taskBooksDataModel> convertToTaskBookDataModel(List<Map<String, Object?>> value) {
    List<taskBooksDataModel> newList = [];
    for(int i = 0; i < value.length; i++) {
      newList.add(new taskBooksDataModel.withInfo(int.parse(value[i]["c_id"].toString()), value[i]["c_name"].toString()));
    }
    return newList;
  }
}

Widget

import 'package:flutter/material.dart';
import "package:flutter/cupertino.dart";
import 'package:todolist/dataModels/taskBookDataModel.dart';
import 'package:todolist/database/database.dart';
import 'package:todolist/screens/tasksScreen/tasksScreen.dart';

class taskBooksWidget extends StatefulWidget {
  late String searchingValue;
  Function callback;

  taskBooksWidget(this.callback, {this.searchingValue = ""});

  @override
  State<taskBooksWidget> createState() => _taskBooksWidgetState();
}

class _taskBooksWidgetState extends State<taskBooksWidget> {
  @override
  Widget build(BuildContext context) {
    databaseHelper databaseTrans = new databaseHelper();

    return FutureBuilder(
      future: databaseTrans.getTables(whereValue: widget.searchingValue),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return taskBookErrorWidget(context);
        } else if (snapshot.data == null) {
          return taskBookErrorWidget(context);
        } else {
          return GridView.count(
            crossAxisCount: 3,
            children: List.generate(snapshot.data!.length, (i) {
              return Dismissible(
                  key: Key(snapshot.data![i].taskBookId.toString()),
                  direction: DismissDirection.horizontal,
                  child: Container(
                    margin: EdgeInsets.all(10),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Colors.white10,
                      borderRadius: BorderRadius.circular(30),
                    ),
                    child: InkWell(
                      onTap: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => tasksScreen(
                                    snapshot.data![i].taskBookId,
                                    snapshot.data![i].taskBookName)));
                      },
                      child: Text(snapshot.data![i].taskBookName.toString(),
                          style: TextStyle(color: Colors.white)),
                    ),
                  ),
                  onDismissed: (DismissDirection direction) {
                    databaseTrans.deleteTaskBook(
                        new taskBooksDataModel.justWithId(
                            snapshot.data![i].taskBookId));
                    widget.callback();
                  });
            }),
          );
        }
      },
    );
  }

  SnackBar taskBookErrorWidget(BuildContext context) {
    return SnackBar(
      content: Text(
        "There is no task book",
        style: TextStyle(fontSize: 20, color: Colors.white),
      ),
      behavior: SnackBarBehavior.floating,
      backgroundColor: Colors.pinkAccent,
      dismissDirection: DismissDirection.startToEnd,
    );
  }
}

Database Function

import 'dart:async';
import "package:sqflite/sqflite.dart";
import "package:path/path.dart";
import 'package:todolist/dataModels/taskBookDataModel.dart';
import 'package:todolist/dataModels/tasksDataModel.dart';

class databaseHelper {
  Database? _databaseConn;

  final _chartTable = "charts_table";
  final _taskTable = "tasks_table";
  final _state_table = "state_table";

  Future get database async {
    if (_databaseConn == null) {
      _databaseConn = await databaseConnect();
    } else {
      return _databaseConn;
    }
    return _databaseConn;
  }

  Future<Database> databaseConnect() async {
    String path = join(getDatabasesPath().toString(), "8hhgjgggegerege.db");
    var connection = await openDatabase(path, version: 1, onCreate: createDefaultDatabase);
    return connection;
  }

  FutureOr<void> createDefaultDatabase(Database db, int version) async {
    db.execute("CREATE TABLE IF NOT EXISTS ${_chartTable} (c_id INTEGER NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT, c_name TEXT NOT NULL)");
    db.execute("CREATE TABLE IF NOT EXISTS ${_state_table} (s_id INTEGER NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT, s_name TEXT NOT NULL)");
    db.execute("CREATE TABLE IF NOT EXISTS ${_taskTable} (t_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, t_name TEXT NOT NULL, t_content TEXT NOT NULL, t_date TEXT NOT NULL, c_id INTEGER NOT NULL, s_id INT NOT NULL DEFAULT '2')");

    db.execute("INSERT INTO ${_state_table} (s_name) VALUES ('done')");
    db.execute("INSERT INTO ${_state_table} (s_name) VALUES ('undone')");
  }

  Future<List<taskBooksDataModel>> getTables({String whereValue = ""}) async {
    Database db = await database;

    if (whereValue == "") {
      var result = await db.rawQuery("SELECT * FROM ${_chartTable}");

      return taskBooksDataModel.convertToTaskBookDataModel(result);
    } else {
      var result = await db.rawQuery("SELECT * FROM ${_chartTable} WHERE c_name LIKE '${whereValue}%'");

      return taskBooksDataModel.convertToTaskBookDataModel(result);
    }
  }

  Future<int> createTaskBook(taskBooksDataModel table) async {
    Database db = await database;
    return await db.rawInsert("INSERT INTO ${_chartTable} (c_name) VALUES ('${table.taskBookName}')");
  }

  Future<int> deleteTaskBook(taskBooksDataModel table) async {
    Database db = await database;
    return await db.rawDelete("DELETE FROM ${_chartTable} WHERE c_id = '${table.taskBookId}'");
  }

  Future<List<taskDataModel>> getTasks(taskBooksDataModel table, {String whereValue = ""}) async {
    Database db = await database;

    if (whereValue == "") {
      var result = await db.rawQuery("SELECT * FROM ${_taskTable} WHERE c_id = '${table.taskBookId}'");
      return taskDataModel.convertToTasksDataModel(result);
    } else {
      var result = await db.rawQuery("SELECT * FROM ${_taskTable} WHERE c_id = '${table.taskBookId}' AND t_name LIKE '${whereValue}%'");
      return taskDataModel.convertToTasksDataModel(result);
    }
  }

  Future<int> createTask(taskDataModel value) async {
    Database db = await database;
    return await db.rawInsert("INSERT INTO ${_taskTable} (t_name, t_content, t_date, c_id) VALUES ('${value.taskName}', '${value.taskContent}', '${value.taskDate}', '${value.tableId}')");
  }

  Future<int> deleteTask(taskDataModel value) async {
    Database db = await database;
    return await db.rawDelete("DELETE FROM ${_taskTable} WHERE t_id = '${value.taskId}'");
  }

  Future<int> changeTaskState(taskDataModel value) async {
    Database db = await database;
    return await db.rawUpdate("UPDATE ${_taskTable} SET s_id = '1' WHERE t_id = '${value.taskId}'");
  }
}


问:
Error 500 : upload file AWS3, multer, Angular
I want to upload a file to AWS-S3 with an Angular frontend and a Node.js/Multer backend. I get a 500 error when I put everything together:

index.ts (server side)

```<code>import aws from 'aws-sdk';
import multer, { FileFilterCallback, MulterError } from 'multer';
import multerS3 from 'multer-s3';
import { Request } from 'express';
import { v4 as uuid4 } from 'uuid';
import path from 'path';

const s3 = new aws.S3({
  secretAccessKey: process.env.S3_ACCESS_SECRET,
  accessKeyId: process.env.S3_ACCESS_KEY,
  region: 'eu-west-3',
});

const fileFilter = (
  req: Request,
  file: Express.Multer.File,
  cb: FileFilterCallback // FileFilterCallback
) => {
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(new MulterError('LIMIT_UNEXPECTED_FILE'));
    //cb(new Error('Invalid file type, only JPEG and PNG is allowed!'), false);
  }
};

const upload = multer({
  fileFilter,
  storage: multerS3({
    acl: 'public-read',
    s3,
    bucket: 'bucket',
    contentType: multerS3.AUTO_CONTENT_TYPE,
    metadata: function (req, file, cb) {
      console.log('Called when saving image  to AWS');
      cb(null, { fieldName: 'TESTING_METADATA' });
    },
    key: function (req, file, cb) {
      console.log('FILE ==> ' + JSON.stringify(file));
      cb(null, uuid4().replace(/-/g, '') + path.extname(file.originalname));
    },
  }),
});

// -----------------------------------
//           RAYONS
// -----------------------------------
router
  .route('/rayons')
  .get(ctrlRayons.rayonsListe)
  .post(upload.single('imgInp'), ctrlRayons.rayonsCreer);
//.post(ctrlRayons.rayonsTest);
</code>```

ctrlRayons.rayonsCreer (for the POST request)

```<code>const rayonsCreer = (req: express.Request, res: express.Response) => {
  let imgRayon: File | string;
  if (req.file) {
    imgRayon = req.file;
  } else {
    imgRayon = 'https://via.placeholder.com/150';
  }

  Rayon.create(
    {
      auteur: 'auteur',
      nom: req.body.nom,
      img: imgRayon,
    },
    (err: express.ErrorRequestHandler, rayon: TypeRayon) => {
      if (err) {
        res.status(400).json(err);
      } else {
        res.status(201).json(rayon);
      }
    }
  );
};
</code>```

rayons-form.component.html

```<code><h6>Angular 15 FormData (multipart/data-form) Example</h6>
<div>
    <form [formGroup]="uploadForm" (ngSubmit)="onSubmit()">
        <div>
            <input type="text" name="nom" />
        </div>
        <div>
            <input type="file" name="imgInp" (change)="onFileSelect($event)" />
        </div>
        <div>
            <button type="submit">Upload</button>
        </div>
    </form>
</div>
</code>```

rayons-form.component.ts

```<code>export class RayonsFormComponent implements OnInit {
  SERVER_URL = 'http://localhost:3000/api/rayons';
  uploadForm: FormGroup;
  constructor(
    private formBuilder: FormBuilder,
    private httpClient: HttpClient
  ) {
    this.uploadForm = this.formBuilder.group({
      nom: '',
      imgInp: [''],
    });
  }

  onFileSelect(event: any) {
    const file = event.target.files[0];
    this.uploadForm.patchValue({
      imgInp: file,
    });
    this.uploadForm.get('imgInp')?.updateValueAndValidity();
  }

  onSubmit() {
    const formData = new FormData();
    formData.append('nom', this.uploadForm.get('nom')?.value);
    formData.append('imgInp', this.uploadForm.get('imgInp')?.value);

    this.httpClient.post<any>(this.SERVER_URL, formData).subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );
  }

  ngOnInit(): void {}
}
</code>```

I googled and tried everything I could but still getting the same error. Thanks in advance for your quick help!

Body:
I want to upload a file to AWS-S3 with an Angular frontend and a Node.js/Multer backend. I get a 500 error when I put everything together:

index.ts (server side)

import aws from 'aws-sdk';
import multer, { FileFilterCallback, MulterError } from 'multer';
import multerS3 from 'multer-s3';
import { Request } from 'express';
import { v4 as uuid4 } from 'uuid';
import path from 'path';

const s3 = new aws.S3({
  secretAccessKey: process.env.S3_ACCESS_SECRET,
  accessKeyId: process.env.S3_ACCESS_KEY,
  region: 'eu-west-3',
});

const fileFilter = (
  req: Request,
  file: Express.Multer.File,
  cb: FileFilterCallback // FileFilterCallback
) => {
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(new MulterError('LIMIT_UNEXPECTED_FILE'));
    //cb(new Error('Invalid file type, only JPEG and PNG is allowed!'), false);
  }
};

const upload = multer({
  fileFilter,
  storage: multerS3({
    acl: 'public-read',
    s3,
    bucket: 'bucket',
    contentType: multerS3.AUTO_CONTENT_TYPE,
    metadata: function (req, file, cb) {
      console.log('Called when saving image  to AWS');
      cb(null, { fieldName: 'TESTING_METADATA' });
    },
    key: function (req, file, cb) {
      console.log('FILE ==> ' + JSON.stringify(file));
      cb(null, uuid4().replace(/-/g, '') + path.extname(file.originalname));
    },
  }),
});

// -----------------------------------
//           RAYONS
// -----------------------------------
router
  .route('/rayons')
  .get(ctrlRayons.rayonsListe)
  .post(upload.single('imgInp'), ctrlRayons.rayonsCreer);
//.post(ctrlRayons.rayonsTest);

ctrlRayons.rayonsCreer (for the POST request)

const rayonsCreer = (req: express.Request, res: express.Response) => {
  let imgRayon: File | string;
  if (req.file) {
    imgRayon = req.file;
  } else {
    imgRayon = 'https://via.placeholder.com/150';
  }

  Rayon.create(
    {
      auteur: 'auteur',
      nom: req.body.nom,
      img: imgRayon,
    },
    (err: express.ErrorRequestHandler, rayon: TypeRayon) => {
      if (err) {
        res.status(400).json(err);
      } else {
        res.status(201).json(rayon);
      }
    }
  );
};

rayons-form.component.html

Angular 15 FormData (multipart/data-form) Example

    <form [formGroup]="uploadForm" (ngSubmit)="onSubmit()">

            <input type="text" name="nom" />

            <input type="file" name="imgInp" (change)="onFileSelect($event)" />

            <button type="submit">Upload</button>

    </form>

rayons-form.component.ts

export class RayonsFormComponent implements OnInit {
  SERVER_URL = 'http://localhost:3000/api/rayons';
  uploadForm: FormGroup;
  constructor(
    private formBuilder: FormBuilder,
    private httpClient: HttpClient
  ) {
    this.uploadForm = this.formBuilder.group({
      nom: '',
      imgInp: [''],
    });
  }

  onFileSelect(event: any) {
    const file = event.target.files[0];
    this.uploadForm.patchValue({
      imgInp: file,
    });
    this.uploadForm.get('imgInp')?.updateValueAndValidity();
  }

  onSubmit() {
    const formData = new FormData();
    formData.append('nom', this.uploadForm.get('nom')?.value);
    formData.append('imgInp', this.uploadForm.get('imgInp')?.value);

    this.httpClient.post<any>(this.SERVER_URL, formData).subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );
  }

  ngOnInit(): void {}
}

I googled and tried everything I could but still getting the same error. Thanks in advance for your quick help!


问:
How to resolve the tree dependencies problem for run knex.js migrations scripts

Problem

I am trying to run the knex.js migration script knex migrate:latest --env development, but I am getting an error message. I have also tried using the --esm flag, but that results in another error message.

Proof

Here are photos of the error messages I am getting:

Error message without -esm flag:

```<code>npm run migrateDev

> memr-api@0.23.0 migrateDev
> knex migrate:latest --env development

Requiring external module ts-node/register
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/alucard/Work/kepler/api/knexfile.ts
    at new NodeError (node:internal/errors:371:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:87:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:102:38)
    at defaultLoad (node:internal/modules/esm/load:21:14)
    at ESMLoader.load (node:internal/modules/esm/loader:359:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:280:58)
    at new ModuleJob (node:internal/modules/esm/module_job:66:26)
    at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:297:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:261:34)
    at async Promise.all (index 0)
</code>```

Error message with -esm flag:

```<code>npm run migrateDev

> memr-api@0.23.0 migrateDev
> knex --esm migrate:latest --env development

Requiring external module ts-node/register
/Users/alucard/Work/kepler/api/migrations/20221212111522_add-other-not-listed-record-to-fda-drug-table.ts:4
export async function up(knex: Knex): Promise<void> {
                             ^

SyntaxError: Invalid or unexpected token
    at Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
</code>```

Here is a photo of my tsconfig.json file:

```<code>{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "tmp",
    "paths": {
      "*": ["*"]
    },
    "target": "esnext",
    "module": "esnext",
    "lib": ["es2020", "dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": false,
    "noEmit": true,
    "jsx": "preserve",
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUnusedLocals": true,
    "useUnknownInCatchVariables": false,
    "inlineSourceMap": true
  },
  "include": ["src"],
  "ts-node": {
    "esm": true
  },
  "lib": ["esnext"]
}

</code>```

Here is a photo of my knexfile.ts config:

```<code>const knexConfig = {
  client: "pg",
  connection,
  migrations: {
    directory: "migrations",
    tableName: "knex_migrations",
    extension: "ts",
  },
  seeds: {
    directory: "seeds",
    extension: "ts",
  },
  useNullAsDefault: true,
};

module.exports = knexConfig;
export default knexConfig;
</code>```

Question

What suggestions do you have for resolving this problem with the knex.js migration script?

Thanks to all who tried to help and for attention to my trouble

What I've Tried

I have tried using different node versions (v14.21.2, v16.14.2, v18.12.1, and v19.1.0) and switching between them using nvm.

I have deleted the node_modules and package-lock.json directories and reinstalled the dependencies using npm i --force.

I have tried installing the dependencies with a simple npm i, but that results in an error message.

Body:
Problem

I am trying to run the knex.js migration script knex migrate:latest --env development, but I am getting an error message. I have also tried using the --esm flag, but that results in another error message.

Proof

Here are photos of the error messages I am getting:

Error message without -esm flag:

npm run migrateDev

> memr-api@0.23.0 migrateDev
> knex migrate:latest --env development

Requiring external module ts-node/register
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/alucard/Work/kepler/api/knexfile.ts
    at new NodeError (node:internal/errors:371:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:87:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:102:38)
    at defaultLoad (node:internal/modules/esm/load:21:14)
    at ESMLoader.load (node:internal/modules/esm/loader:359:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:280:58)
    at new ModuleJob (node:internal/modules/esm/module_job:66:26)
    at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:297:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:261:34)
    at async Promise.all (index 0)

Error message with -esm flag:

npm run migrateDev

> memr-api@0.23.0 migrateDev
> knex --esm migrate:latest --env development

Requiring external module ts-node/register
/Users/alucard/Work/kepler/api/migrations/20221212111522_add-other-not-listed-record-to-fda-drug-table.ts:4
export async function up(knex: Knex): Promise<void> {
                             ^

SyntaxError: Invalid or unexpected token
    at Module._extensions..js (node:internal/modules/cjs/loader:1157:10)

Here is a photo of my tsconfig.json file:

{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "tmp",
    "paths": {
      "*": ["*"]
    },
    "target": "esnext",
    "module": "esnext",
    "lib": ["es2020", "dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": false,
    "noEmit": true,
    "jsx": "preserve",
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUnusedLocals": true,
    "useUnknownInCatchVariables": false,
    "inlineSourceMap": true
  },
  "include": ["src"],
  "ts-node": {
    "esm": true
  },
  "lib": ["esnext"]
}

Here is a photo of my knexfile.ts config:

const knexConfig = {
  client: "pg",
  connection,
  migrations: {
    directory: "migrations",
    tableName: "knex_migrations",
    extension: "ts",
  },
  seeds: {
    directory: "seeds",
    extension: "ts",
  },
  useNullAsDefault: true,
};

module.exports = knexConfig;
export default knexConfig;

Question

What suggestions do you have for resolving this problem with the knex.js migration script?

Thanks to all who tried to help and for attention to my trouble

What I've Tried

I have tried using different node versions (v14.21.2, v16.14.2, v18.12.1, and v19.1.0) and switching between them using nvm.

I have deleted the node_modules and package-lock.json directories and reinstalled the dependencies using npm i --force.

I have tried installing the dependencies with a simple npm i, but that results in an error message.


问:
Can I make a proxy_pass to a service that is not enabled?
My doubt begins because I have an nginx and a number of dockerized apis in a virtual machine. In my nginx.conf file I have each api defined as follows:

```<code>location /items {
      set $backend_server http://api-items:8080;
      # Access swagger via proxy
      location ~ ^(/items/).*\.(js|css|html|png|json)$ {
        set $backend_server http://api-items:8080;
        rewrite ^/items/(.*)$ /$1 break;
        proxy_pass $backend_server;
      }
      proxy_set_header X-Forwarded-For $remote_addr;
      proxy_set_header Host            $http_host;
      proxy_pass $backend_server/items;
    }
</code>```

For nginx to build correctly I need to have all the APIs built in my virtual machine.
The question is if I can have this directive for a service (url) that is not working. I don't know if there is a way to mark a url so that if the proxy_pass doesn't work, nginx doesn't throw you down.
Conditionals in location directives for nginx configuration

Body:
My doubt begins because I have an nginx and a number of dockerized apis in a virtual machine. In my nginx.conf file I have each api defined as follows:

location /items {
      set $backend_server http://api-items:8080;
      # Access swagger via proxy
      location ~ ^(/items/).*\.(js|css|html|png|json)$ {
        set $backend_server http://api-items:8080;
        rewrite ^/items/(.*)$ /$1 break;
        proxy_pass $backend_server;
      }
      proxy_set_header X-Forwarded-For $remote_addr;
      proxy_set_header Host            $http_host;
      proxy_pass $backend_server/items;
    }

For nginx to build correctly I need to have all the APIs built in my virtual machine.
The question is if I can have this directive for a service (url) that is not working. I don't know if there is a way to mark a url so that if the proxy_pass doesn't work, nginx doesn't throw you down.
Conditionals in location directives for nginx configuration


问:
JsTree invisible after reload the page
I have a button to create first node in jstree after submit that form page reload and jstree not visible.

js

```<code>$(document).on("click", "#templatename", function() {
    let templatename = $(".template_name").val();
    let csr = $("input[name=csrfmiddlewaretoken]").val();
    mydata = { templatename: templatename, csrfmiddlewaretoken: csr };
    $.ajax({
        url: '/templatename/',
        type: "POST",
        data: mydata,
        success: function (data) {
            let template_name = data.data
            createJSTree(template_name)
        },
        error: function (e) {
            console.error(e)
        }
    });
});

function createJSTree(template_name) {
    $('#jstree_template').jstree({
        "core": {
            "themes": {
                "responsive": false
            },
            "check_callback": true,
            'data': template_name,
        },
        "types": {
          "default": {
              "icon": "fa fa-folder text-primary"
          },
          "file": {
              "icon": "fa fa-file  text-primary"
          }
        },
        "state": {
            "key": "demo2"
        },
        "plugins": ["contextmenu", "state", "types"],
        "contextmenu": {
            "items": function ($node) {
                var tree = $("#jstree_template").jstree(true);
                return {
                    "Create": {
                        "separator_before": false,
                        "separator_after": true,
                        "label": "Create",
                        "action":
                            function (obj) {
                                for (let i = 0; i<template_name.length; i++){
                                    debugger
                                    obj_id = obj.reference[0].id.split('_')[0]
                                    obj_hastag = obj.reference[0].href.split('/')[3]

                                    data_id= `${template_name[i].id}`
                                    data_hastag = `${template_name[i].parent}`

                                    obj_id_hastag = obj_id + obj_hastag
                                    data_id_hastag = data_id + data_hastag

                                    if(obj_id_hastag == data_id_hastag)
                                    {
                                        $('#template_modal').modal('show');
                                    }
                                    else if(obj.reference[0].id.split('_').slice(0,2).join('_') == `${template_name[i].id}`){

                                        $('#mode_modal').modal('show');
                                    }
                                   else if(obj.reference[0].id.split('_').slice(0,2).join('_') == `${template_name[i].id}_anchor`){

                                        $('#mode_modal').modal('show');
                                    }

                                }

                        }
                    },
                    "Rename": {
                        "separator_before": false,
                        "separator_after": false,
                        "label": "Rename",
                        "action": function (obj) {
                            tree.edit($node);
                        }
                    },
                    "Delete": {
                        "separator_before": false,
                        "separator_after": false,
                        "label": "Delete",
                        "action": function (obj) {
                            tree.delete_node($node);
                        }
                    }
                };
            }
        }
    }).on('select_node.jstree', function (e, data) {
        var tree_data = template_name
        debugger
        if(data.node.text == tree_data[1].text){

            location.href = data.node.a_attr.href;
            data.node.a_attr.href = document.location.origin + '/channel/'

        }
        else if(data.node.text == tree_data[2].text){

            location.href = data.node.a_attr.href;
            data.node.a_attr.href = document.location.origin + '/mode/'

        }
        for(i=0; i<template_name.length; i++){
            if(data.node.id == template_name[i].id ){
                debugger
                location.href = data.node.a_attr.href;
                data.node.a_attr.href = document.location.origin + '/template/' + template_name[i].id
            }
        }
    });

}
</code>```

views.py

in view file I created a two class one which is createtemplatenameview for submit form which is click on button and after submit data save into database and templatejstreeview is creating jstree after getting data from database and creating jstree.

```<code>class TemplateJstreeView(View):

    def post(self,request):
        data = []
        template_name = TemplateName.objects.values()
        mode_name = Mode.objects.values()
        for index,result in enumerate(template_name):
            data.append({'id':result['id'],'parent':'#','text':result['name']})
            data.append({'id':f'{index}_channel','parent':result['id'],'text':'Channel List'})
            data.append({'id':f'{index}_mode','parent':result['id'],'text':'Mode Condition'})
            for values in mode_name:
                if(result['id'] == values['template_id']):
                    data.append({'id':values['id'], 'parent':f'{index}_mode','text':values['mode_name']})
        return JsonResponse({'data':data})

class CreateTemplateNameView(TemplateView):
    form_class = TemplateNameForm
    template_name = 'anomaly_template/create_template.html'

    def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        template_form = context["template_form"]

        if template_form.is_valid():
            form_obj = template_form.save(commit=False)
            form_obj.user = request.user
            id = request.POST.get('templatename-id')
            name = request.POST.get('name')
            if(id == ''):
                if (TemplateName.objects.filter(name=name)):
                    messages.error(self.request, f'{self.request.POST.get("name")} was Already Exists')
                else:
                    form_obj.save()
                    messages.success(self.request, f'{self.request.POST.get("name")} was Created Successfully')

        return super(TemplateView, self).render_to_response(context)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        template_form = TemplateNameForm(self.request.POST or None)
        context["template_form"] = template_form
        context['TemplateName'] = TemplateName.objects.all()
        return context

</code>```

urls.py

```<code>  path('',login_required(CreateTemplateNameView.as_view()),name='template'),
  path("templatename/", login_required(TemplateJstreeView.as_view()), name="templatename"),
</code>```

Title: JsTree invisible after reload the page

Body:
I have a button to create first node in jstree after submit that form page reload and jstree not visible.

js

$(document).on("click", "#templatename", function() {
    let templatename = $(".template_name").val();
    let csr = $("input[name=csrfmiddlewaretoken]").val();
    mydata = { templatename: templatename, csrfmiddlewaretoken: csr };
    $.ajax({
        url: '/templatename/',
        type: "POST",
        data: mydata,
        success: function (data) {
            let template_name = data.data
            createJSTree(template_name)
        },
        error: function (e) {
            console.error(e)
        }
    });
});

function createJSTree(template_name) {
    $('#jstree_template').jstree({
        "core": {
            "themes": {
                "responsive": false
            },
            "check_callback": true,
            'data': template_name,
        },
        "types": {
          "default": {
              "icon": "fa fa-folder text-primary"
          },
          "file": {
              "icon": "fa fa-file  text-primary"
          }
        },
        "state": {
            "key": "demo2"
        },
        "plugins": ["contextmenu", "state", "types"],
        "contextmenu": {
            "items": function ($node) {
                var tree = $("#jstree_template").jstree(true);
                return {
                    "Create": {
                        "separator_before": false,
                        "separator_after": true,
                        "label": "Create",
                        "action":
                            function (obj) {
                                for (let i = 0; i<template_name.length; i++){
                                    debugger
                                    obj_id = obj.reference[0].id.split('_')[0]
                                    obj_hastag = obj.reference[0].href.split('/')[3]

                                    data_id= `${template_name[i].id}`
                                    data_hastag = `${template_name[i].parent}`

                                    obj_id_hastag = obj_id + obj_hastag
                                    data_id_hastag = data_id + data_hastag

                                    if(obj_id_hastag == data_id_hastag)
                                    {
                                        $('#template_modal').modal('show');
                                    }
                                    else if(obj.reference[0].id.split('_').slice(0,2).join('_') == `${template_name[i].id}`){

                                        $('#mode_modal').modal('show');
                                    }
                                   else if(obj.reference[0].id.split('_').slice(0,2).join('_') == `${template_name[i].id}_anchor`){

                                        $('#mode_modal').modal('show');
                                    }

                                }

                        }
                    },
                    "Rename": {
                        "separator_before": false,
                        "separator_after": false,
                        "label": "Rename",
                        "action": function (obj) {
                            tree.edit($node);
                        }
                    },
                    "Delete": {
                        "separator_before": false,
                        "separator_after": false,
                        "label": "Delete",
                        "action": function (obj) {
                            tree.delete_node($node);
                        }
                    }
                };
            }
        }
    }).on('select_node.jstree', function (e, data) {
        var tree_data = template_name
        debugger
        if(data.node.text == tree_data[1].text){

            location.href = data.node.a_attr.href;
            data.node.a_attr.href = document.location.origin + '/channel/'

        }
        else if(data.node.text == tree_data[2].text){

            location.href = data.node.a_attr.href;
            data.node.a_attr.href = document.location.origin + '/mode/'

        }
        for(i=0; i<template_name.length; i++){
            if(data.node.id == template_name[i].id ){
                debugger
                location.href = data.node.a_attr.href;
                data.node.a_attr.href = document.location.origin + '/template/' + template_name[i].id
            }
        }
    });

}

views.py

in view file I created a two class one which is createtemplatenameview for submit form which is click on button and after submit data save into database and templatejstreeview is creating jstree after getting data from database and creating jstree.

class TemplateJstreeView(View):

    def post(self,request):
        data = []
        template_name = TemplateName.objects.values()
        mode_name = Mode.objects.values()
        for index,result in enumerate(template_name):
            data.append({'id':result['id'],'parent':'#','text':result['name']})
            data.append({'id':f'{index}_channel','parent':result['id'],'text':'Channel List'})
            data.append({'id':f'{index}_mode','parent':result['id'],'text':'Mode Condition'})
            for values in mode_name:
                if(result['id'] == values['template_id']):
                    data.append({'id':values['id'], 'parent':f'{index}_mode','text':values['mode_name']})
        return JsonResponse({'data':data})

class CreateTemplateNameView(TemplateView):
    form_class = TemplateNameForm
    template_name = 'anomaly_template/create_template.html'

    def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        template_form = context["template_form"]

        if template_form.is_valid():
            form_obj = template_form.save(commit=False)
            form_obj.user = request.user
            id = request.POST.get('templatename-id')
            name = request.POST.get('name')
            if(id == ''):
                if (TemplateName.objects.filter(name=name)):
                    messages.error(self.request, f'{self.request.POST.get("name")} was Already Exists')
                else:
                    form_obj.save()
                    messages.success(self.request, f'{self.request.POST.get("name")} was Created Successfully')

        return super(TemplateView, self).render_to_response(context)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        template_form = TemplateNameForm(self.request.POST or None)
        context["template_form"] = template_form
        context['TemplateName'] = TemplateName.objects.all()
        return context

urls.py

  path('',login_required(CreateTemplateNameView.as_view()),name='template'),
  path("templatename/", login_required(TemplateJstreeView.as_view()), name="templatename"),


问:
Freqtrade Shorting Strategy implementing
I am trying to apply a short/leverage strategy using freqtrade but getting stuck in one place I made the necessary changes for that(can_short: bool = True, def leverage,populate_exit_trend,populate_entry_trend,populate_indicators, "trading_mode": "futures", "margin_mode": "isolated", "liquidation_buffer":0.05) but still I am stuck at the strategy part it is not trading in short mode not event in DRY RUN so anybody ca help me with that

I tried this thing in Strategy Customization(can_short: bool = True, def leverage,populate_exit_trend,populate_entry_trend,populate_indicators, "trading_mode": "futures", "margin_mode": "isolated", "liquidation_buffer":0.05) and I am expecting the short mode trading in the freqtrade

is there anybody who that guide me with these problems

thank you in advance!


问:
Producer Consumer problem: Incompatible pointer type C
The code returns the following output. I saw a similar issue before but the solve there was

```<code>void* funcname(void *args) {
}
</code>```

I applied that and yet I am still facing this issue. I tried what i know so far and am only ending up with a part of the output. I am confused as to what is causing the issue.

```<code>main.c: In function ‘main’:
main.c:33:42: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [-Wincompatible-pointer-types]
   33 |         pthread_create(&thread[i], NULL, producer, &thread_id[i]);
      |                                          ^~~~~~~~
      |                                          |
      |                                          void * (*)(int *)
In file included from main.c:2:
/usr/include/pthread.h:200:15: note: expected ‘void * (*)(void *)’ but argument is of type ‘void * (*)(int *)’
  200 |       void *(*__start_routine) (void *),
      |       ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
main.c:36:42: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [-Wincompatible-pointer-types]
   36 |         pthread_create(&thread[i], NULL, consumer, &thread_id[i]);
      |                                          ^~~~~~~~
      |                                          |
      |                                          void * (*)(int *)
In file included from main.c:2:
/usr/include/pthread.h:200:15: note: expected ‘void * (*)(void *)’ but argument is of type ‘void * (*)(int *)’
  200 |       void *(*__start_routine) (void *),
      |       ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
main.c:30:5: warning: ‘__builtin_memcpy’ writing 7 bytes into a region of size 6 overflows the destination [-Wstringop-overflow=]
   30 |     strcpy(source, "abcdef");
      |     ^~~~~~~~~~~~~~~~~~~~~~~~
1 is produced abcdef in buffer
1 is consuming  from buffer
0 is consuming  from buffer
</code>```

I was attempting the Producer Consumer Issue. This is my approach to the problem using mutex, sephamore and pthreads. My entire code is:

```<code>#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10
#define BUFLEN 6
#define NUMTHREAD 2

void* consumer(int *id);
void* producer(int *id);

char buffer[BUFLEN];
char source[BUFLEN];
int pCount = 0;
int cCount = 0;
int buflen;

pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t nonEmpty = PTHREAD_COND_INITIALIZER;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
int thread_id[NUMTHREAD] = {0, 1};
int i = 0;
int j = 0;

int main()
{
    int i;
    pthread_t thread[NUMTHREAD];
    strcpy(source, "abcdef");
    buflen = strlen(source);
    for (i = 0; i < NUMTHREAD; i++){
        pthread_create(&thread[i], NULL, producer, &thread_id[i]);
    }
    for (i = 0; i < NUMTHREAD; i++){
        pthread_create(&thread[i], NULL, consumer, &thread_id[i]);
    }
    for (i = 0; i < NUMTHREAD; i++){
        pthread_join(thread[i], NULL);
    }
    printf("\n");
}

void *producer(int *id)
{
    int i;
    pthread_mutex_lock(&count_mutex);
    while (pCount == MAX)
    {
        printf("Producer %d is waiting for empty buffer\n", *id);
        pthread_cond_wait(&nonEmpty, &count_mutex);
    }
    for (i = 0; i < BUFLEN; i++)
    {
        buffer[i] = source[i];
    }
    pCount++;
    printf("%d is produced %s in buffer\n", *id, source);
    pthread_cond_signal(&full);
    pthread_mutex_unlock(&count_mutex);
}

void *consumer(int *id)
{
    int i;
    pthread_mutex_lock(&count_mutex);
    while (cCount == MAX)
    {
        printf("Consumer %d is waiting for full buffer\n", *id);
        pthread_cond_wait(&full, &count_mutex);
    }
    for (i = 0; i < BUFLEN; i++)
    {
        buffer[i] = '\0';
    }
    cCount++;
    printf("%d is consuming %s from buffer\n", *id, buffer);
    pthread_cond_signal(&nonEmpty);
    pthread_mutex_unlock(&count_mutex);
}
</code>```

Body:
The code returns the following output. I saw a similar issue before but the solve there was

void* funcname(void *args) {
}

I applied that and yet I am still facing this issue. I tried what i know so far and am only ending up with a part of the output. I am confused as to what is causing the issue.

main.c: In function ‘main’:
main.c:33:42: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [-Wincompatible-pointer-types]
   33 |         pthread_create(&thread[i], NULL, producer, &thread_id[i]);
      |                                          ^~~~~~~~
      |                                          |
      |                                          void * (*)(int *)
In file included from main.c:2:
/usr/include/pthread.h:200:15: note: expected ‘void * (*)(void *)’ but argument is of type ‘void * (*)(int *)’
  200 |       void *(*__start_routine) (void *),
      |       ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
main.c:36:42: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [-Wincompatible-pointer-types]
   36 |         pthread_create(&thread[i], NULL, consumer, &thread_id[i]);
      |                                          ^~~~~~~~
      |                                          |
      |                                          void * (*)(int *)
In file included from main.c:2:
/usr/include/pthread.h:200:15: note: expected ‘void * (*)(void *)’ but argument is of type ‘void * (*)(int *)’
  200 |       void *(*__start_routine) (void *),
      |       ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
main.c:30:5: warning: ‘__builtin_memcpy’ writing 7 bytes into a region of size 6 overflows the destination [-Wstringop-overflow=]
   30 |     strcpy(source, "abcdef");
      |     ^~~~~~~~~~~~~~~~~~~~~~~~
1 is produced abcdef in buffer
1 is consuming  from buffer
0 is consuming  from buffer

I was attempting the Producer Consumer Issue. This is my approach to the problem using mutex, sephamore and pthreads. My entire code is:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10
#define BUFLEN 6
#define NUMTHREAD 2

void* consumer(int *id);
void* producer(int *id);

char buffer[BUFLEN];
char source[BUFLEN];
int pCount = 0;
int cCount = 0;
int buflen;

pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t nonEmpty = PTHREAD_COND_INITIALIZER;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
int thread_id[NUMTHREAD] = {0, 1};
int i = 0;
int j = 0;

int main()
{
    int i;
    pthread_t thread[NUMTHREAD];
    strcpy(source, "abcdef");
    buflen = strlen(source);
    for (i = 0; i < NUMTHREAD; i++){
        pthread_create(&thread[i], NULL, producer, &thread_id[i]);
    }
    for (i = 0; i < NUMTHREAD; i++){
        pthread_create(&thread[i], NULL, consumer, &thread_id[i]);
    }
    for (i = 0; i < NUMTHREAD; i++){
        pthread_join(thread[i], NULL);
    }
    printf("\n");
}

void *producer(int *id)
{
    int i;
    pthread_mutex_lock(&count_mutex);
    while (pCount == MAX)
    {
        printf("Producer %d is waiting for empty buffer\n", *id);
        pthread_cond_wait(&nonEmpty, &count_mutex);
    }
    for (i = 0; i < BUFLEN; i++)
    {
        buffer[i] = source[i];
    }
    pCount++;
    printf("%d is produced %s in buffer\n", *id, source);
    pthread_cond_signal(&full);
    pthread_mutex_unlock(&count_mutex);
}

void *consumer(int *id)
{
    int i;
    pthread_mutex_lock(&count_mutex);
    while (cCount == MAX)
    {
        printf("Consumer %d is waiting for full buffer\n", *id);
        pthread_cond_wait(&full, &count_mutex);
    }
    for (i = 0; i < BUFLEN; i++)
    {
        buffer[i] = '\0';
    }
    cCount++;
    printf("%d is consuming %s from buffer\n", *id, buffer);
    pthread_cond_signal(&nonEmpty);
    pthread_mutex_unlock(&count_mutex);
}


问:
Jest Test is failing with the GlideJS - Cannot read property 'querySelector' of undefined
I had make a slider with GlideJS. This widget is working fine. But when I am writing the jest test. My Test is failing, it's saying TypeError: Cannot read property 'querySelector' of undefined. Here is the complete error while I am playing the test case.

```<code>    TypeError: Cannot read property 'querySelector' of undefined

  55 |     const slider = new Glide(sliderRef.current, options);
  56 |
> 57 |     slider.mount();
     |            ^
  58 |   }, [options]);
  59 |
  60 |   const handleOnMouseEnter = () => setNavigationVisible(true);
</code>```

Here is the Test Suite which I write down.

```<code>import React from 'react';
import renderer from 'react-test-renderer';
import Widget from './Widget';

const mockArray = [
  { title: 'Mock Title 1', completed: false },
  { title: 'Mock Title 2', completed: false },
  { title: 'Mock Title 3', completed: false },
];
describe('Widget', () => {
  it('renders Widget according to design', () => {
    const component = renderer.create(
      <Widget lessons={mockArray} title={'mock title'} />
    );
    const tree = component.toJSON();

    expect(tree).toMatchSnapshot();
  });
});
</code>```

Body:
I had make a slider with GlideJS. This widget is working fine. But when I am writing the jest test. My Test is failing, it's saying TypeError: Cannot read property 'querySelector' of undefined. Here is the complete error while I am playing the test case.

    TypeError: Cannot read property 'querySelector' of undefined

  55 |     const slider = new Glide(sliderRef.current, options);
  56 |
> 57 |     slider.mount();
     |            ^
  58 |   }, [options]);
  59 |
  60 |   const handleOnMouseEnter = () => setNavigationVisible(true);

Here is the Test Suite which I write down.

import React from 'react';
import renderer from 'react-test-renderer';
import Widget from './Widget';

const mockArray = [
  { title: 'Mock Title 1', completed: false },
  { title: 'Mock Title 2', completed: false },
  { title: 'Mock Title 3', completed: false },
];
describe('Widget', () => {
  it('renders Widget according to design', () => {
    const component = renderer.create(
      <Widget lessons={mockArray} title={'mock title'} />
    );
    const tree = component.toJSON();

    expect(tree).toMatchSnapshot();
  });
});


问:
how to custom styles for ngxboostrap time picker, i want arrow indicators position as same
<timepicker #timePicker class="check" onkeydown="event.preventDefault()"
[(ngModel)]="mytime" [hourStep]="hstep" [minuteStep]="mstep" [showSpinners]="true"   [min]="minTime" [max]="maxTime"  [mousewheel]="true"  formControlName="appointment_time" (ngModelChange)="onDateChange($event)"  ></p>


问:
Formula Validation - How to provide a value which contains a comma
I am trying to create an Excel Workbook using excel4node in Node JS

```<code>const workbook = new excel.Workbook();
  const sheet = workbook.addWorksheet();
  sheet.cell(1, 1).string("title");
  sheet.cell(1, 2).string("description");
  sheet.cell(1, 5).string("option1");
  sheet.cell(1, 6).string("option2");

  ["E", "F"].forEach((col) => {
    sheet.addDataValidation({
      type: "list",
      allowBlank: true,
      prompt: "Choose from dropdown",
      error: "Invalid choice was chosen",
      showDropDown: true,
      sqref: `${col}2:${col}2000`,
      formulas: [
        "P20 - Attend workshops ABCs, and Lessons learned sessions",
        "P40 - Facilitate workshops, ABC, and lessons learned sessions",
      ],
    });
  });
  return workbook
</code>```

The problem is when I download and open the Excel file instead of 2 options in Row E3 I see multiple options like

```<code>P20 - Attend workshops ABCs
and Lessons learned sessions
P40 - Facilitate workshops
ABC
and lessons learned sessions
</code>```

I read online and it seems one solution is to use Named Range. However, I could not figure out how to use Named Range in excel4Node or if there is any other solution that I can try

Body:
I am trying to create an Excel Workbook using excel4node in Node JS

const workbook = new excel.Workbook();
  const sheet = workbook.addWorksheet();
  sheet.cell(1, 1).string("title");
  sheet.cell(1, 2).string("description");
  sheet.cell(1, 5).string("option1");
  sheet.cell(1, 6).string("option2");

  ["E", "F"].forEach((col) => {
    sheet.addDataValidation({
      type: "list",
      allowBlank: true,
      prompt: "Choose from dropdown",
      error: "Invalid choice was chosen",
      showDropDown: true,
      sqref: `${col}2:${col}2000`,
      formulas: [
        "P20 - Attend workshops ABCs, and Lessons learned sessions",
        "P40 - Facilitate workshops, ABC, and lessons learned sessions",
      ],
    });
  });
  return workbook

The problem is when I download and open the Excel file instead of 2 options in Row E3 I see multiple options like

P20 - Attend workshops ABCs
and Lessons learned sessions
P40 - Facilitate workshops
ABC
and lessons learned sessions

I read online and it seems one solution is to use Named Range. However, I could not figure out how to use Named Range in excel4Node or if there is any other solution that I can try


问:
Converting a react made responsive navbar into nextjs navbar
I am trying to convert a react made responsive navbar component into next js navbar component. I don't know much about next js. Can anyone help with this code.The responsiveness works just fine. However, I cannot close the hamburger menu once I clicked it. The issue is with close Hamburger menu  button. Here is the navbar component code converted from React js app:

```<code>import React from 'react';
import React from 'react';
import { GiHamburgerMenu } from 'react-icons/gi';
import { MdOutlineRestaurantMenu } from 'react-icons/md';
import Image from "next/image";
import styles from "../styles/Navbar.module.css"

const Navbar = () => {
  const [toggleMenu, setToggleMenu] = React.useState(false);
  return (
    <nav className={styles.app__navbar}>
      <div className={styles.app__navbar_logo}>
      <Image src="/img/ephielogo.png" alt="app__logo" />
      </div>
      <ul className={styles.app__navbar_links}>
        <li className={styles.p__opensans}><a href="#home">Home</a></li>
        <li className={styles.p__opensans}><a href="#about">About</a></li>
        <li className={styles.p__opensans}><a href="#menu">Menu</a></li>
        <li className={styles.p__opensans}><a href="#awards">Awards</a></li>
        <li className={styles.p__opensans}><a href="#contact">Contact</a></li>
      </ul>
      <div className={styles.app__navbar_login}>
        <a href="#login" className={styles.p__opensans}>Log In / Registration</a>
        <div />
        <a href="/" className={styles.p__opensans}>Book Table</a>
      </div>
      <div className={styles.app__navbar_smallscreen}>
        <GiHamburgerMenu color="#fff" fontSize={27} onClick={() => setToggleMenu(true)} />
        {toggleMenu && (
          <div className={styles["app__navbar_smallscreen_overlay"] + " " + styles["flex__center"] + styles["slide_bottom"]}>
            <MdOutlineRestaurantMenu fontSize={27} className="overlay__close" onClick={() => setToggleMenu(false)} />
            <ul className={styles.app__navbar_smallscreen_links}>
              <li><a href="#home" onClick={() => setToggleMenu(false)}>Home</a></li>
              <li><a href="#about" onClick={() => setToggleMenu(false)}>About</a></li>
              <li><a href="#menu" onClick={() => setToggleMenu(false)}>Menu</a></li>
              <li><a href="#awards" onClick={() => setToggleMenu(false)}>Awards</a></li>
              <li><a href="#contact" onClick={() => setToggleMenu(false)}>Contact</a></li>
            </ul>
          </div>
        )}
      </div>
    </nav>
  );
};

export default Navbar;
</code>```

Here is my Navbar.Module.css code.

```<code>.app__navbar {

   width: 100%;
   display: flex;
   justify-content: space-between;
   align-items: center;
   background: var(--color-black);

   padding: 1rem 2rem;
}

.app__navbar_logo {
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.app__navbar_logo img {
    width: 150px;
}

.app__navbar_links {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    color: var(--color-white);

    list-style: none;
}

.app__navbar_links li {
    margin: 0 1rem;
    cursor: pointer;
}

.app__navbar_links li:hover {
    color: var(--color-grey);
}

.app__navbar_login {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.app__navbar_login a {
    margin: 0 1rem;
    text-decoration: none;
    transition: .5s ease;
    color: var(--color-white)
}

.app__navbar_login a:hover {
    border-bottom: 1px solid var(--color-golden);
}

.app__navbar_login div {
    width: 1px;
    height: 30px;
    background: var(--color-grey);
}

.app__navbar_smallscreen {
    display: none;
}

.app__navbar_smallscreen_overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background: var(--color-black);
    transition: .5s ease;

    flex-direction: column;
    z-index: 5;
}

.app__navbar_smallscreen_overlay .overlay__close {
    font-size: 27px;
    color: var(--color-golden);
    cursor: pointer;

    position: absolute;
    top: 20px;
    right: 20px;
}

.app__navbar_smallscreen_links {
    list-style: none;
}

.app__navbar_smallscreen_links li {
    margin: 2rem;
    cursor: pointer;
    color: var(--color-golden);
    font-size: 2rem;
    text-align: center;
    font-family: var(--font-base);
}

.app__navbar_smallscreen_links li:hover {
    color: var(--color-white);
}

@media screen and (min-width: 2000px) {
    .app__navbar_logo img {
        width: 210px;
    }
}

@media screen and (max-width: 1150px) {
    .app__navbar_links {
        display: none;
    }

    .app__navbar_smallscreen {
        display: flex;
    }
}

@media screen and (max-width: 650px) {
    .app__navbar {
        padding: 1rem;
    }

    .app__navbar_login {
        display: none;
    }

    .app__navbar_logo img {
        width: 110px;
    }
}
</code>```

Body:
I am trying to convert a react made responsive navbar component into next js navbar component. I don't know much about next js. Can anyone help with this code.The responsiveness works just fine. However, I cannot close the hamburger menu once I clicked it. The issue is with close Hamburger menu  button. Here is the navbar component code converted from React js app:

import React from 'react';
import React from 'react';
import { GiHamburgerMenu } from 'react-icons/gi';
import { MdOutlineRestaurantMenu } from 'react-icons/md';
import Image from "next/image";
import styles from "../styles/Navbar.module.css"

const Navbar = () => {
  const [toggleMenu, setToggleMenu] = React.useState(false);
  return (

      <Image src="/img/ephielogo.png" alt="app__logo" />

Home

About

Menu

Awards

Contact

        Log In / Registration

        Book Table

        <GiHamburgerMenu color="#fff" fontSize={27} onClick={() => setToggleMenu(true)} />
        {toggleMenu && (

            <MdOutlineRestaurantMenu fontSize={27} className="overlay__close" onClick={() => setToggleMenu(false)} />

 setToggleMenu(false)}>Home

 setToggleMenu(false)}>About

 setToggleMenu(false)}>Menu

 setToggleMenu(false)}>Awards

 setToggleMenu(false)}>Contact

        )}

  );
};

export default Navbar;

Here is my Navbar.Module.css code.

.app__navbar {

   width: 100%;
   display: flex;
   justify-content: space-between;
   align-items: center;
   background: var(--color-black);

   padding: 1rem 2rem;
}

.app__navbar_logo {
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.app__navbar_logo img {
    width: 150px;
}

.app__navbar_links {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    color: var(--color-white);

    list-style: none;
}

.app__navbar_links li {
    margin: 0 1rem;
    cursor: pointer;
}

.app__navbar_links li:hover {
    color: var(--color-grey);
}

.app__navbar_login {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.app__navbar_login a {
    margin: 0 1rem;
    text-decoration: none;
    transition: .5s ease;
    color: var(--color-white)
}

.app__navbar_login a:hover {
    border-bottom: 1px solid var(--color-golden);
}

.app__navbar_login div {
    width: 1px;
    height: 30px;
    background: var(--color-grey);
}

.app__navbar_smallscreen {
    display: none;
}

.app__navbar_smallscreen_overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background: var(--color-black);
    transition: .5s ease;

    flex-direction: column;
    z-index: 5;
}

.app__navbar_smallscreen_overlay .overlay__close {
    font-size: 27px;
    color: var(--color-golden);
    cursor: pointer;

    position: absolute;
    top: 20px;
    right: 20px;
}

.app__navbar_smallscreen_links {
    list-style: none;
}

.app__navbar_smallscreen_links li {
    margin: 2rem;
    cursor: pointer;
    color: var(--color-golden);
    font-size: 2rem;
    text-align: center;
    font-family: var(--font-base);
}

.app__navbar_smallscreen_links li:hover {
    color: var(--color-white);
}

@media screen and (min-width: 2000px) {
    .app__navbar_logo img {
        width: 210px;
    }
}

@media screen and (max-width: 1150px) {
    .app__navbar_links {
        display: none;
    }

    .app__navbar_smallscreen {
        display: flex;
    }
}

@media screen and (max-width: 650px) {
    .app__navbar {
        padding: 1rem;
    }

    .app__navbar_login {
        display: none;
    }

    .app__navbar_logo img {
        width: 110px;
    }
}


问:
How to add link to parent object in schema
I have a simple dto

```<code>@Getter
@Setter
@Schema(title = "TestDto", description = "Test dto")
public class TestDto {

    private Integer id;
    private String value;
    @ArraySchema(schema = @Schema(implementation = TestDto.class))
    private List<TestDto> children;
</code>```

and when i generate schema i see

```<code>"testDto": [
        {
          "id": 0,
          "value": "string",
          "children":["string"]
        }
</code>```

but i need something like this

```<code> "testDto": [
            {
              "id": 0,
              "value": "string",
              "children":[
                          {"id": 0,
                           "value": "string",
                           "children":[{}]}]
            }
</code>```

or like this

```<code>"testDto": [
        {
          "id": 0,
          "value": "string",
          "children":["testDto"]
        }
</code>```

is there any way to do that?

Body:
I have a simple dto

@Getter
@Setter
@Schema(title = "TestDto", description = "Test dto")
public class TestDto {

    private Integer id;
    private String value;
    @ArraySchema(schema = @Schema(implementation = TestDto.class))
    private List<TestDto> children;

and when i generate schema i see

"testDto": [
        {
          "id": 0,
          "value": "string",
          "children":["string"]
        }

but i need something like this

 "testDto": [
            {
              "id": 0,
              "value": "string",
              "children":[
                          {"id": 0,
                           "value": "string",
                           "children":[{}]}]
            }

or like this

"testDto": [
        {
          "id": 0,
          "value": "string",
          "children":["testDto"]
        }

is there any way to do that?


问:
Uncaught TypeError: Cannot convert undefined or null to object
Getting error in this line as cannot convert undefined or null to abject
also i highlighted a line in which error is showing

```<code>import React from 'react';
import { useParams } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { DetailsHeader, Error, Loader, RelatedSongs } from '../components';

import { useGetArtistDetailsQuery } from '../redux/sevices/shazamCore';

const ArtistDetails = () => {
  const { id: artistId } = useParams();
  const { activeSong, isPlaying } = useSelector((state) => state.player);
  const { data: artistData, isFetching: isFetchingArtistDetails, error } = useGetArtistDetailsQuery(artistId);

  if (isFetchingArtistDetails) return <Loader title="Loading artist details..." />;

  if (error) return <Error />;

  return (
    <div className="flex flex-col">
      <DetailsHeader
        artistId={artistId}
        artistData={artistData}
      />

      <RelatedSongs
`***        data={Object.values(artistData?.songs)}    //// error in this line ***`
        artistId={artistId}
        isPlaying={isPlaying}
        activeSong={activeSong}
      />
    </div>
  );
};

export default ArtistDetails;
</code>```

I am not sure whats the error in this

data={Object.values(artistData?.songs)}

Body:
Getting error in this line as cannot convert undefined or null to abject
also i highlighted a line in which error is showing

import React from 'react';
import { useParams } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { DetailsHeader, Error, Loader, RelatedSongs } from '../components';

import { useGetArtistDetailsQuery } from '../redux/sevices/shazamCore';

const ArtistDetails = () => {
  const { id: artistId } = useParams();
  const { activeSong, isPlaying } = useSelector((state) => state.player);
  const { data: artistData, isFetching: isFetchingArtistDetails, error } = useGetArtistDetailsQuery(artistId);

  if (isFetchingArtistDetails) return <Loader title="Loading artist details..." />;

  if (error) return <Error />;

  return (

      <DetailsHeader
        artistId={artistId}
        artistData={artistData}
      />

      <RelatedSongs
`***        data={Object.values(artistData?.songs)}    //// error in this line ***`
        artistId={artistId}
        isPlaying={isPlaying}
        activeSong={activeSong}
      />

  );
};

export default ArtistDetails;

I am not sure whats the error in this

data={Object.values(artistData?.songs)}


问:
How I can keep the same space height in AEM eCommerce images?
How to work on the space height to be more consistent across the page? In order to don't have space differences as per below?

eCommerce Page with images with space differences

I used the images and try to avoid the differences in the AEM contents.


问:
VRP : Arc cost based on current vehicle load (CO2 Emissions)
I would like to factor in the CO2 emission in the Vehicle Routing Problem. The Arc Cost is not the distance anymore but the CO2 emission over each Arc

As a first order approximation, the CO2 emission of each arc can be modeled as a linear function of the current load and constant topographic characteristics of the arc (the slope, distance, altitude, ...)
arc_cost(arc,load) = K(arc) + alpha(arc)*load

K and alpha are functions of the arc only (stateless)
The load depends on the previous deliveries.

I haven't found how to model this with the ORTools Python API. Here is my current attempt : https://github.com/remisoulignac/scm_optim_problems/blob/main/SCM290-GreenVehicleRoutingProblem.ipynb

For now, I fall back on a two-level optimization approach:
A classical VRP optimization model. I parameterize this model by several control points at which I impose a certain weight of goods to be delivered to the chosen route.
A hyperparametric optimization level that will play with the different control points and optimize the overall real fuel consumption of the tour.
Thank you for your help,


问:
xtext to xtend and xtend to xtext transformation
Good day,

I am working on an xtext project. I have written xtend to transform "runtime DSL instance" into equivalent code (text file).

Now I want that when I change the generated code (text file) the same is reflected in the "runtime DSL instance"

Any guidelines please .... ?