问:
Alwaysdata node.js deployment
I have a following http service in js:

```<code>const express = require('express')
const {Client} = require('pg')
var cors = require('cors')
bodyParser = require('body-parser');
port = 8100

const app = express()

const client = new Client({
    // censored database connection credentials
})

client.connect()
app.use(bodyParser.json());
app.use(cors())
app.use(bodyParser.urlencoded({extended: true}));
app.post('/user', function(req, res){
    console.log(req.body)
    var sql = `INSERT INTO "public"."Users" VALUES ('${req.body.Name}','${req.body.Password}','${req.body.Question}','${req.body.Answer}')`
    client.query(sql, function(err){
        console.log(err)
    })
    res.send();
})
app.listen(port, () => {
    console.log('Server started: ' + port)
})
</code>```

I upload it on alwaysdata in the following way:
upload form

I get connections timeouts when trying to connect to the hosted server.
What is missing?

Title: Alwaysdata node.js deployment

Body:
I have a following http service in js:

const express = require('express')
const {Client} = require('pg')
var cors = require('cors')
bodyParser = require('body-parser');
port = 8100

const app = express()

const client = new Client({
    // censored database connection credentials
})

client.connect()
app.use(bodyParser.json());
app.use(cors())
app.use(bodyParser.urlencoded({extended: true}));
app.post('/user', function(req, res){
    console.log(req.body)
    var sql = `INSERT INTO "public"."Users" VALUES ('${req.body.Name}','${req.body.Password}','${req.body.Question}','${req.body.Answer}')`
    client.query(sql, function(err){
        console.log(err)
    })
    res.send();
})
app.listen(port, () => {
    console.log('Server started: ' + port)
})

I upload it on alwaysdata in the following way:
upload form

I get connections timeouts when trying to connect to the hosted server.
What is missing?


来源: stackexchange

问:
Trying to Authenticate using CookieAuthenticationDefaults.AuthenticationScheme with OpenIddict through angular client application
Trying to Authenticate using CookieAuthenticationDefaults.AuthenticationScheme with OpenIddict through angular client application but cookie not authenticated. does anyone know whats the issue</p>
```<code>[HttpPost("login")]
        [AllowAnonymous]
        public async Task<IActionResult> Login(LoginRequestDTO model)
        {
            var user = await _context.Users.Where(x => x.Username == model.Username).FirstOrDefaultAsync();

            if(user == null)
            {
                return Ok(GenericResponse<bool>.Failure("Invalid Username or Password!", Models.Enums.ApiStatusCode.RecordNotFound));
            }
            else
            {
                if(user.Password != model.Password)
                {
                    return Ok(GenericResponse<bool>.Failure("Invalid Username or Password!", Models.Enums.ApiStatusCode.RecordNotFound));
                }
                else
                {
                    var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, model.Username)
                };

                    var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                    await HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity));

                    return Redirect(model.ReturnUrl);
                }
            }
        }
</code>```
```<code>builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
        {
            //options.LoginPath = "/login";
            options.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = (context) =>
                {
                    context.HttpContext.Response.Redirect("http://localhost:4200/login" + context.RedirectUri.Split("Login")[1]);
                    return Task.CompletedTask;
                }
            };
        });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Trying to Authenticate using CookieAuthenticationDefaults.AuthenticationScheme with OpenIddict through angular client application but cookie not authenticated. does anyone know whats the issue

[HttpPost("login")]
        [AllowAnonymous]
        public async Task<IActionResult> Login(LoginRequestDTO model)
        {
            var user = await _context.Users.Where(x => x.Username == model.Username).FirstOrDefaultAsync();

            if(user == null)
            {
                return Ok(GenericResponse<bool>.Failure("Invalid Username or Password!", Models.Enums.ApiStatusCode.RecordNotFound));
            }
            else
            {
                if(user.Password != model.Password)
                {
                    return Ok(GenericResponse<bool>.Failure("Invalid Username or Password!", Models.Enums.ApiStatusCode.RecordNotFound));
                }
                else
                {
                    var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, model.Username)
                };

                    var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                    await HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity));

                    return Redirect(model.ReturnUrl);
                }
            }
        }

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
        {
            //options.LoginPath = "/login";
            options.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = (context) =>
                {
                    context.HttpContext.Response.Redirect("http://localhost:4200/login" + context.RedirectUri.Split("Login")[1]);
                    return Task.CompletedTask;
                }
            };
        });


问:
connect to a terminal from usb dongle
i am making a micro-controller based dongle and i need it to interrogate host state when connected and display status (status={HOST_OFF,HOST_BOOTED,SERVICE_DOWN,SERVICE_STARTING,SERVICE_UP,SERVICE_ERROR}
i can get all the statuses from a terminal so i wanted the device to be able to login and run some commands to check stuff.

I considered the option of using CDC-ACM and a monitoring service running to update the device but that only works if the monitoring service doesn't fail (say because of disk space or port unavailable etc), and when it fails i cannot get errors.

I am basically trying to eliminate the reason for sending a tech just to look at the screen to see whats going on.

I tried just identifying device as tty device but this seems to expect a service to connect to it from the host side before i can send and characters

Title: connect to a terminal from usb dongle


问:
linked lists and fgets
How do I create a list with numbers read from a file? I can't seem to understand how to do that, because I don't know how many numbers the sequence contains, so how am I supposed to know how many nodes my list has to be composed of.
Here is the code I wrote: does the fgets command create a full list or it just fills the first node?

```<code>    #include <stdio.h>
    #include <stdlib.h>

    int Sequenza (fp f1, fp f2, fp f3);

    typedef FILE* fp;

    typedef struct Nd{
      int dato;
      struct Nd* next;
    } Nodo;

    typedef Nodo* lista;

    int Sequenza (fp f1, fp f2, fp f3){
      lista seq1, seq2;

      seq1 = malloc (sizeof(Nodo));
      seq2 = malloc (sizeof(Nodo));

      f1 = fopen ("sequenza1.txt", "r");
      f2 = fopen ("sequenza2.txt", "r");

    if (f1 == NULL || f2 == NULL){
      printf ("Errore nell'apertura di uno dei due file\n");
      return 0;
    } else {
      while (!feof(f1) && !feof(f2)){
        fgets (seq1, MAX, f1);
        fgets (seq2, MAX, f2);
      }

    }

    fclose (f1);
    fclose (f2);

   }

</code>```

I'm not sure that fgets creates a full list, but just fills in the first node.

Title: linked lists and fgets

Body:
How do I create a list with numbers read from a file? I can't seem to understand how to do that, because I don't know how many numbers the sequence contains, so how am I supposed to know how many nodes my list has to be composed of.
Here is the code I wrote: does the fgets command create a full list or it just fills the first node?

    #include <stdio.h>
    #include <stdlib.h>

    int Sequenza (fp f1, fp f2, fp f3);

    typedef FILE* fp;

    typedef struct Nd{
      int dato;
      struct Nd* next;
    } Nodo;

    typedef Nodo* lista;

    int Sequenza (fp f1, fp f2, fp f3){
      lista seq1, seq2;

      seq1 = malloc (sizeof(Nodo));
      seq2 = malloc (sizeof(Nodo));

      f1 = fopen ("sequenza1.txt", "r");
      f2 = fopen ("sequenza2.txt", "r");

    if (f1 == NULL || f2 == NULL){
      printf ("Errore nell'apertura di uno dei due file\n");
      return 0;
    } else {
      while (!feof(f1) && !feof(f2)){
        fgets (seq1, MAX, f1);
        fgets (seq2, MAX, f2);
      }

    }

    fclose (f1);
    fclose (f2);

   }

I'm not sure that fgets creates a full list, but just fills in the first node.


问:
Vtune profile result show a significant portion of CPU time is spinning
I am using Vtune Threading mode to profile my project which running on windows 10. At Top-down view, I found 39.1% cpu time spend on spinning, callstack show in below picture.

But in Platform View, I find the spinning callstack only cost 40us per frame, in my project on frame cost about 7~14ms,

1.Whether I need to pay attention to the spin time of WaitForSingleObject, if i want to optimize running speed of my project

2.Why Top-down view show ApexScene::simulate spinning cost 39.1% Cup time ,but ApexScene::simulate callstack only cost 3%~6% cpu time each
frame at Platform View

As far as I can see, WaitForSingleObject make thread enter kernel mode, which cost a large amount of cpu time, but thread will not spinning when there is not signal


问:
Python How can I stop the bot if there is no message?
How can I stop the bot from working if my Telegram bot does not have any in-group messages?

I tried the time and datetime modules and when I do any math, the counter doesn't work. I tried the sleep function in the time module and failed again.


问:
How to list all child items of specific product backlog item
I want to list all of the child items that belongs to one specific product backlog item. For example; the algorithm below lists all the parents that belong to the child. I want to do its vice versa which is listing all the children for a parent.

```<code>SELECT
        [System.Id],

        [System.Title],
        [System.AssignedTo],
        [System.State]
FROM workitemLinks
WHERE ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward')
AND ([Target].[System.Id] = 1111)
ORDER BY [System.Id]
MODE (Recursive, ReturnMatchingChildren)
</code>```

I have done some research on Google but I always found the version of "All parents for child item" query. Since I have never used WIQL before and it's one time need, I struggled a bit. I am aware that I can do this from the queries part with the new update of Microsoft. But my company uses the old version of 2020 so the new parent filtering options are unavailable for me.

Body:
I want to list all of the child items that belongs to one specific product backlog item. For example; the algorithm below lists all the parents that belong to the child. I want to do its vice versa which is listing all the children for a parent.

SELECT
        [System.Id],

        [System.Title],
        [System.AssignedTo],
        [System.State]
FROM workitemLinks
WHERE ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward')
AND ([Target].[System.Id] = 1111)
ORDER BY [System.Id]
MODE (Recursive, ReturnMatchingChildren)

I have done some research on Google but I always found the version of "All parents for child item" query. Since I have never used WIQL before and it's one time need, I struggled a bit. I am aware that I can do this from the queries part with the new update of Microsoft. But my company uses the old version of 2020 so the new parent filtering options are unavailable for me.


问:
JPDA doesn't seem to work in IDEA deployed with JBoss
I have a Java project which is deployed on remote JBoss server that I'm trying to debug using JPDA in IDEA.

The following was added to JBoss config to turn this feature on:

```<code>"JAVA_OPTS=$JAVA_OPTS -agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n"
</code>```

I created a new debug configuration in IDEA for the server and it seems that the port is opened and I'm able to connect:

```<code>Connected to the target VM, address: 'here's goes the IP:8787', transport: 'socket'
</code>```

However, when I add breakpoints in the app it doesn't seem to stop executing the code.

There's a REST controller which is I'm absolutely sure should trigger the breakpoint when request is sent to the server. But for some reason that's not the case.

Here's what I've tried so far:

Invalidate Caches/Reset IDEA

Make request to server via Postman instead of browser

But with no luck.
The code on the server should match with my local project.

I'm pretty convinced that the problem has to be on my side.

I've only debugged applications deployed with Tomcat, maybe there's something specific about JBoss?

Might be related to IntelliJ IDEA: Breakpoint not being hit, and is shown without the tick, just a red dot since there's no ticks and also gradle is used.

In addition, I remember when I debugged a tomcat + maven project with JPDA and added breakpoint, IDEA would evaluate and calculate something for a considerable amount of time but in the current project there's no sign of it.

Body:
I have a Java project which is deployed on remote JBoss server that I'm trying to debug using JPDA in IDEA.

The following was added to JBoss config to turn this feature on:

"JAVA_OPTS=$JAVA_OPTS -agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n"

I created a new debug configuration in IDEA for the server and it seems that the port is opened and I'm able to connect:

Connected to the target VM, address: 'here's goes the IP:8787', transport: 'socket'

However, when I add breakpoints in the app it doesn't seem to stop executing the code.

There's a REST controller which is I'm absolutely sure should trigger the breakpoint when request is sent to the server. But for some reason that's not the case.

Here's what I've tried so far:

Invalidate Caches/Reset IDEA

Make request to server via Postman instead of browser

But with no luck.
The code on the server should match with my local project.

I'm pretty convinced that the problem has to be on my side.

I've only debugged applications deployed with Tomcat, maybe there's something specific about JBoss?

Might be related to IntelliJ IDEA: Breakpoint not being hit, and is shown without the tick, just a red dot since there's no ticks and also gradle is used.

In addition, I remember when I debugged a tomcat + maven project with JPDA and added breakpoint, IDEA would evaluate and calculate something for a considerable amount of time but in the current project there's no sign of it.


问:
Remove character from string
Given two strings string1 and string2, remove those characters from first string(string1) which are present in second string(string2). Both the strings are different and contain only lowercase characters.
NOTE: Size of  first string is always greater than the size of  second string( |string1| > |string2|).

```<code>class Solution {
  public:
    string removeChars(string string1, string string2) {
        // code here
        int i;
           int arr[26]={0},curr=0;
           for(i=0; i<string2.size(); i++){
               if((string2[i]-'a')!=-1){
                   arr[string1[i]-'a']=-1;
               }
           }
           for(i=0; i<string1.size(); i++){
               if(arr[string1[i]-'a']!=-1){
                   string1[curr]=string1[i];
                   curr++;
               }
               string1[curr]='\0';

           }

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

For Input: computer cat

Your Output:

puterer

Expected Output:

ompuer

Title: Remove character from string

Body:
Given two strings string1 and string2, remove those characters from first string(string1) which are present in second string(string2). Both the strings are different and contain only lowercase characters.
NOTE: Size of  first string is always greater than the size of  second string( |string1| > |string2|).

class Solution {
  public:
    string removeChars(string string1, string string2) {
        // code here
        int i;
           int arr[26]={0},curr=0;
           for(i=0; i<string2.size(); i++){
               if((string2[i]-'a')!=-1){
                   arr[string1[i]-'a']=-1;
               }
           }
           for(i=0; i<string1.size(); i++){
               if(arr[string1[i]-'a']!=-1){
                   string1[curr]=string1[i];
                   curr++;
               }
               string1[curr]='\0';

           }

       return string1;
    }
};

For Input: computer cat

Your Output:

puterer

Expected Output:

ompuer


问:
Why my clang-format formated C++ code getting a result as `task && t` rather than `task&& t`?
The relative clang-format config is:

```<code>Language: Cpp
BasedOnStyle: Google
PointerAlignment: Left
DerivePointerAlignment: false
AccessModifierOffset: -4
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
...
</code>```

I have surely configure the PointerAlignment as Left. When I format my code, I still get a result as

    task(task && t) noexcept : coro_handle_(t.coro_handle_) { t.coro_handle_ = nullptr; }
```
<p>rather than</p>
```    task(task&& t) noexcept : coro_handle_(t.coro_handle_) { t.coro_handle_ = nullptr; }
```
<p>At the same time, the other line of my code is formatted correctly:</p>
```    task& operator=(const task&) = delete;
    task& operator=(task&& other) noexcept {
        ...
    }

```

What's wrong with the code or clang-format? What's the reason for the problem, and how can that problem be solved / avoided?

Body:
The relative clang-format config is:

Language: Cpp
BasedOnStyle: Google
PointerAlignment: Left
DerivePointerAlignment: false
AccessModifierOffset: -4
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
...

I have surely configure the PointerAlignment as Left. When I format my code, I still get a result as

    task(task && t) noexcept : coro_handle_(t.coro_handle_) { t.coro_handle_ = nullptr; }

rather than

    task(task&& t) noexcept : coro_handle_(t.coro_handle_) { t.coro_handle_ = nullptr; }

At the same time, the other line of my code is formatted correctly:

    task& operator=(const task&) = delete;
    task& operator=(task&& other) noexcept {
        ...
    }

What's wrong with the code or clang-format? What's the reason for the problem, and how can that problem be solved / avoided?


问:
FCNT Arrows F-41B device appear Native Crash In libmedia_omx.so
I had an Native Crash In FCNT Arrows F-41B device. When I play Ad，This is follow error Stack</p>
```<code># CodecLooper(12543)

SIGSEGV(SEGV_MAPERR)

#00 pc 000000000001f2b4 /system/lib64/libmedia_omx.so (android::hardware::media::omx::V1_0::utils::LWOmxNode::freeNode()+52) [arm64-v8a::d6ca6ad0aa6b451025aea9b50df3a511]
#01 pc 000000000009cdc8 /system/lib64/libstagefright.so (android::ACodec::LoadedState::onShutdown(bool)+128) [arm64-v8a::3a0f159449aafa5318775893fbfa1be5]
3
java:
4
[Failed to get Java stack]`

Log printing before errors：
`12312-29 23:18:37.554 900 6264 E ACodec : signalError(omxError 0x80001001, internalError -2)
12412-29 23:18:37.554 900 6264 E ACodec : [c2.android.avc.decoder] configureCodec returning error -2
12512-29 23:18:37.554 900 6264 E ACodec : signalError(omxError 0x80001001, internalError -2)
12612-29 23:18:37.554 900 6263 E MediaCodec: Codec reported err 0xfffffffe, actionCode 0, while in state 3/CONFIGURING
12712-29 23:18:37.555 900 6263 D SurfaceUtils: disconnecting from surface 0xb40000709bb72c70, reason disconnectFromSurface
12812-29 23:18:37.555 900 6263 E MediaCodec: Codec reported err 0xfffffffe, actionCode 0, while in state 0/UNINITIALIZED
12912-29 23:18:37.555 900 2389 E MediaCodec: configure failed with err 0xfffffffe, resetting...
130--------- beginning of crash
13112-29 23:18:37.600 6268 6264 F libc : fdsan: attempted to close file descriptor 293, expected to be unowned, actually owned by unique_fd 0x6f2bbf50d4
13212-29 23:18:38.647 6270 6270 E chromium: [1229/231838.646784:ERROR:process_memory_range.cc(75)] read out of range
13412-29 23:18:39.369 900 900 I Choreographer: Skipped 101 frames! The application may be doing too much work on its main thread.
13912-29 23:18:39.389 900 6264 E npth : Native crash was detected!
</code>```

Body:
I had an Native Crash In FCNT Arrows F-41B device. When I play Ad，This is follow error Stack

# CodecLooper(12543)

SIGSEGV(SEGV_MAPERR)

#00 pc 000000000001f2b4 /system/lib64/libmedia_omx.so (android::hardware::media::omx::V1_0::utils::LWOmxNode::freeNode()+52) [arm64-v8a::d6ca6ad0aa6b451025aea9b50df3a511]
#01 pc 000000000009cdc8 /system/lib64/libstagefright.so (android::ACodec::LoadedState::onShutdown(bool)+128) [arm64-v8a::3a0f159449aafa5318775893fbfa1be5]
3
java:
4
[Failed to get Java stack]`

Log printing before errors：
`12312-29 23:18:37.554 900 6264 E ACodec : signalError(omxError 0x80001001, internalError -2)
12412-29 23:18:37.554 900 6264 E ACodec : [c2.android.avc.decoder] configureCodec returning error -2
12512-29 23:18:37.554 900 6264 E ACodec : signalError(omxError 0x80001001, internalError -2)
12612-29 23:18:37.554 900 6263 E MediaCodec: Codec reported err 0xfffffffe, actionCode 0, while in state 3/CONFIGURING
12712-29 23:18:37.555 900 6263 D SurfaceUtils: disconnecting from surface 0xb40000709bb72c70, reason disconnectFromSurface
12812-29 23:18:37.555 900 6263 E MediaCodec: Codec reported err 0xfffffffe, actionCode 0, while in state 0/UNINITIALIZED
12912-29 23:18:37.555 900 2389 E MediaCodec: configure failed with err 0xfffffffe, resetting...
130--------- beginning of crash
13112-29 23:18:37.600 6268 6264 F libc : fdsan: attempted to close file descriptor 293, expected to be unowned, actually owned by unique_fd 0x6f2bbf50d4
13212-29 23:18:38.647 6270 6270 E chromium: [1229/231838.646784:ERROR:process_memory_range.cc(75)] read out of range
13412-29 23:18:39.369 900 900 I Choreographer: Skipped 101 frames! The application may be doing too much work on its main thread.
13912-29 23:18:39.389 900 6264 E npth : Native crash was detected!


问:
What is the **purpose** of move-appending a vector to another?
In my mind, it seems fairly useless, since the elements will have to be copied anyway for the destination vector to be contiguous in memory. Is there any advantage to the move construction?

I've read the other threads. No, no one addressed this. They only provided solutions on how to perform the move-appension.

Reason this arises -> I'm looking for the most efficient way to append a vector to another, but my question is the one above, so no it is not a duplicate.

I'm specifically referring to the else part of the accepted answer below:

How to use c++11 move semantics to append vector contents to another vector?


问:
How to make Custom CSS select list appear as a modal when the button is clicked?
I have created a custom CSS select and need help to make the #drop in form of a modal.

So that whenever a user clicks on the dropdown button, it will open a modal containing a list of options. And selecting a list will show information on that particular list option.

Also, the #drop div does not appear in the middle of the screen.

I'm new to JS and have managed to create a structure. I'm sharing the code below. Please help me with the modal so that the entire thing works perfectly.

Thanks in advance.

PS: If you think there's some easy way of doing this please add the code to the answer.

```<code><!-- HTML -->

<div class="dropdown">
        <button onclick="toggleDrop(document.querySelector('#drop'))" class="dropbtn"></button>
        <div id="drop" class="dropdown-content d-none">
        <ul>
            <li><a href="#bird" onclick="openPage('dl-tabOne', this)">Click for Bird Name</a></li>
            <li><a href="#animal" onclick="openPage('dl-tabTwo', this)">Click for Animal Name</a></li>
        </ul>
        </div>
    </div>

    <div class="tabs">
        <!-- Bird Name -->
        <div tab-name="dl-tabOne" class="dl-tabcontent">
            Parrot
        </div>

        <!-- Animal Name -->
        <div tab-name="dl-tabTwo" class="dl-tabcontent d-none">
            Lion
        </div>
    </div>

</code>```
```<code><!-- CSS -->

.d-none {
       display: none;
   }

   .dropbtn {
    display: block;
       font-size: 40px;
       font-weight: 700;
       margin: auto;
       width: auto;
       outline: none;
       border: none;
       border-bottom: 2px solid ;
       border-bottom-style: dotted;
       height: 60px;
       cursor: pointer;
       overflow: hidden;
       color: #150ee6;
       background: none;
   }

   .dropdown {
       position: relative;
       margin: 30px 30px 10px;
       text-align: center;
   }

   .dropdown-content {
       position: absolute;
       background-color: #fff;
       min-width: 250px;
       box-shadow:  0 4px 12px 0 rgba(0, 0, 0, 0.1), 0 5px 4px -5px rgba(0, 0, 0, 0.1);
       z-index: 1;
       text-align: left;
       padding: 20px;
   }

   .dropdown-content ul {
       padding: 0;
   }

   .dropdown-content li {
       list-style-type: none;
       border-bottom: 1px solid #dfe1e5;
   }
   .dropdown-content li:last-child{
       border: none;
   }

   .dropdown-content a {
       color: #0d0d21;
       padding: 15px 10px;
       font-size: 1rem;
       text-decoration: none;
       list-style-type: none;
       display: block;
       font-weight: 600;
   }

   .dropdown-content a:hover {
       background-color: #f2f2f2;
   }

   .tabs {
       max-width: 720px;
       margin: 0 auto;
   }

   .dl-tab-abt{
       margin-top: 25px !important;
   }

</code>```
```<code><!-- JS -->

    setButtonInnerText(document.querySelector(".dropbtn"))
    function openPage(id, a) {
        const p = document.querySelector("[tab-name='" + id + "']");
        const tabs = document.querySelectorAll(".tabs .dl-tabcontent");
        for (var x = 0; x < tabs.length; x++)
            tabs[x].classList.add("d-none");
        if (p !== null) {
            document.querySelector(".dropbtn").innerHTML = a.innerHTML;
            p.classList.remove("d-none");
        }
    }

    function toggleDrop(drop) {
        drop.classList.toggle("d-none");
        drop.onclick = function (e) {
            drop.classList.add("d-none");
        }
    }

    function setButtonInnerText(btn) {
        const firstOption = btn.parentElement.querySelector("#drop a:first-child");
        btn.innerHTML = firstOption.innerHTML;
    }

</code>```

Body:
I have created a custom CSS select and need help to make the #drop in form of a modal.

So that whenever a user clicks on the dropdown button, it will open a modal containing a list of options. And selecting a list will show information on that particular list option.

Also, the #drop div does not appear in the middle of the screen.

I'm new to JS and have managed to create a structure. I'm sharing the code below. Please help me with the modal so that the entire thing works perfectly.

Thanks in advance.

PS: If you think there's some easy way of doing this please add the code to the answer.

        <button onclick="toggleDrop(document.querySelector('#drop'))" class="dropbtn"></button>

Click for Bird Name

Click for Animal Name

            Parrot

            Lion

.d-none {
       display: none;
   }

   .dropbtn {
    display: block;
       font-size: 40px;
       font-weight: 700;
       margin: auto;
       width: auto;
       outline: none;
       border: none;
       border-bottom: 2px solid ;
       border-bottom-style: dotted;
       height: 60px;
       cursor: pointer;
       overflow: hidden;
       color: #150ee6;
       background: none;
   }

   .dropdown {
       position: relative;
       margin: 30px 30px 10px;
       text-align: center;
   }

   .dropdown-content {
       position: absolute;
       background-color: #fff;
       min-width: 250px;
       box-shadow:  0 4px 12px 0 rgba(0, 0, 0, 0.1), 0 5px 4px -5px rgba(0, 0, 0, 0.1);
       z-index: 1;
       text-align: left;
       padding: 20px;
   }

   .dropdown-content ul {
       padding: 0;
   }

   .dropdown-content li {
       list-style-type: none;
       border-bottom: 1px solid #dfe1e5;
   }
   .dropdown-content li:last-child{
       border: none;
   }

   .dropdown-content a {
       color: #0d0d21;
       padding: 15px 10px;
       font-size: 1rem;
       text-decoration: none;
       list-style-type: none;
       display: block;
       font-weight: 600;
   }

   .dropdown-content a:hover {
       background-color: #f2f2f2;
   }

   .tabs {
       max-width: 720px;
       margin: 0 auto;
   }

   .dl-tab-abt{
       margin-top: 25px !important;
   }

    setButtonInnerText(document.querySelector(".dropbtn"))
    function openPage(id, a) {
        const p = document.querySelector("[tab-name='" + id + "']");
        const tabs = document.querySelectorAll(".tabs .dl-tabcontent");
        for (var x = 0; x < tabs.length; x++)
            tabs[x].classList.add("d-none");
        if (p !== null) {
            document.querySelector(".dropbtn").innerHTML = a.innerHTML;
            p.classList.remove("d-none");
        }
    }

    function toggleDrop(drop) {
        drop.classList.toggle("d-none");
        drop.onclick = function (e) {
            drop.classList.add("d-none");
        }
    }

    function setButtonInnerText(btn) {
        const firstOption = btn.parentElement.querySelector("#drop a:first-child");
        btn.innerHTML = firstOption.innerHTML;
    }


问:
Can we run appium test scripts through flask server on locally connected device
I am trying to run my appium scripts on button click in a html template, but unfortunately I have searched everywhere but still I found no solution.
My html template is inside a templates folder in the flask project directory and I am taking path as an input and want to pass that string to my Appium script and as soon as I click on the Submit button on my template it should launch the test script on my locally connected phone taking the path as a parameter.
Any kind of help will be appreciated.
Regards

I tried adding functions of my test script in the flask route but I have multiple functions in my python script and for every function I would have to create multiple routes. I was expecting to run the python script all at once on the default flask route ('/').

Following is my code for flask_server.py file as per now I am just getting the parameter in it and showing it in the next route but instead I want to pass my appium script here and run it on device on submit.

```<code>from flask import Flask
from flask import render_template
from flask import request

from Instagram.instagram_android_automation import
InstagramAndroidAutomation

from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/dashboard/<name>')
def dashboard(name):
   return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
  if request.method == 'POST':
    user = request.form['name']
    return redirect(url_for('dashboard',name = user))
  else:
    user = request.args.get('name')
    return render_template('login.html')

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

Body:
I am trying to run my appium scripts on button click in a html template, but unfortunately I have searched everywhere but still I found no solution.
My html template is inside a templates folder in the flask project directory and I am taking path as an input and want to pass that string to my Appium script and as soon as I click on the Submit button on my template it should launch the test script on my locally connected phone taking the path as a parameter.
Any kind of help will be appreciated.
Regards

I tried adding functions of my test script in the flask route but I have multiple functions in my python script and for every function I would have to create multiple routes. I was expecting to run the python script all at once on the default flask route ('/').

Following is my code for flask_server.py file as per now I am just getting the parameter in it and showing it in the next route but instead I want to pass my appium script here and run it on device on submit.

from flask import Flask
from flask import render_template
from flask import request

from Instagram.instagram_android_automation import
InstagramAndroidAutomation

from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/dashboard/<name>')
def dashboard(name):
   return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
  if request.method == 'POST':
    user = request.form['name']
    return redirect(url_for('dashboard',name = user))
  else:
    user = request.args.get('name')
    return render_template('login.html')

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


问:
multiprocessing on numpy object not work with CUDA enabled
I found that multiprocessing.Pool was not work on numpy object (in the code is y) when CUDA was enabled, but multiprocessing.Process could. Why?

However, Process took a lot of time at the p.start(), so how to make the Pool work?

```<code>import torch
from multiprocessing import Pool, Process

class myclass:
    def __init__(self):
        self.model = torch.nn.Linear(2, 2).cuda() # model on CUDA

    # do some post-processing of numpy object
    def f(self, x):
        return x+100

    def CUDA_then_CPUmp(self, x):
        y = self.model(x).data.cpu().numpy() # y is on the CPU

        # Pool or ThreadPoolExecutor on CPU can't work
        with Pool(5) as p:
            print(p.map(self.f, y))

        # Process could work, but `p.start()` may be slow
        # p = Process(target=self.f, args=(1,))
        # p.start()
        # p.join()

        return y

if __name__ == "__main__":
    obj = myclass()
    x = torch.arange(4).reshape(2, 2).float().cuda()
    print(obj.CUDA_then_CPUmp(x))
</code>```

It throwed error

RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method

I tried add torch.multiprocessing.set_start_method('spawn') in the main code, Pool can work but the Pool maybe used GPU twice (but there was no need GPU operation in the f function).

Body:
I found that multiprocessing.Pool was not work on numpy object (in the code is y) when CUDA was enabled, but multiprocessing.Process could. Why?

However, Process took a lot of time at the p.start(), so how to make the Pool work?

import torch
from multiprocessing import Pool, Process

class myclass:
    def __init__(self):
        self.model = torch.nn.Linear(2, 2).cuda() # model on CUDA

    # do some post-processing of numpy object
    def f(self, x):
        return x+100

    def CUDA_then_CPUmp(self, x):
        y = self.model(x).data.cpu().numpy() # y is on the CPU

        # Pool or ThreadPoolExecutor on CPU can't work
        with Pool(5) as p:
            print(p.map(self.f, y))

        # Process could work, but `p.start()` may be slow
        # p = Process(target=self.f, args=(1,))
        # p.start()
        # p.join()

        return y

if __name__ == "__main__":
    obj = myclass()
    x = torch.arange(4).reshape(2, 2).float().cuda()
    print(obj.CUDA_then_CPUmp(x))

It throwed error

RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method

I tried add torch.multiprocessing.set_start_method('spawn') in the main code, Pool can work but the Pool maybe used GPU twice (but there was no need GPU operation in the f function).


问:
Socket Connect calls in a loop
is it ok to connect to Sockets inside of a loop?

even if that is ok

if I put the connect call before the loop - would it automatically reconnect on a recv or send call if the connection was lost?

would it slow down the loop noticeably?

What are the best practices here?

In my case currently I'm asking about a SUB client. But soon I will need to use some REP/REQ as well on another socket.

Title: Socket Connect calls in a loop


问:
How to Handle the Back and Foward Buttons of the Web browser on flutter Web
I am working on a flutter web project and I am using AutoRoute ( https://pub.dev/packages/auto_route)  for my routing. I am facing this challenge, trying to handle the use of the browser Back and Forward arrow buttons.

A scenario is : After login page I send the user to a homepage. I want to prevent the user from coming back to the Login page when he/she uses the Back Arrow of the browser.
Also I want to prevent the user from going straight to the home page without login by using the route url.

I have tried WillPopScope and I could not achieved my target on the web... I know that works very fine for me on mobile but not working on the web.


问:
Using list comprehension to replace a string containing space
I am trying to build a simple correction-function for some grammatically wrong sentences I randomly generated elsewhere. I would like to use a dictionary and list comprehension as there are only a few options where the program will not generate a correct sentence, ie "JEDER KIRCHE" which needs to be corrected to "JEDE KIRCHE".

So I built my dic and defined a variable with list comprehension, but it doesn't work. I'm guessing the problem is the whitespace in the strings, as the same thing works fine if I try to replace strings without it.

```<code>text = 'JEDER KIRCHE'
ersetzungen = {'EIN KIRCHE': 'EINE KIRCHE', 'KEIN KIRCHE': 'KEINE KIRCHE', 'JEDER KIRCHE': 'JEDE KIRCHE', 'JEDER SCHLOSS': 'JEDES SCHLOSS', 'JEDER BILD': 'JEDES BILD', 'JEDER AUGE': 'JEDES AUGE','JEDER DORF': 'JEDES DORF', 'JEDER HAUS': 'JEDES HAUS'}
korrektur = ' '.join([ersetzungen.get(x, x) for x in text.split()])
print(korrektur)
</code>```

Thanks in advance!

Body:
I am trying to build a simple correction-function for some grammatically wrong sentences I randomly generated elsewhere. I would like to use a dictionary and list comprehension as there are only a few options where the program will not generate a correct sentence, ie "JEDER KIRCHE" which needs to be corrected to "JEDE KIRCHE".

So I built my dic and defined a variable with list comprehension, but it doesn't work. I'm guessing the problem is the whitespace in the strings, as the same thing works fine if I try to replace strings without it.

text = 'JEDER KIRCHE'
ersetzungen = {'EIN KIRCHE': 'EINE KIRCHE', 'KEIN KIRCHE': 'KEINE KIRCHE', 'JEDER KIRCHE': 'JEDE KIRCHE', 'JEDER SCHLOSS': 'JEDES SCHLOSS', 'JEDER BILD': 'JEDES BILD', 'JEDER AUGE': 'JEDES AUGE','JEDER DORF': 'JEDES DORF', 'JEDER HAUS': 'JEDES HAUS'}
korrektur = ' '.join([ersetzungen.get(x, x) for x in text.split()])
print(korrektur)

Thanks in advance!


问:
Python - AttributeError: 'numpy.ndarray' object has no attribute 'device'
everyone. I am beginner in coding and non-major in it.

I run the code by python on Window WSL(Ubuntu).

In running the code, dgl was run and it has error like 'AttributeError: 'numpy.ndarray' object has no attribute 'device''

More detail:

```<code>AttributeError: Caught AttributeError in DataLoader worker process 0.
Original Traceback (most recent call last):
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/worker.py", line 302, in _worker_loop
    data = fetcher.fetch(index)
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 49, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 49, in <listcomp>
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "~/interactive_se3/OpenFold2-toy_se3/src/Dataset.py", line 67, in __getitem__
    G.ndata['x'] = r.astype(np.float32)
  File "~/lib/python3.8/site-packages/dgl/view.py", line 90, in __setitem__
    self._graph._set_n_repr(self._ntid, self._nodes, {key: val})
  File "~/lib/python3.8/site-packages/dgl/heterograph.py", line 4121, in _set_n_repr
    if F.context(val) != self.device:
  File "~/lib/python3.8/site-packages/dgl/backend/pytorch/tensor.py", line 80, in context
    return input.device
AttributeError: 'numpy.ndarray' object has no attribute 'device'
</code>```

I found the error line and I got the reason of error.
The module 'ndarray.py' in dgl package (\lib\python3.8\site-packages\dgl) actually doesn't have 'device' attribute as the error said.

After I found the reason of error, 'no attribute',

I changed the code like that:
from:

```<code>from ... import ndarray as nd
</code>```

to:

```<code>from numpy import ndarray as nd
</code>```

It work!

But I faced again the error like 'AttributeError: type object 'numpy.ndarray' has no attribute 'from_dlpack''

More detail:

```<code>AttributeError: Caught AttributeError in DataLoader worker process 0.
Original Traceback (most recent call last):
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/worker.py", line 302, in _worker_loop
    data = fetcher.fetch(index)
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 49, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 49, in <listcomp>
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "~/OpenFold2-toy_se3/src/Dataset.py", line 65, in __getitem__
    G = dgl.DGLGraph((src, dst))
  File "~/lib/python3.8/site-packages/dgl/heterograph.py", line 76, in __init__
    gidx = heterograph_index.create_unitgraph_from_coo(
  File "~/lib/python3.8/site-packages/dgl/heterograph_index.py", line 1160, in create_unitgraph_from_coo
    F.to_dgl_nd(row), F.to_dgl_nd(col),
  File "~/lib/python3.8/site-packages/dgl/backend/__init__.py", line 128, in to_dgl_nd
    return zerocopy_to_dgl_ndarray(data)
  File "~/lib/python3.8/site-packages/dgl/backend/pytorch/tensor.py", line 344, in zerocopy_to_dgl_ndarray
    return nd.from_dlpack(dlpack.to_dlpack(data.contiguous()))
AttributeError: type object 'numpy.ndarray' has no attribute 'from_dlpack'
</code>```

Yes, now the 'from_dlpack' attribute was not in the numpy packge.

I serached what is 'from_dlpack',and 'from_dlpack' is torch attribute (torch.from_dlpack).

And 'device' attribute is also torch attribute.

What is wrong with the dgl package?
Why the code try to find the 'device' and 'from_dlpack' attribute from numpy and how can I fix it?

Body:
everyone. I am beginner in coding and non-major in it.

I run the code by python on Window WSL(Ubuntu).

In running the code, dgl was run and it has error like 'AttributeError: 'numpy.ndarray' object has no attribute 'device''

More detail:

AttributeError: Caught AttributeError in DataLoader worker process 0.
Original Traceback (most recent call last):
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/worker.py", line 302, in _worker_loop
    data = fetcher.fetch(index)
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 49, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 49, in <listcomp>
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "~/interactive_se3/OpenFold2-toy_se3/src/Dataset.py", line 67, in __getitem__
    G.ndata['x'] = r.astype(np.float32)
  File "~/lib/python3.8/site-packages/dgl/view.py", line 90, in __setitem__
    self._graph._set_n_repr(self._ntid, self._nodes, {key: val})
  File "~/lib/python3.8/site-packages/dgl/heterograph.py", line 4121, in _set_n_repr
    if F.context(val) != self.device:
  File "~/lib/python3.8/site-packages/dgl/backend/pytorch/tensor.py", line 80, in context
    return input.device
AttributeError: 'numpy.ndarray' object has no attribute 'device'

I found the error line and I got the reason of error.
The module 'ndarray.py' in dgl package (\lib\python3.8\site-packages\dgl) actually doesn't have 'device' attribute as the error said.

After I found the reason of error, 'no attribute',

I changed the code like that:
from:

from ... import ndarray as nd

to:

from numpy import ndarray as nd

It work!

But I faced again the error like 'AttributeError: type object 'numpy.ndarray' has no attribute 'from_dlpack''

More detail:

AttributeError: Caught AttributeError in DataLoader worker process 0.
Original Traceback (most recent call last):
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/worker.py", line 302, in _worker_loop
    data = fetcher.fetch(index)
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 49, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "~/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 49, in <listcomp>
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "~/OpenFold2-toy_se3/src/Dataset.py", line 65, in __getitem__
    G = dgl.DGLGraph((src, dst))
  File "~/lib/python3.8/site-packages/dgl/heterograph.py", line 76, in __init__
    gidx = heterograph_index.create_unitgraph_from_coo(
  File "~/lib/python3.8/site-packages/dgl/heterograph_index.py", line 1160, in create_unitgraph_from_coo
    F.to_dgl_nd(row), F.to_dgl_nd(col),
  File "~/lib/python3.8/site-packages/dgl/backend/__init__.py", line 128, in to_dgl_nd
    return zerocopy_to_dgl_ndarray(data)
  File "~/lib/python3.8/site-packages/dgl/backend/pytorch/tensor.py", line 344, in zerocopy_to_dgl_ndarray
    return nd.from_dlpack(dlpack.to_dlpack(data.contiguous()))
AttributeError: type object 'numpy.ndarray' has no attribute 'from_dlpack'

Yes, now the 'from_dlpack' attribute was not in the numpy packge.

I serached what is 'from_dlpack',and 'from_dlpack' is torch attribute (torch.from_dlpack).

And 'device' attribute is also torch attribute.

What is wrong with the dgl package?
Why the code try to find the 'device' and 'from_dlpack' attribute from numpy and how can I fix it?


问:
Code Sniffer single line block problem (Generic.WhiteSpace.ScopeIndent)
I have such code (for example)

```<code><?php

while ( false )
    for ( $i = 1; $i < 10; $i++ )
    {
        $k = 1;
        $i = 1;
    }
$t = 3;
$s = 5;
</code>```

And check it by PHP CodeSniffer

It produces errors:

4 | ERROR | [x] Line indented incorrectly; expected 0 spaces, found 4

8 | ERROR | [x] Line indented incorrectly; expected 0 spaces, found 4

Error

Sounds like a bug in Generic.WhiteSpace.ScopeIndent

Сorrect processing should not give an error to this code

Body:
I have such code (for example)

<?php

while ( false )
    for ( $i = 1; $i < 10; $i++ )
    {
        $k = 1;
        $i = 1;
    }
$t = 3;
$s = 5;

And check it by PHP CodeSniffer

It produces errors:

4 | ERROR | [x] Line indented incorrectly; expected 0 spaces, found 4

8 | ERROR | [x] Line indented incorrectly; expected 0 spaces, found 4

Error

Sounds like a bug in Generic.WhiteSpace.ScopeIndent

Сorrect processing should not give an error to this code


问:
I use HopcroftKarp algorithm for find the partition
I used HopcroftKarp's algorithm but I can't figure out how to partition my devices based on the maximum matching found from the algorithm output. Out HopcroftKarp:
{'Device 5': 60, 'Device 3': 61, 'Device 1': 63, 'Device 4': 65, 'Device 2': 75}

and i need to partition my device in:
['Device 1', 'Device 3', 'Device 5'], ['Device 2'], ['Device 4']
succeeding in satisfying the dominance relationship


问:
Select tab Bootstrap 4 after reload page
I'm trying to keep tabs showing after I save data and reload the page. However, an error appears :"$(...).tab is not a function".

i have tried to do this below, and what I want to get is, when I save the data it will be redirected to "http...../setting?set_name=general". And when set_name = mail I want to show tab $('#v-pills-profile'):

```<code><div class="col-md-3 col-lg-3 col-xs-12 col-sm-12">
    <div class="nav menu" id="tabs" role="tablist" aria-orientation="vertical">
        <a class="nav-link active" id="v-pills-home-tab" data-bs-toggle="pill" href="#v-pills-home"
           role="tab" aria-controls="v-pills-home" aria-selected="true"><span><i class="fa fa-cog"></i></span>General</a>
        <a class="nav-link" id="v-pills-profile-tab" data-bs-toggle="pill" href="#v-pills-profile"
           role="tab" aria-controls="v-pills-profile" aria-selected="true"><span><i
                    class="fa fa-user"></i></span>Account</a>
        <a class="nav-link" id="v-pills-messages-tab" data-bs-toggle="pill" href="#v-pills-messages"
           role="tab" aria-controls="v-pills-messages" aria-selected="true"><span><i class="fa fa-envelope"></i></span>Mail</a>
    </div>
</div>

<!-- end col -->
<!-- Right Sidebar -->
<div class="col-md-9 col-lg-9 col-xs-12 col-sm-12">

    <div class="card">
        <div class="card-body">
            <div class="tab-content text-muted mt-4 mt-md-0" id="v-pills-tabContent">
                <div class="tab-pane fade show active" id="v-pills-home" role="tabpanel"
                     aria-labelledby="v-pills-home-tab">

                </div>
                <div class="tab-pane fade" id="v-pills-profile" role="tabpanel"
                     aria-labelledby="v-pills-profile-tab">

                </div>
                <div class="tab-pane fade" id="v-pills-messages" role="tabpanel"
                     aria-labelledby="v-pills-messages-tab">
                    <div class="row mb-3">
                        <label for="example-text-input" class="col-sm-2 col-form-label">Email </label>
                        <div class="col-sm-10">
                            <input class="form-control" type="mail" placeholder="Artisanal kale"
                                   id="example-text-input">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <label for="example-text-input" class="col-sm-2 col-form-label">Email</label>
                        <div class="col-sm-10">
                            <input class="form-control" type="text" placeholder="Artisanal kale"
                                   id="example-text-input">
                        </div>
                    </div>
                </div>

            </div>
        </div>

    </div>
    <!-- card -->

</div>
</code>```
```<code>@push('scripts')
    <script>

        let tabSelected = $('a[data-bs-toggle="pill"]');
        tabSelected.on('shown.bs.tab', function (e) {
            e.preventDefault();
            localStorage.setItem('lastTab', $(this).attr('href'));
            tabSelected.removeClass('active');
            $(this).addClass('active');
        });

        @if($setName != null)
            let nameTab = '{{$setName}}';

            if(nameTab == "mail"){
                console.log(nameTab);
                $('#v-pills-profile').tab('show');
            }
        @endif
    </script>
@endpush
</code>```

Body:
I'm trying to keep tabs showing after I save data and reload the page. However, an error appears :"$(...).tab is not a function".

i have tried to do this below, and what I want to get is, when I save the data it will be redirected to "http...../setting?set_name=general". And when set_name = mail I want to show tab $('#v-pills-profile'):

        General
        Account
        Mail

                        Email

                            <input class="form-control" type="mail" placeholder="Artisanal kale"
                                   id="example-text-input">

                        Email

                            <input class="form-control" type="text" placeholder="Artisanal kale"
                                   id="example-text-input">

@push('scripts')

@endpush


问:
Python/Pandas- json_normalize throwing "KeyError"
I have multilevel JSON that I'm trying to normalize and write to csv.

```<code>{"related":
    {"chart":
        {"name": "All stations",
         "type": "song",
         "slug": "airplay-daily-ar",
         "platform": "airplay",
         "countryCode": "AR",
         "countryName": "Argentina",
         "cityName": "",
         "maxResultsCount": 400,
         "metric": {
             "type": "playcount",
             "description": "Number of radio spins"
         }
    },
    "date": "2022-12-08T12:00:00+00:00"

    },
    "items": [
        {"song": {
            "uuid": "e685f5ec-001b-4af6-8e45-27d5e418b006",
            "name": "Underground",
            "creditName": "Emilia"},
        "position": 1,
        "positionEvolution": 2,
        "metric": 19,
        "entryState": "",
        "entryDate": "2022-11-18T12:00:00+00:00",
        "rankDate": "2022-12-08T12:00:00+00:00",
        "oldPosition": 3,
        "timeOnChart": 21,
        "timeOnChartUnit": "DOC"},
        ...
</code>```

(This comes from a service called Soundcharts, in case you're curious.)

I'm interested in getting to the items section, which contains information about songs and their rankings.

When I run the following code block, I get a json and csv file generated:

```<code>import pandas as pd
import requests
import json

song_chart_date_dict = song_chart_date_list.json()
with open("song_chart_2022_12_08_ar.json", "w") as outfile:
  json.dump(song_chart_date_dict, outfile)
song_data = pd.json_normalize(song_chart_date_dict["items"])
song_data_csv_file = "song_chart_2022_12_08_ar.csv"
song_data.to_csv(song_data_csv_file)
</code>```

However, when I put the same code into a function to generate a set of files, I get a KeyError:

```<code>def music_charts():

  date_list = [<list of dates>]

  slug_list = [<list of chart slugs>]

  #setting request URL to include chart slugs and dates
  chart_slug = ""
  chart_date = ""
  chart_date_slug_url = '/api/v2.14/chart/song/' + chart_slug + '/ranking/' + chart_date + 'T12:00:00+00:00'
  song_chart_date_list = requests.get(URL + chart_date_slug_url + '?offset=0&limit=100',
                            headers = {"x-app-id": ID, "x-api-key": TOKEN})
  for slug in slug_list:
    for date in date_list:
      chart_slug = slug
      chart_date = date
      song_chart_date_list = requests.get(URL + chart_date_slug_url + '?offset=0&limit=100',
                            headers = {"x-app-id": ID, "x-api-key": TOKEN})
      song_chart_date_dict = song_chart_date_list.json()
      with open("song_chart_" + slug + "_" + date +".json", "w") as outfile:
        json.dump(song_chart_date_dict, outfile)
      song_data = pd.json_normalize(song_chart_date_dict["items"])
      song_data_csv_file = "song_chart_" + slug + date + ".csv"
      song_data.to_csv(song_data_csv_file, index=False)

music_charts()
</code>```

The error:

```<code>KeyError                                  Traceback (most recent call last)
<ipython-input-30-7341d243638f> in <module>
     31
     32
---> 33 sweet_sixteen_charts()

<ipython-input-30-7341d243638f> in sweet_sixteen_charts()
     25       with open("song_chart_" + slug + date +".json", "w") as outfile:
     26         json.dump(song_chart_date_dict, outfile)
---> 27       song_data = pd.json_normalize(song_chart_date_dict["items"])
     28       song_data_csv_file = "song_chart_" + slug + date + ".csv"
     29       song_data.to_csv(song_data_csv_file, index=False)

KeyError: 'items'
</code>```

I appreciate any help.

Body:
I have multilevel JSON that I'm trying to normalize and write to csv.

{"related":
    {"chart":
        {"name": "All stations",
         "type": "song",
         "slug": "airplay-daily-ar",
         "platform": "airplay",
         "countryCode": "AR",
         "countryName": "Argentina",
         "cityName": "",
         "maxResultsCount": 400,
         "metric": {
             "type": "playcount",
             "description": "Number of radio spins"
         }
    },
    "date": "2022-12-08T12:00:00+00:00"

    },
    "items": [
        {"song": {
            "uuid": "e685f5ec-001b-4af6-8e45-27d5e418b006",
            "name": "Underground",
            "creditName": "Emilia"},
        "position": 1,
        "positionEvolution": 2,
        "metric": 19,
        "entryState": "",
        "entryDate": "2022-11-18T12:00:00+00:00",
        "rankDate": "2022-12-08T12:00:00+00:00",
        "oldPosition": 3,
        "timeOnChart": 21,
        "timeOnChartUnit": "DOC"},
        ...

(This comes from a service called Soundcharts, in case you're curious.)

I'm interested in getting to the items section, which contains information about songs and their rankings.

When I run the following code block, I get a json and csv file generated:

import pandas as pd
import requests
import json

song_chart_date_dict = song_chart_date_list.json()
with open("song_chart_2022_12_08_ar.json", "w") as outfile:
  json.dump(song_chart_date_dict, outfile)
song_data = pd.json_normalize(song_chart_date_dict["items"])
song_data_csv_file = "song_chart_2022_12_08_ar.csv"
song_data.to_csv(song_data_csv_file)

However, when I put the same code into a function to generate a set of files, I get a KeyError:

def music_charts():

  date_list = [<list of dates>]

  slug_list = [<list of chart slugs>]

  #setting request URL to include chart slugs and dates
  chart_slug = ""
  chart_date = ""
  chart_date_slug_url = '/api/v2.14/chart/song/' + chart_slug + '/ranking/' + chart_date + 'T12:00:00+00:00'
  song_chart_date_list = requests.get(URL + chart_date_slug_url + '?offset=0&limit=100',
                            headers = {"x-app-id": ID, "x-api-key": TOKEN})
  for slug in slug_list:
    for date in date_list:
      chart_slug = slug
      chart_date = date
      song_chart_date_list = requests.get(URL + chart_date_slug_url + '?offset=0&limit=100',
                            headers = {"x-app-id": ID, "x-api-key": TOKEN})
      song_chart_date_dict = song_chart_date_list.json()
      with open("song_chart_" + slug + "_" + date +".json", "w") as outfile:
        json.dump(song_chart_date_dict, outfile)
      song_data = pd.json_normalize(song_chart_date_dict["items"])
      song_data_csv_file = "song_chart_" + slug + date + ".csv"
      song_data.to_csv(song_data_csv_file, index=False)

music_charts()

The error:

KeyError                                  Traceback (most recent call last)
<ipython-input-30-7341d243638f> in <module>
     31
     32
---> 33 sweet_sixteen_charts()

<ipython-input-30-7341d243638f> in sweet_sixteen_charts()
     25       with open("song_chart_" + slug + date +".json", "w") as outfile:
     26         json.dump(song_chart_date_dict, outfile)
---> 27       song_data = pd.json_normalize(song_chart_date_dict["items"])
     28       song_data_csv_file = "song_chart_" + slug + date + ".csv"
     29       song_data.to_csv(song_data_csv_file, index=False)

KeyError: 'items'

I appreciate any help.


问:
Crontab append a command to certain user using shell
I am trying to set up a cron job using a shell script but I am unable to find a solution to it I am trying to use crontab like this:

```<code>#cron.sh
echo "*/1**** /opt/file/test.sh" | crontab -
</code>```

I can run cron.sh as a sudo user So my question is how to add this cron job to a specific user I am using this command:

```<code>su -s /bin/bash -c  "echo "*/1**** /opt/file/test.sh" | crontab -" -g user user
</code>```

but it doesn't work how to make the above code work.

Body:
I am trying to set up a cron job using a shell script but I am unable to find a solution to it I am trying to use crontab like this:

#cron.sh
echo "*/1**** /opt/file/test.sh" | crontab -

I can run cron.sh as a sudo user So my question is how to add this cron job to a specific user I am using this command:

su -s /bin/bash -c  "echo "*/1**** /opt/file/test.sh" | crontab -" -g user user

but it doesn't work how to make the above code work.


问:
worker threads cant use packaged modules in ElectronJS production
With modules comes with when installing nodejs such as fs, path, worker threads have no problem importing in.

While external packages such as jimp it fails with Cannot find module jimp.


问:
How to trigger Python script when sending an Outlook email?
How to trigger Python script when sending an Outlook email?
Alt+F11 from Outlook opens the VBA window, then in the white space under Project1, right click and Insert a Module. Open the module and start scripting. To run your python code.I tried didnt work</p>


问:
CI/CD Analysis Services stuck throug DevOps
Hi I am trying to implement CI/CD process for cube deployment using Devops. I have configured everything and after creating release it gets stuck in this screen like forever.
enter image description here

Any ideas why it is happening? when i deploy the same model using VS it got deployed in seconds.
enter image description here


Title: DecisionTreeClassifier with torch tensor

Body:
I want to use a Decision Tree with data from audio. I get this Torch.Tensor for X_train :

[tensor([[ 0,  0,  0,  0,  0,  0,  0,  0, 11,  0,  0, 28,  0,  0, 11,  0,  0, 20,
       0,  4,  0,  0,  0,  0,  0,  0, 15,  0,  0,  0,  0,  4,  4,  0, 21,  0,
       9,  0,  9,  0,  0,  0,  7,  0,  0, 25, 15, 15, 21,  0, 20,  7, 18,  0,
       0, 18, 31,  4,  4, 13,  0, 11,  0, 26,  0,  4,  4, 26, 14,  0, 11,  4,
       0, 19,  0, 21,  0, 20,  0,  0, 10,  0,  7,  0,  0, 31,  0,  4,  4,  0,
       8,  0, 18, 27, 27, 11,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 25,  0,
       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  4]]),
tensor([[ 0,  0,  0,  0,  0,  0,  0, 10, 21,  0, 20, 20,  5, 26, 26,  0,  4,  4,
       0,  0,  7,  0,  0, 25,  0, 17,  4,  4, 19, 19, 11,  4,  4, 26, 21, 21,
       4,  0,  9,  0,  0,  7,  0, 24,  0,  0, 24,  0, 31,  4,  4,  7, 20,  0,
       4,  4,  0,  0,  0,  0,  7,  0, 27,  0,  0,  0, 18,  0,  0, 31,  0,  0,
       4,  4,  0, 24, 24,  0,  0,  7,  0,  0,  0,  0, 13,  0,  0,  0,  4, 18,
      18, 15, 15,  0,  0, 17,  0, 11,  4,  4,  0, 26, 14, 14,  0,  0,  7,  0,
       0,  0,  0,  0,  0, 26,  0,  0,  0,  0,  0,  0,  0,  0,  4]]),
tensor([[ 0,  0,  0,  0,  0,  0,  0,  0, 25, 25, 14, 21,  0, 27, 18, 10,  4,  4,
      16,  0,  0, 15,  0,  0,  0, 24,  0,  0,  7,  0,  0,  0, 12,  0,  0,  0,
       4,  8,  0,  0, 11,  0,  4,  0, 17,  0,  0, 11,  0,  0, 22,  0,  0, 26,
       0,  4,  0, 15, 20,  0,  4,  4,  4,  0, 25,  0,  0,  0, 19,  0,  0,  0,
       0,  7, 18,  0,  0, 18,  0,  4,  0, 32, 21, 21,  0, 21,  0,  0,  0,  0,
       0,  0,  0, 25, 11,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  4]]), .......

And this series for y_train:

12    M
16    M
10    M
9     F

When I apply the decision tree I have problems with X_train:

from sklearn.tree import DecisionTreeClassifier

for i in range(0,3):
    Xtrain = X_train[i][0]
    Ytrain = y_train[i]
    clf = DecisionTreeClassifier()
    clf.fit(Xtrain, Ytrain)

ValueError: Expected 2D array, got 1D array instead:
array=[ 0.  0.  0.  0.  0.  0.  0.  0. 11.  0.  0. 28.  0.  0. 11.  0.  0. 20.
  0.  4.  0.  0.  0.  0.  0.  0. 15.  0.  0.  0.  0.  4.  4.  0. 21.  0.
  9.  0.  9.  0.  0.  0.  7.  0.  0. 25. 15. 15. 21.  0. 20.  7. 18.  0.
  0. 18. 31.  4.  4. 13.  0. 11.  0. 26.  0.  4.  4. 26. 14.  0. 11.  4.
  0. 19.  0. 21.  0. 20.  0.  0. 10.  0.  7.  0.  0. 31.  0.  4.  4.  0.
  8.  0. 18. 27. 27. 11.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0. 25.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  4.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.


问:
How to monkey patch hijack method in GO language for unit test?
we have one handler function in which we're hijacking an incoming connection

```<code>func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("ACK:"))
        hijacker, ok := w.(http.Hijacker)
        if !ok {
            http.Error(w, "hijacking not supported", http.StatusInternalServerError)
            return
        }
        clientConn, _, err := hijacker.Hijack()

        //[TODO] how to trigger this error?
        if err != nil {
            http.Error(w, err.Error(), http.StatusServiceUnavailable)
            return
        }
        // do other stuff
    }
</code>```

We need to write tests and the expectation is 100% code coverage. How do I trigger this error part when using .Hijack method?

I've tried

```<code>        oldHf := http.Hijacker.Hijack
        http.Hijacker.Hijack = func(net.Conn, *bufio.ReadWriter, error) (net.Conn, *bufio.ReadWriter, error) {
            return &net.TCPConn{}, &bufio.ReadWriter{}, errors.New("dummy error")
        }
        defer func() { http.Hijacker.Hijack = oldHf }()

</code>```

But got this error

```<code>defer func() { http.Hijacker.Hijack = oldHf }()
http.Hijacker (type) is not an expressioncompilerNotAnExpr
cannot assign to http.Hijacker.Hijack (value of type func(http.Hijacker) (net.Conn, *bufio.ReadWriter, error))compilerUnassignableOperand
</code>```

Body:
we have one handler function in which we're hijacking an incoming connection

func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("ACK:"))
        hijacker, ok := w.(http.Hijacker)
        if !ok {
            http.Error(w, "hijacking not supported", http.StatusInternalServerError)
            return
        }
        clientConn, _, err := hijacker.Hijack()

        //[TODO] how to trigger this error?
        if err != nil {
            http.Error(w, err.Error(), http.StatusServiceUnavailable)
            return
        }
        // do other stuff
    }

We need to write tests and the expectation is 100% code coverage. How do I trigger this error part when using .Hijack method?

I've tried

        oldHf := http.Hijacker.Hijack
        http.Hijacker.Hijack = func(net.Conn, *bufio.ReadWriter, error) (net.Conn, *bufio.ReadWriter, error) {
            return &net.TCPConn{}, &bufio.ReadWriter{}, errors.New("dummy error")
        }
        defer func() { http.Hijacker.Hijack = oldHf }()

But got this error

defer func() { http.Hijacker.Hijack = oldHf }()
http.Hijacker (type) is not an expressioncompilerNotAnExpr
cannot assign to http.Hijacker.Hijack (value of type func(http.Hijacker) (net.Conn, *bufio.ReadWriter, error))compilerUnassignableOperand


问:
TagCloud npm package not working in Next js Website after Deploying
I am using TagCloud npm package to create 3d word sphere in Next js. It is working fine on development server but not working after Deploying. Website is hosted but 3d word sphere is not showing  up.[here is working TagCloudThis is not working](https://i.stack.imgur.com/kpiMQ.png)

and also it not showing any error in terminal or console

I tried everything but its not working.
I want TagCloud to also word on production environment


问:
Functions in ASP.NET Core shared between views
Is there a way to share functions with html code between .cshtml views in ASP.NET Core? I need it to work similar to helpers, so it can be accessible from a few views. I know that some functions can be shared if moved to a .cs file, but I've never seen cs functions with complex html code. Function example (in project they are much more complex and multiline):

```<code>@{
    async Task Test(string test)
    {
        <div class="test">String @test</div>
    }
}
</code>```

Now I'm using a partial views with functions declared inside, but I do not like how it works.

Body:
Is there a way to share functions with html code between .cshtml views in ASP.NET Core? I need it to work similar to helpers, so it can be accessible from a few views. I know that some functions can be shared if moved to a .cs file, but I've never seen cs functions with complex html code. Function example (in project they are much more complex and multiline):

@{
    async Task Test(string test)
    {

String @test

    }
}

Now I'm using a partial views with functions declared inside, but I do not like how it works.


问:
UWP Application UI fails to function in Release mode but fine in Debug mode
I am a bit stuck now with a UWP app that works fine in DEBUG mode but when compiled for Release mode the UI fails to function.  Buttons are always disabled and the bindings are not functional so basically nothing works.

How is this even possible - I have no idea where to begin looking.


问:
Configure target framework for an exe
Is it possible to configure the .NET target framework in a .exe.config?

Scenario: I want to migrate a .NET 3.5 exe to .NET 4.8 without recompiling it. I can just configure the supportedRuntime and the app will run in the .NET 4.8 runtime, but, until I recompile it targeting .NET 4.8, a lot of AppContextSwitchOverrides will kick in. I want to disable all the AppContextSwitchOverrides without setting them all in the config. It can be done by setting the AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName to .NETFramework,Version=v4.8. In a web it can be set using <httpRuntime targetFramework="4.8"> but this is an exe.

Title: Configure target framework for an exe


问:
Java IMAP connection error javax.mail.AuthenticationFailedException: AUTHENTICATE failed
I am using below java program and configurations to read Inbox in outlook email, but could not succeed.

```<code>import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;

import com.nexera.blustream.batch.constants.CommonConstants;
import com.nexera.blustream.batch.entity.SubscriberDetails;

public class EmailScanner {

    private String protocol;
    private String imapHost;
    private String username;
    private String password;
    private String folderName;
    private String excelFilePath;

    Properties prop;
    InputStream inputStream = null;

    private static final Logger LOG = Logger.getLogger(EmailScanner.class);

    public EmailScanner() {
        try {
            prop = new Properties();
            String propFileName = "config.properties";
            prop.load(EmailScanner.class.getClassLoader()
                    .getResourceAsStream(propFileName));
            this.setProtocol(prop.getProperty("PROTOCOL"));
            this.setImapHost(prop.getProperty("IMAP_HOST"));
            this.setUsername(prop.getProperty("USERNAME"));
            this.setPassword(prop.getProperty("PASSWORD"));
            this.setFolderName(prop.getProperty("FOLDER_NAME"));
            this.setExcelFilePath(prop.getProperty("EXCEL_PATH"));
        } catch (Exception e) {
            LOG.error("Exception: " + e);
        }
    }

    /**
     * configureEmail() - used to connect to mailbox using properties mentioned
     * in config.properties.
     * passes the control to fetchUnReadMails.
     */
    public void configureEmail() {
        LOG.info("Entering method : configureEmail");
        // Download Attachment First
        Properties properties = new Properties();
        properties.setProperty("mail.store.protocol", this.getProtocol());
        properties.setProperty("mail.imap.partialfetch", "false");
        properties.put("mail.mime.base64.ignoreerrors", "true");
        properties.put("mail.imap.tls.enable", "true");
        properties.put("mail.imap.auth.plain.disable", "true");
        Folder inbox = null;
        Store store = null;
        Session session = null;
        try {
            LOG.info("Creating session for email with properties "
                    + properties.getProperty("mail.store.protocol"));

            session = Session.getDefaultInstance(properties, null);
            store = session.getStore(this.getProtocol());
            LOG.info("Checking if store is connected " + store.isConnected());
            if (!store.isConnected()) {
                LOG.info("Store not connected, connecting");
                try {
                    store.connect(imapHost,993, username, password);
                } catch (Exception ex) {
                    LOG.error("Exception caught while connecting : "
                            + ex.getMessage());
                }

            } else {
                LOG.info("Store already connected, reading emails");
            }

            LOG.info("Reading emails");
            inbox = store.getFolder(folderName);
            inbox.open(Folder.READ_WRITE);
            LOG.info("Opening Inbox in readWrite");
            fetchUnReadMails(inbox);

        } catch (MessagingException e) {
            LOG.error("Exception Thrown while reading mails :  " + e);
        } catch (Exception ex) {
            LOG.error("Exception Thrown  while reading mails : " + ex);
        } finally {

            if (inbox != null) {
                if (inbox.isOpen())
                    try {
                        inbox.close(true);
                    } catch (MessagingException e) {
                        LOG.error("Exception Thrown " + e.getMessage());
                    }
            }
            if (store != null) {
                if (store.isConnected())
                    try {
                        store.close();
                    } catch (MessagingException e) {
                        LOG.error(
                                "Unable to close the store " + e.getMessage());
                    }
            }
        }
        LOG.info("Exiting method : configureEmail");
    }

  public static void main(String[] args) {
        LOG.info("Starting Execution");
        EmailScanner emailBatchJob = new EmailScanner();
        emailBatchJob.configureEmail();
        LOG.info("Finished Execution");
    }
}
</code>```

program is failing to connect to the server, exception is thrown at the below line

```<code>    store.connect(imapHost,993, username, password);
</code>```
```<code># MAIL BOX DETAILS FOR READING
PROTOCOL=imap
IMAP_HOST=outlook.office365.com
USERNAME=subscriptions@test.com
PASSWORD=<password>
FOLDER_NAME=Inbox`
</code>```

#Exception Thrown

```<code>    javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:708)
    at javax.mail.Service.connect(Service.java:342)
    at javax.mail.Service.connect(Service.java:222)
    at javax.mail.Service.connect(Service.java:243)
    at com.email.demo.RetrieveEmailsUsingIMAP.getEmails(RetrieveEmailsUsingIMAP.java:46)
    at com.email.demo.RetrieveEmailsUsingIMAP.main(RetrieveEmailsUsingIMAP.java:241)

</code>```

Your help is much appreciated!!!

Thanks

I have tried to change the protocol to imaps but didn't work.

Also, facing below error when I tried to do some other changes to the configurations

```<code>javax.mail.MessagingException: Connection dropped by server?;
</code>```

Body:
I am using below java program and configurations to read Inbox in outlook email, but could not succeed.

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;

import com.nexera.blustream.batch.constants.CommonConstants;
import com.nexera.blustream.batch.entity.SubscriberDetails;

public class EmailScanner {

    private String protocol;
    private String imapHost;
    private String username;
    private String password;
    private String folderName;
    private String excelFilePath;

    Properties prop;
    InputStream inputStream = null;

    private static final Logger LOG = Logger.getLogger(EmailScanner.class);

    public EmailScanner() {
        try {
            prop = new Properties();
            String propFileName = "config.properties";
            prop.load(EmailScanner.class.getClassLoader()
                    .getResourceAsStream(propFileName));
            this.setProtocol(prop.getProperty("PROTOCOL"));
            this.setImapHost(prop.getProperty("IMAP_HOST"));
            this.setUsername(prop.getProperty("USERNAME"));
            this.setPassword(prop.getProperty("PASSWORD"));
            this.setFolderName(prop.getProperty("FOLDER_NAME"));
            this.setExcelFilePath(prop.getProperty("EXCEL_PATH"));
        } catch (Exception e) {
            LOG.error("Exception: " + e);
        }
    }

    /**
     * configureEmail() - used to connect to mailbox using properties mentioned
     * in config.properties.
     * passes the control to fetchUnReadMails.
     */
    public void configureEmail() {
        LOG.info("Entering method : configureEmail");
        // Download Attachment First
        Properties properties = new Properties();
        properties.setProperty("mail.store.protocol", this.getProtocol());
        properties.setProperty("mail.imap.partialfetch", "false");
        properties.put("mail.mime.base64.ignoreerrors", "true");
        properties.put("mail.imap.tls.enable", "true");
        properties.put("mail.imap.auth.plain.disable", "true");
        Folder inbox = null;
        Store store = null;
        Session session = null;
        try {
            LOG.info("Creating session for email with properties "
                    + properties.getProperty("mail.store.protocol"));

            session = Session.getDefaultInstance(properties, null);
            store = session.getStore(this.getProtocol());
            LOG.info("Checking if store is connected " + store.isConnected());
            if (!store.isConnected()) {
                LOG.info("Store not connected, connecting");
                try {
                    store.connect(imapHost,993, username, password);
                } catch (Exception ex) {
                    LOG.error("Exception caught while connecting : "
                            + ex.getMessage());
                }

            } else {
                LOG.info("Store already connected, reading emails");
            }

            LOG.info("Reading emails");
            inbox = store.getFolder(folderName);
            inbox.open(Folder.READ_WRITE);
            LOG.info("Opening Inbox in readWrite");
            fetchUnReadMails(inbox);

        } catch (MessagingException e) {
            LOG.error("Exception Thrown while reading mails :  " + e);
        } catch (Exception ex) {
            LOG.error("Exception Thrown  while reading mails : " + ex);
        } finally {

            if (inbox != null) {
                if (inbox.isOpen())
                    try {
                        inbox.close(true);
                    } catch (MessagingException e) {
                        LOG.error("Exception Thrown " + e.getMessage());
                    }
            }
            if (store != null) {
                if (store.isConnected())
                    try {
                        store.close();
                    } catch (MessagingException e) {
                        LOG.error(
                                "Unable to close the store " + e.getMessage());
                    }
            }
        }
        LOG.info("Exiting method : configureEmail");
    }

  public static void main(String[] args) {
        LOG.info("Starting Execution");
        EmailScanner emailBatchJob = new EmailScanner();
        emailBatchJob.configureEmail();
        LOG.info("Finished Execution");
    }
}

program is failing to connect to the server, exception is thrown at the below line

    store.connect(imapHost,993, username, password);

# MAIL BOX DETAILS FOR READING
PROTOCOL=imap
IMAP_HOST=outlook.office365.com
USERNAME=subscriptions@test.com
PASSWORD=<password>
FOLDER_NAME=Inbox`

#Exception Thrown

    javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:708)
    at javax.mail.Service.connect(Service.java:342)
    at javax.mail.Service.connect(Service.java:222)
    at javax.mail.Service.connect(Service.java:243)
    at com.email.demo.RetrieveEmailsUsingIMAP.getEmails(RetrieveEmailsUsingIMAP.java:46)
    at com.email.demo.RetrieveEmailsUsingIMAP.main(RetrieveEmailsUsingIMAP.java:241)

Your help is much appreciated!!!

Thanks

I have tried to change the protocol to imaps but didn't work.

Also, facing below error when I tried to do some other changes to the configurations

javax.mail.MessagingException: Connection dropped by server?;


问:
tying to add boolean values as timeseries gives error Time series is configured as numeric but used as a string or the other way around
I have IOT data that is coming from devices into foundry. I created the timeseries dataset and metadata as explained in the documentation https://www.palantir.com/docs/foundry/time-series/time-series-setup/#time-series-dataset
I have two datasets, one with double values that show up fine, but the dataset with value as string doesnt work.
As per the domumentation it says the Dataset itself should have cloumn type String for enum series .
Then it says that the metadataa should have is_enum which should be of type boolean

is_enum: This is an optional field for time series values that are expected in string format (ie Open/Close). Must be of type Boolean and is required to be true for series that are Enum types (otherwise is optional). This value should be consistent for a measure.

So in my metadata, for the series Id that have boolean value, I have is_enum set to true and datatype is boolean.  Im able to create the time series sync. But I get the error that the time series is configured as numeric.


问:
Android studio throwing error Invalid packageName while trying to run the app
I am having one android project with diffrent build flavours like "Debug,release,SIT,UAT,...".Based on the build variant the package name is changing(Dynamic).Like if i select SIT the package name would be com.abc.xyz.SIT and if i will select UAT it will be like com.abc.xyz.UAT.(Suffix).

This is working very fine previously,Suddenly it stopped working with an error as below

2022-12-30 15:46:32.988   562-4108  ActivityManager         system_process                       W  Invalid packageName: com.mbb.mketrade.sit 2022-12-30 16:24:03.265   562-932   ActivityManager         system_process                       W  Invalid packageName: com.mbb.mketrade.sit

Surprisingly...I am able to generate the signed bundle and apk from the same source code from the android studio and can run the exported apk/bundle to the emulator but when i am trying to run it manually by hitting "Run" option it always give me error "INVALID PACKAGE NAME".

I have tried couple of steps as google suggested as below without luck.
1)Checked my manifest and build.gradle file where i have. not changed anything.
2)Tried creating a new emulator
3)tried invalidating caches and restarted the emulator.

I am still looking for any solution.Can anyone please help me on this.

I have attached my run configurations.
Run Configuration

Thank you everyone.


问:
Having 2 synchronous videos in reveal.js
I am trying to have 2 videos plays synchronously together in Reveal.js.
The goal is to have 2 (or multiple videos) in the same slide.

I want one video to be in the foreground and one in the background (hidden by the first video).
Both videos start as the slide is shown, but when I go to the next slide I want the video in the foreground to get invisible and the second video to show.

This could also work in another way. It does not have to be 2 videos on the same slide.
Another way I imagine this could work is when I have the first slide I want the same video time be put on the second video. So if the first slide is shown for 20 seconds, skip the first 20 second on the video in the next slide.

I have been using data-background-video before, but I fear that this will not work for what I am trying to achieve here.


问:
How do I handle SPARQL duplicate specific values?
```<code>SELECT ?s ?data ?pro ?o
WHERE {
?s rdf:type rdfs:Class .
?data rdf:type ?s .
pro rdf:type rdf:Property .
?data ?pro ?o .}
</code>```

This SPARQL result is as follows:

```<code>?s    ?data    ?pro    ?o
A1    B1       A1.a     0
A1    B1       A1.b     0
A1    B1       A1.c     1
A1    B1       A1.d     1
A2    B2       A2.a     0
A2    B2       A2.b     0
.
.
.
</code>```

The result I want is

```<code>A1    B1       A1.a     0
               A1.b     0
               A1.c     1
               A1.d     1
A2    B2       A2.a     0
               A2.b     0
.
.
.
</code>```

Is this possible?
I understand that DISTINCT is not the solution I want.
Thank you. Happy New Year

Body:
SELECT ?s ?data ?pro ?o
WHERE {
?s rdf:type rdfs:Class .
?data rdf:type ?s .
pro rdf:type rdf:Property .
?data ?pro ?o .}

This SPARQL result is as follows:

?s    ?data    ?pro    ?o
A1    B1       A1.a     0
A1    B1       A1.b     0
A1    B1       A1.c     1
A1    B1       A1.d     1
A2    B2       A2.a     0
A2    B2       A2.b     0
.
.
.

The result I want is

A1    B1       A1.a     0
               A1.b     0
               A1.c     1
               A1.d     1
A2    B2       A2.a     0
               A2.b     0
.
.
.

Is this possible?
I understand that DISTINCT is not the solution I want.
Thank you. Happy New Year


问:
Yodlee UI closing issue
I'm using the yodlee for some developing purposes for my ongoing project with nuxtjs 2.I cannot close the rendered Yodlee UI by clicking the close button in top of the yodlee page. However, the back button is working as expected after selecting a bank.

The initial page

After selecting a bank and its working(the go back which is in the top of the left side)

Even no console errors and I just tried with the class of the a tag related to the button below

mounted() {
  let fastLinkCloseBtn = document.getElementsByClassName(
    'icon-link close-icon'
  )
  if (fastLinkCloseBtn) {
    console.log('working')
    fastLinkCloseBtn.onClick = window.fastlink.close()
  } else {
    console.log('not working')
  }
},```

Title: Yodlee UI closing issue


问:
How does this Javascript .map() function works?
I found a function for the running sum of an array in javascript.

```<code>const runningSum = function(nums) {
  return nums.map((acc = 0, num => acc += num));
};
</code>```

For my understanding and according to the definition from MDN is acc := currentValue and num:= Index. But how does that work with the arrow function inside the parameters?
I appreciate any help or explantions

Body:
I found a function for the running sum of an array in javascript.

const runningSum = function(nums) {
  return nums.map((acc = 0, num => acc += num));
};

For my understanding and according to the definition from MDN is acc := currentValue and num:= Index. But how does that work with the arrow function inside the parameters?
I appreciate any help or explantions


问:
Using VLD, Dynamic load DLL failed
We have a windows Application, some DLLs are dynamic loaded using LoadLibraryW(). These Dlls are put in different Directory。 When we turn on VLD memory leak check, these DLLs failed to load. It seems like not search folders normally when load library. When we turn off VLD, the Application can be Started normally. Is anyone know the reasons? Thanks.

We try to load Dll in the same folder of main application, it can be loaded successfully. But Dlls in children folders can not be loaded。

Title: Using VLD, Dynamic load DLL failed


问:
App crashes when receiving a VoIP call before unlocking after reboot
My app is using Linphone and PushKit to handle VoIP calls. It works well when the app is in the foreground, background, or suspended (killing app).

If we restart the phone and the app receives a VoIP call before the phone is unlocked (i.e. PIN is entered for the first time) then the app crashes - this is shown to the user when they unlock the phone.  The crash only occurs in iOS 16 (and not with iOS 14).

Reboot -> make a VoIP call to the phone -> unlock -> crash. (iOS 16)

We've tested with other VoIP apps (e.g. Skype, Messenger); they do not crash but they do not notify the user that a call is received. There is just a notice that a call was missed when the phone is unlocked. We would like the same behaviour (i.e. do not crash, show a missed call).

What do we need to do to properly handle this use case?

Crash report:


问:
Ideal memory profile usage graph and possible improvements
I've built a .NET 6 Web API, while I was monitoring and profiling memory usage using Jetbrains Rider tooling I've got the following graph and results:

During the profiling session the application was handling ~ 200 requests per second with ~ 100 concurrent users. Here are some more memory consumption details before the CG call:

There are many short-lived objects (heap generation 0) as time goes by, what would be an approach to reduce them?

What would be the ideal graph of the memory usage I should aim for?


问:
Datatable binary installation not working in PyCharm
I am on Apple Silicon and I was not able to install datatable. So I cloned and build a wheel from their gitrepo(as mentioned in their docs).

pip3 install git+https://github.com/h2oai/datatable

The libraries show that I have datatable installed but when I try to run a script it fails with message:
ModuleNotFoundError: No module named 'datatable'

enter image description here

enter image description here

I have tried uninstalling and installing it again but this is not helping.

Thanks in advance!

I was trying to run a script that uses datatable for aggregation operations.


问:
Spring batch : Inputstream is getting closed in spring batch reader if writer takes more than 5 minutes in processing
Whats need to be achieve: Read a csv from sftp location and write again to different path and also save to db with Spring batch in springboot app.

Issue : 1. Reader is getting executed only once and writer as per the chunk size like print statement in reader gets printed only one time while in writer per chunk execution. It seems to be the default behaviour of FlatfileItemReader.

I am using SFTP channel to read the file from sftp location which is getting closed after read if writer processing time is huge.

So is there a way, I can always pass a new SFTP connection for eech chunk size or is there a way I can extend this readers input stream timeout as I dont see any option of timeout. In sftp configuration, I already tried increasing the timeout and idle time but of no use.

I have tried creating the new sftp connection in reader and pass it to stream but as reader is only getting initialized one, this does not help.

I already tried increasing the timeout and idle time but of no use.

Reader snippet:

```<code>    private Step step (FileInputDTO input,
    Map<String, Float> ratelist) throws
    SftpException { return
    stepBuilderFactory.get("Step").<DTO,
    DTO>chunk(chunkSize)
    .reader(buildReader(input)).writer(new
     Writer(input, fileUtil, ratelist,
      mapper,service))
    .taskExecutor (taskExecutor)
    .listener(stepListener)
    .build();
    }

    private FlatFileItemReader<? extends
    DTO> buildReader(FileInputDTO input)
    throws SftpException {

    //Create reader instance

   FlatFileItemReader<DTO> reader = new
   FlatFileItemReader<>();
   log.info("reading file :starts" );"

   //Set input file location

   reader.setResource(new  InputStreamResource(input.getChannel().get(input.getPath())));

   //Set number of Lines to ships. Use it if file has header rows.

     reader.setLinesToSkip(1);

    //Other code

    return reader;
    }
</code>```

SFTP configuration:

```<code>    public SFTPUtil (Environment env, String sftpPassword) throws JSchException {

     JSch jsch = new JSch();

     log.debug("Creating SFTP channelSftp");

     Session session = jSch.getSession(env.getProperty("sftp.remoteUserName"),

     env.getProperty("sftp.remoteHost"), Integer.parseInt(env.getProperty("sftp.remotePort"))); session.setConfig(Constants.STRICT_HOST_KEY_CHECKING, Constants.NO);

    session.setPassword(sftpPassword);
    session.connect(Integer.parseInt(env.getProperty("sftp.sessionTimeout")));
    Channel sftpchannel = session.openChannel (Constants.SFTP);

   sftpchannel.connect(Integer.parseInt(env.getProperty("sftp.channelTimeout")));

    this.channel = (ChannelSftp) sftpchannel;

    log.debug("SFTP channelSftp connected");

   }

   public ChannelSftp get() throws CustomException {

   if(channel == null) throw new CustomException("Channel creation failed");
   return channel;
   }
</code>```

Body:
Whats need to be achieve: Read a csv from sftp location and write again to different path and also save to db with Spring batch in springboot app.

Issue : 1. Reader is getting executed only once and writer as per the chunk size like print statement in reader gets printed only one time while in writer per chunk execution. It seems to be the default behaviour of FlatfileItemReader.

I am using SFTP channel to read the file from sftp location which is getting closed after read if writer processing time is huge.

So is there a way, I can always pass a new SFTP connection for eech chunk size or is there a way I can extend this readers input stream timeout as I dont see any option of timeout. In sftp configuration, I already tried increasing the timeout and idle time but of no use.

I have tried creating the new sftp connection in reader and pass it to stream but as reader is only getting initialized one, this does not help.

I already tried increasing the timeout and idle time but of no use.

Reader snippet:

    private Step step (FileInputDTO input,
    Map<String, Float> ratelist) throws
    SftpException { return
    stepBuilderFactory.get("Step").<DTO,
    DTO>chunk(chunkSize)
    .reader(buildReader(input)).writer(new
     Writer(input, fileUtil, ratelist,
      mapper,service))
    .taskExecutor (taskExecutor)
    .listener(stepListener)
    .build();
    }

    private FlatFileItemReader<? extends
    DTO> buildReader(FileInputDTO input)
    throws SftpException {

    //Create reader instance

   FlatFileItemReader<DTO> reader = new
   FlatFileItemReader<>();
   log.info("reading file :starts" );"

   //Set input file location

   reader.setResource(new  InputStreamResource(input.getChannel().get(input.getPath())));

   //Set number of Lines to ships. Use it if file has header rows.

     reader.setLinesToSkip(1);

    //Other code

    return reader;
    }

SFTP configuration:

    public SFTPUtil (Environment env, String sftpPassword) throws JSchException {

     JSch jsch = new JSch();

     log.debug("Creating SFTP channelSftp");

     Session session = jSch.getSession(env.getProperty("sftp.remoteUserName"),

     env.getProperty("sftp.remoteHost"), Integer.parseInt(env.getProperty("sftp.remotePort"))); session.setConfig(Constants.STRICT_HOST_KEY_CHECKING, Constants.NO);

    session.setPassword(sftpPassword);
    session.connect(Integer.parseInt(env.getProperty("sftp.sessionTimeout")));
    Channel sftpchannel = session.openChannel (Constants.SFTP);

   sftpchannel.connect(Integer.parseInt(env.getProperty("sftp.channelTimeout")));

    this.channel = (ChannelSftp) sftpchannel;

    log.debug("SFTP channelSftp connected");

   }

   public ChannelSftp get() throws CustomException {

   if(channel == null) throw new CustomException("Channel creation failed");
   return channel;
   }