问:
OpenCV virtual keyboard how to change keyboard keys when shift button is clicked?
I am creating a virtual keyboard using OpenCV. I want to implement a function whereby whenever the shift button is clicked, the keys change to their respective "shifted" keys, e.g. a -> A.

Here is what I have currently:

A keyboard class that contains:

the set of keys

is_clicked function which calls the is_clicked function of the Button class, which uses cv2.EVENT_LBUTTONDOWN

and a draw function, which draws the keyboard on the screen

```<code>class QWERTYKeyboard:
    def __init__(self):

        self.keys = [['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '+'],
                    ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\\'],
                    ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '"'],
                    ['z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '?']]

        self.button_list = []

        for i in range(len(self.keys[0])):
            self.button_list.append(NormalButton((50 * i + 100, 250), self.keys[0][i]))

        for i in range(len(self.keys[1])):
            self.button_list.append(NormalButton((50 * i + 125, 300), self.keys[1][i]))

        for i in range(len(self.keys[2])):
            self.button_list.append(NormalButton((50 * i + 150, 350), self.keys[2][i]))

        for i in range(len(self.keys[3])):
            self.button_list.append(NormalButton((50 * i + 175, 400), self.keys[3][i]))

        self.button_list.append(SpaceBar((250, 450)))

        self.button_list.append(Backspace((700, 250)))

        self.button_list.append(Enter((700, 350)))

        self.button_list.append(Shift((675, 400)))

    def draw(self, img):
        for button in self.button_list:
            button.draw(img)

        return img

    def is_clicked(self, event, x, y, flags, param):
        for button in self.button_list:
            if button.is_clicked(event, x, y, flags, param):
                if button.text == "Shift":
                    self.shift_keys()
                return button.text

    def is_hovered_over(self, event, x, y, flags, param):
        for button in self.button_list:
            if button.is_hovered_over(event, x, y, flags, param):
                return button.text

    def shift_keys(self) :
        '''
        Change keys when shift or caps lock is pressed
        '''
        # I'm testing it with the alphabet keys first
        for i in range(len(self.keys)):
            for j in range(len(self.keys[i])):
                self.keys[i][j] = self.keys[i][j].upper()

</code>```

The main python file:

```<code>import cv2
from keyboards import QWERTYKeyboard

cap = cv2.VideoCapture(0)
keyboard = QWERTYKeyboard.QWERTYKeyboard()

cv2.namedWindow("Image", cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty("Image", cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)
cv2.setMouseCallback("Image", keyboard.is_clicked)
cv2.setMouseCallback("Image", keyboard.is_hovered_over)

while cap.isOpened():
    success, img = cap.read()

    img = keyboard.draw(img)

    cv2.imshow("Image", img)

    if cv2.waitKey(5) & 0xFF == 27:
      break

cv2.destroyAllWindows()
cap.release()
</code>```

I understand that even though shift_keys is called when the Shift button is pressed, the updated keyboard is not being drawn. How do I draw the new keyboard in the main python file?

Body:
I am creating a virtual keyboard using OpenCV. I want to implement a function whereby whenever the shift button is clicked, the keys change to their respective "shifted" keys, e.g. a -> A.

Here is what I have currently:

A keyboard class that contains:

the set of keys

is_clicked function which calls the is_clicked function of the Button class, which uses cv2.EVENT_LBUTTONDOWN

and a draw function, which draws the keyboard on the screen

class QWERTYKeyboard:
    def __init__(self):

        self.keys = [['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '+'],
                    ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\\'],
                    ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '"'],
                    ['z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '?']]

        self.button_list = []

        for i in range(len(self.keys[0])):
            self.button_list.append(NormalButton((50 * i + 100, 250), self.keys[0][i]))

        for i in range(len(self.keys[1])):
            self.button_list.append(NormalButton((50 * i + 125, 300), self.keys[1][i]))

        for i in range(len(self.keys[2])):
            self.button_list.append(NormalButton((50 * i + 150, 350), self.keys[2][i]))

        for i in range(len(self.keys[3])):
            self.button_list.append(NormalButton((50 * i + 175, 400), self.keys[3][i]))

        self.button_list.append(SpaceBar((250, 450)))

        self.button_list.append(Backspace((700, 250)))

        self.button_list.append(Enter((700, 350)))

        self.button_list.append(Shift((675, 400)))

    def draw(self, img):
        for button in self.button_list:
            button.draw(img)

        return img

    def is_clicked(self, event, x, y, flags, param):
        for button in self.button_list:
            if button.is_clicked(event, x, y, flags, param):
                if button.text == "Shift":
                    self.shift_keys()
                return button.text

    def is_hovered_over(self, event, x, y, flags, param):
        for button in self.button_list:
            if button.is_hovered_over(event, x, y, flags, param):
                return button.text

    def shift_keys(self) :
        '''
        Change keys when shift or caps lock is pressed
        '''
        # I'm testing it with the alphabet keys first
        for i in range(len(self.keys)):
            for j in range(len(self.keys[i])):
                self.keys[i][j] = self.keys[i][j].upper()

The main python file:

import cv2
from keyboards import QWERTYKeyboard

cap = cv2.VideoCapture(0)
keyboard = QWERTYKeyboard.QWERTYKeyboard()

cv2.namedWindow("Image", cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty("Image", cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)
cv2.setMouseCallback("Image", keyboard.is_clicked)
cv2.setMouseCallback("Image", keyboard.is_hovered_over)

while cap.isOpened():
    success, img = cap.read()

    img = keyboard.draw(img)

    cv2.imshow("Image", img)

    if cv2.waitKey(5) & 0xFF == 27:
      break

cv2.destroyAllWindows()
cap.release()

I understand that even though shift_keys is called when the Shift button is pressed, the updated keyboard is not being drawn. How do I draw the new keyboard in the main python file?


来源: stackexchange

问:
How to subset a xarray.Dataset according to lat/lon values taken from a SRTM DEM extents
I have a year wise (1980-2020) precipitation data set in netCDF format. I am importing them in xarray to have 40 years of merged precipitation values:

```<code>import netCDF4
import numpy
import xarray as xr
import pandas as pd

prcp=xr.open_mfdataset('/home/hrsa/Sayantan/HAR_V2/prcp/HARv2_d10km_d_2d_prcp_*.nc',combine = 'nested', concat_dim="time")
prcp
</code>```

which renders:

```<code>xarray.Dataset
Dimensions:
time: 14976west_east: 381south_north: 252
Coordinates:
time
(time)
datetime64[ns]
1980-01-01 ... 2020-12-31
west_east
(west_east)
float32
-1.675e+06 -1.665e+06 ... 2.125e+06
south_north
(south_north)
float32
-7.45e+05 -7.35e+05 ... 1.765e+06
lon
(south_north, west_east)
float32
dask.array<chunksize=(252, 381), meta=np.ndarray>
lat
(south_north, west_east)
float32
dask.array<chunksize=(252, 381), meta=np.ndarray>
Data variables:
prcp
(time, south_north, west_east)
float32
dask.array<chunksize=(366, 252, 381), meta=np.ndarray>
Attributes: (33)
</code>```

This a large dataset, hence I am required to subset it according to an SRTM image whose extents (in EPSG:4326) is defined as

```<code># Extents of the SRTM DEM covering Panchi_B and the SASE AWS/Base Camp
min_lon = 77.0
min_lat = 32.0
max_lon = 78.0
max_lat = 33.0
</code>```

In order to subset according to above coordinates I have tried the following:

```<code>prcp = prcp.sel(lat = slice(min_lat,max_lat), lon = slice(min_lon,max_lon))
</code>```

the Error output:

```<code>---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~/.pyenv/versions/3.9.7/envs/v3.9.7/lib/python3.9/site-packages/xarray/core/indexing.py:73, in group_indexers_by_index(data_obj, indexers, method, tolerance)
     72 try:
---> 73     index = xindexes[key]
     74     coord = data_obj.coords[key]

KeyError: 'lat'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
Input In [25], in <cell line: 1>()
----> 1 prcp = prcp.sel(lat = slice(min_lat,max_lat), lon = slice(min_lon,max_lon))

File ~/.pyenv/versions/3.9.7/envs/v3.9.7/lib/python3.9/site-packages/xarray/core/dataset.py:2501, in Dataset.sel(self, indexers, method, tolerance, drop, **indexers_kwargs)
   2440 """Returns a new dataset with each array indexed by tick labels
   2441 along the specified dimension(s).
   2442
   (...)
   2498 DataArray.sel
   2499 """
   2500 indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "sel")
-> 2501 pos_indexers, new_indexes = remap_label_indexers(
   2502     self, indexers=indexers, method=method, tolerance=tolerance
   2503 )
   2504 # TODO: benbovy - flexible indexes: also use variables returned by Index.query
   2505 # (temporary dirty fix).
   2506 new_indexes = {k: v[0] for k, v in new_indexes.items()}

File ~/.pyenv/versions/3.9.7/envs/v3.9.7/lib/python3.9/site-packages/xarray/core/coordinates.py:421, in remap_label_indexers(obj, indexers, method, tolerance, **indexers_kwargs)
    414 indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "remap_label_indexers")
    416 v_indexers = {
    417     k: v.variable.data if isinstance(v, DataArray) else v
    418     for k, v in indexers.items()
    419 }
--> 421 pos_indexers, new_indexes = indexing.remap_label_indexers(
    422     obj, v_indexers, method=method, tolerance=tolerance
    423 )
    424 # attach indexer's coordinate to pos_indexers
    425 for k, v in indexers.items():

File ~/.pyenv/versions/3.9.7/envs/v3.9.7/lib/python3.9/site-packages/xarray/core/indexing.py:110, in remap_label_indexers(data_obj, indexers, method, tolerance)
    107 pos_indexers = {}
    108 new_indexes = {}
--> 110 indexes, grouped_indexers = group_indexers_by_index(
    111     data_obj, indexers, method, tolerance
    112 )
    114 forward_pos_indexers = grouped_indexers.pop(None, None)
    115 if forward_pos_indexers is not None:

File ~/.pyenv/versions/3.9.7/envs/v3.9.7/lib/python3.9/site-packages/xarray/core/indexing.py:84, in group_indexers_by_index(data_obj, indexers, method, tolerance)
     82 except KeyError:
     83     if key in data_obj.coords:
---> 84         raise KeyError(f"no index found for coordinate {key}")
     85     elif key not in data_obj.dims:
     86         raise KeyError(f"{key} is not a valid dimension or coordinate")

KeyError: 'no index found for coordinate lat'
</code>```

How can I resolve this issue? Any help will be appreciated, Thank you.

############# Edit (for @Robert Wilson) ##################

In order to find out the ranges, I did the following:

```<code>lon = prcp.lon.to_dataframe()
lon
</code>```

```<code>lat = prcp.lat.to_dataframe()
lat
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a year wise (1980-2020) precipitation data set in netCDF format. I am importing them in xarray to have 40 years of merged precipitation values:

import netCDF4
import numpy
import xarray as xr
import pandas as pd

prcp=xr.open_mfdataset('/home/hrsa/Sayantan/HAR_V2/prcp/HARv2_d10km_d_2d_prcp_*.nc',combine = 'nested', concat_dim="time")
prcp

which renders:

xarray.Dataset
Dimensions:
time: 14976west_east: 381south_north: 252
Coordinates:
time
(time)
datetime64[ns]
1980-01-01 ... 2020-12-31
west_east
(west_east)
float32
-1.675e+06 -1.665e+06 ... 2.125e+06
south_north
(south_north)
float32
-7.45e+05 -7.35e+05 ... 1.765e+06
lon
(south_north, west_east)
float32
dask.array<chunksize=(252, 381), meta=np.ndarray>
lat
(south_north, west_east)
float32
dask.array<chunksize=(252, 381), meta=np.ndarray>
Data variables:
prcp
(time, south_north, west_east)
float32
dask.array<chunksize=(366, 252, 381), meta=np.ndarray>
Attributes: (33)

This a large dataset, hence I am required to subset it according to an SRTM image whose extents (in EPSG:4326) is defined as

# Extents of the SRTM DEM covering Panchi_B and the SASE AWS/Base Camp
min_lon = 77.0
min_lat = 32.0
max_lon = 78.0
max_lat = 33.0

In order to subset according to above coordinates I have tried the following:

prcp = prcp.sel(lat = slice(min_lat,max_lat), lon = slice(min_lon,max_lon))

the Error output:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~/.pyenv/versions/3.9.7/envs/v3.9.7/lib/python3.9/site-packages/xarray/core/indexing.py:73, in group_indexers_by_index(data_obj, indexers, method, tolerance)
     72 try:
---> 73     index = xindexes[key]
     74     coord = data_obj.coords[key]

KeyError: 'lat'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
Input In [25], in <cell line: 1>()
----> 1 prcp = prcp.sel(lat = slice(min_lat,max_lat), lon = slice(min_lon,max_lon))

File ~/.pyenv/versions/3.9.7/envs/v3.9.7/lib/python3.9/site-packages/xarray/core/dataset.py:2501, in Dataset.sel(self, indexers, method, tolerance, drop, **indexers_kwargs)
   2440 """Returns a new dataset with each array indexed by tick labels
   2441 along the specified dimension(s).
   2442
   (...)
   2498 DataArray.sel
   2499 """
   2500 indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "sel")
-> 2501 pos_indexers, new_indexes = remap_label_indexers(
   2502     self, indexers=indexers, method=method, tolerance=tolerance
   2503 )
   2504 # TODO: benbovy - flexible indexes: also use variables returned by Index.query
   2505 # (temporary dirty fix).
   2506 new_indexes = {k: v[0] for k, v in new_indexes.items()}

File ~/.pyenv/versions/3.9.7/envs/v3.9.7/lib/python3.9/site-packages/xarray/core/coordinates.py:421, in remap_label_indexers(obj, indexers, method, tolerance, **indexers_kwargs)
    414 indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "remap_label_indexers")
    416 v_indexers = {
    417     k: v.variable.data if isinstance(v, DataArray) else v
    418     for k, v in indexers.items()
    419 }
--> 421 pos_indexers, new_indexes = indexing.remap_label_indexers(
    422     obj, v_indexers, method=method, tolerance=tolerance
    423 )
    424 # attach indexer's coordinate to pos_indexers
    425 for k, v in indexers.items():

File ~/.pyenv/versions/3.9.7/envs/v3.9.7/lib/python3.9/site-packages/xarray/core/indexing.py:110, in remap_label_indexers(data_obj, indexers, method, tolerance)
    107 pos_indexers = {}
    108 new_indexes = {}
--> 110 indexes, grouped_indexers = group_indexers_by_index(
    111     data_obj, indexers, method, tolerance
    112 )
    114 forward_pos_indexers = grouped_indexers.pop(None, None)
    115 if forward_pos_indexers is not None:

File ~/.pyenv/versions/3.9.7/envs/v3.9.7/lib/python3.9/site-packages/xarray/core/indexing.py:84, in group_indexers_by_index(data_obj, indexers, method, tolerance)
     82 except KeyError:
     83     if key in data_obj.coords:
---> 84         raise KeyError(f"no index found for coordinate {key}")
     85     elif key not in data_obj.dims:
     86         raise KeyError(f"{key} is not a valid dimension or coordinate")

KeyError: 'no index found for coordinate lat'

How can I resolve this issue? Any help will be appreciated, Thank you.

############# Edit (for @Robert Wilson) ##################

In order to find out the ranges, I did the following:

lon = prcp.lon.to_dataframe()
lon

lat = prcp.lat.to_dataframe()
lat


问:
How to use dynamic Heroku PORT for Node.js server inside Front-end part of the app?
I'm trying to deploy an app created with the MERN stack on Heroku.

The structure of my app:

the port for the Back-end (Node.js server) is created in server.js:

```<code>const port = process.env.PORT || 80;

app.listen(port, () => console.log(`Server running on port ${port}`));
</code>```

I added a proxy to my client's package.json:

I haven't added the environmental variable PORT to Config Vars inside the Heroku panel (I only have added mongoURI and REACT_APP_API_KEY):

As I understand, each time  in Heroku a dynamic port is created for the server:

Inside the 'client' part of the app (where all React.js files are kept) I'm calling a Back-end endpoint, e.g:

However, once the app is deployed (it is built successfully), in the Network tab I can see that the request is being made to http://localhost/pagesWithMovies/1.

How to use the dynamic PORT assigned by Heroku instead? Thanks

Body:
I'm trying to deploy an app created with the MERN stack on Heroku.

The structure of my app:

the port for the Back-end (Node.js server) is created in server.js:

const port = process.env.PORT || 80;

app.listen(port, () => console.log(`Server running on port ${port}`));

I added a proxy to my client's package.json:

I haven't added the environmental variable PORT to Config Vars inside the Heroku panel (I only have added mongoURI and REACT_APP_API_KEY):

As I understand, each time  in Heroku a dynamic port is created for the server:

Inside the 'client' part of the app (where all React.js files are kept) I'm calling a Back-end endpoint, e.g:

However, once the app is deployed (it is built successfully), in the Network tab I can see that the request is being made to http://localhost/pagesWithMovies/1.

How to use the dynamic PORT assigned by Heroku instead? Thanks


问:
How to create an Assembly (CSharpCompilation) from an existing Assembly in Roslyn?
In .NET Framework 4.8, i could use AssemblyBuilder to create a new Assembly based on an existing Assembly, add some further modifications (such as encryption) and save it as a new .dll with AssemblyBuilder.Save().

In .NET 6, they removed the functionality to save an Assembly to file, along with other methods i used.

As an alternative i looked into Roslyn and how to generate Assemblies. The thing is, that i don't have the source code i want to compile into a new Assembly, but only an already compiled Assembly i want to modify.

My use case would look like this:

private void Protect(FileInfo dllSourceFile, FileInfo targetFile) {
    Assembly assembly = Assembly.LoadFrom(dllSourceFile.FullName);
    CSharpCompilation compilation = CSharpCompilation.Create(assembly);
    //...modify compilation, encrypt files
    var result = compilation.Emit(targetFile.FullName);
}
```

Is there any functionality in Roslyn (or .Net 6) that helps me here? Even better if it directly uses AssemblyBuilder instead of Assembly.

Body:
In .NET Framework 4.8, i could use AssemblyBuilder to create a new Assembly based on an existing Assembly, add some further modifications (such as encryption) and save it as a new .dll with AssemblyBuilder.Save().

In .NET 6, they removed the functionality to save an Assembly to file, along with other methods i used.

As an alternative i looked into Roslyn and how to generate Assemblies. The thing is, that i don't have the source code i want to compile into a new Assembly, but only an already compiled Assembly i want to modify.

My use case would look like this:

private void Protect(FileInfo dllSourceFile, FileInfo targetFile) {
    Assembly assembly = Assembly.LoadFrom(dllSourceFile.FullName);
    CSharpCompilation compilation = CSharpCompilation.Create(assembly);
    //...modify compilation, encrypt files
    var result = compilation.Emit(targetFile.FullName);
}

Is there any functionality in Roslyn (or .Net 6) that helps me here? Even better if it directly uses AssemblyBuilder instead of Assembly.


问:
Query DSL exemple for the Opensearch Anomaly detection plugin
Since we cannot use scripted fields in the opensearch anomaly detector plugin, I would like to compute small math operation within a Custom expression of my feature.

Now, it feels like it shouldn't be too complicated but I can't find a piece of information on where to start and what my query should look like.

So far, by default, it looks like that :

```<code>{
    "aggregation_name": {
        "sum": {
            "field": "field_name"
        }
    }
}
</code>```

And I don't know where to begin to make a change on this one.
I've read the doc , which simply refers the Query DSL doc, but I don't find any info about math op on fetch data.

The closest doc I found so far is this Pipeline Aggs doc. But I'm quite stuck here.

My question is how do I get a custom field that looks like that :

```<code>{
    "aggregation_name": {
        "sum": {
            "field": "field_name1 / (field_name1 + field_name2)"
        }
    }
}
</code>```

Thanks.

Body:
Since we cannot use scripted fields in the opensearch anomaly detector plugin, I would like to compute small math operation within a Custom expression of my feature.

Now, it feels like it shouldn't be too complicated but I can't find a piece of information on where to start and what my query should look like.

So far, by default, it looks like that :

{
    "aggregation_name": {
        "sum": {
            "field": "field_name"
        }
    }
}

And I don't know where to begin to make a change on this one.
I've read the doc , which simply refers the Query DSL doc, but I don't find any info about math op on fetch data.

The closest doc I found so far is this Pipeline Aggs doc. But I'm quite stuck here.

My question is how do I get a custom field that looks like that :

{
    "aggregation_name": {
        "sum": {
            "field": "field_name1 / (field_name1 + field_name2)"
        }
    }
}

Thanks.


问:
How to make www.mydomain.com work in nextjs
I am working on a project and trying to make www.mydomain.com work. I am working on localhost:3000 and when I put in url: mydomain.com:3000 it works but when I set www.mydomian.com:3000 it redirects me on mydomain.is which is my main page.

this is my code in next.config.js file

```<code>const path = require("path");
const redirects = require("./redirects");

/** @type {import('next').NextConfig} */
const nextConfig = async () => {
  return {
    reactStrictMode: false,
    swcMinify: true,
    sassOptions: {
      includePaths: [path.join(__dirname, "src/styles")],
    },
    redirects() {
      return Promise.resolve(redirects);
    },
    images: {
      domains: ["mydomain.cdn.prismic.io", "images.prismic.io"],
    },
    i18n: {
      // https://nextjs.org/docs/advanced-features/i18n-routing
      localeDetection: false,

      locales: ["is", "en"],

      defaultLocale: "is",

      domains: [
        {
          domain: 'mydomain.is',
          defaultLocale: 'is',
        },
        {
          domain: 'mydomain.com',
          defaultLocale: 'en',
        },
      ],
    },
  };
};

module.exports = nextConfig;`
</code>```

Body:
I am working on a project and trying to make www.mydomain.com work. I am working on localhost:3000 and when I put in url: mydomain.com:3000 it works but when I set www.mydomian.com:3000 it redirects me on mydomain.is which is my main page.

this is my code in next.config.js file

const path = require("path");
const redirects = require("./redirects");

/** @type {import('next').NextConfig} */
const nextConfig = async () => {
  return {
    reactStrictMode: false,
    swcMinify: true,
    sassOptions: {
      includePaths: [path.join(__dirname, "src/styles")],
    },
    redirects() {
      return Promise.resolve(redirects);
    },
    images: {
      domains: ["mydomain.cdn.prismic.io", "images.prismic.io"],
    },
    i18n: {
      // https://nextjs.org/docs/advanced-features/i18n-routing
      localeDetection: false,

      locales: ["is", "en"],

      defaultLocale: "is",

      domains: [
        {
          domain: 'mydomain.is',
          defaultLocale: 'is',
        },
        {
          domain: 'mydomain.com',
          defaultLocale: 'en',
        },
      ],
    },
  };
};

module.exports = nextConfig;`


问:
Which Woocommerce hook should i use?
I want to get new order information but after payment.

i tried use new_order hook but i get all status orders

This hook doesn't work.

```<code>add_action('woocommerce_payment_successful_result','order_to_tsm',10,1);
</code>```

Title: Which Woocommerce hook should i use?

Body:
I want to get new order information but after payment.

i tried use new_order hook but i get all status orders

This hook doesn't work.

add_action('woocommerce_payment_successful_result','order_to_tsm',10,1);


问:
Wrong list output based on algorithm pseudocode
To give a brief overview on the problem I am having, I am following a research paper and implementing an algorithm that given some properties of my DFA as shown below

I am to implement these two algorithms

I implemented both algorithms and instead of getting Max = [1, 2, 2, 2, 3, 3, 3] and
Boxed = [1, 2, 1, 2, 2, 1, 3]

I get Max: [1, 2, 2, 2, 2, 2, 2] Boxed: [1, 2, 1, 2, 2, 1, 2]

I cannot figure out what is wrong with my function implementation to get the wrong lists I have tried to debug but based on the algorithm description and implementation everything looks right, any help would be appreciated. I will include code below to run the DFA along with the inputs to replicate the same output that I am getting.

```<code>import os

class DFA:

    def __init__(self):
        """Initialize DFSM object"""
        self.Q = self.populateStates()
        self.SIGMA = self.populateAlphabet()
        self.DELTA = self.populateDeltaTable()
        self.startState, self.acceptStates = self.setStartingandAccepting()
        self.currentState = self.startState # Would be start state by default

    def setStartingandAccepting(self):
        """Takes user input for startState and ACCEPT_STATE, and checks if it's a valid state (if it belongs to Q)"""
        while(True):
            start = input("Enter the start state: ")
            accept = input("Enter the accept states: ").split()
            #Making sure that start and accept are both in Q and that start and accept are not the state
            if (start in self.Q) and (set(accept).issubset(set(self.Q))):
                return start, accept
            else:
                print("Please enter start state and accept states that are in Q : {}.\nAccept states should be a valid subset of Q\n".format(self.Q))

    def populateStates(self):
        """Takes user input for states (Q)"""
        Q_input = input("Enter list of states separated by spaces: ").split()
        print("STATES : {}".format(Q_input))
        return Q_input

    def populateAlphabet(self):
        """Takes user input for alphabet/symbols (SIGMA)"""
        SIGMA_input = input("Enter input alphabet separated by spaces: ").split()
        print("ALPHABET : {}".format(SIGMA_input))
        return SIGMA_input

    def populateDeltaTable(self):
        """Creates the transition function (Q X SIGMA -> Q) and prints it out"""
        transition_dict = {el : {el_2 : 'REJECT' for el_2 in self.SIGMA} for el in self.Q} # Holds a dict that consists of {states: alphabet}

        for key, dict_value in transition_dict.items():
            print("Enter transitions for state {}. If required, use 'REJECT'.".format(key))

            for input_alphabet, transition_state in dict_value.items():
                transition_dict[key][input_alphabet] = input("CURRENT STATE : {}\tINPUT ALPHABET : {}\tNEXT STATE : ".format(key, input_alphabet))

        print("\nTRANSITION FUNCTION Q X SIGMA -> Q")
        print("CURRENT STATE\tINPUT ALPHABET\tNEXT STATE")
        for key, dict_value in transition_dict.items():
            for input_alphabet, transition_state in dict_value.items():
                print("{}\t\t{}\t\t{}".format(key, input_alphabet, transition_state))

        return transition_dict

    def runStateTransitions(self, input_symbol):
        """Takes in current state and goes to next state based on input symbol."""
        if (self.currentState == 'REJECT'):
            return False
        print("CURRENT STATE : {}\tINPUT SYMBOL : {}\t NEXT STATE : {}".format(self.currentState, input_symbol, self.DELTA[self.currentState][input_symbol]))
        self.currentState = self.DELTA[self.currentState][input_symbol]
        return self.currentState

    def checkIfValid(self):
        """Checks if the current state is one of the accept states."""
        if self.currentState in self.acceptStates:
            return True
        else:
            return False

    def runAutomata(self, in_string):
        """Run the machine on input string"""
        self.currentState = self.startState
        for ele in in_string:
            check_state = self.runStateTransitions(ele)
            #Check if new state is not REJECT
            if (check_state == 'REJECT'):
                return False
        return self.checkIfValid()

    def prettyPrint(self):
        """
        Displays information about the DFA in an easy to read manner
        """
        print("\n--------------------------------------------\n")
        print("Pretty Printing DFA Information: ")
        print("This DFA has %s states" %len(self.Q))
        print("States: ", self.Q)
        print("Alphabet: ", self.SIGMA)
        print("Starting State: ", self.startState)
        print("Accepting States:", self.acceptStates)
        print("Current State: ", self.currentState)
        print("TRANSITION FUNCTION Q X SIGMA -> Q")
        print("CURRENT STATE\tINPUT ALPHABET\tNEXT STATE")
        for key, dict_value in self.DELTA.items():
            for input_alphabet, transition_state in dict_value.items():
                print("{}\t\t{}\t\t{}".format(key, input_alphabet, transition_state))

def FromDfaToBoxedDyck(D):
    Max = []
    Boxed = []
    for q in D.Q:
        Visited = {q: False for q in D.Q} # Makes a dictionary with every state being set to false
        Number = {q: 0 for q in D.Q} # Makes a dictionary with every state being set to 0
    nbr = 0
    DepthFirst(D, D.startState, Max, Boxed, nbr, Visited, Number)
    return Max, Boxed

def DepthFirst(D, q, Max, Boxed, nbr, Visited, Number):
    Visited[q] = True
    nbr = nbr + 1
    print("updated nbr:",nbr)
    Number[q] = nbr
    for a in sorted(D.SIGMA):
        if Visited[D.DELTA[q][a]]:
            Max.append(nbr)
            print("Visited State:",D.DELTA[q][a])
            print("nbr:",nbr)
            Boxed.append(Number[D.DELTA[q][a]])
        else:
            print("Not Visited:",D.DELTA[q][a])
            DepthFirst(D, D.DELTA[q][a], Max, Boxed, nbr, Visited, Number)

if __name__ == "__main__":
    # check = True
    print("\nDeterministic Finite State Machine.")
    machine = DFA()
    os.system('clear') # Deletes all user inputted info
    machine.prettyPrint()
    Max,Boxed = FromDfaToBoxedDyck(machine)
    print("Max:",Max,"Boxed:",Boxed)
</code>```

Body:
To give a brief overview on the problem I am having, I am following a research paper and implementing an algorithm that given some properties of my DFA as shown below

I am to implement these two algorithms

I implemented both algorithms and instead of getting Max = [1, 2, 2, 2, 3, 3, 3] and
Boxed = [1, 2, 1, 2, 2, 1, 3]

I get Max: [1, 2, 2, 2, 2, 2, 2] Boxed: [1, 2, 1, 2, 2, 1, 2]

I cannot figure out what is wrong with my function implementation to get the wrong lists I have tried to debug but based on the algorithm description and implementation everything looks right, any help would be appreciated. I will include code below to run the DFA along with the inputs to replicate the same output that I am getting.

import os

class DFA:

    def __init__(self):
        """Initialize DFSM object"""
        self.Q = self.populateStates()
        self.SIGMA = self.populateAlphabet()
        self.DELTA = self.populateDeltaTable()
        self.startState, self.acceptStates = self.setStartingandAccepting()
        self.currentState = self.startState # Would be start state by default

    def setStartingandAccepting(self):
        """Takes user input for startState and ACCEPT_STATE, and checks if it's a valid state (if it belongs to Q)"""
        while(True):
            start = input("Enter the start state: ")
            accept = input("Enter the accept states: ").split()
            #Making sure that start and accept are both in Q and that start and accept are not the state
            if (start in self.Q) and (set(accept).issubset(set(self.Q))):
                return start, accept
            else:
                print("Please enter start state and accept states that are in Q : {}.\nAccept states should be a valid subset of Q\n".format(self.Q))

    def populateStates(self):
        """Takes user input for states (Q)"""
        Q_input = input("Enter list of states separated by spaces: ").split()
        print("STATES : {}".format(Q_input))
        return Q_input

    def populateAlphabet(self):
        """Takes user input for alphabet/symbols (SIGMA)"""
        SIGMA_input = input("Enter input alphabet separated by spaces: ").split()
        print("ALPHABET : {}".format(SIGMA_input))
        return SIGMA_input

    def populateDeltaTable(self):
        """Creates the transition function (Q X SIGMA -> Q) and prints it out"""
        transition_dict = {el : {el_2 : 'REJECT' for el_2 in self.SIGMA} for el in self.Q} # Holds a dict that consists of {states: alphabet}

        for key, dict_value in transition_dict.items():
            print("Enter transitions for state {}. If required, use 'REJECT'.".format(key))

            for input_alphabet, transition_state in dict_value.items():
                transition_dict[key][input_alphabet] = input("CURRENT STATE : {}\tINPUT ALPHABET : {}\tNEXT STATE : ".format(key, input_alphabet))

        print("\nTRANSITION FUNCTION Q X SIGMA -> Q")
        print("CURRENT STATE\tINPUT ALPHABET\tNEXT STATE")
        for key, dict_value in transition_dict.items():
            for input_alphabet, transition_state in dict_value.items():
                print("{}\t\t{}\t\t{}".format(key, input_alphabet, transition_state))

        return transition_dict

    def runStateTransitions(self, input_symbol):
        """Takes in current state and goes to next state based on input symbol."""
        if (self.currentState == 'REJECT'):
            return False
        print("CURRENT STATE : {}\tINPUT SYMBOL : {}\t NEXT STATE : {}".format(self.currentState, input_symbol, self.DELTA[self.currentState][input_symbol]))
        self.currentState = self.DELTA[self.currentState][input_symbol]
        return self.currentState

    def checkIfValid(self):
        """Checks if the current state is one of the accept states."""
        if self.currentState in self.acceptStates:
            return True
        else:
            return False

    def runAutomata(self, in_string):
        """Run the machine on input string"""
        self.currentState = self.startState
        for ele in in_string:
            check_state = self.runStateTransitions(ele)
            #Check if new state is not REJECT
            if (check_state == 'REJECT'):
                return False
        return self.checkIfValid()

    def prettyPrint(self):
        """
        Displays information about the DFA in an easy to read manner
        """
        print("\n--------------------------------------------\n")
        print("Pretty Printing DFA Information: ")
        print("This DFA has %s states" %len(self.Q))
        print("States: ", self.Q)
        print("Alphabet: ", self.SIGMA)
        print("Starting State: ", self.startState)
        print("Accepting States:", self.acceptStates)
        print("Current State: ", self.currentState)
        print("TRANSITION FUNCTION Q X SIGMA -> Q")
        print("CURRENT STATE\tINPUT ALPHABET\tNEXT STATE")
        for key, dict_value in self.DELTA.items():
            for input_alphabet, transition_state in dict_value.items():
                print("{}\t\t{}\t\t{}".format(key, input_alphabet, transition_state))

def FromDfaToBoxedDyck(D):
    Max = []
    Boxed = []
    for q in D.Q:
        Visited = {q: False for q in D.Q} # Makes a dictionary with every state being set to false
        Number = {q: 0 for q in D.Q} # Makes a dictionary with every state being set to 0
    nbr = 0
    DepthFirst(D, D.startState, Max, Boxed, nbr, Visited, Number)
    return Max, Boxed

def DepthFirst(D, q, Max, Boxed, nbr, Visited, Number):
    Visited[q] = True
    nbr = nbr + 1
    print("updated nbr:",nbr)
    Number[q] = nbr
    for a in sorted(D.SIGMA):
        if Visited[D.DELTA[q][a]]:
            Max.append(nbr)
            print("Visited State:",D.DELTA[q][a])
            print("nbr:",nbr)
            Boxed.append(Number[D.DELTA[q][a]])
        else:
            print("Not Visited:",D.DELTA[q][a])
            DepthFirst(D, D.DELTA[q][a], Max, Boxed, nbr, Visited, Number)

if __name__ == "__main__":
    # check = True
    print("\nDeterministic Finite State Machine.")
    machine = DFA()
    os.system('clear') # Deletes all user inputted info
    machine.prettyPrint()
    Max,Boxed = FromDfaToBoxedDyck(machine)
    print("Max:",Max,"Boxed:",Boxed)


问:
Python with docker - no such file or directory
i'm trying to develop a python application with vscode and docker containers.

Currently i'm using vscode's default dockerfile and when i run it returns this error:

```<code>FileNotFoundError: [Errno 2] No such file or directory: '/app/spotify-2-mp3\\main.py'
</code>```

This is my dockerfile:

```<code># For more information, please refer to https://aka.ms/vscode-docker-python
FROM python

# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1

# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
WORKDIR /app
# Install pip requirements
COPY . .
RUN python -m pip install -r requirements.txt

# Creates a non-root user with an explicit UID and adds permission to access the /app folder
# For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
USER appuser

# During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["python", "spotify-2-mp3/main.py"]
</code>```

And this is my directory tree:

Body:
i'm trying to develop a python application with vscode and docker containers.

Currently i'm using vscode's default dockerfile and when i run it returns this error:

FileNotFoundError: [Errno 2] No such file or directory: '/app/spotify-2-mp3\\main.py'

This is my dockerfile:

# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python

# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1

# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
WORKDIR /app
# Install pip requirements
COPY . .
RUN python -m pip install -r requirements.txt

# Creates a non-root user with an explicit UID and adds permission to access the /app folder
# For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
USER appuser

# During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["python", "spotify-2-mp3/main.py"]

And this is my directory tree:


Title: Maintain a submenu open after clicking a submenu item In next js

Body:
I have  a list array with submenu items which I am mapping through for the content of my sidebar. How do I maintain my submenu open after clicking on a submenu item ? It automatically closes when I click on a sub menu item.
Here is my array with sub menu item,
`

const navigation = [
  {
    name: "Business Summary",
    href: "/Settings",
    icon: (
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="22"
        height="22"
        viewBox="0 0 22 22"
        fill="none"

      >
        <path
          d="M7 12V16M15 10V16M11 6V16M21 11C21 16.5228 16.5228 21 11 21C5.47715 21 1 16.5228 1 11C1 5.47715 5.47715 1 11 1C16.5228 1 21 5.47715 21 11Z"
          strokeWidth="2"
         strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    ),
  },
  {
    name: "Customers",
    href: "/customers",
    icon: (
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="22"
        height="22"
        viewBox="0 0 22 19"
        fill="none"
      >
        <path
          d="M15 1.46776C16.4817 2.20411 17.5 3.73314 17.5 5.5C17.5 7.26686 16.4817 8.79589 15 9.53224M17 14.7664C18.5115 15.4503 19.8725 16.565 21 18M1 18C2.94649 15.5226 5.58918 14 8.5 14C11.4108 14 14.0535 15.5226 16 18M13 5.5C13 7.98528 10.9853 10 8.5 10C6.01472 10 4 7.98528 4 5.5C4 3.01472 6.01472 1 8.5 1C10.9853 1 13 3.01472 13 5.5Z"
          strokeWidth="2"
         strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    ),
  },
  {
    name: "Products",
    href: "/products",
    icon: (
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="22"
        height="22"
        viewBox="0 0 22 22"
        fill="none"
      >
        <path
          d="M11 11H11.01M17 5H17.01M5 5H5.01M17 17H17.01M5 17H5.01M5.8 21H16.2C17.8802 21 18.7202 21 19.362 20.673C19.9265 20.3854 20.3854 19.9265 20.673 19.362C21 18.7202 21 17.8802 21 16.2V5.8C21 4.11984 21 3.27976 20.673 2.63803C20.3854 2.07354 19.9265 1.6146 19.362 1.32698C18.7202 1 17.8802 1 16.2 1H5.8C4.11984 1 3.27976 1 2.63803 1.32698C2.07354 1.6146 1.6146 2.07354 1.32698 2.63803C1 3.27976 1 4.11984 1 5.8V16.2C1 17.8802 1 18.7202 1.32698 19.362C1.6146 19.9265 2.07354 20.3854 2.63803 20.673C3.27976 21 4.11984 21 5.8 21ZM11.5 11C11.5 11.2761 11.2761 11.5 11 11.5C10.7239 11.5 10.5 11.2761 10.5 11C10.5 10.7239 10.7239 10.5 11 10.5C11.2761 10.5 11.5 10.7239 11.5 11ZM16 11C16 13.7614 13.7614 16 11 16C8.23858 16 6 13.7614 6 11C6 8.23858 8.23858 6 11 6C13.7614 6 16 8.23858 16 11Z"
          strokeWidth="2"
         strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    ),
},
{
    name: "Loans",
    href: "/loans",
    icon: (
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="20"
        height="20"
        viewBox="0 0 20 20"
        fill="none"
      >
        <path
          d="M19 19H2.6C2.03995 19 1.75992 19 1.54601 18.891C1.35785 18.7951 1.20487 18.6422 1.10899 18.454C1 18.2401 1 17.9601 1 17.4V1M18 6L14.0811 10.1827C13.9326 10.3412 13.8584 10.4204 13.7688 10.4614C13.6897 10.4976 13.6026 10.5125 13.516 10.5047C13.4179 10.4958 13.3215 10.4458 13.1287 10.3457L9.87132 8.65433C9.67854 8.55423 9.58215 8.50418 9.48404 8.49534C9.39744 8.48753 9.31031 8.50245 9.23124 8.5386C9.14165 8.57957 9.06739 8.65883 8.91887 8.81734L5 13"
          strokeWidth="2"
         strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    ),

    submenu: true,
    submenuItems: [
      {
        title: "All Loans",
        href: "/loans",
      },
      {
        title: "Loan Products",
        href: "/loans/loanproducts",
      },
      {
        title: "Credit Portfolio",
        href: "/loans/creditportfolio",
      },
    ],
  },
];

`
Here is the opening and closing state,

const [submenuopen, setSubmenuOpen] = useState(false);

Here is how I am mapping
`

          {navigation.map((item, index) => (
            <>

                <span className={` flex  items-center stroke-current space-y-2.5   hover:text-slate-200  border-gray-700  text-[#5F6062]    ${router.pathname ===  item.href  && "text-slate-200"}`}>

                {item.icon}

                {/* <span className={` ${sidebar  ? "hidden" : "text-[#5F6062]  text-md ml-4" }  ${router.pathname === item.href ? " text-slate-200 text-md " : ""} `}  > */}
                <Link href={item.href}  >
               <span className={`${sidebar ?  "hidden" : "pb-2"}`}>
               {item.name}

               </Link>
                {/*   */}
                {item.submenu &&   (
                    <span    className={`hover:bg-[#808080] hover:text-slate-200 text-gray-700 ${router.pathname === item.href  && "text-slate-200"}`}>
                    <ChevronDownIcon className={`h-5 w-5 ml-32 cursor-pointer ${submenuopen &&  "rotate-180"}  ${sidebar ?  "hidden" : ""}` } onClick={()=>
                      setSubmenuOpen(!submenuopen) }/>

                  )}

              {item.submenu && submenuopen &&  !sidebar &&(

                  {item.submenuItems.map((submenuitem,index)=>(
                    <Link href={submenuitem.href} key={submenuitem.title} >
                    <li key={item.name} className={`flex items-center gap-x-4 mb-2 cursor-pointer  text-[#5F6062]  text-base px-12 ${router.pathname === submenuitem.href  && "text-[#F58426]"}` }>
                        {submenuitem.title}

                    </Link>
                  ))}

              )}
            </>

          ))}

`

Here is a screenshot of my sidebar.When I click on the loan item ,I need the loan with items toremain open

I have tried this with no avail ,`

{item.submenu && submenuopen &&  !sidebar &&(

                  {item.submenuItems.map((submenuitem,index)=>(
                    <Link href={submenuitem.href} key={submenuitem.title} >

                      setSubmenuOpen(submenuopen) }  key={item.name} className={`flex items-center gap-x-4 mb-2 cursor-pointer  text-[#5F6062]  text-base px-12 ${router.pathname === submenuitem.href  && "text-[#F58426]"}` }>
                        {submenuitem.title}

                    </Link>
                  ))}

              )}

`


问:
How to get a hierarchy list in SQL Server without NULL anchor?
I have two tables, one table is Client with ClientID and a column that indicates if it is a private person or a company and other table ClientConnection with BaseClientID and ConnectedClientID.
ConnectedClientID is a child ID of BaseClientID and I need to put it in a hierarchy list
but I cannot include clients that are private person, only companies are included.

For example, data is like this:
**Client **table

Client ID
PrivateOrCompany

123892
C

35809
P

37527
P

934507
P

934520
P

1233929
C

7827
C

905007
P

**ClientConnection **table

BaseClientID
ConnectedClientID
StartDate
EndDate

35809
123892
2009-09-09
NULL

37527
123892
2018-01-26
2021-07-21

934507
123892
2018-01-26
NULL

934520
123892
2018-01-26
NULL

1233929
123892
2018-01-26
NULL

7827
1233929
2018-01-26
NULL

905007
7827
2018-01-26
NULL

For each ConnectedClientID I need to find first hierarchical level that has PrivateOrCompany 'C'
and all levels above it that have PrivateOrCompany 'C' and that current date is lower than ISNULL(EndDate,'2099-12-31'). I don't have the highest hierarchical level for companies because each company has private person at the top level.
CREATE/INSERT script is here: (https://pastebin.com/pKMyM8hB)

```<code>CREATE TABLE Client (
    ClientID INT,
    PrivateOrCompany CHAR(1),
);
INSERT INTO ClientConnection VALUES (123892,'C');
INSERT INTO ClientConnection VALUES (35809,'P');
INSERT INTO ClientConnection VALUES (37527,'P');
INSERT INTO ClientConnection VALUES (934507,'P');
INSERT INTO ClientConnection VALUES (934520,'P');
INSERT INTO ClientConnection VALUES (1233929,'C');
INSERT INTO ClientConnection VALUES (7827,'C');
INSERT INTO ClientConnection VALUES (905007,'P');

CREATE TABLE ClientConnection (
    BaseClientID INT,
    ConnectedClientID INT,
    StartDate date NOT NULL,
    EndDate date NULL
);
INSERT INTO ClientConnection VALUES (35809,123892,2009-09-09,NULL);
INSERT INTO ClientConnection VALUES (37527,123892,2018-01-26,2021-07-21);
INSERT INTO ClientConnection VALUES (934507,123892,2018-01-26,NULL);
INSERT INTO ClientConnection VALUES (934520,123892,2018-01-26,NULL);
INSERT INTO ClientConnection VALUES (1233929,123892,2018-01-26,2021-07-21);
INSERT INTO ClientConnection VALUES (7827,1233929,2018-01-26,NULL);
INSERT INTO ClientConnection VALUES (905007,7827,2018-01-26,NULL);

</code>```

I tried to do CTE recursion but I cannot figure out how to do it without anchor, top level that has ParentID (BaseClientID) NULL.

I created a function that returns first level above and a level above it but than my procedure is slow. I was populating parent ID in a variable and after that use that variable as child id until my SELECT returned results.

Expected result from this data is:

BaseClientID
ConnectedClientID
Lvl

1233929
123892
1

7827
1233929
2

905007
7827
3

I would like levels are counted until the last ConnectedClientID has PrivateOrCompany 'C'. How is this possible to achieve? DISCLAIMER: It is a data model currently on the client database and I need to use it. I would also welcome suggestions that include creation of temp tables etc. Thank you.

Body:
I have two tables, one table is Client with ClientID and a column that indicates if it is a private person or a company and other table ClientConnection with BaseClientID and ConnectedClientID.
ConnectedClientID is a child ID of BaseClientID and I need to put it in a hierarchy list
but I cannot include clients that are private person, only companies are included.

For example, data is like this:
**Client **table

Client ID
PrivateOrCompany

123892
C

35809
P

37527
P

934507
P

934520
P

1233929
C

7827
C

905007
P

**ClientConnection **table

BaseClientID
ConnectedClientID
StartDate
EndDate

35809
123892
2009-09-09
NULL

37527
123892
2018-01-26
2021-07-21

934507
123892
2018-01-26
NULL

934520
123892
2018-01-26
NULL

1233929
123892
2018-01-26
NULL

7827
1233929
2018-01-26
NULL

905007
7827
2018-01-26
NULL

For each ConnectedClientID I need to find first hierarchical level that has PrivateOrCompany 'C'
and all levels above it that have PrivateOrCompany 'C' and that current date is lower than ISNULL(EndDate,'2099-12-31'). I don't have the highest hierarchical level for companies because each company has private person at the top level.
CREATE/INSERT script is here: (https://pastebin.com/pKMyM8hB)

CREATE TABLE Client (
    ClientID INT,
    PrivateOrCompany CHAR(1),
);
INSERT INTO ClientConnection VALUES (123892,'C');
INSERT INTO ClientConnection VALUES (35809,'P');
INSERT INTO ClientConnection VALUES (37527,'P');
INSERT INTO ClientConnection VALUES (934507,'P');
INSERT INTO ClientConnection VALUES (934520,'P');
INSERT INTO ClientConnection VALUES (1233929,'C');
INSERT INTO ClientConnection VALUES (7827,'C');
INSERT INTO ClientConnection VALUES (905007,'P');

CREATE TABLE ClientConnection (
    BaseClientID INT,
    ConnectedClientID INT,
    StartDate date NOT NULL,
    EndDate date NULL
);
INSERT INTO ClientConnection VALUES (35809,123892,2009-09-09,NULL);
INSERT INTO ClientConnection VALUES (37527,123892,2018-01-26,2021-07-21);
INSERT INTO ClientConnection VALUES (934507,123892,2018-01-26,NULL);
INSERT INTO ClientConnection VALUES (934520,123892,2018-01-26,NULL);
INSERT INTO ClientConnection VALUES (1233929,123892,2018-01-26,2021-07-21);
INSERT INTO ClientConnection VALUES (7827,1233929,2018-01-26,NULL);
INSERT INTO ClientConnection VALUES (905007,7827,2018-01-26,NULL);

I tried to do CTE recursion but I cannot figure out how to do it without anchor, top level that has ParentID (BaseClientID) NULL.

I created a function that returns first level above and a level above it but than my procedure is slow. I was populating parent ID in a variable and after that use that variable as child id until my SELECT returned results.

Expected result from this data is:

BaseClientID
ConnectedClientID
Lvl

1233929
123892
1

7827
1233929
2

905007
7827
3

I would like levels are counted until the last ConnectedClientID has PrivateOrCompany 'C'. How is this possible to achieve? DISCLAIMER: It is a data model currently on the client database and I need to use it. I would also welcome suggestions that include creation of temp tables etc. Thank you.


问:
get api returns HTML instead of JSON in MEAN app
I have following server.ts file

```<code>import 'zone.js/node';
const mongoose = require('mongoose');
const express = require('express');
const cors = require("cors");

import { APP_BASE_HREF } from '@angular/common';
import { ngExpressEngine } from '@nguniversal/express-engine';
import { existsSync } from 'fs';
import { join } from 'path';
import { AppServerModule } from './src/main.server';

const dotenv = require('dotenv');
const app = express();
dotenv.config({path: './config.env'});
const farmerRoute = require('./routes/farmerRoute');
const bodyParser = require('body-parser');

app.use(express.json());
app.use(bodyParser.json());

const db = process.env.DATABASE.replace('<PASSWORD>', process.env.DATABASE_PASSWORD);

mongoose.connect(db, {
    useNewUrlParser:true,
    useCreateIndex:true,
    useFindAndModify:false
}).then(con => {
    console.log('DB connection successful')
})

app.use('/api', farmerRoute);
const distFolder = join(process.cwd(), 'dist/farmer-world/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/main/modules/express-engine)
app.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));

app.set('view engine', 'html');
app.set('views', distFolder);

// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
app.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
});

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Accept", "application/json");
    res.header("Content-Type", "application/json");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

var options = {
    "origin": "*",
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
    "preflightContinue": false,
    "optionsSuccessStatus": 204
  }
  app.use(cors(options));

const port = process.env.port || 3000;

app.listen(port, () => {
    console.log(`app is running on ${port}`);
})
</code>```

and the having following farmerRoute file
const express = require('express');

```<code>
const farmerController = require('./../controllers/farmerController');

const router = express.Router();

router.get('/getAllFarmers', farmerController.getAllFarmers);

module.exports = router;
</code>```

and the controller file like follow

```<code>exports.getAllFarmers = async (req, res) => {
    try {
        const farmers = await Farmer.find();

        return res.status(200).json({
            status: 'success',
            data: farmers
        })
    } catch (err) {
        return res.status(400).json({
            status:'fail',
            message: err
        })
    }
}
</code>```

so now when I am calling http://localhost:3000/api/getAllFarmers itr returns a htmn instead of JSON.

Any guess why this is getting like this.

I looked for many answers but unable to find correct solution for my above problem.

Body:
I have following server.ts file

import 'zone.js/node';
const mongoose = require('mongoose');
const express = require('express');
const cors = require("cors");

import { APP_BASE_HREF } from '@angular/common';
import { ngExpressEngine } from '@nguniversal/express-engine';
import { existsSync } from 'fs';
import { join } from 'path';
import { AppServerModule } from './src/main.server';

const dotenv = require('dotenv');
const app = express();
dotenv.config({path: './config.env'});
const farmerRoute = require('./routes/farmerRoute');
const bodyParser = require('body-parser');

app.use(express.json());
app.use(bodyParser.json());

const db = process.env.DATABASE.replace('<PASSWORD>', process.env.DATABASE_PASSWORD);

mongoose.connect(db, {
    useNewUrlParser:true,
    useCreateIndex:true,
    useFindAndModify:false
}).then(con => {
    console.log('DB connection successful')
})

app.use('/api', farmerRoute);
const distFolder = join(process.cwd(), 'dist/farmer-world/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/main/modules/express-engine)
app.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));

app.set('view engine', 'html');
app.set('views', distFolder);

// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
app.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
});

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Accept", "application/json");
    res.header("Content-Type", "application/json");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

var options = {
    "origin": "*",
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
    "preflightContinue": false,
    "optionsSuccessStatus": 204
  }
  app.use(cors(options));

const port = process.env.port || 3000;

app.listen(port, () => {
    console.log(`app is running on ${port}`);
})

and the having following farmerRoute file
const express = require('express');

const farmerController = require('./../controllers/farmerController');

const router = express.Router();

router.get('/getAllFarmers', farmerController.getAllFarmers);

module.exports = router;

and the controller file like follow

exports.getAllFarmers = async (req, res) => {
    try {
        const farmers = await Farmer.find();

        return res.status(200).json({
            status: 'success',
            data: farmers
        })
    } catch (err) {
        return res.status(400).json({
            status:'fail',
            message: err
        })
    }
}

so now when I am calling http://localhost:3000/api/getAllFarmers itr returns a htmn instead of JSON.

Any guess why this is getting like this.

I looked for many answers but unable to find correct solution for my above problem.


问:
Is there a way to simply code a keypress for arrow keys rather than using my self.direction command in python?
This is what I import

from src.common import config, settings, utils
import time
import math
from src.routine.components import Command
from src.common.vkeys import press, key_down, key_up
```
<p>This is the only way im currently able to code a keystroke, as ive tried <code>press(Key.left, 1, up_time=0.05)</code>, <code>press(Key.left_aarrow, 1, up_time=0.05)</code>, etc.</p>
<p>I'm just coding a basic bot for practice as i'm new to coding atm.</p>
<p>This is the only successful way ive been able to code a keypress left or right - by requiring a self input(using <code>self.direction</code>), but id actually like to physically code one in.</p>
<pre class="lang-py prettyprint-override"><code>class Combo(Command):
    """Uses 'Hunting Decree' once."""

    def __init__(self, direction):
        super().__init__(locals())
        self.direction = settings.validate_arrows(direction)

    def main(self):
        key_down(self.direction)
        if self.direction == 'left':
#            key_up(self.direction)
            press(Key.GALE, 1, up_time=0.05)
            time.sleep(0.25)
            press(Key.STONE, 1, up_time=0.05)
            time.sleep(0.5)

        else:
#            key_up(self.direction)
            press(Key.GALE, 1, up_time=0.05)
            time.sleep(0.25)
            press(Key.STONE, 1, up_time=0.05)
            time.sleep(0.5)
        key_up(self.direction)
        time.sleep(0.25)
</code>```

Tried different forms of coding in the key presses but nothing works but the self.command

Body:
This is what I import

from src.common import config, settings, utils
import time
import math
from src.routine.components import Command
from src.common.vkeys import press, key_down, key_up

This is the only way im currently able to code a keystroke, as ive tried press(Key.left, 1, up_time=0.05), press(Key.left_aarrow, 1, up_time=0.05), etc.

I'm just coding a basic bot for practice as i'm new to coding atm.

This is the only successful way ive been able to code a keypress left or right - by requiring a self input(using self.direction), but id actually like to physically code one in.

class Combo(Command):
    """Uses 'Hunting Decree' once."""

    def __init__(self, direction):
        super().__init__(locals())
        self.direction = settings.validate_arrows(direction)

    def main(self):
        key_down(self.direction)
        if self.direction == 'left':
#            key_up(self.direction)
            press(Key.GALE, 1, up_time=0.05)
            time.sleep(0.25)
            press(Key.STONE, 1, up_time=0.05)
            time.sleep(0.5)

        else:
#            key_up(self.direction)
            press(Key.GALE, 1, up_time=0.05)
            time.sleep(0.25)
            press(Key.STONE, 1, up_time=0.05)
            time.sleep(0.5)
        key_up(self.direction)
        time.sleep(0.25)

Tried different forms of coding in the key presses but nothing works but the self.command


问:
why CNN model can't learn well the peak from data
here I have two different datasets. dataset1 is force plate data and dataset2 is plantar pressure data. dataset1 has shape (2050,2) and dataset2 has shape(2050,89). before doing the training I have normalized the data using minmaxscaler() with a scale of 0-1. after normalizing the data then I did data preprocessing for dataset2 using PCA. here I will reduce the data dimension of the plantar pressure to 12, so the current plantar pressure datashape is (2050.12).

here is my CNN model:

```<code>import math
import numpy as np
import pandas as pd
import tensorflow as tf
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler,StandardScaler, RobustScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM,Activation,Dense,BatchNormalization, LeakyReLU, Conv2D, MaxPooling1D, Conv1D, MaxPooling1D, Flatten, Dropout
from tensorflow.keras.losses import sparse_categorical_crossentropy
from tensorflow.keras.optimizers import Adam, RMSprop, SGD, Adadelta, Adagrad
from sklearn.decomposition import PCA
from sklearn.model_selection import KFold
from numpy import zeros, newaxis
from sklearn.feature_selection import mutual_info_regression
from sklearn.feature_selection import mutual_info_regression,SelectKBest
np.set_printoptions(suppress=True)
%matplotlib inline

Insole = pd.read_csv('1119_Rwalk40s2_list.txt', header=None, low_memory=False)
SIData =  np.asarray(Insole)

df = pd.read_csv('1119_Rwalk40s2.csv', low_memory=False)
columns = ['Fx','Fz']
selected_df = df[columns]
FCDatas = selected_df[:2050]

SmartInsole = np.array(SIData[:2050])
FCData = np.array(FCDatas)

scaler_x = MinMaxScaler(feature_range=(0, 1))
scaler_x.fit(SmartInsole)
xscale = scaler_x.transform(SmartInsole)

scaler_y = MinMaxScaler(feature_range=(0, 1))
scaler_y.fit(FCData)
yscale = scaler_y.transform(FCData)

SIDataPCA = xscale
pca = PCA(n_components=0.99)
pca.fit(SIDataPCA)
SIdata_pca = pca.transform(SIDataPCA)

X_train, X_test, y_train, y_test = train_test_split(SIdata_pca, yscale, test_size=0.10, random_state=2)

model = Sequential()
model.add(Conv1D(64,kernel_size=2,strides=1,padding='same',data_format='channels_last',input_shape=(X_train.shape[1],1)))
model.add(Activation('relu'))
model.add(MaxPooling1D(pool_size = 2, strides = 2))

model.add(Conv1D(32,kernel_size=2,strides=1,padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling1D(pool_size = 2, strides = 2))

model.add(Conv1D(16,kernel_size=2,strides=1,padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling1D(pool_size = 2, strides = 2))

model.add(LSTM(units=16))
model.add(Dense(16,activation='relu'))
model.add(Dense(2, activation='sigmoid'))

model.summary()

model.compile(loss='mse', optimizer=Adam(), metrics=['mse'])

history = model.fit(X_train, y_train, batch_size=64, epochs=50,
                    validation_data=(X_test, y_test), verbose=2)

model.evaluate(SIdata_pca, yscale)
ypred = model.predict(SIdata_pca)

plt.figure()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper right')
# plt.show()
plt.savefig('Loss Result.png')

x=[]
colors=['red','green','brown','teal','gray','black','maroon','orange','purple']
colors2=['green','red','orange','black','maroon','teal','blue','gray','brown']
for i in range(0,2050):
    x.append(i)
for i in range(0,2):
    plt.figure(figsize=(15,6))
    # plt.figure()
    plt.plot(x,yscale[0:2050,i], color=colors[i])
    plt.plot(x,ypred[0:2050,i], markerfacecolor='none',color=colors2[i])
    plt.title('Result for ResNet Regression')
    plt.ylabel('Y value')
    plt.xlabel('Instance')
    plt.legend(['Real value', 'Predicted Value'], loc='upper right')
    plt.savefig('Regression Result.png'[i])
    plt.show()
</code>```

below is the model loss plot

looking at the training loss model, I don't think there is any indication of overvitting in training, but why can't my model predict high peaks from train data?

prediction results:

Body:
here I have two different datasets. dataset1 is force plate data and dataset2 is plantar pressure data. dataset1 has shape (2050,2) and dataset2 has shape(2050,89). before doing the training I have normalized the data using minmaxscaler() with a scale of 0-1. after normalizing the data then I did data preprocessing for dataset2 using PCA. here I will reduce the data dimension of the plantar pressure to 12, so the current plantar pressure datashape is (2050.12).

here is my CNN model:

import math
import numpy as np
import pandas as pd
import tensorflow as tf
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler,StandardScaler, RobustScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM,Activation,Dense,BatchNormalization, LeakyReLU, Conv2D, MaxPooling1D, Conv1D, MaxPooling1D, Flatten, Dropout
from tensorflow.keras.losses import sparse_categorical_crossentropy
from tensorflow.keras.optimizers import Adam, RMSprop, SGD, Adadelta, Adagrad
from sklearn.decomposition import PCA
from sklearn.model_selection import KFold
from numpy import zeros, newaxis
from sklearn.feature_selection import mutual_info_regression
from sklearn.feature_selection import mutual_info_regression,SelectKBest
np.set_printoptions(suppress=True)
%matplotlib inline

Insole = pd.read_csv('1119_Rwalk40s2_list.txt', header=None, low_memory=False)
SIData =  np.asarray(Insole)

df = pd.read_csv('1119_Rwalk40s2.csv', low_memory=False)
columns = ['Fx','Fz']
selected_df = df[columns]
FCDatas = selected_df[:2050]

SmartInsole = np.array(SIData[:2050])
FCData = np.array(FCDatas)

scaler_x = MinMaxScaler(feature_range=(0, 1))
scaler_x.fit(SmartInsole)
xscale = scaler_x.transform(SmartInsole)

scaler_y = MinMaxScaler(feature_range=(0, 1))
scaler_y.fit(FCData)
yscale = scaler_y.transform(FCData)

SIDataPCA = xscale
pca = PCA(n_components=0.99)
pca.fit(SIDataPCA)
SIdata_pca = pca.transform(SIDataPCA)

X_train, X_test, y_train, y_test = train_test_split(SIdata_pca, yscale, test_size=0.10, random_state=2)

model = Sequential()
model.add(Conv1D(64,kernel_size=2,strides=1,padding='same',data_format='channels_last',input_shape=(X_train.shape[1],1)))
model.add(Activation('relu'))
model.add(MaxPooling1D(pool_size = 2, strides = 2))

model.add(Conv1D(32,kernel_size=2,strides=1,padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling1D(pool_size = 2, strides = 2))

model.add(Conv1D(16,kernel_size=2,strides=1,padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling1D(pool_size = 2, strides = 2))

model.add(LSTM(units=16))
model.add(Dense(16,activation='relu'))
model.add(Dense(2, activation='sigmoid'))

model.summary()

model.compile(loss='mse', optimizer=Adam(), metrics=['mse'])

history = model.fit(X_train, y_train, batch_size=64, epochs=50,
                    validation_data=(X_test, y_test), verbose=2)

model.evaluate(SIdata_pca, yscale)
ypred = model.predict(SIdata_pca)

plt.figure()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper right')
# plt.show()
plt.savefig('Loss Result.png')

x=[]
colors=['red','green','brown','teal','gray','black','maroon','orange','purple']
colors2=['green','red','orange','black','maroon','teal','blue','gray','brown']
for i in range(0,2050):
    x.append(i)
for i in range(0,2):
    plt.figure(figsize=(15,6))
    # plt.figure()
    plt.plot(x,yscale[0:2050,i], color=colors[i])
    plt.plot(x,ypred[0:2050,i], markerfacecolor='none',color=colors2[i])
    plt.title('Result for ResNet Regression')
    plt.ylabel('Y value')
    plt.xlabel('Instance')
    plt.legend(['Real value', 'Predicted Value'], loc='upper right')
    plt.savefig('Regression Result.png'[i])
    plt.show()

below is the model loss plot

looking at the training loss model, I don't think there is any indication of overvitting in training, but why can't my model predict high peaks from train data?

prediction results:


问:
Add custom JSON Body to forwarded Nginx request
I have a Service A sitting behind NGINX acting as reverse proxy (for http basic auth). The request path is:

Client > NGINX > Service A

My nginx.conf is:

```<code>events {}
http {
    server {
        listen       19202;
        server_name  localhost;

        auth_basic           "Restricted Area";
        auth_basic_user_file /tmp/htpasswd;

        location /api/v1/proxy/info {
            proxy_pass http://api:39999;
            allow all;
        }
}
</code>```

Now I would like to extend the config so whenever request to location /api/v1/proxy/info is forwarded, it should contain JSON Body (application/json MIME) that was added by NGINX (client will send bare GET request w/o any body, it will be appended by nginx).

Client (no JSON Body) > NGINX (add JSON Body) > Service A

How can I easily achieve this?

Body:
I have a Service A sitting behind NGINX acting as reverse proxy (for http basic auth). The request path is:

Client > NGINX > Service A

My nginx.conf is:

events {}
http {
    server {
        listen       19202;
        server_name  localhost;

        auth_basic           "Restricted Area";
        auth_basic_user_file /tmp/htpasswd;

        location /api/v1/proxy/info {
            proxy_pass http://api:39999;
            allow all;
        }
}

Now I would like to extend the config so whenever request to location /api/v1/proxy/info is forwarded, it should contain JSON Body (application/json MIME) that was added by NGINX (client will send bare GET request w/o any body, it will be appended by nginx).

Client (no JSON Body) > NGINX (add JSON Body) > Service A

How can I easily achieve this?


问:
Jest encountered an expected token with personal package (jest-unit)
I created a monorepo with multiple workspaces thanks to NX. In one of my package named @xxx/web-react that uses another personal package named @xxx/foundation, I try to configure jest environment with react 18, typescript 4.9.4 and @testing-library/react

I use same tsconfig for @xxx/web-react and @xxx/foundation

```<code>{
    "compilerOptions": {
        "target": "es2020",
        "module": "commonjs",
        "strict": true,
        "allowSyntheticDefaultImports": true,
        "allowJs": true,
        "esModuleInterop": true,
        "noEmit": true,
        "moduleResolution": "node",
        "skipLibCheck": true,
        "jsx": "preserve"
    },
    "include": [
        "**/*.ts",
        "**/*.tsx",
        "**/*.js",
        "**/*.jsx",
        ".jest/setupTests.ts"
    ],
    "exclude": ["node_modules", "coverage", "dist"]
}

</code>```

You will find below my jest config

```<code>import type { Config } from '@jest/types'
import path from 'path'

const config: Config.InitialOptions = {
    rootDir: path.join(__dirname, '..'),
    testEnvironment: 'jsdom',
    collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}', '!src/**/__stories__/**/*.{js,ts,tsx,mdx}'],
    coverageReporters: ['text', 'cobertura'],
    reporters: [
        'default',
        [
            'jest-junit',
            {
                outputDirectory: '.reports',
                outputName: 'tests.xml',
            },
        ],
    ],
    testPathIgnorePatterns: ['/node_modules/(?!@xxx/)'],
    transformIgnorePatterns: ['node_modules/(?!(@xxx)/)'],
    moduleNameMapper: {
        '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
            '<rootDir>/.jest/fileMock.ts',
        '\\.(css|less)$': 'identity-obj-proxy',
    },
    setupFilesAfterEnv: ['<rootDir>/.jest/setupTests.ts'],
}

export default config

</code>```

I try to test this component that uses @xxx/foundation package

```<code>import { typography } from '@xxx/foundation'
...
const Text = ({...}: TextProps) => {

    return (
        <div ... >
            {children}
        </div>
    )
}

export default Text

</code>```

like that

```<code>import { render } from '@testing-library/react'
import Text from './../../Text'

describe('Text', () => {
    test('renders correctly with default values', () => {
        const { asFragment } = render(<Text as='p'>Example test</Text>)
        expect(asFragment()).toMatchSnapshot()
    })
})

</code>```

But i encountered this error

```<code>
Test suite failed to run

    Jest encountered an unexpected token

....

SyntaxError: /Users/xxx/monorepo/packages/foundation/src/branding.ts: Missing semicolon. (19:4)

      17 | }
      18 |
    > 19 | type Theme = typeof theme & {
         |     ^
      20 |     linkComponent?: unknown
      21 | }
      22 |
</code>```

Anyone knows what is the issue ? This config works if I don't import my personal package @xxx/foundation ?

I try to add ts-jest inside my jest config but didn't work. Maybe it's due to my tsconfig.

Body:
I created a monorepo with multiple workspaces thanks to NX. In one of my package named @xxx/web-react that uses another personal package named @xxx/foundation, I try to configure jest environment with react 18, typescript 4.9.4 and @testing-library/react

I use same tsconfig for @xxx/web-react and @xxx/foundation

{
    "compilerOptions": {
        "target": "es2020",
        "module": "commonjs",
        "strict": true,
        "allowSyntheticDefaultImports": true,
        "allowJs": true,
        "esModuleInterop": true,
        "noEmit": true,
        "moduleResolution": "node",
        "skipLibCheck": true,
        "jsx": "preserve"
    },
    "include": [
        "**/*.ts",
        "**/*.tsx",
        "**/*.js",
        "**/*.jsx",
        ".jest/setupTests.ts"
    ],
    "exclude": ["node_modules", "coverage", "dist"]
}

You will find below my jest config

import type { Config } from '@jest/types'
import path from 'path'

const config: Config.InitialOptions = {
    rootDir: path.join(__dirname, '..'),
    testEnvironment: 'jsdom',
    collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}', '!src/**/__stories__/**/*.{js,ts,tsx,mdx}'],
    coverageReporters: ['text', 'cobertura'],
    reporters: [
        'default',
        [
            'jest-junit',
            {
                outputDirectory: '.reports',
                outputName: 'tests.xml',
            },
        ],
    ],
    testPathIgnorePatterns: ['/node_modules/(?!@xxx/)'],
    transformIgnorePatterns: ['node_modules/(?!(@xxx)/)'],
    moduleNameMapper: {
        '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
            '<rootDir>/.jest/fileMock.ts',
        '\\.(css|less)$': 'identity-obj-proxy',
    },
    setupFilesAfterEnv: ['<rootDir>/.jest/setupTests.ts'],
}

export default config

I try to test this component that uses @xxx/foundation package

import { typography } from '@xxx/foundation'
...
const Text = ({...}: TextProps) => {

    return (

            {children}

    )
}

export default Text

like that

import { render } from '@testing-library/react'
import Text from './../../Text'

describe('Text', () => {
    test('renders correctly with default values', () => {
        const { asFragment } = render(<Text as='p'>Example test</Text>)
        expect(asFragment()).toMatchSnapshot()
    })
})

But i encountered this error

Test suite failed to run

    Jest encountered an unexpected token

....

SyntaxError: /Users/xxx/monorepo/packages/foundation/src/branding.ts: Missing semicolon. (19:4)

      17 | }
      18 |
    > 19 | type Theme = typeof theme & {
         |     ^
      20 |     linkComponent?: unknown
      21 | }
      22 |

Anyone knows what is the issue ? This config works if I don't import my personal package @xxx/foundation ?

I try to add ts-jest inside my jest config but didn't work. Maybe it's due to my tsconfig.


问:
Different between Text Index and Regular Index in Mongodb
I'm wondering about the difference between Text Index and Regular Index in Mongodb. What are the specific cases where a Text Index can and a Regular Index can't?

Example: I have json with structure like this

```<code>{
"_id": {
    "$oid": "5f39f4a95224cf235e134c5c"
},
"name": [{
    "languageId": 228,
    "name": "A random sentence in language A"
}, {
    "languageId": 46,
    "name": "A random sentence in language B"
}],
"status": 1,
"updatedDate": {
    "$date": "2022-06-28T09:34:06.473Z"
},
"createdDate": {
    "$date": "2020-08-26T08:04:38.000Z"
}
</code>```

}

This is my query generate by spring data mongodb:

```<code>{ "name.name" : { "$regularExpression" : { "pattern" : "string input", "options" : "i"}}}
</code>```

What cases in language A can be found but not in language B when using TextIndex instead of Regular Index? Sorry for my bad Eng!

Thank you!

Body:
I'm wondering about the difference between Text Index and Regular Index in Mongodb. What are the specific cases where a Text Index can and a Regular Index can't?

Example: I have json with structure like this

{
"_id": {
    "$oid": "5f39f4a95224cf235e134c5c"
},
"name": [{
    "languageId": 228,
    "name": "A random sentence in language A"
}, {
    "languageId": 46,
    "name": "A random sentence in language B"
}],
"status": 1,
"updatedDate": {
    "$date": "2022-06-28T09:34:06.473Z"
},
"createdDate": {
    "$date": "2020-08-26T08:04:38.000Z"
}

}

This is my query generate by spring data mongodb:

{ "name.name" : { "$regularExpression" : { "pattern" : "string input", "options" : "i"}}}

What cases in language A can be found but not in language B when using TextIndex instead of Regular Index? Sorry for my bad Eng!

Thank you!


问:
How to solve the firebase storage error in flutter Code?
While Uploading  product to the firebase to firebase database and storage by using the flutter code error caught of TypeError :cannot read properties of undefined(reading 'storage')

```<code>                                 CO
</code>```

``'void _uploadForm() async {
final isValid = _formKey.currentState!.validate();
FocusScope.of(context).unfocus();

```<code>if (isValid) {
  _formKey.currentState!.save();

  // THis use for the image session is necessary for the Prodcut upload
  if (_pickedImage == null) {
    GlobalMethods.ErrorDialog(
        subtitle: "Please pickup the product image!!", context: context);
    return;
  }
  final _uuid = const Uuid().v4();
  try {
    setState(() {
      _isLoading = true;
    });
    fb.StorageReference storageRef =
        fb.storage().ref().child('productsImages').child(_uuid + 'jpg');
    final fb.UploadTaskSnapshot uploadTaskSnapshot =
        await storageRef.put(kIsWeb ? webImage : _pickedImage).future;
    Uri imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
    await FirebaseFirestore.instance.collection('products').doc(_uuid).set({
      // this Part is use for the Database attributes.

      "id": _uuid,
      'title': _titleController.text,
      'price': _priceController.text, //Major changes
      'salePrice': 0.1,
      'imageAsset': imageUri.toString(),
      'productCategroyName': _catValue,
      'isOnSale': false,
      'isPiece': isPiece,
      'createdAt': Timestamp.now(),
    });
    _clearForm();
    Fluttertoast.showToast(
      msg: "Product uploaded succefully",
      toastLength: Toast.LENGTH_LONG,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1,
    );
    //print("Successfully Registered , Bro!!!!");
    // Navigator.of(context).pushReplacement(MaterialPageRoute(
    //   builder: (context) => const BottomBarScreen(),
    // ));
  } on FirebaseException catch (error) {
    GlobalMethods.ErrorDialog(
        subtitle: "${error.message}", context: context);
    //print("Hey Man you Got the Error Resolve it,Try Again$error");
    setState(() {
      _isLoading = false;
    });
  } catch (error) {
    GlobalMethods.ErrorDialog(subtitle: "$error", context: context);
    //print("Hey Man you Got the Error Resolve it,Try Again$error");
    setState(() {
      _isLoading = false;
    });
  } finally {
    setState(() {
      _isLoading = false;
    });
  }
}
</code>```

}

```<code>`

\[enter image [enter image description here](https://i.stack.imgur.com/kW5b7.png)description here\](https://i.stack.imgur.com/1SkoD.png)
</code>```

Body:
While Uploading  product to the firebase to firebase database and storage by using the flutter code error caught of TypeError :cannot read properties of undefined(reading 'storage')

                                 CO

``'void _uploadForm() async {
final isValid = _formKey.currentState!.validate();
FocusScope.of(context).unfocus();

if (isValid) {
  _formKey.currentState!.save();

  // THis use for the image session is necessary for the Prodcut upload
  if (_pickedImage == null) {
    GlobalMethods.ErrorDialog(
        subtitle: "Please pickup the product image!!", context: context);
    return;
  }
  final _uuid = const Uuid().v4();
  try {
    setState(() {
      _isLoading = true;
    });
    fb.StorageReference storageRef =
        fb.storage().ref().child('productsImages').child(_uuid + 'jpg');
    final fb.UploadTaskSnapshot uploadTaskSnapshot =
        await storageRef.put(kIsWeb ? webImage : _pickedImage).future;
    Uri imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
    await FirebaseFirestore.instance.collection('products').doc(_uuid).set({
      // this Part is use for the Database attributes.

      "id": _uuid,
      'title': _titleController.text,
      'price': _priceController.text, //Major changes
      'salePrice': 0.1,
      'imageAsset': imageUri.toString(),
      'productCategroyName': _catValue,
      'isOnSale': false,
      'isPiece': isPiece,
      'createdAt': Timestamp.now(),
    });
    _clearForm();
    Fluttertoast.showToast(
      msg: "Product uploaded succefully",
      toastLength: Toast.LENGTH_LONG,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1,
    );
    //print("Successfully Registered , Bro!!!!");
    // Navigator.of(context).pushReplacement(MaterialPageRoute(
    //   builder: (context) => const BottomBarScreen(),
    // ));
  } on FirebaseException catch (error) {
    GlobalMethods.ErrorDialog(
        subtitle: "${error.message}", context: context);
    //print("Hey Man you Got the Error Resolve it,Try Again$error");
    setState(() {
      _isLoading = false;
    });
  } catch (error) {
    GlobalMethods.ErrorDialog(subtitle: "$error", context: context);
    //print("Hey Man you Got the Error Resolve it,Try Again$error");
    setState(() {
      _isLoading = false;
    });
  } finally {
    setState(() {
      _isLoading = false;
    });
  }
}

}

`

\[enter image [enter image description here](https://i.stack.imgur.com/kW5b7.png)description here\](https://i.stack.imgur.com/1SkoD.png)


问:
TYPO3: webp images are converted to png
I'm using a webp image in a default image content element.
webp images are enabled:

```<code>$GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] .= ',webp';
</code>```

But in frontend, a png is rendered, instead of a webp, when it's processed by TYPO3/ImageMagick/GraphicsMagick.
When explicitly saying webp should be generated, it works as expected:

```<code><f:image image="{file}" fileExtension="webp" />
</code>```

How to configure TYPO3 or ImageMagick/GraphicsMagick to not convert it to webp automatically?

Title: TYPO3: webp images are converted to png

Body:
I'm using a webp image in a default image content element.
webp images are enabled:

$GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] .= ',webp';

But in frontend, a png is rendered, instead of a webp, when it's processed by TYPO3/ImageMagick/GraphicsMagick.
When explicitly saying webp should be generated, it works as expected:

<f:image image="{file}" fileExtension="webp" />

How to configure TYPO3 or ImageMagick/GraphicsMagick to not convert it to webp automatically?


问:
access camera on Android simulator using Flutter
Using Flutter, I want to preview Camera in my Android Simulator.

I have set up as follows:

Plug my physical webcam, and test that Webcam works well.

set Camera = Webcam0 in AVD

My simulation device is Pixel 5 and Pixel2.

I have used the following code,

```<code>import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';

List<CameraDescription>? cameras;
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  cameras = await availableCameras();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  CameraController? controller;
  String imagePath = "";
  @override
  void initState() {
    super.initState();
    controller = CameraController(cameras![0], ResolutionPreset.max);
    debugPrint("Camera");
    debugPrint(cameras![0].name);
    controller?.initialize().then((_) {
      if (!mounted) {
        return Container(
          margin: const EdgeInsets.all(10.0),
          color: Colors.amber[600],
          width: 48.0,
          height: 48.0,
        );
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!controller!.value.isInitialized) {
      return Container(
        margin: const EdgeInsets.all(10.0),
        color: Colors.amber[600],
        width: 48.0,
        height: 48.0,
      );
    }
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: Column(
            children: [
              SizedBox(
                height: 50,
              ),
              Container(
                width: 200,
                height: 200,
                child: AspectRatio(
                  aspectRatio: controller!.value.aspectRatio,
                  child: CameraPreview(controller!),
                ),
              ),
              TextButton(
                  onPressed: () async {
                    try {
                      final image = await controller!.takePicture();
                      setState(() {
                        imagePath = image.path;
                      });
                    } catch (e) {
                      print(e);
                    }
                  },
                  child: Text("Take Photo")),
              if (imagePath != "")
                Container(
                    width: 300,
                    height: 300,
                    child: Image.file(
                      File(imagePath),
                    ))
            ],
          ),
        ),
      ),
    );
  }
}

</code>```

but it displays only yellow images like

My dependencies as follows:

```<code>dependencies:
  flutter:
    sdk: flutter
  camera: ^0.9.4+18
  path_provider: ^2.0.9
  path: ^1.8.0
</code>```

Where I am wrong? Any hints would help me a lot.

Body:
Using Flutter, I want to preview Camera in my Android Simulator.

I have set up as follows:

Plug my physical webcam, and test that Webcam works well.

set Camera = Webcam0 in AVD

My simulation device is Pixel 5 and Pixel2.

I have used the following code,

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';

List<CameraDescription>? cameras;
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  cameras = await availableCameras();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  CameraController? controller;
  String imagePath = "";
  @override
  void initState() {
    super.initState();
    controller = CameraController(cameras![0], ResolutionPreset.max);
    debugPrint("Camera");
    debugPrint(cameras![0].name);
    controller?.initialize().then((_) {
      if (!mounted) {
        return Container(
          margin: const EdgeInsets.all(10.0),
          color: Colors.amber[600],
          width: 48.0,
          height: 48.0,
        );
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!controller!.value.isInitialized) {
      return Container(
        margin: const EdgeInsets.all(10.0),
        color: Colors.amber[600],
        width: 48.0,
        height: 48.0,
      );
    }
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: Column(
            children: [
              SizedBox(
                height: 50,
              ),
              Container(
                width: 200,
                height: 200,
                child: AspectRatio(
                  aspectRatio: controller!.value.aspectRatio,
                  child: CameraPreview(controller!),
                ),
              ),
              TextButton(
                  onPressed: () async {
                    try {
                      final image = await controller!.takePicture();
                      setState(() {
                        imagePath = image.path;
                      });
                    } catch (e) {
                      print(e);
                    }
                  },
                  child: Text("Take Photo")),
              if (imagePath != "")
                Container(
                    width: 300,
                    height: 300,
                    child: Image.file(
                      File(imagePath),
                    ))
            ],
          ),
        ),
      ),
    );
  }
}

but it displays only yellow images like

My dependencies as follows:

dependencies:
  flutter:
    sdk: flutter
  camera: ^0.9.4+18
  path_provider: ^2.0.9
  path: ^1.8.0

Where I am wrong? Any hints would help me a lot.