问:
Error while sending a pdf from Node.js server to Angular client
I try to send a pdf made by Puppeteer to my Angular client but I get this error:

The server-side code:

```<code>app.get('/convCVtoPDF',auth, jsonParser,async (req,res)=>{
const id = req.header('id')

const options = {

margin: {
  top: '50px',
  right: '50px',
  bottom: '50px',
  left: '50px',
},
pageSize: 'A4',
landscape: false,}
try {
const browser = await puppeteer.launch({"headless": true});

const page = await browser.newPage();
await page.setExtraHTTPHeaders({
  'id':id
});

await page.goto('http://localhost:4200/BasicCvPDF');

const pdf = await page.pdf(options);

await browser.close();

// Send the PDF buffer in the response
res.setHeader('Content-Type', 'application/pdf');

res.send(pdf);
} catch (e) {
console.log(e);
res.status(500).send();
}

})
</code>```

And the client side is:

```<code>async ngOnInit(){
 await this.http.get<any>('http://localhost:3000/getUserById',{
 headers:new HttpHeaders({'Content-Type':'application/json'})
 }).toPromise()
}
</code>```

I am sure the PDF is valid because If I specify a path for Puppeteer to save it, I can open and view it without a problem.
Any thoughts on why it can happen?

Body:
I try to send a pdf made by Puppeteer to my Angular client but I get this error:

The server-side code:

app.get('/convCVtoPDF',auth, jsonParser,async (req,res)=>{
const id = req.header('id')

const options = {

margin: {
  top: '50px',
  right: '50px',
  bottom: '50px',
  left: '50px',
},
pageSize: 'A4',
landscape: false,}
try {
const browser = await puppeteer.launch({"headless": true});

const page = await browser.newPage();
await page.setExtraHTTPHeaders({
  'id':id
});

await page.goto('http://localhost:4200/BasicCvPDF');

const pdf = await page.pdf(options);

await browser.close();

// Send the PDF buffer in the response
res.setHeader('Content-Type', 'application/pdf');

res.send(pdf);
} catch (e) {
console.log(e);
res.status(500).send();
}

})

And the client side is:

async ngOnInit(){
 await this.http.get<any>('http://localhost:3000/getUserById',{
 headers:new HttpHeaders({'Content-Type':'application/json'})
 }).toPromise()
}

I am sure the PDF is valid because If I specify a path for Puppeteer to save it, I can open and view it without a problem.
Any thoughts on why it can happen?


来源: stackexchange

问:
Callback mongodb aggregation with Dash Plotly DatePickerSingle
So i use this to list signals from the selected date. However it only returns signals from a single date. which is date_f here.

Example db and query here : https://mongoplayground.net/p/xWWfW0VAZoP

I tried to wrap aggregation query into a function and call it under populate_datatable function.
Whenever i try to call signals from 12/13 it returns signals from 12/12.

Here is the code i use:

```<code>from pymongo import MongoClient
import pandas as pd
from datetime import datetime as dt
from datetime import date
from dash.dependencies import Input, Output
from dash import Dash, dcc, html, Input, Output, dash_table
#from queries import *
from bson.tz_util import FixedOffset
client =  MongoClient("mongodb+srv://user:pass@etc")
database = client["Raw_Signals"]
collection = database["raw_daily"]

date_f = dt.strptime("2022-12-12 03:00:00.000000", "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo = FixedOffset(180, "+0300"))
pipeline =  [
    {
        u"$match": {
            u"$or": [
                {
                    u"MOSC": {
                        u"$gt": 0.0
                    }
                },
                {
                    u"SHL": {
                        u"$gt": 0.0
                    }
                },
                {
                    u"DDSM": {
                        u"$gt": 0.0
                    }
                }
            ],
            u"Date": date_f
        }
    },
    {
        u"$lookup": {
            u"from": u"raw_daily",
            u"let": {
                u"stock": u"$Stock",
                u"date": u"$Date"
            },
            u"pipeline": [
                {
                    u"$sort": {
                        u"Date": 1.0
                    }
                },
                {
                    u"$match": {
                        u"$expr": {
                            u"$and": [
                                {
                                    u"$eq": [
                                        u"$Stock",
                                        u"$$stock"
                                    ]
                                },
                                {
                                    u"$gt": [
                                        u"$Date",
                                        u"$$date"
                                    ]
                                }
                            ]
                        }
                    }
                },
                {
                    u"$project": {
                        u"_id": 0.0,
                        u"Change": 1.0
                    }
                },
                {
                    u"$limit": 3.0
                }
            ],
            u"as": u"ChangeT"
        }
    },
    {
        u"$project": {
            u"_id": 0.0,
            u"Date": 1.0,
            u"Stock": 1.0,
            u"Price": 1.0,
            u"Change_P3": {
                u"$round": [
                    {
                        u"$sum": u"$ChangeT.Change"
                    },
                    2.0
                ]
            }
        }
    }
]

app = Dash(__name__)
app.layout = html.Div(
[
    dcc.DatePickerSingle(
        id='date-picker',
        min_date_allowed=dt.strptime("2000-1-1 03:00:00.000000", "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo = FixedOffset(180, "+0300")),
        max_date_allowed=dt.strptime("2028-12-13 03:00:00.000000", "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo = FixedOffset(180, "+0300")),
        initial_visible_month=dt.strptime("2022-12-1 03:00:00.000000", "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo = FixedOffset(180, "+0300")),
        date=dt.strptime("2022-12-12 03:00:00.000000", "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo = FixedOffset(180, "+0300"))
    ),
    html.Div(id='mongo-datatable', children=[])
    ])
@app.callback(Output('mongo-datatable', 'children'),
              [Input('date-picker', 'date')])

def populate_datatable(date):

    pipeline["Date"] = date
    df = pd.DataFrame(list(collection.aggregate(pipeline)))
    print(df)
    return [
        dash_table.DataTable(
            id='mongo-datatable',
            columns=[{'name': x,'id': x,} for x in df.columns],
            data=df.to_dict('records'),
        )
    ]

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So i use this to list signals from the selected date. However it only returns signals from a single date. which is date_f here.

Example db and query here : https://mongoplayground.net/p/xWWfW0VAZoP

I tried to wrap aggregation query into a function and call it under populate_datatable function.
Whenever i try to call signals from 12/13 it returns signals from 12/12.

Here is the code i use:

from pymongo import MongoClient
import pandas as pd
from datetime import datetime as dt
from datetime import date
from dash.dependencies import Input, Output
from dash import Dash, dcc, html, Input, Output, dash_table
#from queries import *
from bson.tz_util import FixedOffset
client =  MongoClient("mongodb+srv://user:pass@etc")
database = client["Raw_Signals"]
collection = database["raw_daily"]

date_f = dt.strptime("2022-12-12 03:00:00.000000", "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo = FixedOffset(180, "+0300"))
pipeline =  [
    {
        u"$match": {
            u"$or": [
                {
                    u"MOSC": {
                        u"$gt": 0.0
                    }
                },
                {
                    u"SHL": {
                        u"$gt": 0.0
                    }
                },
                {
                    u"DDSM": {
                        u"$gt": 0.0
                    }
                }
            ],
            u"Date": date_f
        }
    },
    {
        u"$lookup": {
            u"from": u"raw_daily",
            u"let": {
                u"stock": u"$Stock",
                u"date": u"$Date"
            },
            u"pipeline": [
                {
                    u"$sort": {
                        u"Date": 1.0
                    }
                },
                {
                    u"$match": {
                        u"$expr": {
                            u"$and": [
                                {
                                    u"$eq": [
                                        u"$Stock",
                                        u"$$stock"
                                    ]
                                },
                                {
                                    u"$gt": [
                                        u"$Date",
                                        u"$$date"
                                    ]
                                }
                            ]
                        }
                    }
                },
                {
                    u"$project": {
                        u"_id": 0.0,
                        u"Change": 1.0
                    }
                },
                {
                    u"$limit": 3.0
                }
            ],
            u"as": u"ChangeT"
        }
    },
    {
        u"$project": {
            u"_id": 0.0,
            u"Date": 1.0,
            u"Stock": 1.0,
            u"Price": 1.0,
            u"Change_P3": {
                u"$round": [
                    {
                        u"$sum": u"$ChangeT.Change"
                    },
                    2.0
                ]
            }
        }
    }
]

app = Dash(__name__)
app.layout = html.Div(
[
    dcc.DatePickerSingle(
        id='date-picker',
        min_date_allowed=dt.strptime("2000-1-1 03:00:00.000000", "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo = FixedOffset(180, "+0300")),
        max_date_allowed=dt.strptime("2028-12-13 03:00:00.000000", "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo = FixedOffset(180, "+0300")),
        initial_visible_month=dt.strptime("2022-12-1 03:00:00.000000", "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo = FixedOffset(180, "+0300")),
        date=dt.strptime("2022-12-12 03:00:00.000000", "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo = FixedOffset(180, "+0300"))
    ),
    html.Div(id='mongo-datatable', children=[])
    ])
@app.callback(Output('mongo-datatable', 'children'),
              [Input('date-picker', 'date')])

def populate_datatable(date):

    pipeline["Date"] = date
    df = pd.DataFrame(list(collection.aggregate(pipeline)))
    print(df)
    return [
        dash_table.DataTable(
            id='mongo-datatable',
            columns=[{'name': x,'id': x,} for x in df.columns],
            data=df.to_dict('records'),
        )
    ]

if __name__ == '__main__':
    app.run_server(debug=True)


问:
ValueError Input shape in a custom layer tensorflow
I have this custom layer:

```<code>class PhysicalLayer(keras.layers.Layer):
    def __init__(self,units, speed):
        self.units = units
        self.speed = speed
        super(PhysicalLayer, self).__init__()
    def build(self, input_shape):

        self.w = self.add_weight(shape=(input_shape[-1], self.units), initializer="random_normal", trainable=True)
        self.b = self.add_weight(shape=(self.units,), initializer="random_normal", trainable=True)

    def call(self, inputs):
        squareSpeed = tf.math.square(self.speed)
        vibrationMax = tf.math.reduce_max(inputs, axis = 1, keepdims = True)
        inputsSpeed = tf.math.divide(squareSpeed, vibrationMax)
        print(tf.shape(inputsSpeed))
        print(tf.shape(self.w))
        multiplication = tf.multiply(squareSpeed, self.w)

        return tf.matmul(inputsSpeed , self.w) + self.b
        #return multiplication + self.b
</code>```

And when I try to build this following model

```<code>inputs = keras.Input(shape=(500,))
dense = layers.Dense(64, activation="relu")
x = PhysicalLayer(1, rotationSpeed)(inputs)
x = dense(x)
x = layers.Dense(32, activation="relu")(x)
outputs = layers.Dense(1)(x)
modelPhi = keras.Model(inputs=inputs, outputs=outputs, name="model_phi_custom")
</code>```

I have the following error:

```<code>ValueError: Dimensions must be equal, but are 1 and 500 for '{{node physical_layer_34/MatMul}} = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false](physical_layer_34/truediv, physical_layer_34/MatMul/ReadVariableOp)' with input shapes: [?,1], [500,1].
</code>```

I tried to use multiplication instead of matmul but then for fitting the model, I need to use a batch_size of 500 or i come across this error:

```<code>Node: 'gradient_tape/mean_absolute_error/sub/BroadcastGradientArgs'Incompatible shapes: [500,1] vs. [64,1]
</code>```

How can I fix this ?
Thanks

Body:
I have this custom layer:

class PhysicalLayer(keras.layers.Layer):
    def __init__(self,units, speed):
        self.units = units
        self.speed = speed
        super(PhysicalLayer, self).__init__()
    def build(self, input_shape):

        self.w = self.add_weight(shape=(input_shape[-1], self.units), initializer="random_normal", trainable=True)
        self.b = self.add_weight(shape=(self.units,), initializer="random_normal", trainable=True)

    def call(self, inputs):
        squareSpeed = tf.math.square(self.speed)
        vibrationMax = tf.math.reduce_max(inputs, axis = 1, keepdims = True)
        inputsSpeed = tf.math.divide(squareSpeed, vibrationMax)
        print(tf.shape(inputsSpeed))
        print(tf.shape(self.w))
        multiplication = tf.multiply(squareSpeed, self.w)

        return tf.matmul(inputsSpeed , self.w) + self.b
        #return multiplication + self.b

And when I try to build this following model

inputs = keras.Input(shape=(500,))
dense = layers.Dense(64, activation="relu")
x = PhysicalLayer(1, rotationSpeed)(inputs)
x = dense(x)
x = layers.Dense(32, activation="relu")(x)
outputs = layers.Dense(1)(x)
modelPhi = keras.Model(inputs=inputs, outputs=outputs, name="model_phi_custom")

I have the following error:

ValueError: Dimensions must be equal, but are 1 and 500 for '{{node physical_layer_34/MatMul}} = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false](physical_layer_34/truediv, physical_layer_34/MatMul/ReadVariableOp)' with input shapes: [?,1], [500,1].

I tried to use multiplication instead of matmul but then for fitting the model, I need to use a batch_size of 500 or i come across this error:

Node: 'gradient_tape/mean_absolute_error/sub/BroadcastGradientArgs'Incompatible shapes: [500,1] vs. [64,1]

How can I fix this ?
Thanks


问:
Why cant I assign $with in the model of both end of the relationship
So I have 2 models in this example that is Gig and GigImage. Here's the Gig model

```<code>class Gig extends Model
{
    use HasFactory, Uuids, SoftDeletes;

    protected $fillable = [...]
    protected $with = ['gigImages'];

    public function gigImages()
    {
        return $this->hasMany(GigImage::class);
    }
}
</code>```

as you can see $with is referencing the GigImage and so far things worked as expected.
The problem comes when i did the same thing for GigImage

```<code>class GigImage extends Model
{
    use HasFactory;

    protected $fillable = ['image', 'gig_id', 'is_thumbnail'];
    protected $with = ['gig'];

    public function gig()
    {
        return $this->belongsTo(Gig::class);
    }
}
</code>```

After I assign the GigImage instance to Gig and tried to execute Gig::first() on tinker it just freezes for a minute and stops working entirely by itself, there's no error message. This occurs when I tried to mention anything related to those two models with any eloquent method. Maybe there's some sort of endless loop going on but I'm not sure what's wrong.

Body:
So I have 2 models in this example that is Gig and GigImage. Here's the Gig model

class Gig extends Model
{
    use HasFactory, Uuids, SoftDeletes;

    protected $fillable = [...]
    protected $with = ['gigImages'];

    public function gigImages()
    {
        return $this->hasMany(GigImage::class);
    }
}

as you can see $with is referencing the GigImage and so far things worked as expected.
The problem comes when i did the same thing for GigImage

class GigImage extends Model
{
    use HasFactory;

    protected $fillable = ['image', 'gig_id', 'is_thumbnail'];
    protected $with = ['gig'];

    public function gig()
    {
        return $this->belongsTo(Gig::class);
    }
}

After I assign the GigImage instance to Gig and tried to execute Gig::first() on tinker it just freezes for a minute and stops working entirely by itself, there's no error message. This occurs when I tried to mention anything related to those two models with any eloquent method. Maybe there's some sort of endless loop going on but I'm not sure what's wrong.


问:
User Defined Special Formats returning same index for two different types
I have a program that is using the Apache POI to determine the Format Index returned for all built-in formats and all user-defined special formats.  The issue I am running into is that there are at least 15 indices that have multiple "Type" that are returning the index.  For example,

In this image, each of these two cells has a different type, e.g. Apache POI > handling Special formats?, but both return the index 164 for User-Defined Special Format.  It would be expected that they would each have a different index #, as they are two different types of values (a number and date).

I understand that the Excel POI returns both of these as an Integer, and that I myself have to determine whether it's a number or a date (I'm doing that by looking at each Format Index and keeping a Map to reference keys); however most other User Defined Indices are one specific type when you look in the Excel dialogue box shown.

I have had the index returned in my program and have compared both types shown in the Excel Special Format dialogue box, and they are different.

Index #164 has the following type within the POI: "$"#,##0_);[Red]\("$"#,##0\).  This kind of renders the index useless because it could either be a number OR a date.  Just wondering if I'm missing an extra step that could delineate it more to find out which of the two it is since the type is really smashing two different types together.


问:
How to compile Python with CFLAGS = "-fno-omit-frame-pointer -mno-omit-leaf-frame-pointer"
I am trying to check perf profiling for python code..

I followed the official documentation.
Updated my python3.10 to python3.12,

I was not able to get function names in the perf report

I tried running the way, documentation said

python -X perf script.py

perf report -g -i perf.data

As expected, didn't get any function names in perf report

Documentation also said to compile Python with CFLAGS of "-fno-omit-frame-pointer -mno-omit-leaf-frame-pointer" to obtain best results - link

checked with the given code, python -m sysconfig | grep 'no-omit-frame-pointer'
there was no output, that means the flag is not set,

How can I set the CFLAG and compile Python ?


问:
How to make a watermark transparent in pypdf?
I'm trying to add a slightly transparent watermark to a bunch of pdf's. The problem is that my watermark only shows up on non-solid white pages (i.e if there is a solid color or a solid white background, the watermark doesn't show). My watermark is a pdf file. This is my code:

```<code>from pathlib import Path
from typing import Union, Literal, List
import pypdf
from pypdf import PdfWriter, PdfReader, PageObject

def watermark(
content_pdf: Path,
stamp_pdf: Path,
pdf_result: Path,
page_indices: Union[Literal["ALL"], List[int]] = "ALL",
):
reader = PdfReader(content_pdf)
if page_indices == "ALL":
    page_indices = list(range(0, len(reader.pages)))

writer = PdfWriter()
reader_stamp = PdfReader(stamp_pdf)

for index in page_indices:
    page = PageObject.create_blank_page(reader_stamp)
    page.merge_page(reader_stamp.pages[0])
    content_page = reader.pages[index]
    mediabox = content_page.mediabox

    page.merge_page(content_page)
    page.mediabox = mediabox
    writer.add_page(page)

with open(pdf_result, "wb") as fp:
    writer.write(fp)

watermark(content_pdf=path/to/pdf.pdf,
stamp_pdf=path/to/watermark.pdf,
pdf_result=path/to/outout/dir )
</code>```

This is the pdf I get as an output. Essentially, the top pdf (where the watermark is in the background) is the result I want, but when there's a solid color in the original pdf the watermark doesn't show.

I have also tried adding the watermark as a stamp (see code below), but naturally the watermark is added on top of the pdf, blocking some of the text.

```<code>from pathlib import Path
from typing import Union, Literal, List

from pypdf import PdfWriter, PdfReader

def stamp(
content_pdf: Path,
stamp_pdf: Path,
pdf_result: Path,
page_indices: Union[Literal["ALL"], List[int]] = "ALL",
):
reader = PdfReader(stamp_pdf)
image_page = reader.pages[0]

writer = PdfWriter()

reader = PdfReader(content_pdf)
if page_indices == "ALL":
    page_indices = list(range(0, len(reader.pages)))
for index in page_indices:
    content_page = reader.pages[index]
    mediabox = content_page.mediabox
    content_page.merge_page(image_page)
    content_page.mediabox = mediabox
    writer.add_page(content_page)

with open(pdf_result, "wb") as fp:
    writer.write(fp)

watermark(content_pdf=path/to/pdf.pdf,
stamp_pdf=path/to/watermark.pdf,
pdf_result=path/to/outout/dir )
</code>```

So my question is, is there a way to modify one of these code snippets so that I get the output I want?

Body:
I'm trying to add a slightly transparent watermark to a bunch of pdf's. The problem is that my watermark only shows up on non-solid white pages (i.e if there is a solid color or a solid white background, the watermark doesn't show). My watermark is a pdf file. This is my code:

from pathlib import Path
from typing import Union, Literal, List
import pypdf
from pypdf import PdfWriter, PdfReader, PageObject

def watermark(
content_pdf: Path,
stamp_pdf: Path,
pdf_result: Path,
page_indices: Union[Literal["ALL"], List[int]] = "ALL",
):
reader = PdfReader(content_pdf)
if page_indices == "ALL":
    page_indices = list(range(0, len(reader.pages)))

writer = PdfWriter()
reader_stamp = PdfReader(stamp_pdf)

for index in page_indices:
    page = PageObject.create_blank_page(reader_stamp)
    page.merge_page(reader_stamp.pages[0])
    content_page = reader.pages[index]
    mediabox = content_page.mediabox

    page.merge_page(content_page)
    page.mediabox = mediabox
    writer.add_page(page)

with open(pdf_result, "wb") as fp:
    writer.write(fp)

watermark(content_pdf=path/to/pdf.pdf,
stamp_pdf=path/to/watermark.pdf,
pdf_result=path/to/outout/dir )

This is the pdf I get as an output. Essentially, the top pdf (where the watermark is in the background) is the result I want, but when there's a solid color in the original pdf the watermark doesn't show.

I have also tried adding the watermark as a stamp (see code below), but naturally the watermark is added on top of the pdf, blocking some of the text.

from pathlib import Path
from typing import Union, Literal, List

from pypdf import PdfWriter, PdfReader

def stamp(
content_pdf: Path,
stamp_pdf: Path,
pdf_result: Path,
page_indices: Union[Literal["ALL"], List[int]] = "ALL",
):
reader = PdfReader(stamp_pdf)
image_page = reader.pages[0]

writer = PdfWriter()

reader = PdfReader(content_pdf)
if page_indices == "ALL":
    page_indices = list(range(0, len(reader.pages)))
for index in page_indices:
    content_page = reader.pages[index]
    mediabox = content_page.mediabox
    content_page.merge_page(image_page)
    content_page.mediabox = mediabox
    writer.add_page(content_page)

with open(pdf_result, "wb") as fp:
    writer.write(fp)

watermark(content_pdf=path/to/pdf.pdf,
stamp_pdf=path/to/watermark.pdf,
pdf_result=path/to/outout/dir )

So my question is, is there a way to modify one of these code snippets so that I get the output I want?


问:
Not getting the same result in Python Tesseract every time I run it
I'm creating a script for reading information in a game, I need to read the usernames of players, the problem is, since some of them have special characters, I can't get the script to get consistent results.

Scaled image 2x

Converting to grayscale

Applying threshold

Eroding the image

I run the script five times and got these results:

```<code>['W lil Clarke', 'uw SlavBoogie', 'W SHADZ']

['W lil Clarke', 'w SlavBoogie', 'Ww SHAD2Z']

['W lil Clarke', 'uw SlavBoogie', 'Ww SHAD']

['W lil Clarke', 'w SlavBoogie', 'Ww SHAD2Z']

['w lil Clarke', 'uw SlavBoogie', 'wW SHADZ']
</code>```

Here's the code

    # Image post-processing

    kernel = np.ones((5, 5), np.uint8)

    name_capture_resized = np.array(name_capture)

    name_capture_resized = cv2.resize(name_capture_resized, None, fx=2, fy=2)

    name_capture_gray = cv2.cvtColor(name_capture_resized, cv2.COLOR_BGR2GRAY)

    name_capture_threshold = cv2.threshold(name_capture_gray, 127, 255, cv2.THRESH_BINARY)[1]

    name_capture_erode = cv2.erode(name_capture_threshold, kernel, iterations=1)

    names = tess.image_to_string(name_capture_erode, config='-c tessedit_char_blacklist=~ﬂ')

```

What can I do to improve the postprocessing and get the same result every time?

Body:
I'm creating a script for reading information in a game, I need to read the usernames of players, the problem is, since some of them have special characters, I can't get the script to get consistent results.

Scaled image 2x

Converting to grayscale

Applying threshold

Eroding the image

I run the script five times and got these results:

['W lil Clarke', 'uw SlavBoogie', 'W SHADZ']

['W lil Clarke', 'w SlavBoogie', 'Ww SHAD2Z']

['W lil Clarke', 'uw SlavBoogie', 'Ww SHAD']

['W lil Clarke', 'w SlavBoogie', 'Ww SHAD2Z']

['w lil Clarke', 'uw SlavBoogie', 'wW SHADZ']

Here's the code

    # Image post-processing

    kernel = np.ones((5, 5), np.uint8)

    name_capture_resized = np.array(name_capture)

    name_capture_resized = cv2.resize(name_capture_resized, None, fx=2, fy=2)

    name_capture_gray = cv2.cvtColor(name_capture_resized, cv2.COLOR_BGR2GRAY)

    name_capture_threshold = cv2.threshold(name_capture_gray, 127, 255, cv2.THRESH_BINARY)[1]

    name_capture_erode = cv2.erode(name_capture_threshold, kernel, iterations=1)

    names = tess.image_to_string(name_capture_erode, config='-c tessedit_char_blacklist=~ﬂ')

What can I do to improve the postprocessing and get the same result every time?


问:
DialogflowSDK nodejs
I am creating Intents using Dialogflow SDK. I am able to create custom follow-up intents and fallback intents. But I am not seeing any format for creating Yes/No intent with all the built-in training phrases.

How can I create  Yes/No follow-up intents with all the built-in training phrases using SDK?

Title: DialogflowSDK nodejs


问:
WebRTC İOS sending data
I want to send mp3 file to the other peer. Once other peer has the audio I want it to be played immediately. How can I send and and do this event

I couldn’t find any solution

Title: WebRTC İOS sending data


问:
Make woocommerce product attribute unremovable?
I have a problem with my Woocommerce. I use my supplier's plugin which very regularly and automatically updates the stock and price of my products. I can, on my supplier's site, request that the product updates of their API linked to my site via their plugin do not erase the titles and descriptions of the products (I modified some of them after adding them ).

Problem: I must add to my products an attribute (example "Color") which is not assigned to them by default (they have two but it is not "Color".)

I can add this attribute to them and define a particular color for them, but when they are updated by my supplier, it overwrites the attributes that were not on my basic products (here the "Color" attribute) .

I wish I could tell their API not to overwrite it, like title or description, but they don't know how to do that..

Do you have an idea ?
I got a start of the trail thanks to this page: https://datafeedrapi.helpscoutdocs.com/article/44-prevent-attributes-from-being-overwritten-during-product-set-updates but the code is for THEIR API and so that the value of an attribute is not erased. For me, it's the ENTIRE attribute that I want to preserve..

Thank you !


问:
Clear an MUI Select value using react-hook-form
I have a dropdown where a user can choose from "Item 1", "Item 2" and "Item 3". There is also a "Reset" button that lets the user clear their choice to make a new one.

Here's my code :

```<code>import React from "react";
import { Button, FormControl, MenuItem, Select } from "@mui/material";
import { Controller, useForm, FormProvider } from "react-hook-form";

export default function App() {
  const methods = useForm();
  const { control, resetField } = methods;
  const dropDownItems = ["Item 1", "Item 2", "Item 3"];

  return (
    <FormProvider {...methods}>
      <form>
        <FormControl sx={{ width: "51%" }}>
          <Controller
            name="firstItem"
            control={control}
            rules={{ required: true }}
            render={({ field }) => (
              <Select {...field} id="firstItem">
                {dropDownItems.map((name) => (
                  <MenuItem key={name} value={name}>
                    {name}
                  </MenuItem>
                ))}
              </Select>
            )}
          />
        </FormControl>
      </form>
      <Button onClick={() => resetField("firstItem")}>Reset</Button>
    </FormProvider>
  );
}
</code>```

I expect the resetField to empty the choice of the dropdown on clicking the reset button. And it does so, but only in the state of the form (and the display does not change). I'm assuming there is something about control that I do not quite understand, but an afternoon of looking around did not let me find the answer.

I also tried using setValue instead of resetField, to no avail.

Link: https://codesandbox.io/s/blue-platform-74tgg8?file=/src/App.js

What am I missing? Thanks for the help :)

Edit: In my use-case, this is part of a bigger form, so using reset to reset the fields entirely does not work for me.

Body:
I have a dropdown where a user can choose from "Item 1", "Item 2" and "Item 3". There is also a "Reset" button that lets the user clear their choice to make a new one.

Here's my code :

import React from "react";
import { Button, FormControl, MenuItem, Select } from "@mui/material";
import { Controller, useForm, FormProvider } from "react-hook-form";

export default function App() {
  const methods = useForm();
  const { control, resetField } = methods;
  const dropDownItems = ["Item 1", "Item 2", "Item 3"];

  return (
    <FormProvider {...methods}>
      <form>
        <FormControl sx={{ width: "51%" }}>
          <Controller
            name="firstItem"
            control={control}
            rules={{ required: true }}
            render={({ field }) => (
              <Select {...field} id="firstItem">
                {dropDownItems.map((name) => (
                  <MenuItem key={name} value={name}>
                    {name}
                  </MenuItem>
                ))}
              </Select>
            )}
          />
        </FormControl>
      </form>
      <Button onClick={() => resetField("firstItem")}>Reset</Button>
    </FormProvider>
  );
}

I expect the resetField to empty the choice of the dropdown on clicking the reset button. And it does so, but only in the state of the form (and the display does not change). I'm assuming there is something about control that I do not quite understand, but an afternoon of looking around did not let me find the answer.

I also tried using setValue instead of resetField, to no avail.

Link: https://codesandbox.io/s/blue-platform-74tgg8?file=/src/App.js

What am I missing? Thanks for the help :)

Edit: In my use-case, this is part of a bigger form, so using reset to reset the fields entirely does not work for me.


问:
How can I optimize a slow MySQL query that uses multiple LEFT JOINs and a GROUP BY clause?
I have a MySQL query that performs several LEFT JOINs on large tables, and then uses a GROUP BY clause to aggregate the results. The query takes a long time to execute and I'm looking for ways to optimize it. Here is the current query:

```<code>SELECT
t1.col1, t2.col2, t3.col3, SUM(t4.col4)
FROM
table1 t1
LEFT JOIN
table2 t2 ON t2.id = t1.table2_id
LEFT JOIN
table3 t3 ON t3.id = t1.table3_id
LEFT JOIN
table4 t4 ON t4.id = t1.table4_id
GROUP BY
t1.id
</code>```

Any suggestions on how to improve the performance of this query would be greatly appreciated. Thank you!

Body:
I have a MySQL query that performs several LEFT JOINs on large tables, and then uses a GROUP BY clause to aggregate the results. The query takes a long time to execute and I'm looking for ways to optimize it. Here is the current query:

SELECT
t1.col1, t2.col2, t3.col3, SUM(t4.col4)
FROM
table1 t1
LEFT JOIN
table2 t2 ON t2.id = t1.table2_id
LEFT JOIN
table3 t3 ON t3.id = t1.table3_id
LEFT JOIN
table4 t4 ON t4.id = t1.table4_id
GROUP BY
t1.id

Any suggestions on how to improve the performance of this query would be greatly appreciated. Thank you!


问:
Azure Front Door routing when secured with Azure b2c
I'm looking at ways to modernise some of our existing web apps without a total rewrite. One idea that's being bandied around is having pluggable modules that can be written in more up to date languages that can be bolted onto the existing webapps.

I tried this out with both an iFrame approach and also using Azure Front Door routing, so that even though I had separate Azure App Services, I managed to get everything to appear as though it was part of the same web app/domain with routing rules.

Unfortunately both these methods failed once I secured the websites using Azure b2c. As an example, I tried to create two bog standard asp.net core mvc apps (deployed in Azure as AppService1 and AppService2). I secured them both using b2c with separate b2c apps. I checked I could log into both apps successfully. Also once I logged into one app, I could go to the other via a different browser tab and didn't need to log in so I knew that SSO was working.

I then tried to embed one app service in the other via an iFrame and got the following error

```<code>Refused to display 'https://xxx.b2clogin.com/' in a frame because it set 'X-Frame-Options' to 'deny'.
</code>```

Didn't pursue this so my next step was to try and use Azure Front Door routing to help me out. I managed to get this working for the top level app service (AppService1) by following this post

Exception: Correlation failed. AAD + Azure Front Door

However, I haven't managed to get the routing to AppService2 working. Here's what I tried

Attempt 1

Added a routing path in front door that used /service2 as 'patterns to match'. AppService2 had the following CallBackPath

```<code>"CallbackPath": "/signin-demo"
</code>```

Used a b2c app which a redirect URL of

```<code>https://<frontdoor url>/signin-demo
</code>```

When I try to go to https://[frontdoor url]/service2 I just get taken to the following URL

```<code>https://<frontdoor url>/signin-demo
</code>```

which doesn't display anything.

Attempt 2

Changed the b2c app to one that used a redirect URL of

```<code>https://<frontdoor url>/signin-oidc
</code>```

which is the callback path of AppService1. Doing so gives the error when going to https://[frontdoor url]/service2

```<code>Unable to unprotect the message.State.
</code>```

So, I'm not sure what to try next. What I'm doing feels like it should be possible but I wonder if anyone could help or work out what I'm doing wrong.

Many thanks

Body:
I'm looking at ways to modernise some of our existing web apps without a total rewrite. One idea that's being bandied around is having pluggable modules that can be written in more up to date languages that can be bolted onto the existing webapps.

I tried this out with both an iFrame approach and also using Azure Front Door routing, so that even though I had separate Azure App Services, I managed to get everything to appear as though it was part of the same web app/domain with routing rules.

Unfortunately both these methods failed once I secured the websites using Azure b2c. As an example, I tried to create two bog standard asp.net core mvc apps (deployed in Azure as AppService1 and AppService2). I secured them both using b2c with separate b2c apps. I checked I could log into both apps successfully. Also once I logged into one app, I could go to the other via a different browser tab and didn't need to log in so I knew that SSO was working.

I then tried to embed one app service in the other via an iFrame and got the following error

Refused to display 'https://xxx.b2clogin.com/' in a frame because it set 'X-Frame-Options' to 'deny'.

Didn't pursue this so my next step was to try and use Azure Front Door routing to help me out. I managed to get this working for the top level app service (AppService1) by following this post

Exception: Correlation failed. AAD + Azure Front Door

However, I haven't managed to get the routing to AppService2 working. Here's what I tried

Attempt 1

Added a routing path in front door that used /service2 as 'patterns to match'. AppService2 had the following CallBackPath

"CallbackPath": "/signin-demo"

Used a b2c app which a redirect URL of

https://<frontdoor url>/signin-demo

When I try to go to https://[frontdoor url]/service2 I just get taken to the following URL

https://<frontdoor url>/signin-demo

which doesn't display anything.

Attempt 2

Changed the b2c app to one that used a redirect URL of

https://<frontdoor url>/signin-oidc

which is the callback path of AppService1. Doing so gives the error when going to https://[frontdoor url]/service2

Unable to unprotect the message.State.

So, I'm not sure what to try next. What I'm doing feels like it should be possible but I wonder if anyone could help or work out what I'm doing wrong.

Many thanks


问:
The chart.js/ng2-charts is not displaying the data given
I've developed a website in Angular 14 that treat about cryptocurrencies using the CoinGecko API.

I wanted to display a chart for every cryptocurrency on a specific page using chart.js and ng2-charts.

I've parsed the data sent by the API and used it in my chart but it is not showing the line chart expected.

Here is a service that is getting the data from the API and parse it:

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {map, Observable, Subscription } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class SingleCryptoGraphService {
  subscription: Subscription;

  doubletab: any = {
    date : Array<string>(),
    price: Array<number>(),
  };

  constructor(private httpClient: HttpClient) {
    this.subscription = Subscription.EMPTY;
  }

HistoricalChart(id: string, currency: string, days: number): Observable<any> {

    return this.httpClient
      .get<any[]>(
        'https://api.coingecko.com/api/v3/coins/'+id+'/market_chart?vs_currency='+currency+'&days='+days+'&interval=daily').pipe(
              map( (obj: any) => obj['prices']),
              map((tab: any[]) => {
                const res = [];
                for (let i = 0; i < tab.length; i++) {
                  this.doubletab.date.push(this.getDate(tab[i][0]));
                  this.doubletab.price.push(this.convertToNumber(tab[i][1]));
                }
                console.log(this.doubletab);
                return this.doubletab;
              }
            )
          );
  }

  getDate = (date: number) : string => {
    let d = new Date(date)
    let day = d.getDate()
    let month = d.getMonth() + 1
    let year = d.getFullYear()
    return day + "/" + month + "/" + year
  }

  convertToNumber = (str: string) : number => {
    return Number(str)
  }
}
</code>```

Here is the chart component TypeScript:

```<code>import { Component, OnDestroy, OnInit, Input, ViewChild } from '@angular/core';
import { SingleCryptoGraphService } from '../single-crypto-graph.service';
import { Subscription } from 'rxjs';
import { Chart, ChartConfiguration, ChartEvent, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';

@Component({
  selector: 'app-crypto-graph',
  templateUrl: './crypto-graph.component.html',
  styleUrls: ['./crypto-graph.component.css']
})
export class CryptoGraphComponent implements OnInit, OnDestroy {

  subscription3: Subscription

  chartInfoTabs: any = {
    date: Array<string>(),
    price: Array<number>(),
  }

   @Input() id = ''

  constructor(private SingleCryptoGraphService:SingleCryptoGraphService) {
    this.subscription3 = Subscription.EMPTY;
    this.id = "none";
  }

  ngOnInit(): void {
    this.subscription3.unsubscribe()

    this.subscription3 = this.SingleCryptoGraphService.HistoricalChart(this.id,"eur",30).subscribe(
      (data) => {
        this.chartInfoTabs.date = data.date;
        this.chartInfoTabs.price = data.price;
      }
    );
  }

  ngOnDestroy() {
    this.subscription3.unsubscribe()
  }

  public lineChartData: ChartConfiguration['data'] = {
    datasets: [{
        data: this.chartInfoTabs.price,
        label: this.id,
        backgroundColor: 'rgba(148,159,177,0.2)',
        borderColor: 'rgba(148,159,177,1)',
        pointBackgroundColor: 'rgba(148,159,177,1)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: 'rgba(148,159,177,0.8)',
        fill: 'origin',
      }],
      labels: this.chartInfoTabs.date,
    }

    public lineChartOptions: ChartConfiguration['options'] = {
      elements: {
        line: {
          tension: 0.5
        }
      },
      scales: {
        y:
          {
            position: 'left',
          },
      },
    };

  public lineChartType: ChartType = 'line';

  @ViewChild(BaseChartDirective) chart?: BaseChartDirective;
}
</code>```

And here is the canvas used to display the chart and the result I got:

```<code><canvas baseChart class="chart"
        [data]="lineChartData"
        [options]="lineChartOptions"
        [type]="lineChartType"
        (chartHover)="chartHovered($event)">
</canvas>
</code>```

What's actually shown by my code

I suspect my tables of data implement the wrong type but I can't figure out why because they seem to be right.

I would really appreciate help with this problem because I really don't understand why it is not working.

Body:
I've developed a website in Angular 14 that treat about cryptocurrencies using the CoinGecko API.

I wanted to display a chart for every cryptocurrency on a specific page using chart.js and ng2-charts.

I've parsed the data sent by the API and used it in my chart but it is not showing the line chart expected.

Here is a service that is getting the data from the API and parse it:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {map, Observable, Subscription } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class SingleCryptoGraphService {
  subscription: Subscription;

  doubletab: any = {
    date : Array<string>(),
    price: Array<number>(),
  };

  constructor(private httpClient: HttpClient) {
    this.subscription = Subscription.EMPTY;
  }

HistoricalChart(id: string, currency: string, days: number): Observable<any> {

    return this.httpClient
      .get<any[]>(
        'https://api.coingecko.com/api/v3/coins/'+id+'/market_chart?vs_currency='+currency+'&days='+days+'&interval=daily').pipe(
              map( (obj: any) => obj['prices']),
              map((tab: any[]) => {
                const res = [];
                for (let i = 0; i < tab.length; i++) {
                  this.doubletab.date.push(this.getDate(tab[i][0]));
                  this.doubletab.price.push(this.convertToNumber(tab[i][1]));
                }
                console.log(this.doubletab);
                return this.doubletab;
              }
            )
          );
  }

  getDate = (date: number) : string => {
    let d = new Date(date)
    let day = d.getDate()
    let month = d.getMonth() + 1
    let year = d.getFullYear()
    return day + "/" + month + "/" + year
  }

  convertToNumber = (str: string) : number => {
    return Number(str)
  }
}

Here is the chart component TypeScript:

import { Component, OnDestroy, OnInit, Input, ViewChild } from '@angular/core';
import { SingleCryptoGraphService } from '../single-crypto-graph.service';
import { Subscription } from 'rxjs';
import { Chart, ChartConfiguration, ChartEvent, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';

@Component({
  selector: 'app-crypto-graph',
  templateUrl: './crypto-graph.component.html',
  styleUrls: ['./crypto-graph.component.css']
})
export class CryptoGraphComponent implements OnInit, OnDestroy {

  subscription3: Subscription

  chartInfoTabs: any = {
    date: Array<string>(),
    price: Array<number>(),
  }

   @Input() id = ''

  constructor(private SingleCryptoGraphService:SingleCryptoGraphService) {
    this.subscription3 = Subscription.EMPTY;
    this.id = "none";
  }

  ngOnInit(): void {
    this.subscription3.unsubscribe()

    this.subscription3 = this.SingleCryptoGraphService.HistoricalChart(this.id,"eur",30).subscribe(
      (data) => {
        this.chartInfoTabs.date = data.date;
        this.chartInfoTabs.price = data.price;
      }
    );
  }

  ngOnDestroy() {
    this.subscription3.unsubscribe()
  }

  public lineChartData: ChartConfiguration['data'] = {
    datasets: [{
        data: this.chartInfoTabs.price,
        label: this.id,
        backgroundColor: 'rgba(148,159,177,0.2)',
        borderColor: 'rgba(148,159,177,1)',
        pointBackgroundColor: 'rgba(148,159,177,1)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: 'rgba(148,159,177,0.8)',
        fill: 'origin',
      }],
      labels: this.chartInfoTabs.date,
    }

    public lineChartOptions: ChartConfiguration['options'] = {
      elements: {
        line: {
          tension: 0.5
        }
      },
      scales: {
        y:
          {
            position: 'left',
          },
      },
    };

  public lineChartType: ChartType = 'line';

  @ViewChild(BaseChartDirective) chart?: BaseChartDirective;
}

And here is the canvas used to display the chart and the result I got:

<canvas baseChart class="chart"
        [data]="lineChartData"
        [options]="lineChartOptions"
        [type]="lineChartType"
        (chartHover)="chartHovered($event)">
</canvas>

What's actually shown by my code

I suspect my tables of data implement the wrong type but I can't figure out why because they seem to be right.

I would really appreciate help with this problem because I really don't understand why it is not working.


问:
WinUI3 does not launch when launched from other system languages unless en-US is installed
Background: I am switching from WPF to WinUi3. The WinUI3 application works on en-US systems without any problems but requires en-US language to be installed on systems like ru-RU Russian.

I tried adding languages from this Windows Documentation "Localize your WinUI3 app" https://learn.microsoft.com/en-us/windows/apps/winui/winui3/localize-winui3-app

I don't think that is the solution.

I think I need en-US installed because the program is uses English language in its design. It fails to launch when used on a system with only ru-RU language installed in Windows. I am guessing en-US must be a requirement?

WPF is fine but WinUI3 requires en-US. Is there a possibility WinUI3 can work like WPF did?


问:
How to use Azure AD to authentication customer access to SaaS product
We developing a SaaS product and currently looking at how to secure access to it. We will be deploying the product to MS Azure so are investigating the use of Azure AD to provide the authentication and authorisation framework.

From the research that has been done so far, it would look like the 'client credentials' flow would be a good fit. We've developed a test application using Microsoft Documentation to register a 'test server app' and 'test client app' in Azure AD which has delivered the required functionality, using scopes to limit access to actions in the API.

What we can't find is an obvious solution to how we scale this to authenticate a 'customer test client app'.  From its documentation Azure Active Directory B2C seems to offer the required functionality, but all the examples that we've found have both the 'server app' and 'client app' in the same AD Tenancy rather than the 'client app' being a third-party customer.

Have we mis-understood the  Azure Active Directory B2C?
What Azure AD based solution would provide us with the functionality of authenticating licenced-customers?


问:
Combobox break when dragging the window
This is a bug I was avoiding to check , but it comes the time do fix it but can't find the reason.

It's simple, having a combobox inside a form, thats inside a windows, when opening the combobox and them dragging the window, the combox got desformatted.

Is this a bug, anyone with this kind of stuff and know how to solve it?

Using extjs 6.0.1

Fiddle link:
https://fiddle.sencha.com/#view/editor&fiddle/3mek

Title: Combobox break when dragging the window


问:
VBS code is finding the file with oFSO.FileExist but giving an error = 1004 when trying to run Application.Run
Good evening. I'm trying to schedule an excel macro through task scheduler. I've got the below code written for opening the excel file and running the code however it's kicking out an error when it's hitting the Application.Run step.

Does anyone have any ideas where i'm going wrong?

```<code>On Error Resume Next

Set oFSO = CreateObject("Scripting.FileSystemObject")

set oFile = oFSO.CreateTextFile("c:\scripts\log.txt")

Set oExcel = WScript.CreateObject("Excel.Application")

If oFSO.FileExist("C:\scripts\Excel Files\my_excel_file.xlsm") then
    oFile.WriteLine "File Exists"
    oExcel.Application.Run "'C:\scripts\Excel Files\my_excel_file.xlsm'!RefreshAll"
    if err.number <> 0 then
        oFile.WriteLine "error = " & err.number & " " & err.description
    end if
Else
    oFile.WriteLine "File does not exist"
End If

oExcel.Application.close
</code>```

I originally had the file on a network drive which I thought would be the issue so i've moved it to the C: Drive on a remote desktop to try and counter that issue.

I initially thought it was a task scheduler issue, however the log is being filled out which tells me there's something else going on. I've set up the action as the attached image.

Body:
Good evening. I'm trying to schedule an excel macro through task scheduler. I've got the below code written for opening the excel file and running the code however it's kicking out an error when it's hitting the Application.Run step.

Does anyone have any ideas where i'm going wrong?

On Error Resume Next

Set oFSO = CreateObject("Scripting.FileSystemObject")

set oFile = oFSO.CreateTextFile("c:\scripts\log.txt")

Set oExcel = WScript.CreateObject("Excel.Application")

If oFSO.FileExist("C:\scripts\Excel Files\my_excel_file.xlsm") then
    oFile.WriteLine "File Exists"
    oExcel.Application.Run "'C:\scripts\Excel Files\my_excel_file.xlsm'!RefreshAll"
    if err.number <> 0 then
        oFile.WriteLine "error = " & err.number & " " & err.description
    end if
Else
    oFile.WriteLine "File does not exist"
End If

oExcel.Application.close

I originally had the file on a network drive which I thought would be the issue so i've moved it to the C: Drive on a remote desktop to try and counter that issue.

I initially thought it was a task scheduler issue, however the log is being filled out which tells me there's something else going on. I've set up the action as the attached image.


问:
Redocly File References With Different Wording?
We have references in the OpenAPI to separate files, like described below. The problem is the description should be different in many cases but only by one word. For instance, in some cases it's "business unit", others as "consumer unit", and so on.

My question is, is it possible to pass in different words without having to create different files? How do others handle this case?

In the OpenAPI file:

```<code>consumerId:
  $ref: 'components/schemas/consumerid.yaml'
</code>```

The (truncated) destination file:

```<code>type: string
description: |
  Specifies the business unit.
example: 49304
</code>```

Body:
We have references in the OpenAPI to separate files, like described below. The problem is the description should be different in many cases but only by one word. For instance, in some cases it's "business unit", others as "consumer unit", and so on.

My question is, is it possible to pass in different words without having to create different files? How do others handle this case?

In the OpenAPI file:

consumerId:
  $ref: 'components/schemas/consumerid.yaml'

The (truncated) destination file:

type: string
description: |
  Specifies the business unit.
example: 49304


问:
Ruby on Rails: db:schema:load fails due foreign key
okay,

I've been trying to wrap my head around this problem for a while, and I simply cannot come up with an explanation why this behavior is happening.
I have a project that's running Ruby 2.7, Ruby on Rails 5.2.8.1.

On a new system, I'm trying to set up the database using a MySQL 5.7 database, and every time I run bundle exec rake db:create db:schema:load it fails because of a Foreign Key error. And the weird part is that it tries to create the Foreign Key before the actual tables, which is what doesn't make any sense to me as the add_foreign_key statement is the last statement in the schema.rb.

Simplified schema.rb

```<code>ActiveRecord::Schema.define(version: 20211230212616) do

  create_table "categories", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" do |t|
    t.integer "category_id", null: false
    t.string "subtitle"
    t.text "page_content"
    t.text "pinned_styles"
    t.text "unpinned_styles"
    t.text "updated_by"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["category_id"], name: "index_categories_on_category_id", unique: true
  end

  create_table "faqs", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" do |t|
    t.text "question"
    t.text "answer"
    t.bigint "category_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["category_id"], name: "index_faqs_on_category_id"
  end

  add_foreign_key "faqs", "categories"
end
</code>```

Error Message

```<code>bundle exec db:drop db:create db:schema:load

-- create_table("categories", {:force=>:cascade, :options=>"ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"})
rake aborted!
ActiveRecord::StatementInvalid: Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails: DROP TABLE IF EXISTS `categories` CASCADE
/Users/olivar/RubymineProjects/catalog/db/schema.rb:15:in `block in <main>'
/Users/olivar/RubymineProjects/catalog/db/schema.rb:13:in `<main>'
/Users/olivar/.rbenv/versions/2.7.2/bin/bundle:25:in `load'
/Users/olivar/.rbenv/versions/2.7.2/bin/bundle:25:in `<main>'

Caused by:
Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails
/Users/olivar/RubymineProjects/catalog/db/schema.rb:15:in `block in <main>'
/Users/olivar/RubymineProjects/catalog/db/schema.rb:13:in `<main>'
/Users/olivar/.rbenv/versions/2.7.2/bin/bundle:25:in `load'
/Users/olivar/.rbenv/versions/2.7.2/bin/bundle:25:in `<main>'
Tasks: TOP => db:schema:load
</code>```

Yet, every time the command fails because it creates the categories table, then it tries the foreign key, without the faqs table existing (or switches the tables).

Can someone explain this behavior?

Body:
okay,

I've been trying to wrap my head around this problem for a while, and I simply cannot come up with an explanation why this behavior is happening.
I have a project that's running Ruby 2.7, Ruby on Rails 5.2.8.1.

On a new system, I'm trying to set up the database using a MySQL 5.7 database, and every time I run bundle exec rake db:create db:schema:load it fails because of a Foreign Key error. And the weird part is that it tries to create the Foreign Key before the actual tables, which is what doesn't make any sense to me as the add_foreign_key statement is the last statement in the schema.rb.

Simplified schema.rb

ActiveRecord::Schema.define(version: 20211230212616) do

  create_table "categories", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" do |t|
    t.integer "category_id", null: false
    t.string "subtitle"
    t.text "page_content"
    t.text "pinned_styles"
    t.text "unpinned_styles"
    t.text "updated_by"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["category_id"], name: "index_categories_on_category_id", unique: true
  end

  create_table "faqs", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" do |t|
    t.text "question"
    t.text "answer"
    t.bigint "category_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["category_id"], name: "index_faqs_on_category_id"
  end

  add_foreign_key "faqs", "categories"
end

Error Message

bundle exec db:drop db:create db:schema:load

-- create_table("categories", {:force=>:cascade, :options=>"ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"})
rake aborted!
ActiveRecord::StatementInvalid: Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails: DROP TABLE IF EXISTS `categories` CASCADE
/Users/olivar/RubymineProjects/catalog/db/schema.rb:15:in `block in '
/Users/olivar/RubymineProjects/catalog/db/schema.rb:13:in `'
/Users/olivar/.rbenv/versions/2.7.2/bin/bundle:25:in `load'
/Users/olivar/.rbenv/versions/2.7.2/bin/bundle:25:in `'

Caused by:
Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails
/Users/olivar/RubymineProjects/catalog/db/schema.rb:15:in `block in '
/Users/olivar/RubymineProjects/catalog/db/schema.rb:13:in `'
/Users/olivar/.rbenv/versions/2.7.2/bin/bundle:25:in `load'
/Users/olivar/.rbenv/versions/2.7.2/bin/bundle:25:in `'
Tasks: TOP => db:schema:load

Yet, every time the command fails because it creates the categories table, then it tries the foreign key, without the faqs table existing (or switches the tables).

Can someone explain this behavior?


问:
EF cannot insert entity because key value for {'Id'} is already being tracked
I'm trying to write some tests around my Entity Framework code, an as part of the isolation of logic, I'm inserting a model into the database like this:

```<code>_context.Database.ExecuteSqlInterpolated(
                $@"INSERT INTO MyModel(Id, Name, PostTown)
                   VALUES({Id}, {myModel.Name}, {myModel.PostTown});");
</code>```

I have several tests based around reading this entity using _contest.Set<MyModel>().Find() which all work as expected.

I'm now trying to write a test to ensure my update methods work, the test looks something like this:

```<code>MyModel myModel = new Model("AName", "ATown");

_context.Database.ExecuteSqlInterpolated(
                $@"INSERT INTO MyModel(Id, Name, PostTown)
                   VALUES({myModel.Id}, {myModel..Name}, {intermediary.PostTown});");

...

_context.Set<MyModel>.Update(myModel);
await _context.SaveChangesAsync();
</code>```

However the update fails with an error:

The instance of entity type 'MyModel' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

Do I need to do something after my SQL insert to get EF to recognise the entity?

Body:
I'm trying to write some tests around my Entity Framework code, an as part of the isolation of logic, I'm inserting a model into the database like this:

_context.Database.ExecuteSqlInterpolated(
                $@"INSERT INTO MyModel(Id, Name, PostTown)
                   VALUES({Id}, {myModel.Name}, {myModel.PostTown});");

I have several tests based around reading this entity using _contest.Set<MyModel>().Find() which all work as expected.

I'm now trying to write a test to ensure my update methods work, the test looks something like this:

MyModel myModel = new Model("AName", "ATown");

_context.Database.ExecuteSqlInterpolated(
                $@"INSERT INTO MyModel(Id, Name, PostTown)
                   VALUES({myModel.Id}, {myModel..Name}, {intermediary.PostTown});");

...

_context.Set<MyModel>.Update(myModel);
await _context.SaveChangesAsync();

However the update fails with an error:

The instance of entity type 'MyModel' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

Do I need to do something after my SQL insert to get EF to recognise the entity?


问:
How to add a different labels
I am new in Tableau and I couldn't find a solution so I am searching help here.

Problem:
I have a chart that looks like below:

I need to add to the brighter blue bars a string "Start" and to the dark blue string "End". Unfortunately when I click on "Label" I change for all. Do you know how I could do that?

Regards
Tomasz

Title: How to add a different labels


问:
Not sure how I can end the else statement here
I am trying to add some logic to a link so that I can have a toggle between states

In the HTML I am using some nunjucks to set the content for the link in the page template. This works:

```<code>prototypeLinks = [{href: 'thispage?from=indexpage', text: 'Reset the list of options'} if data['from'] == 'contentpage'] %}
</code>```

But when I try to add an else if to create the toggle, it doesn't work:

```<code>prototypeLinks = [{href: 'thispage?from=indexpage', text: 'Reset the list of options'} if data['from'] == 'contentpage'] else { href: 'thispage?from=indexpage', text: 'Reduce the options' } endif %}
</code>```

When I run it I get:

```<code>[Line 5, Column 131] expected block end in set statement
</code>```

It feels like there is a way to add the expected block end.

Body:
I am trying to add some logic to a link so that I can have a toggle between states

In the HTML I am using some nunjucks to set the content for the link in the page template. This works:

prototypeLinks = [{href: 'thispage?from=indexpage', text: 'Reset the list of options'} if data['from'] == 'contentpage'] %}

But when I try to add an else if to create the toggle, it doesn't work:

prototypeLinks = [{href: 'thispage?from=indexpage', text: 'Reset the list of options'} if data['from'] == 'contentpage'] else { href: 'thispage?from=indexpage', text: 'Reduce the options' } endif %}

When I run it I get:

[Line 5, Column 131] expected block end in set statement

It feels like there is a way to add the expected block end.


问:
Fatal error: __autoload() is no longer supported, use spl_autoload_register() instead in /home/storage/736/3736736/user/htdocs/wp-includes/compat.php
My wordpress website is getting the below error:

Fatal error: __autoload() is no longer supported, use spl_autoload_register() instead in /home/storage/736/3736736/user/htdocs/wp-includes/compat.php on line 502

From review of other tickets I updated line 502 with:

```<code>function spl_autoload_register( $classname ) {
    ...
}
</code>```

However I now get the below error:

Warning: Private methods cannot be final as they are never overridden by other classes in /home/storage/736/3736736/user/htdocs/wp-includes/class-wp-session-tokens.php on line 71

Deprecated: Required parameter $tt_id follows optional parameter $object_id in /home/storage/736/3736736/user/htdocs/wp-includes/nav-menu.php on line 931

Deprecated: Required parameter $taxonomy follows optional parameter $object_id in /home/storage/736/3736736/user/htdocs/wp-includes/nav-menu.php on line 931

Fatal error: Uncaught Error: Call to undefined function create_function() in /home/storage/736/3736736/user/htdocs/wp-content/plugins/LayerSlider/layerslider.php:69 Stack trace: #0 /home/storage/736/3736736/user/htdocs/wp-settings.php(303): include_once() #1 /home/storage/736/3736736/user/htdocs/wp-config.php(81): require_once('/home/storage/7...') #2 /home/storage/736/3736736/user/htdocs/wp-load.php(37): require_once('/home/storage/7...') #3 /home/storage/736/3736736/user/htdocs/wp-blog-header.php(13): require_once('/home/storage/7...') #4 /home/storage/736/3736736/user/htdocs/index.php(17): require('/home/storage/7...') #5 {main} thrown in /home/storage/736/3736736/user/htdocs/wp-content/plugins/LayerSlider/layerslider.php on line 69

I am using WordPress.

Can anyone please help?

Body:
My wordpress website is getting the below error:

Fatal error: __autoload() is no longer supported, use spl_autoload_register() instead in /home/storage/736/3736736/user/htdocs/wp-includes/compat.php on line 502

From review of other tickets I updated line 502 with:

function spl_autoload_register( $classname ) {
    ...
}

However I now get the below error:

Warning: Private methods cannot be final as they are never overridden by other classes in /home/storage/736/3736736/user/htdocs/wp-includes/class-wp-session-tokens.php on line 71

Deprecated: Required parameter $tt_id follows optional parameter $object_id in /home/storage/736/3736736/user/htdocs/wp-includes/nav-menu.php on line 931

Deprecated: Required parameter $taxonomy follows optional parameter $object_id in /home/storage/736/3736736/user/htdocs/wp-includes/nav-menu.php on line 931

Fatal error: Uncaught Error: Call to undefined function create_function() in /home/storage/736/3736736/user/htdocs/wp-content/plugins/LayerSlider/layerslider.php:69 Stack trace: #0 /home/storage/736/3736736/user/htdocs/wp-settings.php(303): include_once() #1 /home/storage/736/3736736/user/htdocs/wp-config.php(81): require_once('/home/storage/7...') #2 /home/storage/736/3736736/user/htdocs/wp-load.php(37): require_once('/home/storage/7...') #3 /home/storage/736/3736736/user/htdocs/wp-blog-header.php(13): require_once('/home/storage/7...') #4 /home/storage/736/3736736/user/htdocs/index.php(17): require('/home/storage/7...') #5 {main} thrown in /home/storage/736/3736736/user/htdocs/wp-content/plugins/LayerSlider/layerslider.php on line 69

I am using WordPress.

Can anyone please help?


问:
Remove elements created by jquery
I'm trying to create delete button which can remove elements in html code and which elements I created by jquery, but no luck. I thought the reason it's not working is because elements  have not yet been added to the DOM, but I created a button with only function delete last child and it's work. My first delete button have animation properties. Look at this:</p>
```<code>//Button add element to html code
$('#projects input:button').click(function(){
        var name = $("#projects input:text").eq(0).val();
        var link = $("#projects input:text").eq(1).val();

        if (name === "") {
            name = $("#projects input:text").eq(0).attr("placeholder");
        }

        if (link === "") {
            link = $("#projects input:text").eq(1).attr("placeholder");
        }

        icon_place = '<img src="' + icon + '" alt="">';
        if (icon === undefined) {
            icon_place = '<img style="background-color: black">';
        }

        bg_place = 'background-image: url('+ bg +')';
        if (bg === undefined) {
            bg_place = 'background-color: red';
        }

        var ic4 = '<div class="item_card bg hover" style="'+ bg_place +'"><div class="delete"><img src="" alt=""></div><a href="' + link +'"></a>' + icon_place + '<span class="name">' + name + '</span></div>';
        $('.column').append(ic4);

        $('.delete').css('display','none');

        if ( a % 2 != 0) {
            a--;
            $('#change').attr('value','Изменить');
        }
});

//New delete button
$('#dl-other').click(function(){
        $('.item_card').last().remove();
    });

//My first delete button, it's work great with elements which in html code already been
$('.delete').click(function(){
        var kek = $(this).parent();

        kek.animate({opacity: 0, bottom: "+=16"}, 64).delay(128).hide(128, function(){ kek.remove()});
});
</code>```

Title: Remove elements created by jquery

Body:
I'm trying to create delete button which can remove elements in html code and which elements I created by jquery, but no luck. I thought the reason it's not working is because elements  have not yet been added to the DOM, but I created a button with only function delete last child and it's work. My first delete button have animation properties. Look at this:

//Button add element to html code
$('#projects input:button').click(function(){
        var name = $("#projects input:text").eq(0).val();
        var link = $("#projects input:text").eq(1).val();

        if (name === "") {
            name = $("#projects input:text").eq(0).attr("placeholder");
        }

        if (link === "") {
            link = $("#projects input:text").eq(1).attr("placeholder");
        }

        icon_place = '';
        if (icon === undefined) {
            icon_place = '';
        }

        bg_place = 'background-image: url('+ bg +')';
        if (bg === undefined) {
            bg_place = 'background-color: red';
        }

        var ic4 = '

' + icon_place + '' + name + '
';
        $('.column').append(ic4);

        $('.delete').css('display','none');

        if ( a % 2 != 0) {
            a--;
            $('#change').attr('value','Изменить');
        }
});

//New delete button
$('#dl-other').click(function(){
        $('.item_card').last().remove();
    });

//My first delete button, it's work great with elements which in html code already been
$('.delete').click(function(){
        var kek = $(this).parent();

        kek.animate({opacity: 0, bottom: "+=16"}, 64).delay(128).hide(128, function(){ kek.remove()});
});


问:
Failing to Install ROS apt packages on clean Ubuntu
On a machine running a just installed Ubuntu 20.04.5 OS,
I'm trying to install some packages, specifically the ROS framework.

The process fails in step 1.4 of such (taken from the ROS install guide):
enter image description here

after running the sudo apt install ros-noetic-desktop-full I get the following output:

```<code>ros-noetic-desktop-full : Depends: ros-noetic-desktop but it is not going to be installed
                           Depends: ros-noetic-perception but it is not going to be installed
                           Depends: ros-noetic-simulators but it is not going to be installed
                           Depends: ros-noetic-urdf-sim-tutorial but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

I should say that the first time I did this, I set the package server for software download to 'main server' instead of the regional server automatically assigned and set the update request to 'Never', and got the message

```<code>error while refreshing cache ubuntu pk-client-error-quark
</code>```

I have tried fixing the broken dependencies with the apt commands, I've google the problem and the terminal output but haven't been able to solve the problem.

I ran into this problem in two different machines, and when tried to replicate in a VM with 'Boxes' inside my dev-machine I didn't face the same issue.

I should also add that I am not a Linux expert by any means, and that I might have done or do something that's beyond me yet. However, any suggestions/explanations are highly welcomed.

best regards

Body:
On a machine running a just installed Ubuntu 20.04.5 OS,
I'm trying to install some packages, specifically the ROS framework.

The process fails in step 1.4 of such (taken from the ROS install guide):
enter image description here

after running the sudo apt install ros-noetic-desktop-full I get the following output:

ros-noetic-desktop-full : Depends: ros-noetic-desktop but it is not going to be installed
                           Depends: ros-noetic-perception but it is not going to be installed
                           Depends: ros-noetic-simulators but it is not going to be installed
                           Depends: ros-noetic-urdf-sim-tutorial but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I should say that the first time I did this, I set the package server for software download to 'main server' instead of the regional server automatically assigned and set the update request to 'Never', and got the message

error while refreshing cache ubuntu pk-client-error-quark

I have tried fixing the broken dependencies with the apt commands, I've google the problem and the terminal output but haven't been able to solve the problem.

I ran into this problem in two different machines, and when tried to replicate in a VM with 'Boxes' inside my dev-machine I didn't face the same issue.

I should also add that I am not a Linux expert by any means, and that I might have done or do something that's beyond me yet. However, any suggestions/explanations are highly welcomed.

best regards


问:
Delay displaying array objects multiple hours after created
I've got a project in React that I'm working on where I create events based on TV shows. Obviously, with how timezones and air times work in the US we have a show that airs 8pm ET/PT which means it airs at 8pm eastern and 8pm pacific, but 8pm pacific is actually 3 hours after 8pm eastern. So whenever a user in eastern time zone visits my page I'm creating those events as they happen live and the user sees them as they come in. By the time the TV show airs in pacific time I will already have all of the events logged, but want it to feel like they are being logged in real time like the eastern time user.

Do I just need to use setInterval to check the existing array that I have every couple seconds to see if anything in that array should be shown.

I'm sorry if this is super confusing, but basically I have an existing array with created at times and want to delay showing them to a pacific time user based on how long ago that array item was created.


问:
Metro bundles error in Visual studio showing error as shown in image below
this is screenshot of error showning my visual studio code

Code shows error  when' try to open metro bundler  with web and android , by pressing 'w'for web and 'a' for android . I have tried to find solution from web  many times but didnot succeed.
I tried to change port to 80 in inblound in  window firewall .An anyone help me to resolving this error.


问:
Can't fetchdata with useEffect in a product component
hello everyone I am aking a MERN project and Im running into a peobleme.
so Im using redux toolkit slice and when I try to dispatch the fetchProduct like so

```<code>import React, { useEffect, useState } from "react";
import "./products.css";
import { useSelector, useDispatch } from "react-redux";
import { DataGrid } from "@mui/x-data-grid";
import { Link, Navigate } from "react-router-dom";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import Loader from "components/Loader";
import { Button } from "@mui/material";
import { useNavigate } from "react-router-dom";
import Message from "components/Message";
import { fetchProducts } from "slices/productSlice";

const Products = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const { loading, error, products } = useSelector((state) => state.product);

  useEffect(() => {
    dispatch(fetchProducts());
  }, [dispatch]);

  const columns = [
    { field: "_id", hide: true },
    {
      field: "name",
      flex: 1,
      headerName: "Product",
      width: 200,
      renderCell: (params) => {
        return (
          <div className="productListItem">
            <img className="productListImg" src={params.row.image} alt="" />
            {params.row.name}
          </div>
        );
      },
    },
    { field: "countInStock", headerName: "Stock", flex: 1 },
    {
      field: "price",
      headerName: "Price",
      flex: 1,
    },
    {
      field: "brand",
      headerName: "Brand",
      flex: 1,
    },
    {
      field: "action",
      headerName: "Action",
      flex: 1,
      renderCell: (params) => {
        return (
          <>
            <Link to={"/products/" + params.row._id}>
              <button className="productListEdit">Edit</button>
            </Link>
            <DeleteForeverIcon
              className="productListDelete"
              // onClick={() => deleteHandler(params.row._id)}
            />
          </>
        );
      },
    },
  ];

  return (
    <div style={{ height: "90vh" }}>
      {loading ? (
        <Loader />
      ) : error ? (
        <Message variant="error" />
      ) : (
        <DataGrid
          height={100}
          getRowId={(row) => row._id}
          rows={products?.products}
          disableSelectionOnClick
          columns={columns}
          rowsPerPageOptions={[10, 15, 20]}
          pageSize={10}
          checkboxSelection
        />
      )}

    </div>
  );
};

export default Products;

</code>```

the data never get fetched and I get this error in the browser:
"Warning: Failed prop type: The prop rows is marked as required in ForwardRef(DataGrid), but its value is undefined."

but when I remove what's inside the return of the componenet and add just an h1 tag the data get fetched and I can find it in redux store states

this is the slice I am working with :

```<code>import axios from 'axios';
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  products: [],
  loading: false,
  error: null
};
const baseurl = "http://localhost:5001"

const productSlice = createSlice({
  name: 'product',
  initialState,
  reducers: {
    fetchProductsStart(state) {
      state.loading = true;
    },
    fetchProductsSuccess(state, action) {
      state.products = action.payload;
      state.loading = false;
      state.error = null;
    },
    fetchProductsError(state, action) {
      state.loading = false;
      state.error = action.payload;
    },
    deleteProductStart(state) {
      state.loading = true;
    },
    deleteProductSuccess(state, action) {
      state.products = state.products.filter(product => product._id !== action.payload);
      state.loading = false;
      state.error = null;
    },
    deleteProductError(state, action) {
      state.loading = false;
      state.error = action.payload;
    },
    updateProductStart(state) {
      state.loading = true;
    },
    updateProductSuccess(state, action) {
      const index = state.products.findIndex(product => product._id === action.payload._id);
      state.products[index] = action.payload;
      state.loading = false;
      state.error = null;
    },
    updateProductError(state, action) {
      state.loading = false;
      state.error = action.payload;
    },
    fetchProductStart(state) {
      state.loading = true;
    },
    fetchProductSuccess(state, action) {
      state.products = [action.payload];
      state.loading = false;
      state.error = null;
    },
    fetchProductError(state, action) {
      state.loading = false;
      state.error = action.payload;
    }
  }
});

export const {
  fetchProductsStart,
  fetchProductsSuccess,
  fetchProductsError,
  deleteProductStart,
  deleteProductSuccess,
  deleteProductError,
  updateProductStart,
  updateProductSuccess,
  updateProductError,
  fetchProductStart,
  fetchProductSuccess,
  fetchProductError
} = productSlice.actions;
export default productSlice.reducer

export const fetchProducts = () => async dispatch => {
  try {
    dispatch(fetchProductsStart());
    const response = await axios.get(`${baseurl}/products`);
    dispatch(fetchProductsSuccess(response.data));
  } catch (error) {
    dispatch(fetchProductsError(error.message));
  }
};

export const deleteProduct = id => async dispatch => {
  try {
    dispatch(deleteProductStart());
    await axios.delete(`${baseurl}/products/${id}`);
    dispatch(deleteProductSuccess(id));
  } catch (error) {
    dispatch(deleteProductError(error.message));
  }
};

export const updateProduct = product => async dispatch => {
  try {
    dispatch(updateProductStart());
    const response = await axios.patch(`${baseurl}/products/${product._id}`, product);
    dispatch(updateProductSuccess(response.data));
  } catch (error) {
    dispatch(updateProductError(error.message));
  }
};

</code>```

so what am I doing wrrong here

the modified Slice

```<code>import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

const initialState = {
  products: [],
  loading: 'idle',
  error: null
};

const baseurl = 'http://localhost:5001';

export const fetchProducts = createAsyncThunk(
  'products/fetchProducts',
  async () => {
    const response = await axios.get(`${baseurl}/products`);
    return response.data;
  }
);

export const deleteProduct = createAsyncThunk(
  'products/deleteProduct',
  async id => {
    await axios.delete(`${baseurl}/products/${id}`);
    return id;
  }
);

export const updateProduct = createAsyncThunk(
  'products/updateProduct',
  async product => {
    const response = await axios.patch(
      `${baseurl}/products/${product._id}`,
      product
    );
    return response.data;
  }
);

export const fetchProduct = createAsyncThunk(
  'products/fetchProduct',
  async id => {
    const response = await axios.get(`${baseurl}/products/${id}`);
    return response.data;
  }
)

const productSlice = createSlice({
  name: 'products',
  initialState,
  reducers: {},
  extraReducers: {
    [fetchProducts.pending]: state => {
      state.loading = 'pending';
    },
    [fetchProducts.fulfilled]: (state, action) => {
      state.loading = 'idle';
      state.products = action.payload;
    },
    [fetchProducts.rejected]: (state, action) => {
      state.loading = 'idle';
      state.error = action.error.message;
    },
    [deleteProduct.pending]: state => {
      state.loading = 'pending';
    },
    [deleteProduct.fulfilled]: (state, action) => {
      state.loading = 'idle';
      state.products = state.products.filter(product => product._id !== action.payload);
    },
    [deleteProduct.rejected]: (state, action) => {
      state.loading = 'idle';
      state.error = action.error.message;
    },
    [updateProduct.pending]: state => {
      state.loading = 'pending';
    },
    [updateProduct.fulfilled]: (state, action) => {
      state.loading = 'idle';
      const index = state.products.findIndex(product => product._id === action.payload._id);
      state.products[index] = action.payload;
    },
    [updateProduct.rejected]: (state, action) => {
      state.loading = 'idle';
      state.error = action.error.message

</code>```

Body:
hello everyone I am aking a MERN project and Im running into a peobleme.
so Im using redux toolkit slice and when I try to dispatch the fetchProduct like so

import React, { useEffect, useState } from "react";
import "./products.css";
import { useSelector, useDispatch } from "react-redux";
import { DataGrid } from "@mui/x-data-grid";
import { Link, Navigate } from "react-router-dom";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import Loader from "components/Loader";
import { Button } from "@mui/material";
import { useNavigate } from "react-router-dom";
import Message from "components/Message";
import { fetchProducts } from "slices/productSlice";

const Products = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const { loading, error, products } = useSelector((state) => state.product);

  useEffect(() => {
    dispatch(fetchProducts());
  }, [dispatch]);

  const columns = [
    { field: "_id", hide: true },
    {
      field: "name",
      flex: 1,
      headerName: "Product",
      width: 200,
      renderCell: (params) => {
        return (

            {params.row.name}

        );
      },
    },
    { field: "countInStock", headerName: "Stock", flex: 1 },
    {
      field: "price",
      headerName: "Price",
      flex: 1,
    },
    {
      field: "brand",
      headerName: "Brand",
      flex: 1,
    },
    {
      field: "action",
      headerName: "Action",
      flex: 1,
      renderCell: (params) => {
        return (
          <>
            <Link to={"/products/" + params.row._id}>
              <button className="productListEdit">Edit</button>
            </Link>
            <DeleteForeverIcon
              className="productListDelete"
              // onClick={() => deleteHandler(params.row._id)}
            />
          </>
        );
      },
    },
  ];

  return (

      {loading ? (
        <Loader />
      ) : error ? (
        <Message variant="error" />
      ) : (
        <DataGrid
          height={100}
          getRowId={(row) => row._id}
          rows={products?.products}
          disableSelectionOnClick
          columns={columns}
          rowsPerPageOptions={[10, 15, 20]}
          pageSize={10}
          checkboxSelection
        />
      )}

  );
};

export default Products;

the data never get fetched and I get this error in the browser:
"Warning: Failed prop type: The prop rows is marked as required in ForwardRef(DataGrid), but its value is undefined."

but when I remove what's inside the return of the componenet and add just an h1 tag the data get fetched and I can find it in redux store states

this is the slice I am working with :

import axios from 'axios';
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  products: [],
  loading: false,
  error: null
};
const baseurl = "http://localhost:5001"

const productSlice = createSlice({
  name: 'product',
  initialState,
  reducers: {
    fetchProductsStart(state) {
      state.loading = true;
    },
    fetchProductsSuccess(state, action) {
      state.products = action.payload;
      state.loading = false;
      state.error = null;
    },
    fetchProductsError(state, action) {
      state.loading = false;
      state.error = action.payload;
    },
    deleteProductStart(state) {
      state.loading = true;
    },
    deleteProductSuccess(state, action) {
      state.products = state.products.filter(product => product._id !== action.payload);
      state.loading = false;
      state.error = null;
    },
    deleteProductError(state, action) {
      state.loading = false;
      state.error = action.payload;
    },
    updateProductStart(state) {
      state.loading = true;
    },
    updateProductSuccess(state, action) {
      const index = state.products.findIndex(product => product._id === action.payload._id);
      state.products[index] = action.payload;
      state.loading = false;
      state.error = null;
    },
    updateProductError(state, action) {
      state.loading = false;
      state.error = action.payload;
    },
    fetchProductStart(state) {
      state.loading = true;
    },
    fetchProductSuccess(state, action) {
      state.products = [action.payload];
      state.loading = false;
      state.error = null;
    },
    fetchProductError(state, action) {
      state.loading = false;
      state.error = action.payload;
    }
  }
});

export const {
  fetchProductsStart,
  fetchProductsSuccess,
  fetchProductsError,
  deleteProductStart,
  deleteProductSuccess,
  deleteProductError,
  updateProductStart,
  updateProductSuccess,
  updateProductError,
  fetchProductStart,
  fetchProductSuccess,
  fetchProductError
} = productSlice.actions;
export default productSlice.reducer

export const fetchProducts = () => async dispatch => {
  try {
    dispatch(fetchProductsStart());
    const response = await axios.get(`${baseurl}/products`);
    dispatch(fetchProductsSuccess(response.data));
  } catch (error) {
    dispatch(fetchProductsError(error.message));
  }
};

export const deleteProduct = id => async dispatch => {
  try {
    dispatch(deleteProductStart());
    await axios.delete(`${baseurl}/products/${id}`);
    dispatch(deleteProductSuccess(id));
  } catch (error) {
    dispatch(deleteProductError(error.message));
  }
};

export const updateProduct = product => async dispatch => {
  try {
    dispatch(updateProductStart());
    const response = await axios.patch(`${baseurl}/products/${product._id}`, product);
    dispatch(updateProductSuccess(response.data));
  } catch (error) {
    dispatch(updateProductError(error.message));
  }
};

so what am I doing wrrong here

the modified Slice

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

const initialState = {
  products: [],
  loading: 'idle',
  error: null
};

const baseurl = 'http://localhost:5001';

export const fetchProducts = createAsyncThunk(
  'products/fetchProducts',
  async () => {
    const response = await axios.get(`${baseurl}/products`);
    return response.data;
  }
);

export const deleteProduct = createAsyncThunk(
  'products/deleteProduct',
  async id => {
    await axios.delete(`${baseurl}/products/${id}`);
    return id;
  }
);

export const updateProduct = createAsyncThunk(
  'products/updateProduct',
  async product => {
    const response = await axios.patch(
      `${baseurl}/products/${product._id}`,
      product
    );
    return response.data;
  }
);

export const fetchProduct = createAsyncThunk(
  'products/fetchProduct',
  async id => {
    const response = await axios.get(`${baseurl}/products/${id}`);
    return response.data;
  }
)

const productSlice = createSlice({
  name: 'products',
  initialState,
  reducers: {},
  extraReducers: {
    [fetchProducts.pending]: state => {
      state.loading = 'pending';
    },
    [fetchProducts.fulfilled]: (state, action) => {
      state.loading = 'idle';
      state.products = action.payload;
    },
    [fetchProducts.rejected]: (state, action) => {
      state.loading = 'idle';
      state.error = action.error.message;
    },
    [deleteProduct.pending]: state => {
      state.loading = 'pending';
    },
    [deleteProduct.fulfilled]: (state, action) => {
      state.loading = 'idle';
      state.products = state.products.filter(product => product._id !== action.payload);
    },
    [deleteProduct.rejected]: (state, action) => {
      state.loading = 'idle';
      state.error = action.error.message;
    },
    [updateProduct.pending]: state => {
      state.loading = 'pending';
    },
    [updateProduct.fulfilled]: (state, action) => {
      state.loading = 'idle';
      const index = state.products.findIndex(product => product._id === action.payload._id);
      state.products[index] = action.payload;
    },
    [updateProduct.rejected]: (state, action) => {
      state.loading = 'idle';
      state.error = action.error.message


问:
How to create a Dashboard in ARCGis to display a map?
I have created a map in ARCGis Pro. Now, I want to use that map to create a Dashboard where users might be able to see it and interact with it. I am barely learning ARCGis, and I know it's possible to create Dashboards within its interface. However, I am not sure how the process would look like. Can I create a Dashboard within ARCGis Pro? Do I have to export the map to ARCGis online first?</p>


问:
Only Show Power BI Matrix value at Row Grand Total
Is there a way to have a Power BI matrix value ONLY show on the totals?

I have them shrunk so they're not seen, but this rolls every week so it becomes a weekly task to hide.


问:
When to make an endpoint sync vs async while developing new api?
Creating an GET endpoint that generates upwards of 50,000 records, as this system is communicating with a message broker and where the work is done by another application layer to generate all the data. This process takes on average 30 seconds.

Can GET endpoints be async and when should an endpoint be async ?

My current async implementation for API is based on the Request Reply Pattern .

I have tried looking for other examples on this, found most async API's are POST requests. Cannot confirm if making an GET endpoint async breaks the common conventions.


问:
Including Insomnia requests setup with project's Github repo
Is is possible to include the setup that I have configured in Insomnia with my Github repo? I have a bunch of requests with routes set up in Insomnia that include json and tokens and all kinds of other data. The project is just the backend so I'd like for developers that visit my repo to have access to this Insomnia setup so they don't have to build their own requests to test the project.

I have a paid account with Insomnia and all of my routes are saved. I'm just looking to include it with my repo.


问:
Setting Clipboard data object with - copy after app exits - bool to true
I have a line of code that sets text to the clipboard:

```<code>Clipboard.SetDataObject(clipBoardExceptions);
</code>```

When I try to set this data object to also persist after the application exits I get an error that the clipboard can't open:

```<code>Clipboard.SetDataObject(clipBoardExceptions, true);
</code>```

Produces:

```<code>the second arg: {"OpenClipboard Failed (0x800401D0 (CLIPBRD_E_CANT_OPEN))"}

This exception was originally thrown at this call stack:
System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(int, System.IntPtr)
in Marshal.cs System.Windows.Clipboard.Flush()
System.Windows.Clipboard.CriticalSetDataObject(object, bool)
System.Windows.Clipboard.SetDataObject(object, bool)
</code>```

Body:
I have a line of code that sets text to the clipboard:

Clipboard.SetDataObject(clipBoardExceptions);

When I try to set this data object to also persist after the application exits I get an error that the clipboard can't open:

Clipboard.SetDataObject(clipBoardExceptions, true);

Produces:

the second arg: {"OpenClipboard Failed (0x800401D0 (CLIPBRD_E_CANT_OPEN))"}

This exception was originally thrown at this call stack:
System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(int, System.IntPtr)
in Marshal.cs System.Windows.Clipboard.Flush()
System.Windows.Clipboard.CriticalSetDataObject(object, bool)
System.Windows.Clipboard.SetDataObject(object, bool)


问:
My cardview is overlapping all layouts (cards)
I am trying to make a cardview showing different options for a menu, but the cards are just overlapping each other, i have followed multiple tutorials and repeat things exactly as shown but the cardview isnt working properly, how do i fix it or make it work properly? am i doing something wrong?
xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/purple"
    android:orientation="vertical"
    tools:context=".MainMenu">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.85"
        android:background="@drawable/userpanel">

    </RelativeLayout>

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.3 " >

        <LinearLayout
            android:background="@drawable/cardcontainer"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:orientation="vertical">
        </LinearLayout>

        <LinearLayout
            android:background="@drawable/cardcontainer"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:orientation="vertical">
        </LinearLayout>
        </androidx.cardview.widget.CardView>
</LinearLayout>
</code>```

Img

idk why is it showing like that, i did this before but got the project deleted because my pc died and worked perfectly, and now it isnt

Body:
I am trying to make a cardview showing different options for a menu, but the cards are just overlapping each other, i have followed multiple tutorials and repeat things exactly as shown but the cardview isnt working properly, how do i fix it or make it work properly? am i doing something wrong?
xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/purple"
    android:orientation="vertical"
    tools:context=".MainMenu">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.85"
        android:background="@drawable/userpanel">

    </RelativeLayout>

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0.3 " >

        <LinearLayout
            android:background="@drawable/cardcontainer"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:orientation="vertical">
        </LinearLayout>

        <LinearLayout
            android:background="@drawable/cardcontainer"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:orientation="vertical">
        </LinearLayout>
        </androidx.cardview.widget.CardView>
</LinearLayout>

Img

idk why is it showing like that, i did this before but got the project deleted because my pc died and worked perfectly, and now it isnt