问:
Machine Learning model to predict solar radiation with meteorological data as input
I'm trying to learn how to train some machine learning models using scikit learn.
The main goal is getting a model that predict the solar radiation with given meteorological data.

I've got an historical data of 2 years with meteorological data and solar radiation with hourly granularity. The meteorological have these columns:

Column
Description
Type

time
The datetime of the observation
Datetime64

hour
Hour of the observation
String

Month
Month of the observation
String

temp
The air temperature in °C
Float64

dwpt
The dew point in °C
Float64

rhum
The relative humidity in percent (%)
Float64

prcp
The one hour precipitation total in mm
Float64

wdir
The average wind direction in degrees (°)
Float64

wspd
The average wind speed in km/h
Float64

wpgt
The peak wind gust in km/h
Float64

pres
The average sea-level air pressure in hPa
Float64

coco
The weather condition code
String

As you can see, 3 columns have cathegorical values (hour, month, coco) and I'm treating this with OneHotEncoder.
For the models I've tested with MLP and Decision Tree Regressor but the results are not as good as I would like. This is part of the code that i'm using to transform the data and training the model:

```<code>X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2)
train_data = X_train.join(y_train)

columns_pipeline = ColumnTransformer([
    ("cat", OneHotEncoder(), ["coco","month"]),
    ("time_hot", OneHotEncoder(), ["hour"]),
    ])

X_train = columns_pipeline.fit_transform(X_train)

tree_model = DecisionTreeRegressor()
tree_model.fit(X_train, y_train)

MLP_model = MLPRegressor(activation = 'relu', hidden_layer_sizes=(125))
MLP_model.fit(X_train, y_train)

</code>```

Since I'm new with this I would like to ask you if you have any other idea for data transformation , what other model i should try or if you consider something that i am doing wrong.
Maybe someone who have experience with making models for a problem like this could help me.

Thanks in advance!
Regards

Body:
I'm trying to learn how to train some machine learning models using scikit learn.
The main goal is getting a model that predict the solar radiation with given meteorological data.

I've got an historical data of 2 years with meteorological data and solar radiation with hourly granularity. The meteorological have these columns:

Column
Description
Type

time
The datetime of the observation
Datetime64

hour
Hour of the observation
String

Month
Month of the observation
String

temp
The air temperature in °C
Float64

dwpt
The dew point in °C
Float64

rhum
The relative humidity in percent (%)
Float64

prcp
The one hour precipitation total in mm
Float64

wdir
The average wind direction in degrees (°)
Float64

wspd
The average wind speed in km/h
Float64

wpgt
The peak wind gust in km/h
Float64

pres
The average sea-level air pressure in hPa
Float64

coco
The weather condition code
String

As you can see, 3 columns have cathegorical values (hour, month, coco) and I'm treating this with OneHotEncoder.
For the models I've tested with MLP and Decision Tree Regressor but the results are not as good as I would like. This is part of the code that i'm using to transform the data and training the model:

X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2)
train_data = X_train.join(y_train)

columns_pipeline = ColumnTransformer([
    ("cat", OneHotEncoder(), ["coco","month"]),
    ("time_hot", OneHotEncoder(), ["hour"]),
    ])

X_train = columns_pipeline.fit_transform(X_train)

tree_model = DecisionTreeRegressor()
tree_model.fit(X_train, y_train)

MLP_model = MLPRegressor(activation = 'relu', hidden_layer_sizes=(125))
MLP_model.fit(X_train, y_train)

Since I'm new with this I would like to ask you if you have any other idea for data transformation , what other model i should try or if you consider something that i am doing wrong.
Maybe someone who have experience with making models for a problem like this could help me.

Thanks in advance!
Regards


来源: stackexchange

问:
Invalid Map Key when using {{.Task.Slot}} in docker compose
I am trying to create a docker service with multiple replicas. I want each replica to have an environment variable with their respective replica number, and the toal number of replicas. The documentation leads me to think that {{.Task.Slot}} would do this, however I get
yaml: invalid map key: map[interface {}]interface {}{".Task.Slot":interface {}(nil)}
when I use it.

The relevant part of my docker compose file is

```<code>version: "3.9"

services:
  app:
    build:
      context: ./
      dockerfile: Dockerfile
    volumes:
      - ./logs:/app/logs
    restart:
      always
    environment:
      replica_id: {{.Task.Slot}}
      total_replicas: {{.Service.Replicas}}
    deploy:
      mode: replicated
      replicas: 2
</code>```

If it is of note, im starting the service like this
docker-compose up app --build

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a docker service with multiple replicas. I want each replica to have an environment variable with their respective replica number, and the toal number of replicas. The documentation leads me to think that {{.Task.Slot}} would do this, however I get
yaml: invalid map key: map[interface {}]interface {}{".Task.Slot":interface {}(nil)}
when I use it.

The relevant part of my docker compose file is

version: "3.9"

services:
  app:
    build:
      context: ./
      dockerfile: Dockerfile
    volumes:
      - ./logs:/app/logs
    restart:
      always
    environment:
      replica_id: {{.Task.Slot}}
      total_replicas: {{.Service.Replicas}}
    deploy:
      mode: replicated
      replicas: 2

If it is of note, im starting the service like this
docker-compose up app --build


问:
How can I get the tooltip to display on ApexCharts Track?
If you look at their example, I would like to hover in one of the gray areas and display the tooltip:
https://apexcharts.com/javascript-chart-demos/radialbar-charts/multiple-radialbars/

Extensive trial and error of their functions and searching to no luck on here and Google.

I am expecting to hover in the gray area (the track itself) and see the tooltip for that series.


问:
Python error: Invalid number of channels in input image
I am having this error:

```<code>Traceback (most recent call last):
  File "/Users/yvesbernas/Python/main.py", line 8, in <module>
    features0 = FeatureExtraction(img0)
  File "/Users/yvesbernas/Python/aux.py", line 14, in __init__
    self.gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.6.0) /Users/runner/work/opencv-python/opencv-python/opencv/modules/imgproc/src/color.simd_helpers.hpp:92: error: (-2:Unspecified error) in function 'cv::impl::(anonymous namespace)::CvtHelper<cv::impl::(anonymous namespace)::Set<3, 4,   -1>, cv::impl::(anonymous namespace)::Set<1, -1, -1>, cv::impl::(anonymous namespace)::Set<0, 2, 5>, cv::impl::(anonymous namespace)::NONE>::CvtHelper(cv::InputArray, cv::OutputArray, int) [VScn = cv::impl::(anonymous namespace)::Set<3, 4, -1>, VDcn = cv::impl::(anonymous namespace)::Set<1, -1, -1>, VDepth = cv::impl::(anonymous namespace)::Set<0, 2, 5>, sizePolicy = cv::impl::(anonymous namespace)::NONE]'
> Invalid number of channels in input image:
>     'VScn::contains(scn)'
> where
>     'scn' is 1
</code>```

Anyone has an idea? I am running Python 3.9.0 and opencd 4.6.0 on  Monterey 12..6.1
Thanks in advance
Yves

This program matches 2 pictures by shifting zooming rotating and perspective changing one image.
I did not write the code : it comes from https://magamig.github.io/posts/accurate-image-alignment-and-registration-using-opencv/
Wrote to the developper but he can't help.
I am pretty new to Python.

The code is called by main :

```<code>
aux

</code>```
```<code>import cv2 as cv
import numpy as np
import copy

orb = cv.ORB_create(
nfeatures=10000,
scaleFactor=1.2,
scoreType=cv.ORB_HARRIS_SCORE)

class FeatureExtraction:
def __init__(self, img):
    self.img = copy.copy(img)
    self.gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    self.kps, self.des = orb.detectAndCompute(self.gray_img, None)
    self.img_kps = cv.drawKeypoints(self.img, self.kps,          0,flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
    self.matched_pts = []

LOWES_RATIO = 0.7
MIN_MATCHES = 50
index_params = dict(
algorithm = 6, # FLANN_INDEX_LSH
table_number = 6,
key_size = 10,
multi_probe_level = 2)
search_params = dict(checks=50)
flann = cv.FlannBasedMatcher(
index_params,
search_params)

def feature_matching(features0, features1):
matches = [] # good matches as per Lowe's ratio test
if(features0.des is not None and len(features0.des) > 2):
    all_matches = flann.knnMatch( \
        features0.des, features1.des, k=2)
    try:
        for m,n in all_matches:
            if m.distance < LOWES_RATIO * n.distance:
                matches.append(m)
    except ValueError:
        pass
    if(len(matches) > MIN_MATCHES):
        features0.matched_pts = np.float32( \
            [ features0.kps[m.queryIdx].pt for m in matches ] \
            ).reshape(-1,1,2)
        features1.matched_pts = np.float32( \
            [ features1.kps[m.trainIdx].pt for m in matches ] \
            ).reshape(-1,1,2)
return matches
</code>```
```<code>
</code>```

Body:
I am having this error:

Traceback (most recent call last):
  File "/Users/yvesbernas/Python/main.py", line 8, in <module>
    features0 = FeatureExtraction(img0)
  File "/Users/yvesbernas/Python/aux.py", line 14, in __init__
    self.gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.6.0) /Users/runner/work/opencv-python/opencv-python/opencv/modules/imgproc/src/color.simd_helpers.hpp:92: error: (-2:Unspecified error) in function 'cv::impl::(anonymous namespace)::CvtHelper<cv::impl::(anonymous namespace)::Set<3, 4,   -1>, cv::impl::(anonymous namespace)::Set<1, -1, -1>, cv::impl::(anonymous namespace)::Set<0, 2, 5>, cv::impl::(anonymous namespace)::NONE>::CvtHelper(cv::InputArray, cv::OutputArray, int) [VScn = cv::impl::(anonymous namespace)::Set<3, 4, -1>, VDcn = cv::impl::(anonymous namespace)::Set<1, -1, -1>, VDepth = cv::impl::(anonymous namespace)::Set<0, 2, 5>, sizePolicy = cv::impl::(anonymous namespace)::NONE]'
> Invalid number of channels in input image:
>     'VScn::contains(scn)'
> where
>     'scn' is 1

Anyone has an idea? I am running Python 3.9.0 and opencd 4.6.0 on  Monterey 12..6.1
Thanks in advance
Yves

This program matches 2 pictures by shifting zooming rotating and perspective changing one image.
I did not write the code : it comes from https://magamig.github.io/posts/accurate-image-alignment-and-registration-using-opencv/
Wrote to the developper but he can't help.
I am pretty new to Python.

The code is called by main :

aux

import cv2 as cv
import numpy as np
import copy

orb = cv.ORB_create(
nfeatures=10000,
scaleFactor=1.2,
scoreType=cv.ORB_HARRIS_SCORE)

class FeatureExtraction:
def __init__(self, img):
    self.img = copy.copy(img)
    self.gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    self.kps, self.des = orb.detectAndCompute(self.gray_img, None)
    self.img_kps = cv.drawKeypoints(self.img, self.kps,          0,flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
    self.matched_pts = []

LOWES_RATIO = 0.7
MIN_MATCHES = 50
index_params = dict(
algorithm = 6, # FLANN_INDEX_LSH
table_number = 6,
key_size = 10,
multi_probe_level = 2)
search_params = dict(checks=50)
flann = cv.FlannBasedMatcher(
index_params,
search_params)

def feature_matching(features0, features1):
matches = [] # good matches as per Lowe's ratio test
if(features0.des is not None and len(features0.des) > 2):
    all_matches = flann.knnMatch( \
        features0.des, features1.des, k=2)
    try:
        for m,n in all_matches:
            if m.distance < LOWES_RATIO * n.distance:
                matches.append(m)
    except ValueError:
        pass
    if(len(matches) > MIN_MATCHES):
        features0.matched_pts = np.float32( \
            [ features0.kps[m.queryIdx].pt for m in matches ] \
            ).reshape(-1,1,2)
        features1.matched_pts = np.float32( \
            [ features1.kps[m.trainIdx].pt for m in matches ] \
            ).reshape(-1,1,2)
return matches


问:
Set background color to excel using pandas
I'm coloring all rows in Excel file with:

```<code>writer = pd.ExcelWriter(file_name, engine="xlsxwriter")

for dataframe, sheet, columns_list in zip(new_df_list, sheet_list, unique_columns):

    dataframe = dataframe.sort_index().reset_index(drop=True)

    dataframe.to_excel(
        writer,
        sheet_name=sheet,
        startrow=0,
        startcol=0,
        index=False,
        columns=columns_list,
    )

    workbook = writer.book
    worksheet = writer.sheets[sheet]
    worksheet.set_default_row(25)

    text_format = workbook.add_format({'text_wrap': True, 'bg_color': '#78B0DE', 'border': 1})

    for col_num, value in enumerate(columns_list):
        # set column length
        length_list = [len(x) + 30 for x in columns_list]

        for i, width in enumerate(length_list):
            worksheet.set_column(i, i, width, text_format)

writer.save()
</code>```

Not sure how to modify my code to color row based on column value. For example, column "Names" have 1000 women names and if "Sasha" will be find, entire row should be colored with pink.

Body:
I'm coloring all rows in Excel file with:

writer = pd.ExcelWriter(file_name, engine="xlsxwriter")

for dataframe, sheet, columns_list in zip(new_df_list, sheet_list, unique_columns):

    dataframe = dataframe.sort_index().reset_index(drop=True)

    dataframe.to_excel(
        writer,
        sheet_name=sheet,
        startrow=0,
        startcol=0,
        index=False,
        columns=columns_list,
    )

    workbook = writer.book
    worksheet = writer.sheets[sheet]
    worksheet.set_default_row(25)

    text_format = workbook.add_format({'text_wrap': True, 'bg_color': '#78B0DE', 'border': 1})

    for col_num, value in enumerate(columns_list):
        # set column length
        length_list = [len(x) + 30 for x in columns_list]

        for i, width in enumerate(length_list):
            worksheet.set_column(i, i, width, text_format)

writer.save()

Not sure how to modify my code to color row based on column value. For example, column "Names" have 1000 women names and if "Sasha" will be find, entire row should be colored with pink.


问:
How to add customized menu options in React toolbar using Electron App?
I have a customized toolbar in Electron using React as shown below, with minimize,maximize and close buttons.

Now I want to add customized menu items like shown below (similar to VS code)

File -> New Text File, New File, New Window

Edit -> Undo, Redo

Help -> Get Started, About

Can someone tell me how to add such menu items in electron using react ?

Titlebar.tsx:

```<code>import React, { useState } from "react";

import { app } from "../../utils/services";

import favicon from "./img/logo.png";
import styles from "./scss/Titlebar.module.scss";
import {
  CloseButton,
  ContractButton,
  MaximizeButton,
  MinimizeButton,
} from './TitlebarButtons';
import MenuBar from "./MenuBar";

/**
 * @namespace Titlebar
 * @description Title Component to use as an Electron customized titlebar.
 * electron-window-title-text used in main.js to set opacity on/off focus.
 * electron-window-title-buttons used in main.js to set opacity on/off focus.
 */

const Titlebar = () => {
  const [maximized, setMaximized] = useState(false);

  const handleMaximizeToggle = () => {
    !maximized ? app.maximize() : app.unmaximize();
    setMaximized(!maximized);
  };

  return (
    <section className={styles.titlebar}>
      <div>
        <img src={favicon} alt="favicon" />
        <span id="electron-window-title-text">My Electron App</span>
        <MenuBar />
      </div>

      <div id="electron-window-title-buttons">
        <MinimizeButton onClick={app.minimize} />
        {maximized ? (
          <ContractButton onClick={handleMaximizeToggle} />
        ) : (
          <MaximizeButton onClick={handleMaximizeToggle} />
        )}
        <CloseButton onClick={app.quit} />
      </div>
    </section>
  );
};

export default Titlebar;
</code>```

Body:
I have a customized toolbar in Electron using React as shown below, with minimize,maximize and close buttons.

Now I want to add customized menu items like shown below (similar to VS code)

File -> New Text File, New File, New Window

Edit -> Undo, Redo

Help -> Get Started, About

Can someone tell me how to add such menu items in electron using react ?

Titlebar.tsx:

import React, { useState } from "react";

import { app } from "../../utils/services";

import favicon from "./img/logo.png";
import styles from "./scss/Titlebar.module.scss";
import {
  CloseButton,
  ContractButton,
  MaximizeButton,
  MinimizeButton,
} from './TitlebarButtons';
import MenuBar from "./MenuBar";

/**
 * @namespace Titlebar
 * @description Title Component to use as an Electron customized titlebar.
 * electron-window-title-text used in main.js to set opacity on/off focus.
 * electron-window-title-buttons used in main.js to set opacity on/off focus.
 */

const Titlebar = () => {
  const [maximized, setMaximized] = useState(false);

  const handleMaximizeToggle = () => {
    !maximized ? app.maximize() : app.unmaximize();
    setMaximized(!maximized);
  };

  return (

        My Electron App
        <MenuBar />

        <MinimizeButton onClick={app.minimize} />
        {maximized ? (
          <ContractButton onClick={handleMaximizeToggle} />
        ) : (
          <MaximizeButton onClick={handleMaximizeToggle} />
        )}
        <CloseButton onClick={app.quit} />

  );
};

export default Titlebar;


问:
got error in authenticating a login from Discord
When i made a loging with discord button via discord own site [https://discordjs.guide/oauth2/#implicit-grant-flow][1]
The Code I copied from here works well and I did not got any code stuck but when I tried login to app via my second discord to check then all the authorization worked but in console I got error at the .style.display
it gives error: Code.js:47 Uncaught TypeError: Cannot read properties of null (reading 'style')  the code is copied from official site so i was not expecting error.
[1]: https://discordjs.guide/oauth2/#implicit-grant-flow

I was expecting the string including user name etc from the memebrs authorization but i didnot got.   The code is:

```<code><a id="login" style="display: none;" href="your-oauth2-URL-here">Identify Yourself</a>
<script>
    window.onload = () => {
        const fragment = new URLSearchParams(window.location.hash.slice(1));
        const [accessToken, tokenType] = [fragment.get('access_token'), fragment.get('token_type')];

        if (!accessToken) {
            return (document.getElementById('login').style.display = 'block');
        }

        fetch('https://discord.com/api/users/@me', {
            headers: {
                authorization: `${tokenType} ${accessToken}`,
            },
        })
            .then(result => result.json())
            .then(response => {
                const { username, discriminator } = response;
                document.getElementById('info').innerText += ` ${username}#${discriminator}`;
            })
            .catch(console.error);
    };
</script>
</code>```

I got error at:   return (document.getElementById('login').style.display = 'block');

Body:
When i made a loging with discord button via discord own site [https://discordjs.guide/oauth2/#implicit-grant-flow][1]
The Code I copied from here works well and I did not got any code stuck but when I tried login to app via my second discord to check then all the authorization worked but in console I got error at the .style.display
it gives error: Code.js:47 Uncaught TypeError: Cannot read properties of null (reading 'style')  the code is copied from official site so i was not expecting error.
[1]: https://discordjs.guide/oauth2/#implicit-grant-flow

I was expecting the string including user name etc from the memebrs authorization but i didnot got.   The code is:

Identify Yourself

I got error at:   return (document.getElementById('login').style.display = 'block');


问:
Create Iterator up to LONG.MAX_VALUE number of elements
I can create an iterator of INTEGER.MAX_VALUE elements via:

```<code>class MyClass {
// irrelevant details
}

private def expandMyClass(notExpanded: Iterator[MyClass], amount: Int): Iterator[MyClass] = {
  notExpanded.flatMap(c => {
    Array.fill(amount)(MyClass())
  }
}
</code>```

How can I create iterators up to LONG.MAX_VALUE? Java collections seem to have a max number of elements up to INTEGER.MAX_VALUE. Something like this:

```<code>private def expandMyClass(notExpanded: Iterator[MyClass], amount: Long): Iterator[MyClass] = {
  notExpanded.flatMap(c => {
    Array.fill(amount)(MyClass()) // amount is a Long, won't work here
  }
}
</code>```

Body:
I can create an iterator of INTEGER.MAX_VALUE elements via:

class MyClass {
// irrelevant details
}

private def expandMyClass(notExpanded: Iterator[MyClass], amount: Int): Iterator[MyClass] = {
  notExpanded.flatMap(c => {
    Array.fill(amount)(MyClass())
  }
}

How can I create iterators up to LONG.MAX_VALUE? Java collections seem to have a max number of elements up to INTEGER.MAX_VALUE. Something like this:

private def expandMyClass(notExpanded: Iterator[MyClass], amount: Long): Iterator[MyClass] = {
  notExpanded.flatMap(c => {
    Array.fill(amount)(MyClass()) // amount is a Long, won't work here
  }
}


问:
How to Convert SQL Queries to LinQ in C#. entity framework
im having trouble converting these 4 queries to LinQ in C#, using entity framework

ive tried going thro linqpad, but cant get it done.
is there any other way to cover these to Linq and get the same result

```<code>SELECT userid,  count(ActDescription) as Visits
  FROM [ExcelSuggestedOrdersDev].[dbo].[tblAppActivityLog] a
  join  [dbo].[tblAppActivityTypes] b on b.id = a.ActivityID
  where [Page] like '%eso/Warehouse/InsertNewBatch' and cast(ActivityDate as date) between '2022-12-05' and '2022-12-11'
  group by userid

  SELECT UserName, count(ApprovedOn) as PO_Count
  FROM [dbo].[tblSuggestedOrdersbatch]
  where UserName in('somename','somename','somename','somename','somename')  and  Approved = 1 and cast(ApprovedOn as date) between '2022-12-05' and '2022-12-11'
  group by UserName

select username, sum(modcount) as modcount, sum(totitemcount) as totitemcount, 1-(cast(sum(modcount) as decimal(18,2))/sum(totitemcount)) AccurPct
from (
SELECT b.UserName, PrimaryVendorNo, BatchDesc, batchid, (select count(id) from [tblweeklySuggestedOrders] z where z.batchid = a.batchid and onadwk <> 1 and convorder <> oriconvorder) as ModCount, (select count(id) from [tblweeklySuggestedOrders] z where z.batchid = a.batchid) as TotItemCount
FROM [dbo].[tblweeklySuggestedOrders] a
join [dbo].[tblSuggestedOrdersbatch] b on a.batchid = b.ID and cast(b.ActivityDate as date) between '2022-12-05' and '2022-12-11'
where batchid in (select id from [dbo].[tblSuggestedOrdersbatch] where Approved = 1)
group by b.UserName,PrimaryVendorNo, BatchDesc, batchid
) x
group by username
order by AccurPct desc

SELECT userid, DATENAME(dw, ActivityDate),DATEPART(dw,ActivityDate), count(ActDescription) as Visits
  FROM [ExcelSuggestedOrdersDev].[dbo].[tblAppActivityLog] a
  join  [dbo].[tblAppActivityTypes] b on b.id = a.ActivityID
  where [Page] like '%eso/Warehouse/InsertNewBatch' and cast(ActivityDate as date) between '2022-12-05' and '2022-12-18'
  group by userid, DATENAME(dw, ActivityDate),DATEPART(dw,ActivityDate)
  order by userid, DATEPART(dw,ActivityDate)

</code>```

Body:
im having trouble converting these 4 queries to LinQ in C#, using entity framework

ive tried going thro linqpad, but cant get it done.
is there any other way to cover these to Linq and get the same result

SELECT userid,  count(ActDescription) as Visits
  FROM [ExcelSuggestedOrdersDev].[dbo].[tblAppActivityLog] a
  join  [dbo].[tblAppActivityTypes] b on b.id = a.ActivityID
  where [Page] like '%eso/Warehouse/InsertNewBatch' and cast(ActivityDate as date) between '2022-12-05' and '2022-12-11'
  group by userid

  SELECT UserName, count(ApprovedOn) as PO_Count
  FROM [dbo].[tblSuggestedOrdersbatch]
  where UserName in('somename','somename','somename','somename','somename')  and  Approved = 1 and cast(ApprovedOn as date) between '2022-12-05' and '2022-12-11'
  group by UserName

select username, sum(modcount) as modcount, sum(totitemcount) as totitemcount, 1-(cast(sum(modcount) as decimal(18,2))/sum(totitemcount)) AccurPct
from (
SELECT b.UserName, PrimaryVendorNo, BatchDesc, batchid, (select count(id) from [tblweeklySuggestedOrders] z where z.batchid = a.batchid and onadwk <> 1 and convorder <> oriconvorder) as ModCount, (select count(id) from [tblweeklySuggestedOrders] z where z.batchid = a.batchid) as TotItemCount
FROM [dbo].[tblweeklySuggestedOrders] a
join [dbo].[tblSuggestedOrdersbatch] b on a.batchid = b.ID and cast(b.ActivityDate as date) between '2022-12-05' and '2022-12-11'
where batchid in (select id from [dbo].[tblSuggestedOrdersbatch] where Approved = 1)
group by b.UserName,PrimaryVendorNo, BatchDesc, batchid
) x
group by username
order by AccurPct desc

SELECT userid, DATENAME(dw, ActivityDate),DATEPART(dw,ActivityDate), count(ActDescription) as Visits
  FROM [ExcelSuggestedOrdersDev].[dbo].[tblAppActivityLog] a
  join  [dbo].[tblAppActivityTypes] b on b.id = a.ActivityID
  where [Page] like '%eso/Warehouse/InsertNewBatch' and cast(ActivityDate as date) between '2022-12-05' and '2022-12-18'
  group by userid, DATENAME(dw, ActivityDate),DATEPART(dw,ActivityDate)
  order by userid, DATEPART(dw,ActivityDate)


问:
Apache NIFI - How to wait for SQL Insert full completion
I wanted to wait until 'ExecuteSQL' processor finishes inserting big file into SQL database (table: bu_service_template), then move to other section.'ExecuteSQL' processor inserts row by row content of a file. I wanted to wait until file is fully inserted and then move to a next file.

My current flow:

FLOW

Update attribute

MergeContent

Wait

I wanted to wait until file is fully inserted and then move to a next file.


问:
When I use the PutObjectCommand is there an option to set an expiration of the object?
When I use the PutObjectCommand is there an option to expire the object after a specific timeout?

For example, when I use the getSignedUrl there is an option to expire the url after a specific timeout.

I want the same thing but to delete or mark the object for deletion.


问:
Calculated float price starting from MA indicator for VecotBT
Im trying to create a simple backtesting using VectorBT with Python. My workflow try to achieve the float price calculated on SMA indicator. So simply take my ponderation number, turn it into percentage and calculate the return. The return should be a float number, next I take this number and I add it to the current SMA. The issue is about the object of MA that seem a special object type. Anyone have a solution for do this simple thing ? Thanks.</p>
```<code>import vectorbt as vbt

price_data = vbt.YFData.download(
    'AAPL',
    interval='15m',
    missing_index='drop',
    start='2022-11-01'
)
price_close = price_data.get('Close')
sma = vbt.MA.run(price_close, 12, short_name = "SMA")
ponderation_input = 2.00
up = sma + (sma * ponderation_input/100)
print(float(up))
</code>```

Body:
Im trying to create a simple backtesting using VectorBT with Python. My workflow try to achieve the float price calculated on SMA indicator. So simply take my ponderation number, turn it into percentage and calculate the return. The return should be a float number, next I take this number and I add it to the current SMA. The issue is about the object of MA that seem a special object type. Anyone have a solution for do this simple thing ? Thanks.

import vectorbt as vbt

price_data = vbt.YFData.download(
    'AAPL',
    interval='15m',
    missing_index='drop',
    start='2022-11-01'
)
price_close = price_data.get('Close')
sma = vbt.MA.run(price_close, 12, short_name = "SMA")
ponderation_input = 2.00
up = sma + (sma * ponderation_input/100)
print(float(up))


问:
How to properly set the name of the BEM class for different card designs
Let's imagine that the task before us is to develop 50+ unique types of cards, headers, footers, etc.

It will be okay if I name the card types like this:
card-23, card-24

Or is there a better solution?

It scares me to think that all nested elements will have the prefix card-23__title, card-24__title because in fact they may be the same, and at the same time I want to be able to control a particular element separately without harming other types of cards.


问:
DeprecationWarning: `np.bool8` is a deprecated alias for `np.bool_`. (Deprecated NumPy 1.24)
Can anyone help me to fix this issue
warnings.warn(msg, DeprecationWarning, stacklevel=2)
E   DeprecationWarning: np.bool8 is a deprecated alias for np.bool_.  (Deprecated NumPy 1.24)

DeprecationWarning: `np.bool`
tried the abov fix but it not worked.


问:
I am running into an issue trying to set a formula in Excel
So simple functions work fine

```<code> ws.Cells(2, 26).Formula = '=A4'
</code>```

But trying to set a more complex formula:

```<code> ws.Cells(2, 26).Formula = '=TEXT([@[Impact Restore Time]],"mmm-yy")'
</code>```

This is giving an error:

```<code> pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None)
</code>```

Any idea why it will not take this more complex formula? This works if I manually enter it.

Body:
So simple functions work fine

 ws.Cells(2, 26).Formula = '=A4'

But trying to set a more complex formula:

 ws.Cells(2, 26).Formula = '=TEXT([@[Impact Restore Time]],"mmm-yy")'

This is giving an error:

 pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None)

Any idea why it will not take this more complex formula? This works if I manually enter it.


问:
Filter output array where `VoucherConfirm` equals `Y`
I’ve set up an example in JSFiddle that takes some sample data, manipulates it slightly and then loads this into a new variable. I think this is working.

As an experiment, I’d like to filter this output array where VoucherConfirm equals Y.

Can anyone help with this?

const h2 = document.getElementById("end");

// Manipulate Input JSON push result out.

// Create Empty array to store data after manipulation.
let MyOutputArray = {
  Reformated_Stores: []
}
// Get sample data.
const inputData = {
  Stores: [
    {
      'AccountNumber': '10',
      'Store_ID': '1073741825',
      'Store_NAME': 'Store A',
      'Vouchers': "0"
    },
    {
      'AccountNumber': '20',
      "Store_ID": "1073741826",
      "Store_NAME": "Store B",
      "Vouchers": "0"
    },
    {
      "AccountNumber": "30",
      "Store_ID": "1073741827",
      "Store_NAME": "Store C",
      "Vouchers": "1"
    }
  ]
}

// Loop through all sample data.
for (let i = 0; i < inputData.Stores.length; i++) {
  // If the voucher value = 1 set a new variable to Y otherwise set it to N.
  if (inputData.Stores[i].Vouchers === '1') {
    VOUCHER_VAL = "Y";
  }
  else {
    VOUCHER_VAL = "N";
  };

  // Reformat the data. Not that Voucher Confirm has been added showing the Y or N.
  const Reformatted_Data = {
    "Status": "Active",
    "Account": +inputData.Stores[i].AccountNumber,
    "ProdID": +inputData.Stores[i].Store_ID,
    "VouchersAvailable": +inputData.Stores[i].Vouchers,
    "VoucherConfirm": VOUCHER_VAL
  }

  // Push newly reformatted data to our originally empty output array.
  MyOutputArray.Reformated_Stores.push(Reformatted_Data);
}

html = "

My INPUT Data =
";
h2.insertAdjacentHTML("beforebegin", html);

// Stringify input data. I do this to allow the resulting string to be diplayed on the page.
const MyinputDataJSON = JSON.stringify(inputData);

// Display string on page.
document.getElementById("INPUT_Data_Output").innerHTML += MyinputDataJSON;

html = "
My Reformatted Data =
";
h2.insertAdjacentHTML("beforebegin", html);

// Stringify output data. I do this to allow the resulting string to be diplayed on the page.
const MyOutputArrayJSON = JSON.stringify(MyOutputArray);

// Display string on page.
document.getElementById("Reformatted_Data_Output").innerHTML += MyOutputArrayJSON;

// Script Complete Message.
html = "
Script Completed. Please See Console For Any Additional Notes or Errors
";
h2.insertAdjacentHTML("afterend", html);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2 id="myTitle">Script Output Notes</h2>
<div id="end">---</end></code>```

Body:
I’ve set up an example in JSFiddle that takes some sample data, manipulates it slightly and then loads this into a new variable. I think this is working.

As an experiment, I’d like to filter this output array where VoucherConfirm equals Y.

Can anyone help with this?

const h2 = document.getElementById("end");

// Manipulate Input JSON push result out.

// Create Empty array to store data after manipulation.
let MyOutputArray = {
  Reformated_Stores: []
}
// Get sample data.
const inputData = {
  Stores: [
    {
      'AccountNumber': '10',
      'Store_ID': '1073741825',
      'Store_NAME': 'Store A',
      'Vouchers': "0"
    },
    {
      'AccountNumber': '20',
      "Store_ID": "1073741826",
      "Store_NAME": "Store B",
      "Vouchers": "0"
    },
    {
      "AccountNumber": "30",
      "Store_ID": "1073741827",
      "Store_NAME": "Store C",
      "Vouchers": "1"
    }
  ]
}

// Loop through all sample data.
for (let i = 0; i < inputData.Stores.length; i++) {
  // If the voucher value = 1 set a new variable to Y otherwise set it to N.
  if (inputData.Stores[i].Vouchers === '1') {
    VOUCHER_VAL = "Y";
  }
  else {
    VOUCHER_VAL = "N";
  };

  // Reformat the data. Not that Voucher Confirm has been added showing the Y or N.
  const Reformatted_Data = {
    "Status": "Active",
    "Account": +inputData.Stores[i].AccountNumber,
    "ProdID": +inputData.Stores[i].Store_ID,
    "VouchersAvailable": +inputData.Stores[i].Vouchers,
    "VoucherConfirm": VOUCHER_VAL
  }

  // Push newly reformatted data to our originally empty output array.
  MyOutputArray.Reformated_Stores.push(Reformatted_Data);
}

html = "

My INPUT Data =
";
h2.insertAdjacentHTML("beforebegin", html);

// Stringify input data. I do this to allow the resulting string to be diplayed on the page.
const MyinputDataJSON = JSON.stringify(inputData);

// Display string on page.
document.getElementById("INPUT_Data_Output").innerHTML += MyinputDataJSON;

html = "
My Reformatted Data =
";
h2.insertAdjacentHTML("beforebegin", html);

// Stringify output data. I do this to allow the resulting string to be diplayed on the page.
const MyOutputArrayJSON = JSON.stringify(MyOutputArray);

// Display string on page.
document.getElementById("Reformatted_Data_Output").innerHTML += MyOutputArrayJSON;

// Script Complete Message.
html = "
Script Completed. Please See Console For Any Additional Notes or Errors
";
h2.insertAdjacentHTML("afterend", html);

Script Output Notes

---</end>


问:
Can you create a binding for a PopUpButton's selected value to a NSMutableDictionary's key (NSString)?
You can create bindings on a NSView element to an delegate's instance variable, but can you create a binding for a PopUpButton's selected value to a NSMutableDictionary's key (NSString)? how you can do this in xcode 4?</p>

ContentLicense: CC BY-SA 3.0


问:
unable to create PVC after upgrading cluster to 1.23
I upgraded an EKS from 1.20 to 1.23 and then created the EBS CSI driver.  (according to the instructions I should have done this step prior to upgrading)
After the upgrade existing volumes are fine, but any new volume I attempt to create they get stuck in a pending state.  When I do a describe on the pvc, this is the error message I keep getting.
https://docs.aws.amazon.com/eks/latest/userguide/csi-iam-role.html

```<code>Warning  ProvisioningFailed  44s  ebs.csi.aws.com_ebs-csi-controller-xxxxxxxxxxxxxxxx  failed to provision volume with StorageClass "gp2": rpc error: code = Internal desc = Could not create volume "pvc-yyyyyyyyyyyyyyyyyyyyyyy": could not create volume in EC2: WebIdentityErr: failed to retrieve credentials
caused by: InvalidIdentityToken: No OpenIDConnect provider found in your account for https://oidc.eks.us-east-1.amazonaws.com/id/123456788990
           status code: 400, request id: 60739110-15b6-4e53-9e5b-zzzzzzzzzzzz
</code>```

I have checked that provider shows up in the cluster using the following command

```<code>aws eks describe-cluster --name cluster_name --query "cluster.identity.oidc.issuer" --output text

aws iam list-open-id-connect-providers | grep EXAMPLED539D4633E53DE1B716D3041E (where EXAMPLED539D4633E53DE1B716D3041E == $Value_from_previous_command)
</code>```

I have restarted the ebs-csi-controller deployments as per the instructions and then deleted the pvc and recreated it, but still gettting the same results.

This is the settings my StorageClass is set to

```<code>NAME                PROVISIONER             RECLAIMPOLICY   VOLUMEBINDINGMODE   ALLOWVOLUMEEXPANSION   AGE
gp2 (default)       kubernetes.io/aws-ebs   Delete          Immediate           false                  2y254d
</code>```

Not sure what else to try.

Body:
I upgraded an EKS from 1.20 to 1.23 and then created the EBS CSI driver.  (according to the instructions I should have done this step prior to upgrading)
After the upgrade existing volumes are fine, but any new volume I attempt to create they get stuck in a pending state.  When I do a describe on the pvc, this is the error message I keep getting.
https://docs.aws.amazon.com/eks/latest/userguide/csi-iam-role.html

Warning  ProvisioningFailed  44s  ebs.csi.aws.com_ebs-csi-controller-xxxxxxxxxxxxxxxx  failed to provision volume with StorageClass "gp2": rpc error: code = Internal desc = Could not create volume "pvc-yyyyyyyyyyyyyyyyyyyyyyy": could not create volume in EC2: WebIdentityErr: failed to retrieve credentials
caused by: InvalidIdentityToken: No OpenIDConnect provider found in your account for https://oidc.eks.us-east-1.amazonaws.com/id/123456788990
           status code: 400, request id: 60739110-15b6-4e53-9e5b-zzzzzzzzzzzz

I have checked that provider shows up in the cluster using the following command

aws eks describe-cluster --name cluster_name --query "cluster.identity.oidc.issuer" --output text

aws iam list-open-id-connect-providers | grep EXAMPLED539D4633E53DE1B716D3041E (where EXAMPLED539D4633E53DE1B716D3041E == $Value_from_previous_command)

I have restarted the ebs-csi-controller deployments as per the instructions and then deleted the pvc and recreated it, but still gettting the same results.

This is the settings my StorageClass is set to

NAME                PROVISIONER             RECLAIMPOLICY   VOLUMEBINDINGMODE   ALLOWVOLUMEEXPANSION   AGE
gp2 (default)       kubernetes.io/aws-ebs   Delete          Immediate           false                  2y254d

Not sure what else to try.


问:
Is the debugger running in the new Windows Terminal app
When working on a console app, is there a way to tell if I'm debugging in the new Windows Terminal app?  When I actually run the console app it doesn't run in Windows Terminal but when debugging (with VS2022) the debugger runs in the new Windows Terminal app if the default terminal option in windows is set to Windows Console Host.

I know in cmd.exe or PowerShell I can get the WT_SESSION environment variable and it will return a guid but when I'm debugging WT_SESSION is null even if its running in Windows Terminal.

Another way to would be to check what the default terminal app is set to, but I can't seem to find how to do that programmatically either.  Does anyone know if that's maybe a registry setting or something?


问:
Get Refresh Time and Date on Winforms Label
My goal is to have a C# Winforms label that shows the last date/time the label was refreshed.

I have a TIMER_Tick event that refreshes after 1000 ms and is refreshing a toolstrip_button that fetches all the data.

I need to get a label2 that will display the last refresh time so that I can compare my data with the time on the label in attempt to troubleshoot an issue. I tried using label2.Text = this.DateTime.Now but I am not sure if that is something that continuously changes, or if it is the TIMER refreshing it.

And ideas on how I can get a label that shows me just when the last refresh happened?


问:
Issue with Scanner hasNextLine() but resolved with BufferedReader readLine()?
I have a file with 84000 lines in it.

My goal is to add each one of these lines to a String ArrayList. For some reason, it does not work using Scanner's hasNextLine(), but does work with BufferedReader's readLine(). The Scanner version stops about 1/5 of the way through the file. The BufferedReader version correctly goes to the end. There is nothing special about line 17132. It's a normal line like every other line.

For example, I have the following:

```<code>File file = new File("wordlist.txt");
Scanner s = new Scanner(file);

BufferedReader br = new BufferedReader(new FileReader(file));

ArrayList <String> al = new ArrayList <String> ();
ArrayList <String> al2 = new ArrayList <String> ();

String line = br.readLine();

while (line != null)
{
    al.add(line);
    line = br.readLine();
}

while (s.hasNextLine())
    al2.add(s.nextLine());

System.out.println(al.size());
System.out.println(al2.size());
</code>```

Here, the first print statement evaluates to 84095 (correct) and the second to 17132 (incorrect). Can anyone provide some insight as to why this is happening?

Body:
I have a file with 84000 lines in it.

My goal is to add each one of these lines to a String ArrayList. For some reason, it does not work using Scanner's hasNextLine(), but does work with BufferedReader's readLine(). The Scanner version stops about 1/5 of the way through the file. The BufferedReader version correctly goes to the end. There is nothing special about line 17132. It's a normal line like every other line.

For example, I have the following:

File file = new File("wordlist.txt");
Scanner s = new Scanner(file);

BufferedReader br = new BufferedReader(new FileReader(file));

ArrayList <String> al = new ArrayList <String> ();
ArrayList <String> al2 = new ArrayList <String> ();

String line = br.readLine();

while (line != null)
{
    al.add(line);
    line = br.readLine();
}

while (s.hasNextLine())
    al2.add(s.nextLine());

System.out.println(al.size());
System.out.println(al2.size());

Here, the first print statement evaluates to 84095 (correct) and the second to 17132 (incorrect). Can anyone provide some insight as to why this is happening?


问:
Moving passport AUTH route handler to controller not working
I would like to move the passport logic to a controller (in another file). First example is working, but in example below the googleCallback in authController isn't working, I can't figure out where's the error. Thanks in advance.

app.get('/auth/google',
  passport.authenticate('google', { session: false, scope: ['email', 'profile'] })
)

app.get('/auth/google/callback',
  passport.authenticate('google', { session: false }),
  (req, res) => {
    res.send({ loggedUser: req.user.displayName })
  }
)```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>app.get('/auth/google', authController.googleAuth)
app.get('/auth/google/callback', authController.googleCallback)

authController = {

  googleAuth: passport.authenticate('google', { session: false, scope: ['email', 'profile'] }),

  googleCallback: (
    passport.authenticate('google', { session: false }),
    (req, res) => {
      res.send({ loggedUser: req.user.displayName })
    }
  )

}</code>```

Body:
I would like to move the passport logic to a controller (in another file). First example is working, but in example below the googleCallback in authController isn't working, I can't figure out where's the error. Thanks in advance.

app.get('/auth/google',
  passport.authenticate('google', { session: false, scope: ['email', 'profile'] })
)

app.get('/auth/google/callback',
  passport.authenticate('google', { session: false }),
  (req, res) => {
    res.send({ loggedUser: req.user.displayName })
  }
)

app.get('/auth/google', authController.googleAuth)
app.get('/auth/google/callback', authController.googleCallback)

authController = {

  googleAuth: passport.authenticate('google', { session: false, scope: ['email', 'profile'] }),

  googleCallback: (
    passport.authenticate('google', { session: false }),
    (req, res) => {
      res.send({ loggedUser: req.user.displayName })
    }
  )

}


问:
How to change MIME type of the JS file that is received?
When I am trying to import JS file "/assets/js/@ckeditor/ckeditor5-upload/src/adapters/simpleuploadadapter" I get the error:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

As I have understood I need to add MIME type for the directory where the JS file is contained. Can I do it in htaccess?

```<code><script type="module">
    import SimpleUploadAdapter from '/assets/js/@ckeditor/ckeditor5-upload/src/adapters/simpleuploadadapter';

    ClassicEditor
        .create( document.querySelector( '#editor' ), {
            plugins: [ SimpleUploadAdapter],
            toolbar: [],
            simpleUpload: {
                // The URL that the images are uploaded to.
                uploadUrl: 'http://example.com',

                // Enable the XMLHttpRequest.withCredentials property.
                withCredentials: true,

                // Headers sent along with the XMLHttpRequest to the upload server.
                headers: {
                    'X-CSRF-TOKEN': 'CSRF-Token',
                    Authorization: 'Bearer <JSON Web Token>'
                }
            }
        } )
        .then( )
        .catch( );
</script>
</code>```

I used the function shown below to know mime type. result - text/x-c++

```<code><?php echo mime_content_type($_SERVER['DOCUMENT_ROOT'] . '/assets/js/@ckeditor/ckeditor5-upload/src/adapters/simpleuploadadapter.js') ?>
</code>```

Body:
When I am trying to import JS file "/assets/js/@ckeditor/ckeditor5-upload/src/adapters/simpleuploadadapter" I get the error:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

As I have understood I need to add MIME type for the directory where the JS file is contained. Can I do it in htaccess?

I used the function shown below to know mime type. result - text/x-c++

<?php echo mime_content_type($_SERVER['DOCUMENT_ROOT'] . '/assets/js/@ckeditor/ckeditor5-upload/src/adapters/simpleuploadadapter.js') ?>


问:
Socket.io path not resolving in production using Node.js and Apache
I have a website, let's say website.com. I hosted another website in the sub path as website.com/app. I'm trying to create Socket.io connection from client code when user visits /action path (website.com/app/action).

Please keep in mind that:

Development URL is http://localhost:8089/action.

Production URL is https://website.com/app/action.

Issue only occurs in Production.

Endpoints are working fine.

Below codes (including website URL) are simplified version of my actual code for better clarity.

Apache httpd.conf

<VirtualHost *:443>
        ServerAdmin admin@website.com
        ServerName website.com
        ServerAlias www.website.com

        ErrorLog /var/www/website.com/error-ssl.log

        SSLProxyEngine on
        SSLProxyVerify none
        SSLProxyCheckPeerCN off
        SSLProxyCheckPeerName off
        SSLProxyCheckPeerExpire off

        SSLCertificateFile /path/to/cert
        SSLCertificateKeyFile /path/to/cert

        ProxyRequests off
        ProxyPreserveHost On
        ProxyVia Full

        <Proxy *>
                Require all granted
        </Proxy>

        proxyPass /first http://127.0.0.1:8090
        proxyPassReverse /first http://127.0.0.1:8090
</VirtualHost>
```
<hr />
<p><strong>Node.js Server Code</strong></p>
<pre class="lang-js prettyprint-override"><code>const path = require('path');
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const bodyParser = require('body-parser');
const router = require('./controller/router');
const express = require('express');
const router = express.Router();

router.get('/action', (req, res) => {
   const root = path.resolve('src', 'view');
   res.sendFile('./action.html', {root});
});
router.post('/action', (req, res) => {
   const socketId = req.body.socketId;
   console.log(socketId);
   res.send('succeess');
});

app.use(
   bodyParser.urlencoded({ extended: true }),
   bodyParser.json(),
   express.static(path.join(__dirname, 'view')),
   router,
);

require('socket.io')(server.listen(8090));
</code>```

Client Code (action.html) - Where the problem occurs..?

btn.addEventListener('click', () => {
   const url = isDev ? 'http://localhost:8089' : 'https://website.com';
   let path;

   // Works fine.
   if (isDev) {
      path = '/action/';
   }
   // Here is what I'm struggling with.
   else {
      // So far I've tried:
      path = '/action/';
      path = '/action';
      path = 'action/';
      path = 'action';
      path = '/app/action/';
      path = '/app/action';
      path = 'app/action';
      path = 'app/action/';
   }

   try {
      const socket = io.connect(url, {
         path
      });
   } catch (error) {
      console.error(error); // "404 (Not Found)" or "Server Error".
   }
});
```

Error

I either get 404 (Not Found) server response or simply Server Error depending on path string.

Body:
I have a website, let's say website.com. I hosted another website in the sub path as website.com/app. I'm trying to create Socket.io connection from client code when user visits /action path (website.com/app/action).

Please keep in mind that:

Development URL is http://localhost:8089/action.

Production URL is https://website.com/app/action.

Issue only occurs in Production.

Endpoints are working fine.

Below codes (including website URL) are simplified version of my actual code for better clarity.

Apache httpd.conf

<VirtualHost *:443>
        ServerAdmin admin@website.com
        ServerName website.com
        ServerAlias www.website.com

        ErrorLog /var/www/website.com/error-ssl.log

        SSLProxyEngine on
        SSLProxyVerify none
        SSLProxyCheckPeerCN off
        SSLProxyCheckPeerName off
        SSLProxyCheckPeerExpire off

        SSLCertificateFile /path/to/cert
        SSLCertificateKeyFile /path/to/cert

        ProxyRequests off
        ProxyPreserveHost On
        ProxyVia Full

        <Proxy *>
                Require all granted
        </Proxy>

        proxyPass /first http://127.0.0.1:8090
        proxyPassReverse /first http://127.0.0.1:8090
</VirtualHost>

Node.js Server Code

const path = require('path');
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const bodyParser = require('body-parser');
const router = require('./controller/router');
const express = require('express');
const router = express.Router();

router.get('/action', (req, res) => {
   const root = path.resolve('src', 'view');
   res.sendFile('./action.html', {root});
});
router.post('/action', (req, res) => {
   const socketId = req.body.socketId;
   console.log(socketId);
   res.send('succeess');
});

app.use(
   bodyParser.urlencoded({ extended: true }),
   bodyParser.json(),
   express.static(path.join(__dirname, 'view')),
   router,
);

require('socket.io')(server.listen(8090));

Client Code (action.html) - Where the problem occurs..?

btn.addEventListener('click', () => {
   const url = isDev ? 'http://localhost:8089' : 'https://website.com';
   let path;

   // Works fine.
   if (isDev) {
      path = '/action/';
   }
   // Here is what I'm struggling with.
   else {
      // So far I've tried:
      path = '/action/';
      path = '/action';
      path = 'action/';
      path = 'action';
      path = '/app/action/';
      path = '/app/action';
      path = 'app/action';
      path = 'app/action/';
   }

   try {
      const socket = io.connect(url, {
         path
      });
   } catch (error) {
      console.error(error); // "404 (Not Found)" or "Server Error".
   }
});

Error

I either get 404 (Not Found) server response or simply Server Error depending on path string.


问:
nginx ingress rewrite target in reverse
I'm running zoneminder as a pod that responds to the path "/zm." Right now, if I hit the main URL, I get a default index page, and I have to manually add the /zm path to my URL.

I would like to basically like to add "/zm" to the path for a backend service so that zoneminder.example.com goes to "zoneminder.svc/zm".

Long story short, I want to do nginx ingress & rewrite-target but in reverse.

I played with the annotation "nginx.ingress.kubernetes.io/rewrite-target" but nothing worked.

Title: nginx ingress rewrite target in reverse


问:
Carousel slideshow is not working in bootstrap 4.5.2
I am not getting desired slideshow as output. It is stuck on this output not changing slides on clicking prev or next buttons or clicking slider list below.

It is working with Bootstrap 3.4.1 by changing some classes accordingly but not working with Bootstrap 4.5.2.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

      Previous

      Next

```


问:
C#.Net Core 3.1 HttpRequest timeout or SSL connection issue
Ok i have the following code

```<code>HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
clientHandler.UseProxy = false;

using (HttpClient client = new HttpClient(clientHandler))
{
    var reqUri = string.Format("{0}/{1}?getBIC=true&validateBankCode=true", AppSettings.Instance.ValidationSettings.IBANValidationUri, iban);
    Logger.Instance.LogInfo("IBAN Validation: Sending request");
    using (HttpResponseMessage res = await client.GetAsync(reqUri))
    {
        using (HttpContent content = res.Content)
        {
            if (content != null)
            {
                Logger.Instance.LogInfo("IBAN Validation: Reading data");
                var data = res.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(data.Result))
                {
                    result = JsonConvert.DeserializeObject<IBANValidationResult>(data.Result);
                }

            }
        }
    }
}
</code>```

Now this code simply makes a rquest to the openiban api to get the specific bank information from a IBAN number.

This code runs on a ASP.NET Core 3.1 Web API that is running on a IIS Server.

Now we have 3 exact same server with the same web api.

The problem:

when i call the service from a browser on server 1, the service works fine i get the response etc.

when i call the service from a browser on server 2 it works also fine.

when i call the service from a browser on server 3 it takes too long and then i receive following error on the backend:

ERROR: The SSL connection could not be established, see inner
exception

ERROR: Authentication failed because the remote party has closed the
transport stream.

The funny thing is: This issue does not depend on one server, sometimes the server 3 works but then server 2 does not work, sometimes server 1 does not work an the other servers are working.

Does anybody have a clue what is going on here?

PS: The SSL certificates are installed on the server

Thanks a lot

Body:
Ok i have the following code

HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
clientHandler.UseProxy = false;

using (HttpClient client = new HttpClient(clientHandler))
{
    var reqUri = string.Format("{0}/{1}?getBIC=true&validateBankCode=true", AppSettings.Instance.ValidationSettings.IBANValidationUri, iban);
    Logger.Instance.LogInfo("IBAN Validation: Sending request");
    using (HttpResponseMessage res = await client.GetAsync(reqUri))
    {
        using (HttpContent content = res.Content)
        {
            if (content != null)
            {
                Logger.Instance.LogInfo("IBAN Validation: Reading data");
                var data = res.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(data.Result))
                {
                    result = JsonConvert.DeserializeObject<IBANValidationResult>(data.Result);
                }

            }
        }
    }
}

Now this code simply makes a rquest to the openiban api to get the specific bank information from a IBAN number.

This code runs on a ASP.NET Core 3.1 Web API that is running on a IIS Server.

Now we have 3 exact same server with the same web api.

The problem:

when i call the service from a browser on server 1, the service works fine i get the response etc.

when i call the service from a browser on server 2 it works also fine.

when i call the service from a browser on server 3 it takes too long and then i receive following error on the backend:

ERROR: The SSL connection could not be established, see inner
exception

ERROR: Authentication failed because the remote party has closed the
transport stream.

The funny thing is: This issue does not depend on one server, sometimes the server 3 works but then server 2 does not work, sometimes server 1 does not work an the other servers are working.

Does anybody have a clue what is going on here?

PS: The SSL certificates are installed on the server

Thanks a lot


问:
Mocking Controller Action Method which use 'RouteData.Values' in dot net 6 using MOQ and Xunits
Sorry for long piece of code but I have tried my best to make it as simple as possible:
I have an action method which I am trying to mock:

```<code>public IActionResult Get(long siteId)
    {
        //Get all the Reports
        var countryCode = (string)this.RouteData.Values["CountryCode"];
        var microMarketReport = _microMarketPriceOverviewBusiness.GetMicroMarketOverviewReport(siteId, countryCode).GetAwaiter().GetResult();
        return Ok(microMarketReport);
    }
</code>```

The Test method is as follows:

```<code>[Fact]
    public void Get_OK()
    {
        // Arrange
        MockMicroMarketPriceOverviewBusiness.Setup(x => x.GetMicroMarketOverviewReport(It.IsAny<long>(),It.IsAny<string>()))
            .Returns(Task.Run(() => new MicroMarketOverviewModel()));
        var unitUnderTest = CreateMicroMarketPriceOverviewController();

        var routeData = new RouteData();
        routeData.Values.Add("CountryCode", "DE");

        // Act
        var result = (OkObjectResult)unitUnderTest.Get(120);

        // Assert
        Assert.True(result.StatusCode == StatusCodes.Status200OK);
    }
</code>```

CreateMicroMarketPriceOverviewController which is used inside the Fact is as follows:

```<code>private MicroMarketPriceOverviewController CreateMicroMarketPriceOverviewController()
    {
        var context = new DefaultHttpContext();

        context.Request.Headers.Add("X-Correlation-ID", Guid.NewGuid().ToString());

        var controllerContext = new ControllerContext()
        {
            HttpContext = context.HttpContext
        };

        context.HttpContext.Request.Path = PathString.FromUriComponent(new Uri("http://localhost/api/v1/{CountryCode}/[controller]"));
        context.HttpContext.Request.RouteValues = new Microsoft.AspNetCore.Routing.RouteValueDictionary() { { "CountryCode", "NL" } };
        return new MicroMarketPriceOverviewController(MockMicroMarketPriceOverviewBusiness.Object, mockLogger);
    }
</code>```

When I Run my test the line 'var countryCode = (string)this.RouteData.Values["CountryCode"]' inside the action method throws following error:

Object reference not set to an instance of an object.

What Am I doing wrong even after I am setting the RouteData value??.

Body:
Sorry for long piece of code but I have tried my best to make it as simple as possible:
I have an action method which I am trying to mock:

public IActionResult Get(long siteId)
    {
        //Get all the Reports
        var countryCode = (string)this.RouteData.Values["CountryCode"];
        var microMarketReport = _microMarketPriceOverviewBusiness.GetMicroMarketOverviewReport(siteId, countryCode).GetAwaiter().GetResult();
        return Ok(microMarketReport);
    }

The Test method is as follows:

[Fact]
    public void Get_OK()
    {
        // Arrange
        MockMicroMarketPriceOverviewBusiness.Setup(x => x.GetMicroMarketOverviewReport(It.IsAny<long>(),It.IsAny<string>()))
            .Returns(Task.Run(() => new MicroMarketOverviewModel()));
        var unitUnderTest = CreateMicroMarketPriceOverviewController();

        var routeData = new RouteData();
        routeData.Values.Add("CountryCode", "DE");

        // Act
        var result = (OkObjectResult)unitUnderTest.Get(120);

        // Assert
        Assert.True(result.StatusCode == StatusCodes.Status200OK);
    }

CreateMicroMarketPriceOverviewController which is used inside the Fact is as follows:

private MicroMarketPriceOverviewController CreateMicroMarketPriceOverviewController()
    {
        var context = new DefaultHttpContext();

        context.Request.Headers.Add("X-Correlation-ID", Guid.NewGuid().ToString());

        var controllerContext = new ControllerContext()
        {
            HttpContext = context.HttpContext
        };

        context.HttpContext.Request.Path = PathString.FromUriComponent(new Uri("http://localhost/api/v1/{CountryCode}/[controller]"));
        context.HttpContext.Request.RouteValues = new Microsoft.AspNetCore.Routing.RouteValueDictionary() { { "CountryCode", "NL" } };
        return new MicroMarketPriceOverviewController(MockMicroMarketPriceOverviewBusiness.Object, mockLogger);
    }

When I Run my test the line 'var countryCode = (string)this.RouteData.Values["CountryCode"]' inside the action method throws following error:

Object reference not set to an instance of an object.

What Am I doing wrong even after I am setting the RouteData value??.


问:
Trigger function for table with multiple joins PostgreSQL
I'm new to PostgreSQL and I didn't find any questions specifically for this issue.

I'm trying to create a PostgreSQL trigger with a table which contains joins.

Table A

Salesman_id
Salesman name

1
John Snow

2
Jennifer

3
Cleiton

Table B

Salesman_id
order value
item
order_id

1
500
Bananas
1

2
1000
tomatos
20

3
5000
Tigers
200

Joined Table A-B (Selected couple columns)

Salesman name
Order Value

John Snow
500

Jennifer
1000

Cleiton
5000

my code for this trigger:

    CREATE OR REPLACE FUNCTION atualiza_tabela()
    RETURNS TRIGGER AS $$
    BEGIN
    if new.order_id<>old.order_id then

    INSERT INTO Table A-B (Salesman_id, Salesman name, order value, item, order id)
    VALUES (NEW.Salesman_id, NEW.Salesman name, NEW.order value, NEW.item, NEW.order id);

    RETURN NULL;

    END;
    $$ LANGUAGE plpgsql;
```
<p>Is there any syntax error or another kind of error in my code?</p>
<p>It returns:</p>
```  ERROR:  syntax error at or near ";"
  LINE 35: END;
            ^
  SQL state: 42601
  Character: 748
```

Body:
I'm new to PostgreSQL and I didn't find any questions specifically for this issue.

I'm trying to create a PostgreSQL trigger with a table which contains joins.

Table A

Salesman_id
Salesman name

1
John Snow

2
Jennifer

3
Cleiton

Table B

Salesman_id
order value
item
order_id

1
500
Bananas
1

2
1000
tomatos
20

3
5000
Tigers
200

Joined Table A-B (Selected couple columns)

Salesman name
Order Value

John Snow
500

Jennifer
1000

Cleiton
5000

my code for this trigger:

    CREATE OR REPLACE FUNCTION atualiza_tabela()
    RETURNS TRIGGER AS $$
    BEGIN
    if new.order_id<>old.order_id then

    INSERT INTO Table A-B (Salesman_id, Salesman name, order value, item, order id)
    VALUES (NEW.Salesman_id, NEW.Salesman name, NEW.order value, NEW.item, NEW.order id);

    RETURN NULL;

    END;
    $$ LANGUAGE plpgsql;

Is there any syntax error or another kind of error in my code?

It returns:

  ERROR:  syntax error at or near ";"
  LINE 35: END;
            ^
  SQL state: 42601
  Character: 748


问:
GraphQL save self relation in custom resolver in amplify
I have the following models:

```<code>type Field @model {
  id: ID!
  fieldID: ID @index(name: "byField", sortKeyFields: ["name"])
  name: String!
  type: String!
  required: Boolean
  fields: [Field] @hasMany(indexName: "byField", fields: ["id"])
}
type Mutation {
    batchCreateField(fields: [BatchCreateField]): [Field]
}

input BatchCreateField {
  id: ID
  fieldID: ID
  name: String!
  type: String!
  required: Boolean
  fields: [BatchCreateField]
}
</code>```

And wrote a custom resolver:

```<code>$util.log.info($util.toJson($context))
#set($isAuthorized = false)
#set( $createdAt = $util.time.nowISO8601() )
#set($fieldsArray = [])

#foreach($item in \${ctx.args.fields})
  $util.qr($item.put("id", $util.defaultIfNullOrBlank($item.id, $util.autoId())))
  $util.qr($item.put("createdAt", $util.defaultIfNull($item.createdAt, $createdAt)))
  $util.qr($item.put("updatedAt", $util.defaultIfNull($item.updatedAt, $createdAt)))
  $util.qr($item.put("__typename", "Field"))
  $util.qr($fieldsArray.add($util.dynamodb.toMapValues($item)))
#end
## [End] Initialization default values. **
$util.toJson( {
  "version": "2018-05-29",
  "operation": "BatchPutItem",
  "tables": {
    "Field-INSERT_APIID-INSERT_PROJECT_ENV": $fieldsArray
  }
} )
</code>```

Saving in batch works fine, the self relation is not working. Is there any way i can save this self relation like below in a batch and the resolver autofilling the sub fields with the fieldID of the previously inserted field?

```<code>let fieldInput: CreateFieldInput = {
  name: field.name,
  type: field.type,
  required: field.required,
  fields: field.fields
};

batchFieldsInput.push(fieldInput)

API.graphql(graphqlOperation(batchCreateField, {fields: batchFieldsInput}))
</code>```

Body:
I have the following models:

type Field @model {
  id: ID!
  fieldID: ID @index(name: "byField", sortKeyFields: ["name"])
  name: String!
  type: String!
  required: Boolean
  fields: [Field] @hasMany(indexName: "byField", fields: ["id"])
}
type Mutation {
    batchCreateField(fields: [BatchCreateField]): [Field]
}

input BatchCreateField {
  id: ID
  fieldID: ID
  name: String!
  type: String!
  required: Boolean
  fields: [BatchCreateField]
}

And wrote a custom resolver:

$util.log.info($util.toJson($context))
#set($isAuthorized = false)
#set( $createdAt = $util.time.nowISO8601() )
#set($fieldsArray = [])

#foreach($item in \${ctx.args.fields})
  $util.qr($item.put("id", $util.defaultIfNullOrBlank($item.id, $util.autoId())))
  $util.qr($item.put("createdAt", $util.defaultIfNull($item.createdAt, $createdAt)))
  $util.qr($item.put("updatedAt", $util.defaultIfNull($item.updatedAt, $createdAt)))
  $util.qr($item.put("__typename", "Field"))
  $util.qr($fieldsArray.add($util.dynamodb.toMapValues($item)))
#end
## [End] Initialization default values. **
$util.toJson( {
  "version": "2018-05-29",
  "operation": "BatchPutItem",
  "tables": {
    "Field-INSERT_APIID-INSERT_PROJECT_ENV": $fieldsArray
  }
} )

Saving in batch works fine, the self relation is not working. Is there any way i can save this self relation like below in a batch and the resolver autofilling the sub fields with the fieldID of the previously inserted field?

let fieldInput: CreateFieldInput = {
  name: field.name,
  type: field.type,
  required: field.required,
  fields: field.fields
};

batchFieldsInput.push(fieldInput)

API.graphql(graphqlOperation(batchCreateField, {fields: batchFieldsInput}))


问:
Codeigniter 3 | Copy zip file and extract
I've function for demo import database:

```<code>        /**
     * Demo importer post [Template 01 - Fashion / Clothing]
     */
    public function demo_importer_post_template01()
    {
        $folder_name = 'template01';
        $file_name = 'template01.sql';
$path = 'assets/backup_db/'; // Codeigniter application /assets
$file_restore = $this->load->file($path . $folder_name . '/' . $file_name, true);
$file_array = explode(';', $file_restore);
foreach ($file_array as $query)
 {
 $this->db->query("SET FOREIGN_KEY_CHECKS = 0");
 $this->db->query($query);
 $this->db->query("SET FOREIGN_KEY_CHECKS = 1");
 }
 $this->session->set_flashdata('success', trans("msg_updated"));
 redirect($this->agent->referrer());
    }
</code>```

This function insert database from /assets/backup_db/template01/template01.sql

This working fine. Now I  need with this function extract some static files from: /assets/backup_db/template01/template01.zip

Can anyone help me How to copy template01.zip to root public_html and then unzip  files from template01.zip

Body:
I've function for demo import database:

        /**
     * Demo importer post [Template 01 - Fashion / Clothing]
     */
    public function demo_importer_post_template01()
    {
        $folder_name = 'template01';
        $file_name = 'template01.sql';
$path = 'assets/backup_db/'; // Codeigniter application /assets
$file_restore = $this->load->file($path . $folder_name . '/' . $file_name, true);
$file_array = explode(';', $file_restore);
foreach ($file_array as $query)
 {
 $this->db->query("SET FOREIGN_KEY_CHECKS = 0");
 $this->db->query($query);
 $this->db->query("SET FOREIGN_KEY_CHECKS = 1");
 }
 $this->session->set_flashdata('success', trans("msg_updated"));
 redirect($this->agent->referrer());
    }

This function insert database from /assets/backup_db/template01/template01.sql

This working fine. Now I  need with this function extract some static files from: /assets/backup_db/template01/template01.zip

Can anyone help me How to copy template01.zip to root public_html and then unzip  files from template01.zip


问:
How to export Google sheets data to JPEG/PNG to be used as Inline Image in Gmail using GAS?
I am currently trying to export data from the spreadsheet to JPEG/PNG format and use it the email body as an Inline image rather than an attachment.
previously, I used to export the data to PDF and send as an attachment using the below code:

```<code>function sendReport() {

    var message = {
        to: "trial@gmail.com",
        subject: "Random Subject Line",
        body: "This is just a trial. Ignore.",
        name: "Name",
        attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("SampleOutput")]
      }
      MailApp.sendEmail(message);
    }
</code>```

I tried changing the MimeType to PNG, but it returned an error. Is there any way to do this? I couldn't find any existing solution to this issue.
PS: I need data to be captured for the first 10 rows only OR till the row where data ends.

Body:
I am currently trying to export data from the spreadsheet to JPEG/PNG format and use it the email body as an Inline image rather than an attachment.
previously, I used to export the data to PDF and send as an attachment using the below code:

function sendReport() {

    var message = {
        to: "trial@gmail.com",
        subject: "Random Subject Line",
        body: "This is just a trial. Ignore.",
        name: "Name",
        attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("SampleOutput")]
      }
      MailApp.sendEmail(message);
    }

I tried changing the MimeType to PNG, but it returned an error. Is there any way to do this? I couldn't find any existing solution to this issue.
PS: I need data to be captured for the first 10 rows only OR till the row where data ends.


问:
using ffmpeg to rotate a RTSP stream and then restram that back to my local network ( usign windows )
I would like to use FFMPEG to consume a stream from my cctv ip camera,rotate the video feed 90 and then re-streamt that back to my local network over rtsp. I would like to make this work on Windows only, and using the igpu in my machine to help with the cpu load. My camera does not support 90 degree rotation native so the use of FFMPEG would be nice help.

Here is what I have tried so far but it will not give me anything that I can watch on VLC for example.

ffmpeg -i rtsp://admin:passwordhere@192.168.1.147:554/h264Preview_01_main -vf "transpose=2" -c:v libx264 -b:v 1000k -s 640x480 -f rtsp
```
```rtsp://localhost:8888/live.sdp
```

Body:
I would like to use FFMPEG to consume a stream from my cctv ip camera,rotate the video feed 90 and then re-streamt that back to my local network over rtsp. I would like to make this work on Windows only, and using the igpu in my machine to help with the cpu load. My camera does not support 90 degree rotation native so the use of FFMPEG would be nice help.

Here is what I have tried so far but it will not give me anything that I can watch on VLC for example.

ffmpeg -i rtsp://admin:passwordhere@192.168.1.147:554/h264Preview_01_main -vf "transpose=2" -c:v libx264 -b:v 1000k -s 640x480 -f rtsp

rtsp://localhost:8888/live.sdp


问:
Decode password in SOAP xml envelope
Im working on a Java solution that acts as a proxy for some soap web services. We receive the envelope as it was sent directly to the web service, do some processing to it and redirected to its corresponding WS. However, I can't just pass the xml directly, I have to use the information given there to build my own envelope, so I'm wondering if there is a way to decode the password in the security section of the envelope (PasswordDigest). I have checked some soap documentation but it is more on how to create it, rather than how to 'decode' it......I have all the fields available to me (Nonce, pass, created, etc)... any recommendations?

thanks!

Title: Decode password in SOAP xml envelope


问:
React Native Android duplicate resources when building with asembleRelease
"react-native": "0.68.2"

Hi everybody, I'm trying to get .aab file for my react native app but when I use command:

```<code>gradlew assembleRelease
</code>```

I get the following error:

```<code>Task :app:mergeReleaseResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeReleaseResources'.
> [drawable-hdpi-v4/node_modules_reactnavigation_elements_src_assets_backicon] C:\xampp\htdocs\Woo\android\app\src\main\res\drawable-hdpi\node_modules_reactnavigation_elements_src_assets_backicon.png [drawable-hdpi-v4/node_modules_reactnavigation_elements_src_assets_backicon] C:\xampp\htdocs\Woo\android\app\build\generated\res\react\release\drawable-hdpi\node_modules_reactnavigation_elements_src_assets_backicon.png: Error: Duplicate resources
  [drawable-mdpi-v4/assets_images_amaro1] C:\xampp\htdocs\Woo\android\app\src\main\res\drawable-mdpi\assets_images_amaro1.jpeg  [drawable-mdpi-v4/assets_images_amaro1] C:\xampp\htdocs\Woo\android\app\build\generated\res\react\release\drawable-mdpi\assets_images_amaro1.jpeg: Error: Duplicate resources
  [drawable-mdpi-v4/assets_images_applogo] C:\xampp\htdocs\Woo\android\app\src\main\res\drawable-mdpi\assets_images_applogo.png [drawable-mdpi-v4/assets_images_applogo] C:\xampp\htdocs\Woo\android\app\build\generated\res\react\release\drawable-mdpi\assets_images_applogo.png: Error: Duplicate resources
</code>```

Body:
"react-native": "0.68.2"

Hi everybody, I'm trying to get .aab file for my react native app but when I use command:

gradlew assembleRelease

I get the following error:

Task :app:mergeReleaseResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeReleaseResources'.
> [drawable-hdpi-v4/node_modules_reactnavigation_elements_src_assets_backicon] C:\xampp\htdocs\Woo\android\app\src\main\res\drawable-hdpi\node_modules_reactnavigation_elements_src_assets_backicon.png [drawable-hdpi-v4/node_modules_reactnavigation_elements_src_assets_backicon] C:\xampp\htdocs\Woo\android\app\build\generated\res\react\release\drawable-hdpi\node_modules_reactnavigation_elements_src_assets_backicon.png: Error: Duplicate resources
  [drawable-mdpi-v4/assets_images_amaro1] C:\xampp\htdocs\Woo\android\app\src\main\res\drawable-mdpi\assets_images_amaro1.jpeg  [drawable-mdpi-v4/assets_images_amaro1] C:\xampp\htdocs\Woo\android\app\build\generated\res\react\release\drawable-mdpi\assets_images_amaro1.jpeg: Error: Duplicate resources
  [drawable-mdpi-v4/assets_images_applogo] C:\xampp\htdocs\Woo\android\app\src\main\res\drawable-mdpi\assets_images_applogo.png [drawable-mdpi-v4/assets_images_applogo] C:\xampp\htdocs\Woo\android\app\build\generated\res\react\release\drawable-mdpi\assets_images_applogo.png: Error: Duplicate resources


问:
Hello, I am running e2e tests in my NestJs application. But on Auth the test kept failing I tried to modify from scratch but I'm not getting the issue
I tried to make modifications but I keep on getting the same error each time I run the test this error is the following:

```<code> console.error
    {
      "errno": -4078,
      "code": "ECONNREFUSED",
      "syscall": "connect",
      "address": "127.0.0.1",
      "port": 5000
    }
</code>```
```<code> FAIL  test/app.e2e-spec.ts (20.009 s)
  App e2e
    ✎ todo should compile
  Auth
    Signup
      × should signup (416 ms)

  ● Auth › Signup › should signup

    assert.strictEqual(received, expected)

    Expected value to strictly be equal to:
      201
    Received:
      undefined

    Message:
      HTTP status undefined !== 201
</code>```

app.e2e-spec.ts:

`

```<code>import { INestApplication, ValidationPipe } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as pactum from 'pactum';
import { AppModule } from '../src/app.module';
import { AuthDto } from '../src/auth/dto';
import { PrismaService } from '../src/prisma/prisma.service';

describe('App e2e', () => {
  let app: INestApplication;
  let prisma: PrismaService;
  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();
    app = moduleRef.createNestApplication();
    app.useGlobalPipes(
      new ValidationPipe({
        whitelist: true,
      }),
    );
    await app.init();
    await app.listen(5000);
    pactum.request.setBaseUrl('http://localhost:5000');

    prisma = app.get(PrismaService);
  });
  afterAll(() => {
    app.close();
  });
  it.todo('should compile');
});

//auth
describe('Auth', () => {
  const dto: AuthDto = {
    adminID: '223yui',
    email: 'user@example.com',
    firstName: 'John',
    lastName: 'Doe',
    password: 'life',
  };
  describe('Signup', () => {
    it('should signup', () => {
      return pactum
        .spec()
        .post('/auth/signup')
        .withBody(dto)
        .expectStatus(201)
        .inspect();
    });
  });

  describe('Login', () => {});
});
</code>```

`

auth.controller.ts:

`

```<code>import { Body, Controller, HttpCode, Post } from '@nestjs/common';
import { HttpStatus } from '@nestjs/common/enums';
import { AuthService } from './auth.service';
import { AuthDto, LoginDto } from './dto';

@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @Post('signup')
  signup(@Body() dto: AuthDto) {
    return this.authService.signup(dto);
  }

  @HttpCode(HttpStatus.OK)
  @Post('login')
  login(@Body() dto: LoginDto) {
    return this.authService.login(dto);
  }
}
</code>```

`

initially the signup function is for creating the user admin and when I was passing the data in the postman it works perfectly so I started running test for my application then Auth tests on Signup tests kept failing and I kept getting the same exact error

Body:
I tried to make modifications but I keep on getting the same error each time I run the test this error is the following:

 console.error
    {
      "errno": -4078,
      "code": "ECONNREFUSED",
      "syscall": "connect",
      "address": "127.0.0.1",
      "port": 5000
    }

 FAIL  test/app.e2e-spec.ts (20.009 s)
  App e2e
    ✎ todo should compile
  Auth
    Signup
      × should signup (416 ms)

  ● Auth › Signup › should signup

    assert.strictEqual(received, expected)

    Expected value to strictly be equal to:
      201
    Received:
      undefined

    Message:
      HTTP status undefined !== 201

app.e2e-spec.ts:

`

import { INestApplication, ValidationPipe } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as pactum from 'pactum';
import { AppModule } from '../src/app.module';
import { AuthDto } from '../src/auth/dto';
import { PrismaService } from '../src/prisma/prisma.service';

describe('App e2e', () => {
  let app: INestApplication;
  let prisma: PrismaService;
  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();
    app = moduleRef.createNestApplication();
    app.useGlobalPipes(
      new ValidationPipe({
        whitelist: true,
      }),
    );
    await app.init();
    await app.listen(5000);
    pactum.request.setBaseUrl('http://localhost:5000');

    prisma = app.get(PrismaService);
  });
  afterAll(() => {
    app.close();
  });
  it.todo('should compile');
});

//auth
describe('Auth', () => {
  const dto: AuthDto = {
    adminID: '223yui',
    email: 'user@example.com',
    firstName: 'John',
    lastName: 'Doe',
    password: 'life',
  };
  describe('Signup', () => {
    it('should signup', () => {
      return pactum
        .spec()
        .post('/auth/signup')
        .withBody(dto)
        .expectStatus(201)
        .inspect();
    });
  });

  describe('Login', () => {});
});

`

auth.controller.ts:

`

import { Body, Controller, HttpCode, Post } from '@nestjs/common';
import { HttpStatus } from '@nestjs/common/enums';
import { AuthService } from './auth.service';
import { AuthDto, LoginDto } from './dto';

@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @Post('signup')
  signup(@Body() dto: AuthDto) {
    return this.authService.signup(dto);
  }

  @HttpCode(HttpStatus.OK)
  @Post('login')
  login(@Body() dto: LoginDto) {
    return this.authService.login(dto);
  }
}

`

initially the signup function is for creating the user admin and when I was passing the data in the postman it works perfectly so I started running test for my application then Auth tests on Signup tests kept failing and I kept getting the same exact error


问:
How to get multi keys event in Node.js terminal app?
I'm trying to read the keyboard input in a Node.js terminal application.
Currently, I can only read 1 key each time with some code like this:

process.stdin.setRawMode(true);
process.stdin.on('data', console.log);
```

I can also read some special keys (i.e. ctrl, shift, alt) at the same time they are pressed with other keys. But it doesn't work for all the keys.

For example, I cannot read w and d at the same time they are pressed. Only one of them will be caught in that listener (the latest one).

So, any idea how I can read multiple keys at the same time? (even more than 2 keys)

It's also fine if you recommend me any library that does this thing, then I can check its code to see how it works.

Body:
I'm trying to read the keyboard input in a Node.js terminal application.
Currently, I can only read 1 key each time with some code like this:

process.stdin.setRawMode(true);
process.stdin.on('data', console.log);

I can also read some special keys (i.e. ctrl, shift, alt) at the same time they are pressed with other keys. But it doesn't work for all the keys.

For example, I cannot read w and d at the same time they are pressed. Only one of them will be caught in that listener (the latest one).

So, any idea how I can read multiple keys at the same time? (even more than 2 keys)

It's also fine if you recommend me any library that does this thing, then I can check its code to see how it works.


问:
Can only save one input of my checkboxes to json
I would like to save my input of my checkboxes to json
When I use this method i can only save 1 checkbox.

```<code>import { useEffect } from "react";
import { MouseEventHandler, useState } from "react"
import Styles from "../css/BraboInputMeeting.module.css"
import { Disciplines, InputMeetingProps, NewMeeting } from "../datatypes";

export const InputMeeting = ({ onAdd }: InputMeetingProps) => {
    const [users, setUsers] = useState<Array<Disciplines>>([]);
    useEffect(() => {
        const fetchAndSet = async () => {
            const Response = await fetch('http://localhost:3000/disciplines');
            const json = await Response.json() as Disciplines[];
            setUsers(json);
        }
        fetchAndSet().catch((reason) => alert("Er is iets misgelopen bij het ophalen van de verschillende statistieken."));
    }, []);

    const [firstname, setFirstName] = useState('');
    const [lastname, setLastName] = useState('');
    const [discipline, setDiscipline] = useState('');
    const handleClick: MouseEventHandler<HTMLInputElement> = (event) => {
        if (firstname == '') { alert("U hebt nog geen voornaam ingevuld!!") }
        else if (lastname == '') { alert("U hebt nog geen achternaam ingevuld!!") }
        else if (discipline == '') { alert("U hebt nog geen discipline ingevuld!!") }
        else {
            onAdd({
                firstname: firstname,
                lastname: lastname,
                discipline: discipline,
            });
            {
                setFirstName('');
                setLastName('');
                setDiscipline('');
                alert("We hebben uw inschrijving goed ontvangen!")
            }
        }
    }
    return (
        <form>
            <table className={Styles.table}>
                <tr className={Styles.labelinput}>
                    <td><label className={Styles.label}>Voornaam</label></td>
                    <td colSpan={2}><input required type="text" id="firstname" value={firstname} onChange={(event) => setFirstName(event.target.value)} className={Styles.input} /></td>
                </tr>
                <tr className={Styles.labelinput}>
                    <td> <label className={Styles.label}>Achternaam</label></td>
                    <td colSpan={2}> <input required type="text" id="lastname" value={lastname} onChange={(event) => setLastName(event.target.value)} className={Styles.input} /></td>
                </tr>
                <tr className={Styles.labelinput}>
                    <td><label className={Styles.label}>Discipline</label></td>
                    <td className={Styles.checkbox}>{users.length > 0 &&
                        users.map((item: any) => (
                            <div key={item.id} >
                                <span>
                                    <input
                                        type="checkbox"
                                        value={item.disc}
                                        onChange={(event) => setDiscipline(event.target.value)}

                                    />
                                    {item.disc}</span>
                            </div>
                        ))}
                    </td>
                </tr>
                <tr>
                    <td colSpan={4} className={Styles.tdbutton}><input type="button" id="submit" value="Add" onClick={handleClick} className={Styles.button} /></td>
                </tr>
            </table >

        </form >
    )
}
</code>```

Here I would like to save the input of my checkbox.
Firstname and lastname and all the disciplines i would like to run

```<code>"newmeeting": [
    {
      "firstname": "Danny",
      "lastname": "Van Cauwenbergh",
      "discipline": "100m",
      "id": 1
    }]
</code>```

This is the list in json I use to make the checkboxes.

```<code>"disciplines": [
    {
      "id": 1,
      "disc": "100m"
    },
    {
      "id": 2,
      "disc": "200m"
    },
    {
      "id": 3,
      "disc": "800m"
    },
    {
      "id": 4,
      "disc": "1500m"
    },
    {
      "id": 5,
      "disc": "Kogelstoten"
    },
    {
      "id": 6,
      "disc": "Hoogspringen"
    },
    {
      "id": 7,
      "disc": "Verspringen"
    },
    {
      "id": 8,
      "disc": "Speerwerpen"
    },
    {
      "id": 9,
      "disc": "Discuswerpen"
    }
  ]
</code>```

Now I can only save the last checkbox to json but I want them to save all my checked checkboxes

Body:
I would like to save my input of my checkboxes to json
When I use this method i can only save 1 checkbox.

import { useEffect } from "react";
import { MouseEventHandler, useState } from "react"
import Styles from "../css/BraboInputMeeting.module.css"
import { Disciplines, InputMeetingProps, NewMeeting } from "../datatypes";

export const InputMeeting = ({ onAdd }: InputMeetingProps) => {
    const [users, setUsers] = useState<Array<Disciplines>>([]);
    useEffect(() => {
        const fetchAndSet = async () => {
            const Response = await fetch('http://localhost:3000/disciplines');
            const json = await Response.json() as Disciplines[];
            setUsers(json);
        }
        fetchAndSet().catch((reason) => alert("Er is iets misgelopen bij het ophalen van de verschillende statistieken."));
    }, []);

    const [firstname, setFirstName] = useState('');
    const [lastname, setLastName] = useState('');
    const [discipline, setDiscipline] = useState('');
    const handleClick: MouseEventHandler<HTMLInputElement> = (event) => {
        if (firstname == '') { alert("U hebt nog geen voornaam ingevuld!!") }
        else if (lastname == '') { alert("U hebt nog geen achternaam ingevuld!!") }
        else if (discipline == '') { alert("U hebt nog geen discipline ingevuld!!") }
        else {
            onAdd({
                firstname: firstname,
                lastname: lastname,
                discipline: discipline,
            });
            {
                setFirstName('');
                setLastName('');
                setDiscipline('');
                alert("We hebben uw inschrijving goed ontvangen!")
            }
        }
    }
    return (
        <form>

                    Voornaam
                    <input required type="text" id="firstname" value={firstname} onChange={(event) => setFirstName(event.target.value)} className={Styles.input} />

                     Achternaam
                     <input required type="text" id="lastname" value={lastname} onChange={(event) => setLastName(event.target.value)} className={Styles.input} />

                    Discipline
                    {users.length > 0 &&
                        users.map((item: any) => (

                                    <input
                                        type="checkbox"
                                        value={item.disc}
                                        onChange={(event) => setDiscipline(event.target.value)}

                                    />
                                    {item.disc}

                        ))}

                    <input type="button" id="submit" value="Add" onClick={handleClick} className={Styles.button} />

        </form >
    )
}

Here I would like to save the input of my checkbox.
Firstname and lastname and all the disciplines i would like to run

"newmeeting": [
    {
      "firstname": "Danny",
      "lastname": "Van Cauwenbergh",
      "discipline": "100m",
      "id": 1
    }]

This is the list in json I use to make the checkboxes.

"disciplines": [
    {
      "id": 1,
      "disc": "100m"
    },
    {
      "id": 2,
      "disc": "200m"
    },
    {
      "id": 3,
      "disc": "800m"
    },
    {
      "id": 4,
      "disc": "1500m"
    },
    {
      "id": 5,
      "disc": "Kogelstoten"
    },
    {
      "id": 6,
      "disc": "Hoogspringen"
    },
    {
      "id": 7,
      "disc": "Verspringen"
    },
    {
      "id": 8,
      "disc": "Speerwerpen"
    },
    {
      "id": 9,
      "disc": "Discuswerpen"
    }
  ]

Now I can only save the last checkbox to json but I want them to save all my checked checkboxes


问:
connection timed out while reading ssm parameter in Lambda
I have a lambda that it is vpce enabled to read secure string ssm paramater.

I have created vpc endpoint for ssm to establish private connectivity.

I'm getting this error Connect timeout on endpoint URL: "https://ssm.us-east-1.amazonaws.com/", even though I can access the ssm parameter via ec2 instance.

python code:

```<code>ssmp='testssm'
config = Config(retries=dict(max_attempts=3, mode='standard'))
ssm_client = boto3.client('ssm', config=config)
fx= ssm_client.get_parameter(
    Name=ssmp,
    WithDecryption=True
)
</code>```

is there any idea why this is happening?

Body:
I have a lambda that it is vpce enabled to read secure string ssm paramater.

I have created vpc endpoint for ssm to establish private connectivity.

I'm getting this error Connect timeout on endpoint URL: "https://ssm.us-east-1.amazonaws.com/", even though I can access the ssm parameter via ec2 instance.

python code:

ssmp='testssm'
config = Config(retries=dict(max_attempts=3, mode='standard'))
ssm_client = boto3.client('ssm', config=config)
fx= ssm_client.get_parameter(
    Name=ssmp,
    WithDecryption=True
)

is there any idea why this is happening?


问:
Decrypting file created with old openssl version
I have an archive created with OpenSSL 1.0.lt version (May 2016). I am able to decrypt it by using the same version with command openssl aes-256-cbc -d -in file.enc -out clear.zip -pass pass:MY_KEY. I am not able to decrypt it using a more recent OpenSSL version.

When I try the same command with OpenSSL version 1.1.1 I get an error message: digital envelope routines: EVP_DecryptFinal_ex:bad decrypt:../crypto/evp/evp_enc.c.610. Do I have to modify the command?