问:
Unity PHP to SSMS
I have two tables: one for user credentials and another for inputting remarks.

Table 1 (User credentials):

id
name

1007
max

1008
james

Table 2 (Input remarks to the user ID):

id
remarks

1007
user input 1

1007
user input 2

1008
user input 1

Currently, this is my code

```<code>$stmt = sqlsrv_prepare($conn, "INSERT INTO remarks (id) SELECT id FROM testing WHERE id = ?", array($loginID));

if (sqlsrv_execute($stmt)) {
    echo "Record inserted successfully.";
} else {
    echo "Error inserting record: " . sqlsrv_errors();
}

$stmt1 = sqlsrv_prepare($conn, "INSERT INTO remarks (remarks) VALUES (?)", array($remarks1));
if (sqlsrv_execute($stmt1)) {
    echo "Record inserted successfully.";
} else {
    echo "Error inserting record: " . sqlsrv_errors();
}
</code>```

What should I change my php code to?

Title: Unity PHP to SSMS

Body:
I have two tables: one for user credentials and another for inputting remarks.

Table 1 (User credentials):

id
name

1007
max

1008
james

Table 2 (Input remarks to the user ID):

id
remarks

1007
user input 1

1007
user input 2

1008
user input 1

Currently, this is my code

$stmt = sqlsrv_prepare($conn, "INSERT INTO remarks (id) SELECT id FROM testing WHERE id = ?", array($loginID));

if (sqlsrv_execute($stmt)) {
    echo "Record inserted successfully.";
} else {
    echo "Error inserting record: " . sqlsrv_errors();
}

$stmt1 = sqlsrv_prepare($conn, "INSERT INTO remarks (remarks) VALUES (?)", array($remarks1));
if (sqlsrv_execute($stmt1)) {
    echo "Record inserted successfully.";
} else {
    echo "Error inserting record: " . sqlsrv_errors();
}

What should I change my php code to?


来源: stackexchange

问:
Getting crash when calling CallWindowProc()
In order to do some hooks on windows messages, I added a dll to the exe file.

```<code>result = isUnicodeWindow ? ::CallWindowProcW(wndProc, hWnd, message, wParam, lParam) : ::CallWindowProcA(wndProc, hWnd, message, wParam, lParam);
    return result;
</code>```

But when CallWindowProcW is called in dll, it will cause crash, where the parameter is EVENT_OBJECT_HELPCHANGE.

I know my question is too general, but I really don't have any more information. Can anyone give me some advice, thank you very much.

My dll did not process EVENT_OBJECT_HELPCHANGE, but just called CallWindowProcW directly. But it caused a crash.

enter image description here

ContentLicense: CC BY-SA 4.0

Body:
In order to do some hooks on windows messages, I added a dll to the exe file.

result = isUnicodeWindow ? ::CallWindowProcW(wndProc, hWnd, message, wParam, lParam) : ::CallWindowProcA(wndProc, hWnd, message, wParam, lParam);
    return result;

But when CallWindowProcW is called in dll, it will cause crash, where the parameter is EVENT_OBJECT_HELPCHANGE.

I know my question is too general, but I really don't have any more information. Can anyone give me some advice, thank you very much.

My dll did not process EVENT_OBJECT_HELPCHANGE, but just called CallWindowProcW directly. But it caused a crash.

enter image description here


问:
What is the specific meaning of the GPU_NUM_COMPUTE_RINGS environment variable?
What is the specific meaning of the GPU_NUM_COMPUTE_RINGS environment variable? And Where can I find anything about the restrictions on setting this environment variable?

Picture about the original description

The figure is from the AMD Opencl-programming-guide.  https://rocmdocs.amd.com/en/latest/Programming_Guides/Opencl-programming-guide.html#a-note-on-hardware-queues

And What is the relationship between compute queue and hardware queue?


问:
How do I convert wstring to unsigned long long?
I want to convert a wstring to unsigned long long.

I am trying it like this:

```<code>ret.push_back(_wtol(s1));
</code>```

The compiler throws this error:

```<code>No conversion available for "std::wstring" to const "wchar_t *"
</code>```

This is the entire code:

```<code>vector<unsigned long long> splitW2(const wstring& uMain, const wstring& uSplitBy)
{
    vector<unsigned long long>ret;

    int iStart = 0;

    for (;;)
    {
        int iPos = uMain.find(uSplitBy, iStart);
        if (iPos == -1)
        {
            wstring s1;
            s1 = uMain.substr(iStart, uMain.size() - iStart);
            if (s1.size() > 0)
            {
                ret.push_back(_wtol(s1));//the error here is: There is conversion available for "std::wstring" to const "wchar_t *"
            }
            break;
        }
        else
        {
            wstring s2;
            s2 = uMain.substr(iStart, iPos - iStart);
            ret.push_back(s2);//this of course is also not possible.
            iStart = iPos + 1;
        }
    }
    return ret;
}
</code>```

Body:
I want to convert a wstring to unsigned long long.

I am trying it like this:

ret.push_back(_wtol(s1));

The compiler throws this error:

No conversion available for "std::wstring" to const "wchar_t *"

This is the entire code:

vector<unsigned long long> splitW2(const wstring& uMain, const wstring& uSplitBy)
{
    vector<unsigned long long>ret;

    int iStart = 0;

    for (;;)
    {
        int iPos = uMain.find(uSplitBy, iStart);
        if (iPos == -1)
        {
            wstring s1;
            s1 = uMain.substr(iStart, uMain.size() - iStart);
            if (s1.size() > 0)
            {
                ret.push_back(_wtol(s1));//the error here is: There is conversion available for "std::wstring" to const "wchar_t *"
            }
            break;
        }
        else
        {
            wstring s2;
            s2 = uMain.substr(iStart, iPos - iStart);
            ret.push_back(s2);//this of course is also not possible.
            iStart = iPos + 1;
        }
    }
    return ret;
}


问:
I want to do div doesn't work unless I press it
I want to do div doesn't work unless I press it, I call users using for loob.
I useing "onclick" but it work when page load

HTML code
`

```<code> <main>
         <div class="conterner">

            <div class="users " >
               <div style="margin: 0 a;" id="parUser">
                  <div class="user" id="user" >
                     <h3 id="name"> Ahmed </h3>
                     <h3 id="email"> Ahmed.ali@gmail.com</h3>
                  </div>
               </div>

            </div>
            <div class="infos">
               <div class="info">
                  <h5 class="postHead" > post post postpost</h5>
                  <div class="line"></div>
                  <p class="postP"> post post postpost</p>

               </div>
            </div>
         </div>

      </main>
</code>```

`

JS code
`

```<code> function getUsers(){

       fetch('https://jsonplaceholder.typicode.com/users')
         .then((response) =>{
            if (response.ok) {
               return response.json()
            }

         })
         .then((users) => {
            for(user of users){
               console.log(user)
               let orginalDiv = document.querySelector("#user");
               orginalDiv.style.display ='none';
               let newDiv = document.createElement('div')
               newDiv.innerHTML= orginalDiv.innerHTML;
               newDiv.className="user";
               let nameH = document.querySelector('#name')
               nameH.innerHTML = user.name;
               let emailH = document.querySelector('#email')
               emailH.innerHTML = user.email;
               const parentDiv = document.getElementById("parUser")
               parentDiv.appendChild(newDiv);
             **  user.onclick =userEvent();** I wnat when user click hear take to userEvent()

            }

                     return
         });

      }
</code>```

`

**  user.onclick =userEvent();** I wnat when user click hear take to userEvent()

Body:
I want to do div doesn't work unless I press it, I call users using for loob.
I useing "onclick" but it work when page load

HTML code
`

 Ahmed

 Ahmed.ali@gmail.com

 post post postpost

 post post postpost

`

JS code
`

 function getUsers(){

       fetch('https://jsonplaceholder.typicode.com/users')
         .then((response) =>{
            if (response.ok) {
               return response.json()
            }

         })
         .then((users) => {
            for(user of users){
               console.log(user)
               let orginalDiv = document.querySelector("#user");
               orginalDiv.style.display ='none';
               let newDiv = document.createElement('div')
               newDiv.innerHTML= orginalDiv.innerHTML;
               newDiv.className="user";
               let nameH = document.querySelector('#name')
               nameH.innerHTML = user.name;
               let emailH = document.querySelector('#email')
               emailH.innerHTML = user.email;
               const parentDiv = document.getElementById("parUser")
               parentDiv.appendChild(newDiv);
             **  user.onclick =userEvent();** I wnat when user click hear take to userEvent()

            }

                     return
         });

      }

`

**  user.onclick =userEvent();** I wnat when user click hear take to userEvent()


问:
AutoMapper: ResolveUsing deprecated, replace with MapFrom
In my solution in .NET Framework 4.8.1, I'm upgrading AutoMapper from 7.0.1 to 10.1.1.
This result in +800 errors because I'm using ResolveUsing and that method was deprecated.
Could I just find and replace all occurrences of ResolveUsing to MapFrom and call it a day?

Old Code Sample1:

```<code>.ForMember(rh => rh.Document, option => option.ResolveUsing<RHFileClass>())
</code>```

New Code Sample1:

```<code>.ForMember(rh => rh.Document, option => option.MapFrom<RHFileClass>())
</code>```

Old Code Sample2:

```<code>.ForMember(buzz => buzz.Id, option => option.ResolveUsing<AgendaPK>(data => AgendaPK.NewOrNull(data.number)));
</code>```

New Code Sample2:

```<code>.ForMember(buzz => buzz.Id, option => option.MapFrom<AgendaPK>(data => AgendaPK.NewOrNull(data.number)));
</code>```

I would say that 65% of my cases are like Sample1.

Does someone already faced a similar issue?

I tried to find and replace all the occurrences of ResolveUsing to MapFrom. No more inline error but my question is: Is it really gonna work?

Body:
In my solution in .NET Framework 4.8.1, I'm upgrading AutoMapper from 7.0.1 to 10.1.1.
This result in +800 errors because I'm using ResolveUsing and that method was deprecated.
Could I just find and replace all occurrences of ResolveUsing to MapFrom and call it a day?

Old Code Sample1:

.ForMember(rh => rh.Document, option => option.ResolveUsing<RHFileClass>())

New Code Sample1:

.ForMember(rh => rh.Document, option => option.MapFrom<RHFileClass>())

Old Code Sample2:

.ForMember(buzz => buzz.Id, option => option.ResolveUsing<AgendaPK>(data => AgendaPK.NewOrNull(data.number)));

New Code Sample2:

.ForMember(buzz => buzz.Id, option => option.MapFrom<AgendaPK>(data => AgendaPK.NewOrNull(data.number)));

I would say that 65% of my cases are like Sample1.

Does someone already faced a similar issue?

I tried to find and replace all the occurrences of ResolveUsing to MapFrom. No more inline error but my question is: Is it really gonna work?


问:
vscode shows postgresql query execution error but not the detail
I'm using vscode 1.74.2 with SQLTools extension v0.26.0 with postgresql 15.

when I run a query that results in an error in psql it returns error output in several namespaces, for example in my case when i run a function that i created the returns wrong result type, it's divided to 3 sections:

```<code>ERROR:  structure of query does not match function result type
DETAIL:  Returned type numeric does not match expected type integer in column 11.
CONTEXT: SQL statement "..."
</code>```

when I run that query in vscode, it only shows the ERROR:

when when I look at the SQL Console messages it shows only the error:

I want to also see the Detail of the error, how can i do that ?

Body:
I'm using vscode 1.74.2 with SQLTools extension v0.26.0 with postgresql 15.

when I run a query that results in an error in psql it returns error output in several namespaces, for example in my case when i run a function that i created the returns wrong result type, it's divided to 3 sections:

ERROR:  structure of query does not match function result type
DETAIL:  Returned type numeric does not match expected type integer in column 11.
CONTEXT: SQL statement "..."

when I run that query in vscode, it only shows the ERROR:

when when I look at the SQL Console messages it shows only the error:

I want to also see the Detail of the error, how can i do that ?


问:
Module parse failed: Unexpected token (108:62)
./src/Chat.js 108:62
Module parse failed: Unexpected token (108:62)
You may need an appropriate loader to handle this file type.
|       columnNumber: 11
|     }

}, "last seen", " ", new Date(messages[messages.length - 1]?.timestamp?.toDate()).toUTCString())), /#PURE/React.createElement("div", {
|     className: "chat__headerRight",
|     __self: this,

```<code>

I tried, but nothing happened.
</code>```

Body:
./src/Chat.js 108:62
Module parse failed: Unexpected token (108:62)
You may need an appropriate loader to handle this file type.
|       columnNumber: 11
|     }

}, "last seen", " ", new Date(messages[messages.length - 1]?.timestamp?.toDate()).toUTCString())), /#PURE/React.createElement("div", {
|     className: "chat__headerRight",
|     __self: this,

I tried, but nothing happened.


问:
How to rename column names using a pattern of names in r
I have a dataframe with 7000+ columns and I want to assign names to them in a pattern such as G1, G2, G3....
It is not possible by simply using colnames or rename functions.
How can I do it?</p>


问:
How to add value on sankey links with plotly on python
I have a sankey plot using plotly but I do not managed to display values on links (only on the hover toolbox). In In R, how to display value on the links/paths of Sankey Graph? they add custom code to do so in R but I was not able to reproduce it in python. Any help welcomed :)

Lets say I have this code:

```<code>import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = ["A1", "A2", "B1", "B2", "C1", "C2"],
      color = "blue"
    ),
    link = dict(
      source = [0, 1, 0, 2, 3, 3], # indices correspond to labels, eg A1, A2, A1, B1, ...
      target = [2, 3, 3, 4, 4, 5],
      value = [8, 4, 2, 8, 4, 2]
  ))])

fig.update_layout(title_text="Basic Sankey Diagram", font_size=10)
fig.show()
</code>```

I expected to be able to do this like for sunburst:

```<code>fig.update_traces(textinfo="label+value", selector=dict(type='sunburst'))
</code>```

Body:
I have a sankey plot using plotly but I do not managed to display values on links (only on the hover toolbox). In In R, how to display value on the links/paths of Sankey Graph? they add custom code to do so in R but I was not able to reproduce it in python. Any help welcomed :)

Lets say I have this code:

import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = ["A1", "A2", "B1", "B2", "C1", "C2"],
      color = "blue"
    ),
    link = dict(
      source = [0, 1, 0, 2, 3, 3], # indices correspond to labels, eg A1, A2, A1, B1, ...
      target = [2, 3, 3, 4, 4, 5],
      value = [8, 4, 2, 8, 4, 2]
  ))])

fig.update_layout(title_text="Basic Sankey Diagram", font_size=10)
fig.show()

I expected to be able to do this like for sunburst:

fig.update_traces(textinfo="label+value", selector=dict(type='sunburst'))


问:
How the get the status of the Form upload process
I have an simple HTML form that takes files as a input and user name. It sends and data to action attribute and redirect successfully to action's attribute after clicking on the submit button by user.
It is good for small images but user don't knows that how long he should wait for submission.

The problem is if user submits the large image then it takes some more time to process and redirect it.

I need the same default functionality but it will be good If i can read form progress that how much percent it has uploaded.

Note - I don't want to submit form via. ajax method, I need default submission functionality with file upload progess.

Currently I applied the following javascript code to listen formupload progess, But It was not printing to console.

I will be thankful to know the solution. Thank you for help.

```<code><form enctype="multipart/form-data" action="/success/" id="form_by_user" method="POST">

<input type="file" name="image_field" multiple  id="image_field"" accept="image/*" required>

<input type="text" name="user_name" id="user_name" required>

<input type="submit" name="submit" value="submit">

</form>
</code>```

--javascript part

```<code><script>

$('form#form_by_user').submit(function() {

   console.log("Listening form progress");

    var xhr = new window.XMLHttpRequest();

    xhr.open();

    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = (evt.loaded / evt.total)*100;
        console.log(percentComplete);

      }
}, false );

 });

</script>
</code>```

Body:
I have an simple HTML form that takes files as a input and user name. It sends and data to action attribute and redirect successfully to action's attribute after clicking on the submit button by user.
It is good for small images but user don't knows that how long he should wait for submission.

The problem is if user submits the large image then it takes some more time to process and redirect it.

I need the same default functionality but it will be good If i can read form progress that how much percent it has uploaded.

Note - I don't want to submit form via. ajax method, I need default submission functionality with file upload progess.

Currently I applied the following javascript code to listen formupload progess, But It was not printing to console.

I will be thankful to know the solution. Thank you for help.

<form enctype="multipart/form-data" action="/success/" id="form_by_user" method="POST">

<input type="file" name="image_field" multiple  id="image_field"" accept="image/*" required>

<input type="text" name="user_name" id="user_name" required>

<input type="submit" name="submit" value="submit">

</form>

--javascript part


问:
The process cannot access the file because it is being used by another process Exception
I have receved that exception

java.nio.file.FileSystemException:
C:\Users\Sajith\AppData\Local\Temp\billing6178517837067812146.tmp: The
process cannot access the file because it is being used by another
process.

How to fix it?

Below has a code,

```<code>try (final TempFile tempFile = new TempFile()) {
      tempFile.setExposedFileName(title);
      tempFile.setContentType(XLSX_CONTENT_TYPE);
      generator.writeTo(tempFile);
      final AssetContent assetContent =
        AssetContentUtils.createAssetContent(new FileInputStream(tempFile.getFile()));
      assetContent.setContentType(XLSX_CONTENT_TYPE);
      assetContent.setFileName(tempFile.getExposedFileName());
      assetContent.setContentLength(tempFile.getFile().length());
      return assetContent;
   }
</code>```

Body:
I have receved that exception

java.nio.file.FileSystemException:
C:\Users\Sajith\AppData\Local\Temp\billing6178517837067812146.tmp: The
process cannot access the file because it is being used by another
process.

How to fix it?

Below has a code,

try (final TempFile tempFile = new TempFile()) {
      tempFile.setExposedFileName(title);
      tempFile.setContentType(XLSX_CONTENT_TYPE);
      generator.writeTo(tempFile);
      final AssetContent assetContent =
        AssetContentUtils.createAssetContent(new FileInputStream(tempFile.getFile()));
      assetContent.setContentType(XLSX_CONTENT_TYPE);
      assetContent.setFileName(tempFile.getExposedFileName());
      assetContent.setContentLength(tempFile.getFile().length());
      return assetContent;
   }


问:
Need help in setting up dev environment & running unit tests for rethinkdb server
I am new to rethinkdb and want to setup development environment (particularly rethindb server) on my Ubuntu-20 box.

I was able to build the source, thanks to very concise README!

I want to run unit tests & I am struggling there.

Appreciate any help!
Thanks

I could not find the instructions, hence I peeped into Github Actions file (btw I am not very familiar to Github actions) & ran the following  command:

```<code>test/run --verbose --jobs "${MAX_JOBS}" -H unit
</code>```

I get an error:

```<code>ile "test/run", line 33, in load_tests
    execfile(full_path, {"__builtins__": __builtins__, "generate_test": generate_test(tree)})
NameError: name 'execfile' is not defined
</code>```

BTW: I am using python-3

Body:
I am new to rethinkdb and want to setup development environment (particularly rethindb server) on my Ubuntu-20 box.

I was able to build the source, thanks to very concise README!

I want to run unit tests & I am struggling there.

Appreciate any help!
Thanks

I could not find the instructions, hence I peeped into Github Actions file (btw I am not very familiar to Github actions) & ran the following  command:

test/run --verbose --jobs "${MAX_JOBS}" -H unit

I get an error:

ile "test/run", line 33, in load_tests
    execfile(full_path, {"__builtins__": __builtins__, "generate_test": generate_test(tree)})
NameError: name 'execfile' is not defined

BTW: I am using python-3


问:
How to check which argument is running in a thread
I have a list of threads each of which takes a function run([sql_query_1, sql_query_2...]). The argument to the function is a list of SQL queries. Some of these queries are invalid and raise an exception in the run() function.

Is there a way to check inside the thread, which query is running in the run() function so I can suppress that exception? (I cannot modify run())

```<code>threads = []
for _ in range(x):
    t = Thread(target = run(), args=[list_of_queries])
    threads.append(t)

for t in threads:
    if # check if invalid query is running in t.start(), then suppress
       # the error that run() will raise for that query
    else: # continue running normally
</code>```

Body:
I have a list of threads each of which takes a function run([sql_query_1, sql_query_2...]). The argument to the function is a list of SQL queries. Some of these queries are invalid and raise an exception in the run() function.

Is there a way to check inside the thread, which query is running in the run() function so I can suppress that exception? (I cannot modify run())

threads = []
for _ in range(x):
    t = Thread(target = run(), args=[list_of_queries])
    threads.append(t)

for t in threads:
    if # check if invalid query is running in t.start(), then suppress
       # the error that run() will raise for that query
    else: # continue running normally


问:
In Android 12+ Splash Screen API, how to provide a banner as icon in the centre?
I need splash screen with banner in middle that occupies full screen width like this

I am able to get like this in Android versions below 12, but 12 and above, I get an crushed icon that only the middle part of the banner is visible.(Also have elevation around the circle)

I also tried android:windowSplashScreenBrandingImage but I works only from 31+ and when using it both icon and banner showing !!!

Is it possible to implement a full width banner Splash in Android 12+ like in the image ?


问:
how to get only left table from join sequelize
I try to implement this query

SELECT [pelanggan].[id],
       [pelanggan].[nama_pelanggan],
       [pelanggan].[hp],
       Format(ABS(SUM([hutangs].[nominal])), N'c', N'id-ID') AS [total],
       [hutangs].[id_pelanggan] AS [hutangs.id_pelanggan]
FROM [pelanggan] AS [pelanggan]
LEFT OUTER JOIN [hutang] AS [hutangs] ON [pelanggan].[id] = [hutangs].[id_pelanggan]
WHERE [pelanggan].[kode_reseller] = N'MP0000001'
GROUP BY [pelanggan].[id],
         [pelanggan].[nama_pelanggan],
         [pelanggan].[hp],
         [hutangs].[id_pelanggan]
ORDER BY [pelanggan].[id]
OFFSET 0 ROWS FETCH NEXT 50 ROWS ONLY;
```
<p>to sequelize, i tried this code</p>
<pre class="lang-js prettyprint-override"><code>    Pelanggan.findAndCountAll({
      attributes: [
        'pelanggan.id',
        'nama_pelanggan',
        'hp',
        [db.sequelize.fn('Format', db.sequelize.fn('ABS',db.sequelize.fn('SUM', db.sequelize.col('hutangs.nominal'))) ,'c','id-ID') , 'total'],
      ],
      include: [
        {
          model : db.hutang,
          required: false,
          attributes: [
            'id_pelanggan',
          ],
        }
      ],
      where: {
        kode_reseller: "MP0000001"
      },
      group: ['pelanggan.id','pelanggan.nama_pelanggan','pelanggan.hp','hutangs.id_pelanggan'],
      subQuery : false,
      limit: 5,
      offset: 0,
    })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      console.log(err)
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving tutorials."
      });
    });
</code>```

but I'm getting error, when i console the query from sequelize i got this

SELECT [pelanggan].[id],
       [pelanggan].[nama_pelanggan],
       [pelanggan].[hp],
       Format(ABS(SUM([hutangs].[nominal])), N'c', N'id-ID') AS [total],
       [hutangs].[id] AS [hutangs.id],
       [hutangs].[id_pelanggan] AS [hutangs.id_pelanggan]
FROM [pelanggan] AS [pelanggan]
LEFT OUTER JOIN [hutang] AS [hutangs] ON [pelanggan].[id] = [hutangs].[id_pelanggan]
WHERE [pelanggan].[kode_reseller] = N'MP0000001'
GROUP BY [pelanggan].[id],
         [pelanggan].[nama_pelanggan],
         [pelanggan].[hp],
         [hutangs].[id_pelanggan]
ORDER BY [pelanggan].[id]
OFFSET 0 ROWS FETCH NEXT 50 ROWS ONLY;
```

on the query from sequelize had [hutangs].[id] AS [hutangs.id] but i dont set hutangs.id on attribute sequelize how can I remove that ?

sorry for my bad English

Body:
I try to implement this query

SELECT [pelanggan].[id],
       [pelanggan].[nama_pelanggan],
       [pelanggan].[hp],
       Format(ABS(SUM([hutangs].[nominal])), N'c', N'id-ID') AS [total],
       [hutangs].[id_pelanggan] AS [hutangs.id_pelanggan]
FROM [pelanggan] AS [pelanggan]
LEFT OUTER JOIN [hutang] AS [hutangs] ON [pelanggan].[id] = [hutangs].[id_pelanggan]
WHERE [pelanggan].[kode_reseller] = N'MP0000001'
GROUP BY [pelanggan].[id],
         [pelanggan].[nama_pelanggan],
         [pelanggan].[hp],
         [hutangs].[id_pelanggan]
ORDER BY [pelanggan].[id]
OFFSET 0 ROWS FETCH NEXT 50 ROWS ONLY;

to sequelize, i tried this code

    Pelanggan.findAndCountAll({
      attributes: [
        'pelanggan.id',
        'nama_pelanggan',
        'hp',
        [db.sequelize.fn('Format', db.sequelize.fn('ABS',db.sequelize.fn('SUM', db.sequelize.col('hutangs.nominal'))) ,'c','id-ID') , 'total'],
      ],
      include: [
        {
          model : db.hutang,
          required: false,
          attributes: [
            'id_pelanggan',
          ],
        }
      ],
      where: {
        kode_reseller: "MP0000001"
      },
      group: ['pelanggan.id','pelanggan.nama_pelanggan','pelanggan.hp','hutangs.id_pelanggan'],
      subQuery : false,
      limit: 5,
      offset: 0,
    })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      console.log(err)
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving tutorials."
      });
    });

but I'm getting error, when i console the query from sequelize i got this

SELECT [pelanggan].[id],
       [pelanggan].[nama_pelanggan],
       [pelanggan].[hp],
       Format(ABS(SUM([hutangs].[nominal])), N'c', N'id-ID') AS [total],
       [hutangs].[id] AS [hutangs.id],
       [hutangs].[id_pelanggan] AS [hutangs.id_pelanggan]
FROM [pelanggan] AS [pelanggan]
LEFT OUTER JOIN [hutang] AS [hutangs] ON [pelanggan].[id] = [hutangs].[id_pelanggan]
WHERE [pelanggan].[kode_reseller] = N'MP0000001'
GROUP BY [pelanggan].[id],
         [pelanggan].[nama_pelanggan],
         [pelanggan].[hp],
         [hutangs].[id_pelanggan]
ORDER BY [pelanggan].[id]
OFFSET 0 ROWS FETCH NEXT 50 ROWS ONLY;

on the query from sequelize had [hutangs].[id] AS [hutangs.id] but i dont set hutangs.id on attribute sequelize how can I remove that ?

sorry for my bad English


问:
What is the meaning of Build Failing tag in Npm packages. Is it fine to use the package?
In this tag is given as Build Failing

I need to use this package in my project. So is it fine for use?


问:
Can I modify history stack on Next.js project?
I make 3 Pages.

Click Summit button on Page A, It make condition routing, router.push(PageB) or router.push(PageC).

There is a problem for me.
On PageC, If user click the browser back button, I want to reach PageB user not A.

```<code>// when need to go Page C.
await router.push(`/box/${createdBox._id}`);
router.push(`/box/${createdBox._id}/payment`);
</code>```

I try this little trick on PageA, but display PageB before going PageC.

THank you anyway.

Body:
I make 3 Pages.

Click Summit button on Page A, It make condition routing, router.push(PageB) or router.push(PageC).

There is a problem for me.
On PageC, If user click the browser back button, I want to reach PageB user not A.

// when need to go Page C.
await router.push(`/box/${createdBox._id}`);
router.push(`/box/${createdBox._id}/payment`);

I try this little trick on PageA, but display PageB before going PageC.

THank you anyway.


问:
WebMvcTest not giving any code coverage in IntelliJ
I have integration test class for a controller as below

```<code>@WebMvcTest(DepartmentController.class)
public class DepartmentControllerTest {

    @MockBean
    private DepartmentService departmentService;

    @MockBean
    private RestTemplateBuilder restTemplateBuilder;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    ObjectMapper objectMapper;

    @Test
    void Get_Department_Returns_200_Ok_When_Department_Present() throws Exception {
        Optional<Department> deptOptional = Optional.of(new Department(1, "Tech"));
        when(departmentService.getDepartment(1)).thenReturn(deptOptional);
        assertThat(departmentService.getDepartment(1)).isEqualTo(deptOptional);
        mockMvc.perform(get("/department/{id}", 1)
        .contentType("application/json")
        ).andExpect(status().isOk());
    }

    //other tests
}
</code>```

All the tests pass but it is not including the controller in the coverage results in IntelliJ

Body:
I have integration test class for a controller as below

@WebMvcTest(DepartmentController.class)
public class DepartmentControllerTest {

    @MockBean
    private DepartmentService departmentService;

    @MockBean
    private RestTemplateBuilder restTemplateBuilder;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    ObjectMapper objectMapper;

    @Test
    void Get_Department_Returns_200_Ok_When_Department_Present() throws Exception {
        Optional<Department> deptOptional = Optional.of(new Department(1, "Tech"));
        when(departmentService.getDepartment(1)).thenReturn(deptOptional);
        assertThat(departmentService.getDepartment(1)).isEqualTo(deptOptional);
        mockMvc.perform(get("/department/{id}", 1)
        .contentType("application/json")
        ).andExpect(status().isOk());
    }

    //other tests
}

All the tests pass but it is not including the controller in the coverage results in IntelliJ


问:
How to handle keybinding on button click?
On click of buttons how to access keymap binding in react code mirror . For eg onclick of button comment first line like cntrl + /

A proper solution with codemirror code


问:
How to use Postman Share collection link from via JSON link to via API link?
Earlier I was sharing postman collection link from via JSON link on AzureDevops. But due to version upgrade in postman it is now showing via API link which uses access key.

I tried using older version of postman but it is stuck at fetching link.

How can this issue be resolved?


问:
I can't use Scanner object to input in Java?
I want to create id (int), title (String), category (String) and cost (Float) for a class in Java. I used an Scanner object to read them from keyboard. But I can only read the id, after that the console do not allow me to read the title, it goes to category and then cost. Even if I type a float to cost, it throws an exception. Please help me.

```<code>package ChuoiTrongJava;
import java.util.Scanner;
public class IndexOf {

    public static void main(String[] args) {

        Scanner kb = new Scanner(System.in);
        System.out.print("ID: ");
        int id = kb.nextInt();
        System.out.print("\nTitle: ");
        String title = kb.nextLine();
        System.out.print("\nCategory: ");
        String category = kb.nextLine();
        System.out.print("\nCost: ");
        Float cost = kb.nextFloat();

    }
}
</code>```

Body:
I want to create id (int), title (String), category (String) and cost (Float) for a class in Java. I used an Scanner object to read them from keyboard. But I can only read the id, after that the console do not allow me to read the title, it goes to category and then cost. Even if I type a float to cost, it throws an exception. Please help me.

package ChuoiTrongJava;
import java.util.Scanner;
public class IndexOf {

    public static void main(String[] args) {

        Scanner kb = new Scanner(System.in);
        System.out.print("ID: ");
        int id = kb.nextInt();
        System.out.print("\nTitle: ");
        String title = kb.nextLine();
        System.out.print("\nCategory: ");
        String category = kb.nextLine();
        System.out.print("\nCost: ");
        Float cost = kb.nextFloat();

    }
}


问:
How do I know when an iOS App Open Ad is dismissed in Xamarin/MAUI?
I am using Xamarin.Google.iOS.MobileAds package to show Google App Open Ad in my MAUI app. The code below has error handling code removed for brevity.

this.ad = await AppOpenAd.LoadAsync(
    o.IosUnitId,
    null,
    o.Orientation switch
    {
        AppOpenAdOrientation.Landscape => UIInterfaceOrientation.LandscapeLeft,
        _ => UIInterfaceOrientation.Portrait,
    }
);

var oldHandler = ad.PaidEventHandler;
var openTcs = new TaskCompletionSource();

// The handler below is actually called when the ad show up
ad.PaidEventHandler = v =>
{
    oldHandler?.Invoke(v);
    openTcs.TrySetResult();
};

var root = Platform.GetCurrentUIViewController();
this.ad.PresentFromRootViewController(root);

```
<p>In the Google's doc on Handle presentation callbacks, a <code>GADFullScreenContentDelegate</code> is needed but I have no idea how I can put it in C# and there is no event/delegate corresponding to this <code>self.appOpenAd.fullScreenContentDelegate = self;</code>.</p>
<p>Please advice on the event of ad dismissal. I could do it for Android like this but I can't see the equivalent in Xamarin.iOS:</p>
<pre class="lang-cs prettyprint-override"><code>this.currAd.FullScreenContentCallback = callback;
</code>```

Body:
I am using Xamarin.Google.iOS.MobileAds package to show Google App Open Ad in my MAUI app. The code below has error handling code removed for brevity.

this.ad = await AppOpenAd.LoadAsync(
    o.IosUnitId,
    null,
    o.Orientation switch
    {
        AppOpenAdOrientation.Landscape => UIInterfaceOrientation.LandscapeLeft,
        _ => UIInterfaceOrientation.Portrait,
    }
);

var oldHandler = ad.PaidEventHandler;
var openTcs = new TaskCompletionSource();

// The handler below is actually called when the ad show up
ad.PaidEventHandler = v =>
{
    oldHandler?.Invoke(v);
    openTcs.TrySetResult();
};

var root = Platform.GetCurrentUIViewController();
this.ad.PresentFromRootViewController(root);

In the Google's doc on Handle presentation callbacks, a GADFullScreenContentDelegate is needed but I have no idea how I can put it in C# and there is no event/delegate corresponding to this self.appOpenAd.fullScreenContentDelegate = self;.

Please advice on the event of ad dismissal. I could do it for Android like this but I can't see the equivalent in Xamarin.iOS:

this.currAd.FullScreenContentCallback = callback;


问:
compute hmac from message bytes and key bytes in javascript
I'm trying to reproduce the following code in javascript

```<code>var hashInput = "a::string::to::hash";
        var privateKey = "C0B615950F9D577A4EAF64C9B4F2E50F3DA2C6BB6F790FA346E9732788B29A08AC5444F1B82984DB190A75D3861CC4802D598EBF0025FD1C327928F43EB1C80E";

        byte[] inputBytes = Encoding.UTF8.GetBytes(hashInput);
        byte[] keyBytes = Encoding.UTF8.GetBytes(privateKey);

        HMACSHA256 hmac = new HMACSHA256(keyBytes);
        hmac.Initialize();
        var clientHash = hmac.ComputeHash(inputBytes);
        var base64 = Convert.ToBase64String(clientHash);

</code>```

But i ignore how can i import Enocde and HMACSHA256. I found the code in the following answer:
stackoverflow answer

This is what i've tried so far

```<code>  const HashMAC = (key, message) => {
    let keyBytes = Buffer.from(key, 'base64');
    let messageBytes = Buffer.from(message, 'utf8');
    // i don't know which library should i use, in crypto js thay're talking about
      message and key noy bytes i tried but nothing.
    const base64 = Buffer.from(hmac, 'base64');
    return base64;
  };
</code>```

Body:
I'm trying to reproduce the following code in javascript

var hashInput = "a::string::to::hash";
        var privateKey = "C0B615950F9D577A4EAF64C9B4F2E50F3DA2C6BB6F790FA346E9732788B29A08AC5444F1B82984DB190A75D3861CC4802D598EBF0025FD1C327928F43EB1C80E";

        byte[] inputBytes = Encoding.UTF8.GetBytes(hashInput);
        byte[] keyBytes = Encoding.UTF8.GetBytes(privateKey);

        HMACSHA256 hmac = new HMACSHA256(keyBytes);
        hmac.Initialize();
        var clientHash = hmac.ComputeHash(inputBytes);
        var base64 = Convert.ToBase64String(clientHash);

But i ignore how can i import Enocde and HMACSHA256. I found the code in the following answer:
stackoverflow answer

This is what i've tried so far

  const HashMAC = (key, message) => {
    let keyBytes = Buffer.from(key, 'base64');
    let messageBytes = Buffer.from(message, 'utf8');
    // i don't know which library should i use, in crypto js thay're talking about
      message and key noy bytes i tried but nothing.
    const base64 = Buffer.from(hmac, 'base64');
    return base64;
  };


问:
Unable to connect internet on a docker container running on GKE pod
We have a GKE pod running with Jenkins image having docker installed in it. When I tried to build a image using Dockerfile on this Jenkins GKE pod, It is not working as background containers created while building image from Dockerfile are unable to access internet to fetch data.


问:
Unable to return value inside function in node.js
Unable to return value inside function in node.js . Below is my function which I am calling from another function to get desired value but I am getting undefined.

```<code>const getBBBMeetingInfo = (meetingID) => {

    let bbbHttp = bbb.http;
    let getMeetingInfo = api.monitoring.getMeetingInfo(meetingID);
    let val;
    bbbHttp(getMeetingInfo).then((result) => {
      let newRes = {};
      newRes = result;
      newRes.meetingID = meetingID;
      if(newRes.returncode == 'FAILED'){
        updateNotificationCallStatus(meetingID)
      }
      val = newRes.returncode

    });

    return val
}
</code>```

calling fuction like this

```<code>let bn =  getBBBMeetingInfo(ele.meetingId);
console.log(bn)//undefined
</code>```

I am new to node.js.  Please let me know how I can get it and use it as returned value.

Body:
Unable to return value inside function in node.js . Below is my function which I am calling from another function to get desired value but I am getting undefined.

const getBBBMeetingInfo = (meetingID) => {

    let bbbHttp = bbb.http;
    let getMeetingInfo = api.monitoring.getMeetingInfo(meetingID);
    let val;
    bbbHttp(getMeetingInfo).then((result) => {
      let newRes = {};
      newRes = result;
      newRes.meetingID = meetingID;
      if(newRes.returncode == 'FAILED'){
        updateNotificationCallStatus(meetingID)
      }
      val = newRes.returncode

    });

    return val
}

calling fuction like this

let bn =  getBBBMeetingInfo(ele.meetingId);
console.log(bn)//undefined

I am new to node.js.  Please let me know how I can get it and use it as returned value.


问:
Duplicated and unauthenticated requests from users from a corporation using Zscaler for authentication
We've got a Ruby on Rails application and some of our users connect to our website from a network of a company that uses Zscaler for network security/administration.

When an ajax request is made by one of these users, we see a pattern of requests that does not happen normally:

First, we get an OPTIONS request to which we respond with 200 and some headers:

```<code>headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*'
headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, Origin, Content-Length, Accept, ' + request.headers['Access-Control-Request-Headers'].to_s
headers['Access-Control-Allow-Credentials'] = 'true'
headers['Access-Control-Max-Age'] = '600'
</code>```

Note: This request has an additional parameter that we do not add nor use called _sm_byp (a sample value would be iVVsN0kN0745SVp5)

Right after, we get a GET request that halts and redirects (302) because our server detects it as not signed in. As if the session cookies were not correct, maybe. This request also has the _sm_byp query parameter (same value as the OPTIONS request).

Then, we see a successful GET request. This request does not have the _sm_byp parameter.

By investigating the origin of this parameter, I found out Zscaler might be the cause. Then I found out Zscaler manages these users' company network. Therefore, I am quite sure this is related to how Zscaler manages authentication.

I had a call with the Zscaler user support but they would not help without a user to reproduce the problem. They did explain that use SAML for authentication and sent me this link. The website explains this:

A user opens a browser and tries to reach a website.

The Zscaler service generates a SAML authentication request, which is encoded and embedded into the URL for the IdP.

The service sends a redirect to the user's browser. It includes the encoded SAML authentication request to be submitted to the IdP.

The user's browser submits the authentication request to the IdP.

The IdP (...) generates a SAML response with digitally signed public/private DSA/RSA keys, encodes it and sends it to browser.

The browser forwards the SAML response to the service. The CAS of Zscaler uses the IdP's public key to verify the response.

After the service successfully verifies the response, it logs in the user and redirects the user's browser to the destination URL.

I am thinking the _sm_byp parameter is related to the authentication request mentioned in point #2.
And, could point #3 be the redirect (not signed in) we are getting? It seems normal that the ajax treats it as a failure since it is expecting a json but gets an html response (due to the redirect to the login page).
Is this a normal auth behaviour? How should our RoR server respond to those requests? I could just ignore these ajax "errors" but I feel like we might be treating this the wrong way. I just want to make sure it's not Zscalers fault but ours.

Finally, these users have not made any complaint about this so we figured they are not really seeing any problem. However, although the OPTIONS and the first GET request are just a second apart, the successful GET request arrives about 40 seconds later. Therefore, I suspect they might actually be seing some problem but I am not 100% sure.

Body:
We've got a Ruby on Rails application and some of our users connect to our website from a network of a company that uses Zscaler for network security/administration.

When an ajax request is made by one of these users, we see a pattern of requests that does not happen normally:

First, we get an OPTIONS request to which we respond with 200 and some headers:

headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*'
headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, Origin, Content-Length, Accept, ' + request.headers['Access-Control-Request-Headers'].to_s
headers['Access-Control-Allow-Credentials'] = 'true'
headers['Access-Control-Max-Age'] = '600'

Note: This request has an additional parameter that we do not add nor use called _sm_byp (a sample value would be iVVsN0kN0745SVp5)

Right after, we get a GET request that halts and redirects (302) because our server detects it as not signed in. As if the session cookies were not correct, maybe. This request also has the _sm_byp query parameter (same value as the OPTIONS request).

Then, we see a successful GET request. This request does not have the _sm_byp parameter.

By investigating the origin of this parameter, I found out Zscaler might be the cause. Then I found out Zscaler manages these users' company network. Therefore, I am quite sure this is related to how Zscaler manages authentication.

I had a call with the Zscaler user support but they would not help without a user to reproduce the problem. They did explain that use SAML for authentication and sent me this link. The website explains this:

A user opens a browser and tries to reach a website.

The Zscaler service generates a SAML authentication request, which is encoded and embedded into the URL for the IdP.

The service sends a redirect to the user's browser. It includes the encoded SAML authentication request to be submitted to the IdP.

The user's browser submits the authentication request to the IdP.

The IdP (...) generates a SAML response with digitally signed public/private DSA/RSA keys, encodes it and sends it to browser.

The browser forwards the SAML response to the service. The CAS of Zscaler uses the IdP's public key to verify the response.

After the service successfully verifies the response, it logs in the user and redirects the user's browser to the destination URL.

I am thinking the _sm_byp parameter is related to the authentication request mentioned in point #2.
And, could point #3 be the redirect (not signed in) we are getting? It seems normal that the ajax treats it as a failure since it is expecting a json but gets an html response (due to the redirect to the login page).
Is this a normal auth behaviour? How should our RoR server respond to those requests? I could just ignore these ajax "errors" but I feel like we might be treating this the wrong way. I just want to make sure it's not Zscalers fault but ours.

Finally, these users have not made any complaint about this so we figured they are not really seeing any problem. However, although the OPTIONS and the first GET request are just a second apart, the successful GET request arrives about 40 seconds later. Therefore, I suspect they might actually be seing some problem but I am not 100% sure.


问:
How to hide element on page load?
This question doesn't fix the problem

I'm using this to hide/show a form field if an option in a menu is selected:

```<code>function updateView() {
    $('#id_selection').on('change', function (e) {
        const valueSelected = this.value;
        if (valueSelected === 'Value1') {
            $('#id_field').hide();
        } else {
            $('#id_field').show();
        }
    });
}
</code>```

and it works perfectly fine. Now I need the same changes to occur when the page has loaded, so I tried:

```<code>$('#id_selection').on('change load', function (e) {...}
</code>```

and

```<code>$('#id_selection').on('change DOMContentLoaded', function (e) {...}
</code>```

and

```<code>$('#id_selection').on('change ready', function (e) {...}
</code>```

For each, the field is hidden only if the menu selection is changed but nothing happens on page load.

Based on suggestions in the question mentioned above, I also tried:

```<code>$(document).ready(function () {
    $("#id_field").hide();
});
</code>```

which doesn't make any difference, the field remains visible.

Title: How to hide element on page load?

Body:
This question doesn't fix the problem

I'm using this to hide/show a form field if an option in a menu is selected:

function updateView() {
    $('#id_selection').on('change', function (e) {
        const valueSelected = this.value;
        if (valueSelected === 'Value1') {
            $('#id_field').hide();
        } else {
            $('#id_field').show();
        }
    });
}

and it works perfectly fine. Now I need the same changes to occur when the page has loaded, so I tried:

$('#id_selection').on('change load', function (e) {...}

and

$('#id_selection').on('change DOMContentLoaded', function (e) {...}

and

$('#id_selection').on('change ready', function (e) {...}

For each, the field is hidden only if the menu selection is changed but nothing happens on page load.

Based on suggestions in the question mentioned above, I also tried:

$(document).ready(function () {
    $("#id_field").hide();
});

which doesn't make any difference, the field remains visible.


问:
sending spark dataframe via email without using pandas in pyspark?
I'm trying to send spark dataframe via email.
normally i'm able to send spark dataframe by converting spark dataframe to pandas and using to_html() function to send spark dataframe as email..

as i don't have pandas package in server .can anyone tell is there any other alternate to send spark dataframe via email without using pandas

i followed below code

I'm automating the whole process. can someone help me with this?


问:
to stay the image\table in its postion ie after the sectionoverleaf
in a two column article the figure is not staying its postion ie after the section. But it goes and sits to the top of the page even if i use \usepackage{float} with[H] shat to do

\section{The Design, Intent, and \ Limitations of the Templates}
The templates are intended to {\bf{approximate the final look and page length of the articles/papers}}. {\bf{They are NOT intended to be the final produced work that is displayed in print or on IEEEXplore\textsuperscript{\textregistered}}}. They will help to give the authors an approximation of the number of pages that will be in the final version. The structure of the \LaTeX\ files, as designed, enable easy conversion to XML for the composition systems used by the IEEE. The XML files are used to produce the final print/IEEEXplore pdf and then converted to HTML for IEEEXplore.

```<code>
\begin{table}[H]
    \centering
        \caption{Comparison of different indexing methods (weight assignment to each CMP)
Method  Accuracy (\%)}
    \label{tab:my_label}
    \begin{tabular}{c|c}
A   &59.8\\
B   &73.2\\
C   &65.4\\
D   &67.26\\
E   &88.86
    \end{tabular}

\end{table}
</code>```

Body:
in a two column article the figure is not staying its postion ie after the section. But it goes and sits to the top of the page even if i use \usepackage{float} with[H] shat to do

\section{The Design, Intent, and \ Limitations of the Templates}
The templates are intended to {\bf{approximate the final look and page length of the articles/papers}}. {\bf{They are NOT intended to be the final produced work that is displayed in print or on IEEEXplore\textsuperscript{\textregistered}}}. They will help to give the authors an approximation of the number of pages that will be in the final version. The structure of the \LaTeX\ files, as designed, enable easy conversion to XML for the composition systems used by the IEEE. The XML files are used to produce the final print/IEEEXplore pdf and then converted to HTML for IEEEXplore.

\begin{table}[H]
    \centering
        \caption{Comparison of different indexing methods (weight assignment to each CMP)
Method  Accuracy (\%)}
    \label{tab:my_label}
    \begin{tabular}{c|c}
A   &59.8\\
B   &73.2\\
C   &65.4\\
D   &67.26\\
E   &88.86
    \end{tabular}

\end{table}


问:
How to get LiveResponse library file history?
I uploaded files to LiveResponse library using https://github.com/MicrosoftDocs/microsoft-365-docs/blob/public/microsoft-365/security/defender-endpoint/live-response-library-methods.md API.

I overwrite specific file in mistake (and I have no local backup of this file), How can I recover the content of the file from the LiveResponse library before the overwrite?

When I get the list of the library files using GET /api/libraryfiles I got:

{"@odata.context":"https://api.securitycenter.microsoft.com/api/$metadata#LibraryFiles","value":[{"fileName":"script.ps1","sha256":"8b0....f1c63abad95d6bda","description":"1","creationTime":"2022-08-08T15:45:05.170374Z","lastUpdatedTime":"2022-08-08T15:45:05.170374Z","createdBy":"MyUser","hasParameters":false,"parametersDescription":null}
...
```

And I dont see any indication about the file history etc.

Body:
I uploaded files to LiveResponse library using https://github.com/MicrosoftDocs/microsoft-365-docs/blob/public/microsoft-365/security/defender-endpoint/live-response-library-methods.md API.

I overwrite specific file in mistake (and I have no local backup of this file), How can I recover the content of the file from the LiveResponse library before the overwrite?

When I get the list of the library files using GET /api/libraryfiles I got:

{"@odata.context":"https://api.securitycenter.microsoft.com/api/$metadata#LibraryFiles","value":[{"fileName":"script.ps1","sha256":"8b0....f1c63abad95d6bda","description":"1","creationTime":"2022-08-08T15:45:05.170374Z","lastUpdatedTime":"2022-08-08T15:45:05.170374Z","createdBy":"MyUser","hasParameters":false,"parametersDescription":null}
...

And I dont see any indication about the file history etc.


问:
How to import javax.smartcard library in android studio?
I am currently using javax.smartcardio in a spring project using eclipse. I added the library in eclipse by going to Build Path > Configure Build Path > Module Dependencies and then selecting the javax.smartcardio from the list then Apply and Close.

Now I am working on an android project which is using the same hardware that I used in spring project. As of my current knowledge, I know that javax.smartcardio is present already in Java SDK. Now I need to import the same module in Android Studio to use in my android project but don't know from where to add the javax.smartcardio library into my android studio project.

Looking forward to hearing soon. Thanks


问:
chart.js doesn't load in flow+hilla
Made a hilla view based on the standard start.vaadin.com bundle for version 23. I use chart.js version 3.8.2, but also later versions have the same issue.

```<code>import { html } from 'lit';
import { customElement, query } from 'lit/decorators.js';
import { View } from '../../views/view';
import * as ChartJS from 'chart.js';

@customElement('welcome-view')
export class WelcomeView extends View {

  @query('#plot')
  plot!: HTMLCanvasElement;

  connectedCallback() {
    super.connectedCallback();
    this.classList.add('flex', 'p-m', 'gap-m', 'items-end');
  }

  createRenderRoot() {
    // Do not use a shadow root
    return this;
  }

  firstUpdated(changedProperties: Map<string | number | symbol, unknown> | undefined) {

    const data = [
      { year: 2010, count: 10 },
      { year: 2011, count: 20 },
      { year: 2012, count: 15 },
      { year: 2013, count: 25 },
      { year: 2014, count: 22 },
      { year: 2015, count: 30 },
      { year: 2016, count: 28 },
    ];
    try {
      new ChartJS.Chart(
          this.plot,
          {
            type: 'bar',
            data: {
              labels: data.map(row => row.year),
              datasets: [
                {
                  label: 'Acquisitions by year',
                  data: data.map(row => row.count)
                }
              ]
            }
          }
      );
    } catch(e:unknown){
      if (typeof e === "string") {
        console.log("Chart exception:"+e);
      } else if (e instanceof Error) {
        console.log("Chart exception:"+e.message);
      }
    }
  }

  render() {
    return html`
      <div style="height: 800px;width: 800px;"><canvas id="plot"></canvas></div>
    `;
  }
}
</code>```

Produces the following console.log message:
"Chart exception:"bar" is not a registered controller."

Any idea's?

I suspect it is related to vite? I didn't try webpack yet, since that is deprecated.

Title: chart.js doesn't load in flow+hilla

Body:
Made a hilla view based on the standard start.vaadin.com bundle for version 23. I use chart.js version 3.8.2, but also later versions have the same issue.

import { html } from 'lit';
import { customElement, query } from 'lit/decorators.js';
import { View } from '../../views/view';
import * as ChartJS from 'chart.js';

@customElement('welcome-view')
export class WelcomeView extends View {

  @query('#plot')
  plot!: HTMLCanvasElement;

  connectedCallback() {
    super.connectedCallback();
    this.classList.add('flex', 'p-m', 'gap-m', 'items-end');
  }

  createRenderRoot() {
    // Do not use a shadow root
    return this;
  }

  firstUpdated(changedProperties: Map<string | number | symbol, unknown> | undefined) {

    const data = [
      { year: 2010, count: 10 },
      { year: 2011, count: 20 },
      { year: 2012, count: 15 },
      { year: 2013, count: 25 },
      { year: 2014, count: 22 },
      { year: 2015, count: 30 },
      { year: 2016, count: 28 },
    ];
    try {
      new ChartJS.Chart(
          this.plot,
          {
            type: 'bar',
            data: {
              labels: data.map(row => row.year),
              datasets: [
                {
                  label: 'Acquisitions by year',
                  data: data.map(row => row.count)
                }
              ]
            }
          }
      );
    } catch(e:unknown){
      if (typeof e === "string") {
        console.log("Chart exception:"+e);
      } else if (e instanceof Error) {
        console.log("Chart exception:"+e.message);
      }
    }
  }

  render() {
    return html`

<canvas id="plot"></canvas>

    `;
  }
}

Produces the following console.log message:
"Chart exception:"bar" is not a registered controller."

Any idea's?

I suspect it is related to vite? I didn't try webpack yet, since that is deprecated.


问:
WebSocket connection issue on e-mobility-charging-stations-simulator
enter image description hereunable to add webSocket connection

I have cloned the code from Github

then in the root directory I have given npm install and then npm start.

server started.

to start client side rendering under ui/web directory I have given npm install and then start.

client side is rendered

after clicking start simulator in console it shows webSocket Error.
kindly share the solution.
enter image description here


问:
Display data according to user name in Grafana
I have dashboards that monitor servers and they are divided into groups according to the departments I created and each department has a username that corresponds to its name.
The servers are filtered using regex so that each department has its own servers.
I want each department to be shown its server table only and not all the tables of all departments.
I would appreciate your help

I tried using the global variable “${__user.login}” but without success.


问:
Why can't com.google.inject.Singleton be found when I have the Google Guice library added to the project?
I want to add Google Guice to my multi-module Gradle project. So I added this to the relevant module's build.gradle file:

```<code>implementation group: 'com.google.inject', name: 'guice', version: '5.1.0'
</code>```

When I build it, the files download and it shows:

Build successfull

But then when I want to use it, for example I add

import com.google.inject.Singleton;
```

it reports:

Cannot resolve symbol 'google'

I use IntellijIDEA.

I don't know much about it, so I would appreciate it if someone could explain to me what I'm doing wrong or how to correctly add this library to the project.

Body:
I want to add Google Guice to my multi-module Gradle project. So I added this to the relevant module's build.gradle file:

implementation group: 'com.google.inject', name: 'guice', version: '5.1.0'

When I build it, the files download and it shows:

Build successfull

But then when I want to use it, for example I add

import com.google.inject.Singleton;

it reports:

Cannot resolve symbol 'google'

I use IntellijIDEA.

I don't know much about it, so I would appreciate it if someone could explain to me what I'm doing wrong or how to correctly add this library to the project.


问:
Lock only specific region of array
I have read about std::sync::Mutex but it lock whole array which I don't want. Mine requirement is lock only region or block (certain contiguous indices) which I'm currently modifying and other regions should be available for other threads for write also.
Can someone give hint for what I should look for?

Title: Lock only specific region of array


问:
.getState() returning initial value when used with redux-persist
I stored chosen language with redux-persist but when I try to access it with getState in i18next file, it returns Initial value, everywhere else it returns stored data.

I've tried accessing it like this

store.getState().language.language

Only in this file/component it returns initial value, anywhere else it gets stored data

Because of rules of hooks I can’t access it with useSelector.


问:
Log file is not generated in spring boot application
I am trying to write log into file but it doesn't working. Its printing in console but log file not getting generated on given path. In pom.xml, add dependency of log4j2. I have also added xml file but it also did not work.

Please guide me that how can I generate log file in spring boot application. I tried multiple solutions but it did not work.

As you can see codes.

```<code>@Slf4j
@Service
public class Main {

    @Autowired
    private DemoDao dao;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Asyn asyn;

    static int schedulerCount = 0;

    @Scheduled(fixedDelay=8000)
    public void schedule() {

        log.info("++++++++++++++++++++++++++++++++++++Scheduler started schedulerCount  :  "+schedulerCount+"+++++++++++++++++++++++++++++++++++++"+ LocalDateTime.now());
        List<Json> jsonList = new ArrayList<Json>();
        List<List<Json>> smallLi = new ArrayList<List<Json>>();
        try {

            jsonList = dao.getJsonList();
            log.info("jsonList size   :   " + jsonList.size());

            Future<String> futureResult = null;
            for (int i = 0; i < jsonList.size(); i++) {
                futureResult = asyn.withAsynUpdate(jsonList.get(i), schedulerCount);
            }

            if(futureResult != null) {
                futureResult.get();
            }
            schedulerCount++;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 @Slf4j
    @Component
    public class Asyn {

        @Autowired
        private DemoDao dao;

        private final Logger log = LoggerFactory.getLogger(this.getClass());

        public void withoutAsynInsert(List<Json> li) throws Exception {

            log.info("without start+++++++++++++  " + LocalDateTime.now());
            System.out.println("without start+++++++++++++  " + LocalDateTime.now());
            try {
                for (int i = 0; i < li.size(); i++) {
                    dao.saveJson(li.get(i));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("without end  +++++++++++++  " + LocalDateTime.now());
            System.out.println("without end  +++++++++++++  " + LocalDateTime.now());
        }
    }
</code>```

Body:
I am trying to write log into file but it doesn't working. Its printing in console but log file not getting generated on given path. In pom.xml, add dependency of log4j2. I have also added xml file but it also did not work.

Please guide me that how can I generate log file in spring boot application. I tried multiple solutions but it did not work.

As you can see codes.

@Slf4j
@Service
public class Main {

    @Autowired
    private DemoDao dao;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Asyn asyn;

    static int schedulerCount = 0;

    @Scheduled(fixedDelay=8000)
    public void schedule() {

        log.info("++++++++++++++++++++++++++++++++++++Scheduler started schedulerCount  :  "+schedulerCount+"+++++++++++++++++++++++++++++++++++++"+ LocalDateTime.now());
        List<Json> jsonList = new ArrayList<Json>();
        List<List<Json>> smallLi = new ArrayList<List<Json>>();
        try {

            jsonList = dao.getJsonList();
            log.info("jsonList size   :   " + jsonList.size());

            Future<String> futureResult = null;
            for (int i = 0; i < jsonList.size(); i++) {
                futureResult = asyn.withAsynUpdate(jsonList.get(i), schedulerCount);
            }

            if(futureResult != null) {
                futureResult.get();
            }
            schedulerCount++;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 @Slf4j
    @Component
    public class Asyn {

        @Autowired
        private DemoDao dao;

        private final Logger log = LoggerFactory.getLogger(this.getClass());

        public void withoutAsynInsert(List<Json> li) throws Exception {

            log.info("without start+++++++++++++  " + LocalDateTime.now());
            System.out.println("without start+++++++++++++  " + LocalDateTime.now());
            try {
                for (int i = 0; i < li.size(); i++) {
                    dao.saveJson(li.get(i));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("without end  +++++++++++++  " + LocalDateTime.now());
            System.out.println("without end  +++++++++++++  " + LocalDateTime.now());
        }
    }


问:
Register implementation of IDependencyResolver in ASP.NET Core 6 Web API
I'm playing around with trying to implement my own IoC Container in .NET 6.

As far as I can understand based on reading, the way I should go about it is to implement the IDependencyResolver interface and then register this resolver in the program.cs file. The resolver is then responsible for calling my custom IoC container.

My issue is, or at least I think my issue is that I don't know how to register this resolver in the program.cs file of my ASP.NET Core 6 Web API.

If I for example look at how I would go about to add autofac to my application, I guess I would do something like this:

```<code>// Do I need this?
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    builder.RegisterModule(new MyApplicationModule());
});
</code>```

I'm a bit confused to this in comparison to the IDependencyResolver. Looking at the source code of autofac it seems like the UseServiceProviderFactory call is used to create the ContainerBuilder which is then used to register dependencies?

I know it maybe doesn't make sense to look at Autofac but I can't seem to find much documentation about this that makes sense to me.

My resolver looks something like this now (removed code for clarity):

```<code>    public class RandomResolver : IDependencyResolver
    {
        // MyContainer has RegisterService and ResolveService
        // methods etc that will be called.
        private MyContainer _container;

        public RandomResolver(MyContainer container)
        {
            _container = container;
        }

        public IDependencyScope BeginScope()
        {
            //
        }

        public void Dispose()
        {
            //
        }

        public object GetService(Type serviceType)
        {
            //Get service from MyContainer
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            //Get Services from MyContainer
        }
    }
</code>```

In my head my program.cs file should look something like this:

```<code>var myContainer = new MyContainer()
myContainer.Register<SomeService, ISomeService>();

var resolver = new RandomResolver(myContainer);

// This does not exist
builder.Host.DependencyResolver = resolver;
</code>```

I'm guessing I'm missing some core concept in creating and registering a minimal IoC container? Or have I just misunderstood the entire concept of the resolver?

Any help would be highly appreciated, thanks!

Body:
I'm playing around with trying to implement my own IoC Container in .NET 6.

As far as I can understand based on reading, the way I should go about it is to implement the IDependencyResolver interface and then register this resolver in the program.cs file. The resolver is then responsible for calling my custom IoC container.

My issue is, or at least I think my issue is that I don't know how to register this resolver in the program.cs file of my ASP.NET Core 6 Web API.

If I for example look at how I would go about to add autofac to my application, I guess I would do something like this:

// Do I need this?
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    builder.RegisterModule(new MyApplicationModule());
});

I'm a bit confused to this in comparison to the IDependencyResolver. Looking at the source code of autofac it seems like the UseServiceProviderFactory call is used to create the ContainerBuilder which is then used to register dependencies?

I know it maybe doesn't make sense to look at Autofac but I can't seem to find much documentation about this that makes sense to me.

My resolver looks something like this now (removed code for clarity):

    public class RandomResolver : IDependencyResolver
    {
        // MyContainer has RegisterService and ResolveService
        // methods etc that will be called.
        private MyContainer _container;

        public RandomResolver(MyContainer container)
        {
            _container = container;
        }

        public IDependencyScope BeginScope()
        {
            //
        }

        public void Dispose()
        {
            //
        }

        public object GetService(Type serviceType)
        {
            //Get service from MyContainer
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            //Get Services from MyContainer
        }
    }

In my head my program.cs file should look something like this:

var myContainer = new MyContainer()
myContainer.Register<SomeService, ISomeService>();

var resolver = new RandomResolver(myContainer);

// This does not exist
builder.Host.DependencyResolver = resolver;

I'm guessing I'm missing some core concept in creating and registering a minimal IoC container? Or have I just misunderstood the entire concept of the resolver?

Any help would be highly appreciated, thanks!


问:
Have Telegram Bot API any method for create the unique link for private telegram channel?
I would like to make a bot using aiogram that sends on command '/start' link to a private channel. Link can be used only one time, 1 link = 1 user that opened bot and got link.

The problem: I made the bot the administrator of my channel, but i can't find the method that could help them for create unique link

I tried to use method createChatInviteLink, but it doesnt work for channels


问:
How to replace image automatically in google slide using App Script?
I have written a code, but images are inserting one on one. I need image should be replace which is stored in drive folder. Please let me know the solution for this.</p>


问:
The default canonical URL is set to localhost instead of domain URL. How to resolve this?
Hi, Everyone.

With Spartacus 4.0 onwards, the canonical URL is configured to be default as below. However, the canonical URL for PDP page has local IP address in quality and production environment. The other pages have the domain name as expected. Any help to resolve this

pageMeta: { canonicalUrl: { forceHttps: true, forceWww: false, removeQueryParams: true, forceTrailingSlash: true } }

Setting it manually on PDP controller also didn't help.

this.pageMetaLinkService.setCanonicalLink(this.winRef.location.href);

Any help to resolve this will be appreciated. Thanks!


问:
Could passing "this" pointer in constructor possibly discard qualifiers and lead to undefined behaviour
I have this simple mechanism for subscribing and sending messages.

```<code>#include <iostream>
#include <functional>

struct Messager;
struct Subscriber
{
    Subscriber(Messager& messager);
    void call() // This (non-const) version of the method is called
    {
        i = 10;
        std::cout << "Non-const " << i << '\n';
    }
    void call() const
    {
        std::cout << "Const\n";
    }
private:
    int i = 0;
};

struct Messager
{
    // This (non-const) version of the method is called
    void subscribe(Subscriber& subscriber)
    {
        callback = [&subscriber]
        {
            subscriber.call();
        };
    }

    // Expected behaviour is that this (const-qualified) version would be called
    void subscribe(const Subscriber& subscriber)
    {
        callback = [&subscriber]
        {
            subscriber.call();
        };
    }

    void notify()
    {
        callback();
    }
    std::function<void()> callback;
};

Subscriber::Subscriber(Messager& messager)
{
    messager.subscribe(*this);
}

int main()
{
    Messager messager;
    const Subscriber s{messager};
    messager.notify();
}
</code>```

My question is if passing this pointer in the Subsriber's constructor to the Messager::subscribe method, can lead to undefined behaviour (as it appears that there is mutation of state in a const object) when Messager::notify is called?

If so, what can be done about that or how could one make the compiler enforce that it's is not allowed?

Body:
I have this simple mechanism for subscribing and sending messages.

#include <iostream>
#include <functional>

struct Messager;
struct Subscriber
{
    Subscriber(Messager& messager);
    void call() // This (non-const) version of the method is called
    {
        i = 10;
        std::cout << "Non-const " << i << '\n';
    }
    void call() const
    {
        std::cout << "Const\n";
    }
private:
    int i = 0;
};

struct Messager
{
    // This (non-const) version of the method is called
    void subscribe(Subscriber& subscriber)
    {
        callback = [&subscriber]
        {
            subscriber.call();
        };
    }

    // Expected behaviour is that this (const-qualified) version would be called
    void subscribe(const Subscriber& subscriber)
    {
        callback = [&subscriber]
        {
            subscriber.call();
        };
    }

    void notify()
    {
        callback();
    }
    std::function<void()> callback;
};

Subscriber::Subscriber(Messager& messager)
{
    messager.subscribe(*this);
}

int main()
{
    Messager messager;
    const Subscriber s{messager};
    messager.notify();
}

My question is if passing this pointer in the Subsriber's constructor to the Messager::subscribe method, can lead to undefined behaviour (as it appears that there is mutation of state in a const object) when Messager::notify is called?

If so, what can be done about that or how could one make the compiler enforce that it's is not allowed?


问:
How to secure client http calls to the backend?
I am trying to figure out what is the best way to prevent random people access/make requests to the server.
Currently, everyone that have the url and the endpoint can easily make requests and I believe it's kind of security breach.

I am using Express.js that hosting static build of React.js

Here is an example of a call:

// Client:

```<code>async function getData(id){
  try {
    const res = await axios.get(`${backendDomain}/data/${id}`)
    const data = res.data

    return data
  } catch (error) {
    ...
  }
}
</code>```

// Server:

```<code>app.get('/data/:id', function(req, res) {
  ...logic
  res.send(data);
});

</code>```

I tried adding to the Client "x-api-key" header and pass an api key that only I have and add a middleware that will check the api and see if it passed currectly from the client. But obviously it is not a good solution because you can see the key on "Network" section while inspecting.

What can I do?

Looking for the best way to prevent random people accessing the data

Body:
I am trying to figure out what is the best way to prevent random people access/make requests to the server.
Currently, everyone that have the url and the endpoint can easily make requests and I believe it's kind of security breach.

I am using Express.js that hosting static build of React.js

Here is an example of a call:

// Client:

async function getData(id){
  try {
    const res = await axios.get(`${backendDomain}/data/${id}`)
    const data = res.data

    return data
  } catch (error) {
    ...
  }
}

// Server:

app.get('/data/:id', function(req, res) {
  ...logic
  res.send(data);
});

I tried adding to the Client "x-api-key" header and pass an api key that only I have and add a middleware that will check the api and see if it passed currectly from the client. But obviously it is not a good solution because you can see the key on "Network" section while inspecting.

What can I do?

Looking for the best way to prevent random people accessing the data


问:
How to make one stack view compression priority less than other
I'm trying to make one stack view not collapse the labels in it, but setting the stack view compression and hugging priority is not giving any results.

The stacks are placed in a collection view cell. In the title stack there are 3 stacks with fill distribution and in the info stack there are 3 stacks with the same distribution.

I've pinned the title stack on top, bottom, and leading to superview, and trailing to the leading of info stack. And pinned info stack top, bottom, and trailing to superview.

I tried to set content & hugging priority that way that info stack won't collapse, as follows

```<code>[infoStack setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    [infoStack setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];

[titleStack setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    [infoStack setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
</code>```

Body:
I'm trying to make one stack view not collapse the labels in it, but setting the stack view compression and hugging priority is not giving any results.

The stacks are placed in a collection view cell. In the title stack there are 3 stacks with fill distribution and in the info stack there are 3 stacks with the same distribution.

I've pinned the title stack on top, bottom, and leading to superview, and trailing to the leading of info stack. And pinned info stack top, bottom, and trailing to superview.

I tried to set content & hugging priority that way that info stack won't collapse, as follows

[infoStack setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    [infoStack setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];

[titleStack setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    [infoStack setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];


问:
Photo slider glitches in mobile when button is added
I am using a swiper API to make a swipeable gallery. I am trying to add a button on the slider card however to do so I must remove an overlay on the card and when I do so the slider glitches and goes crazy. I'm a beginner in code so I apologize if it's a silly issue but I'd appreciate some assistance.

The way i make the button functional is by removing the content: '' from the .gallery-cards class. However when I remove it the slider glitches in the mobile view. the .gallery-cards is only present in the codes JS to make the card swipe. I have added the CSS, JS, and HTML below. Thanks for any suggestions or help

/*=============== SWIPER JS GALLERY ===============*/
let swiperCards = new Swiper(".gallery-cards", {
  loop: true,
  loopedSlides: 5,
  cssMode: true,
  effect: 'fade',
});

let swiperThumbs = new Swiper(".gallery-thumbs", {
  loop: true,
  loopedSlides: 5,
  slidesPerView: 3,
  centeredSlides: true,
  slideToClickedSlide: true,

  pagination: {
    el: ".swiper-pagination",
    type: "fraction",
  },
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev",
  },
});

swiperThumbs.controller.control = swiperCards;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.gallery {
  height: 100vh;
  display: grid;
  align-content: center;
  justify-content: center;
}

.gallery__card {
  position: relative;
  width: 228px;
  height: 288px;
  border-radius: 25px;
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
}

.gallery__img,
.gallery__card::after,
.gallery__data {
  position: absolute;
}

.gallery__img {
  inset: 0;
  margin: auto;
  transition: transform .3s;
}

.gallery__button {
  padding: 12px 20px;
  border-radius: 25px;
  margin-left: 60%;
  width: 100%;
  cursor: pointer;
  border: none;
  margin-bottom: 20px;
  z-index: 15;
}

.gallery__button:hover {
  background-color: #074bb1;
  color: white;
  transition: .6s;
}

.gallery__button-pink {
  padding: 12px 20px;
  border-radius: 25px;
  margin-left: 60%;
  width: 100%;
  cursor: pointer;
  border: none;
  margin-bottom: 20px;
  z-index: 15;
}

.gallery__button-pink:hover {
  background-color: #ff66c4;
  color: white;
  transition: .6s;
}

.gallery__card::after {
  content: '';
  width: 100%;
  height: 100%;
  background: linear-gradient(180deg, hsla(0, 0%, 100%, 0) 32%, hsla(0, 0%, 0%, .3) 100%);
  top: 0;
  z-index: 1;
}

.gallery__data {
  bottom: 1.5rem;
  left: 1.75rem;
  z-index: 10;
}

.gallery__title,
.gallery__subtitle {
  color: #fff;
  font-weight: 500;
}

.gallery__title {
  font-size: 1rem;
}

.gallery__subtitle {
  font-size: .75rem;
}

.gallery__overflow {
  position: relative;
}

.gallery__thumbnail {
  position: relative;
  width: 60px;
  height: 60px;
  border-radius: 1.5rem;
  overflow: hidden;
  cursor: pointer;
  margin-left: auto;
  margin-right: auto;
  transition: transform .3s;
}

.gallery__thumbnail-img {
  position: absolute;
  inset: 0;
  margin: auto;
}

/* Swiper class */

.gallery-cards,
.gallery-thumbs {
  width: 260px;
}

.gallery-cards:hover .gallery__img {
  transform: scale(1.1);
}

.gallery .swiper-wrapper {
  padding: 2.5rem 0;
}

.gallery-thumbs {
  height: 132px;
}

/* Active thumbnail */

.swiper-slide-active .gallery__thumbnail {
  transform: translateY(-1.25rem) scale(1.2);
}

/* Rotate thumbnail */

.swiper-slide-next .gallery__thumbnail {
  transform: rotate(15deg);
}

.swiper-slide-prev .gallery__thumbnail {
  transform: rotate(-15deg);
}

/* Sliding numbers */

.swiper-pagination-fraction {
  font-size: .813rem;
  letter-spacing: -1px;
  font-weight: 500;
  color: hsl(30, 16%, 50%);
  bottom: 0;
}

/* Arrow buttons */

.swiper-button-next::after,
.swiper-button-prev::after {
  content: '';
}

.swiper-button-next,
.swiper-button-prev {
  font-size: 1.5rem;
  color: hsl(30, 8%, 15%);
  top: 5.5rem;
}

.swiper-button-next {
  right: -1.5rem;
  transform: rotate(15deg);
}

.swiper-button-prev {
  left: -1.5rem;
  transform: rotate(-15deg);
}

/* Other swiper settings */

.gallery-cards::after {
  content: '';
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}

.swiper-horizontal.swiper-css-mode>.swiper-wrapper {
  scroll-snap-type: initial;
}

/*=============== BREAKPOINTS ===============*/

/* For small devices */

@media screen and (max-width: 320px) {
  .swiper-button-next,
  .swiper-button-prev {
    display: none;
  }
}

/* For medium devices */

@media screen and (min-width: 1024px) {
  .gallery__card {
    width: 290px;
    height: 370px;
  }
  .gallery__thumbnail {
    width: 65px;
    height: 65px;
  }
  .gallery-cards,
  .gallery-thumbs {
    width: 290px;
  }
}</code>```

       <button class="gallery__button">More Info</button>

```

Body:
I am using a swiper API to make a swipeable gallery. I am trying to add a button on the slider card however to do so I must remove an overlay on the card and when I do so the slider glitches and goes crazy. I'm a beginner in code so I apologize if it's a silly issue but I'd appreciate some assistance.

The way i make the button functional is by removing the content: '' from the .gallery-cards class. However when I remove it the slider glitches in the mobile view. the .gallery-cards is only present in the codes JS to make the card swipe. I have added the CSS, JS, and HTML below. Thanks for any suggestions or help

/*=============== SWIPER JS GALLERY ===============*/
let swiperCards = new Swiper(".gallery-cards", {
  loop: true,
  loopedSlides: 5,
  cssMode: true,
  effect: 'fade',
});

let swiperThumbs = new Swiper(".gallery-thumbs", {
  loop: true,
  loopedSlides: 5,
  slidesPerView: 3,
  centeredSlides: true,
  slideToClickedSlide: true,

  pagination: {
    el: ".swiper-pagination",
    type: "fraction",
  },
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev",
  },
});

swiperThumbs.controller.control = swiperCards;

.gallery {
  height: 100vh;
  display: grid;
  align-content: center;
  justify-content: center;
}

.gallery__card {
  position: relative;
  width: 228px;
  height: 288px;
  border-radius: 25px;
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
}

.gallery__img,
.gallery__card::after,
.gallery__data {
  position: absolute;
}

.gallery__img {
  inset: 0;
  margin: auto;
  transition: transform .3s;
}

.gallery__button {
  padding: 12px 20px;
  border-radius: 25px;
  margin-left: 60%;
  width: 100%;
  cursor: pointer;
  border: none;
  margin-bottom: 20px;
  z-index: 15;
}

.gallery__button:hover {
  background-color: #074bb1;
  color: white;
  transition: .6s;
}

.gallery__button-pink {
  padding: 12px 20px;
  border-radius: 25px;
  margin-left: 60%;
  width: 100%;
  cursor: pointer;
  border: none;
  margin-bottom: 20px;
  z-index: 15;
}

.gallery__button-pink:hover {
  background-color: #ff66c4;
  color: white;
  transition: .6s;
}

.gallery__card::after {
  content: '';
  width: 100%;
  height: 100%;
  background: linear-gradient(180deg, hsla(0, 0%, 100%, 0) 32%, hsla(0, 0%, 0%, .3) 100%);
  top: 0;
  z-index: 1;
}

.gallery__data {
  bottom: 1.5rem;
  left: 1.75rem;
  z-index: 10;
}

.gallery__title,
.gallery__subtitle {
  color: #fff;
  font-weight: 500;
}

.gallery__title {
  font-size: 1rem;
}

.gallery__subtitle {
  font-size: .75rem;
}

.gallery__overflow {
  position: relative;
}

.gallery__thumbnail {
  position: relative;
  width: 60px;
  height: 60px;
  border-radius: 1.5rem;
  overflow: hidden;
  cursor: pointer;
  margin-left: auto;
  margin-right: auto;
  transition: transform .3s;
}

.gallery__thumbnail-img {
  position: absolute;
  inset: 0;
  margin: auto;
}

/* Swiper class */

.gallery-cards,
.gallery-thumbs {
  width: 260px;
}

.gallery-cards:hover .gallery__img {
  transform: scale(1.1);
}

.gallery .swiper-wrapper {
  padding: 2.5rem 0;
}

.gallery-thumbs {
  height: 132px;
}

/* Active thumbnail */

.swiper-slide-active .gallery__thumbnail {
  transform: translateY(-1.25rem) scale(1.2);
}

/* Rotate thumbnail */

.swiper-slide-next .gallery__thumbnail {
  transform: rotate(15deg);
}

.swiper-slide-prev .gallery__thumbnail {
  transform: rotate(-15deg);
}

/* Sliding numbers */

.swiper-pagination-fraction {
  font-size: .813rem;
  letter-spacing: -1px;
  font-weight: 500;
  color: hsl(30, 16%, 50%);
  bottom: 0;
}

/* Arrow buttons */

.swiper-button-next::after,
.swiper-button-prev::after {
  content: '';
}

.swiper-button-next,
.swiper-button-prev {
  font-size: 1.5rem;
  color: hsl(30, 8%, 15%);
  top: 5.5rem;
}

.swiper-button-next {
  right: -1.5rem;
  transform: rotate(15deg);
}

.swiper-button-prev {
  left: -1.5rem;
  transform: rotate(-15deg);
}

/* Other swiper settings */

.gallery-cards::after {
  content: '';
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}

.swiper-horizontal.swiper-css-mode>.swiper-wrapper {
  scroll-snap-type: initial;
}

/*=============== BREAKPOINTS ===============*/

/* For small devices */

@media screen and (max-width: 320px) {
  .swiper-button-next,
  .swiper-button-prev {
    display: none;
  }
}

/* For medium devices */

@media screen and (min-width: 1024px) {
  .gallery__card {
    width: 290px;
    height: 370px;
  }
  .gallery__thumbnail {
    width: 65px;
    height: 65px;
  }
  .gallery-cards,
  .gallery-thumbs {
    width: 290px;
  }
}

       <button class="gallery__button">More Info</button>


问:
How to return a processed video stream to the front end?
I want to get a video stream from a user and draw dots in certain places, but I don't understand how to do it yet.

Originally I wanted to get a video stream from the frontend to the backend, draw dots and return the video back, but now it seems strange.


问:
Macos crash report shows a thread id / number that is different from posix thread id
I have a Macos application that is crashing, I'm trying to analyze the crash report and I see that a certain thread is the one that keeps on crashing in all of the reports.

Trying to associate that thread to my application thread, the report shows threads numbers (0 as main thread, thread 1, 2 and so on)

and they are totally different number from the thread ID I get from pthread_self / pthread_threadid_np

Anyway to connet between these number so I can find the problematic thread in my app ?

Thanks!


问:
Code Coverage of Companion Object in Android
```<code>public class Util
{
    companion object {
        fun isPalindrome(num: Int): Boolean {
            var num = num
            var reversedInteger = 0
            var remainder: Int
            val originalInteger: Int = num
            while (num != 0) {
                remainder = num % 10
                reversedInteger = reversedInteger * 10 + remainder
                num /= 10
            }
            return originalInteger == reversedInteger
        }
    }
}

internal class UtilTest
{
    @Test
    fun is_palindrome_true() {
        val isPalindrome = isPalindrome(232)
        assertEquals(true,isPalindrome)
    }
    @Test
    fun is_palindrome_false() {
        val isPalindrome = isPalindrome(112)
        assertEquals(false,isPalindrome)
    }
}
</code>```

Code coverage when using companion object is
Method 50% (1/2)    Class 50% (1/2) Line 88% (8/9)

And when I use the function as a Top Level Function the code coverage is 100% for all.

Why is it so ?

How can I increase coverage while using companion object?

Body:
public class Util
{
    companion object {
        fun isPalindrome(num: Int): Boolean {
            var num = num
            var reversedInteger = 0
            var remainder: Int
            val originalInteger: Int = num
            while (num != 0) {
                remainder = num % 10
                reversedInteger = reversedInteger * 10 + remainder
                num /= 10
            }
            return originalInteger == reversedInteger
        }
    }
}

internal class UtilTest
{
    @Test
    fun is_palindrome_true() {
        val isPalindrome = isPalindrome(232)
        assertEquals(true,isPalindrome)
    }
    @Test
    fun is_palindrome_false() {
        val isPalindrome = isPalindrome(112)
        assertEquals(false,isPalindrome)
    }
}

Code coverage when using companion object is
Method 50% (1/2)    Class 50% (1/2) Line 88% (8/9)

And when I use the function as a Top Level Function the code coverage is 100% for all.

Why is it so ?

How can I increase coverage while using companion object?


问:
Why the Int-Result of "9995151671798245" is 9995151671798244?
During development work on a project, we encountered some strange behavior.
We implemented a REST route using the NodeJs framework in version 14. The route accepts a query parameter. When passing the value "9995151671798245" as a string and then parsing it as an integer, we noticed that the result is the integer value 9995151671798244. So the string got subtracted by a value of one.

I was able to reproduce this issue with the following console output:

// Wrong ?
console.log(["9995151671798245", parseInt("9995151671798245", 10), Number("9995151671798245"), Math.ceil("9995151671798245"), parseFloat("9995151671798245")])
// Correct!
console.log(["9995151671798244", parseInt("9995151671798244", 10), Number("9995151671798244"), Math.ceil("9995151671798244"), parseFloat("9995151671798244")])
// Correct!
console.log(["9995151671798246", parseInt("9995151671798246", 10), Number("9995151671798246"), Math.ceil("9995151671798246"), parseFloat("9995151671798246")])```

The surrounding numbers are also working as expected. How can it be that the value is subtracted by one during parsing?

Body:
During development work on a project, we encountered some strange behavior.
We implemented a REST route using the NodeJs framework in version 14. The route accepts a query parameter. When passing the value "9995151671798245" as a string and then parsing it as an integer, we noticed that the result is the integer value 9995151671798244. So the string got subtracted by a value of one.

I was able to reproduce this issue with the following console output:

// Wrong ?
console.log(["9995151671798245", parseInt("9995151671798245", 10), Number("9995151671798245"), Math.ceil("9995151671798245"), parseFloat("9995151671798245")])
// Correct!
console.log(["9995151671798244", parseInt("9995151671798244", 10), Number("9995151671798244"), Math.ceil("9995151671798244"), parseFloat("9995151671798244")])
// Correct!
console.log(["9995151671798246", parseInt("9995151671798246", 10), Number("9995151671798246"), Math.ceil("9995151671798246"), parseFloat("9995151671798246")])

The surrounding numbers are also working as expected. How can it be that the value is subtracted by one during parsing?


问:
Code push is showing memory leak in the react native app
I am using code push for my app but it is showing me memory leak

```<code>useEffect(() => {
    checkforupdate();
  }, []);

  async function checkforupdate() {
    codePush.sync(
      {
        installMode: codePush.InstallMode.ON_NEXT_RESTART,
      },
      checkdata,
    );
  }
  function checkdata(syncStatus) {
    switch (syncStatus) {
      case codePush.SyncStatus.CHECKING_FOR_UPDATE:
        break;
      case codePush.SyncStatus.DOWNLOADING_PACKAGE:
        break;
      case codePush.SyncStatus.AWAITING_USER_ACTION:
        break;
      case codePush.SyncStatus.INSTALLING_UPDATE:
        break;
      case codePush.SyncStatus.UP_TO_DATE:
        break;
      case codePush.SyncStatus.UPDATE_IGNORED:
        break;
      case codePush.SyncStatus.UPDATE_INSTALLED:
        break;
      case codePush.SyncStatus.UNKNOWN_ERROR:
        break;
      default:
        null;
    }
  }s
</code>```

what is the issue in this i am not able to get it. As i have checked with all functions but it is giving me memory leak on app start. In this checkdata() is calling 2 times i think i don't know why and i think so that my other function is call again.

Error:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function

Body:
I am using code push for my app but it is showing me memory leak

useEffect(() => {
    checkforupdate();
  }, []);

  async function checkforupdate() {
    codePush.sync(
      {
        installMode: codePush.InstallMode.ON_NEXT_RESTART,
      },
      checkdata,
    );
  }
  function checkdata(syncStatus) {
    switch (syncStatus) {
      case codePush.SyncStatus.CHECKING_FOR_UPDATE:
        break;
      case codePush.SyncStatus.DOWNLOADING_PACKAGE:
        break;
      case codePush.SyncStatus.AWAITING_USER_ACTION:
        break;
      case codePush.SyncStatus.INSTALLING_UPDATE:
        break;
      case codePush.SyncStatus.UP_TO_DATE:
        break;
      case codePush.SyncStatus.UPDATE_IGNORED:
        break;
      case codePush.SyncStatus.UPDATE_INSTALLED:
        break;
      case codePush.SyncStatus.UNKNOWN_ERROR:
        break;
      default:
        null;
    }
  }s

what is the issue in this i am not able to get it. As i have checked with all functions but it is giving me memory leak on app start. In this checkdata() is calling 2 times i think i don't know why and i think so that my other function is call again.

Error:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function