问:
MVC Json controller returning full page when called from different project in different sub domain?
I have my MVC project running under a sub domain, say json.mysite.com and my controller being something similar to

```<code>/// assume this method is in some controller - MyJsonController.cs
public JsonResult GetStoreDetails(int storeId)
{
    .....
    return Json(MyStatisticsObject, JsonRequestBehavior.AllowGet);
}
</code>```

This works fine, only as long as I load any page from the same sub domain json.mysite.local. All I need to do is

```<code>    $.ajax({
    url: "/MyJson/GetStoreDetails?storeId=18"
    success: function (result) {
    ...
    }
});
</code>```

say, in firebug and I can see the json returned beautifully.

Now, I go back to my main asp.net project that runs on different subdomain (technically, they are completely different projects), I am doing this to grab json off my json domain

```<code>try
{
    string jsonUrl = string.format("http://json.mysite.local/MyJson/GetStoreDetails?storeId={0}", SelectedStore.Id);

    WebRequest requestObj = WebRequest.Create(jsonUrl);
    requestObj.Method = "GET"; //this did not do anything
    WebResponse responseObj = requestObj.GetResponse();

    string json;
    using (StreamReader objStreamReader = new StreamReader(responseObj.GetResponseStream()))
    {
        json = objStreamReader.ReadToEnd();
    }

    JavaScriptSerializer jss = new JavaScriptSerializer();
    DataTransfer.MyStoreStats storeStats = jss.Deserialize<DataTransfer.MyStoreStats>(json); //this line ALWAYS throws exception
}
catch (Exception ex)
{
    Log.Fatal("storeId: " + SelectedStore.Id, ex);
    base.RaiseError(ErrorCode._500);
}
</code>```

I always get an exception. If I inspect the json string, I always have a whole lotta full document from  to closing tag, and I don't even have a view to this controller.

I tried several things like changing post type etc but nothing seems to be working.
What needs to be done if I need to get just my json here please?

Thanks much.

ContentLicense: CC BY-SA 3.0

Body:
I have my MVC project running under a sub domain, say json.mysite.com and my controller being something similar to

/// assume this method is in some controller - MyJsonController.cs
public JsonResult GetStoreDetails(int storeId)
{
    .....
    return Json(MyStatisticsObject, JsonRequestBehavior.AllowGet);
}

This works fine, only as long as I load any page from the same sub domain json.mysite.local. All I need to do is

    $.ajax({
    url: "/MyJson/GetStoreDetails?storeId=18"
    success: function (result) {
    ...
    }
});

say, in firebug and I can see the json returned beautifully.

Now, I go back to my main asp.net project that runs on different subdomain (technically, they are completely different projects), I am doing this to grab json off my json domain

try
{
    string jsonUrl = string.format("http://json.mysite.local/MyJson/GetStoreDetails?storeId={0}", SelectedStore.Id);

    WebRequest requestObj = WebRequest.Create(jsonUrl);
    requestObj.Method = "GET"; //this did not do anything
    WebResponse responseObj = requestObj.GetResponse();

    string json;
    using (StreamReader objStreamReader = new StreamReader(responseObj.GetResponseStream()))
    {
        json = objStreamReader.ReadToEnd();
    }

    JavaScriptSerializer jss = new JavaScriptSerializer();
    DataTransfer.MyStoreStats storeStats = jss.Deserialize<DataTransfer.MyStoreStats>(json); //this line ALWAYS throws exception
}
catch (Exception ex)
{
    Log.Fatal("storeId: " + SelectedStore.Id, ex);
    base.RaiseError(ErrorCode._500);
}

I always get an exception. If I inspect the json string, I always have a whole lotta full document from  to closing tag, and I don't even have a view to this controller.

I tried several things like changing post type etc but nothing seems to be working.
What needs to be done if I need to get just my json here please?

Thanks much.


来源: stackexchange

问:
Plotting data in nested for loop and function and then combine all the plots in one plot
I am trying to plot a simple nested function and mwe goes like this: In the end I get just an empty plot</p>
```<code>import matplotlib.pyplot as plt
k = 1.38e-23;
h = 6.6e-34;
T = 7;
Temp = np.array([7, 0.268, 0.02025])
Freq = np.arange(1, 10, 2)
for T in Temp:
    for f in Freq:
        def quanta(f,T):
             return (f*T)
        final = quanta(f,T)
        plt.plot(f, final)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to plot a simple nested function and mwe goes like this: In the end I get just an empty plot

import matplotlib.pyplot as plt
k = 1.38e-23;
h = 6.6e-34;
T = 7;
Temp = np.array([7, 0.268, 0.02025])
Freq = np.arange(1, 10, 2)
for T in Temp:
    for f in Freq:
        def quanta(f,T):
             return (f*T)
        final = quanta(f,T)
        plt.plot(f, final)


问:
Visual studio 2022, Press '(' on selected text not working (as expected)
I don't know how to describe this behaivor:

Press ( key on selected text in vs2022, what i want is to replace the whole selection with (, but it does not, even worse, what it does is to add another ) to the end of the selection, this is really annoying and happened many times. i tried to find options in Tools/Options, twice, and nothing found to disable it.

(actualy, it happens to all marching symbols like "(<{, so i guess it's something to do with the brace marching thing.)

Please help, thank you.


问:
How to remove boxes around shx text without AutoCAD?
I try to use OCR (Optical Character Reader) for a lot of documents of the same type. I use pdf2image library for Python. But when it sees pdfs with AutoCAD shx text it captures the bounding boxes around text as well. At first they are not visible on pdf. You need to click on text to see the boxes. But they appear in jpg result after conversion.

Here's an image of a part of pdf document:
crop from actual pdf

And here's the output of conversion: pdf after conversion

I expect somethink like that:
pdf after conversion how it should be

Here's my function for pdf2image conversion:

```<code>def get_image_for_blueprint(path, dpi):
    """Create image for full blueprint from path
    path: path to pdf file
    """
    from pdf2image import convert_from_bytes
    images = convert_from_bytes(open(path, 'rb').read(), dpi=dpi)  # Actual conversion function
    for i in images:
        width, height = i.size
        if width < height:
            continue
        else:
            print(i.size)  # tuple : (width, height)
            image = i.resize((4096, int(height / width * 4096)))
            enhancer = ImageEnhance.Sharpness(image)
            image = enhancer.enhance(2)  # Sharpness
            enhancer = ImageEnhance.Color(image)
            image = enhancer.enhance(0)  # black and white
            enhancer = ImageEnhance.Contrast(image)
            image = enhancer.enhance(2)  # Contrast
            image = np.asarray(image)  # array
            image = image.astype(np.uint8)
            return image
</code>```

I found solutions to be made in AutoCAD before saving the document but I can not really find a way to get rid of these boxes having pdf only.(in python or c++)

Maybe it's possible to resolve using any other programming language library or additional software.

Body:
I try to use OCR (Optical Character Reader) for a lot of documents of the same type. I use pdf2image library for Python. But when it sees pdfs with AutoCAD shx text it captures the bounding boxes around text as well. At first they are not visible on pdf. You need to click on text to see the boxes. But they appear in jpg result after conversion.

Here's an image of a part of pdf document:
crop from actual pdf

And here's the output of conversion: pdf after conversion

I expect somethink like that:
pdf after conversion how it should be

Here's my function for pdf2image conversion:

def get_image_for_blueprint(path, dpi):
    """Create image for full blueprint from path
    path: path to pdf file
    """
    from pdf2image import convert_from_bytes
    images = convert_from_bytes(open(path, 'rb').read(), dpi=dpi)  # Actual conversion function
    for i in images:
        width, height = i.size
        if width < height:
            continue
        else:
            print(i.size)  # tuple : (width, height)
            image = i.resize((4096, int(height / width * 4096)))
            enhancer = ImageEnhance.Sharpness(image)
            image = enhancer.enhance(2)  # Sharpness
            enhancer = ImageEnhance.Color(image)
            image = enhancer.enhance(0)  # black and white
            enhancer = ImageEnhance.Contrast(image)
            image = enhancer.enhance(2)  # Contrast
            image = np.asarray(image)  # array
            image = image.astype(np.uint8)
            return image

I found solutions to be made in AutoCAD before saving the document but I can not really find a way to get rid of these boxes having pdf only.(in python or c++)

Maybe it's possible to resolve using any other programming language library or additional software.


问:
Deduction guide with non-type template parameter
In this simplified example, how can I achieve this kind of deduction guide ?</p>
```<code>template<bool even>
struct Num {
    const int i;
};

template<int i>
Num(int) -> Num<i%2>; // Num(2) -> Num<true> ;; Num(3) -> Num<false>

int main() {
    const Num a{3};
}
</code>```

Body:
In this simplified example, how can I achieve this kind of deduction guide ?

template<bool even>
struct Num {
    const int i;
};

template<int i>
Num(int) -> Num; // Num(2) -> Num<true> ;; Num(3) -> Num<false>

int main() {
    const Num a{3};
}


问:
Unnecessary menu items in edit cell NatTable
When a cell is in edit mode, and I right click on that cell then I get few menu items which feel unnecessary.

The menu items as shown in the image:

Let me know if there is a way to remove those menu items.


问:
I am trying to install the react cogo toast but after i use the command npm install --save cogo-toast All i can see in my console is:
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: react-bootstrap@0.1.0
npm ERR! Found: react@18.2.0
npm ERR! node_modules/react
npm ERR!   react@"^18.2.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0" from cogo-toast@4.2.3
npm ERR! node_modules/cogo-toast
npm ERR!   cogo-toast@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\JHONY\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!

C:\Users\JHONY\AppData\Local\npm-cache_logs\2022-12-22T10_57_19_718Z-debug-0.log

```<code>0 verbose cli C:\Program Files\nodejs\node.exe C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js
1 info using npm@8.11.0
2 info using node@v16.16.0
3 timing npm:load:whichnode Completed in 0ms
4 timing config:load:defaults Completed in 1ms
5 timing config:load:file:C:\Program Files\nodejs\node_modules\npm\npmrc Completed in 4ms
6 timing config:load:builtin Completed in 4ms
7 timing config:load:cli Completed in 2ms
8 timing config:load:env Completed in 0ms
9 timing config:load:file:F:\Course\Ostad\Practice\React\react-bootstrap\.npmrc Completed in 0ms
10 timing config:load:project Completed in 4ms
11 timing config:load:file:C:\Users\JHONY\.npmrc Completed in 1ms
12 timing config:load:user Completed in 1ms
13 timing config:load:file:C:\Users\JHONY\AppData\Roaming\npm\etc\npmrc Completed in 0ms
14 timing config:load:global Completed in 0ms
15 timing config:load:validate Completed in 0ms
16 timing config:load:credentials Completed in 1ms
17 timing config:load:setEnvs Completed in 1ms
18 timing config:load Completed in 14ms
19 timing npm:load:configload Completed in 14ms
20 timing npm:load:mkdirpcache Completed in 1ms
21 timing npm:load:mkdirplogs Completed in 0ms
22 verbose title npm install cogo-toast
23 verbose argv "install" "--save" "cogo-toast"
24 timing npm:load:setTitle Completed in 2ms
25 timing config:load:flatten Completed in 2ms
26 timing npm:load:display Completed in 3ms
27 verbose logfile logs-max:10 dir:C:\Users\JHONY\AppData\Local\npm-cache\_logs
28 verbose logfile C:\Users\JHONY\AppData\Local\npm-cache\_logs\2022-12-22T10_52_18_092Z-debug-0.log
29 timing npm:load:logFile Completed in 5ms
30 timing npm:load:timers Completed in 0ms
31 timing npm:load:configScope Completed in 0ms
32 timing npm:load Completed in 25ms
33 timing arborist:ctor Completed in 0ms
34 silly logfile start cleaning logs, removing 2 files
35 silly logfile done cleaning log files
36 timing idealTree:init Completed in 706ms
37 timing idealTree:userRequests Completed in 4ms
38 silly idealTree buildDeps
39 silly fetch manifest cogo-toast@*
40 timing arborist:ctor Completed in 0ms
41 http fetch GET 200 https://registry.npmjs.org/cogo-toast 625ms (cache hit)
42 silly fetch manifest prop-types@^15.6.2
43 http fetch GET 200 https://registry.npmjs.org/prop-types 6ms (cache hit)
44 silly fetch manifest react@^18.2.0
45 http fetch GET 200 https://registry.npmjs.org/react 7ms (cache hit)
46 silly fetch manifest react@^16.8.0
47 timing idealTree Completed in 1370ms
48 timing command:install Completed in 1381ms
49 verbose stack Error: unable to resolve dependency tree
49 verbose stack     at Arborist.[failPeerConflict] (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:1428:25)
49 verbose stack     at Arborist.[loadPeerSet] (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:1394:34)
49 verbose stack     at async Arborist.[buildDepStep] (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:976:11)
49 verbose stack     at async Arborist.buildIdealTree (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:218:7)
49 verbose stack     at async Promise.all (index 1)
49 verbose stack     at async Arborist.reify (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\reify.js:153:5)
49 verbose stack     at async Install.exec (C:\Program Files\nodejs\node_modules\npm\lib\commands\install.js:156:5)
49 verbose stack     at async module.exports (C:\Program Files\nodejs\node_modules\npm\lib\cli.js:78:5)
50 verbose cwd F:\Course\Ostad\Practice\React\react-bootstrap
51 verbose Windows_NT 10.0.22621
52 verbose node v16.16.0
53 verbose npm  v8.11.0
54 error code ERESOLVE
55 error ERESOLVE unable to resolve dependency tree
56 error
57 error While resolving: [1mreact-bootstrap[22m@[1m0.1.0[22m
57 error Found: [1mreact[22m@[1m18.2.0[22m[2m[22m
57 error [2mnode_modules/react[22m
57 error   [1mreact[22m@"[1m^18.2.0[22m" from the root project
57 error
57 error Could not resolve dependency:
57 error [35mpeer[39m [1mreact[22m@"[1m^16.8.0[22m" from [1mcogo-toast[22m@[1m4.2.3[22m[2m[22m
57 error [2mnode_modules/cogo-toast[22m
57 error   [1mcogo-toast[22m@"[1m*[22m" from the root project
57 error
57 error Fix the upstream dependency conflict, or retry
57 error this command with --force, or --legacy-peer-deps
57 error to accept an incorrect (and potentially broken) dependency resolution.
57 error
57 error See C:\Users\JHONY\AppData\Local\npm-cache\eresolve-report.txt for a full report.
58 verbose exit 1
59 timing npm Completed in 1501ms
60 verbose unfinished npm timer reify 1671706338204
61 verbose unfinished npm timer reify:loadTrees 1671706338212
62 verbose unfinished npm timer idealTree:buildDeps 1671706338923
63 verbose unfinished npm timer idealTree:#root 1671706338923
64 verbose code 1
65 error A complete log of this run can be found in:
65 error     C:\Users\JHONY\AppData\Local\npm-cache\_logs\2022-12-22T10_52_18_092Z-debug-0.log
</code>```

How to fixed this issue ?

Body:
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: react-bootstrap@0.1.0
npm ERR! Found: react@18.2.0
npm ERR! node_modules/react
npm ERR!   react@"^18.2.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0" from cogo-toast@4.2.3
npm ERR! node_modules/cogo-toast
npm ERR!   cogo-toast@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\JHONY\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!

C:\Users\JHONY\AppData\Local\npm-cache_logs\2022-12-22T10_57_19_718Z-debug-0.log

0 verbose cli C:\Program Files\nodejs\node.exe C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js
1 info using npm@8.11.0
2 info using node@v16.16.0
3 timing npm:load:whichnode Completed in 0ms
4 timing config:load:defaults Completed in 1ms
5 timing config:load:file:C:\Program Files\nodejs\node_modules\npm\npmrc Completed in 4ms
6 timing config:load:builtin Completed in 4ms
7 timing config:load:cli Completed in 2ms
8 timing config:load:env Completed in 0ms
9 timing config:load:file:F:\Course\Ostad\Practice\React\react-bootstrap\.npmrc Completed in 0ms
10 timing config:load:project Completed in 4ms
11 timing config:load:file:C:\Users\JHONY\.npmrc Completed in 1ms
12 timing config:load:user Completed in 1ms
13 timing config:load:file:C:\Users\JHONY\AppData\Roaming\npm\etc\npmrc Completed in 0ms
14 timing config:load:global Completed in 0ms
15 timing config:load:validate Completed in 0ms
16 timing config:load:credentials Completed in 1ms
17 timing config:load:setEnvs Completed in 1ms
18 timing config:load Completed in 14ms
19 timing npm:load:configload Completed in 14ms
20 timing npm:load:mkdirpcache Completed in 1ms
21 timing npm:load:mkdirplogs Completed in 0ms
22 verbose title npm install cogo-toast
23 verbose argv "install" "--save" "cogo-toast"
24 timing npm:load:setTitle Completed in 2ms
25 timing config:load:flatten Completed in 2ms
26 timing npm:load:display Completed in 3ms
27 verbose logfile logs-max:10 dir:C:\Users\JHONY\AppData\Local\npm-cache\_logs
28 verbose logfile C:\Users\JHONY\AppData\Local\npm-cache\_logs\2022-12-22T10_52_18_092Z-debug-0.log
29 timing npm:load:logFile Completed in 5ms
30 timing npm:load:timers Completed in 0ms
31 timing npm:load:configScope Completed in 0ms
32 timing npm:load Completed in 25ms
33 timing arborist:ctor Completed in 0ms
34 silly logfile start cleaning logs, removing 2 files
35 silly logfile done cleaning log files
36 timing idealTree:init Completed in 706ms
37 timing idealTree:userRequests Completed in 4ms
38 silly idealTree buildDeps
39 silly fetch manifest cogo-toast@*
40 timing arborist:ctor Completed in 0ms
41 http fetch GET 200 https://registry.npmjs.org/cogo-toast 625ms (cache hit)
42 silly fetch manifest prop-types@^15.6.2
43 http fetch GET 200 https://registry.npmjs.org/prop-types 6ms (cache hit)
44 silly fetch manifest react@^18.2.0
45 http fetch GET 200 https://registry.npmjs.org/react 7ms (cache hit)
46 silly fetch manifest react@^16.8.0
47 timing idealTree Completed in 1370ms
48 timing command:install Completed in 1381ms
49 verbose stack Error: unable to resolve dependency tree
49 verbose stack     at Arborist.[failPeerConflict] (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:1428:25)
49 verbose stack     at Arborist.[loadPeerSet] (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:1394:34)
49 verbose stack     at async Arborist.[buildDepStep] (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:976:11)
49 verbose stack     at async Arborist.buildIdealTree (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\build-ideal-tree.js:218:7)
49 verbose stack     at async Promise.all (index 1)
49 verbose stack     at async Arborist.reify (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\reify.js:153:5)
49 verbose stack     at async Install.exec (C:\Program Files\nodejs\node_modules\npm\lib\commands\install.js:156:5)
49 verbose stack     at async module.exports (C:\Program Files\nodejs\node_modules\npm\lib\cli.js:78:5)
50 verbose cwd F:\Course\Ostad\Practice\React\react-bootstrap
51 verbose Windows_NT 10.0.22621
52 verbose node v16.16.0
53 verbose npm  v8.11.0
54 error code ERESOLVE
55 error ERESOLVE unable to resolve dependency tree
56 error
57 error While resolving: [1mreact-bootstrap[22m@[1m0.1.0[22m
57 error Found: [1mreact[22m@[1m18.2.0[22m[2m[22m
57 error [2mnode_modules/react[22m
57 error   [1mreact[22m@"[1m^18.2.0[22m" from the root project
57 error
57 error Could not resolve dependency:
57 error [35mpeer[39m [1mreact[22m@"[1m^16.8.0[22m" from [1mcogo-toast[22m@[1m4.2.3[22m[2m[22m
57 error [2mnode_modules/cogo-toast[22m
57 error   [1mcogo-toast[22m@"[1m*[22m" from the root project
57 error
57 error Fix the upstream dependency conflict, or retry
57 error this command with --force, or --legacy-peer-deps
57 error to accept an incorrect (and potentially broken) dependency resolution.
57 error
57 error See C:\Users\JHONY\AppData\Local\npm-cache\eresolve-report.txt for a full report.
58 verbose exit 1
59 timing npm Completed in 1501ms
60 verbose unfinished npm timer reify 1671706338204
61 verbose unfinished npm timer reify:loadTrees 1671706338212
62 verbose unfinished npm timer idealTree:buildDeps 1671706338923
63 verbose unfinished npm timer idealTree:#root 1671706338923
64 verbose code 1
65 error A complete log of this run can be found in:
65 error     C:\Users\JHONY\AppData\Local\npm-cache\_logs\2022-12-22T10_52_18_092Z-debug-0.log

How to fixed this issue ?


问:
imx8mplus dev board yocto image psplash shows dual image on mipi dsi touch display
I was trying boot yocto image with custom boot logo on imx8mplus (compulab bsp) dev board with touch display interfaced via mipi dsi port, the procedure was simple, created bbappend for psplash recipe and located custom boot logo. The boot logo was coming up but it was showing double images of custom logo. The boot logo supposed to show as single image full screen on display.

The display resolution is 1280x800 .

the fbset output of target board is

```<code>
mode "720x600-0"
    # D: 0.000 MHz, H: 0.000 kHz, V: 0.000 Hz
    geometry 720 600 1024 1200 32
    timings 0 0 0 0 0 0 0
    accel true
    rgba 8/16,8/8,8/0,0/0
endmode

</code>```

My Finding:
The display resolution and fbset mode values are different.

How can I change display resolution atleast for psplash while compiling yocto ?

Display Psplash Image

Tried to boot custom logo with help of psplash on yocto. But the psplash boot logo displayed as two while booting up. boot logo double issue

Body:
I was trying boot yocto image with custom boot logo on imx8mplus (compulab bsp) dev board with touch display interfaced via mipi dsi port, the procedure was simple, created bbappend for psplash recipe and located custom boot logo. The boot logo was coming up but it was showing double images of custom logo. The boot logo supposed to show as single image full screen on display.

The display resolution is 1280x800 .

the fbset output of target board is

mode "720x600-0"
    # D: 0.000 MHz, H: 0.000 kHz, V: 0.000 Hz
    geometry 720 600 1024 1200 32
    timings 0 0 0 0 0 0 0
    accel true
    rgba 8/16,8/8,8/0,0/0
endmode

My Finding:
The display resolution and fbset mode values are different.

How can I change display resolution atleast for psplash while compiling yocto ?

Display Psplash Image

Tried to boot custom logo with help of psplash on yocto. But the psplash boot logo displayed as two while booting up. boot logo double issue


问:
How to get Latitude and Logitude in RecyclerView Kotlin Android
I try to get latitude and Longitude in Recyclerview.In Main Activity I get permission for Access Location. In Secound Activity I wrote a code for get latitude and Logitude.I need to get latitude and longitude in recycler view insted of text view ..
someone help me in this..
here is the code i have tryed it ...

SecoundActivity.kt

```<code>class SecondActivity : AppCompatActivity(), LocationListener {
    private lateinit var locationManager: LocationManager
    private lateinit var binding: ActivitySecondBinding
    private var dataAdapter: LocationAdapter? = null

    private val locationPermissionCode = 2
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySecondBinding.inflate(LayoutInflater.from(this))
        setContentView(binding.root)
        setAdapter()
        binding.btnGetLocation.setOnClickListener {
            getLocation()
        }
    }

    private fun getLocation() {
        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if ((ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        ) {
            ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                locationPermissionCode)
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5f, this)
    }

    val lstApplication: ArrayList<LocationEntity> = ArrayList()

    override fun onLocationChanged(location: Location) {
        setDataList(lstApplication)

        binding.tvLocationText.text = "Latitude: " + location.latitude + ",Longitude: " + location.longitude  +  ",altitude:"+location.altitude
    }

    private fun setDataList(lstApplication: ArrayList<LocationEntity>) {

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        if (requestCode == locationPermissionCode) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun setAdapter() {

        dataAdapter = LocationAdapter()
        binding.rvRecyclerView.apply {
            layoutManager = LinearLayoutManager(applicationContext)
            adapter = dataAdapter
        }
    }
}
</code>```

Here I want to get latitude and longitude in recyclerview items, Not in textview.

This is my recyclerview adapter. Here I just initialize latitude and longitude textview to get them in recyclerview
LocationAdapter.kt

```<code>    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val itemsViewModel = dataList[position]

        holder.tvLatitude.text = itemsViewModel.latitude.toString()
        holder.tvLongitude.text = itemsViewModel.longitude.toString()
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvLatitude: TextView = itemView.findViewById(R.id.tvLatitude)
        var tvLongitude: TextView = itemView.findViewById(R.id.tvLongitude)

    }
}
</code>```

In model class I just gave latitude and Longitude and extends double for them

Body:
I try to get latitude and Longitude in Recyclerview.In Main Activity I get permission for Access Location. In Secound Activity I wrote a code for get latitude and Logitude.I need to get latitude and longitude in recycler view insted of text view ..
someone help me in this..
here is the code i have tryed it ...

SecoundActivity.kt

class SecondActivity : AppCompatActivity(), LocationListener {
    private lateinit var locationManager: LocationManager
    private lateinit var binding: ActivitySecondBinding
    private var dataAdapter: LocationAdapter? = null

    private val locationPermissionCode = 2
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySecondBinding.inflate(LayoutInflater.from(this))
        setContentView(binding.root)
        setAdapter()
        binding.btnGetLocation.setOnClickListener {
            getLocation()
        }
    }

    private fun getLocation() {
        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if ((ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        ) {
            ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                locationPermissionCode)
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5f, this)
    }

    val lstApplication: ArrayList<LocationEntity> = ArrayList()

    override fun onLocationChanged(location: Location) {
        setDataList(lstApplication)

        binding.tvLocationText.text = "Latitude: " + location.latitude + ",Longitude: " + location.longitude  +  ",altitude:"+location.altitude
    }

    private fun setDataList(lstApplication: ArrayList<LocationEntity>) {

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        if (requestCode == locationPermissionCode) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun setAdapter() {

        dataAdapter = LocationAdapter()
        binding.rvRecyclerView.apply {
            layoutManager = LinearLayoutManager(applicationContext)
            adapter = dataAdapter
        }
    }
}

Here I want to get latitude and longitude in recyclerview items, Not in textview.

This is my recyclerview adapter. Here I just initialize latitude and longitude textview to get them in recyclerview
LocationAdapter.kt

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val itemsViewModel = dataList[position]

        holder.tvLatitude.text = itemsViewModel.latitude.toString()
        holder.tvLongitude.text = itemsViewModel.longitude.toString()
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvLatitude: TextView = itemView.findViewById(R.id.tvLatitude)
        var tvLongitude: TextView = itemView.findViewById(R.id.tvLongitude)

    }
}

In model class I just gave latitude and Longitude and extends double for them


问:
In Tkinter, is there a way to add internal padding (ipadx, ipady) to a Frame?
```<code>import tkinter as tk

root = tk.Tk()
root.geometry('500x300')

frame = tk.Frame(master=root, background='blue')
frame.pack(
    ipadx=50,
    ipady=50,
    fill='both',
    expand=True
)

button = tk.Button(master=frame, text='Button')
button.pack(
    fill='both',
    expand=True
)

root.mainloop()
</code>```

When I run the code above, I get a root window, then a frame that fills the root window entirely and has an inner padding of 50 on all sides.

Then, what I want is a button inside the frame that is centered so there is a 50 pixel gap between the button and frame on all sides.

Instead, the button fills the entire frame

Body:
import tkinter as tk

root = tk.Tk()
root.geometry('500x300')

frame = tk.Frame(master=root, background='blue')
frame.pack(
    ipadx=50,
    ipady=50,
    fill='both',
    expand=True
)

button = tk.Button(master=frame, text='Button')
button.pack(
    fill='both',
    expand=True
)

root.mainloop()

When I run the code above, I get a root window, then a frame that fills the root window entirely and has an inner padding of 50 on all sides.

Then, what I want is a button inside the frame that is centered so there is a 50 pixel gap between the button and frame on all sides.

Instead, the button fills the entire frame


问:
Does C++ ternary operator not work for initialization?
I am trying to conditionally initialize a structure but I cannot seem to find the source of the problem.

The code that I have is

```<code>struct CalculatorPair
  {
    using Calculator = std::function<std::optional<float>(Obj&, int)>;

    CalculatorPair(const Calculator & init, const Calculator & fin) : initial(init), final(fin)
    {
    }

    Calculator initial;
    Calculator final;
  };

</code>```

as a helper structure and then I want to initialize it like this

```<code>CalculatorPair calculator = getCondition() ? { computeInitialWay1, computeFinalWay1 } : { computeInitialWay2, computeFinalWay2 };
</code>```

But I keep getting messages from the compiler saying "syntax error: missing ';' before '{'" which I don't think is the problem.

Body:
I am trying to conditionally initialize a structure but I cannot seem to find the source of the problem.

The code that I have is

struct CalculatorPair
  {
    using Calculator = std::function<std::optional<float>(Obj&, int)>;

    CalculatorPair(const Calculator & init, const Calculator & fin) : initial(init), final(fin)
    {
    }

    Calculator initial;
    Calculator final;
  };

as a helper structure and then I want to initialize it like this

CalculatorPair calculator = getCondition() ? { computeInitialWay1, computeFinalWay1 } : { computeInitialWay2, computeFinalWay2 };

But I keep getting messages from the compiler saying "syntax error: missing ';' before '{'" which I don't think is the problem.


问:
model-viewer repetitions doesn't work on mobile during AR session
Whe using google model-viewer animation repetitions count is ignored on phone during AR session. However its works on desktop chrome when using webxr emulator</p>
```<code>modelViewer.play({ repetitions: 1 });
</code>```

Body:
Whe using google model-viewer animation repetitions count is ignored on phone during AR session. However its works on desktop chrome when using webxr emulator

modelViewer.play({ repetitions: 1 });


问:
Get a single document in firestore with a variable as parameter does not work
I am currently trying to get one document from my firebase/firestore. Using the following code.

```<code> const docRef = doc(firestore, 'users', "customidxyz");

      const docSnap = await getDoc(docRef);
      console.log(docSnap.data()); // => gives me excpected output
</code>```

That works as expected, but if I change the code to the following:

```<code>const docRef = doc(firestore, 'users', userData.uid);

      const docSnap = await getDoc(docRef);
      console.log(docSnap.data()); => logs undefined
</code>```

I only receive an undefined log. I checked and am very sure that the value in userData.uid is the exact same as the hardcoded value.

I hope you someone could help me.

thank you

I checked that the hardcoded value is the same one as the value in the variable.

Body:
I am currently trying to get one document from my firebase/firestore. Using the following code.

 const docRef = doc(firestore, 'users', "customidxyz");

      const docSnap = await getDoc(docRef);
      console.log(docSnap.data()); // => gives me excpected output

That works as expected, but if I change the code to the following:

const docRef = doc(firestore, 'users', userData.uid);

      const docSnap = await getDoc(docRef);
      console.log(docSnap.data()); => logs undefined

I only receive an undefined log. I checked and am very sure that the value in userData.uid is the exact same as the hardcoded value.

I hope you someone could help me.

thank you

I checked that the hardcoded value is the same one as the value in the variable.


问:
Set width of scrollbar in JS to 8px
I need to amend the following code that is detecting the scrollbar width. It is opening a fullscreen menu by applying "overflow-y:hidden" to "html" when the menu is opened. This code should add a fake scrollbar to stop the content jumping to the right. Im also using a custom scrollbar that is 8px wide, so I think I just need to amend the code below to make the fake scrollbar 8px.</p>
```<code>menuButton.addEventListener('click', () => {

   // get width before hiding scrollbar
   let oldWidth = document.documentElement.clientWidth;

   // toggle CSS class that sets overflow to hidden
   document.querySelector("html").classList.toggle("no-scroll");

   // get new width after hiding scrollbar
   let newWidth = document.documentElement.clientWidth;

   // set margin-right value equal to width of the scrollbar
   let scrollbarWidth = Math.max(0, newWidth - oldWidth);
   document.body.style.marginRight = `${scrollbarWidth}px`;
});
</code>```

Title: Set width of scrollbar in JS to 8px

Body:
I need to amend the following code that is detecting the scrollbar width. It is opening a fullscreen menu by applying "overflow-y:hidden" to "html" when the menu is opened. This code should add a fake scrollbar to stop the content jumping to the right. Im also using a custom scrollbar that is 8px wide, so I think I just need to amend the code below to make the fake scrollbar 8px.

menuButton.addEventListener('click', () => {

   // get width before hiding scrollbar
   let oldWidth = document.documentElement.clientWidth;

   // toggle CSS class that sets overflow to hidden
   document.querySelector("html").classList.toggle("no-scroll");

   // get new width after hiding scrollbar
   let newWidth = document.documentElement.clientWidth;

   // set margin-right value equal to width of the scrollbar
   let scrollbarWidth = Math.max(0, newWidth - oldWidth);
   document.body.style.marginRight = `${scrollbarWidth}px`;
});


问:
How can I set validation and default value in proto3?
I'm trying to add default value to an optional field alongside with validation, but could not find any infos in the docs for multiple conditions in a proto field.
This is the example:

```<code>optional string date = 1 [(validate.rules).string = { pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(Z|[+,-][0-9]{2}:[0-9]{2})"}];
</code>```

After this I'd like to add a [default = "0001-01-01T00:00:00Z"].

How can I perform this?

Body:
I'm trying to add default value to an optional field alongside with validation, but could not find any infos in the docs for multiple conditions in a proto field.
This is the example:

optional string date = 1 [(validate.rules).string = { pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(Z|[+,-][0-9]{2}:[0-9]{2})"}];

After this I'd like to add a [default = "0001-01-01T00:00:00Z"].

How can I perform this?


问:
How to pick records that have lower rank than a specific record in PostgreSQL?
Suppose there's a ranked comment list, and I want to implement relay-style pagination on it.

For example I have this query:

SELECT
  comment.id,
  (comment.like_count * 0.5 + comment.reply_count * 3) AS score
FROM
  comment
WHERE
  comment.is_deleted = false
ORDER BY score desc
LIMIT 10;
```

And the ranked comment IDs are in this order: [20, 1, 4, 12, 9, 5]

Now a user passes a cursor 12, and wants to query ranked comments after ID 12, in this case [9, 5]

How can I implement this in PostgreSQL?

Edit: I figured out another way to achieve this by adding a cache layer. So the implementation becomes:

Get the IDs from cache (for example Redis)

find the index of cursor in the array

If the index > -1, then slice the array

Query the database using WHERE IN

That solves my problem, but if anyone could help with the original quesion, I'd appreciate.

Body:
Suppose there's a ranked comment list, and I want to implement relay-style pagination on it.

For example I have this query:

SELECT
  comment.id,
  (comment.like_count * 0.5 + comment.reply_count * 3) AS score
FROM
  comment
WHERE
  comment.is_deleted = false
ORDER BY score desc
LIMIT 10;

And the ranked comment IDs are in this order: [20, 1, 4, 12, 9, 5]

Now a user passes a cursor 12, and wants to query ranked comments after ID 12, in this case [9, 5]

How can I implement this in PostgreSQL?

Edit: I figured out another way to achieve this by adding a cache layer. So the implementation becomes:

Get the IDs from cache (for example Redis)

find the index of cursor in the array

If the index > -1, then slice the array

Query the database using WHERE IN

That solves my problem, but if anyone could help with the original quesion, I'd appreciate.


问:
Can I use the pool connection of mysql2 outside the handler?
I use mysql2 in lambda.

pool connection is working in main handler.

but can't working pool connection in arrow function

why? I don't understand this.

my code,

```<code>const mysql = require('mysql2/promise')
const pool = mysql.createPool({
  host: SERVICE_INFO.DB_HOST,
  database: SERVICE_INFO.DB_NAME,
  user: SERVICE_INFO.DB_USERNAME,
  password: SERVICE_INFO.DB_PASSWORD,
  port: SERVICE_INFO.DB_PORT,
  connectionLimit: 20,
})

const user = async (event) => {
  // not working, pool.getConnection fail, why?
  // can't print log, fail to connection then exit function
  const connection = await pool.getConnection(async conn => conn)
  console.log('user connection : ', connection)
  const result = await connection.query(`select * from table`);
  connection.release()
}

module.exports.server_main = async (event, context, callback) => {
  // it's working
  // const connection = await pool.getConnection(async conn => conn);
  // const result = await connection.query(`select * from table`);
  //  connection.release()
  context.callbackWaitsForEmptyEventLoop = false

  const { path } = event
  let res
  switch (path) {
    case '/user':
      res = user(event)
      break
  }

</code>```

Body:
I use mysql2 in lambda.

pool connection is working in main handler.

but can't working pool connection in arrow function

why? I don't understand this.

my code,

const mysql = require('mysql2/promise')
const pool = mysql.createPool({
  host: SERVICE_INFO.DB_HOST,
  database: SERVICE_INFO.DB_NAME,
  user: SERVICE_INFO.DB_USERNAME,
  password: SERVICE_INFO.DB_PASSWORD,
  port: SERVICE_INFO.DB_PORT,
  connectionLimit: 20,
})

const user = async (event) => {
  // not working, pool.getConnection fail, why?
  // can't print log, fail to connection then exit function
  const connection = await pool.getConnection(async conn => conn)
  console.log('user connection : ', connection)
  const result = await connection.query(`select * from table`);
  connection.release()
}

module.exports.server_main = async (event, context, callback) => {
  // it's working
  // const connection = await pool.getConnection(async conn => conn);
  // const result = await connection.query(`select * from table`);
  //  connection.release()
  context.callbackWaitsForEmptyEventLoop = false

  const { path } = event
  let res
  switch (path) {
    case '/user':
      res = user(event)
      break
  }


问:
Collapse a View with a slide right/left to centre animation
I have a LinearLayout with orientation horizontal and I want to collapse all the views in linear layout with a slow Animation (1000 mili secs) that pushes the layout inward from left and right to centre.

It has 5 icon views and want to collapse to 1 icon view on any icon click. And move that selected view to centre.


问:
Override vuetify 3 breakpoints globally
I'm currently using vuetify 3 with nuxt 3 and I need to customize the grid-breakpoint globally in scss. I have tried different solutions propose in the documentations and nothing seems to work.
I followed the guide here https://next.vuetifyjs.com/en/features/sass-variables/ and it didn't work

// ./assets/styles/main.scss

```<code>@forward 'vuetify/settings' with (
$grid-breakpoints: (
  'xs': 0,
  'sm': 390px,
  'md': 768px,
  'lg': 1024px,
  'xl': 1440px,
  'xxl': 1920px,
)
);
</code>```

included it in app.vue

```<code><style lang="scss">
@use './assets/styles/main';
</style>
</code>```

my expectation was to have see the view port changes occur at those breakpoints, but the default vuetify breakpoints are still applied.

```<code><v-row>
  <v-col
    v-for="(category, index2) in section.categories"
    :key="index2"
    cols="12"
    lg="4"
  >
...
  </v-col>
</v-row>
</code>```

I expected to see 3 columns at a view width off 1025px upward, but this is the case only from  1280px

Title: Override vuetify 3 breakpoints globally

Body:
I'm currently using vuetify 3 with nuxt 3 and I need to customize the grid-breakpoint globally in scss. I have tried different solutions propose in the documentations and nothing seems to work.
I followed the guide here https://next.vuetifyjs.com/en/features/sass-variables/ and it didn't work

// ./assets/styles/main.scss

@forward 'vuetify/settings' with (
$grid-breakpoints: (
  'xs': 0,
  'sm': 390px,
  'md': 768px,
  'lg': 1024px,
  'xl': 1440px,
  'xxl': 1920px,
)
);

included it in app.vue

my expectation was to have see the view port changes occur at those breakpoints, but the default vuetify breakpoints are still applied.

<v-row>
  <v-col
    v-for="(category, index2) in section.categories"
    :key="index2"
    cols="12"
    lg="4"
  >
...
  </v-col>
</v-row>

I expected to see 3 columns at a view width off 1025px upward, but this is the case only from  1280px


问:
Why shuffle doesn't work after I added new functionality of changing a gameboard size in a slider-puzzle game?
I created a slider-puzzle game and recently decided to reafctor the code using OOP. Besides I added a new functionality, so a player can change the size of the game board (3X3, 4X4, 5X5 etc.) by pressing a sertain button. But somehow a shuffle function stopped working. If you have any ideas of what I might do wrong, I will be very grateful if you let me know.

```<code>"use strict";
///////////////////////////////////////////////////////////////////////////
// Elements
const body = document.body;
const root = document.querySelector(".root");
const buttons = document.createElement("div");
const table = document.querySelector(".table");
const timeAndMoves = document.createElement("div");
const cubeSize = 125;
let cubes = [];
let gameRoundResults = {round: [], moves: [], time: []};

let countMoves = 0;
let gameRound = 0;
let cube, timer, left, top, tr, td;
let rowColumnLength = [3, 4, 5, 6, 7, 8]; // the default size of the game board - 4 columns and 4 rows
let boardSize = [9, 16, 15, 36, 49, 64];

let cubesArray = [];

let blankSpace = document.querySelector(".blank_space");
blankSpace = {
  // blank space coords
};

// calculating coordinates of each cube and setting style
function getCoords(a, b) {
  return Math.abs(a - b);
}

function setElementStyle(a, b) {
  return `${a * b}px`;
}

// changing position of cubes
function changePosition(i) {
  let cube = cubes[i];
  const blankSpaceLeft = blankSpace.left;
  const blankSpaceTop = blankSpace.top;

  let coordsLeft = getCoords(blankSpace.left, cube.left);
  let coordsTop = getCoords(blankSpace.top, cube.top);

  if (
    (blankSpaceLeft === cube.left && blankSpaceTop === cube.top) ||
    coordsLeft + coordsTop > 1
  ) {
    return;
  } else {
    countMoves++;
    calcMoves.textContent = `Moves: ${countMoves}`;
  }

  cube.element.style.left = setElementStyle(blankSpace.left, cubeSize);
  cube.element.style.top = setElementStyle(blankSpace.top, cubeSize);

  blankSpace.top = cube.top;
  blankSpace.left = cube.left;
  cube.top = blankSpaceTop;
  cube.left = blankSpaceLeft;

  const winCondition = cubes.every(
    (cube) => cube.value - 1 === cube.top * rowColumnLength + cube.left
  );

  if (winCondition) {
    winAnnouncement();
    clearInterval(timer);
    gameRound++;
    gameRoundResults.round.push(gameRound);
    gameRoundResults.moves.push(countMoves);
    gameRoundResults.time.push(setTimer.textContent);
  }
}

// resetting the game, so after clicking on a shuffle button the original game board won't overlay newly shuffled cubes
const resetGame = () => {
  clearInterval(timer);
  setTimer.textContent = `Time: 00:00`;
  countMoves = 0;
  calcMoves.textContent = `Moves: ${countMoves}`;
  [...root.children].forEach((el) => {
    root.removeChild(el); //removing elements from the board
  });
  [...table.children].forEach((el) => {
    table.removeChild(el); //removing elements from the board
  });
  cubes.splice(0); // deleting all elements starting from index 0
  blankSpace.top = 0; // resetting coordinates
  blankSpace.left = 0;
};

// creating a timer
const setTimer = document.createElement("div");
setTimer.classList.add("timer");
setTimer.textContent = `Time: 00:00`;
body.append(setTimer);

function startTimer() {
  let sec = 0;
  let min = 0;

  timer = setInterval(() => {
    setTimer.textContent =
      "Time: " + `${min}`.padStart(2, 0) + ":" + `${sec}`.padStart(2, 0);
    sec++;

    if (sec >= 60) {
      sec = 0;
      min++;
    }
  }, 1000);
}

// creating moves counter
const calcMoves = document.createElement("div");
calcMoves.classList.add("count_moves");
calcMoves.textContent = `Moves: ${countMoves}`;
body.append(calcMoves);

////////////////////////////////////////////////////////////////////////////////////
// Creating buttons using OOP and adding event listeners to each of them

class Button {
  constructor(name, attribute, classList, textContent, value) {
    this.name = document.createElement("button");
    this.name.setAttribute("id", attribute);
    this.name.classList.add(classList);
    this.textContent = this.name.textContent = textContent;
    buttons.append(this.name);
  }

  //Methods that will be added to .prototype property
  addEventShuffle() {
    this.name.addEventListener("click", function () {
      shuffle(cubesArray);
    });
  }

  addEventStop() {
    this.name.addEventListener("click", function () {
      clearInterval(timer);
    });
  }

  addEventResult() {
    this.name.addEventListener("click", function () {
      clearInterval(timer);
      tableCreate();
      showResults();
    });
  }

  clickOnlyOnce() {
    this.name.addEventListener("click", function () {
      this.disabled = "disabled";
    });
  }

  clickOnlyOnceDisabled() {
    this.name.removeAttribute("disabled");
  }

  renderCubesNumber(number){
    this.name.addEventListener("click", function () {
      cubesArray.push(...Array(boardSize[number]).keys());
      setPosition(boardSize = boardSize[number], rowColumnLength = rowColumnLength[number]);
      console.log(cubesArray);
    });
  }
}

const shuffleButton = new Button(
  "shuffleButton",
  "button",
  "shuffleButton",
  "SHUFFLE"
);
const stopButton = new Button("stopButton", "button", "stopButton", "STOP");
const saveButton = new Button("saveButton", "button", "saveButton", "SAVE");
const resultsButton = new Button( "resultsButton", "button", "resultsButton", "RESULT");

shuffleButton.addEventShuffle();
stopButton.addEventStop();
resultsButton.addEventResult();
resultsButton.clickOnlyOnce();

// Creating size buttons
for(let i = 3; i <= 8; i++){
new Button("rowsCols", "button", "row_col_length", `${i}X${i}`).renderCubesNumber(i - 3);
}

// implementing shuffle functionality

function shuffle(cubesArray) {
  for (let i = cubesArray.length - 1; i > 0; i--) {
    resetGame(); // deleting original game board
    setPosition(cubesArray); // creating a new shuffled game board
    startTimer();

    let j = Math.floor(Math.random() * (i + 1));

    [cubesArray[i], cubesArray[j]] = [cubesArray[j], cubesArray[i]];

    // [cubesArray[i], cubesArray[newPos]] = [cubesArray[newPos], cubesArray[i]]; //swapping original and randomized coordinates
    console.log(
      ([cubesArray[i], cubesArray[j]] = [cubesArray[j], cubesArray[i]])
    );
  }
  }

////////////////////////////////////////////////////////////////////////////////////
// Creating banners using OOP
class Banner {
  constructor(name, classList, textContent, bannerMessage, bannerMessageClass) {
    this.name = document.createElement("div");
    this.name.classList.add(classList);
    this.bannerMessage = document.createElement("h2");
    this.bannerMessage.classList.add(bannerMessageClass);
    this.bannerMessage.textContent = textContent;
    root.append(this.bannerMessage);
    root.append(this.name);
  }

  removeBanner() {
    this.name.addEventListener("click", () => {
      resultBanner.classList.remove("result_banner");
      resultsButton.clickOnlyOnceDisabled();
    });
  }
}

// const startBanner = new Banner("startBanner","start_banner", `Slider puzzle challenge Click on 'Shuffle' to start the game!`, "bannerMessage","banner_message"
// );

// create pop-up if the user wins
function winAnnouncement() {
  const winMessage = new Banner(
    "winAnnounce",
    "win_announce",
    `Congrats! You solved the puzzle! Moves: ${countMoves} | ${setTimer.textContent}`,
    "winMessage",
    "win_message"
  );
}

// Creating a result banner
function showResults() {
  const resultBanner = document.createElement("div");
  resultBanner.classList.add("result_banner");
  const closeBanner = document.createElement("div");
  closeBanner.classList.add("close_banner");
  root.append(resultBanner);
  table.append(closeBanner);
  tableCreate();

  const resultMessage = document.createElement("h2");
  resultMessage.classList.add("banner_message");
  resultBanner.append(resultMessage);

  closeBanner.addEventListener("click", () => {
    resultBanner.classList.remove("result_banner");
    resultsButton.clickOnlyOnceDisabled();
    [...table.children].forEach((el) => {
      table.removeChild(el); //removing elements from the board
    });
  });
}

function tableCreate() {
  const tbl = document.createElement("table");
  tbl.classList.add("score_table");

  for (let i = 0; i < 11; i++) {
    tr = tbl.insertRow();
    td = tr.insertCell();

    if (gameRound === i + 1) {
      td.appendChild(
        document.createTextNode(
          `Round: ${i + 1} | Moves: ${gameRoundResults.moves[i]} | ${gameRoundResults.time[i]}`
        )
      );
    } else {
      td.appendChild(
        document.createTextNode(`Round: ${i + 1} | Moves: 0 | Time: 00:00`)
      );
    }

    td.style.border = "1px solid black";
  }
  table.appendChild(tbl);
}

buttons.classList.add("button");
body.append(buttons);

// creating cubes
function setPosition() {
  for (let i = 0; i < boardSize; i++) {
    cube = document.createElement("div");
    cube.classList.add("cube");
    const value = i + 1; // adding +1 to the cubes' values to start the order from 1 (123...) instead of 0 (0123...)
    cube.textContent = value;

    left = i % rowColumnLength; // setting horizontal position
    cube.style.left = setElementStyle(cubeSize, left);
    top = (i - left) / rowColumnLength; // setting vertical position
    cube.style.top = setElementStyle(cubeSize, top);

    root.append(cube);

    if (value === boardSize) {
      // separating basic cubes with a blank space which is going to be the 16th cube
      cube.classList.add("blank_space"); // adding a class to the last cube, so it'll be possible to hide it using css
      blankSpace.top = top;
      blankSpace.left = left;
      blankSpace.value = value;
      blankSpace.element = cube;
      cubes.push(blankSpace);
    } else {
      cubes.push({
        top: top,
        left: left,
        value: value,
        element: cube,
      });
    }

    cube.addEventListener("click", () => {
      changePosition(i);
    });
  }
}
setPosition();

</code>```

To solve the problem I've tried to refactor the shuffle function, but nothing works. In the screenshot you can see the results of console.logs

Body:
I created a slider-puzzle game and recently decided to reafctor the code using OOP. Besides I added a new functionality, so a player can change the size of the game board (3X3, 4X4, 5X5 etc.) by pressing a sertain button. But somehow a shuffle function stopped working. If you have any ideas of what I might do wrong, I will be very grateful if you let me know.

"use strict";
///////////////////////////////////////////////////////////////////////////
// Elements
const body = document.body;
const root = document.querySelector(".root");
const buttons = document.createElement("div");
const table = document.querySelector(".table");
const timeAndMoves = document.createElement("div");
const cubeSize = 125;
let cubes = [];
let gameRoundResults = {round: [], moves: [], time: []};

let countMoves = 0;
let gameRound = 0;
let cube, timer, left, top, tr, td;
let rowColumnLength = [3, 4, 5, 6, 7, 8]; // the default size of the game board - 4 columns and 4 rows
let boardSize = [9, 16, 15, 36, 49, 64];

let cubesArray = [];

let blankSpace = document.querySelector(".blank_space");
blankSpace = {
  // blank space coords
};

// calculating coordinates of each cube and setting style
function getCoords(a, b) {
  return Math.abs(a - b);
}

function setElementStyle(a, b) {
  return `${a * b}px`;
}

// changing position of cubes
function changePosition(i) {
  let cube = cubes[i];
  const blankSpaceLeft = blankSpace.left;
  const blankSpaceTop = blankSpace.top;

  let coordsLeft = getCoords(blankSpace.left, cube.left);
  let coordsTop = getCoords(blankSpace.top, cube.top);

  if (
    (blankSpaceLeft === cube.left && blankSpaceTop === cube.top) ||
    coordsLeft + coordsTop > 1
  ) {
    return;
  } else {
    countMoves++;
    calcMoves.textContent = `Moves: ${countMoves}`;
  }

  cube.element.style.left = setElementStyle(blankSpace.left, cubeSize);
  cube.element.style.top = setElementStyle(blankSpace.top, cubeSize);

  blankSpace.top = cube.top;
  blankSpace.left = cube.left;
  cube.top = blankSpaceTop;
  cube.left = blankSpaceLeft;

  const winCondition = cubes.every(
    (cube) => cube.value - 1 === cube.top * rowColumnLength + cube.left
  );

  if (winCondition) {
    winAnnouncement();
    clearInterval(timer);
    gameRound++;
    gameRoundResults.round.push(gameRound);
    gameRoundResults.moves.push(countMoves);
    gameRoundResults.time.push(setTimer.textContent);
  }
}

// resetting the game, so after clicking on a shuffle button the original game board won't overlay newly shuffled cubes
const resetGame = () => {
  clearInterval(timer);
  setTimer.textContent = `Time: 00:00`;
  countMoves = 0;
  calcMoves.textContent = `Moves: ${countMoves}`;
  [...root.children].forEach((el) => {
    root.removeChild(el); //removing elements from the board
  });
  [...table.children].forEach((el) => {
    table.removeChild(el); //removing elements from the board
  });
  cubes.splice(0); // deleting all elements starting from index 0
  blankSpace.top = 0; // resetting coordinates
  blankSpace.left = 0;
};

// creating a timer
const setTimer = document.createElement("div");
setTimer.classList.add("timer");
setTimer.textContent = `Time: 00:00`;
body.append(setTimer);

function startTimer() {
  let sec = 0;
  let min = 0;

  timer = setInterval(() => {
    setTimer.textContent =
      "Time: " + `${min}`.padStart(2, 0) + ":" + `${sec}`.padStart(2, 0);
    sec++;

    if (sec >= 60) {
      sec = 0;
      min++;
    }
  }, 1000);
}

// creating moves counter
const calcMoves = document.createElement("div");
calcMoves.classList.add("count_moves");
calcMoves.textContent = `Moves: ${countMoves}`;
body.append(calcMoves);

////////////////////////////////////////////////////////////////////////////////////
// Creating buttons using OOP and adding event listeners to each of them

class Button {
  constructor(name, attribute, classList, textContent, value) {
    this.name = document.createElement("button");
    this.name.setAttribute("id", attribute);
    this.name.classList.add(classList);
    this.textContent = this.name.textContent = textContent;
    buttons.append(this.name);
  }

  //Methods that will be added to .prototype property
  addEventShuffle() {
    this.name.addEventListener("click", function () {
      shuffle(cubesArray);
    });
  }

  addEventStop() {
    this.name.addEventListener("click", function () {
      clearInterval(timer);
    });
  }

  addEventResult() {
    this.name.addEventListener("click", function () {
      clearInterval(timer);
      tableCreate();
      showResults();
    });
  }

  clickOnlyOnce() {
    this.name.addEventListener("click", function () {
      this.disabled = "disabled";
    });
  }

  clickOnlyOnceDisabled() {
    this.name.removeAttribute("disabled");
  }

  renderCubesNumber(number){
    this.name.addEventListener("click", function () {
      cubesArray.push(...Array(boardSize[number]).keys());
      setPosition(boardSize = boardSize[number], rowColumnLength = rowColumnLength[number]);
      console.log(cubesArray);
    });
  }
}

const shuffleButton = new Button(
  "shuffleButton",
  "button",
  "shuffleButton",
  "SHUFFLE"
);
const stopButton = new Button("stopButton", "button", "stopButton", "STOP");
const saveButton = new Button("saveButton", "button", "saveButton", "SAVE");
const resultsButton = new Button( "resultsButton", "button", "resultsButton", "RESULT");

shuffleButton.addEventShuffle();
stopButton.addEventStop();
resultsButton.addEventResult();
resultsButton.clickOnlyOnce();

// Creating size buttons
for(let i = 3; i <= 8; i++){
new Button("rowsCols", "button", "row_col_length", `${i}X${i}`).renderCubesNumber(i - 3);
}

// implementing shuffle functionality

function shuffle(cubesArray) {
  for (let i = cubesArray.length - 1; i > 0; i--) {
    resetGame(); // deleting original game board
    setPosition(cubesArray); // creating a new shuffled game board
    startTimer();

    let j = Math.floor(Math.random() * (i + 1));

    [cubesArray[i], cubesArray[j]] = [cubesArray[j], cubesArray[i]];

    // [cubesArray[i], cubesArray[newPos]] = [cubesArray[newPos], cubesArray[i]]; //swapping original and randomized coordinates
    console.log(
      ([cubesArray[i], cubesArray[j]] = [cubesArray[j], cubesArray[i]])
    );
  }
  }

////////////////////////////////////////////////////////////////////////////////////
// Creating banners using OOP
class Banner {
  constructor(name, classList, textContent, bannerMessage, bannerMessageClass) {
    this.name = document.createElement("div");
    this.name.classList.add(classList);
    this.bannerMessage = document.createElement("h2");
    this.bannerMessage.classList.add(bannerMessageClass);
    this.bannerMessage.textContent = textContent;
    root.append(this.bannerMessage);
    root.append(this.name);
  }

  removeBanner() {
    this.name.addEventListener("click", () => {
      resultBanner.classList.remove("result_banner");
      resultsButton.clickOnlyOnceDisabled();
    });
  }
}

// const startBanner = new Banner("startBanner","start_banner", `Slider puzzle challenge Click on 'Shuffle' to start the game!`, "bannerMessage","banner_message"
// );

// create pop-up if the user wins
function winAnnouncement() {
  const winMessage = new Banner(
    "winAnnounce",
    "win_announce",
    `Congrats! You solved the puzzle! Moves: ${countMoves} | ${setTimer.textContent}`,
    "winMessage",
    "win_message"
  );
}

// Creating a result banner
function showResults() {
  const resultBanner = document.createElement("div");
  resultBanner.classList.add("result_banner");
  const closeBanner = document.createElement("div");
  closeBanner.classList.add("close_banner");
  root.append(resultBanner);
  table.append(closeBanner);
  tableCreate();

  const resultMessage = document.createElement("h2");
  resultMessage.classList.add("banner_message");
  resultBanner.append(resultMessage);

  closeBanner.addEventListener("click", () => {
    resultBanner.classList.remove("result_banner");
    resultsButton.clickOnlyOnceDisabled();
    [...table.children].forEach((el) => {
      table.removeChild(el); //removing elements from the board
    });
  });
}

function tableCreate() {
  const tbl = document.createElement("table");
  tbl.classList.add("score_table");

  for (let i = 0; i < 11; i++) {
    tr = tbl.insertRow();
    td = tr.insertCell();

    if (gameRound === i + 1) {
      td.appendChild(
        document.createTextNode(
          `Round: ${i + 1} | Moves: ${gameRoundResults.moves[i]} | ${gameRoundResults.time[i]}`
        )
      );
    } else {
      td.appendChild(
        document.createTextNode(`Round: ${i + 1} | Moves: 0 | Time: 00:00`)
      );
    }

    td.style.border = "1px solid black";
  }
  table.appendChild(tbl);
}

buttons.classList.add("button");
body.append(buttons);

// creating cubes
function setPosition() {
  for (let i = 0; i < boardSize; i++) {
    cube = document.createElement("div");
    cube.classList.add("cube");
    const value = i + 1; // adding +1 to the cubes' values to start the order from 1 (123...) instead of 0 (0123...)
    cube.textContent = value;

    left = i % rowColumnLength; // setting horizontal position
    cube.style.left = setElementStyle(cubeSize, left);
    top = (i - left) / rowColumnLength; // setting vertical position
    cube.style.top = setElementStyle(cubeSize, top);

    root.append(cube);

    if (value === boardSize) {
      // separating basic cubes with a blank space which is going to be the 16th cube
      cube.classList.add("blank_space"); // adding a class to the last cube, so it'll be possible to hide it using css
      blankSpace.top = top;
      blankSpace.left = left;
      blankSpace.value = value;
      blankSpace.element = cube;
      cubes.push(blankSpace);
    } else {
      cubes.push({
        top: top,
        left: left,
        value: value,
        element: cube,
      });
    }

    cube.addEventListener("click", () => {
      changePosition(i);
    });
  }
}
setPosition();

To solve the problem I've tried to refactor the shuffle function, but nothing works. In the screenshot you can see the results of console.logs


问:
How can I disable adding data if the field is empty
```<code>'''INSERT INTO
       main_parse_user ("user_id","group_id", "username","bio", "first_name")
       VALUES (%s,%s,%s,%s,%s)
       ON CONFLICT (user_id)
       DO UPDATE SET (group_id,username,bio,first_name) =(EXCLUDED.group_id,EXCLUDED.username,coalesce(main_parse_user.bio, EXCLUDED.bio),EXCLUDED.first_name)'''
</code>```

How can I make the username field so that when adding a new record, make it so that if the value from the loaded request in the username field is empty, just skip this user

I haven't tried anything yet

Body:
'''INSERT INTO
       main_parse_user ("user_id","group_id", "username","bio", "first_name")
       VALUES (%s,%s,%s,%s,%s)
       ON CONFLICT (user_id)
       DO UPDATE SET (group_id,username,bio,first_name) =(EXCLUDED.group_id,EXCLUDED.username,coalesce(main_parse_user.bio, EXCLUDED.bio),EXCLUDED.first_name)'''

How can I make the username field so that when adding a new record, make it so that if the value from the loaded request in the username field is empty, just skip this user

I haven't tried anything yet


问:
Linkerd2 and Network Policys
i run an k3s Cluster in the latest version. Everything works like expected. Now i wrote a Programm for my CI/CD Pipeline that automatically create Network Policy´s based on my deployment Files. (only needed Ports are allowed for external or allowed containers..) In my bare Metal Cluster everything works fine. Now i want to encrypt my Traffic via mTLS an collect some Communication Logs via Linkerd2 so in installed Linkerd2 and Linkerd2-viz over the linkerd cli.

For my Network Policy´s i added some ingress allows like here:
https://ihcsim.medium.com/linkerd-2-x-with-network-policy-2657103333ca

When I inject the Linkerd-Proxy´s all my Webservers are Reachable. My clamav pod works as well, but if i try to connect to my Redis Container it wont work.

So my question is: Witch Ports/ Network Policy´s dose Linkerd2 need to Communicate?

Thanks for helping!

Example Network-Policy for Redis without the Linkerd2 parts:

```<code>apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: fw-redis
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: redis
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          firewall/allowed.redis.6379-TCP: 'true'
    ports:
    - port: 6379
      protocol: TCP
  egress:
  - to:
    - namespaceSelector: {}
      podSelector:
        matchLabels:
          k8s-app: kube-dns
    ports:
    - port: 53
      protocol: UDP
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0
        except:
        - 10.11.12.0/27

</code>```

Title: Linkerd2 and Network Policys

Body:
i run an k3s Cluster in the latest version. Everything works like expected. Now i wrote a Programm for my CI/CD Pipeline that automatically create Network Policy´s based on my deployment Files. (only needed Ports are allowed for external or allowed containers..) In my bare Metal Cluster everything works fine. Now i want to encrypt my Traffic via mTLS an collect some Communication Logs via Linkerd2 so in installed Linkerd2 and Linkerd2-viz over the linkerd cli.

For my Network Policy´s i added some ingress allows like here:
https://ihcsim.medium.com/linkerd-2-x-with-network-policy-2657103333ca

When I inject the Linkerd-Proxy´s all my Webservers are Reachable. My clamav pod works as well, but if i try to connect to my Redis Container it wont work.

So my question is: Witch Ports/ Network Policy´s dose Linkerd2 need to Communicate?

Thanks for helping!

Example Network-Policy for Redis without the Linkerd2 parts:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: fw-redis
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: redis
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          firewall/allowed.redis.6379-TCP: 'true'
    ports:
    - port: 6379
      protocol: TCP
  egress:
  - to:
    - namespaceSelector: {}
      podSelector:
        matchLabels:
          k8s-app: kube-dns
    ports:
    - port: 53
      protocol: UDP
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0
        except:
        - 10.11.12.0/27


问:
Retrieving object metadata while traversing S3 using Minio client's list_objects method
I am using the list_objects method of the python minio client and trying to retrieve the metadata for each object while traversing folders in S3. I attempted to do this by setting the include_user_meta parameter of the method to True. However, when I look at the returned objects, the metadata of the returned objects is not included. I checked the S3 API Reference documentation for the ListObjectsV2 endpoint and there is no mention of a metadata parameter that could be passed to include the metadata during file traversal.

Is there some other way to retrieve the metadata for each object while traversing a folder in S3 (without firing off one request for each retrieved object), or is this simply not possible and there is a bug in the python minio client?


问:
Brotli not being served with AWS amplify but gzip files are
I'm using Aws amplify to host a vue3 app,  I have got webpack bulding the .gz & .br files, have updated my redirect in aws amplify to </^[^.]+$|.(?!(gz|br|css|gif|ico|jpg|js|png|txt|svg|woff|woff2|ttf|map|json)$)([^.]+$)/>

so as gz and br are included.  So gzip file are now being served but its not serving brotli files, the amplify cloudfront is setup to enable both gzip and brotli,  so i'm stumped as to whats wrong, would anyone know why?


问:
Form group validator is overriding the form control validator in Angular 11
I am facing the problem as described in this topic

I am trying to add a validator to a form group in which I have already 3 validators on form controls.
So I have a form group with 6 controls, 3 of them have a required validator. And I want to validate globally my form to check if a date period is correctly described, so I add a validator to my form group.

Here is an example of code :

```<code>        this.identifierForm = this.formBuilder.group({
            id: [],
            type: [null, Validators.required],
            value: [null, Validators.required],
            validFrom: [],
            validUntil: [],
            authority: [null, Validators.required],
        });
        this.identifierForm.setValidators(
            FormValidator.dateOrderValidator(
                this.identifierForm,
                'validFrom',
                'validUntil',
                this.i18nService
            )
        );
</code>```

This results in only the form group validator to work. The form control validators are just ommited.
If I delete my form group validator, everything is working well in my form controls validators.

How can I do to "add" validator to my form group without overriding the included form controls validators?

I saw that angular 12 added the "addValidators" method to the FormGroup but I am not able to use this version at the moment.

EDIT:
I just tryed to define my formgroup validator at instantiation timebut result is still the same

```<code>        this.identifierForm = this.formBuilder.group(
            {
                id: [],
                type: [null, Validators.required],
                value: [null, Validators.required],
                validFrom: [],
                validUntil: [],
                authority: [null, Validators.required],
            },
            {
                validators: [
                    FormValidator.dateOrderValidator('validFrom', 'validUntil', this.i18nService),
                ],
            }
        );
</code>```

Here is my validator :

```<code>dateOrderValidator(
        startDateFieldName: string,
        endDateFieldName: string,
        i18nService: DngI18nService
    ): ValidatorFn {
        return (formGroup: FormGroup): ValidationErrors | null => {
            resetErrors(formGroup);
            const startDate = formGroup.controls[startDateFieldName]?.value;
            const endDate = formGroup.controls[endDateFieldName]?.value;
            if (Date.parse(startDate) >= Date.parse(endDate)) {
                formGroup.controls[startDateFieldName].setErrors({
                    error: i18nService.instant('invalidDatePeriod') as string,
                });
                formGroup.controls[endDateFieldName].setErrors({
                    error: i18nService.instant('invalidDatePeriod') as string,
                });
                return { error: i18nService.instant('invalidForm') as string };
            }
            return null;
        };
    },
</code>```

Body:
I am facing the problem as described in this topic

I am trying to add a validator to a form group in which I have already 3 validators on form controls.
So I have a form group with 6 controls, 3 of them have a required validator. And I want to validate globally my form to check if a date period is correctly described, so I add a validator to my form group.

Here is an example of code :

        this.identifierForm = this.formBuilder.group({
            id: [],
            type: [null, Validators.required],
            value: [null, Validators.required],
            validFrom: [],
            validUntil: [],
            authority: [null, Validators.required],
        });
        this.identifierForm.setValidators(
            FormValidator.dateOrderValidator(
                this.identifierForm,
                'validFrom',
                'validUntil',
                this.i18nService
            )
        );

This results in only the form group validator to work. The form control validators are just ommited.
If I delete my form group validator, everything is working well in my form controls validators.

How can I do to "add" validator to my form group without overriding the included form controls validators?

I saw that angular 12 added the "addValidators" method to the FormGroup but I am not able to use this version at the moment.

EDIT:
I just tryed to define my formgroup validator at instantiation timebut result is still the same

        this.identifierForm = this.formBuilder.group(
            {
                id: [],
                type: [null, Validators.required],
                value: [null, Validators.required],
                validFrom: [],
                validUntil: [],
                authority: [null, Validators.required],
            },
            {
                validators: [
                    FormValidator.dateOrderValidator('validFrom', 'validUntil', this.i18nService),
                ],
            }
        );

Here is my validator :

dateOrderValidator(
        startDateFieldName: string,
        endDateFieldName: string,
        i18nService: DngI18nService
    ): ValidatorFn {
        return (formGroup: FormGroup): ValidationErrors | null => {
            resetErrors(formGroup);
            const startDate = formGroup.controls[startDateFieldName]?.value;
            const endDate = formGroup.controls[endDateFieldName]?.value;
            if (Date.parse(startDate) >= Date.parse(endDate)) {
                formGroup.controls[startDateFieldName].setErrors({
                    error: i18nService.instant('invalidDatePeriod') as string,
                });
                formGroup.controls[endDateFieldName].setErrors({
                    error: i18nService.instant('invalidDatePeriod') as string,
                });
                return { error: i18nService.instant('invalidForm') as string };
            }
            return null;
        };
    },


问:
Temporal disaggregation of a grouped time series (Yearly to Quarterly)
I have this dataset (source Eurostat, last accessed 21 December 2022):

```<code>library(countrycode)
library(eurostat)
library(fpp3)
library(tempdisagg)
library(tsbox)

# defines
cols <- c("geo", "age", "sex")
eu27 <- setdiff(eu_countries$code, "UK")

# Population on 1 January by age group, sex and citizenship
population <-
  get_eurostat(
    id = "migr_pop1ctz",
    time_format = "num",
    filters = list(
      geo = eu27,
      citizen = "TOTAL",
      age = c("TOTAL", "UNK", "Y_GE65"),
      sex = c("F", "M", "T")
    )
  )

# remove rows with no data (if any)
population <- population %>% drop_na(c(all_of(cols), values))
</code>```

I need to group it by gender (sex) and geo, and then temporally disaggregate each grouped time series from Yearly to Quarterly frequency.

I know I can do this using the tempdisagg on a non-disaggregated time series. For intance, this code works:

```<code>test <- population %>% filter(geo == "IT", age == "TOTAL", sex == "F") %>% select(time, values)
m1 <- td(test ~ 1, to = "quarterly", method = "denton-cholette")
</code>```

However, I can't seem to find a nice way to make it work on each group separately.

I know I could probably do this by manually separating (slicing) the dataset into subdataset (representing each group), run td function, and aggregate back everything together, but I was hoping to find a more appropriate way that could handle the time series + group nature of the dataset without much manual intervention.

I have tried some options, such as converting my data to a tsibble, and then aggregating it using the aggregate_key function. However, when introducing groups, I don't know how to use the td function properly, since my attempts led to various errors.

```<code># convert to time series
population <- population %>%
  as_tsibble(key = all_of(cols), index = time)

# grouped time series with crossed attributes
#https://otexts.com/fpp3/hts.html#mixed-hierarchical-and-grouped-structure
population_gts <- population %>%
  filter(age == "TOTAL" & !sex == "T") %>%
  aggregate_key(sex * geo, values = sum(values))

population_gts %>%
  group_map(~ td(~1, to = "quarterly", method = "denton-cholette"))
</code>```

The above gives the error:

```<code>Error in td(~1, to = "quarterly", method = "denton-cholette") :
  In numeric mode, 'to' must be an integer number.
</code>```

FIRST "SEMI-SUCCESSFUL ATTEMPT"

I found one working solution, although it's far from being ideal.

Apparently, the td function seems to require a regular panel (i.e. no missing time index like 2008, 2010, 2011, ...), which can be obtained using fill_gaps().

Moreover, tsbox throws an error if it there are NAs in the series. So, at the end, one first possible solution would be to replace NAs with zeroes (although it feels very bad!):

```<code>td_list = function(formula) {
  return(list(td = td(formula, to = "quarter", method = "fast")))

# disaggregate from yearly to quarterly frequency
pop_q <- population %>%
  replace_na(list(values = 0)) %>%
  group_by(across(c(all_of(agg_cols)))) %>%
  select(time, values) %>%
  group_map(~ td_list(.x~1))
}
</code>```

Body:
I have this dataset (source Eurostat, last accessed 21 December 2022):

library(countrycode)
library(eurostat)
library(fpp3)
library(tempdisagg)
library(tsbox)

# defines
cols <- c("geo", "age", "sex")
eu27 <- setdiff(eu_countries$code, "UK")

# Population on 1 January by age group, sex and citizenship
population <-
  get_eurostat(
    id = "migr_pop1ctz",
    time_format = "num",
    filters = list(
      geo = eu27,
      citizen = "TOTAL",
      age = c("TOTAL", "UNK", "Y_GE65"),
      sex = c("F", "M", "T")
    )
  )

# remove rows with no data (if any)
population <- population %>% drop_na(c(all_of(cols), values))

I need to group it by gender (sex) and geo, and then temporally disaggregate each grouped time series from Yearly to Quarterly frequency.

I know I can do this using the tempdisagg on a non-disaggregated time series. For intance, this code works:

test <- population %>% filter(geo == "IT", age == "TOTAL", sex == "F") %>% select(time, values)
m1 <- td(test ~ 1, to = "quarterly", method = "denton-cholette")

However, I can't seem to find a nice way to make it work on each group separately.

I know I could probably do this by manually separating (slicing) the dataset into subdataset (representing each group), run td function, and aggregate back everything together, but I was hoping to find a more appropriate way that could handle the time series + group nature of the dataset without much manual intervention.

I have tried some options, such as converting my data to a tsibble, and then aggregating it using the aggregate_key function. However, when introducing groups, I don't know how to use the td function properly, since my attempts led to various errors.

# convert to time series
population <- population %>%
  as_tsibble(key = all_of(cols), index = time)

# grouped time series with crossed attributes
#https://otexts.com/fpp3/hts.html#mixed-hierarchical-and-grouped-structure
population_gts <- population %>%
  filter(age == "TOTAL" & !sex == "T") %>%
  aggregate_key(sex * geo, values = sum(values))

population_gts %>%
  group_map(~ td(~1, to = "quarterly", method = "denton-cholette"))

The above gives the error:

Error in td(~1, to = "quarterly", method = "denton-cholette") :
  In numeric mode, 'to' must be an integer number.

FIRST "SEMI-SUCCESSFUL ATTEMPT"

I found one working solution, although it's far from being ideal.

Apparently, the td function seems to require a regular panel (i.e. no missing time index like 2008, 2010, 2011, ...), which can be obtained using fill_gaps().

Moreover, tsbox throws an error if it there are NAs in the series. So, at the end, one first possible solution would be to replace NAs with zeroes (although it feels very bad!):

td_list = function(formula) {
  return(list(td = td(formula, to = "quarter", method = "fast")))

# disaggregate from yearly to quarterly frequency
pop_q <- population %>%
  replace_na(list(values = 0)) %>%
  group_by(across(c(all_of(agg_cols)))) %>%
  select(time, values) %>%
  group_map(~ td_list(.x~1))
}


问:
Internal Rxjs error during nestjs grpc request using client-streaming
I'm using a nestjs backend that receives gRPC calls with client-side streaming and I've encountered a very odd issue:
When many gRPC requests are made to the server from a client, and the client crashes/exits mid-way, then that causes the server to crash as well.
The error however is not coherent and appears to be an internal rxjs error.

Basically, my backend controller receives an rxjs Observable of data, which I subscribe on and process. After the subscription, I await the lastValueFrom result of said Observable. Then the server returns a message to the client. I'll supply some sample code and the error below:

Code:

```<code>@GrpcStreamMethod('MyService', 'MyCallName')
  async myCallHandler(
    messages: Observable<RequestClass>,
  ): Promise<ResponseClass> {
    let errorsOccured = false;

    const subscription: Subscription = messages
      .pipe(catchError((err) => of()))
      .subscribe({
        next: async (msg) => {

          try {
            await this.myService.process(msg);
          } catch (err) {
            errorsOccured = true;
          }
        },
        error: (err) => {
          errorsOccured = true;
          const stack: string | undefined = (<Error>err)?.stack;
        },
      });

    let lastValue = undefined;
    try {
      lastValue = await lastValueFrom(messages);
    } catch (err) {
      if (!(err instanceof EmptyError)) {
        errorsOccured = true;
      }
    }

    subscription.unsubscribe();

    return {
      code: `${errorsOccured ? 'E' : 'S'}_GEN_00001`,
    };
  }
</code>```

Error:

```<code>/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/util/createErrorClass.ts:13
    instance.stack = new Error().stack;
                     ^
Error:
    at _super (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/util/createErrorClass.ts:13:22)
    at new EmptyErrorImpl (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/util/EmptyError.ts:26:3)
    at Object.complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/lastValueFrom.ts:71:18)
    at ConsumerObserver.complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/Subscriber.ts:185:25)
    at SafeSubscriber.Subscriber._complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/Subscriber.ts:132:24)
    at SafeSubscriber.Subscriber.complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/Subscriber.ts:106:12)
    at OperatorSubscriber.Subscriber._complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/Subscriber.ts:132:24)
    at OperatorSubscriber.Subscriber.complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/Subscriber.ts:106:12)
    at /home/ioch/unucare/lnp/node_modules/rxjs/src/internal/operators/takeUntil.ts:48:89
    at OperatorSubscriber._this._next (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts:70:13)
</code>```

I fail to understand what is causing this error.

Body:
I'm using a nestjs backend that receives gRPC calls with client-side streaming and I've encountered a very odd issue:
When many gRPC requests are made to the server from a client, and the client crashes/exits mid-way, then that causes the server to crash as well.
The error however is not coherent and appears to be an internal rxjs error.

Basically, my backend controller receives an rxjs Observable of data, which I subscribe on and process. After the subscription, I await the lastValueFrom result of said Observable. Then the server returns a message to the client. I'll supply some sample code and the error below:

Code:

@GrpcStreamMethod('MyService', 'MyCallName')
  async myCallHandler(
    messages: Observable<RequestClass>,
  ): Promise<ResponseClass> {
    let errorsOccured = false;

    const subscription: Subscription = messages
      .pipe(catchError((err) => of()))
      .subscribe({
        next: async (msg) => {

          try {
            await this.myService.process(msg);
          } catch (err) {
            errorsOccured = true;
          }
        },
        error: (err) => {
          errorsOccured = true;
          const stack: string | undefined = (<Error>err)?.stack;
        },
      });

    let lastValue = undefined;
    try {
      lastValue = await lastValueFrom(messages);
    } catch (err) {
      if (!(err instanceof EmptyError)) {
        errorsOccured = true;
      }
    }

    subscription.unsubscribe();

    return {
      code: `${errorsOccured ? 'E' : 'S'}_GEN_00001`,
    };
  }

Error:

/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/util/createErrorClass.ts:13
    instance.stack = new Error().stack;
                     ^
Error:
    at _super (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/util/createErrorClass.ts:13:22)
    at new EmptyErrorImpl (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/util/EmptyError.ts:26:3)
    at Object.complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/lastValueFrom.ts:71:18)
    at ConsumerObserver.complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/Subscriber.ts:185:25)
    at SafeSubscriber.Subscriber._complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/Subscriber.ts:132:24)
    at SafeSubscriber.Subscriber.complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/Subscriber.ts:106:12)
    at OperatorSubscriber.Subscriber._complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/Subscriber.ts:132:24)
    at OperatorSubscriber.Subscriber.complete (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/Subscriber.ts:106:12)
    at /home/ioch/unucare/lnp/node_modules/rxjs/src/internal/operators/takeUntil.ts:48:89
    at OperatorSubscriber._this._next (/home/ioch/unucare/lnp/node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts:70:13)

I fail to understand what is causing this error.


问:
How to export excel file from php
I want to remove warning (warning)
P.S I know that .xls is old version and I'm trying to use .xlsx but don't working.</p>
```<code>header("Content-Type: application/xls");
header("Content-Type: application/octet-stream");
header('Content-Encoding: UTF-8');
header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
$data = "Some utf-8 characters Ä…Ä‡Å¼ÅºÄ‡Å‚";
header("Content-Transfer-Encoding: binary");
header('Expires: '.gmdate('D, d M Y H:i:s').' GMT');
header('Content-Disposition: attachment; filename = "Export '.date("Y-m-d").'.tsv"');
header("Content-Disposition: attachment; filename=municipaliteties_list.xls");
header("Pragma: no-cache");
header("Expires: 0");
</code>```

Title: How to export excel file from php

Body:
I want to remove warning (warning)
P.S I know that .xls is old version and I'm trying to use .xlsx but don't working.

header("Content-Type: application/xls");
header("Content-Type: application/octet-stream");
header('Content-Encoding: UTF-8');
header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
$data = "Some utf-8 characters Ä…Ä‡Å¼ÅºÄ‡Å‚";
header("Content-Transfer-Encoding: binary");
header('Expires: '.gmdate('D, d M Y H:i:s').' GMT');
header('Content-Disposition: attachment; filename = "Export '.date("Y-m-d").'.tsv"');
header("Content-Disposition: attachment; filename=municipaliteties_list.xls");
header("Pragma: no-cache");
header("Expires: 0");


问:
Fetch-function gets called at the end of the code
I'm a beginner in javascript, but did a lot of googling to figure out promises and async/await. However, it seems like the fetch function call gets called at the end the very end of my program and i don't know how to fix it. I have tried multiple versions of this function from stackoverflow but it seems nothing is giving me the expected result.. What do i do wrong?

This would be my fetch function:

```<code>async function fetchData() {
    const resp = await fetch("/test.csv");
    const data = await resp.text();
    return data;
}
function processData(data) {
    console.log(data);
}
</code>```

Whith this call:

```<code>console.log("Before Fetch")
fetchData().then(processData)
console.log("Code after Fetch")
</code>```

I would expect the following output:

```<code>Before Fetch
data
Code after Fetch
</code>```

But i get:

```<code>Before Fetch
Code after Fetch
data
</code>```

A weird fix would be to put my entire code in the processData(data) function, but there has to be another way i guess?

Body:
I'm a beginner in javascript, but did a lot of googling to figure out promises and async/await. However, it seems like the fetch function call gets called at the end the very end of my program and i don't know how to fix it. I have tried multiple versions of this function from stackoverflow but it seems nothing is giving me the expected result.. What do i do wrong?

This would be my fetch function:

async function fetchData() {
    const resp = await fetch("/test.csv");
    const data = await resp.text();
    return data;
}
function processData(data) {
    console.log(data);
}

Whith this call:

console.log("Before Fetch")
fetchData().then(processData)
console.log("Code after Fetch")

I would expect the following output:

Before Fetch
data
Code after Fetch

But i get:

Before Fetch
Code after Fetch
data

A weird fix would be to put my entire code in the processData(data) function, but there has to be another way i guess?