问:
How to create editable inline elements in CKEditor5 with actual nodes not text attributes
We work with a backend that tags words like Persons or locations. I send text to the backend and it tags me words. I have to create tags in the ckeditor frontend.

So I have the task to create editable inline elements, means they should be addable to where text is addable.

The tag must be editable.

The tag should also be visible if its empty (should be a own tree node not text attribute).

The tag should have visual highlighting, like a background-color and border radius.

If the tag is empty, its type should be added via css' ::before pseudo class and content property.

It would be nice if you can toggle it's edtiable part. Since we also need readonly tags, their are developed as seperate elements so far.

My approach so far was using text attributes applying:

```<code>writer.createText('my tag', {tag: tagType})
</code>```

I was basically creating tags like you would create bold text. I was applying css styles like background-color and border radius to make it look like a tag, but this approach came to it's limits. Also with this approach you cannot have editable and non-editable tags be the same ckeditor entity, since you cannot have non-editable text, I guess.

Then I found editableElement's in the view side. The Problem is you cannot have emtpy tags since empty text is nothing. You also cannot modify the "tag" at index 0 because then you are outside of the tag, see bold behavior for this. I mean I could somehow fix it all, but I would like the tags to be their own element on model side. so I have tried this approach:

```<code>// in editingDowncast conversion:
viewWriter.createEditableElement('div', {class: 'inline'})

// this is the whole code in the ui:

        this.editor.model.schema.register( 'test-tag', {
            allowChildren: '$text',
            allowWhere: '$text',
            allowAttributesOf: '$text',
            isObject: true
        });
        // if it is isInline: true it behaves mostly like my approach with text attributes

        this.editor.conversion.for('editingDowncast').elementToElement({
            model: 'test-tag',
            view: (modelItem, conversionApi) => {

                let { writer: viewWriter } = conversionApi;

                const tagView = viewWriter.createEditableElement( 'div', {

                    class: 'inline'

                });

                return tagView;

            }
        })

</code>```

basically EdtiableElement's work only with block elements, so I have tried to make them inline via css, setting their display property to inline-block. Here I have again the problem that when the element is empty you cannot access it anymore via cursor. So it will stay empty forever. Generelly it seems that it's behavior is kind of buggy because I guess you should not use it as inline. Basically I have many similiar issues like with the approach above.

I will keep implementing it with the first solution but I wanted to ask the community if there is any other way, maybe a less hacky way to create inline editable elements that are actual nodes in the model. Something like a span tag but on model side.
Any Ideas?

Body:
We work with a backend that tags words like Persons or locations. I send text to the backend and it tags me words. I have to create tags in the ckeditor frontend.

So I have the task to create editable inline elements, means they should be addable to where text is addable.

The tag must be editable.

The tag should also be visible if its empty (should be a own tree node not text attribute).

The tag should have visual highlighting, like a background-color and border radius.

If the tag is empty, its type should be added via css' ::before pseudo class and content property.

It would be nice if you can toggle it's edtiable part. Since we also need readonly tags, their are developed as seperate elements so far.

My approach so far was using text attributes applying:

writer.createText('my tag', {tag: tagType})

I was basically creating tags like you would create bold text. I was applying css styles like background-color and border radius to make it look like a tag, but this approach came to it's limits. Also with this approach you cannot have editable and non-editable tags be the same ckeditor entity, since you cannot have non-editable text, I guess.

Then I found editableElement's in the view side. The Problem is you cannot have emtpy tags since empty text is nothing. You also cannot modify the "tag" at index 0 because then you are outside of the tag, see bold behavior for this. I mean I could somehow fix it all, but I would like the tags to be their own element on model side. so I have tried this approach:

// in editingDowncast conversion:
viewWriter.createEditableElement('div', {class: 'inline'})

// this is the whole code in the ui:

        this.editor.model.schema.register( 'test-tag', {
            allowChildren: '$text',
            allowWhere: '$text',
            allowAttributesOf: '$text',
            isObject: true
        });
        // if it is isInline: true it behaves mostly like my approach with text attributes

        this.editor.conversion.for('editingDowncast').elementToElement({
            model: 'test-tag',
            view: (modelItem, conversionApi) => {

                let { writer: viewWriter } = conversionApi;

                const tagView = viewWriter.createEditableElement( 'div', {

                    class: 'inline'

                });

                return tagView;

            }
        })

basically EdtiableElement's work only with block elements, so I have tried to make them inline via css, setting their display property to inline-block. Here I have again the problem that when the element is empty you cannot access it anymore via cursor. So it will stay empty forever. Generelly it seems that it's behavior is kind of buggy because I guess you should not use it as inline. Basically I have many similiar issues like with the approach above.

I will keep implementing it with the first solution but I wanted to ask the community if there is any other way, maybe a less hacky way to create inline editable elements that are actual nodes in the model. Something like a span tag but on model side.
Any Ideas?


来源: stackexchange

问:
How to cache and reuse data shared between multiple users?
I am currently working on a webapp where case investigation details will be stored and displayed to the end user. The investigation details is a shared data where all the users who worked in that investigation(user permissions are provided) can view and edit the data. We have planned for a feature to show all the investigation over a year/month under one window. In such case we need to fetch a huge details over the network, as we can have multiple department working in multiple investigations(in their departments  as well as other departments too). So the data fetched in pretty huge(even though I fetch only the basic details of those investigations).

I make a request for every year/month. There is an option for navigating to and fro and when the user comes back to a year/month which he has already seen, i make the request and fetch the data once again(this is done because the investigation details are dynamic and shared b/w users. Also any user at any moment may modify it too). Caching was one of the option suggested but i am unsure when to cache and when to stale the cached data. Any suggestions/ideas are appreciated.

ContentLicense: CC BY-SA 4.0


问:
Adding values to the 4th dimension of an empty numpy array
Im trying to make an ordered 4 dimentional array with dimentions being latitude, longitude month and data.
i have all my data sorted based on latitude, longitude and month in separate lists, but for analysing them further i need to store them in a way that i can access it. so far i managed to to a nested for list to solve my problem and i will attach the code. i was wondering if its possible to do this with numpy since by using a 4D nested list it is taking lots of computational power. also, the datapoints that i have for all the months and locations is dynamic basically, my dimenstions would be 18,28,12,?.

P.S. Temperature_monthly function, gives me a list for a specific coordianets and month.

```<code>
def param_sorted_loc_month(lst1,lst2):
    """
    :param lst1: Variable Dataset
    :param lst2: Monthly index
    :return: Sorted temperature data for all the locations and months
    """
    dummy = []
    for i in range(len(lst1)):
        dummy1 = []
        for j in range(len(lst1[i])):
            dummy2 = []
            for k in range(len(lst2)):
                dummy2.append(Temperature_monthly(i, j, k, lst1, lst2))
            dummy1.append(dummy2)
        dummy.append(dummy1)

    return dummy
</code>```

Body:
Im trying to make an ordered 4 dimentional array with dimentions being latitude, longitude month and data.
i have all my data sorted based on latitude, longitude and month in separate lists, but for analysing them further i need to store them in a way that i can access it. so far i managed to to a nested for list to solve my problem and i will attach the code. i was wondering if its possible to do this with numpy since by using a 4D nested list it is taking lots of computational power. also, the datapoints that i have for all the months and locations is dynamic basically, my dimenstions would be 18,28,12,?.

P.S. Temperature_monthly function, gives me a list for a specific coordianets and month.

def param_sorted_loc_month(lst1,lst2):
    """
    :param lst1: Variable Dataset
    :param lst2: Monthly index
    :return: Sorted temperature data for all the locations and months
    """
    dummy = []
    for i in range(len(lst1)):
        dummy1 = []
        for j in range(len(lst1[i])):
            dummy2 = []
            for k in range(len(lst2)):
                dummy2.append(Temperature_monthly(i, j, k, lst1, lst2))
            dummy1.append(dummy2)
        dummy.append(dummy1)

    return dummy


问:
Octave doesn't disp my values, and only stores in ans variable
```<code>function t = metodoDeNewton(a, t0, N, epsilon)
  a = 2;
  epsilon = 1e-10;
  t0 = 1;
  N = 20;
  t = zeros(1, N+1);
  t(1) = t0;
  for i = 1:N
    t(i+1) = t(i) - (t(i)^2 - (a - sin(t(i)))) / (2 * t(i) - cos(t(i)));
    if (abs(t(i+1) - t(i)) < epsilon)
    break;
  endif
endfor
endfunction

t = metodoDeNewton(a, t0, N, epsilon);

% Mostra a última iteração, que é a aproximação da raiz da equação
disp(t(end));

% Estima a ordem de convergência e o coeficiente assintótico de convergência
% Para isso, calcula a razão entre duas iterações consecutivas e a razão entre
% o erro absoluto dessas iterações e o erro absoluto das iterações anteriores
r = zeros(1, length(t) - 1);
k = zeros(1, length(t) - 1);
for i = 2:length(t)
  r(i-1) = t(i) / t(i-1);
  k(i-1) = abs(t(i) - t(i-1)) / abs(t(i-1) - t(i-2));
endfor

% Mostra a razão e o coeficiente assintótico de convergência
x = disp(r(end))
y = disp(k(end))
</code>```

The code doesn't display my final values, and it doesn't store any of the variables I define either (like the r and k variables), the only variable it stores is the ans, and I don't really understand where it's that's coming from.

Body:
function t = metodoDeNewton(a, t0, N, epsilon)
  a = 2;
  epsilon = 1e-10;
  t0 = 1;
  N = 20;
  t = zeros(1, N+1);
  t(1) = t0;
  for i = 1:N
    t(i+1) = t(i) - (t(i)^2 - (a - sin(t(i)))) / (2 * t(i) - cos(t(i)));
    if (abs(t(i+1) - t(i)) < epsilon)
    break;
  endif
endfor
endfunction

t = metodoDeNewton(a, t0, N, epsilon);

% Mostra a última iteração, que é a aproximação da raiz da equação
disp(t(end));

% Estima a ordem de convergência e o coeficiente assintótico de convergência
% Para isso, calcula a razão entre duas iterações consecutivas e a razão entre
% o erro absoluto dessas iterações e o erro absoluto das iterações anteriores
r = zeros(1, length(t) - 1);
k = zeros(1, length(t) - 1);
for i = 2:length(t)
  r(i-1) = t(i) / t(i-1);
  k(i-1) = abs(t(i) - t(i-1)) / abs(t(i-1) - t(i-2));
endfor

% Mostra a razão e o coeficiente assintótico de convergência
x = disp(r(end))
y = disp(k(end))

The code doesn't display my final values, and it doesn't store any of the variables I define either (like the r and k variables), the only variable it stores is the ans, and I don't really understand where it's that's coming from.


问:
How to make the space bar go to the VS code terminal?

I have a problem that is becoming a nuisance, I am writing the code and I decide to run it in the vs code terminal but when I run the space bar stays in the code, and I have to move the mouse to interact with the terminal, does anyone know how to change that?


问:
Export TypeScript Class with 'export' as part of the result?
I have written a TypeScript Class

```<code>export class myClass{
   //Code here...
}
</code>```

I would like the following result af compile:

```<code>export function myClass() {

}
</code>```

The compiled JS is for a Blazor WASM app.

How should I write my TypeScript?

With Blazor I have the opportunity to JSInvoke javascript code but from what I have learned it only invokes exported functions.

/* UPDATE */

With target set to ES5 I can get the TS code transpiled to:

```<code>function myClass() {
}
</code>```

But I need the 'export' in front?

```<code>export function myClass() {

}
</code>```

Body:
I have written a TypeScript Class

export class myClass{
   //Code here...
}

I would like the following result af compile:

export function myClass() {

}

The compiled JS is for a Blazor WASM app.

How should I write my TypeScript?

With Blazor I have the opportunity to JSInvoke javascript code but from what I have learned it only invokes exported functions.

/* UPDATE */

With target set to ES5 I can get the TS code transpiled to:

function myClass() {
}

But I need the 'export' in front?

export function myClass() {

}


问:
Authorise apis of other application using django authentication system
I have a requirement to build an application say A. The application A is an authentication system, and i'm planning to build it in django using django oauth toolkit library.

Then there will be some external applications say B and C, and they will be using the auth system A.

How can I implement the authorisation for the applications A and B?

Application B and C will be built on other languages like php or java.

django oauth toolkit documentation describes an api for authentication where the client_id, client_secret, username and password is being sent to an api and the token is being generated. I need to use that token to authorise the APIs in application B and C

Need your insight on this one.

Thanks in advance.


问:
"Access blocked: project-165437914245’s request is invalid" to get a code for Google Assistant SDK
OAuth 2.0

With the message below, i cannot get an authorization code for the credentials.

Sign in with Google
Access blocked: project-165437914245’s request is invalid

You can’t sign in because project-165437914245 sent an invalid request. You can try again later, or contact the developer about this issue. Learn more about this error
If you are a developer of project-165437914245, see error details.
Error 400: invalid_request

console
In hte OAuth consent screen,
set Publishing status to In production
set User type to External
in Test users section, add users to my e-mail address


问:
Problems with inference time and memory in YOLOV7
I'm testing the difference between yolov5 and yolov7 in my code but is not working as it is in the main graphic of the comparison with the real-time object detectors, the yolov7 is slower than the v5(almost the double of the time) and is using more ram too, I'm using exactly the same code of the v7 with some alterations to run inside my code ( just put the detect file in a class).

Do someone knows what could possibly is happening here? Or having the same problem? Or even maybe I'm using it wrong? Because as I said, is the exactly same code but in a class now.


问:
Webpack cannot resolve dynamic imports at runtime
I am using Nx. I built an app using Webpack. Now in a dependent library, there's a dynamic import statement. Webpack gives error on runtime as Module not found with complete path of the file that is not found. Interestingly the file is present in it's location. Basically I am finding all the files that ends with .migration.js using glob pattern and then importing them at runtime.

The error stack is:

```<code>/home/mwaqar666/code/sca/dist/apps/sca-cmd/libs_backend_db_src_index_ts.js:22
                        var e = new Error("Cannot find module '" + req + "'");
                                ^
Error: Cannot find module '/home/mwaqar666/code/sca/dist/libs/backend/data-access-layer/src/domains/user/2022_12_14_09_45_17_941_create-users-table.migration.js'
    at /home/mwaqar666/code/sca/dist/apps/sca-cmd/libs_backend_db_src_index_ts.js:22:12 {
  code: 'MODULE_NOT_FOUND'
}
Node.js v18.12.1
Error: Command failed: NODE_ENV=dev node dist/apps/sca-cmd/main.js migration:up
    at checkExecSyncError (node:child_process:871:11)
    at execSync (node:child_process:943:15)
    at createSyncProcess (/home/mwaqar666/code/sca/node_modules/nx/src/executors/run-commands/run-commands.impl.js:166:34)
    at /home/mwaqar666/code/sca/node_modules/nx/src/executors/run-commands/run-commands.impl.js:113:13
    at Generator.next (<anonymous>)
    at /home/mwaqar666/code/sca/node_modules/tslib/tslib.js:118:75
    at new Promise (<anonymous>)
    at Object.__awaiter (/home/mwaqar666/code/sca/node_modules/tslib/tslib.js:114:16)
    at runSerially (/home/mwaqar666/code/sca/node_modules/nx/src/executors/run-commands/run-commands.impl.js:111:20) {
  status: 1,
  signal: null,
  output: [ null, null, null ],
  pid: 52699,
  stdout: null,
  stderr: null
}
</code>```

The file that is reported to be missing is present at it's place in dist folder which makes this error even weirder.

Steps to reproduce this:

Clone this project repo: https://github.com/mwaqar666/sca

Switch to branch backend/backend-integration.

Run npx nx run sca-cmd:build (Build the command-line application using Webpack)

Run npx nx run backend-data-access-layer:build (Build the lib using tsc which contains files to import)

Run npx nx run sca-cmd:run:dev --verbose -- migration:up (This simply executes the sca-cmd app using node)

Relevant Info

```<code>Webpack version: 5.75.0
Node.js version: 18.12.1
Operating System: Ubuntu 22.04.1 LTS (Jammy Jellyfish)
Nx version: 15.3.3
Typescript version: 4.9.4
</code>```

Body:
I am using Nx. I built an app using Webpack. Now in a dependent library, there's a dynamic import statement. Webpack gives error on runtime as Module not found with complete path of the file that is not found. Interestingly the file is present in it's location. Basically I am finding all the files that ends with .migration.js using glob pattern and then importing them at runtime.

The error stack is:

/home/mwaqar666/code/sca/dist/apps/sca-cmd/libs_backend_db_src_index_ts.js:22
                        var e = new Error("Cannot find module '" + req + "'");
                                ^
Error: Cannot find module '/home/mwaqar666/code/sca/dist/libs/backend/data-access-layer/src/domains/user/2022_12_14_09_45_17_941_create-users-table.migration.js'
    at /home/mwaqar666/code/sca/dist/apps/sca-cmd/libs_backend_db_src_index_ts.js:22:12 {
  code: 'MODULE_NOT_FOUND'
}
Node.js v18.12.1
Error: Command failed: NODE_ENV=dev node dist/apps/sca-cmd/main.js migration:up
    at checkExecSyncError (node:child_process:871:11)
    at execSync (node:child_process:943:15)
    at createSyncProcess (/home/mwaqar666/code/sca/node_modules/nx/src/executors/run-commands/run-commands.impl.js:166:34)
    at /home/mwaqar666/code/sca/node_modules/nx/src/executors/run-commands/run-commands.impl.js:113:13
    at Generator.next (<anonymous>)
    at /home/mwaqar666/code/sca/node_modules/tslib/tslib.js:118:75
    at new Promise (<anonymous>)
    at Object.__awaiter (/home/mwaqar666/code/sca/node_modules/tslib/tslib.js:114:16)
    at runSerially (/home/mwaqar666/code/sca/node_modules/nx/src/executors/run-commands/run-commands.impl.js:111:20) {
  status: 1,
  signal: null,
  output: [ null, null, null ],
  pid: 52699,
  stdout: null,
  stderr: null
}

The file that is reported to be missing is present at it's place in dist folder which makes this error even weirder.

Steps to reproduce this:

Clone this project repo: https://github.com/mwaqar666/sca

Switch to branch backend/backend-integration.

Run npx nx run sca-cmd:build (Build the command-line application using Webpack)

Run npx nx run backend-data-access-layer:build (Build the lib using tsc which contains files to import)

Run npx nx run sca-cmd:run:dev --verbose -- migration:up (This simply executes the sca-cmd app using node)

Relevant Info

Webpack version: 5.75.0
Node.js version: 18.12.1
Operating System: Ubuntu 22.04.1 LTS (Jammy Jellyfish)
Nx version: 15.3.3
Typescript version: 4.9.4


问:
Collect /metrics Prometheus in Azure Container Apps
I'm starting with Azure Container Apps, and I have a question:

All my applications issue a /metrics endpoint that my Prometheus server consumes.

I configured it for 5 instances of container apps. Soon I will have 5 applications running in parallel.

myapplication.com/metrics

Whenever my prometheus accesses /metrics it should collect a different metric due to traffic balancing.

How can I integrate the /metrics export with the average of the 5 container instances via prometheus?

I know that with Kubernetes it is possible, but I intend to use Azure Container Apps.


问:
how to fix iPhone safari browser horizontal scroll issue?
```<code><html lang="en">

    <head>
        <meta charset="utf-8" />
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
        name="viewport" />
        <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"
        />
        <meta http-equiv="Pragma" content="no-cache" />
        <meta http-equiv="Expires" content="0" />
        <meta name="referrer" content="origin" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="baidu-site-verification" content="n9jz6vZbmg" />
        <style>
            * { -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } html, body { width:
            100%; height: 100%; margin: 0; padding: 0; } #app { width: 100%; height:
            100%; }
        </style>
        <style type="text/css">
            .container-bg-color { width: 100%; background: #f7f9fc; height: 100%;
            padding-top: 64px; } .album { width: 100%; position: relative; overflow-y:
            auto; overflow-x: hidden; height: 100%; }
        </style>
    </head>

    <body>
        <div id="app">
            <div style="width: 100%; height: 100%" class="album-layout-63969875c674f44c32168603">
                <div class="container-bg-color" style="padding-top: 0px">
                    <div class="album">
                        <div style="
                        width: 100%;
                        overflow: none;
                        overflow-x: auto;
                        white-space: nowrap;
                        ">
                            <div style="margin-right: 20px; display: inline-block">
                                <div style="
                                background-color: red;
                                height: 120px;
                                width: 120px;
                                position: relative;
                                ">
                                </div>
                            </div>
                            <div style="margin-right: 20px; display: inline-block">
                                <div style="
                                background-color: green;
                                height: 120px;
                                width: 120px;
                                position: relative;
                                ">
                                </div>
                            </div>
                            <div style="margin-right: 20px; display: inline-block">
                                <div style="
                                background-color: red;
                                height: 120px;
                                width: 120px;
                                position: relative;
                                ">
                                </div>
                            </div>
                            <div style="margin-right: 20px; display: inline-block">
                                <div style="
                                background-color: red;
                                height: 120px;
                                width: 120px;
                                position: relative;
                                ">
                                </div>
                            </div>
                        </div>
                        <div>
                            <div>
                                <video controls="" playsinline="" style="width: 100%; height: 222px">
                                </video>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>

</html>
</code>```

this is my code , that has a problem when run in safari.

when scroll top , content render not change but scrollbar changed. then delete video element, the scroll is normal. I don't know why they clashed. Can someone give me an answer.

What causes this problem. This is only exist in safari , chrome is normal.

Body:
        <meta charset="utf-8" />
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
        name="viewport" />
        <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"
        />
        <meta http-equiv="Pragma" content="no-cache" />
        <meta http-equiv="Expires" content="0" />
        <meta name="referrer" content="origin" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="baidu-site-verification" content="n9jz6vZbmg" />

                                <video controls="" playsinline="" style="width: 100%; height: 222px">
                                </video>

this is my code , that has a problem when run in safari.

when scroll top , content render not change but scrollbar changed. then delete video element, the scroll is normal. I don't know why they clashed. Can someone give me an answer.

What causes this problem. This is only exist in safari , chrome is normal.


问:
Why useEffect invoked two times, when redux toolkit function dispatched
I was checked everything, All sections are working good but when I triggered a dispatch ,their dependencies invoked two time!

Bellow is my reducer function :

```<code>recieveMessage(
  state,
  { payload: { message, topic } }: PayloadAction<IWebSocket>,
) {
  console.log('Recive Message from websocket ', message, topic)
  state.recive = { message, topic }
},
</code>```

and useEffect

```<code>const { socketReducer: { recive } } = useSelector(RootSelector);

useEffect(() => {
    recive && console.log("Fetch from redux")
}, [recive])
</code>```

Why it fired two time?

Body:
I was checked everything, All sections are working good but when I triggered a dispatch ,their dependencies invoked two time!

Bellow is my reducer function :

recieveMessage(
  state,
  { payload: { message, topic } }: PayloadAction<IWebSocket>,
) {
  console.log('Recive Message from websocket ', message, topic)
  state.recive = { message, topic }
},

and useEffect

const { socketReducer: { recive } } = useSelector(RootSelector);

useEffect(() => {
    recive && console.log("Fetch from redux")
}, [recive])

Why it fired two time?


问:
jQuery / AngularJS post whole HTML page code with values
I have a Webapp, using AngularJS with asp.net / C# backend.

I need to send the rendered HTML Page to the backend.

I tried different methods, things like document.getElementById("...").innerHTML, but the values from ng-model (in inputs and textareas) are always empty/not visible.

Here is a bit of code i use:

angularjs controller:

```<code>function EditController(user) {
   var vm = this;

   vm.user = user.data.User;
   ...
}

function Print() {
    vm.user.Name = document.getElementById('Name').textContent;
    vm.user.Description = document.getElementById('Description').textContent;

    //THIS IS THE QUESTION
    **vm.user.Html = document.documentElement.html();**

    Service.create('User/print', vm.user).then(successfullyPrinted, errorOnPrinting);
 }
</code>```

angularjs view:

```<code>...
<div class="row">
    <div class="col-sm-6">
        <label class="control-label">Name:</label>
    </div>
    <div class="col-sm-7 ">
        <input type="text" id="Name" class="form-control" ng-model="vm.user.Name">
    </div>
</div>
<div class="row">
    <div class="col-sm-6">
        <label class="control-label">Desc:</label>
    </div>
    <div class="col-sm-7 ">
        <textarea type="text" id="Description" ng-model="vm.user.Description"></textarea>
    </div>
</div>
...
</code>```

For example, the rendered html looks like this:

```<code><textarea type="text" name="x1" id="x1" ng-model="vm.user.Description" class="ng-pristine ng-untouched ng-valid"></textarea>
</code>```

It shows the value, but not in the plain html text... What do i need to do, so that the values would be visible in the html code?

The goal is to create a pdf File in the backend (it has to be there), exactly like the html page is shown.

Thanks for any help

Body:
I have a Webapp, using AngularJS with asp.net / C# backend.

I need to send the rendered HTML Page to the backend.

I tried different methods, things like document.getElementById("...").innerHTML, but the values from ng-model (in inputs and textareas) are always empty/not visible.

Here is a bit of code i use:

angularjs controller:

function EditController(user) {
   var vm = this;

   vm.user = user.data.User;
   ...
}

function Print() {
    vm.user.Name = document.getElementById('Name').textContent;
    vm.user.Description = document.getElementById('Description').textContent;

    //THIS IS THE QUESTION
    **vm.user.Html = document.documentElement.html();**

    Service.create('User/print', vm.user).then(successfullyPrinted, errorOnPrinting);
 }

angularjs view:

...

        Name:

        <input type="text" id="Name" class="form-control" ng-model="vm.user.Name">

        Desc:

        <textarea type="text" id="Description" ng-model="vm.user.Description"></textarea>

...

For example, the rendered html looks like this:

<textarea type="text" name="x1" id="x1" ng-model="vm.user.Description" class="ng-pristine ng-untouched ng-valid"></textarea>

It shows the value, but not in the plain html text... What do i need to do, so that the values would be visible in the html code?

The goal is to create a pdf File in the backend (it has to be there), exactly like the html page is shown.

Thanks for any help


问:
problem in Dictionaries and replace method (python)
im try to make a app witch take words and its trun to security form

its ok with first part
but in second part: i want to turn that word who truned into a security form trun it into a word again and its return incorrect like this :
word: 'hnnh'
sec form: 'yhhy'
But when I try to turn it back, it writes the wrong word: 'nnnn'

and its the problem

code:

```<code>

from tkinter import Tk,Button,Label,Entry

words ={'q':'0','w':'1','e':'2','r':'3','t':'4','y':'5','u':'%','i':'7','o':'8',
    'p':'9','a':'q','s':'w','d':'e','f':'r','g':'t','h':'y','j':'u','k':'i',
    'z':'a','x':'s','c':'d','v':'f','b':'g','n':'h','m':'j','l':'o',
    '1':'z','2':'x','3':'c','4':'v','5':'b','6':'m','7':'.','8':'#','9':'@','0':'!',
    '@':'$','#':':','!':'&',':':'*','.':'n',' ':'6'}

sec ={'0':'q','1':'w','2':'e','3':'r','4':'t','5':'y','%':'u','7':'i','8':'o',
    '9':'p','q':'a','w':'s','e':'d','r':'f','t':'g','y':'h','u':'j',
    'o':'l','a':'z','s':'x','d':'c','f':'v','g':'b','j':'m',
    'z':'1','x':'2','c':'3','v':'4','b':'5','m':'6','.':'7','#':'8','@':'9','!':'0',
    '$':'@',':':'#','&':'!','*':':','6':' ','n':'.','h':'n','i':'k'}
def word_to_sec():
    in_use_words = str(word_to_sec_ent.get())
    for char in words:
        if char in str(word_to_sec_ent.get()):
            in_use_words = in_use_words.replace(char,words[char])
    output = in_use_words
    config_lbl.config(text= 'word to sec: {}'.format(output))
    return output

def sec_to_word():
    in_use_words = str(sec_to_word_ent.get())
    for chars in words:
        for char in words[chars]:
            if char in str(sec_to_word_ent.get()):
                in_use_words = in_use_words.replace(words[char],char)
    output = in_use_words
    config_lbl.config(text= 'sec to word: {}'.format(output))
    return output

window = Tk()
window.title('sec_maker           made by: parsa')

word_to_sec_lbl = Label(window,text= 'enter word to convert into the sec form:          ')
word_to_sec_lbl.grid(row=1,column=1)
word_to_sec_ent = Entry(window)
word_to_sec_ent.grid(row=2,column=1)
word_to_sec_btn = Button(window,text='convert to sec form',command=word_to_sec)
word_to_sec_btn.grid(row=3,column=1)

sec_to_word_lbl = Label(window,text= 'enter sec form to convert into the word:')
sec_to_word_lbl.grid(row=1,column=3)
sec_to_word_ent = Entry(window)
sec_to_word_ent.grid(row=2,column=3)
sec_to_word_btn = Button(window,text='convert to word',command=sec_to_word)
sec_to_word_btn.grid(row=3,column=3)

config_lbl = Label(window,text='out put: ')
config_lbl.grid(row=4,column=2)

window.mainloop()

</code>```

Body:
im try to make a app witch take words and its trun to security form

its ok with first part
but in second part: i want to turn that word who truned into a security form trun it into a word again and its return incorrect like this :
word: 'hnnh'
sec form: 'yhhy'
But when I try to turn it back, it writes the wrong word: 'nnnn'

and its the problem

code:

from tkinter import Tk,Button,Label,Entry

words ={'q':'0','w':'1','e':'2','r':'3','t':'4','y':'5','u':'%','i':'7','o':'8',
    'p':'9','a':'q','s':'w','d':'e','f':'r','g':'t','h':'y','j':'u','k':'i',
    'z':'a','x':'s','c':'d','v':'f','b':'g','n':'h','m':'j','l':'o',
    '1':'z','2':'x','3':'c','4':'v','5':'b','6':'m','7':'.','8':'#','9':'@','0':'!',
    '@':'$','#':':','!':'&',':':'*','.':'n',' ':'6'}

sec ={'0':'q','1':'w','2':'e','3':'r','4':'t','5':'y','%':'u','7':'i','8':'o',
    '9':'p','q':'a','w':'s','e':'d','r':'f','t':'g','y':'h','u':'j',
    'o':'l','a':'z','s':'x','d':'c','f':'v','g':'b','j':'m',
    'z':'1','x':'2','c':'3','v':'4','b':'5','m':'6','.':'7','#':'8','@':'9','!':'0',
    '$':'@',':':'#','&':'!','*':':','6':' ','n':'.','h':'n','i':'k'}
def word_to_sec():
    in_use_words = str(word_to_sec_ent.get())
    for char in words:
        if char in str(word_to_sec_ent.get()):
            in_use_words = in_use_words.replace(char,words[char])
    output = in_use_words
    config_lbl.config(text= 'word to sec: {}'.format(output))
    return output

def sec_to_word():
    in_use_words = str(sec_to_word_ent.get())
    for chars in words:
        for char in words[chars]:
            if char in str(sec_to_word_ent.get()):
                in_use_words = in_use_words.replace(words[char],char)
    output = in_use_words
    config_lbl.config(text= 'sec to word: {}'.format(output))
    return output

window = Tk()
window.title('sec_maker           made by: parsa')

word_to_sec_lbl = Label(window,text= 'enter word to convert into the sec form:          ')
word_to_sec_lbl.grid(row=1,column=1)
word_to_sec_ent = Entry(window)
word_to_sec_ent.grid(row=2,column=1)
word_to_sec_btn = Button(window,text='convert to sec form',command=word_to_sec)
word_to_sec_btn.grid(row=3,column=1)

sec_to_word_lbl = Label(window,text= 'enter sec form to convert into the word:')
sec_to_word_lbl.grid(row=1,column=3)
sec_to_word_ent = Entry(window)
sec_to_word_ent.grid(row=2,column=3)
sec_to_word_btn = Button(window,text='convert to word',command=sec_to_word)
sec_to_word_btn.grid(row=3,column=3)

config_lbl = Label(window,text='out put: ')
config_lbl.grid(row=4,column=2)

window.mainloop()


问:
update quantity of product after checkout
I am trying to update the item quantity after the finished transaction. I have quantity on my item and I wanted to lessen the item quantity depending on the item ordered. the transaction works fine but the problem is the update does not execute and it does not update the quantity of the item in my table.

the code:

```<code><?php
include 'includes/session.php';

if(isset($_GET['confirmation'])){
    $confirmation = $_GET['confirmation'];
    $p_quantity = $_GET['p_quantity'];
    $date = date('Y-m-d');

    $conn = $pdo->open();

    try{

        $stmt = $conn->prepare("INSERT INTO sales (user_id, confirmation, status, sales_date) VALUES (:user_id, :confirmation, :status,  :sales_date)");
        $stmt->execute(['user_id'=>$user['id'], 'confirmation'=>$confirmation, 'status'=>1,  'sales_date'=>$date]);
        $salesid = $conn->lastInsertId();

                $stmt = $conn->prepare("UPDATE products SET p_quantity=p_quantity-:p_quantity WHERE id=:id");
                $stmt->execute(['p_quantity'=>$p_quantity, 'id'=>$id]);

        try{
            $stmt = $conn->prepare("SELECT * FROM cart LEFT JOIN products ON products.id=cart.product_id WHERE user_id=:user_id");
            $stmt->execute(['user_id'=>$user['id']]);

            foreach($stmt as $row){
                $stmt = $conn->prepare("INSERT INTO details (sales_id, product_id, quantity) VALUES (:sales_id, :product_id, :quantity)");
                $stmt->execute(['sales_id'=>$salesid, 'product_id'=>$row['product_id'], 'quantity'=>$row['quantity']]);

            }

            $stmt = $conn->prepare("DELETE FROM cart WHERE user_id=:user_id");
            $stmt->execute(['user_id'=>$user['id']]);

            $_SESSION['success'] = 'Transaction successful. Thank you.';

        }
        catch(PDOException $e){
            $_SESSION['error'] = $e->getMessage();
        }

    }
    catch(PDOException $e){
        $_SESSION['error'] = $e->getMessage();
    }

    $pdo->close();
}

header('location: profile.php');
</code>```

?>

Body:
I am trying to update the item quantity after the finished transaction. I have quantity on my item and I wanted to lessen the item quantity depending on the item ordered. the transaction works fine but the problem is the update does not execute and it does not update the quantity of the item in my table.

the code:

<?php
include 'includes/session.php';

if(isset($_GET['confirmation'])){
    $confirmation = $_GET['confirmation'];
    $p_quantity = $_GET['p_quantity'];
    $date = date('Y-m-d');

    $conn = $pdo->open();

    try{

        $stmt = $conn->prepare("INSERT INTO sales (user_id, confirmation, status, sales_date) VALUES (:user_id, :confirmation, :status,  :sales_date)");
        $stmt->execute(['user_id'=>$user['id'], 'confirmation'=>$confirmation, 'status'=>1,  'sales_date'=>$date]);
        $salesid = $conn->lastInsertId();

                $stmt = $conn->prepare("UPDATE products SET p_quantity=p_quantity-:p_quantity WHERE id=:id");
                $stmt->execute(['p_quantity'=>$p_quantity, 'id'=>$id]);

        try{
            $stmt = $conn->prepare("SELECT * FROM cart LEFT JOIN products ON products.id=cart.product_id WHERE user_id=:user_id");
            $stmt->execute(['user_id'=>$user['id']]);

            foreach($stmt as $row){
                $stmt = $conn->prepare("INSERT INTO details (sales_id, product_id, quantity) VALUES (:sales_id, :product_id, :quantity)");
                $stmt->execute(['sales_id'=>$salesid, 'product_id'=>$row['product_id'], 'quantity'=>$row['quantity']]);

            }

            $stmt = $conn->prepare("DELETE FROM cart WHERE user_id=:user_id");
            $stmt->execute(['user_id'=>$user['id']]);

            $_SESSION['success'] = 'Transaction successful. Thank you.';

        }
        catch(PDOException $e){
            $_SESSION['error'] = $e->getMessage();
        }

    }
    catch(PDOException $e){
        $_SESSION['error'] = $e->getMessage();
    }

    $pdo->close();
}

header('location: profile.php');

?>


问:
Input length must be multiple of 16 when decrypting with padded cipher (PBEWITHHMACSHA512ANDAES_256)
I am trying to write and encrypt/decrypt program that. I am able to encrypt the String just fine, but while decrypting, I am getting the above error.

My code currently looks like this:

```<code>import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class Trial {

    static String key = "USSWIF3925NJ50R";
    static String userName = "sam1234t";

    public static void main(String[] arg) throws IllegalBlockSizeException, BadPaddingException {

        Trial trial = new Trial();

        Cipher cipher = trial.initialiseCipher("encrypt");

        // Finally generate the transient key in bytes.
        byte[] transientKey = cipher.doFinal(userName.getBytes(StandardCharsets.UTF_8));

        String encryptedPassword = Base64.getEncoder().encodeToString(transientKey);

        System.out.println("Encrypted Key: " + encryptedPassword);

        cipher = trial.initialiseCipher("decrypt");

        // Finally decrypt the transient key in bytes.
        byte[] temp = cipher.doFinal(encryptedPassword.getBytes(StandardCharsets.UTF_8));
        String decryptedKey = new String(Base64.getDecoder().decode(temp));

        System.out.println("Decrypted Key: " + decryptedKey);
    }

    private Cipher initialiseCipher(String mode) {

        Cipher cipher = null;

        try {

            Security.setProperty("crypto.policy", "unlimited");

            SecureRandom secureRandom = new SecureRandom();
            byte[] salt = new byte[256];
            byte[] ivBytes = new byte[16];

            secureRandom.nextBytes(salt);
            secureRandom.nextBytes(ivBytes);

            // Generate the Key Specs.
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
            PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 65536, ivParameterSpec);
            PBEKeySpec pbeKeySpec = new PBEKeySpec((key + userName).toCharArray());

            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWITHHMACSHA512ANDAES_256");
            SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);

            cipher = Cipher.getInstance("PBEWITHHMACSHA512ANDAES_256");

            if (mode.equals("encrypt")) {
                cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec);
            } else if (mode.equals("decrypt")) {
                cipher.init(Cipher.DECRYPT_MODE, secretKey, pbeParameterSpec);
            }

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();

        } catch (InvalidKeySpecException e) {

            e.printStackTrace();

        } catch (NoSuchPaddingException e) {

            e.printStackTrace();

        } catch (InvalidKeyException e) {

            e.printStackTrace();

        } catch (InvalidAlgorithmParameterException e) {

            e.printStackTrace();
        }

        return cipher;
    }
}
</code>```

When I run the piece of code I get the output:

```<code>Encrypted Key: 9DfMJ/yuEFobrdGVsVkhpQ==
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
    at com.sun.crypto.provider.CipherCore.prepareInputBuffer(CipherCore.java:1005)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:848)
    at com.sun.crypto.provider.PBES2Core.engineDoFinal(PBES2Core.java:323)
    at javax.crypto.Cipher.doFinal(Cipher.java:2164)
    at com.att.logicalprovisioning.simulators.Trial.main(Trial.java:43)
</code>```

All the solutions I Googled for use the Cipher algorithm as AES. So I am not sure it replicates like for like, I have tried a few of them, without any luck.

Any help would be helpful. Thanks.

Body:
I am trying to write and encrypt/decrypt program that. I am able to encrypt the String just fine, but while decrypting, I am getting the above error.

My code currently looks like this:

import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class Trial {

    static String key = "USSWIF3925NJ50R";
    static String userName = "sam1234t";

    public static void main(String[] arg) throws IllegalBlockSizeException, BadPaddingException {

        Trial trial = new Trial();

        Cipher cipher = trial.initialiseCipher("encrypt");

        // Finally generate the transient key in bytes.
        byte[] transientKey = cipher.doFinal(userName.getBytes(StandardCharsets.UTF_8));

        String encryptedPassword = Base64.getEncoder().encodeToString(transientKey);

        System.out.println("Encrypted Key: " + encryptedPassword);

        cipher = trial.initialiseCipher("decrypt");

        // Finally decrypt the transient key in bytes.
        byte[] temp = cipher.doFinal(encryptedPassword.getBytes(StandardCharsets.UTF_8));
        String decryptedKey = new String(Base64.getDecoder().decode(temp));

        System.out.println("Decrypted Key: " + decryptedKey);
    }

    private Cipher initialiseCipher(String mode) {

        Cipher cipher = null;

        try {

            Security.setProperty("crypto.policy", "unlimited");

            SecureRandom secureRandom = new SecureRandom();
            byte[] salt = new byte[256];
            byte[] ivBytes = new byte[16];

            secureRandom.nextBytes(salt);
            secureRandom.nextBytes(ivBytes);

            // Generate the Key Specs.
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
            PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 65536, ivParameterSpec);
            PBEKeySpec pbeKeySpec = new PBEKeySpec((key + userName).toCharArray());

            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWITHHMACSHA512ANDAES_256");
            SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);

            cipher = Cipher.getInstance("PBEWITHHMACSHA512ANDAES_256");

            if (mode.equals("encrypt")) {
                cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec);
            } else if (mode.equals("decrypt")) {
                cipher.init(Cipher.DECRYPT_MODE, secretKey, pbeParameterSpec);
            }

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();

        } catch (InvalidKeySpecException e) {

            e.printStackTrace();

        } catch (NoSuchPaddingException e) {

            e.printStackTrace();

        } catch (InvalidKeyException e) {

            e.printStackTrace();

        } catch (InvalidAlgorithmParameterException e) {

            e.printStackTrace();
        }

        return cipher;
    }
}

When I run the piece of code I get the output:

Encrypted Key: 9DfMJ/yuEFobrdGVsVkhpQ==
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
    at com.sun.crypto.provider.CipherCore.prepareInputBuffer(CipherCore.java:1005)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:848)
    at com.sun.crypto.provider.PBES2Core.engineDoFinal(PBES2Core.java:323)
    at javax.crypto.Cipher.doFinal(Cipher.java:2164)
    at com.att.logicalprovisioning.simulators.Trial.main(Trial.java:43)

All the solutions I Googled for use the Cipher algorithm as AES. So I am not sure it replicates like for like, I have tried a few of them, without any luck.

Any help would be helpful. Thanks.


问:
Insert into multiple tables with the Last Insert ID in PHP
I'm trying to insert into 2 tables using the Last Insert ID in PHP. I can't seem to figure things out and I'm stuck here.

This is the Database class

```<code>class Database
{

    private $host = 'localhost';
    private $user = 'root';
    private $password = '';
    private $db_name = 'myusers';

    private function connect()
    {
        $string = "mysql:host=$this->host;dbname=$this->db_name";

        try {
            $con = new PDO($string, $this->user, $this->password);
        } catch (PDOException $e) {
            die($e->getMessage());
        }

        return $con;
    }

    public function write($query, $data = array())
    {
        $con = $this->connect();

        $stmt = $con->prepare($query);
        $result = $stmt->execute($data);

        $insert_id = $stmt->insert_id;

        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    public function read($query, $data = array())
    {
        $con = $this->connect();

        $stmt = $con->prepare($query);
        $result = $stmt->execute($data);

        if ($result) {
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if (is_array($data) && count($data) > 0) {
                return $data;
            }
        }

        return false;
    }
}

</code>```

...ans the User class is where I add the user into the database. The commented code is what I've tried:

```<code>$db = new Database();

        // check if email provided already exists
        $data = array();
        $data['email'] = $POST['email'];

        $query = "SELECT * FROM users WHERE email = :email LIMIT 1";
        $result = $db->read($query, $data);

        if ($result) {
            $this->errors['email'] = "Email provided is already in use";
        }

        // save to the database
        if (count($this->errors) == 0) {

            $query = "INSERT INTO users (username, email, password, date) VALUES (:username, :email, :password, :date)";

            $data = array();
            $data['username'] = $POST['username'];
            $data['email'] = $POST['email'];
            $data['password'] = $POST['password'];
            $data['date'] = date("Y-m-d H:i:s");

            $result = $db->write($query, $data);

            // grab the last insert ID
            // $last_insert_id = $this->db->insert_id();

            // // insert into the job table
            // $sql = "INSERT INTO job (user_id, title, manager, salary) VALUES (:user_id, :title, :manager, :salary)";

            // $data = array();
            // $data['user_id'] = $last_insert_id;
            // $data['title'] = $_POST['title'];
            // $data['manager'] = $_POST['manager'];
            // $data['salary'] = $_POST['salary'];

            // $result = $db->write($sql, $data);

            if (!$result) {
                $this->errors['database'] = "Registration unssuccessful, please try again";
            }
        }
</code>```

I can succesffuly add to the first table but can't figure out how to add into the second one

Body:
I'm trying to insert into 2 tables using the Last Insert ID in PHP. I can't seem to figure things out and I'm stuck here.

This is the Database class

class Database
{

    private $host = 'localhost';
    private $user = 'root';
    private $password = '';
    private $db_name = 'myusers';

    private function connect()
    {
        $string = "mysql:host=$this->host;dbname=$this->db_name";

        try {
            $con = new PDO($string, $this->user, $this->password);
        } catch (PDOException $e) {
            die($e->getMessage());
        }

        return $con;
    }

    public function write($query, $data = array())
    {
        $con = $this->connect();

        $stmt = $con->prepare($query);
        $result = $stmt->execute($data);

        $insert_id = $stmt->insert_id;

        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    public function read($query, $data = array())
    {
        $con = $this->connect();

        $stmt = $con->prepare($query);
        $result = $stmt->execute($data);

        if ($result) {
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if (is_array($data) && count($data) > 0) {
                return $data;
            }
        }

        return false;
    }
}

...ans the User class is where I add the user into the database. The commented code is what I've tried:

$db = new Database();

        // check if email provided already exists
        $data = array();
        $data['email'] = $POST['email'];

        $query = "SELECT * FROM users WHERE email = :email LIMIT 1";
        $result = $db->read($query, $data);

        if ($result) {
            $this->errors['email'] = "Email provided is already in use";
        }

        // save to the database
        if (count($this->errors) == 0) {

            $query = "INSERT INTO users (username, email, password, date) VALUES (:username, :email, :password, :date)";

            $data = array();
            $data['username'] = $POST['username'];
            $data['email'] = $POST['email'];
            $data['password'] = $POST['password'];
            $data['date'] = date("Y-m-d H:i:s");

            $result = $db->write($query, $data);

            // grab the last insert ID
            // $last_insert_id = $this->db->insert_id();

            // // insert into the job table
            // $sql = "INSERT INTO job (user_id, title, manager, salary) VALUES (:user_id, :title, :manager, :salary)";

            // $data = array();
            // $data['user_id'] = $last_insert_id;
            // $data['title'] = $_POST['title'];
            // $data['manager'] = $_POST['manager'];
            // $data['salary'] = $_POST['salary'];

            // $result = $db->write($sql, $data);

            if (!$result) {
                $this->errors['database'] = "Registration unssuccessful, please try again";
            }
        }

I can succesffuly add to the first table but can't figure out how to add into the second one


问:
How can I discretize a continuous time-series dataset to build predictive and regression models?
I have a dataset with 3 columns, Index(date_time), Label, Value. Label can be one of 6 different sensors in a pharmaceutical reaction vessel. When I chart the data using plotly I get a continuous series over time with sections that look like this. Plotly chart of my data
T0 denotes the beginning of a chemical reaction. As I have multiple occurrences of this chemical reaction I want to create discrete "batches" from T0 to T0 + 4 hours. This will then be used to analyze the variance in all of the batches. Sometimes teh chemical reaction does not complete after several hours, s my task is to figure out why.

I also have an external dataset that has labels "good" or "bad" so I was also hoping to change the data format to wide and have target column for each batch.

This is all my code until now, using peakutils to try estimate the peaks for T0

```<code>import glob
import pandas as pd
import peakutils
import matplotlib.pyplot as plt
import peakutils
from peakutils.plot import plot as pplot
from matplotlib import pyplot
%matplotlib inline
# Get CSV files list from a folder
path = [path]
csv_files = glob.glob(path + "/*.csv")

# Read each CSV file into DataFrame
# This creates a list of dataframes
df_list = (pd.read_csv(file) for file in csv_files)

# Concatenate all DataFrames
big_df   = pd.concat(df_list, ignore_index=True)
data = big_df

data[' Date'] = pd.to_datetime(data[' Date'], dayfirst='True')

data = data.sort_values(by = ' Date')

import plotly.express as px
import plotly.io as pio
pio.renderers.default='browser'

fig = px.line(data, x = ' Date', y = ' Value', color = ' Pen Name')
fig.show()

x = wt_df[' Date']
y = wt_df[' Value']
indexes = peakutils.indexes(y, thres=0.5, min_dist=300)
print(indexes)
print(x[indexes], y[indexes])
pyplot.figure(figsize=(10,6))
pplot(x, y, indexes)
pyplot.title('First estimate')

T
</code>```

his is the peak utils output
enter image description here

Body:
I have a dataset with 3 columns, Index(date_time), Label, Value. Label can be one of 6 different sensors in a pharmaceutical reaction vessel. When I chart the data using plotly I get a continuous series over time with sections that look like this. Plotly chart of my data
T0 denotes the beginning of a chemical reaction. As I have multiple occurrences of this chemical reaction I want to create discrete "batches" from T0 to T0 + 4 hours. This will then be used to analyze the variance in all of the batches. Sometimes teh chemical reaction does not complete after several hours, s my task is to figure out why.

I also have an external dataset that has labels "good" or "bad" so I was also hoping to change the data format to wide and have target column for each batch.

This is all my code until now, using peakutils to try estimate the peaks for T0

import glob
import pandas as pd
import peakutils
import matplotlib.pyplot as plt
import peakutils
from peakutils.plot import plot as pplot
from matplotlib import pyplot
%matplotlib inline
# Get CSV files list from a folder
path = [path]
csv_files = glob.glob(path + "/*.csv")

# Read each CSV file into DataFrame
# This creates a list of dataframes
df_list = (pd.read_csv(file) for file in csv_files)

# Concatenate all DataFrames
big_df   = pd.concat(df_list, ignore_index=True)
data = big_df

data[' Date'] = pd.to_datetime(data[' Date'], dayfirst='True')

data = data.sort_values(by = ' Date')

import plotly.express as px
import plotly.io as pio
pio.renderers.default='browser'

fig = px.line(data, x = ' Date', y = ' Value', color = ' Pen Name')
fig.show()

x = wt_df[' Date']
y = wt_df[' Value']
indexes = peakutils.indexes(y, thres=0.5, min_dist=300)
print(indexes)
print(x[indexes], y[indexes])
pyplot.figure(figsize=(10,6))
pplot(x, y, indexes)
pyplot.title('First estimate')

T

his is the peak utils output
enter image description here


问:
Can I carry out a similar function to vlookup on a HTML table?
I'm trying to web scrape UFC fighters stats based on user input. I'm using beautiful soup and pandas. The idea is that the user input is matched to a fighters first and last name then returns their stats. Ideally I'd like to add the option of specifying which particular stat is required in a separate input. I've been able to pull the html table headers successfully but I don't know how to assign values to them which will correspond to the matching fighter name and print the associated value. In my code currently I'm splitting the fighter name input into first and last name, but I don't know how to then match them to the table data or how to return corresponding data. The data being returned currently is just the first line of results (fighter 'Tom Aaron') but no lookups or matching is being carried out. Are nested dictionaries the way to go? Any advice is greatly appreciated, this is my first python project so code is probably all over the place.

("Which fight do you want information on?"
input - Forrest Griffin
"What information do you want?:
input - Wins
"Forrest Griffin has won 8 times"

```<code>from bs4 import BeautifulSoup
import requests
import pandas as pd

website = "http://ufcstats.com/statistics/fighters?char=a&page=all"

response = requests.get(website)

response

soup = BeautifulSoup(response.content, 'html.parser')

results = soup.find('table', {'class' : 'b-statistics__table'}).find('tbody').find_all('tr')
len(results)
#print(results)

row = soup.find('tr')
print(row.get_text())

###attempting to split the table headers an assign
table = soup.find('table', {'class' : 'b-statistics__table'}).find('thead').find_all('tr')

#df=pd.read_html(str(table))[0]
#print(df.set_index(0).to_dict('dict'))

#firstname

first_name = str(results[0].find_all('td')[0].get_text())
print(first_name)

def first_names():
    for names in first_name:
        print(names)
    return

#first_names()

last_name = results[1].find_all('td')[1].get_text()
print(last_name)

alias = results[1].find_all('td')[2].get_text()
if len(alias) == 0:
    print("n/a")
else:
    print(alias)

height = results[1].find_all('td')[3].get_text()
print(height)

weight = results[1].find_all('td')[4].get_text()
#print(weight)

wins = results[1].find_all('td')[7].get_text()
losses = results[1].find_all('td')[8].get_text()
draws = results[1].find_all('td')[9].get_text()

###split user input into list of first + second name

x = input("Which fighter do you want to know about?")

####print(str(first_name) + " " + str(last_name) + " has " + str(wins) + " wins, " + str(losses) + " losses and " + str(draws) + ".")

y = input("What do you want to know about?")

###if user input first name is in results row 1(Tom Aarons row) - still need to search through all result names
if x.split()[0] in str(results[1].find_all('td')[0].get_text()) and x.split()[1] in str(results[1].find_all('td')[1].get_text()) and y == "wins":
    print(first_name+ " "+last_name+" has won " + wins + " times.")

if x.split()[1] in str(results[1].find_all('td')[1].get_text()):
    print("ok")

else:
    print('fail')
###Tom Test
print(x.split()[0])

###if input[1] = first_name and input2[2] == second_name:

if x.split()[1] == first_name:
    print(x.split()[1])

if x.split()[0] in results[1] and x.split()[1] in results[1]:
    print('wins')
else:
    print("Who")

print(str(results[1].find_all('td')[0].get_text()))
</code>```

Body:
I'm trying to web scrape UFC fighters stats based on user input. I'm using beautiful soup and pandas. The idea is that the user input is matched to a fighters first and last name then returns their stats. Ideally I'd like to add the option of specifying which particular stat is required in a separate input. I've been able to pull the html table headers successfully but I don't know how to assign values to them which will correspond to the matching fighter name and print the associated value. In my code currently I'm splitting the fighter name input into first and last name, but I don't know how to then match them to the table data or how to return corresponding data. The data being returned currently is just the first line of results (fighter 'Tom Aaron') but no lookups or matching is being carried out. Are nested dictionaries the way to go? Any advice is greatly appreciated, this is my first python project so code is probably all over the place.

("Which fight do you want information on?"
input - Forrest Griffin
"What information do you want?:
input - Wins
"Forrest Griffin has won 8 times"

from bs4 import BeautifulSoup
import requests
import pandas as pd

website = "http://ufcstats.com/statistics/fighters?char=a&page=all"

response = requests.get(website)

response

soup = BeautifulSoup(response.content, 'html.parser')

results = soup.find('table', {'class' : 'b-statistics__table'}).find('tbody').find_all('tr')
len(results)
#print(results)

row = soup.find('tr')
print(row.get_text())

###attempting to split the table headers an assign
table = soup.find('table', {'class' : 'b-statistics__table'}).find('thead').find_all('tr')

#df=pd.read_html(str(table))[0]
#print(df.set_index(0).to_dict('dict'))

#firstname

first_name = str(results[0].find_all('td')[0].get_text())
print(first_name)

def first_names():
    for names in first_name:
        print(names)
    return

#first_names()

last_name = results[1].find_all('td')[1].get_text()
print(last_name)

alias = results[1].find_all('td')[2].get_text()
if len(alias) == 0:
    print("n/a")
else:
    print(alias)

height = results[1].find_all('td')[3].get_text()
print(height)

weight = results[1].find_all('td')[4].get_text()
#print(weight)

wins = results[1].find_all('td')[7].get_text()
losses = results[1].find_all('td')[8].get_text()
draws = results[1].find_all('td')[9].get_text()

###split user input into list of first + second name

x = input("Which fighter do you want to know about?")

####print(str(first_name) + " " + str(last_name) + " has " + str(wins) + " wins, " + str(losses) + " losses and " + str(draws) + ".")

y = input("What do you want to know about?")

###if user input first name is in results row 1(Tom Aarons row) - still need to search through all result names
if x.split()[0] in str(results[1].find_all('td')[0].get_text()) and x.split()[1] in str(results[1].find_all('td')[1].get_text()) and y == "wins":
    print(first_name+ " "+last_name+" has won " + wins + " times.")

if x.split()[1] in str(results[1].find_all('td')[1].get_text()):
    print("ok")

else:
    print('fail')
###Tom Test
print(x.split()[0])

###if input[1] = first_name and input2[2] == second_name:

if x.split()[1] == first_name:
    print(x.split()[1])

if x.split()[0] in results[1] and x.split()[1] in results[1]:
    print('wins')
else:
    print("Who")

print(str(results[1].find_all('td')[0].get_text()))


问:
How to use a local Swift Package which provides two libraries?
I have a local swift package Foo which provides two different libraries Foo and FooB. Now I would like to use them in another local package Bar. I am only able to get the whole package by path declaration. Is there a way to name/specify which library should be used? I want to use FooB in my Bar Package.

```<code>let package = Package(
    name: "Foo",
    products: [
        .library(name: "Foo", targets: ["Foo"]),
        .library(name: "FooB", targets: ["FooB"])
    ]

...)
</code>```
```<code>let package = Package(
    name: "Bar",
   dependencies: [
        .package(path: "Foo"),
        .package(path: "FooB") // this one does not work
    ],

...)
</code>```
```<code>// inside package Bar

import Foo
import FooB // this is throwing "no such module 'FooB'"
</code>```

Body:
I have a local swift package Foo which provides two different libraries Foo and FooB. Now I would like to use them in another local package Bar. I am only able to get the whole package by path declaration. Is there a way to name/specify which library should be used? I want to use FooB in my Bar Package.

let package = Package(
    name: "Foo",
    products: [
        .library(name: "Foo", targets: ["Foo"]),
        .library(name: "FooB", targets: ["FooB"])
    ]

...)

let package = Package(
    name: "Bar",
   dependencies: [
        .package(path: "Foo"),
        .package(path: "FooB") // this one does not work
    ],

...)

// inside package Bar

import Foo
import FooB // this is throwing "no such module 'FooB'"


问:
How to put a TextField within a TextEditor for a placeholder (swiftUI)?
I'm not sure if it's possible but I want to put a textfield within a TextEditor to section it off. Just like how TextFields have placeholders, I want my TextEditor to have placeholders to guide users where to put what type of information. Like a "Name" placeholder for a user to input  name or a "Procedure" placeholder for a user to input their Procedure steps. I'd like to have multiple placeholders within the text editor.

Directly adding a TextField into the TextEditor doesn't work. Does anyone know any ways to accomplish placeholders in a TextEditor?


问:
Can I send state value with EmailJS?
I am trying to create a simple e-shop shopping cart in React (without payment for now) and I would like the order to be sent to me by email using EmailJS. The content of the order is saved in state cartItems but I don't know how to pass it to display in the email. As far as I understand, EmailJS is intended for passing data that is filled in the form but perhaps there is another way?

This is my component EmailOrderForm

```<code>import React, { useRef } from 'react';
> import emailjs from '@emailjs/browser';
> import { useCart } from '../../cart-context';
>
> const EmailOrderForm = () => {
> const { cartItems } = useCart();
>
> const form = useRef();
>
> const sendEmail = (e) => {
> e.preventDefault();
>
> emailjs
>       .sendForm(
>         'service_xxxxx',
>         'template_xxxxx',
> form.current,
>         'XXxxXXxxXXxxXXxx',
>       )
>       .then(
>         (result) => {
> console.log('SUCCESS!');
>         },
>         (error) => {
> console.log('FAILED!');
>         },
>       );
> console.log(cartItems);
>   };
>
> return (
>     <form ref={form} onSubmit={sendEmail}>
>       <label>Name</label>
>       <input type="text" name="user_name" />
>       <label>Email</label>
>       <input type="email" name="user_email" />
>       <label>Note</label>
>       <textarea name="message" />
>       <ul name="order">
>         {cartItems.map((item) => (
>           <li className="cart-item" key={item.index}>
>             <div
> className="cart-item-image"
> style={{
> backgroundImage: `url(${item.image})`,
> width: '100px',
> height: '100px',
> backgroundSize: 'cover',
> backgroundPosition: 'center',
>               }}
> alt={item.name}
>             ></div>
>             <span className="cart-item-name">{item.name}</span>
>             <span className="cart-item-price">{item.price} Kč</span>
>           </li>
>         ))}
>       </ul>
>       <button className="cart-order" type="submit">
> Order
>       </button>
>     </form>
>   );
> };
>
> export default EmailOrderForm;
</code>```

Title: Can I send state value with EmailJS?

Body:
I am trying to create a simple e-shop shopping cart in React (without payment for now) and I would like the order to be sent to me by email using EmailJS. The content of the order is saved in state cartItems but I don't know how to pass it to display in the email. As far as I understand, EmailJS is intended for passing data that is filled in the form but perhaps there is another way?

This is my component EmailOrderForm

import React, { useRef } from 'react';
> import emailjs from '@emailjs/browser';
> import { useCart } from '../../cart-context';
>
> const EmailOrderForm = () => {
> const { cartItems } = useCart();
>
> const form = useRef();
>
> const sendEmail = (e) => {
> e.preventDefault();
>
> emailjs
>       .sendForm(
>         'service_xxxxx',
>         'template_xxxxx',
> form.current,
>         'XXxxXXxxXXxxXXxx',
>       )
>       .then(
>         (result) => {
> console.log('SUCCESS!');
>         },
>         (error) => {
> console.log('FAILED!');
>         },
>       );
> console.log(cartItems);
>   };
>
> return (
>     <form ref={form} onSubmit={sendEmail}>
>       Name
>       <input type="text" name="user_name" />
>       Email
>       <input type="email" name="user_email" />
>       Note
>       <textarea name="message" />
>

>         {cartItems.map((item) => (
>

>
 className="cart-item-image"
> style={{
> backgroundImage: `url(${item.image})`,
> width: '100px',
> height: '100px',
> backgroundSize: 'cover',
> backgroundPosition: 'center',
>               }}
> alt={item.name}
>             >

>             {item.name}
>             {item.price} Kč
>

>         ))}
>

>       <button className="cart-order" type="submit">
> Order
>       </button>
>     </form>
>   );
> };
>
> export default EmailOrderForm;


问:
How can I import imported data from a .json file in a service and then pass that data dynamically into an angular material table?
How can I import imported data from a .json file in a service and then pass that data dynamically into an angular material table?

I tried replacing ELEMENT_DATA with my property but it doesn't work


问:
Encountering "RuntimeError: Legacy model format is not supported on mobile." in Pytorch despite running on desktop
I'm attempting to load in serialised PyTorch models in the format sad_player2_model.pth in PyTorch where torch==1.13.0. However, I keep running into this error:

```<code>RuntimeError: Legacy model format is not supported on mobile.
python: /usr/include/boost/fiber/condition_variable.hpp:56: boost::fibers::condition_variable_any::~condition_variable_any(): Assertion `wait_queue_.empty()' failed.
Aborted (core dumped)
</code>```

As far as I'm aware the models weren't trained on the mobile version of PyTorch and renaming the files to .pt didn't work either. Extracting the archive shows that the model contains the following:

Body:
I'm attempting to load in serialised PyTorch models in the format sad_player2_model.pth in PyTorch where torch==1.13.0. However, I keep running into this error:

RuntimeError: Legacy model format is not supported on mobile.
python: /usr/include/boost/fiber/condition_variable.hpp:56: boost::fibers::condition_variable_any::~condition_variable_any(): Assertion `wait_queue_.empty()' failed.
Aborted (core dumped)

As far as I'm aware the models weren't trained on the mobile version of PyTorch and renaming the files to .pt didn't work either. Extracting the archive shows that the model contains the following:


问:
update grid by async function - react
I have this function - to manage grid and to create it:

```<code>export default function CustomizableComponents({ direction }) {
  const [rows, setRows] = useState(ComponentDidMount);
  const [sortColumns, setSortColumns] = useState([]);
  const [selectedRows, setSelectedRows] = useState(() => new Set());

  const sortedRows = useMemo(() => {
    if (sortColumns.length === 0) return rows;

    return [...rows].sort((a, b) => {
      for (const sort of sortColumns) {
        const comparator = getComparator(sort.columnKey);
        const compResult = comparator(a, b);
        if (compResult !== 0) {
          return sort.direction === 'ASC' ? compResult : -compResult;
        }
      }
      return 0;
    });
  }, [rows, sortColumns]);

  return (
    <DataGrid
      className="fill-grid"
      columns={columns}
      rows={sortedRows}
      sortColumns={sortColumns}
      onSortColumnsChange={setSortColumns}
      selectedRows={selectedRows}
      onSelectedRowsChange={setSelectedRows}
      renderers={{ sortStatus, checkboxFormatter }}
      direction={direction}
    />
  );
}
</code>```

And, I have this function (to get the data from server):

```<code>async function ComponentDidMount() {
  // GET request using fetch with async/await
  const response = await fetch('https://localhost:7198/api/FilesDetails/GetListDetails');
  const data = await response.json();
  for (let i = 1; i < 10; i++) {
    rows.push({
      id: data[i].name,
      name:  data[i].name,
      startTime: data[i].name,
      endTime:  data[i].name
    });
  }

  return rows;
}
</code>```

It reaches the function, and fills the rows,
But the datagrid remains empty and does not fill.

Where am I wrong?

Thanks

Title: update grid by async function - react

Body:
I have this function - to manage grid and to create it:

export default function CustomizableComponents({ direction }) {
  const [rows, setRows] = useState(ComponentDidMount);
  const [sortColumns, setSortColumns] = useState([]);
  const [selectedRows, setSelectedRows] = useState(() => new Set());

  const sortedRows = useMemo(() => {
    if (sortColumns.length === 0) return rows;

    return [...rows].sort((a, b) => {
      for (const sort of sortColumns) {
        const comparator = getComparator(sort.columnKey);
        const compResult = comparator(a, b);
        if (compResult !== 0) {
          return sort.direction === 'ASC' ? compResult : -compResult;
        }
      }
      return 0;
    });
  }, [rows, sortColumns]);

  return (
    <DataGrid
      className="fill-grid"
      columns={columns}
      rows={sortedRows}
      sortColumns={sortColumns}
      onSortColumnsChange={setSortColumns}
      selectedRows={selectedRows}
      onSelectedRowsChange={setSelectedRows}
      renderers={{ sortStatus, checkboxFormatter }}
      direction={direction}
    />
  );
}

And, I have this function (to get the data from server):

async function ComponentDidMount() {
  // GET request using fetch with async/await
  const response = await fetch('https://localhost:7198/api/FilesDetails/GetListDetails');
  const data = await response.json();
  for (let i = 1; i < 10; i++) {
    rows.push({
      id: data[i].name,
      name:  data[i].name,
      startTime: data[i].name,
      endTime:  data[i].name
    });
  }

  return rows;
}

It reaches the function, and fills the rows,
But the datagrid remains empty and does not fill.

Where am I wrong?

Thanks


问:
Extend Grafana table using JSON API request
I was wondering if my scenario is possible with the Grafana extension JSON API.
I am displaying in my Grafana dashboard the result from my Application Insights kusto query. The table in my dashboard currently has two columns with timestamp and a serial number.

I would like to add a third column to my table e.g. name. I.e. I have to request an external API, use per row the serial number displayed there and wait for the result of the API request. In the return value of my API is my needed value for column 3.

Anyone here have experience with extending Grafana with JSON API to request values dynamically?


问:
Is there a function for reading in json files as dicts where you only need to provide a filepath as input?
I'm sick of doing

with open('my.json','r') as inf:
    my_dict = json.load(inf)
```

each time I want to get the contents of a json file as a dict in python. It seems so trivial to simply add a function that just accepts 'my.json' as a path and then implicitly opens the file and then loads the json file with whatever additional keywords you want. I found the pandas.read_json() class, but if I tried that it gave me the same error that I get if I try to call json.load() on a filepath. Is it difficult to add my custon reading function to the json package? How do I add a function to a package that is easily callable from any script with an import statement, so I don't have to write the same function over and over again? Is there a particular reason why this isn't an available function? Am I just lazy?

I know what the code for my solution is, I just don't know where to add it so it's easily importable and whether or not this is a very bad idea to begin with, since it would require a modification of a builtin python package.

Body:
I'm sick of doing

with open('my.json','r') as inf:
    my_dict = json.load(inf)

each time I want to get the contents of a json file as a dict in python. It seems so trivial to simply add a function that just accepts 'my.json' as a path and then implicitly opens the file and then loads the json file with whatever additional keywords you want. I found the pandas.read_json() class, but if I tried that it gave me the same error that I get if I try to call json.load() on a filepath. Is it difficult to add my custon reading function to the json package? How do I add a function to a package that is easily callable from any script with an import statement, so I don't have to write the same function over and over again? Is there a particular reason why this isn't an available function? Am I just lazy?

I know what the code for my solution is, I just don't know where to add it so it's easily importable and whether or not this is a very bad idea to begin with, since it would require a modification of a builtin python package.


问:
How to append more data in a column without overriding
Hi I want to add some data in a column such that I have a List I want to pick the data from it some time the List size is more and some time it less than M(where M is number of rows). if it is more than M it should iterate and append the data and separate the data with comma[,] but does not override it if less it should skip the rest of the data or add empty data. also I'm creating column run time

```<code>def read_tor_cell(self):
    queue = ['a','b','c','a','b','c']
        complete_path = self.Task2 + filename
        print(complete_path)
        for i in queue():
            df_round_robin = self.path_to_csv.head(M)
            df_round_robin["new_column"] = i
            df_round_robin.to_csv('test.csv')
            print(df_round_robin)
</code>```

above script override the previous data.
I Want output like this so that the data does not override

```<code>expected output::

Assume m=2
for row 1:: inside new_column a,c,b
for row 2:: inside new_column b,a,c

m=3
for row 1:: inside new_column a,a
for row 2:: inside new_column b,b
for row 3:: inside new_column c,c
</code>```

Body:
Hi I want to add some data in a column such that I have a List I want to pick the data from it some time the List size is more and some time it less than M(where M is number of rows). if it is more than M it should iterate and append the data and separate the data with comma[,] but does not override it if less it should skip the rest of the data or add empty data. also I'm creating column run time

def read_tor_cell(self):
    queue = ['a','b','c','a','b','c']
        complete_path = self.Task2 + filename
        print(complete_path)
        for i in queue():
            df_round_robin = self.path_to_csv.head(M)
            df_round_robin["new_column"] = i
            df_round_robin.to_csv('test.csv')
            print(df_round_robin)

above script override the previous data.
I Want output like this so that the data does not override

expected output::

Assume m=2
for row 1:: inside new_column a,c,b
for row 2:: inside new_column b,a,c

m=3
for row 1:: inside new_column a,a
for row 2:: inside new_column b,b
for row 3:: inside new_column c,c


问:
Docker can't run php-fpm using VirtioFS on Apple M1 Pro chip
I'm trying to run php-fpm using docker on my MacBook Pro with M1 Pro chip. But it works VERY slow on default gRPC FUSE, so i changed my Choose file sharing implementation for your containers setting to VirtioFS because it should work faster.

When i try to run container, i get this message in logs:

```<code>ERROR: unable to bind listening socket for address '/sock/docker.sock': Operation not supported (95)
</code>```

Here is my docker-compose.yml:

```<code>version: "3"

services:

    test-php-fpm:
        container_name: test-php-fpm
        image: php:7.4-fpm
        environment:
            PHP_IDE_CONFIG: "serverName=docker"
        env_file: .env.local
        working_dir: /app
        volumes:
            - ./:/app
            - ./sock:/sock
            - ./php-fpm/xdebug.ini:/usr/local/etc/php/conf.d/xdebug.ini
            - ./php-fpm/zz-docker.conf:/usr/local/etc/php-fpm.d/zz-docker.conf
            - ./data/upload:/${UPLOAD_STORAGE_PATH}
        networks:
            - test

</code>```

If i delete docker.sock and restart the container, it will not regenerate it, and i will get this message:

```<code>ERROR: [pool www] failed to chown() the socket '/sock/docker.sock': Invalid argument (22)
</code>```

Body:
I'm trying to run php-fpm using docker on my MacBook Pro with M1 Pro chip. But it works VERY slow on default gRPC FUSE, so i changed my Choose file sharing implementation for your containers setting to VirtioFS because it should work faster.

When i try to run container, i get this message in logs:

ERROR: unable to bind listening socket for address '/sock/docker.sock': Operation not supported (95)

Here is my docker-compose.yml:

version: "3"

services:

    test-php-fpm:
        container_name: test-php-fpm
        image: php:7.4-fpm
        environment:
            PHP_IDE_CONFIG: "serverName=docker"
        env_file: .env.local
        working_dir: /app
        volumes:
            - ./:/app
            - ./sock:/sock
            - ./php-fpm/xdebug.ini:/usr/local/etc/php/conf.d/xdebug.ini
            - ./php-fpm/zz-docker.conf:/usr/local/etc/php-fpm.d/zz-docker.conf
            - ./data/upload:/${UPLOAD_STORAGE_PATH}
        networks:
            - test

If i delete docker.sock and restart the container, it will not regenerate it, and i will get this message:

ERROR: [pool www] failed to chown() the socket '/sock/docker.sock': Invalid argument (22)


问:
pyplot & timedelta64: OverflowError: int too big to convert
I try to display a matplotlib.patches.Rectangle over a pyplot. My X-axis is of format datetime64. It spans over ~10hours and I'd like my Rectangle to have a width of 10 minutes. It shall be centered on event Date_hour value.

```<code>In [1]: print(events['Date_hour'].values[1])
Out [1]: ['2022-05-12T16:32:58.000000000']
</code>```
```<code>from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Rectangle width
width = np.timedelta64(10, 'm')

# Create rectangle
events_patches = [Rectangle(xy=[event['Date_hour'].values[1]-width/2, 0], width=width, height=10]
pc = PatchCollection(events_patches)
ax.add_collection(pc)

ax.plot(data['Date_hour'].values[:,0], data['var1'].values[:,0])

fig.savefig('./test.png')
</code>```

It throws the following error:

```<code>Traceback (most recent call last):
........
........
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/axis.py", line 1190, in _update_ticks
    major_locs = self.get_majorticklocs()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/axis.py", line 1416, in get_majorticklocs
    return self.major.locator()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 1366, in __call__
    dmin, dmax = self.viewlim_to_dt()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 1151, in viewlim_to_dt
    return num2date(vmin, self.tz), num2date(vmax, self.tz)
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 533, in num2date
    return _from_ordinalf_np_vectorized(x, tz).tolist()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/numpy/lib/function_base.py", line 2328, in __call__
    return self._vectorize_call(func=func, args=vargs)
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/numpy/lib/function_base.py", line 2411, in _vectorize_call
    outputs = ufunc(*inputs)
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 354, in _from_ordinalf
    np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us'))
OverflowError: int too big to convert
</code>```

Body:
I try to display a matplotlib.patches.Rectangle over a pyplot. My X-axis is of format datetime64. It spans over ~10hours and I'd like my Rectangle to have a width of 10 minutes. It shall be centered on event Date_hour value.

In [1]: print(events['Date_hour'].values[1])
Out [1]: ['2022-05-12T16:32:58.000000000']

from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Rectangle width
width = np.timedelta64(10, 'm')

# Create rectangle
events_patches = [Rectangle(xy=[event['Date_hour'].values[1]-width/2, 0], width=width, height=10]
pc = PatchCollection(events_patches)
ax.add_collection(pc)

ax.plot(data['Date_hour'].values[:,0], data['var1'].values[:,0])

fig.savefig('./test.png')

It throws the following error:

Traceback (most recent call last):
........
........
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/axis.py", line 1190, in _update_ticks
    major_locs = self.get_majorticklocs()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/axis.py", line 1416, in get_majorticklocs
    return self.major.locator()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 1366, in __call__
    dmin, dmax = self.viewlim_to_dt()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 1151, in viewlim_to_dt
    return num2date(vmin, self.tz), num2date(vmax, self.tz)
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 533, in num2date
    return _from_ordinalf_np_vectorized(x, tz).tolist()
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/numpy/lib/function_base.py", line 2328, in __call__
    return self._vectorize_call(func=func, args=vargs)
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/numpy/lib/function_base.py", line 2411, in _vectorize_call
    outputs = ufunc(*inputs)
  File "/Users/user1/myproject/venv/lib/python3.10/site-packages/matplotlib/dates.py", line 354, in _from_ordinalf
    np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us'))
OverflowError: int too big to convert


问:
puppeteer page.click() doesn't work in headless mode for  html element with attached onclick function
When i try to click on  html element with attached onclick function (some jquery call) in headless mode it doesn't work (in headful mode it works). This is example of html element

```<code><a href="#" onclick="some_jquery_call">Click</a>
</code>```

Is it possible puppeteer doesn't see jquery function in headless mode?
Also my current puppeteer version is 11.0.0 , but i tried also with newer versions
]

I tried with classic puppeteer function page.click(), also with page.$eval('selector',(e)=>e.click()) etc.

Title: puppeteer page.click() doesn't work in headless mode for <a> html element with attached onclick function

Body:
When i try to click on  html element with attached onclick function (some jquery call) in headless mode it doesn't work (in headful mode it works). This is example of html element

Click

Is it possible puppeteer doesn't see jquery function in headless mode?
Also my current puppeteer version is 11.0.0 , but i tried also with newer versions
]

I tried with classic puppeteer function page.click(), also with page.$eval('selector',(e)=>e.click()) etc.


问:
Why does my conditional formatting not working?
The conditional formatting is

and the worksheet looks like this

Formula for the AL / MC:

```<code>=IF(ISBLANK(F7),F8,IF(AND(NOT(ISBLANK(F8)),EXACT(F7,F8)),F7,CONCATENATE(F7,CHAR(10),F8)))
</code>```

For the above image, I have done the conditional formatting on the worksheet so that different category is highlighted but for the one with AL/MC together is not following the conditional formatting, any idea why is it so?

I tried to redo the conditional formatting and search for solutions online but just cannot get the AL/MC to change accordingly.

Body:
The conditional formatting is

and the worksheet looks like this

Formula for the AL / MC:

=IF(ISBLANK(F7),F8,IF(AND(NOT(ISBLANK(F8)),EXACT(F7,F8)),F7,CONCATENATE(F7,CHAR(10),F8)))

For the above image, I have done the conditional formatting on the worksheet so that different category is highlighted but for the one with AL/MC together is not following the conditional formatting, any idea why is it so?

I tried to redo the conditional formatting and search for solutions online but just cannot get the AL/MC to change accordingly.


问:
im displaying individual product details by making an api call, all the product data is rendering correctly, except a sub array of imgs while mapping
```<code>const proId = useParams();
    const ProductId = proId.id;
    const [proData, setProData] = useState({})
    useEffect(() => {
        axios.get(`https://dummyjson.com/products/${ProductId}`)
            .then(res => setProData(res.data))
            .catch(err => console.log(err))
    }, [ProductId]);

    const { thumbnail, brand, description, images, price, rating, title } = proData;

    return (
        <div className='w-full p-4'>
            <div className="">
                <div className="md:flex justify-center items-center">
                    <img className='' src={thumbnail} alt="" />
                </div>
                <div className="pt-12 md:p-4 rounded-lg ">
                    <h1 className='text-4xl py-2'>{title}</h1>
                    <h3 className='text-xl font-semibold py-3'> <span className='text-blue-700'>Brand : </span> <span className='opacity-80'>{brand}</span></h3>
                    <p className=''>Description : </p>
                    <p className=''>{description}</p>
                    <h2 className=''>Price : <span className=''>{price} $</span></h2>
                    <p className="">Rating : <span className='opacity-80'>{rating}</span> ⭐</p>
                </div>
                <div className="grid grid-cols-5 gap-8 p-4">
                    {
                            images.map((item, i) => (
                                <div key={`smi${i}`} className=""><img className='max-h-[200px]' src={item} alt={``} /></div>
                            ))
                        }
                </div>
            </div>
        </div>
</code>```

when im trying to map the images[which is an array of imgs in the api response] using .map(), its throwing errors, saying cannot read properties of undefined, every other data renders perfectly but except this image array.can some one explain how can i render the images?

Body:
const proId = useParams();
    const ProductId = proId.id;
    const [proData, setProData] = useState({})
    useEffect(() => {
        axios.get(`https://dummyjson.com/products/${ProductId}`)
            .then(res => setProData(res.data))
            .catch(err => console.log(err))
    }, [ProductId]);

    const { thumbnail, brand, description, images, price, rating, title } = proData;

    return (

{title}

 Brand :  {brand}

Description :

{description}

Price : {price} $

Rating : {rating} ⭐

                    {
                            images.map((item, i) => (
                                <div key={`smi${i}`} className="">

                            ))
                        }

when im trying to map the images[which is an array of imgs in the api response] using .map(), its throwing errors, saying cannot read properties of undefined, every other data renders perfectly but except this image array.can some one explain how can i render the images?


问:
Chrome Extension API: Programmatically resize a user's panel frame without resizing window
I'm writing a Chrome extension that needs to resize a user's page content to a specific size/aspect ratio. Identical functionality can be found in the device toolbar in Chrome inspect: choose a device, resize the content frame to test responsive designs.

I'd like to do this with the Chrome extension API (without requiring the user to open up dev tools).

Similar extensions

"Window-Resizer" will resize the full window (my extensions needs to resize the inner content to accommodate full screens).

"Narrower" adds inner padding to the html (this breaks media queries for different sites, so I can't use that technique either).

chrome.windows.update will work with resizing the full window, but I'd like to resize the web content within an existing window. Is anyone aware of a way to replicate the functionality in chrome's device toolbar for a chrome extension?


问:
Next.js trying to push input value into json, but it doesn't work
Right there I'm trying to get value from inout, and after that change it in json.

Json file is correct, and value from it is also correct, so when I'm trying to output PcosData....Title - everything is okay

the serverside has also no problems, as in terminal i get (get & POST), and data which is in POST is also returning, that means - a) server gets input value b) backend is correct

so the problem. is in frontend, I think I'm doing something wrongg when I'm trying to push data in HandleSubmit or smth like that

```<code>import PcosData from "/data/pcos.json";
import {useEffect} from "react";
import { useState } from "react";
import bodyParser from "body-parser";
import util from "util";

const getBody = util.promisify(bodyParser.urlencoded());

export async function getServerSideProps({req, res}) {
    await getBody(req, res);
    console.log(req.method, req.body);
    return {
        props: {
            // status
        }
    }
}

export default function adminPcos() {

        const [title, setTitle] = useState(PcosData["pcos-first"].title);

        const handleSubmit = (e) => {
            // e.preventDefault();
            PcosData["pcos-first"].title = title;
            console.log(handleSubmit)

        }

    return (
        <div>
            <h1>hello world</h1>

            {PcosData["pcos-first"].map((pcosdata) => (
                <form onSubmit={handleSubmit} key={ pcosdata.id } method="post">

                    <input type="text" className="name" name="title" defaultValue={pcosdata.title} onChange={(e) => setTitle({text: e.target.value})}/>

                    <button type="submit">Submit</button>
                </form>
            ))}

        </div>
    )
}
</code>```

Body:
Right there I'm trying to get value from inout, and after that change it in json.

Json file is correct, and value from it is also correct, so when I'm trying to output PcosData....Title - everything is okay

the serverside has also no problems, as in terminal i get (get & POST), and data which is in POST is also returning, that means - a) server gets input value b) backend is correct

so the problem. is in frontend, I think I'm doing something wrongg when I'm trying to push data in HandleSubmit or smth like that

import PcosData from "/data/pcos.json";
import {useEffect} from "react";
import { useState } from "react";
import bodyParser from "body-parser";
import util from "util";

const getBody = util.promisify(bodyParser.urlencoded());

export async function getServerSideProps({req, res}) {
    await getBody(req, res);
    console.log(req.method, req.body);
    return {
        props: {
            // status
        }
    }
}

export default function adminPcos() {

        const [title, setTitle] = useState(PcosData["pcos-first"].title);

        const handleSubmit = (e) => {
            // e.preventDefault();
            PcosData["pcos-first"].title = title;
            console.log(handleSubmit)

        }

    return (

hello world

            {PcosData["pcos-first"].map((pcosdata) => (
                <form onSubmit={handleSubmit} key={ pcosdata.id } method="post">

                    <input type="text" className="name" name="title" defaultValue={pcosdata.title} onChange={(e) => setTitle({text: e.target.value})}/>

                    <button type="submit">Submit</button>
                </form>
            ))}

    )
}