问:
Load and display an image via dialog window to edit it later (Python TKinter)
I am currently developing a GUI via Tkinter in Python. The idea is to create an interface, which allows me to select two jpg or png formatted pictures from my computer, resize them and show them in two separate square frames. Once done, there is a third frame with the third button underneath, which is supposed to start an animation (sequential image transitions) with the further involvement of pictures 1 and 2. I have no problem with importing these images in frames. However, when I try to access my global image variable inside the function (which is bound to the button) to convert an image to the array of pixels, the compiler finds no value stored in the variable.

```<code>from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
from tkinter import Canvas
from numpy import asarray
import numpy as np

window = Tk()
window.title("Image Transitions")
window.geometry("1200x800")
window.config(background="CornflowerBlue")
window.maxsize(1200, 800)

title1 = Label(window, text="Image 1", width=20)
title1.place(x=180, y=175)
title1.configure(bg="CornflowerBlue")

title2 = Label(window, text="Image 2", width=20)
title2.place(x=530, y=175)
title2.configure(bg="CornflowerBlue")

title3 = Label(window, text="Image Transitions", width=20)
title3.place(x=880, y=175)
title3.configure(bg="CornflowerBlue")

button1 = Button(window, text="Upload Image 1", width=20, command=lambda:browse_Image1())
button1.place(x=180, y=510)

button2 = Button(window, text="Upload Image 2", width=20, command=lambda:browse_Image2())
button2.place(x=530, y=510)

canvas1 = Canvas(window, width=300, height=300)
canvas1.pack()
canvas1.configure(bg="LightSkyBlue")
canvas1.place(x=100, y=200)

canvas2 = Canvas(window, width=300, height=300)
canvas2.pack()
canvas2.configure(bg="LightSkyBlue")
canvas2.place(x=450, y=200)

canvas3 = Canvas(window, width=300, height=300)
canvas3.pack()
canvas3.configure(bg="LightSkyBlue")
canvas3.place(x=800, y=200)

def browse_Image1():
    global image_first

    filename = filedialog.askopenfilename(
    initialdir = "/",
    title = "Select a File",
    filetypes = (("2D - JPG", "*.jpg*"), ("2D - PNG", "*.png*"), ("all files", "*.*")))

    img = Image.open(filename)
    img = img.resize((300, 300))
    image_first = ImageTk.PhotoImage(img)

    label = Label(window, image=image_first)
    label.pack()
    label.place(x=100, y=200)

def browse_Image2():
    global image_second
    filename = filedialog.askopenfilename(
    initialdir = "/",
    title = "Select a File",
    filetypes = (("2D - JPG", "*.jpg*"), ("2D - PNG", "*.png*"), ("all files", "*.*")))

    img2 = Image.open(filename)
    img2 = img2.resize((300, 300))
    image_second = ImageTk.PhotoImage(img2)

    label = Label(window, image=image_second)
    label.pack()
    label.place(x=450, y=200)

ImageA_Width, ImageA_Height = image_first.size
data_A_norm = asarray(image_first) / 255.0
data_B_norm = asarray(image_second) / 255.0

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

As far as I understand, to access an image stored in a variable, I need to call this function. However, in my case, it is not the solution, as the “Select file” window will be called again.

Here I need to do both things:

Execute the command: choose and import images by pressing a button.

Get access to the imported images stored in variables.

Any idea or concept of fixing this would be highly appreciated!

Body:
I am currently developing a GUI via Tkinter in Python. The idea is to create an interface, which allows me to select two jpg or png formatted pictures from my computer, resize them and show them in two separate square frames. Once done, there is a third frame with the third button underneath, which is supposed to start an animation (sequential image transitions) with the further involvement of pictures 1 and 2. I have no problem with importing these images in frames. However, when I try to access my global image variable inside the function (which is bound to the button) to convert an image to the array of pixels, the compiler finds no value stored in the variable.

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
from tkinter import Canvas
from numpy import asarray
import numpy as np

window = Tk()
window.title("Image Transitions")
window.geometry("1200x800")
window.config(background="CornflowerBlue")
window.maxsize(1200, 800)

title1 = Label(window, text="Image 1", width=20)
title1.place(x=180, y=175)
title1.configure(bg="CornflowerBlue")

title2 = Label(window, text="Image 2", width=20)
title2.place(x=530, y=175)
title2.configure(bg="CornflowerBlue")

title3 = Label(window, text="Image Transitions", width=20)
title3.place(x=880, y=175)
title3.configure(bg="CornflowerBlue")

button1 = Button(window, text="Upload Image 1", width=20, command=lambda:browse_Image1())
button1.place(x=180, y=510)

button2 = Button(window, text="Upload Image 2", width=20, command=lambda:browse_Image2())
button2.place(x=530, y=510)

canvas1 = Canvas(window, width=300, height=300)
canvas1.pack()
canvas1.configure(bg="LightSkyBlue")
canvas1.place(x=100, y=200)

canvas2 = Canvas(window, width=300, height=300)
canvas2.pack()
canvas2.configure(bg="LightSkyBlue")
canvas2.place(x=450, y=200)

canvas3 = Canvas(window, width=300, height=300)
canvas3.pack()
canvas3.configure(bg="LightSkyBlue")
canvas3.place(x=800, y=200)

def browse_Image1():
    global image_first

    filename = filedialog.askopenfilename(
    initialdir = "/",
    title = "Select a File",
    filetypes = (("2D - JPG", "*.jpg*"), ("2D - PNG", "*.png*"), ("all files", "*.*")))

    img = Image.open(filename)
    img = img.resize((300, 300))
    image_first = ImageTk.PhotoImage(img)

    label = Label(window, image=image_first)
    label.pack()
    label.place(x=100, y=200)

def browse_Image2():
    global image_second
    filename = filedialog.askopenfilename(
    initialdir = "/",
    title = "Select a File",
    filetypes = (("2D - JPG", "*.jpg*"), ("2D - PNG", "*.png*"), ("all files", "*.*")))

    img2 = Image.open(filename)
    img2 = img2.resize((300, 300))
    image_second = ImageTk.PhotoImage(img2)

    label = Label(window, image=image_second)
    label.pack()
    label.place(x=450, y=200)

ImageA_Width, ImageA_Height = image_first.size
data_A_norm = asarray(image_first) / 255.0
data_B_norm = asarray(image_second) / 255.0

window.mainloop()

As far as I understand, to access an image stored in a variable, I need to call this function. However, in my case, it is not the solution, as the “Select file” window will be called again.

Here I need to do both things:

Execute the command: choose and import images by pressing a button.

Get access to the imported images stored in variables.

Any idea or concept of fixing this would be highly appreciated!


来源: stackexchange

问:
Is it possible to create a web service that changes websites CSS?
Specifically, I'm thinking about a service that hides the price in online shops so that I can share the link without the price with someone.</p>

ContentLicense: CC BY-SA 4.0


问:
.Net Vuejs npm run build .key no such file
I am working on deploying my fist Vue.js application,
I have everything working on my dev machine, I created a server and now I am pushing it up to the server and I get this error:

Error loading /var/www/html/vue/vue.config.js
Error ENOENT: no such file or directory open /root/.aspnet/https/vue.key

I created a new username.
I installed Nginx
I also installed dotnet 6.0 for my current project.

I am running npm run build.

Heres an update.
I am deploying this on a server on our network. When I do `npm run build' I get the following error:
Error: ENOENT: no such file or directory open /home/user/.aspnet/https/ vue.key

This is a vue.js project being built in Visual Studio 2022. with an .Net 6 API for the backend.
I have everything working, just deploying it seems to be my current issue I am running into.


问:
Can't import anything from django
I'm having problems with importing stuff from Django.
I'm entirely new to python and I'm following a tutorial where I'm taught how to make my first Django project (I'm using Pycharm by the way).
The problem I'm encountering is when I try to import something from Django it says Unresolved reference 'django'.

from django.http import HttpResponse
from django.shortcuts import render
```

This case only shows the red squiggly line under the two HttpResponse, and render.

Any help would be appreciated, I have tried searching on google, but I couldn't find what I'm looking for.

Title: Can't import anything from django

Body:
I'm having problems with importing stuff from Django.
I'm entirely new to python and I'm following a tutorial where I'm taught how to make my first Django project (I'm using Pycharm by the way).
The problem I'm encountering is when I try to import something from Django it says Unresolved reference 'django'.

from django.http import HttpResponse
from django.shortcuts import render

This case only shows the red squiggly line under the two HttpResponse, and render.

Any help would be appreciated, I have tried searching on google, but I couldn't find what I'm looking for.


问:
How can I get the value from os.system with Python 3
Hi I have a code where I execute this code:

```<code>import os

os.system("python3 -m http.server 8081")
</code>```

The os.system is displaying a value in the console but I wonder how can I get that value.

I mean

```<code>value =  os.system("python3 -m http.server 8081")
</code>```

Thanks!

Body:
Hi I have a code where I execute this code:

import os

os.system("python3 -m http.server 8081")

The os.system is displaying a value in the console but I wonder how can I get that value.

I mean

value =  os.system("python3 -m http.server 8081")

Thanks!


问:
Simulink misses data points in a from-workspace block for discrete simulation
I have a simulation running at 50 Hz, and some data that comes in at 10 Hz. I have extra 'in-between' points with dummy data at the following 50 Hz time points, and interpolation set to off. This should in theory ensure that between 10 Hz time steps, the dummy data is being held and only at the 10 Hz steps is the actual data present. For example, my data vector would be

```<code>[0.0 0.8 0.1 0.12 0.2 0.22 0.3 0.32 0.4 0.42 0.5 0.52 ...
  -1  -1   1   -1   2   -1   3   -1   4   -1   5   -1 ...]
</code>```

However, with a scope attached directly from the 'from-workspace' block, simulink is returning this:

```<code>[0.0 0.8 0.1 0.12 0.2 0.22 0.3 0.32 0.34 0.4 0.42 0.5 0.52...
  -1  -1  -1   -1   2   -1   3    3   -1   4   -1   5    5...]
</code>```

where some values are skipped and others are repeated in a consistent pattern. Is there something with simulinks time-step algorithms that would cause this?

Edit: A solution I ended up finding was to offset the entire time vector by 1/100th of a second so that the sim was taking data between points rather than on points, and that seemed to fix it. Not ideal, but functional.

Body:
I have a simulation running at 50 Hz, and some data that comes in at 10 Hz. I have extra 'in-between' points with dummy data at the following 50 Hz time points, and interpolation set to off. This should in theory ensure that between 10 Hz time steps, the dummy data is being held and only at the 10 Hz steps is the actual data present. For example, my data vector would be

[0.0 0.8 0.1 0.12 0.2 0.22 0.3 0.32 0.4 0.42 0.5 0.52 ...
  -1  -1   1   -1   2   -1   3   -1   4   -1   5   -1 ...]

However, with a scope attached directly from the 'from-workspace' block, simulink is returning this:

[0.0 0.8 0.1 0.12 0.2 0.22 0.3 0.32 0.34 0.4 0.42 0.5 0.52...
  -1  -1  -1   -1   2   -1   3    3   -1   4   -1   5    5...]

where some values are skipped and others are repeated in a consistent pattern. Is there something with simulinks time-step algorithms that would cause this?

Edit: A solution I ended up finding was to offset the entire time vector by 1/100th of a second so that the sim was taking data between points rather than on points, and that seemed to fix it. Not ideal, but functional.


问:
Sum data inside selection in bokeh image plot
I am starting with bokeh and I wonder if anyone could point me in the right direction.

I have an image (2D array). Using the gallery example:

```<code>import numpy as np

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, RangeTool
from bokeh.layouts import column

x = np.linspace(0, 10, 300)
y = np.linspace(0, 10, 300)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx) * np.cos(yy)

# Figures creation
im_fig = figure(width=400, height=400)

# Plotting the data
im_fig.image(image=[d], x=0, y=0, dw=10, dh=10, palette="Sunset11", level="image")
im_fig.grid.grid_line_width = 0.5

show(im_fig)
</code>```

Which results in:

Now I would like to sum the data along a y selection. This seems to be the work of the RangeTool.

I create another figure to plot the summed data of the selection but I get an error while adding the initial range:

```<code>import numpy as np

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, RangeTool
from bokeh.layouts import column

x = np.linspace(0, 10, 300)
y = np.linspace(0, 10, 300)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx) * np.cos(yy)

# Figures creation
im_fig = figure(width=400, height=400)
sum_fig = figure(width=400, height=200)

# Plotting the data
im_fig.image(image=[d], x=0, y=0, dw=10, dh=10, palette="Sunset11", level="image")
im_fig.grid.grid_line_width = 0.5

# Adding the range tools
range_tool = RangeTool(y_range=im_fig.y_range)
range_tool.overlay.fill_color = "navy"
range_tool.overlay.fill_alpha = 0.2
im_fig.add_tools(range_tool)
im_fig.toolbar.active_multi = range_tool

show(column(im_fig, sum_fig))
</code>```

This is the error:

```<code>failed to validate RangeTool(id='p1108', ...).y_range: expected either None or a value of type Instance(Range1d), got DataRange1d(id='p1003', ...)
</code>```

My guess, this is happening because the Range tool is not compatible with the Image glyph. I wonder if anyone could please point me towards the right direction. Ty.

Body:
I am starting with bokeh and I wonder if anyone could point me in the right direction.

I have an image (2D array). Using the gallery example:

import numpy as np

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, RangeTool
from bokeh.layouts import column

x = np.linspace(0, 10, 300)
y = np.linspace(0, 10, 300)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx) * np.cos(yy)

# Figures creation
im_fig = figure(width=400, height=400)

# Plotting the data
im_fig.image(image=[d], x=0, y=0, dw=10, dh=10, palette="Sunset11", level="image")
im_fig.grid.grid_line_width = 0.5

show(im_fig)

Which results in:

Now I would like to sum the data along a y selection. This seems to be the work of the RangeTool.

I create another figure to plot the summed data of the selection but I get an error while adding the initial range:

import numpy as np

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, RangeTool
from bokeh.layouts import column

x = np.linspace(0, 10, 300)
y = np.linspace(0, 10, 300)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx) * np.cos(yy)

# Figures creation
im_fig = figure(width=400, height=400)
sum_fig = figure(width=400, height=200)

# Plotting the data
im_fig.image(image=[d], x=0, y=0, dw=10, dh=10, palette="Sunset11", level="image")
im_fig.grid.grid_line_width = 0.5

# Adding the range tools
range_tool = RangeTool(y_range=im_fig.y_range)
range_tool.overlay.fill_color = "navy"
range_tool.overlay.fill_alpha = 0.2
im_fig.add_tools(range_tool)
im_fig.toolbar.active_multi = range_tool

show(column(im_fig, sum_fig))

This is the error:

failed to validate RangeTool(id='p1108', ...).y_range: expected either None or a value of type Instance(Range1d), got DataRange1d(id='p1003', ...)

My guess, this is happening because the Range tool is not compatible with the Image glyph. I wonder if anyone could please point me towards the right direction. Ty.


问:
Reactjs send json object from client to server(express) not working
I tried to send the json objects from client to the backend(express) and then save it to mongodb. I can see the json objects sent but with "undefined" at the end.

Client side to send the json object :

```<code> setCategoryFile(JSON.stringify(Categories))
const saveStmnt = async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('categoryFilename', categoryFile)

      const config = {
        headers: {
            'content-type': 'application/json'
        }

       };

        try {
            await axios.post("http://localhost:3001/statements", formData,
           config, {
        });
        navigate("/");
        } catch (error) {
            console.log(error);
        }
};
</code>```

code from backend (express):

```<code>export const saveStatement = async (req , res , next) => {

 //   const info = new StatementSchema(req.body)
    console.log('CreditCardAnalysis.js : Perform saveStatement')
    console.log(req.body.categoryFile)

    let data = new Statement ( {
        categoryFile : req.body.categoryFile
    })

         console.log("perform savedSTmnt...save")
        try {
            const savedStmnt = await data.save();
            if (err)
                res.end('Error in saving the statement');
            else
                {
                    res.status(201).json(savedStmnt)
                    res.redirect('/')
                }
                //res.status(200).json(JSON.stringify(savedProduct));
            } catch (err) {
                res.redirect('/');
                res.end();
            }
        };
</code>```

Result from backend :

Database Connected...
{
categoryFilename: '[{"description":"GOOGLE","category":"MISC"},{"description":"AMZN","category":"MERCHANDISE"},{"description":"MCDONALD","category":"DINNING"},{"description":"SAFEWAY","category":"GROCERIES"},{"description":"WISH","category":"MERCHANDISE"},{"description":"99 RANCH","category":"GROCERIES"},{"description":"PARKMOBILE","category":"COLLEGE FEE"},{"description":"CITY OF SAN RAMON","category":"TENNIS"},{"description":"FILA","category":"APPAREL"},{"description":"COMCAST","category":"TELECOM"},{"description":"PEETS","category":"COFFEE"}]'
}
undefined

Body:
I tried to send the json objects from client to the backend(express) and then save it to mongodb. I can see the json objects sent but with "undefined" at the end.

Client side to send the json object :

 setCategoryFile(JSON.stringify(Categories))
const saveStmnt = async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('categoryFilename', categoryFile)

      const config = {
        headers: {
            'content-type': 'application/json'
        }

       };

        try {
            await axios.post("http://localhost:3001/statements", formData,
           config, {
        });
        navigate("/");
        } catch (error) {
            console.log(error);
        }
};

code from backend (express):

export const saveStatement = async (req , res , next) => {

 //   const info = new StatementSchema(req.body)
    console.log('CreditCardAnalysis.js : Perform saveStatement')
    console.log(req.body.categoryFile)

    let data = new Statement ( {
        categoryFile : req.body.categoryFile
    })

         console.log("perform savedSTmnt...save")
        try {
            const savedStmnt = await data.save();
            if (err)
                res.end('Error in saving the statement');
            else
                {
                    res.status(201).json(savedStmnt)
                    res.redirect('/')
                }
                //res.status(200).json(JSON.stringify(savedProduct));
            } catch (err) {
                res.redirect('/');
                res.end();
            }
        };

Result from backend :

Database Connected...
{
categoryFilename: '[{"description":"GOOGLE","category":"MISC"},{"description":"AMZN","category":"MERCHANDISE"},{"description":"MCDONALD","category":"DINNING"},{"description":"SAFEWAY","category":"GROCERIES"},{"description":"WISH","category":"MERCHANDISE"},{"description":"99 RANCH","category":"GROCERIES"},{"description":"PARKMOBILE","category":"COLLEGE FEE"},{"description":"CITY OF SAN RAMON","category":"TENNIS"},{"description":"FILA","category":"APPAREL"},{"description":"COMCAST","category":"TELECOM"},{"description":"PEETS","category":"COFFEE"}]'
}
undefined


问:
FileSystem vs FileSystemProvider
I am new to vscode extensions API development. I was going through the API documentation when I found FileSystem and FileSystemProvider in order to read a directory's and file's contents. I am finding it hard to understand the differences between the two.

Can someone help me out with when to use FileSystem and FileSystemProvider?

Title: FileSystem vs FileSystemProvider


问:
Mongoose or Webpack: Who to Blame?
I'm losing my mind dealing with Mongoose and Webpack.
Some Mongoose Model functions work, but not create, or save.
Although I tested the scenario in a different file and the exact same code worked.

I am getting the error message: _models_hike__WEBPACK_IMPORTED_MODULE_13__.default.create is not a function

I have my model file (hike.ts) :

```<code>import mongoose, { models, Schema } from 'mongoose';

const HikeSchema: Schema = new Schema({
  name: { required: function () { return this.trailName === undefined }, type: String },
  trailName: { required: false, type: String },
  year: { required: true, type: Number },
  options: {
    continuous: { required: true, type: Boolean },
    direction: { required: true, type: String },
    sameYear: { required: true, type: Boolean },
    terminus: { required: true, type: String }
  }
});

const Hike = models?.hikes || mongoose.model('hike', HikeSchema);
export default Hike;

</code>```

And a form in my React project, where I can create a new Hike (HikeLog.tsx):

```<code>import Hike from '../models/hike';

handleSubmit = (event) => {
    Hike.create(this.state, (error) => { console.log('Save did not work:', error) });
}
</code>```

The form page loads, but throws the runtime error message when the submit button is clicked.

On top of all that, VSCode shows this error for all my model functions after upgrading from mongoose 5.13 to 6.8 :

```<code>This expression is not callable.
  Each member of the union type

{
    <DocContents = AnyKeys<{ [x: string]: any; }>>
        (docs: ({ [x: string]: any; } | DocContents)[], options?: SaveOptions):
            Promise<(Document<unknown, any, { [x: string]: any; }> & { ...; } & Required<...>)[]>;
            <DocContents = AnyKeys<...>>(docs: ({ ...; } | DocContents)[], options?: SaveOptions, callback?: Callback<...>...' has signatures, but none of those signatures are compatible with each other.ts(2349)
</code>```

Help!

Title: Mongoose or Webpack: Who to Blame?

Body:
I'm losing my mind dealing with Mongoose and Webpack.
Some Mongoose Model functions work, but not create, or save.
Although I tested the scenario in a different file and the exact same code worked.

I am getting the error message: _models_hike__WEBPACK_IMPORTED_MODULE_13__.default.create is not a function

I have my model file (hike.ts) :

import mongoose, { models, Schema } from 'mongoose';

const HikeSchema: Schema = new Schema({
  name: { required: function () { return this.trailName === undefined }, type: String },
  trailName: { required: false, type: String },
  year: { required: true, type: Number },
  options: {
    continuous: { required: true, type: Boolean },
    direction: { required: true, type: String },
    sameYear: { required: true, type: Boolean },
    terminus: { required: true, type: String }
  }
});

const Hike = models?.hikes || mongoose.model('hike', HikeSchema);
export default Hike;

And a form in my React project, where I can create a new Hike (HikeLog.tsx):

import Hike from '../models/hike';

handleSubmit = (event) => {
    Hike.create(this.state, (error) => { console.log('Save did not work:', error) });
}

The form page loads, but throws the runtime error message when the submit button is clicked.

On top of all that, VSCode shows this error for all my model functions after upgrading from mongoose 5.13 to 6.8 :

This expression is not callable.
  Each member of the union type

{
    <DocContents = AnyKeys<{ [x: string]: any; }>>
        (docs: ({ [x: string]: any; } | DocContents)[], options?: SaveOptions):
            Promise<(Document<unknown, any, { [x: string]: any; }> & { ...; } & Required<...>)[]>;
            <DocContents = AnyKeys<...>>(docs: ({ ...; } | DocContents)[], options?: SaveOptions, callback?: Callback<...>...' has signatures, but none of those signatures are compatible with each other.ts(2349)

Help!


问:
Extract Column name and datatype from table in ssms with Powershell
I'm trying to do an extract of the column name and datatype of a table in ssms with PowerShell.
I will like the output to be in three columns.

First column: The name of the Column in the table
Second column: The datatype of the column
Third column: tells if it keeps null values.

As an example:

I'm new to powershell and can't find the right way of doing this - Can Anyone help?

Tryed different apporaches and googled but can't find a solution.


问:
How can i send 2(and more) tx in one block? Web3
I want to send 2 or more transactions in one block. I know about using nodes to pack transactions in one block, but I would like to know how I can do the same in Python with just web3 on any networks. Be it eth, polygon or bsc.</p>
```<code>tx1 = {
    'chainId': web3.eth.chain_id,
    'from': address,
    'to': receiver,
    'gas': gas,
    'gasPrice': web3.toWei(gasPrice, 'Gwei'),
    'nonce': web3.eth.getTransactionCount(address),
}

signed_txn1 = web3.eth.account.signTransaction(tx1, private_key1)

txRaw.append(signed_txn1.rawTransaction)

tx2 = {
    'nonce': web3.eth.getTransactionCount(address),
    'from': address,
    'to': contract_address,
    'gas': gas,
    'gasPrice': web3.toWei(5, 'Gwei'),
    'data': byte260
}

signed_txn2 = web3.eth.account.signTransaction(tx2, private_key2)

txRaw.append(signed_txn2.rawTransaction)

#Here smth to send
print(sendTXOneBlock(txRaw[0].hex(), txRaw[1].hex()))
</code>```

Body:
I want to send 2 or more transactions in one block. I know about using nodes to pack transactions in one block, but I would like to know how I can do the same in Python with just web3 on any networks. Be it eth, polygon or bsc.

tx1 = {
    'chainId': web3.eth.chain_id,
    'from': address,
    'to': receiver,
    'gas': gas,
    'gasPrice': web3.toWei(gasPrice, 'Gwei'),
    'nonce': web3.eth.getTransactionCount(address),
}

signed_txn1 = web3.eth.account.signTransaction(tx1, private_key1)

txRaw.append(signed_txn1.rawTransaction)

tx2 = {
    'nonce': web3.eth.getTransactionCount(address),
    'from': address,
    'to': contract_address,
    'gas': gas,
    'gasPrice': web3.toWei(5, 'Gwei'),
    'data': byte260
}

signed_txn2 = web3.eth.account.signTransaction(tx2, private_key2)

txRaw.append(signed_txn2.rawTransaction)

#Here smth to send
print(sendTXOneBlock(txRaw[0].hex(), txRaw[1].hex()))


问:
Yup InferType optional properties
This is an example of a Yup schema i have in order to fetch entities called Parcels

```<code>export const FindParcelsParamsSchema = Yup.object({
  cursor: Yup.number().optional(),
  pageSize: Yup.number().positive().integer().optional(),
});
</code>```

every field is optional

and this is the Interface I try to generate for this schema:

```<code>export interface IParcelsFetchingParams extends Yup.InferType<typeof FindParcelsParamsSchema> { }
</code>```

I believe i should be able to declare this variable :

```<code>let params: TParcelsFetchingParams = {};
</code>```

but typescript won't stop rasing this error:

Type '{ cursor: undefined; pageSize: undefined; }' is missing the following properties from type...

unless i add all the fields as undefined

```<code>let x: TParcelsFetchingParams = {
  cursor: undefined,
  pageSize: undefined,
};
</code>```

my tsconfigs are:

"compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./lib",
    "strict": true
  }
```

So why am I exactly facing this problem, and how can I fix it?

I expect I can declare my variable as an empty variable or with one property without issues.

Title: Yup InferType optional properties

Body:
This is an example of a Yup schema i have in order to fetch entities called Parcels

export const FindParcelsParamsSchema = Yup.object({
  cursor: Yup.number().optional(),
  pageSize: Yup.number().positive().integer().optional(),
});

every field is optional

and this is the Interface I try to generate for this schema:

export interface IParcelsFetchingParams extends Yup.InferType<typeof FindParcelsParamsSchema> { }

I believe i should be able to declare this variable :

let params: TParcelsFetchingParams = {};

but typescript won't stop rasing this error:

Type '{ cursor: undefined; pageSize: undefined; }' is missing the following properties from type...

unless i add all the fields as undefined

let x: TParcelsFetchingParams = {
  cursor: undefined,
  pageSize: undefined,
};

my tsconfigs are:

"compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./lib",
    "strict": true
  }

So why am I exactly facing this problem, and how can I fix it?

I expect I can declare my variable as an empty variable or with one property without issues.


问:
Is it possible to delete specific entry on Windows event log?
I want to delete specific windows event-log entry using PowerShell/Any other method.

I have the relevant event using:

```<code>Get-EventLog -LogName Security -Index 154861
</code>```

My question is if there is a way to delete this entry.

Body:
I want to delete specific windows event-log entry using PowerShell/Any other method.

I have the relevant event using:

Get-EventLog -LogName Security -Index 154861

My question is if there is a way to delete this entry.


问:
How to determine the input object type of arguments to a graphql field in a resolver with graphql-js?
I'm writing a little something to record the usage of types and fields in a graphql server. It's working fine for output objects, but I am not yet able to figure out how to apply it to input arguments.

The simplest approach would be to examine the args argument to the field resolver and record the types used therein, but the input object values of the args object do not seem to convey any type information. Indeed, they unhelpfully report themselves as having a null prototype.

Am I missing some hidden type information? Failing that, can anyone think of a good way to manipulate the schema to have it add that type information, e.g. by visiting all input object types and adding a validation or coercer function with side effects?


问:
Plotting matplotlib data inside PySimpleGUI interface
Currently I'm plotting my data in a figure that shows in a separate window that opens when I click my submit button to plot my data. However, I want to plot the data straight into what I have outlined with a canvas instead. I haven't used python much, so I don't know how to utilize the FigureCanvasTkAgg to my advantage here. Any help would be appreciated. Here is the code snippet:

```<code>def set_data(driver, slice, lap_num):
    if slice == "Fastest Lap":
        self = driver.best_tel

    elif slice == "Specific Lap":
        lap_n = driver.ses[driver.ses['LapNumber'] == lap_num]
        lap_n_tel = lap_n.get_car_data().add_distance()
        self = lap_n_tel

    elif slice == "Full Session":
        self = driver.ses

    return self

def make_figure():
        fig = plt.figure(1, figsize=(16,9), constrained_layout=True)
        ax = fig.subplots()
        return fig, ax

def plot_ax(driver, data, fig, xvar, yvar, ax):
    ax.plot(data[xvar], data[yvar], color=driver.teamcolor, label=f'{driver.id}')
    ax.set_xlim(data[xvar].min(), data[xvar].max())

def compare(grandprix, driver, slice, xvar, yvar, fig, ax, lap_num):
    for abb in driver:
        driver = Driver(grandprix, abb)
        data = set_data(driver, slice, lap_num)
        plot_ax(driver, data, fig, xvar, yvar, ax)

def set_title(grandprix, driver, yvar, slice, ses, lap_num, comp):
    global title
    if slice == "Specific Lap":
        analysis = f"Lap {lap_num}, {yvar} \n {grandprix.event.year} {grandprix.event['EventName']}, {ses}"

    elif slice != "Specific Lap":
        analysis = f"{slice}, {yvar} \n {grandprix.event.year} {grandprix.event['EventName']}, {ses}"
    if comp == True:
        title = analysis

    elif comp != True:
        title = f"{driver.bio['FullName']} " + analysis
    plt.suptitle(f"{title}")

def design_plot(ax, xvar, yvar):
        ax.set_xlabel(xvar)
        ax.set_ylabel(yvar)

        ax.minorticks_on()
        ax.grid(visible=True, axis='both', which='major', linewidth=0.9, alpha=0.3)
        ax.grid(visible=True, axis='both', which='minor', linestyle=':', linewidth=0.6, alpha=0.3)

        ax.legend()

def show_plot():
    plt.show()

def analyse():
    global year, gp, ses, abb, slice
    global lap_num, xvar, yvar, comp

    year = int(values['-YEAR-'])
    gp = values['-GP-'][0]
    ses = values['-SESSION-']
    abb = values['-DRIVER-']
    slice = values['-SLICE-']
    lap_num = int(values['-LAPNUM-'])
    xvar = values['-DRIVERXVAR-']
    yvar = values['-DRIVERYVAR-']
    comp = values['-COMPARE-']

    fig, ax = make_figure()

    if comp == True:
        compare(grandprix, abb, slice, xvar, yvar, fig, ax, lap_num)
        driver = Driver(grandprix, abb[0])

    elif comp != True:
        driver = Driver(grandprix, abb[0])
        data = set_data(driver, slice, lap_num)
        plot_ax(driver, data, fig, xvar, yvar, ax)

    design_plot(ax, xvar, yvar)
    set_title(grandprix, driver, yvar, slice, ses, lap_num, comp)

    show_plot()

def make_window():
    sg.theme('DarkBlue14')
    lists = Lists()
    menu_def = [[('&Help'), ['&About', '&GitHub', 'E&xit']]]

    header_layout = [[sg.Image(source='src/common/images/icon_header.png', size=(120, 60), expand_x=True, expand_y=True)],]

.
    menu_layout_column = [
            [sg.Menubar(menu_def, key='-MENU-')],
            [sg.Frame('', header_layout, size=(500,100), key='-HEAD-')],
            [sg.OptionMenu(lists.Years.list, default_value=f'{lists.Years.list[-1]}', expand_x=True, key='-YEAR-')],
            [sg.Button('Load Season', size=(10,1), expand_x=True)],
            [sg.Listbox(lists.GrandPrix.list, enable_events=True, expand_x=True, size=(None,10), select_mode='single', horizontal_scroll=False, visible=False, pad=(7,7,7,7), key='-GP-')],
            [sg.OptionMenu(lists.Sessions.list, default_value=f'Select Session...', expand_x=True, visible=False, key='-SESSION-')],
            [sg.Button('Drivers in Session', visible=False, expand_x=True, key='-LOADDRIVERS-')],
            [sg.Listbox(lists.Drivers.list, enable_events=True, expand_x=True, size=(None,10), select_mode='single', horizontal_scroll=False, visible=False, pad=(7,7,7,7), key='-DRIVER-')],
            [sg.Checkbox('Compare drivers?', enable_events=True, visible=False, key='-COMPARE-')],
            [sg.OptionMenu(lists.SessionSlice.list, default_value=f'Evalutate Full Session?', disabled=True, expand_x=True, visible=False, key='-SLICE-')],
            [sg.Text('Enter Lap Number', visible=False, key='-LAPASK-')],
            [sg.Input(default_text= 0, expand_x=True, visible=False, key='-LAPNUM-')],
            [sg.Button('Select Telemetry', visible=False, disabled=True, expand_x=True, key='-LOADVARS-')],
            [sg.OptionMenu(lists.LapVarsY.list, default_value='Y Variable...', expand_x=True, visible=False, key='-DRIVERYVAR-')],
            [sg.OptionMenu(lists.LapVarsX.list, default_value='X Variable...', expand_x=True, visible=False, key='-DRIVERXVAR-')],
            [sg.Button('Confirm All', visible=True, expand_x=True, key='-CONFIRM ALL-')],
            [sg.Button('Submit', visible=True, disabled=True, expand_x=True, key='-PLOT-')],
            ]

    graph_layout_column = [

    ]

    layout = [
        [sg.Column(menu_layout_column),
        sg.VSeparator(),
        sg.Column(graph_layout_column)],
                ]

    window = sg.Window('Gr1dGuru', layout, margins=(10, 10), finalize=True)

    window.set_min_size(window.size)

    return window
</code>```

I have tried messing around with the FigureCanvasTkAgg with a fixed plot, but when I try modifying anything with my function setup I'm completely stuck.

Body:
Currently I'm plotting my data in a figure that shows in a separate window that opens when I click my submit button to plot my data. However, I want to plot the data straight into what I have outlined with a canvas instead. I haven't used python much, so I don't know how to utilize the FigureCanvasTkAgg to my advantage here. Any help would be appreciated. Here is the code snippet:

def set_data(driver, slice, lap_num):
    if slice == "Fastest Lap":
        self = driver.best_tel

    elif slice == "Specific Lap":
        lap_n = driver.ses[driver.ses['LapNumber'] == lap_num]
        lap_n_tel = lap_n.get_car_data().add_distance()
        self = lap_n_tel

    elif slice == "Full Session":
        self = driver.ses

    return self

def make_figure():
        fig = plt.figure(1, figsize=(16,9), constrained_layout=True)
        ax = fig.subplots()
        return fig, ax

def plot_ax(driver, data, fig, xvar, yvar, ax):
    ax.plot(data[xvar], data[yvar], color=driver.teamcolor, label=f'{driver.id}')
    ax.set_xlim(data[xvar].min(), data[xvar].max())

def compare(grandprix, driver, slice, xvar, yvar, fig, ax, lap_num):
    for abb in driver:
        driver = Driver(grandprix, abb)
        data = set_data(driver, slice, lap_num)
        plot_ax(driver, data, fig, xvar, yvar, ax)

def set_title(grandprix, driver, yvar, slice, ses, lap_num, comp):
    global title
    if slice == "Specific Lap":
        analysis = f"Lap {lap_num}, {yvar} \n {grandprix.event.year} {grandprix.event['EventName']}, {ses}"

    elif slice != "Specific Lap":
        analysis = f"{slice}, {yvar} \n {grandprix.event.year} {grandprix.event['EventName']}, {ses}"
    if comp == True:
        title = analysis

    elif comp != True:
        title = f"{driver.bio['FullName']} " + analysis
    plt.suptitle(f"{title}")

def design_plot(ax, xvar, yvar):
        ax.set_xlabel(xvar)
        ax.set_ylabel(yvar)

        ax.minorticks_on()
        ax.grid(visible=True, axis='both', which='major', linewidth=0.9, alpha=0.3)
        ax.grid(visible=True, axis='both', which='minor', linestyle=':', linewidth=0.6, alpha=0.3)

        ax.legend()

def show_plot():
    plt.show()

def analyse():
    global year, gp, ses, abb, slice
    global lap_num, xvar, yvar, comp

    year = int(values['-YEAR-'])
    gp = values['-GP-'][0]
    ses = values['-SESSION-']
    abb = values['-DRIVER-']
    slice = values['-SLICE-']
    lap_num = int(values['-LAPNUM-'])
    xvar = values['-DRIVERXVAR-']
    yvar = values['-DRIVERYVAR-']
    comp = values['-COMPARE-']

    fig, ax = make_figure()

    if comp == True:
        compare(grandprix, abb, slice, xvar, yvar, fig, ax, lap_num)
        driver = Driver(grandprix, abb[0])

    elif comp != True:
        driver = Driver(grandprix, abb[0])
        data = set_data(driver, slice, lap_num)
        plot_ax(driver, data, fig, xvar, yvar, ax)

    design_plot(ax, xvar, yvar)
    set_title(grandprix, driver, yvar, slice, ses, lap_num, comp)

    show_plot()

def make_window():
    sg.theme('DarkBlue14')
    lists = Lists()
    menu_def = [[('&Help'), ['&About', '&GitHub', 'E&xit']]]

    header_layout = [[sg.Image(source='src/common/images/icon_header.png', size=(120, 60), expand_x=True, expand_y=True)],]

.
    menu_layout_column = [
            [sg.Menubar(menu_def, key='-MENU-')],
            [sg.Frame('', header_layout, size=(500,100), key='-HEAD-')],
            [sg.OptionMenu(lists.Years.list, default_value=f'{lists.Years.list[-1]}', expand_x=True, key='-YEAR-')],
            [sg.Button('Load Season', size=(10,1), expand_x=True)],
            [sg.Listbox(lists.GrandPrix.list, enable_events=True, expand_x=True, size=(None,10), select_mode='single', horizontal_scroll=False, visible=False, pad=(7,7,7,7), key='-GP-')],
            [sg.OptionMenu(lists.Sessions.list, default_value=f'Select Session...', expand_x=True, visible=False, key='-SESSION-')],
            [sg.Button('Drivers in Session', visible=False, expand_x=True, key='-LOADDRIVERS-')],
            [sg.Listbox(lists.Drivers.list, enable_events=True, expand_x=True, size=(None,10), select_mode='single', horizontal_scroll=False, visible=False, pad=(7,7,7,7), key='-DRIVER-')],
            [sg.Checkbox('Compare drivers?', enable_events=True, visible=False, key='-COMPARE-')],
            [sg.OptionMenu(lists.SessionSlice.list, default_value=f'Evalutate Full Session?', disabled=True, expand_x=True, visible=False, key='-SLICE-')],
            [sg.Text('Enter Lap Number', visible=False, key='-LAPASK-')],
            [sg.Input(default_text= 0, expand_x=True, visible=False, key='-LAPNUM-')],
            [sg.Button('Select Telemetry', visible=False, disabled=True, expand_x=True, key='-LOADVARS-')],
            [sg.OptionMenu(lists.LapVarsY.list, default_value='Y Variable...', expand_x=True, visible=False, key='-DRIVERYVAR-')],
            [sg.OptionMenu(lists.LapVarsX.list, default_value='X Variable...', expand_x=True, visible=False, key='-DRIVERXVAR-')],
            [sg.Button('Confirm All', visible=True, expand_x=True, key='-CONFIRM ALL-')],
            [sg.Button('Submit', visible=True, disabled=True, expand_x=True, key='-PLOT-')],
            ]

    graph_layout_column = [

    ]

    layout = [
        [sg.Column(menu_layout_column),
        sg.VSeparator(),
        sg.Column(graph_layout_column)],
                ]

    window = sg.Window('Gr1dGuru', layout, margins=(10, 10), finalize=True)

    window.set_min_size(window.size)

    return window

I have tried messing around with the FigureCanvasTkAgg with a fixed plot, but when I try modifying anything with my function setup I'm completely stuck.


问:
Call imageCapture.takePicture() inside Analyzer CameraX
I'm trying to use imageCapture.takePicture function from cameraX, but calling it inside my analyzer, so I'm getting "Not Bound To A Valid Camera" CameraX Error, even though my configuration is correct.

```<code>        try {
            cameraProvider.unbindAll()
            cameraProvider.bindToLifecycle(
                lifecycleOwner,
                cameraSelector,
                preview,
                imageCapture,
                faceAnalysis
            )
        } catch (ex: Exception) {
            Log.d("CAMERA-ERROR", "Camera: Error in usage cases")
        }
    }, ContextCompat.getMainExecutor(context))
</code>```

This is my function that I called inside analyzer.

```<code> val metadata = ImageCapture.Metadata().apply {
            // Mirror image when using the front camera
            isReversedHorizontal = cameraSelector == CameraSelector.DEFAULT_FRONT_CAMERA
        }

        MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val outputDirectory: String by lazy {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                "${Environment.DIRECTORY_DCIM}/CameraXDemo/"
            } else {
                "${context.getExternalFilesDir(Environment.DIRECTORY_DCIM)}/CameraXDemo/"
            }
        }

        // Options fot the output image file
        val outputOptions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val contentValues = ContentValues().apply {
                put(MediaStore.MediaColumns.DISPLAY_NAME, System.currentTimeMillis())
                put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
                put(MediaStore.MediaColumns.RELATIVE_PATH, outputDirectory)
            }

            val contentResolver = context.contentResolver

            // Create the output uri
            val contentUri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)

            ImageCapture.OutputFileOptions.Builder(contentResolver, contentUri, contentValues)
        } else {
            File(outputDirectory).mkdirs()
            val file = File(outputDirectory, "${evm.id}.jpg")

            ImageCapture.OutputFileOptions.Builder(file)
        }.setMetadata(metadata).build()

        imageCapture.takePicture(
            outputOptions,
            context.mainExecutor,
            object : ImageCapture.OnImageSavedCallback {
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    outputFileResults.savedUri
                        ?.let { uri ->
                            Log.d("saved", "Photo saved in $uri")
                            Toast.makeText(context, "Foto de en", Toast.LENGTH_SHORT).show()
                        }
                }

                override fun onError(exception: ImageCaptureException) {
                    val msg = "Photo capture failed: ${exception.message}"
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                    Log.e("PHOTO-ERROR", msg)
                    exception.printStackTrace()
                }
            }
        )
</code>```

Then I tried call this function by clicking a button, and is working perfectly. There are any aproach to make this posible but callling it inside my analyzer?

Body:
I'm trying to use imageCapture.takePicture function from cameraX, but calling it inside my analyzer, so I'm getting "Not Bound To A Valid Camera" CameraX Error, even though my configuration is correct.

        try {
            cameraProvider.unbindAll()
            cameraProvider.bindToLifecycle(
                lifecycleOwner,
                cameraSelector,
                preview,
                imageCapture,
                faceAnalysis
            )
        } catch (ex: Exception) {
            Log.d("CAMERA-ERROR", "Camera: Error in usage cases")
        }
    }, ContextCompat.getMainExecutor(context))

This is my function that I called inside analyzer.

 val metadata = ImageCapture.Metadata().apply {
            // Mirror image when using the front camera
            isReversedHorizontal = cameraSelector == CameraSelector.DEFAULT_FRONT_CAMERA
        }

        MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val outputDirectory: String by lazy {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                "${Environment.DIRECTORY_DCIM}/CameraXDemo/"
            } else {
                "${context.getExternalFilesDir(Environment.DIRECTORY_DCIM)}/CameraXDemo/"
            }
        }

        // Options fot the output image file
        val outputOptions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val contentValues = ContentValues().apply {
                put(MediaStore.MediaColumns.DISPLAY_NAME, System.currentTimeMillis())
                put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
                put(MediaStore.MediaColumns.RELATIVE_PATH, outputDirectory)
            }

            val contentResolver = context.contentResolver

            // Create the output uri
            val contentUri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)

            ImageCapture.OutputFileOptions.Builder(contentResolver, contentUri, contentValues)
        } else {
            File(outputDirectory).mkdirs()
            val file = File(outputDirectory, "${evm.id}.jpg")

            ImageCapture.OutputFileOptions.Builder(file)
        }.setMetadata(metadata).build()

        imageCapture.takePicture(
            outputOptions,
            context.mainExecutor,
            object : ImageCapture.OnImageSavedCallback {
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    outputFileResults.savedUri
                        ?.let { uri ->
                            Log.d("saved", "Photo saved in $uri")
                            Toast.makeText(context, "Foto de en", Toast.LENGTH_SHORT).show()
                        }
                }

                override fun onError(exception: ImageCaptureException) {
                    val msg = "Photo capture failed: ${exception.message}"
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                    Log.e("PHOTO-ERROR", msg)
                    exception.printStackTrace()
                }
            }
        )

Then I tried call this function by clicking a button, and is working perfectly. There are any aproach to make this posible but callling it inside my analyzer?


问:
Duplicate/Incorrect Associations when Merging Tables with Power Pivot
I am attempting to create documentation for a wiring project in Excel.

I created a small example where connector A is a 10 pin connector and connector B is a 5 pin connector. I have a table with information about connector A in one table (Pin Numbers and Pin Names), and another table containing information about how the pins on connector A associate the the pins on the two of the B connectors. I'd like to create a pivot table that allows me to show the Pin Names from connector A as a function of connector B ID and Pin Number.

As far as I can tell, this is a very basic example of how to merge data from two tables and PowerPivot should be capable of this, but the tutorials I have followed are not working for me for some reason! I was able to merge the tables using PowerQuery, which I could then use to show the data of in a Pivot table, but I am hoping to do this completely in PowerPivot.

The problem I am having is duplicate/incorrect associations in the PowerPivot Table.

Here is a snip (below) of the table I created using PowerQuery. This table is formatted exactly how I want it to be, but I don't think the method I used to create it will scale well with my project (when I have different permutations of connector A, for example).

And below is the table I get from using PowerPivot.

Note: Each pin name is associated with every possible connector ID and pin number rather than the ones defined in my HarnessDefinition table.

In PowerPivot, I have the two columns linked as shown below. As far as I am aware, this is all that should be required, but for some reason I am seeing every possibility under each connector A name, when there should really only be one association.

I've thought to look at my source data, but it seems correct and analogous to the examples I have seen elsewhere. Here are my two source tables for reference.

Please let me know if you can spot what I am getting wrong!


问:
Nextjs AWS Amplify Build fails because a private npm dependency repository's remote could not be found
I've been encountering an error when trying to deploy my team's Next.js project to AWS Amplify through the AWS Amplify Console. Our project uses two internal packages which are npm installed via a private Github repository link rather than the npm registry. An error we encountered early was not having any deploy keys added for each of our private packages, which was fixed using the solution found here. This solved the issue for one of the private packages, but a new error popped up with the other private package. We keep encountering error in the prebuild phase of the build step for this other private package:

```<code>...
2022-12-19T19:21:31.167Z [WARNING]: npm ERR! code 128
2022-12-19T19:21:31.169Z [WARNING]: npm ERR! An unknown git error occurred
                                    npm ERR! command git --no-replace-objects ls-remote ssh://git@github.com/company/private-repo.git
                                    npm ERR! ERROR: Repository not found.
                                    npm ERR! fatal: Could not read from remote repository.
                                    npm ERR!
                                    npm ERR! Please make sure you have the correct access rights
                                    npm ERR! and the repository exists.
...
</code>```

The other package is being retrieved correctly as in Github it shows that it's deploy key was used, while this one has not. I've tried using a new key for this package, but it still resulted in the same error.

Is there a reason why our private package's repository could not be found? For reference, in our package.json file, we have tried the following for the private package's dependency url:

```<code>git+https://github.com/company/private-package#tag
git@github.com:company/private-pacakge.git#tag
github:company/private-pacakge#tag
</code>```

And here is our build file:

```<code>version: 1
frontend:
  phases:
    preBuild:
      commands:
        - eval "$(ssh-agent -s)"
        - ssh-add <(echo "$PRIVATE_PACKAGE_ONE_DEPLOY_KEY" | base64 -d)
        - ssh-add <(echo "$PRIVATE_PACKAGE_TWO_DEPLOY_KEY" | base64 -d)

        - echo "disable strict host key check"
        - mkdir ~/.ssh
        - touch ~/.ssh/config

        - 'echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'

        - 'git config --global url."https://github.com/".insteadOf ssh://git@github.com/'
        - 'git config --global url."https://github.com/".insteadOf git@github.com:'

        - GIT_SSH_COMMAND="ssh" npm install
        - npm ci
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

</code>```

Body:
I've been encountering an error when trying to deploy my team's Next.js project to AWS Amplify through the AWS Amplify Console. Our project uses two internal packages which are npm installed via a private Github repository link rather than the npm registry. An error we encountered early was not having any deploy keys added for each of our private packages, which was fixed using the solution found here. This solved the issue for one of the private packages, but a new error popped up with the other private package. We keep encountering error in the prebuild phase of the build step for this other private package:

...
2022-12-19T19:21:31.167Z [WARNING]: npm ERR! code 128
2022-12-19T19:21:31.169Z [WARNING]: npm ERR! An unknown git error occurred
                                    npm ERR! command git --no-replace-objects ls-remote ssh://git@github.com/company/private-repo.git
                                    npm ERR! ERROR: Repository not found.
                                    npm ERR! fatal: Could not read from remote repository.
                                    npm ERR!
                                    npm ERR! Please make sure you have the correct access rights
                                    npm ERR! and the repository exists.
...

The other package is being retrieved correctly as in Github it shows that it's deploy key was used, while this one has not. I've tried using a new key for this package, but it still resulted in the same error.

Is there a reason why our private package's repository could not be found? For reference, in our package.json file, we have tried the following for the private package's dependency url:

git+https://github.com/company/private-package#tag
git@github.com:company/private-pacakge.git#tag
github:company/private-pacakge#tag

And here is our build file:

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - eval "$(ssh-agent -s)"
        - ssh-add <(echo "$PRIVATE_PACKAGE_ONE_DEPLOY_KEY" | base64 -d)
        - ssh-add <(echo "$PRIVATE_PACKAGE_TWO_DEPLOY_KEY" | base64 -d)

        - echo "disable strict host key check"
        - mkdir ~/.ssh
        - touch ~/.ssh/config

        - 'echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'

        - 'git config --global url."https://github.com/".insteadOf ssh://git@github.com/'
        - 'git config --global url."https://github.com/".insteadOf git@github.com:'

        - GIT_SSH_COMMAND="ssh" npm install
        - npm ci
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*


问:
React native - Allow scroll inside absolute positionated TouchableOpacity
I have a view with a list of items. The user can click on the menu button of each item and trigger the copy function which will show a button on each item, so that the user can "paste" the selected item and copy it to many other items.

In this image, the user is copying Item 1 into Item 4, 5 and 6.

When the user activate the copy mode, an absolute positioned TouchableOpacity is set in order to capture clicks outside the checkboxes and inform the user if he wants to exit the copy mode. I do that to force the user exit the copy mode.

This however poses the problem that the user is not able to scroll anymore.

Is there a way to detect that the user is scrolling and not clicking the TouchableOpacity?
(Apparently on android I'm able to scroll, while on ios it detects the scroll as a onPress event

Thank you in advance


问:
root filesystem extraction failed with singularity on circleci
I created a test repo to play around with containerization of snakemake workflows. I've got the workflow working locally and on the cluster (slurm) but I can't get it working in circleci. I keep getting:

```<code>Building DAG of jobs...
Pulling singularity image docker://*********/test-containerize:0.0.0.
Using shell: /usr/bin/bash
Provided cores: 1 (use --cores to define parallelism)
Rules claiming more threads will be scaled down.
Conda environments: ignored
Job stats:
job         count    min threads    max threads
--------  -------  -------------  -------------
all             1              1              1
all_TEST        1              1              1
total           2              1              1

Select jobs to execute...

[Mon Dec 19 19:42:03 2022]
rule all_TEST:
    input: test.txt
    output: output.txt
    jobid: 1
    reason: Missing output files: output.txt
    resources: tmpdir=/tmp

Activating singularity image /home/circleci/project/.snakemake/singularity/4f64024d9840ccf1a4d8836c5edc6aa5.simg
INFO:    Converting SIF file to temporary sandbox...
FATAL:   while extracting /home/circleci/project/.snakemake/singularity/4f64024d9840ccf1a4d8836c5edc6aa5.simg: root filesystem extraction failed: extract command failed: ERROR  : Failed to set mount propagation: Operation not permitted
: exit status 1
[Mon Dec 19 19:42:03 2022]
Error in rule all_TEST:
    jobid: 1
    input: test.txt
    output: output.txt
    conda-env: /home/circleci/project/.snakemake/conda/cc6395ec670d10af0374c53e5653fb76_
    shell:
        cat test.txt > output.txt
        (one of the commands exited with non-zero exit code; note that snakemake uses bash strict mode!)

Shutting down, this might take some time.
Exiting because a job execution failed. Look above for error message
Complete log: .snakemake/log/2022-12-19T194136.569293.snakemake.log

Exited with code exit status 1
</code>```

I don't have enough experience with containers to know what's going wrong here, seems like maybe a permissions issue, except I'm also getting the same error locally with a more complicated workflow that I tried to set up containerization for. Any help is appreciated. Thanks.

Body:
I created a test repo to play around with containerization of snakemake workflows. I've got the workflow working locally and on the cluster (slurm) but I can't get it working in circleci. I keep getting:

Building DAG of jobs...
Pulling singularity image docker://*********/test-containerize:0.0.0.
Using shell: /usr/bin/bash
Provided cores: 1 (use --cores to define parallelism)
Rules claiming more threads will be scaled down.
Conda environments: ignored
Job stats:
job         count    min threads    max threads
--------  -------  -------------  -------------
all             1              1              1
all_TEST        1              1              1
total           2              1              1

Select jobs to execute...

[Mon Dec 19 19:42:03 2022]
rule all_TEST:
    input: test.txt
    output: output.txt
    jobid: 1
    reason: Missing output files: output.txt
    resources: tmpdir=/tmp

Activating singularity image /home/circleci/project/.snakemake/singularity/4f64024d9840ccf1a4d8836c5edc6aa5.simg
INFO:    Converting SIF file to temporary sandbox...
FATAL:   while extracting /home/circleci/project/.snakemake/singularity/4f64024d9840ccf1a4d8836c5edc6aa5.simg: root filesystem extraction failed: extract command failed: ERROR  : Failed to set mount propagation: Operation not permitted
: exit status 1
[Mon Dec 19 19:42:03 2022]
Error in rule all_TEST:
    jobid: 1
    input: test.txt
    output: output.txt
    conda-env: /home/circleci/project/.snakemake/conda/cc6395ec670d10af0374c53e5653fb76_
    shell:
        cat test.txt > output.txt
        (one of the commands exited with non-zero exit code; note that snakemake uses bash strict mode!)

Shutting down, this might take some time.
Exiting because a job execution failed. Look above for error message
Complete log: .snakemake/log/2022-12-19T194136.569293.snakemake.log

Exited with code exit status 1

I don't have enough experience with containers to know what's going wrong here, seems like maybe a permissions issue, except I'm also getting the same error locally with a more complicated workflow that I tried to set up containerization for. Any help is appreciated. Thanks.


问:
How do I document events with ESdoc?
Using ESDoc, is there a way to document events as used in code such as:

```<code>class Example extends EventEmitter {
   doSomethingAsynchronously () {
      ....then( () => this.emit('anevent', params) )....
   }
   // and many other methods that can also emit various events defined by this class,
   // including methods that may emit 'anevent'.
}
</code>```

Here, the "anevent" event is associated with the class Example, not with any particular method of it. Multiple methods may emit that event, and the API is designed such that it doesn't matter what method emits the event (this is the intent of events to begin with), as on('anevent', ...) would be called on an Example instance, not on the return value of some particular method.

Also, this code simply uses the functionality of the base EventEmitter, it does not define any custom event code that can itself serve as a documentation target.

In other words, events are a property of the class Example, and not of anything else.

However, ESdoc does not seem to recognize @emits in class documentation, only in method documentation, even though it is the class that "owns" the events.

Is there a way to document the events in this type of code with ESdoc?

I mean I can always just do some custom formatted list in the class documentation, but I'm wondering if there's a built-in way to do it, first.

Title: How do I document events with ESdoc?

Body:
Using ESDoc, is there a way to document events as used in code such as:

class Example extends EventEmitter {
   doSomethingAsynchronously () {
      ....then( () => this.emit('anevent', params) )....
   }
   // and many other methods that can also emit various events defined by this class,
   // including methods that may emit 'anevent'.
}

Here, the "anevent" event is associated with the class Example, not with any particular method of it. Multiple methods may emit that event, and the API is designed such that it doesn't matter what method emits the event (this is the intent of events to begin with), as on('anevent', ...) would be called on an Example instance, not on the return value of some particular method.

Also, this code simply uses the functionality of the base EventEmitter, it does not define any custom event code that can itself serve as a documentation target.

In other words, events are a property of the class Example, and not of anything else.

However, ESdoc does not seem to recognize @emits in class documentation, only in method documentation, even though it is the class that "owns" the events.

Is there a way to document the events in this type of code with ESdoc?

I mean I can always just do some custom formatted list in the class documentation, but I'm wondering if there's a built-in way to do it, first.


问:
i have defined block content in base.html and extents in index.html , block content is not working
in template/app/index.html

```<code>{% extends 'base.html' %}

{% block content %}
replace me
{% endblock %}
</code>```

in template/app/base.html

```<code><!doctype html>
<html>
<head>
    <title>Base title</title>
    </head>
<body>
    {% block content %}
    {% endblock %}
    </body>
</html>
</code>```

in app/urls.py

```<code>from django.urls import path
from app import views
urlpatterns = [
    path('',views.index)
]

</code>```

in app/views.py

```<code>from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request,'app/base.html',{})
</code>```

this is the code...!

i have tried changing the folder location and saw level of the folder

Body:
in template/app/index.html

{% extends 'base.html' %}

{% block content %}
replace me
{% endblock %}

in template/app/base.html

<!doctype html>

    <title>Base title</title>

    {% block content %}
    {% endblock %}

in app/urls.py

from django.urls import path
from app import views
urlpatterns = [
    path('',views.index)
]

in app/views.py

from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request,'app/base.html',{})

this is the code...!

i have tried changing the folder location and saw level of the folder


问:
Problem with compiling app in Delphi 10.4
I am compiling a simple app in Delphi 10.4 for iOS, and the following error occurs:

[PAClient Error] Error: E6665 Cannot open file "/Users/techtrs/PAServer/scratch-dir/techtrs/ImpactoSFA.launchscreen/partial_info.plist". No such file or directory

Does anyone know what the problem is?


问:
Apollo and type-graphql can't find input mutation/query
I'm trying to pass an input to my graphql query and my resolver can't find the input

I have my docker container set to log info and I can see the input is being passed, the log that gets posted looks like this:

```<code>{ getAllPayments(input: {processed: true}) { id processed } }
</code>```

But when I console log input it contains my entity manager data:

```<code><ref *3> EntityManager {
  repositories: [],
  plainObjectToEntityTransformer: PlainObjectToNewEntityTransformer {},
  connection: <ref *1> Connection {
    migrations: [...],
    subscribers: [],
    entityMetadatas: [
      [EntityMetadata],
      [EntityMetadata],
      [EntityMetadata],
      [EntityMetadata]
    ],
    name: 'default',
    options: {...},
    logger: AdvancedConsoleLogger { options: undefined },
    driver: PostgresDriver {...},
    manager: EntityManager {
      repositories: [],
      plainObjectToEntityTransformer: PlainObjectToNewEntityTransformer {},
      connection: [Circular *1]
    },
    namingStrategy: DefaultNamingStrategy {
      nestedSetColumnNames: [Object],
      materializedPathColumnName: 'mpath'
    },
    metadataTableName: 'typeorm_metadata',
    queryResultCache: undefined,
    relationLoader: RelationLoader { connection: [Circular *1] },
    isConnected: true
  },
  queryRunner: <ref *2> PostgresQueryRunner {
    isReleased: false,
    isTransactionActive: true,
    data: {},
    loadedTables: [],
    loadedViews: [],
    sqlMemoryMode: false,
    sqlInMemory: SqlInMemory { upQueries: [], downQueries: [] },
    transactionDepth: 1,
    cachedTablePaths: {},
    driver: PostgresDriver {...},
    connection: <ref *1> Connection {...},
    mode: 'master',
    broadcaster: Broadcaster { queryRunner: [Circular *2] },
    manager: [Circular *3],
    databaseConnectionPromise: Promise { [Client] },
    databaseConnection: Client {...}
    },
    releaseCallback: [Function (anonymous)]
  }
}
</code>```

I replaced some objects with {...}*

My resolver looks like this:

```<code>  @Transaction()
  @Query(() => [Payment], { nullable: false })
  async getAllPayments(
    @Arg('input', { nullable: true }) input?: GetPaymentsInput
  ): Promise<Payment[]> {
    if (!input?.processed) {
      throw new ApolloError('no input passed');
    }

    return getCustomRepository(PaymentRepository).getAll({
      processed: input?.processed,
      paymentProvider: input?.paymentProvider,
      paymentType: input.paymentType,
    });
  }
</code>```

And my GetPaymentsInput type looks like this:

```<code>@InputType({
  description: 'Input type for getting payments.',
})
export class GetPaymentsInput {
  @Field(() => Boolean, {
    nullable: true,
    description: 'Whether or not the payment is processed.',
  })
  processed?: boolean;
...
}
</code>```

Body:
I'm trying to pass an input to my graphql query and my resolver can't find the input

I have my docker container set to log info and I can see the input is being passed, the log that gets posted looks like this:

{ getAllPayments(input: {processed: true}) { id processed } }

But when I console log input it contains my entity manager data:

<ref *3> EntityManager {
  repositories: [],
  plainObjectToEntityTransformer: PlainObjectToNewEntityTransformer {},
  connection: <ref *1> Connection {
    migrations: [...],
    subscribers: [],
    entityMetadatas: [
      [EntityMetadata],
      [EntityMetadata],
      [EntityMetadata],
      [EntityMetadata]
    ],
    name: 'default',
    options: {...},
    logger: AdvancedConsoleLogger { options: undefined },
    driver: PostgresDriver {...},
    manager: EntityManager {
      repositories: [],
      plainObjectToEntityTransformer: PlainObjectToNewEntityTransformer {},
      connection: [Circular *1]
    },
    namingStrategy: DefaultNamingStrategy {
      nestedSetColumnNames: [Object],
      materializedPathColumnName: 'mpath'
    },
    metadataTableName: 'typeorm_metadata',
    queryResultCache: undefined,
    relationLoader: RelationLoader { connection: [Circular *1] },
    isConnected: true
  },
  queryRunner: <ref *2> PostgresQueryRunner {
    isReleased: false,
    isTransactionActive: true,
    data: {},
    loadedTables: [],
    loadedViews: [],
    sqlMemoryMode: false,
    sqlInMemory: SqlInMemory { upQueries: [], downQueries: [] },
    transactionDepth: 1,
    cachedTablePaths: {},
    driver: PostgresDriver {...},
    connection: <ref *1> Connection {...},
    mode: 'master',
    broadcaster: Broadcaster { queryRunner: [Circular *2] },
    manager: [Circular *3],
    databaseConnectionPromise: Promise { [Client] },
    databaseConnection: Client {...}
    },
    releaseCallback: [Function (anonymous)]
  }
}

I replaced some objects with {...}*

My resolver looks like this:

  @Transaction()
  @Query(() => [Payment], { nullable: false })
  async getAllPayments(
    @Arg('input', { nullable: true }) input?: GetPaymentsInput
  ): Promise<Payment[]> {
    if (!input?.processed) {
      throw new ApolloError('no input passed');
    }

    return getCustomRepository(PaymentRepository).getAll({
      processed: input?.processed,
      paymentProvider: input?.paymentProvider,
      paymentType: input.paymentType,
    });
  }

And my GetPaymentsInput type looks like this:

@InputType({
  description: 'Input type for getting payments.',
})
export class GetPaymentsInput {
  @Field(() => Boolean, {
    nullable: true,
    description: 'Whether or not the payment is processed.',
  })
  processed?: boolean;
...
}


Title: Css/javascript/jquery Make svg image dynamically transparent based on background

Body:
I'm trying to make an svg transparent when on a div with a dark background. The final objective is to have the red svg disappear, leaving the hollow black border in place.

I've already thinked of using z-index but this is part of a global header, removing this option.

I've already tried to follow the solution on this thread "How to get mix-blend-mode scroll effect using javascript?" but the solutions doesn't seem suitable for my case.

To do some test at the moment the red svg is used as a mask for a div, but if necessary or better the original svg can be placed like the black border.

Here the link to a jsfiddle with the structure of the test page i'm using : https://jsfiddle.net/qvgtyx46/

<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="style.css">

            <svg xmlns="http://www.w3.org/2000/svg" width="60px" height="60px" version="1.1" viewBox="0 0 100 100">
 <path d="m65.734 32.469c9.375-5.0234 16.742-4.6602 28.379-6.0625-10.992 7.2695-15.949 7.4453-21.719 16.277 10.629 0.33594 16.832 4.3359 27.605 8.9414-13.156 0.80078-17.535-1.5234-26.949 3.2383 9.0391 5.6055 12.41 12.168 19.438 21.547-11.793-5.8828-14.422-10.09-24.957-10.672 5.0234 9.375 4.6602 16.742 6.0625 28.379-7.2695-10.992-7.4453-15.949-16.277-21.719-0.33594 10.629-4.3359 16.832-8.9414 27.605-0.80078-13.156 1.5234-17.535-3.2344-26.949-5.6055 9.0352-12.168 12.41-21.547 19.438 5.8867-11.793 10.09-14.426 10.672-24.957-9.375 5.0234-16.742 4.6602-28.379 6.0625 10.992-7.2695 15.949-7.4453 21.719-16.277-10.629-0.33594-16.832-4.3359-27.605-8.9414 13.156-0.80078 17.535 1.5234 26.949-3.2383-9.0391-5.6055-12.41-12.168-19.438-21.547 11.793 5.8867 14.422 10.09 24.957 10.672-5.0234-9.375-4.6602-16.742-6.0625-28.379 7.2695 10.992 7.4453 15.949 16.277 21.719 0.33594-10.629 4.3359-16.828 8.9414-27.605 0.80078 13.156-1.5234 17.535 3.2344 26.949 5.6055-9.0352 12.168-12.406 21.547-19.438-5.8867 11.793-10.09 14.426-10.672 24.957z" fill="none" stroke-width="2" stroke="black"/>
            </svg>

          lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum

         lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum

         lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum lorem pisum

.fill {
    background: red;
    width: 60px;
    height: 60px;
    position: fixed;
    z-index: 9998;
    -webkit-mask-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/sun.svg);
    mask-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/sun.svg);
    -webkit-mask-size: 60px;
}

.hollow {
    position: fixed;
    z-index: 9999;
    position: fixed;
}

.is-dark {
  display: block;
  height: 600px;
  width: 100%;
  position:relative;
  z-index:0;
  background:green;
}

.is-light {
  display: block;
  position:relative;
  height: 600px;
  width: 100%;
  background: #fff;
  color:#000;
}

UPDATE: Using jquery now i'm able to do it, but only on the first div if is dark https://jsfiddle.net/36fcj9p0/.


问:
How can I manually change the date format of a Pivot Chart?
I have a Pivot Table that has been used to create a Pivot Chart. The x-axis shows dates, while the y-axis shows the magnitude of the data against each date. The date format being used is "mm/dd/yyyy" - however, when I try to change the format to "dd-mmm", the change doesn't reflect onto the chart. I've tried the following methods with no results:

Change the date format in the raw data used to create the Pivot Table

Change the date format in the Pivot Table itself

Right-click the x-axis labels, select "Format Axis", expand the "Number" format settings, select "Date" in the Category dropdown menu and select "dd-mmm" in the Format dropdown menu

Create a new Pivot Chart to test if the pre-existing Pivot Chart has some restrictions on changing label formats

Right-clicking the x-axis labels and opening the Field Settings dialog box doesn't help, because it doesn't show the "Number Format" button that many Google-searched tutorials suggest.


问:
Find p-value through bootstrapping method in periodogram
I have trouble running a bootstrapping method to estimate p-value in a periodogram of my timeseries (myts) from spec.pgram():

```<code># Defining a function for computing the periodogram of a time series
periodogram_fun <- function(x, ind) {
  spec.pgram(ts(x[ind], start=1, end=365), plot=FALSE)$spec
}

# Using the "boot" function to create a set of bootstrapped periodograms
bootstrapped_periodograms <- boot(myts, periodogram_fun, R=1000)

# Calculating a p-value based on the comparison of the observed periodogram
# to the distribution of bootstrapped periodograms
pvalue <- sum(spec.pgram(myts)$spec > quantile(bootstrapped_periodograms$t[,2], probs=0.95)) / 1000
</code>```

If anyone has an idea about how to calculate p-value from timeseries in a periodogram I would thank so much.

Body:
I have trouble running a bootstrapping method to estimate p-value in a periodogram of my timeseries (myts) from spec.pgram():

# Defining a function for computing the periodogram of a time series
periodogram_fun <- function(x, ind) {
  spec.pgram(ts(x[ind], start=1, end=365), plot=FALSE)$spec
}

# Using the "boot" function to create a set of bootstrapped periodograms
bootstrapped_periodograms <- boot(myts, periodogram_fun, R=1000)

# Calculating a p-value based on the comparison of the observed periodogram
# to the distribution of bootstrapped periodograms
pvalue <- sum(spec.pgram(myts)$spec > quantile(bootstrapped_periodograms$t[,2], probs=0.95)) / 1000

If anyone has an idea about how to calculate p-value from timeseries in a periodogram I would thank so much.


问:
Ultra zooming mouse how to tell the first wheel event after rotate the wheel (Logitech MX Master 3S)
I'm a Web frontend developer (JavaScript). I see with "Smooth scrolling" on (MX Master 3S), if I rotate the wheel a step, my mouse will split 1 wheel event with 1.0 wheelDelta into multiple wheel events with fractional delta. But the split events' delta can make 1.0 delta in sum.

My mouse just split the events and release them slowly?

My need is to reverse the split events back to normal mouse's event.

The idea was generally to add the delta together, if make 1.0 then release a wheel event and filter other events in between.

But painpoint is, this mouse releases the events during a 926ms period. During which, if user rotates another time, we need to know this is a new rotating from user and need to reset the delta accumulator.

So, my question is: How can we tell this the first events from a series of events split by mouse driver? Can we tell it from the details of a wheel event in JS?

Thanks!


问:
Creating balanced dataset for YOLO v5 with each image having multiple annotations
Currently using the YOLO v5 code from this https://github.com/ultralytics/yolov5 in which each txt has a line referring to the <object-class> <x> <y> <width> <height> (image below). Each image has multiple classes (in the annotation file below the image has a <object-class> of 0 and 27). The goal is to select an equal number of object-class from the entire dataset. Currently, the issue is that the image comes with the other labels/bounding boxes too. How can I filter so only a certain row is read from the annotation file? Currently have 1000s of annotation files.

image source: COCO json annotation to YOLO txt format


问:
Login without a password is forbidden by configuration (see AllowNoPassword) (on cpanel)
Login error while accessing phpmyadmin on cpanel. how to solve this error on cpanel for wordpress website.

i have tried to create new user for database but still facing error.


问:
Return a max of 5 items per manufacturer
I am trying to understand how to return a maximum of 5 items for each manufacturer from an inventory table, so that no manufacturer can have more than 5 items shown in a list of 100 recent items at any time. The purpose is to avoid any single manufacturer dominating the list of recent items. The basic query is:

```<code>SELECT id, manufacturer_id, product_name, price
FROM inventory_items
WHERE visibility=1 AND availability=1 AND manufacturer_id IN (vw_active_vendor_ids)
ORDER BY creation_datetime DESC LIMIT 0, 100
</code>```

Conceptually I think I could achieve this by looping through the entire table in a stored procedure, putting the manufacturer id in a temp table and counting them on each loop, but this seems like an expensive operation.

I tried various inner joins and groups but these were completely wrong.

Followed the example here MySQL: how to get x number of results per grouping but the query took > 20 sec to execute which doesn't work for an e-commerce site.

```<code>SELECT *, (SELECT manufacturer_name FROM manufacturer WHERE manufacturer.id=t.manufacturer_id) AS manufacturer_name  FROM
  (SELECT t1.id, t1.manufacturer_id, t1.title, t1.price, t1.creation_datetime , COUNT(*) cnt FROM inventory_items t1
    LEFT JOIN inventory_items t2
      ON t2.manufacturer_id = t1.manufacturer_id AND t2.id <= t1.id
      WHERE t1.availability=1  AND t1.visibility=1
      AND t2.availability=1 and t2.visibility=1
      AND t1.manufacturer_id IN (SELECT id FROM vw_active_vendor_ids)
      AND t2.manufacturer_id IN (SELECT id FROM vw_active_vendor_ids)
  GROUP BY
    t1.manufacturer_id, t1.id
  ) t
WHERE
  cnt < 6
ORDER BY creation_datetime  DESC
LIMIT 0,100
</code>```

Body:
I am trying to understand how to return a maximum of 5 items for each manufacturer from an inventory table, so that no manufacturer can have more than 5 items shown in a list of 100 recent items at any time. The purpose is to avoid any single manufacturer dominating the list of recent items. The basic query is:

SELECT id, manufacturer_id, product_name, price
FROM inventory_items
WHERE visibility=1 AND availability=1 AND manufacturer_id IN (vw_active_vendor_ids)
ORDER BY creation_datetime DESC LIMIT 0, 100

Conceptually I think I could achieve this by looping through the entire table in a stored procedure, putting the manufacturer id in a temp table and counting them on each loop, but this seems like an expensive operation.

I tried various inner joins and groups but these were completely wrong.

Followed the example here MySQL: how to get x number of results per grouping but the query took > 20 sec to execute which doesn't work for an e-commerce site.

SELECT *, (SELECT manufacturer_name FROM manufacturer WHERE manufacturer.id=t.manufacturer_id) AS manufacturer_name  FROM
  (SELECT t1.id, t1.manufacturer_id, t1.title, t1.price, t1.creation_datetime , COUNT(*) cnt FROM inventory_items t1
    LEFT JOIN inventory_items t2
      ON t2.manufacturer_id = t1.manufacturer_id AND t2.id <= t1.id
      WHERE t1.availability=1  AND t1.visibility=1
      AND t2.availability=1 and t2.visibility=1
      AND t1.manufacturer_id IN (SELECT id FROM vw_active_vendor_ids)
      AND t2.manufacturer_id IN (SELECT id FROM vw_active_vendor_ids)
  GROUP BY
    t1.manufacturer_id, t1.id
  ) t
WHERE
  cnt < 6
ORDER BY creation_datetime  DESC
LIMIT 0,100


问:
ReactJS accessing current prop state under custom window event
Using ReactJS to create a small reusable component; however I am stumped on accessing the current props inside a custom window event.

```<code>import React, { useEffect, useState } from "react";
import "./styles.css";

export const TestFun = (props) => {
  const handleClick = () =>{
    console.log(props.page);
  }

  useEffect(()=>{
    window.addEventListener("click", handleClick, false)
    return () => window.removeEventListener("click", handleClick, false)
  },[])

  return(<h1>{props.page}</h1>)
}

export default function App() {
  const [page,setPage] = useState(1);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <TestFun page={page} />
      <button onClick={()=>setPage(page+1)}>Click Me</button>
    </div>
  );
}
</code>```

When this little gem is run, it updates the props correctly on the button click but the page number remains the same in the console.

I've tried using useRef() but it is certain that I am not using it correctly because my results don't change.  Can someone give me a nudge in the right direction, please.

Body:
Using ReactJS to create a small reusable component; however I am stumped on accessing the current props inside a custom window event.

import React, { useEffect, useState } from "react";
import "./styles.css";

export const TestFun = (props) => {
  const handleClick = () =>{
    console.log(props.page);
  }

  useEffect(()=>{
    window.addEventListener("click", handleClick, false)
    return () => window.removeEventListener("click", handleClick, false)
  },[])

  return(
{props.page}
)
}

export default function App() {
  const [page,setPage] = useState(1);

  return (

Hello CodeSandbox

      <TestFun page={page} />
      <button onClick={()=>setPage(page+1)}>Click Me</button>

  );
}

When this little gem is run, it updates the props correctly on the button click but the page number remains the same in the console.

I've tried using useRef() but it is certain that I am not using it correctly because my results don't change.  Can someone give me a nudge in the right direction, please.


问:
print complex dictionary content recursively to tree
given the following xml:

```<code><?xml version="1.0" encoding="windows-1252"?>
<xmi:XMI xmlns:uml="http://www.omg.org/spec/UML/20110701" xmlns:xmi="http://www.omg.org/spec/XMI/20110701" xmlns:thecustomprofile="http://www.sparxsystems.com/profiles/thecustomprofile/1.0">
    <xmi:Documentation exporter="Enterprise Architect" exporterVersion="6.5"/>
    <uml:Model xmi:type="uml:Model" name="EA_Model">
        <packagedElement xmi:type="uml:Package" xmi:id="EAPK_FE6A1ABF_4C30_4d66_A200_B29CA55BB50F" name="Root 2">
            <packagedElement xmi:type="uml:Package" xmi:id="EAPK_B25F74E8_35C4_4404_B8C6_C733378D8AFA" name="Package1"/>
            <packagedElement xmi:type="uml:Package" xmi:id="EAPK_8302563D_1E79_40a0_9D73_4E7959BDE221" name="Package2">
                <packagedElement xmi:type="uml:Package" xmi:id="EAPK_1D028092_F199_4043_B690_6373C191272C" name="Package2.1"/>
                <packagedElement xmi:type="uml:Package" xmi:id="EAPK_497888C3_5A47_4d13_BC81_DEF83A199E45" name="Package2.2">
                    <ownedComment xmi:type="uml:Comment" xmi:id="EAID_3A953EDE_D11A_4900_B583_36D8C904E4A1" body="Note"/>
                    <packagedElement xmi:type="uml:Class" xmi:id="EAID_887464C9_87B5_441c_9882_6C9E9A0CA720" name="Class1">
                        <generalization xmi:type="uml:Generalization" xmi:id="EAID_EAE102FD_9B8C_4f91_B7C5_7A87EBBE6F7B" general="EAID_7A45F41C_DFDF_4ef9_BFDA_9D7405BCB6A3"/>
                    </packagedElement>
                    <packagedElement xmi:type="uml:Association" xmi:id="EAID_5513510F_B792_4008_877F_7109B223CE5C">
                        <memberEnd xmi:idref="EAID_dst13510F_B792_4008_877F_7109B223CE5C"/>
                        <memberEnd xmi:idref="EAID_src13510F_B792_4008_877F_7109B223CE5C"/>
                        <ownedEnd xmi:type="uml:Property" xmi:id="EAID_src13510F_B792_4008_877F_7109B223CE5C" association="EAID_5513510F_B792_4008_877F_7109B223CE5C" aggregation="shared">
                            <type xmi:idref="EAID_78E607A2_9161_4e62_887F_9585CF6771DA"/>
                        </ownedEnd>
                    </packagedElement>
                    <packagedElement xmi:type="uml:Class" xmi:id="EAID_78E607A2_9161_4e62_887F_9585CF6771DA" name="Class2">
                        <ownedAttribute xmi:type="uml:Property" xmi:id="EAID_dst13510F_B792_4008_877F_7109B223CE5C" association="EAID_5513510F_B792_4008_877F_7109B223CE5C">
                            <type xmi:idref="EAID_887464C9_87B5_441c_9882_6C9E9A0CA720"/>
                        </ownedAttribute>
                    </packagedElement>
                    <packagedElement xmi:type="uml:Class" xmi:id="EAID_7A45F41C_DFDF_4ef9_BFDA_9D7405BCB6A3" name="Class3"/>
                    <ownedRule xmi:type="uml:Constraint" xmi:id="EAID_7E61CF9B_4137_4ee8_878D_61F03566DAE8">
                        <specification xmi:type="uml:OpaqueExpression" xmi:id="EAID_OE000000_4137_4ee8_878D_61F03566DAE8" body="pvf_Class2"/>
                    </ownedRule>
                </packagedElement>
            </packagedElement>
        </packagedElement>
        <profileApplication xmi:type="uml:ProfileApplication" xmi:id="profileap_thecustomprofile">
            <appliedProfile xmi:type="uml:Profile" href="http://www.sparxsystems.com/profiles/thecustomprofile/1.0#thecustomprofile"/>
        </profileApplication>
    </uml:Model>
</xmi:XMI>
</code>```

which i read into a xml file using the xmltodict lib:

```<code>with open(xml_file, "r") as f:
    xml_content = f.read()
dct = xmltodict.parse(xml_content)
</code>```

I am struggling with the nested loop to print the tree. I am not sure how to reset the counter for example to start a new node. I am also not sure if i am on the right way. I don`t want to use any XPATH stuff here, just keep the loop as general as possible..

```<code>def p(d, counter = 0, c = 0):
    for k, v in d.items():
        print("|___"*counter, k)
        if isinstance(v, dict):
            c = len(v)
            if(c > counter):
                counter += 1
            else:
                counter = 0
            p(v, counter, c)
        elif isinstance(v, list):
            for i, v2 in enumerate(v):
                print("|___" * counter, k)
                p(v2, counter)
</code>```

The result should be like:

```<code>xmi
|_Model
   |_packagedElement (Root 2)
       | _ packagedElement (Package1)
       | - packagedElement (Package2)
             | _ packagedElement (Package2.1)
             | _ packagedElement (Package2.2)
                   | _ ownedComment (Note)
                   | _ ...
</code>```

Any help is really appreciated..

Body:
given the following xml:

<?xml version="1.0" encoding="windows-1252"?>
<xmi:XMI xmlns:uml="http://www.omg.org/spec/UML/20110701" xmlns:xmi="http://www.omg.org/spec/XMI/20110701" xmlns:thecustomprofile="http://www.sparxsystems.com/profiles/thecustomprofile/1.0">
    <xmi:Documentation exporter="Enterprise Architect" exporterVersion="6.5"/>
    <uml:Model xmi:type="uml:Model" name="EA_Model">
        <packagedElement xmi:type="uml:Package" xmi:id="EAPK_FE6A1ABF_4C30_4d66_A200_B29CA55BB50F" name="Root 2">
            <packagedElement xmi:type="uml:Package" xmi:id="EAPK_B25F74E8_35C4_4404_B8C6_C733378D8AFA" name="Package1"/>
            <packagedElement xmi:type="uml:Package" xmi:id="EAPK_8302563D_1E79_40a0_9D73_4E7959BDE221" name="Package2">
                <packagedElement xmi:type="uml:Package" xmi:id="EAPK_1D028092_F199_4043_B690_6373C191272C" name="Package2.1"/>
                <packagedElement xmi:type="uml:Package" xmi:id="EAPK_497888C3_5A47_4d13_BC81_DEF83A199E45" name="Package2.2">
                    <ownedComment xmi:type="uml:Comment" xmi:id="EAID_3A953EDE_D11A_4900_B583_36D8C904E4A1" body="Note"/>
                    <packagedElement xmi:type="uml:Class" xmi:id="EAID_887464C9_87B5_441c_9882_6C9E9A0CA720" name="Class1">
                        <generalization xmi:type="uml:Generalization" xmi:id="EAID_EAE102FD_9B8C_4f91_B7C5_7A87EBBE6F7B" general="EAID_7A45F41C_DFDF_4ef9_BFDA_9D7405BCB6A3"/>
                    </packagedElement>
                    <packagedElement xmi:type="uml:Association" xmi:id="EAID_5513510F_B792_4008_877F_7109B223CE5C">
                        <memberEnd xmi:idref="EAID_dst13510F_B792_4008_877F_7109B223CE5C"/>
                        <memberEnd xmi:idref="EAID_src13510F_B792_4008_877F_7109B223CE5C"/>
                        <ownedEnd xmi:type="uml:Property" xmi:id="EAID_src13510F_B792_4008_877F_7109B223CE5C" association="EAID_5513510F_B792_4008_877F_7109B223CE5C" aggregation="shared">
                            <type xmi:idref="EAID_78E607A2_9161_4e62_887F_9585CF6771DA"/>
                        </ownedEnd>
                    </packagedElement>
                    <packagedElement xmi:type="uml:Class" xmi:id="EAID_78E607A2_9161_4e62_887F_9585CF6771DA" name="Class2">
                        <ownedAttribute xmi:type="uml:Property" xmi:id="EAID_dst13510F_B792_4008_877F_7109B223CE5C" association="EAID_5513510F_B792_4008_877F_7109B223CE5C">
                            <type xmi:idref="EAID_887464C9_87B5_441c_9882_6C9E9A0CA720"/>
                        </ownedAttribute>
                    </packagedElement>
                    <packagedElement xmi:type="uml:Class" xmi:id="EAID_7A45F41C_DFDF_4ef9_BFDA_9D7405BCB6A3" name="Class3"/>
                    <ownedRule xmi:type="uml:Constraint" xmi:id="EAID_7E61CF9B_4137_4ee8_878D_61F03566DAE8">
                        <specification xmi:type="uml:OpaqueExpression" xmi:id="EAID_OE000000_4137_4ee8_878D_61F03566DAE8" body="pvf_Class2"/>
                    </ownedRule>
                </packagedElement>
            </packagedElement>
        </packagedElement>
        <profileApplication xmi:type="uml:ProfileApplication" xmi:id="profileap_thecustomprofile">
            <appliedProfile xmi:type="uml:Profile" href="http://www.sparxsystems.com/profiles/thecustomprofile/1.0#thecustomprofile"/>
        </profileApplication>
    </uml:Model>
</xmi:XMI>

which i read into a xml file using the xmltodict lib:

with open(xml_file, "r") as f:
    xml_content = f.read()
dct = xmltodict.parse(xml_content)

I am struggling with the nested loop to print the tree. I am not sure how to reset the counter for example to start a new node. I am also not sure if i am on the right way. I don`t want to use any XPATH stuff here, just keep the loop as general as possible..

def p(d, counter = 0, c = 0):
    for k, v in d.items():
        print("|___"*counter, k)
        if isinstance(v, dict):
            c = len(v)
            if(c > counter):
                counter += 1
            else:
                counter = 0
            p(v, counter, c)
        elif isinstance(v, list):
            for i, v2 in enumerate(v):
                print("|___" * counter, k)
                p(v2, counter)

The result should be like:

xmi
|_Model
   |_packagedElement (Root 2)
       | _ packagedElement (Package1)
       | - packagedElement (Package2)
             | _ packagedElement (Package2.1)
             | _ packagedElement (Package2.2)
                   | _ ownedComment (Note)
                   | _ ...

Any help is really appreciated..


问:
Red line for code in IntelliJ not appearing in Netbeans - gradle project builds fine
In Netbeans, my code looks like this:

Whereas, in IntelliJ, my code looks like this:

Both IDE's run a gradle build of the project that builds without incident.

So, therefore, why should there be a wavy red line under the second line of code in the IntelliJ IDE?

I suspect this is a JDK version problem, and that perhaps my IntelliJ JDK version is wrong. Being that I am new to IntelliJ, how would I check this?

When my code looks like this, the IntelliJ IDE does not complain:

```<code>ContextResonance<?,S>rCtx=subscriber.getContainer().getContainer().contextResonance();
ContextReferent<?,S>ref=rCtx.getReferent();
</code>```

But when I replace either explicit declaration with a var type (in this particular case, the first declaration), the same IDE gives me the following:

As I observe Netbeans issues no complaints whether I used the var keyword or an explicit type declaration, I think there is a problem with IntelliJ.

Are there any work-arounds for this?

In further work, I have discovered this false negative: one file is error free in IntelliJ, yet Netbeans reports an error, and the project doesn't build.

The IntelliJ code is:

The same code in Netbeans is:

Why would I want to be arsed with IntelliJ when it doesn't seem to reliably report problems with my code?

Body:
In Netbeans, my code looks like this:

Whereas, in IntelliJ, my code looks like this:

Both IDE's run a gradle build of the project that builds without incident.

So, therefore, why should there be a wavy red line under the second line of code in the IntelliJ IDE?

I suspect this is a JDK version problem, and that perhaps my IntelliJ JDK version is wrong. Being that I am new to IntelliJ, how would I check this?

When my code looks like this, the IntelliJ IDE does not complain:

ContextResonance<?,S>rCtx=subscriber.getContainer().getContainer().contextResonance();
ContextReferent<?,S>ref=rCtx.getReferent();

But when I replace either explicit declaration with a var type (in this particular case, the first declaration), the same IDE gives me the following:

As I observe Netbeans issues no complaints whether I used the var keyword or an explicit type declaration, I think there is a problem with IntelliJ.

Are there any work-arounds for this?

In further work, I have discovered this false negative: one file is error free in IntelliJ, yet Netbeans reports an error, and the project doesn't build.

The IntelliJ code is:

The same code in Netbeans is:

Why would I want to be arsed with IntelliJ when it doesn't seem to reliably report problems with my code?


问:
I want to preprocess corpus of text using an NLTK library. My corpus includes 4 different txt files
I uploaded my corpus on drive and then I mounted google drive on google Colab and uploaded my text corpus on google Colab.
Now, I'm supposed to preprocess this corpus in order to do topic modeling next. Now, after having uploaded my corpus, how can I work on the text files contained in it ? E.g. how do I tokenize the 4 files contained in my corpus?
This is what I have done:

```<code>import nltk
from nltk.corpus import PlaintextCorpusReader
from gensim import corpora

from google.colab import drive
drive.mount('/content/drive')
corpus_root='/content/drive/MyDrive/Text1'
corpus=PlaintextCorpusReader(corpus_root,'.\*')
corpus.fileids()

nltk.download('punkt')
def tokenize(text):
tokens = nltk.word_tokenize(text)
return tokens
</code>```

This is what I obtained:

```<code>\[nltk_data\] Downloading package punkt to /root/nltk_data...
\[nltk_data\]   Package punkt is already up-to-date!
</code>```

How should I procede from now on?
Should I create a bag-of-words corpus using Gensim? Also, should I proceed working on corpus or on corpus_root ?

Body:
I uploaded my corpus on drive and then I mounted google drive on google Colab and uploaded my text corpus on google Colab.
Now, I'm supposed to preprocess this corpus in order to do topic modeling next. Now, after having uploaded my corpus, how can I work on the text files contained in it ? E.g. how do I tokenize the 4 files contained in my corpus?
This is what I have done:

import nltk
from nltk.corpus import PlaintextCorpusReader
from gensim import corpora

from google.colab import drive
drive.mount('/content/drive')
corpus_root='/content/drive/MyDrive/Text1'
corpus=PlaintextCorpusReader(corpus_root,'.\*')
corpus.fileids()

nltk.download('punkt')
def tokenize(text):
tokens = nltk.word_tokenize(text)
return tokens

This is what I obtained:

\[nltk_data\] Downloading package punkt to /root/nltk_data...
\[nltk_data\]   Package punkt is already up-to-date!

How should I procede from now on?
Should I create a bag-of-words corpus using Gensim? Also, should I proceed working on corpus or on corpus_root ?